mirror of
https://github.com/anomalyco/opencode.git
synced 2026-11-18 15:28:48 +03:00
fix(codemode): let the runtime drop functions and await promises in host-call arguments (#64513)
This commit is contained in:
committed by
GitHub
Unverified
parent
2b5ea4977f
commit
b24d599d33
@@ -266,6 +266,8 @@ export function make<
|
||||
),
|
||||
}),
|
||||
limits: { timeoutMs: limits.timeoutMs, maxOutputBytes: limits.maxOutputBytes },
|
||||
// Arguments cross as JSON would carry them: functions are left out and promises are awaited.
|
||||
translate: { functions: "drop", promises: "await" },
|
||||
}) as unknown as Language.Runtime.Runtime<R>
|
||||
runtimes.set(key, made)
|
||||
return made
|
||||
|
||||
@@ -2,11 +2,12 @@ import type { Code } from "./code.js"
|
||||
import { DurableFn, Fn } from "./host-function.js"
|
||||
import type { Interpreter } from "./runtime/interpreter.js"
|
||||
import type { AstNode, Diagnostic } from "./runtime/model.js"
|
||||
import type { PromiseObj, Value } from "./runtime/objects.js"
|
||||
import { internalCode } from "./internal-prelude.js"
|
||||
import { Arr, type PromiseObj, type Value } from "./runtime/objects.js"
|
||||
import { promiseLike } from "./runtime/promises.js"
|
||||
import type { Completion } from "./runtime/signals.js"
|
||||
import { HostCall, type HostPolicy, Resolving } from "./scheduler.js"
|
||||
import type { FrameMode } from "./vm.js"
|
||||
import { type FrameMode, Mode } from "./vm.js"
|
||||
|
||||
// The VM's side of host work (plan §4.10): calls to host functions, the host calls they queue, and the blocking call
|
||||
// a job may wait on.
|
||||
@@ -81,31 +82,37 @@ export class HostCalls {
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Calls a host function from the program. Its arguments cross to the host now. An `async` or durable function's
|
||||
* call is queued and the program gets its promise; a failure crossing rejects it. Any other is called now: its value
|
||||
* crosses back at once, a Promise it returned is a promise, and an Effect blocks the job until it completes.
|
||||
* Calls a host function from the program, which reached it as `callee`. Its arguments cross to the host now. An
|
||||
* `async` or durable function's call is queued and the program gets its promise; a failure crossing rejects it. Any
|
||||
* other is called now: its value crosses back at once, a Promise it returned is a promise, and an Effect blocks the
|
||||
* job until it completes. When the runtime awaits promises in arguments and one hasn't fulfilled, the call waits for
|
||||
* them (see `wait`) first.
|
||||
*/
|
||||
call(
|
||||
fn: Fn<unknown> | DurableFn<unknown>,
|
||||
values: Array<Value>,
|
||||
site: AstNode | undefined,
|
||||
target: HostTarget,
|
||||
callee: Value,
|
||||
): HostResult {
|
||||
const hosts = this.ctx.hosts!
|
||||
const waiting: Array<PromiseObj> = []
|
||||
if (fn instanceof DurableFn || fn.type === "async") {
|
||||
const resolving = this.promises.resolving(this.promises.newPromise(), site)
|
||||
let args: ReadonlyArray<unknown>
|
||||
try {
|
||||
args = hosts.toHost(values, target.label)
|
||||
args = hosts.toHost(values, target.label, waiting)
|
||||
} catch (error) {
|
||||
resolving.reject(error)
|
||||
return resolving.promise
|
||||
}
|
||||
if (waiting.length > 0) return this.wait(waiting, callee, values, site, resolving)
|
||||
const policy = fn instanceof DurableFn ? "durable" : fn.idempotent ? "idempotent" : "async"
|
||||
this.queue(target, policy, args, false, resolving, site).fn = fn
|
||||
return resolving.promise
|
||||
}
|
||||
const args = hosts.toHost(values, target.label)
|
||||
const args = hosts.toHost(values, target.label, waiting)
|
||||
if (waiting.length > 0) return this.wait(waiting, callee, values, site)
|
||||
const id = this.nextID++
|
||||
const result = hosts.invoke(fn, args, `${this.runId}:${id}`, target.label)
|
||||
if (result.kind === "value") {
|
||||
@@ -120,6 +127,27 @@ export class HostCalls {
|
||||
return BLOCK
|
||||
}
|
||||
|
||||
// Waits in the program for the promises, then calls `callee` again with the same arguments, which cross with their
|
||||
// values now. A sync function's call waits where it is, as an `await` would; an async one's settles `resolving`.
|
||||
private wait(
|
||||
promises: Array<PromiseObj>,
|
||||
callee: Value,
|
||||
values: Array<Value>,
|
||||
site: AstNode | undefined,
|
||||
resolving?: Resolving,
|
||||
): HostResult {
|
||||
const builtins = this.ctx.builtins
|
||||
this.ctx.vm.pushInternal(
|
||||
internalCode("$vmHostWait"),
|
||||
[new Arr(builtins.Array, promises), callee, new Arr(builtins.Array, values)],
|
||||
site,
|
||||
resolving === undefined ? Mode.CALLER : Mode.ASYNC,
|
||||
resolving,
|
||||
resolving?.promise,
|
||||
)
|
||||
return ENTERED
|
||||
}
|
||||
|
||||
// What a host function left pending (a Promise, or an Effect): the program holds a promise for it.
|
||||
private pending(target: HostTarget, work: unknown, site: AstNode | undefined, id = this.nextID++): PromiseObj {
|
||||
const resolving = this.promises.resolving(this.promises.newPromise(), site)
|
||||
|
||||
@@ -223,6 +223,16 @@ function $vmAsyncFromSyncClose(iter) {
|
||||
if (ret !== undefined && ret !== null) $Call(ret, iter)
|
||||
}
|
||||
|
||||
// A host call whose arguments hold promises that haven't fulfilled: waits for each, then calls again.
|
||||
async function $vmHostWait(promises, callee, args) {
|
||||
let i = 0
|
||||
while (i < promises.length) {
|
||||
await promises[i]
|
||||
i++
|
||||
}
|
||||
return $Apply(callee, undefined, args)
|
||||
}
|
||||
|
||||
async function $vmResult(value) {
|
||||
const root = $IsThenable(value) ? await value : value
|
||||
const walk = $vmJsonVisitor(true, undefined, null)({ "": root }, "", 0)
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -31,6 +31,23 @@ export type Limits = {
|
||||
readonly maxOutputBytes?: number
|
||||
}
|
||||
|
||||
/**
|
||||
* How a host call's arguments carry program values the host can't hold. Every host function in the runtime gets its
|
||||
* arguments this way; results are not affected.
|
||||
*/
|
||||
export type Translate = {
|
||||
/**
|
||||
* A program function inside an argument: `"error"` (the default) fails the call; `"drop"` leaves it out, as
|
||||
* `JSON.stringify` does: an object's key is left out, an array's item is `null`, and an argument is `undefined`.
|
||||
*/
|
||||
readonly functions?: "error" | "drop" | undefined
|
||||
/**
|
||||
* A program promise inside an argument: `"error"` (the default) fails the call; `"await"` makes the call wait for it
|
||||
* to settle and use its value. A rejection fails the call with its reason.
|
||||
*/
|
||||
readonly promises?: "error" | "await" | undefined
|
||||
}
|
||||
|
||||
/** A runtime's host globals for one run: `Host.fn`, `Host.durableFn`, `Host.namespace`, and plain values of them. */
|
||||
export type Globals = Readonly<Record<string, unknown>>
|
||||
|
||||
@@ -41,6 +58,7 @@ export type Options<G extends Globals = Globals> = {
|
||||
*/
|
||||
readonly globals?: ((run: Run) => G) | undefined
|
||||
readonly limits?: Limits | undefined
|
||||
readonly translate?: Translate | undefined
|
||||
}
|
||||
|
||||
/** Options for `Runtime.program`. */
|
||||
@@ -106,6 +124,10 @@ export const make = <const G extends Globals = {}>(options: Options<G> = {}): Ru
|
||||
maxOutputBytes: validateLimit("maxOutputBytes", options.limits?.maxOutputBytes, 0),
|
||||
},
|
||||
globals: options.globals,
|
||||
translate: {
|
||||
functions: options.translate?.functions ?? "error",
|
||||
promises: options.translate?.promises ?? "error",
|
||||
},
|
||||
}
|
||||
const program = (code: string, programOptions?: ProgramOptions) =>
|
||||
makeProgram(() => Effect.succeed(startProgram(setup, code, programOptions?.bindings, programOptions?.runId)))
|
||||
|
||||
@@ -13,6 +13,7 @@ import { Driver, SUSPENDED } from "./driver.js"
|
||||
import { Interruption } from "./signals.js"
|
||||
import { Source } from "./source.js"
|
||||
import type { Vm } from "../vm.js"
|
||||
import type { Translate } from "../runtime.js"
|
||||
|
||||
/**
|
||||
* A suspend that failed, leaving the run running: `running` names each host call that blocked it by its key and its
|
||||
@@ -70,6 +71,7 @@ type Globals<R> = (ctx: Interpreter<R>) => ReadonlyArray<readonly [string, Value
|
||||
/** How a runtime runs programs: its limits and host globals, shared by every run it starts. */
|
||||
export type Setup<R> = {
|
||||
readonly limits: Limits
|
||||
readonly translate?: Required<Translate> | undefined
|
||||
/** Each run's host globals (see `Host`): made when it starts, and again for a restored run. */
|
||||
readonly globals?: ((run: Run) => Readonly<Record<string, unknown>>) | undefined
|
||||
/** Globals made as program values (a test harness), made again the same way for a restored run. */
|
||||
@@ -167,7 +169,7 @@ const instantiate = <R>(setup: Setup<R>, run: Run, bindings?: Readonly<Record<st
|
||||
logs: [],
|
||||
globals: (ctx) => [
|
||||
...(setup.programGlobals?.(ctx) ?? []),
|
||||
...(setup.globals === undefined ? [] : hostGlobals(ctx, setup.globals(run))),
|
||||
...(setup.globals === undefined ? [] : hostGlobals(ctx, setup.globals(run), setup.translate)),
|
||||
],
|
||||
bindings:
|
||||
bindings === undefined
|
||||
|
||||
@@ -25,6 +25,8 @@ import {
|
||||
HostNamespace,
|
||||
MapObj,
|
||||
Obj,
|
||||
OMITTED,
|
||||
PromiseObj,
|
||||
RegExpObj,
|
||||
SetObj,
|
||||
URLObj,
|
||||
@@ -32,7 +34,8 @@ import {
|
||||
coerceToString,
|
||||
type Value,
|
||||
} from "./objects.js"
|
||||
import { describeValue, isOpaque } from "./references.js"
|
||||
import { describeValue, isOpaque, typeofValue } from "./references.js"
|
||||
import type { Translate } from "../runtime.js"
|
||||
import { Interruption } from "./signals.js"
|
||||
import { type HostOrigin, SnapshotError } from "../snapshot/codec.js"
|
||||
|
||||
@@ -61,6 +64,7 @@ type Within = {
|
||||
export const hostGlobals = <R>(
|
||||
ctx: Interpreter<R>,
|
||||
globals: Readonly<Record<string, unknown>>,
|
||||
translate: Required<Translate> = { functions: "error", promises: "error" },
|
||||
): ReadonlyArray<readonly [string, Value]> => {
|
||||
const builtins = ctx.builtins
|
||||
// The `snapshot` hooks of the host functions among the globals that have them, by label.
|
||||
@@ -69,15 +73,36 @@ export const hostGlobals = <R>(
|
||||
// The program functions wrapping functions inside values a hooked host function returned, by where they came from.
|
||||
const origins = new WeakMap<object, HostOrigin>()
|
||||
|
||||
const toHost = (value: Value, label: string, depth = 0, seen = new Set<object>()): unknown => {
|
||||
// With `waiting`, a promise that hasn't fulfilled goes there instead, and the copy is to be made again once it settles.
|
||||
const toHost = (
|
||||
value: Value,
|
||||
label: string,
|
||||
depth: number,
|
||||
seen: Set<object>,
|
||||
waiting: Array<PromiseObj> | undefined,
|
||||
): unknown => {
|
||||
if (depth > MAX_VALUE_DEPTH) throw typeError(`${label} exceeds the maximum value depth of ${MAX_VALUE_DEPTH}.`)
|
||||
if (isPrimitive(value)) return value
|
||||
if (translate.functions === "drop" && typeofValue(value) === "function") return OMITTED
|
||||
if (seen.has(value as object)) throw typeError(`${label} contains a circular value.`)
|
||||
if (waiting !== undefined && value instanceof PromiseObj) {
|
||||
if (value.state !== "fulfilled") {
|
||||
waiting.push(value)
|
||||
return undefined
|
||||
}
|
||||
seen.add(value)
|
||||
const copied = toHost(value.result as Value, label, depth + 1, seen, waiting)
|
||||
seen.delete(value)
|
||||
return copied
|
||||
}
|
||||
if (!(value instanceof Obj) || isOpaque(value)) {
|
||||
throw typeError(`${label} contains ${describeValue(value)}, which cannot be passed to the host.`)
|
||||
}
|
||||
if (seen.has(value)) throw typeError(`${label} contains a circular value.`)
|
||||
seen.add(value)
|
||||
const next = (item: Value) => toHost(item, label, depth + 1, seen)
|
||||
const next = (item: Value) => {
|
||||
const copied = toHost(item, label, depth + 1, seen, waiting)
|
||||
return copied === OMITTED && (value instanceof MapObj || value instanceof SetObj) ? undefined : copied
|
||||
}
|
||||
if (value instanceof ErrorObj) {
|
||||
const name = coerceToString(get(value, "name"))
|
||||
const message = get(value, "message")
|
||||
@@ -87,7 +112,7 @@ export const hostGlobals = <R>(
|
||||
for (const key of new Set(["cause", ...keys(value)])) {
|
||||
if (uncrossed.has(key) || !has(value, key)) continue
|
||||
const item = crossing(() => next(get(value, key)))
|
||||
if (item === left) continue
|
||||
if (item === left || item === OMITTED) continue
|
||||
Object.defineProperty(copied, key, {
|
||||
value: item,
|
||||
writable: true,
|
||||
@@ -260,19 +285,27 @@ export const hostGlobals = <R>(
|
||||
|
||||
// A host function as a program function: its calls go through the run's host calls (see `HostCalls.call`). The
|
||||
// name and length come from the host function, read once, and only as text and a count.
|
||||
const wrap = (fn: Fn<unknown> | DurableFn<unknown>, label: string, target: HostTarget, source?: Function) => {
|
||||
// `callee` is the program function calling it, when that is not the one made here (see `rewrap`).
|
||||
const wrap = (
|
||||
fn: Fn<unknown> | DurableFn<unknown>,
|
||||
label: string,
|
||||
target: HostTarget,
|
||||
source?: Function,
|
||||
callee?: Obj,
|
||||
) => {
|
||||
const named = source ?? (fn instanceof Fn ? fn.run : undefined)
|
||||
const own: unknown = named?.name
|
||||
// A host function made inline has no name of its own: it is named by where it is.
|
||||
const name =
|
||||
source === undefined && (typeof own !== "string" || own === "") ? label.slice(label.lastIndexOf(".") + 1) : own
|
||||
const length: unknown = named?.length ?? 0
|
||||
return native(builtins, {
|
||||
const made = native(builtins, {
|
||||
runtime: "host",
|
||||
name: typeof name === "string" ? name : "",
|
||||
length: typeof length === "number" && Number.isSafeInteger(length) && length >= 0 ? length : 0,
|
||||
call: (_, values, site) => ctx.vm.hosts.call(fn, values, site, target),
|
||||
call: (_, values, site) => ctx.vm.hosts.call(fn, values, site, target, callee ?? made),
|
||||
})
|
||||
return made
|
||||
}
|
||||
|
||||
// A namespace among the globals: a path the program reads into, whose calls ask `resolve` for the function.
|
||||
@@ -282,11 +315,17 @@ export const hostGlobals = <R>(
|
||||
call: (path, values, site) => {
|
||||
const found = value.resolve(path)
|
||||
if (found instanceof HostFailure) throw found
|
||||
return ctx.vm.hosts.call(found, values, site, {
|
||||
label: path.reduce<string>((at, key) => member(at, key), label),
|
||||
path: [...global, ...path],
|
||||
owner: undefined,
|
||||
})
|
||||
return ctx.vm.hosts.call(
|
||||
found,
|
||||
values,
|
||||
site,
|
||||
{
|
||||
label: path.reduce<string>((at, key) => member(at, key), label),
|
||||
path: [...global, ...path],
|
||||
owner: undefined,
|
||||
},
|
||||
new HostNamespace(label, path),
|
||||
)
|
||||
},
|
||||
})
|
||||
shape.push(`${label} (namespace)`)
|
||||
@@ -317,7 +356,17 @@ export const hostGlobals = <R>(
|
||||
|
||||
ctx.hosts = {
|
||||
shape,
|
||||
toHost: (values, label) => values.map((item, index) => toHost(item, `Argument ${index + 1} to ${label}`)),
|
||||
toHost: (values, label, waiting) =>
|
||||
values.map((item, index) => {
|
||||
const copied = toHost(
|
||||
item,
|
||||
`Argument ${index + 1} to ${label}`,
|
||||
0,
|
||||
new Set(),
|
||||
translate.promises === "await" ? waiting : undefined,
|
||||
)
|
||||
return copied === OMITTED ? undefined : copied
|
||||
}),
|
||||
fromHost: (value, label, owner) =>
|
||||
fromHost(value, label, 0, new Set(), {
|
||||
within:
|
||||
@@ -374,7 +423,13 @@ export const hostGlobals = <R>(
|
||||
`The host function ${origin.owner} restored a value with no function at ${origin.label}, so this state can't resume.`,
|
||||
)
|
||||
}
|
||||
const made = wrap(plain(host), origin.label, { label: origin.label, path: undefined, owner: origin.owner }, host)
|
||||
const made = wrap(
|
||||
plain(host),
|
||||
origin.label,
|
||||
{ label: origin.label, path: undefined, owner: origin.owner },
|
||||
host,
|
||||
target,
|
||||
)
|
||||
// The restored function keeps its own properties; only what calling it does comes from the new one.
|
||||
Object.assign(target, { tag: made.tag, call: made.call, construct: made.construct, callback: made.callback })
|
||||
origins.set(target, origin)
|
||||
|
||||
@@ -62,6 +62,9 @@ export const readonly: Attributes = { writable: false, enumerable: false, config
|
||||
/** Constants such as `Math.PI` and a constructor's `prototype`. */
|
||||
export const frozen: Attributes = { writable: false, enumerable: false, configurable: false }
|
||||
|
||||
/** What a child converted by `toHost` gives to be left out: an object's key is skipped, an array's item is `null`. */
|
||||
export const OMITTED: unique symbol = Symbol("omitted")
|
||||
|
||||
/**
|
||||
* An object owned by the program: own properties plus a prototype link. Subclasses answer, in one place, how a
|
||||
* built-in kind of object prints, coerces, iterates, and crosses to the host.
|
||||
@@ -113,9 +116,11 @@ export class Obj {
|
||||
/** A copy the host can hold; `item` converts a child. A `__proto__` key never reaches host code. */
|
||||
toHost(item: (value: Value) => unknown): unknown {
|
||||
return Object.fromEntries(
|
||||
entries(this)
|
||||
.filter(([key]) => key !== "__proto__")
|
||||
.map(([key, value]) => [key, item(value)]),
|
||||
entries(this).flatMap(([key, value]) => {
|
||||
if (key === "__proto__") return []
|
||||
const copied = item(value)
|
||||
return copied === OMITTED ? [] : [[key, copied]]
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -145,7 +150,10 @@ export class Arr extends Obj {
|
||||
return `[${this.items.map(item).join(",")}]`
|
||||
}
|
||||
override toHost(item: (value: Value) => unknown) {
|
||||
return this.items.map(item)
|
||||
return this.items.map((value) => {
|
||||
const copied = item(value)
|
||||
return copied === OMITTED ? null : copied
|
||||
})
|
||||
}
|
||||
override iterator(builtins: Builtins) {
|
||||
return new Position(this, "values", builtins.Array)
|
||||
|
||||
@@ -92,8 +92,11 @@ export type HostOrigin = {
|
||||
export type HostBridge = {
|
||||
/** What a saved state must find again on resume: the host functions with `snapshot` hooks, and the namespaces. */
|
||||
readonly shape: ReadonlyArray<string>
|
||||
/** Program values as host values, for a call's arguments. */
|
||||
readonly toHost: (values: ReadonlyArray<Value>, label: string) => ReadonlyArray<unknown>
|
||||
/**
|
||||
* Program values as host values, for a call's arguments. When the runtime awaits promises in arguments, one that
|
||||
* hasn't fulfilled goes in `waiting` instead, and the arguments are to cross again once it settles.
|
||||
*/
|
||||
readonly toHost: (values: ReadonlyArray<Value>, label: string, waiting: Array<PromiseObj>) => ReadonlyArray<unknown>
|
||||
/** A host value as a program value, for what a call returned; `owner`'s `snapshot` hooks can save it. */
|
||||
readonly fromHost: (value: unknown, label: string, owner: string | undefined) => Value
|
||||
/** What a call's failure is to the program. */
|
||||
|
||||
@@ -2177,7 +2177,7 @@ export class Vm {
|
||||
const site = callee.callback && callee.call.length < 3 ? undefined : callSiteOf(frame, pc)
|
||||
const res = callee.call(thisVal, args, site)
|
||||
if (this.tripEvery === 0) this.fuel -= NATIVE_FUEL
|
||||
if ((res as unknown) !== BLOCK && (res === null || typeof res !== "object" || res instanceof Obj)) {
|
||||
if ((res as unknown) !== BLOCK && (res as unknown) !== ENTERED && (res === null || typeof res !== "object" || res instanceof Obj)) {
|
||||
normalizeItems(res)
|
||||
regs[base - 2] = res
|
||||
frame.sp = base - 1
|
||||
@@ -2303,6 +2303,7 @@ export class Vm {
|
||||
return 1
|
||||
}
|
||||
if ((res as unknown) === BLOCK) return 2
|
||||
if ((res as unknown) === ENTERED) return 1
|
||||
if (res instanceof Convert) {
|
||||
const builtins = this.ctx.builtins
|
||||
this.pushInternalCall(
|
||||
|
||||
@@ -648,6 +648,41 @@ describe("CodeMode schema flexibility", () => {
|
||||
expect(Object.hasOwn(received, "q")).toBe(false)
|
||||
})
|
||||
|
||||
test("tool arguments leave functions out and await promises, as JSON did", async () => {
|
||||
const observed: Array<unknown> = []
|
||||
const show = Tool.make({
|
||||
description: "Show raw input",
|
||||
input: { type: "object" },
|
||||
execute: (input) =>
|
||||
Effect.sync(() => {
|
||||
observed.push(input)
|
||||
return "ok"
|
||||
}),
|
||||
})
|
||||
const runtime = CodeMode.make({ tools: { shop: { show } } })
|
||||
for (const code of [
|
||||
`await tools.shop.show({ q: "x", format(v) { return v } })`,
|
||||
`await tools.shop.show({ n: Promise.resolve(5) })`,
|
||||
// A toJSON method is a function too: left out, not run.
|
||||
`await tools.shop.show({ item: "book", price: { cents: 1999, toJSON() { return "$19.99" } } })`,
|
||||
`await tools.shop.show({ later: (async () => { await null; return [1, () => 2] })() })`,
|
||||
]) {
|
||||
const result = await Effect.runPromise(runtime.execute(code))
|
||||
expect(result.ok).toBe(true)
|
||||
}
|
||||
expect(observed).toStrictEqual([
|
||||
{ q: "x" },
|
||||
{ n: 5 },
|
||||
{ item: "book", price: { cents: 1999 } },
|
||||
{ later: [1, null] },
|
||||
])
|
||||
const rejected = await Effect.runPromise(
|
||||
runtime.execute(`await tools.shop.show({ n: Promise.reject(new Error("no price")) })`),
|
||||
)
|
||||
expect(rejected.ok ? undefined : rejected.error.message).toContain("no price")
|
||||
expect(observed).toHaveLength(4)
|
||||
})
|
||||
|
||||
test("dropping undefined values lets optionalKey schemas accept conditional arguments", async () => {
|
||||
const observed: Array<unknown> = []
|
||||
const find = Tool.make({
|
||||
|
||||
@@ -73,9 +73,9 @@ describe("extension functions", () => {
|
||||
})
|
||||
|
||||
test("a function inside a result is named by its path in diagnostics", async () => {
|
||||
expect((await failure(`const res = await fetch("https://a.test/"); res.handlers[0](() => 1)`)).message).toContain(
|
||||
"Argument 1 to fetch.handlers[0] contains a function",
|
||||
)
|
||||
expect(
|
||||
(await failure(`const res = await fetch("https://a.test/"); res.handlers[0]([1].keys())`)).message,
|
||||
).toContain("Argument 1 to fetch.handlers[0] contains an iterator")
|
||||
const target = CodeMode.make({
|
||||
extensions: [Extension.make({ name: "odd", globals: { make: () => ({ sym: () => Symbol("s") }) } })],
|
||||
})
|
||||
@@ -220,10 +220,11 @@ describe("values are converted at the boundary, never shared", () => {
|
||||
expect(held[1]).toBeInstanceOf(Error)
|
||||
})
|
||||
|
||||
test("functions, promises, iterators, and symbols cannot be passed in", async () => {
|
||||
expect((await failure(`keep(() => 1)`)).message).toContain("Argument 1 to keep contains a function")
|
||||
test("functions are left out and promises awaited, as in tool arguments; iterators and symbols cannot be passed in", async () => {
|
||||
held.length = 0
|
||||
await value(`keep({ f: () => 1, n: later(1) }); keep([() => 1, later(2)]); keep(() => 1); keep(later(3))`)
|
||||
expect(held).toEqual([{ n: 2 }, [null, 3], undefined, 4])
|
||||
expect((await failure(`keep([1].keys())`)).message).toContain("Argument 1 to keep contains an iterator")
|
||||
expect((await failure(`keep(later(1))`)).message).toContain("un-awaited Promise")
|
||||
expect((await failure(`keep(Symbol.iterator)`)).message).toContain("Argument 1 to keep contains a symbol")
|
||||
})
|
||||
|
||||
@@ -639,7 +640,7 @@ describe("configuration", () => {
|
||||
expect(result.toolCalls).toEqual([])
|
||||
})
|
||||
|
||||
test("a result with functions can't be handed to a tool; its data can", async () => {
|
||||
test("a result with functions is handed to a tool as its data", async () => {
|
||||
const tools = CodeMode.make({
|
||||
extensions: [extension],
|
||||
tools: {
|
||||
@@ -651,9 +652,12 @@ describe("configuration", () => {
|
||||
}),
|
||||
},
|
||||
})
|
||||
expect((await failure(`return await tools.echo({ v: await fetch("https://a.test/") })`, tools)).message).toContain(
|
||||
"contains a function, which cannot be passed to the host",
|
||||
)
|
||||
expect(await value(`return await tools.echo({ v: await fetch("https://a.test/") })`, tools)).toEqual({
|
||||
status: 200,
|
||||
ok: true,
|
||||
headers: {},
|
||||
handlers: [null],
|
||||
})
|
||||
expect(
|
||||
await value(
|
||||
`const { status, ok } = await fetch("https://a.test/"); return await tools.echo({ v: { status, ok } })`,
|
||||
|
||||
@@ -199,3 +199,115 @@ describe("per-run state", () => {
|
||||
expect(await resumed).toMatchObject({ ok: true, value: 42 })
|
||||
})
|
||||
})
|
||||
|
||||
describe("translate", () => {
|
||||
const translating = (translate?: Runtime.Translate, limits?: Runtime.Limits) => {
|
||||
const calls: Array<ReadonlyArray<unknown>> = []
|
||||
const runtime = Runtime.make({
|
||||
translate,
|
||||
limits,
|
||||
globals: () => ({
|
||||
keep: Host.fn((args) => void calls.push(args)),
|
||||
send: Host.fn((args) => Effect.sync(() => void calls.push(args)), { type: "async" }),
|
||||
later: Host.fn(([n]) => Effect.succeed(n), { type: "async" }),
|
||||
never: Host.fn(() => Effect.never, { type: "async" }),
|
||||
}),
|
||||
})
|
||||
return { runtime, calls }
|
||||
}
|
||||
|
||||
test("by default, a function or a promise inside an argument fails the call", async () => {
|
||||
const strict = translating().runtime
|
||||
for (const [code, message] of [
|
||||
["keep({ f() {} })", "Argument 1 to keep contains a function, which cannot be passed to the host."],
|
||||
["keep([Promise.resolve(1)])", "Argument 1 to keep contains an un-awaited Promise, which cannot be passed"],
|
||||
["await send(() => 1)", "Argument 1 to send contains a function"],
|
||||
] as const) {
|
||||
const result = await run(strict, code)
|
||||
expect(result.ok).toBe(false)
|
||||
if (!result.ok) expect(result.error.message).toContain(message)
|
||||
}
|
||||
})
|
||||
|
||||
test("functions: drop leaves functions out as JSON.stringify does", async () => {
|
||||
const { runtime, calls } = translating({ functions: "drop" })
|
||||
await value(
|
||||
runtime,
|
||||
`keep({ q: "x", format(v) { return v }, nested: { f: Math.max } }, [1, () => 2, keep], () => 3, new Map([["k", () => 1]]))`,
|
||||
)
|
||||
expect(calls).toEqual([[{ q: "x", nested: {} }, [1, null, null], undefined, new Map([["k", undefined]])]])
|
||||
expect(Object.keys(calls[0]![0] as object)).toEqual(["q", "nested"])
|
||||
const result = await run(runtime, `keep({ p: Promise.resolve(1) })`)
|
||||
expect(result.ok).toBe(false)
|
||||
if (!result.ok) expect(result.error.message).toContain("un-awaited Promise")
|
||||
})
|
||||
|
||||
test("promises: await waits for every promise inside the arguments and uses its value", async () => {
|
||||
const { runtime, calls } = translating({ promises: "await" })
|
||||
expect(
|
||||
await value(
|
||||
runtime,
|
||||
`
|
||||
const slow = (async () => { await null; await null; return "slow" })()
|
||||
const a = keep({ n: Promise.resolve(5), list: [later(1), slow] }, later({ deep: later(2) }))
|
||||
const b = await send(slow, new Promise((resolve) => resolve(later(3))))
|
||||
return [a, b]
|
||||
`,
|
||||
),
|
||||
).toEqual([null, null])
|
||||
expect(calls).toEqual([[{ n: 5, list: [1, "slow"] }, { deep: 2 }], ["slow", 3]])
|
||||
const result = await run(runtime, `keep({ f() {} })`)
|
||||
expect(result.ok).toBe(false)
|
||||
if (!result.ok) expect(result.error.message).toContain("contains a function")
|
||||
})
|
||||
|
||||
test("promises: await fails the call with a rejection's reason", async () => {
|
||||
const { runtime, calls } = translating({ promises: "await" })
|
||||
expect(
|
||||
await value(
|
||||
runtime,
|
||||
`
|
||||
const failing = () => Promise.reject(new RangeError("nope"))
|
||||
let thrown
|
||||
try { keep({ n: failing() }) } catch (error) { thrown = error }
|
||||
const sent = send([later(1), failing()])
|
||||
return [thrown instanceof RangeError, thrown.message, sent instanceof Promise, await sent.catch((e) => e.message)]
|
||||
`,
|
||||
),
|
||||
).toEqual([true, "nope", true, "nope"])
|
||||
expect(calls).toEqual([])
|
||||
})
|
||||
|
||||
test("promises: await waits on a promise that never settles until the timeout", async () => {
|
||||
const result = await run(translating({ promises: "await" }, { timeoutMs: 50 }).runtime, `keep({ n: never() })`)
|
||||
expect(result.ok).toBe(false)
|
||||
if (!result.ok) expect(result.error.kind).toBe("TimeoutExceeded")
|
||||
})
|
||||
|
||||
test("promises: await keeps waiting across a suspend", async () => {
|
||||
const started = latch()
|
||||
const gate = latch<number>()
|
||||
const calls: Array<ReadonlyArray<unknown>> = []
|
||||
const runtime = Runtime.make({
|
||||
translate: { promises: "await" },
|
||||
globals: () => ({
|
||||
keep: Host.fn((args) => (calls.push(args), "kept")),
|
||||
slow: Host.fn(
|
||||
() => Effect.andThen(Effect.sync(started.resolve), Effect.promise(() => gate.promise)),
|
||||
{ type: "async", idempotent: true },
|
||||
),
|
||||
}),
|
||||
})
|
||||
const program = runtime.program(`return [keep({ n: slow() }), await slow()]`)
|
||||
const fiber = Effect.runFork(program.run())
|
||||
await started.promise
|
||||
const suspended = await Effect.runPromise(program.suspend())
|
||||
if (suspended.ok !== "suspended") throw new Error("expected a suspended run")
|
||||
await Effect.runPromise(Fiber.join(fiber))
|
||||
expect(calls).toEqual([])
|
||||
const resumed = Effect.runPromise(runtime.resume(suspended.state).run())
|
||||
gate.resolve(7)
|
||||
expect(await resumed).toMatchObject({ ok: true, value: ["kept", 7] })
|
||||
expect(calls).toEqual([[{ n: 7 }]])
|
||||
})
|
||||
})
|
||||
|
||||
@@ -475,12 +475,10 @@ describe("first-class promise values", () => {
|
||||
})
|
||||
|
||||
describe("promises at data boundaries", () => {
|
||||
test("an un-awaited promise inside a result is awaited; inside a tool argument it fails the call", async () => {
|
||||
test("an un-awaited promise inside a result or a tool argument is awaited", async () => {
|
||||
expect(await value(`return { result: tools.host.echo({ id: 1 }) }`)).toEqual({ result: 1 })
|
||||
expect(await value(`return Array.from([Promise.resolve(1)])`)).toEqual([1])
|
||||
expect((await error(`return await tools.host.echo({ id: tools.host.echo({ id: 1 }) })`)).message).toContain(
|
||||
"un-awaited Promise",
|
||||
)
|
||||
expect(await value(`return await tools.host.echo({ id: tools.host.echo({ id: 1 }) })`)).toBe(1)
|
||||
})
|
||||
|
||||
test("a rejected promise inside a result fails the program with its reason", async () => {
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
import { test } from "bun:test"
|
||||
import { root, run, skipped } from "./test262/run.js"
|
||||
|
||||
for (const file of [...new Bun.Glob("**/*.js").scanSync({ cwd: root })].sort()) {
|
||||
for (const file of [...new Bun.Glob("**/*.js").scanSync({ cwd: root, followSymlinks: true })].sort()) {
|
||||
const define = skipped.has(file) ? test.skip : test
|
||||
define(
|
||||
file,
|
||||
|
||||
Reference in New Issue
Block a user