mirror of
https://github.com/anomalyco/opencode.git
synced 2026-11-29 11:42:17 +00:00
1057 lines
42 KiB
TypeScript
1057 lines
42 KiB
TypeScript
import { afterAll, beforeAll, describe, expect, test } from "bun:test"
|
|
import fs from "fs/promises"
|
|
import path from "path"
|
|
import { pathToFileURL } from "url"
|
|
import type { CodeModeFs } from "@opencode/core/codemode/fs"
|
|
import { CodeModeTool } from "@opencode/core/codemode/tool"
|
|
import { AppNodeBuilder } from "@opencode/core/effect/app-node-builder"
|
|
import { Environment } from "@opencode/core/environment/index"
|
|
import { FileAccess } from "@opencode/core/file-access"
|
|
import { FileWrite } from "@opencode/core/file-write"
|
|
import { Formatter } from "@opencode/core/formatter"
|
|
import { Location } from "@opencode/core/location"
|
|
import { Permission } from "@opencode/core/permission"
|
|
import { AbsolutePath } from "@opencode/core/schema"
|
|
import { Tool } from "@opencode/core/tool"
|
|
import { execute } from "@opencode/core/tool/runtime"
|
|
import { Agent } from "@opencode/schema/agent"
|
|
import { Session } from "@opencode/schema/session"
|
|
import { SessionMessage } from "@opencode/schema/session-message"
|
|
import type { Info } from "@opencode/schema/tool"
|
|
import { LayerNode } from "@opencode/util/effect/layer-node"
|
|
import { Context, Deferred, Effect, Fiber, Layer, Schema } from "effect"
|
|
import { TestClock } from "effect/testing"
|
|
import { hostEnvironmentLayer } from "./fixture/environment"
|
|
import { location } from "./fixture/location"
|
|
import { tmpdir } from "./fixture/tmpdir"
|
|
import { it } from "./lib/effect"
|
|
import { permissionService, permissionLayer } from "./lib/permission"
|
|
|
|
const context = {
|
|
sessionID: Session.ID.make("ses_execute"),
|
|
agent: Agent.ID.make("build"),
|
|
messageID: SessionMessage.ID.make("msg_execute"),
|
|
id: Tool.CallID.make("call_execute"),
|
|
progress: () => Effect.void,
|
|
}
|
|
|
|
const allowAll = permissionService({ assert: () => Effect.void })
|
|
|
|
// The file services of a Location at `directory`, asking `permission` like the execute call's own.
|
|
const fileServices = (
|
|
directory: string,
|
|
permission: Partial<Permission.Interface> = { assert: () => Effect.void },
|
|
formatter: Formatter.Interface["file"] = () => Effect.succeed(false),
|
|
) =>
|
|
Effect.runSync(
|
|
Effect.context<CodeModeFs.Services>().pipe(
|
|
Effect.provide(
|
|
AppNodeBuilder.build(LayerNode.group([Environment.node, FileAccess.node, FileWrite.node, Location.node]), [
|
|
Environment.node.replace(hostEnvironmentLayer),
|
|
Location.node.replace(
|
|
Layer.succeed(Location.Service, Location.Service.of(location({ directory: AbsolutePath.make(directory) }))),
|
|
),
|
|
Formatter.node.replace(Layer.mock(Formatter.Service, { file: formatter })),
|
|
Permission.node.replace(permissionLayer(permission)),
|
|
]),
|
|
),
|
|
),
|
|
)
|
|
|
|
const createCodeMode = (
|
|
tools: ReadonlyMap<string, Info>,
|
|
permission = allowAll,
|
|
files?: Context.Context<CodeModeFs.Services>,
|
|
) => CodeModeTool.create({ tools }, (_, tool, input, context) => execute(tool, input, context), permission, files)
|
|
|
|
test("execute takes raw code as freeform text, and Code Mode calls freeform tools with a string", async () => {
|
|
const input = Schema.Struct({ text: Schema.NonEmptyString })
|
|
const send = {
|
|
name: "send",
|
|
description: "Send text",
|
|
input,
|
|
output: Schema.String,
|
|
execute: ({ text }) => Effect.succeed({ output: text }),
|
|
} satisfies Info<typeof input, typeof Schema.String>
|
|
const tools = new Map<string, Info>([
|
|
["echo", { ...send, name: "echo" }],
|
|
["send", { ...send, freeform: { type: "text" } }],
|
|
])
|
|
const codeMode = createCodeMode(tools)
|
|
expect(codeMode.freeform).toEqual({ type: "text" })
|
|
expect(CodeModeTool.catalog({ tools }).tools.map((tool) => "signature" in tool && tool.signature)).toEqual([
|
|
"tools.echo({\n /** @minLength 1 */\n text: string,\n}): Promise<string>",
|
|
"tools.send(/** @minLength 1 */ text: string): Promise<string>",
|
|
])
|
|
const calls = await Effect.runPromise(
|
|
codeMode.execute({ code: 'return [await tools.send("first"), await tools.send({text: "second"})]' }, context),
|
|
)
|
|
expect(JSON.parse(calls.output.output)).toEqual(["first", "second"])
|
|
expect(calls.output.toolCalls.map((call) => call.input)).toEqual([{ text: "first" }, { text: "second" }])
|
|
})
|
|
|
|
test("execute describes invariant Code Mode behavior", () => {
|
|
expect(createCodeMode(new Map()).description).toBe(
|
|
[
|
|
"Run JavaScript in a confined Code Mode runtime to script tool calls and HTTP requests and compose their results.",
|
|
"Write plain JavaScript and send it exactly as written: no code fence, and no JSON or other wrapper around it.",
|
|
"`fetch` is available for HTTP requests. Imports, direct filesystem access, and timers are unavailable: there is no `setTimeout` or sleep. All other external access goes through `tools`.",
|
|
"Inside `execute`, the only callable tools are those explicitly listed in the Code Mode catalog instructions or returned by the `search` function. Ignore tools shown outside the Code Mode catalog. They are not available in the Code Mode runtime.",
|
|
'Call tools through `tools` using only exact paths and signatures from the catalog. Do not infer or normalize tool names; preserve bracket notation such as `tools.<namespace>["tool-name"](input)`.',
|
|
"Prefer an explicit `return`; if omitted, the final top-level expression becomes the result.",
|
|
"Await every call whose completion matters; pending calls are interrupted when execution ends. Run independent calls concurrently with `Promise.allSettled`.",
|
|
].join("\n"),
|
|
)
|
|
})
|
|
|
|
test("canonical execution distinguishes declared, model-only, and raw schema outputs", async () => {
|
|
const declared: Info = {
|
|
name: "declared",
|
|
description: "Declared",
|
|
input: Schema.Struct({ value: Schema.String }),
|
|
output: Schema.Struct({ value: Schema.String }),
|
|
execute: ({ value }) => Effect.succeed({ output: { value } }),
|
|
}
|
|
const modelOnlyInput = Schema.Struct({})
|
|
const modelOnly = {
|
|
name: "model_only",
|
|
description: "Model only",
|
|
input: modelOnlyInput,
|
|
execute: () => Effect.succeed({ content: "visible only", metadata: { kind: "model" } }),
|
|
} satisfies Info<typeof modelOnlyInput, undefined>
|
|
const raw: Info = {
|
|
name: "raw",
|
|
description: "Raw",
|
|
input: {},
|
|
output: {},
|
|
execute: (input) => Effect.succeed({ output: input, content: "raw" }),
|
|
}
|
|
|
|
expect(await Effect.runPromise(execute(declared, { value: "encoded" }, context))).toEqual({
|
|
output: { value: "encoded" },
|
|
content: [{ type: "text", text: '{"value":"encoded"}' }],
|
|
})
|
|
expect(await Effect.runPromise(execute(modelOnly, {}, context))).toEqual({
|
|
output: undefined,
|
|
content: [{ type: "text", text: "visible only" }],
|
|
metadata: { kind: "model" },
|
|
})
|
|
expect(await Effect.runPromise(execute(raw, { unchecked: true }, context))).toEqual({
|
|
output: { unchecked: true },
|
|
content: [{ type: "text", text: "raw" }],
|
|
})
|
|
})
|
|
|
|
test("declared outputs cannot bypass validation and raw outputs stay JSON-compatible", async () => {
|
|
const missing: Info = {
|
|
name: "missing",
|
|
description: "Missing output",
|
|
input: Schema.Struct({}),
|
|
output: Schema.String,
|
|
execute: () => Effect.succeed({ content: "not an output" }),
|
|
}
|
|
const invalid: Info = {
|
|
name: "invalid",
|
|
description: "Invalid raw output",
|
|
input: {},
|
|
output: {},
|
|
execute: () => Effect.succeed({ output: 1n, content: "not JSON" }),
|
|
}
|
|
|
|
expect((await Effect.runPromiseExit(execute(missing, {}, context))).toString()).toContain(
|
|
"Tool did not return its declared output",
|
|
)
|
|
expect((await Effect.runPromiseExit(execute(invalid, {}, context))).toString()).toContain(
|
|
"Tool returned a non-JSON value",
|
|
)
|
|
})
|
|
|
|
test("foreign typed failures settle as Tool.Error at the untrusted boundary", async () => {
|
|
class ForeignFailure extends Schema.TaggedError<ForeignFailure>()("Plugin.ForeignFailure", {
|
|
message: Schema.String,
|
|
}) {}
|
|
const lying: Info = {
|
|
name: "lying",
|
|
description: "Fails with a non-Tool.Error typed failure",
|
|
input: Schema.Struct({}),
|
|
execute: () => new ForeignFailure({ message: "transport died" }) as never,
|
|
}
|
|
|
|
const error = await Effect.runPromise(execute(lying, {}, context).pipe(Effect.flip))
|
|
expect(error).toBeInstanceOf(Tool.Error)
|
|
expect(error.message).toBe("transport died")
|
|
})
|
|
|
|
test("execute rejects filesystem fetches", async () => {
|
|
const result = await Effect.runPromise(
|
|
createCodeMode(new Map()).execute({ code: 'return await fetch("file:///blocked.txt")' }, context),
|
|
)
|
|
|
|
expect(result.output.error).toBe(true)
|
|
expect(result.output.output).toContain("fetch cannot be used for filesystem access.")
|
|
})
|
|
|
|
describe("execute output", () => {
|
|
const run = async (code: string) =>
|
|
(await Effect.runPromise(createCodeMode(new Map()).execute({ code }, context))).output.output
|
|
|
|
test("a program that only logs shows just its logs", async () => {
|
|
expect(await run('console.log("found", 12, "files")')).toBe("Logs:\nfound 12 files")
|
|
})
|
|
|
|
test("a program that only warns shows just its warnings", async () => {
|
|
expect(await run('const rejected = Promise.reject(new Error("boom"))')).toBe(
|
|
"Warnings:\n- [ExecutionFailure] Unhandled rejection from an un-awaited promise: Error: boom",
|
|
)
|
|
})
|
|
|
|
test("a null result with nothing else still shows null", async () => {
|
|
expect(await run("return null")).toBe("null")
|
|
})
|
|
|
|
test("a returned value keeps its line before the logs", async () => {
|
|
expect(await run('console.log("hi"); return { n: 1 }')).toBe('{"n":1}\n\nLogs:\nhi')
|
|
})
|
|
})
|
|
|
|
describe("streaming fetch", () => {
|
|
const run = (url: URL, code: string, permission = allowAll) =>
|
|
createCodeMode(new Map(), permission).execute(
|
|
{ code: `const res = await fetch(${JSON.stringify(url.href)}); ${code}` },
|
|
context,
|
|
)
|
|
|
|
// Stays open after the first chunk so buffering would block until the test times out.
|
|
const openBody = (cancel: () => void) =>
|
|
new ReadableStream({
|
|
start(controller) {
|
|
controller.enqueue(Uint8Array.of(42))
|
|
},
|
|
cancel,
|
|
})
|
|
|
|
test.each([
|
|
["return with a live reader", "const reader = res.body.getReader(); return (await reader.read()).value[0]"],
|
|
[
|
|
"reader cancellation",
|
|
"const reader = res.body.getReader(); const chunk = await reader.read(); await reader.cancel(); return chunk.value[0]",
|
|
],
|
|
[
|
|
"break from async iteration",
|
|
"let first; for await (const chunk of res.body) { first = chunk[0]; break } return res.body.locked ? 'locked' : first",
|
|
],
|
|
])("reads the first chunk before EOF: %s", async (_, code) => {
|
|
const closed = Promise.withResolvers<void>()
|
|
await using server = Bun.serve({
|
|
port: 0,
|
|
fetch: () => new Response(openBody(closed.resolve)),
|
|
})
|
|
const result = await Effect.runPromise(run(server.url, code))
|
|
expect(result.output.output).toBe("42")
|
|
await closed.promise
|
|
})
|
|
|
|
test("interrupting execute aborts a pending request", async () => {
|
|
const started = Promise.withResolvers<void>()
|
|
const closed = Promise.withResolvers<void>()
|
|
await using server = Bun.serve({
|
|
port: 0,
|
|
fetch: async (req) => {
|
|
req.signal.addEventListener("abort", () => closed.resolve(), { once: true })
|
|
started.resolve()
|
|
await closed.promise
|
|
return new Response(null)
|
|
},
|
|
})
|
|
const fiber = Effect.runFork(run(server.url, "return res.status"))
|
|
await started.promise
|
|
await Effect.runPromise(Fiber.interrupt(fiber))
|
|
await closed.promise
|
|
})
|
|
|
|
test("whole-body methods share consumption and expose Bun's empty body", async () => {
|
|
await using server = Bun.serve({
|
|
port: 0,
|
|
fetch: (req) => (req.method === "HEAD" ? new Response(null) : Response.json(42)),
|
|
})
|
|
const result = await Effect.runPromise(
|
|
run(
|
|
server.url,
|
|
`
|
|
const before = res.bodyUsed
|
|
const number = await res.json()
|
|
const second = await res.text().catch(e => e.name)
|
|
const bytes = await (await fetch(res.url)).bytes()
|
|
const buffer = await (await fetch(res.url)).arrayBuffer()
|
|
const empty = await fetch(res.url, { method: "HEAD" })
|
|
return [res.headers.get("Content-Type"), before, number, res.bodyUsed, second, [...bytes], [...buffer], empty.body === null]
|
|
`,
|
|
),
|
|
)
|
|
expect(JSON.parse(result.output.output)).toEqual([
|
|
"application/json;charset=utf-8",
|
|
false,
|
|
42,
|
|
true,
|
|
"TypeError",
|
|
[52, 50],
|
|
[52, 50],
|
|
true,
|
|
])
|
|
})
|
|
|
|
test("discards a redirect body before reading the destination", async () => {
|
|
const discarded = Promise.withResolvers<void>()
|
|
await using server = Bun.serve({
|
|
port: 0,
|
|
async fetch(req) {
|
|
if (new URL(req.url).pathname === "/")
|
|
return new Response(openBody(discarded.resolve), { status: 302, headers: { location: "/next" } })
|
|
await discarded.promise
|
|
return new Response("ok")
|
|
},
|
|
})
|
|
const result = await Effect.runPromise(
|
|
run(
|
|
server.url,
|
|
`
|
|
const reader = res.body.getReader()
|
|
const first = await reader.read()
|
|
const end = await reader.read()
|
|
reader.releaseLock()
|
|
return [res.redirected, [...first.value], end.done, res.body.locked, await res.text().catch(e => e.name)]
|
|
`,
|
|
permissionService({ assert: () => Effect.void, assertNotDenied: () => Effect.void }),
|
|
),
|
|
)
|
|
expect(JSON.parse(result.output.output)).toEqual([true, [111, 107], true, false, "TypeError"])
|
|
})
|
|
})
|
|
|
|
describe("fetch permissions", () => {
|
|
const hits: Array<string> = []
|
|
let server: ReturnType<typeof Bun.serve>
|
|
beforeAll(() => {
|
|
server = Bun.serve({
|
|
port: 0,
|
|
fetch: (request) => {
|
|
const url = new URL(request.url)
|
|
hits.push(`${request.method} ${url.pathname}`)
|
|
if (url.pathname === "/redirect") return Response.redirect(`${url.origin}/blocked`, 302)
|
|
return new Response("ok")
|
|
},
|
|
})
|
|
})
|
|
afterAll(() => server.stop(true))
|
|
|
|
test("fetch asks the webfetch permission for its URL as the execute call", async () => {
|
|
hits.length = 0
|
|
const asked: Array<Permission.AssertInput> = []
|
|
const url = `${server.url.origin}/allowed`
|
|
const result = await Effect.runPromise(
|
|
createCodeMode(
|
|
new Map(),
|
|
permissionService({ assert: (input) => Effect.sync(() => void asked.push(input)) }),
|
|
).execute({ code: `return await (await fetch("${url}", { method: "POST" })).text()` }, context),
|
|
)
|
|
|
|
expect(result.output.output).toBe("ok")
|
|
expect(hits).toEqual(["POST /allowed"])
|
|
expect(asked).toEqual([
|
|
{
|
|
action: "webfetch",
|
|
resources: [url],
|
|
save: ["*"],
|
|
metadata: { method: "POST", url },
|
|
sessionID: context.sessionID,
|
|
agent: context.agent,
|
|
source: { type: "tool", messageID: context.messageID, id: context.id },
|
|
},
|
|
])
|
|
})
|
|
|
|
test("a redirect to a URL denied for webfetch is never requested", async () => {
|
|
hits.length = 0
|
|
const denied = permissionService({
|
|
assert: () => Effect.void,
|
|
assertNotDenied: (input) =>
|
|
Effect.fail(new Permission.BlockedError({ rules: [], permission: input.action, resources: input.resources })),
|
|
})
|
|
const result = await Effect.runPromise(
|
|
createCodeMode(new Map(), denied).execute(
|
|
{ code: `try { await fetch("${server.url.origin}/redirect") } catch (e) { return e.message }` },
|
|
context,
|
|
),
|
|
)
|
|
|
|
expect(result.output.output).toContain("Permission denied")
|
|
expect(hits).toEqual(["GET /redirect"])
|
|
})
|
|
|
|
test("fetch matches rules without the fragment and rejects credentials in the URL", async () => {
|
|
hits.length = 0
|
|
const asked: Array<ReadonlyArray<string>> = []
|
|
const result = await Effect.runPromise(
|
|
createCodeMode(
|
|
new Map(),
|
|
permissionService({ assert: (input) => Effect.sync(() => void asked.push(input.resources)) }),
|
|
).execute(
|
|
{
|
|
code: `await fetch("${server.url.origin}/allowed#top"); try { await fetch("${server.url.protocol}//user@${server.url.host}/") } catch (e) { return e.message }`,
|
|
},
|
|
context,
|
|
),
|
|
)
|
|
|
|
expect(result.output.output).toBe("fetch cannot be used with credentials in the URL.")
|
|
expect(asked).toEqual([[`${server.url.origin}/allowed`]])
|
|
expect(hits).toEqual(["GET /allowed"])
|
|
})
|
|
|
|
test("a rejection with feedback reaches the program as the error message", async () => {
|
|
hits.length = 0
|
|
const url = `${server.url.origin}/corrected`
|
|
const corrected = permissionService({
|
|
assert: () => Effect.fail(new Permission.CorrectedError({ feedback: "use the docs site instead" })),
|
|
})
|
|
const result = await Effect.runPromise(
|
|
createCodeMode(new Map(), corrected).execute(
|
|
{ code: `try { await fetch("${url}") } catch (e) { return e.message }` },
|
|
context,
|
|
),
|
|
)
|
|
|
|
expect(result.output.output).toBe(`The user rejected fetching ${url}: use the docs site instead`)
|
|
expect(hits).toEqual([])
|
|
})
|
|
|
|
test("a URL denied for webfetch is never requested and rejects like a failed fetch", async () => {
|
|
hits.length = 0
|
|
const url = `${server.url.origin}/denied`
|
|
const denied = permissionService({
|
|
assert: (input) =>
|
|
Effect.fail(new Permission.BlockedError({ rules: [], permission: input.action, resources: input.resources })),
|
|
})
|
|
const result = await Effect.runPromise(
|
|
createCodeMode(new Map(), denied).execute(
|
|
{ code: `const [denied] = await Promise.allSettled([fetch("${url}")]); return denied.status` },
|
|
context,
|
|
),
|
|
)
|
|
|
|
expect(result.output.output).toBe("rejected")
|
|
expect(hits).toEqual([])
|
|
})
|
|
})
|
|
|
|
describe("fs", () => {
|
|
test("without the experimental flag there is no fs or path", async () => {
|
|
const result = await Effect.runPromise(
|
|
createCodeMode(new Map()).execute({ code: "return [typeof fs, typeof path]" }, context),
|
|
)
|
|
|
|
expect(JSON.parse(result.output.output)).toEqual(["undefined", "undefined"])
|
|
})
|
|
|
|
const source = { type: "tool" as const, messageID: context.messageID, id: context.id }
|
|
|
|
test("fs reads and writes files in the session's directory, asking read and edit permission as the execute call", async () => {
|
|
await using tmp = await tmpdir()
|
|
await Bun.write(path.join(tmp.path, "notes.txt"), "hello")
|
|
const asked: Array<Permission.AssertInput> = []
|
|
const record = { assert: (input: Permission.AssertInput) => Effect.sync(() => void asked.push(input)) }
|
|
const result = await Effect.runPromise(
|
|
createCodeMode(new Map(), permissionService(record), fileServices(tmp.path, record)).execute(
|
|
{
|
|
code: `import { readFile } from "node:fs/promises"
|
|
const text = await readFile("notes.txt", "utf8")
|
|
let missingParent
|
|
try { fs.writeFileSync("none/copy.txt", "x") } catch (e) { missingParent = e.code }
|
|
fs.mkdirSync("out")
|
|
fs.writeFileSync("out/copy.txt", text + " world")
|
|
return [text, missingParent, fs.readdirSync("out"), path.join("out", "..", "notes.txt")]`,
|
|
},
|
|
context,
|
|
),
|
|
)
|
|
|
|
expect(JSON.parse(result.output.output)).toEqual(["hello", "ENOENT", ["copy.txt"], "notes.txt"])
|
|
expect(await Bun.file(path.join(tmp.path, "out", "copy.txt")).text()).toBe("hello world")
|
|
expect(asked.map((input) => [input.action, input.resources, input.sessionID, input.source])).toEqual([
|
|
["read", ["notes.txt"], context.sessionID, source],
|
|
["edit", ["out"], context.sessionID, source],
|
|
["edit", ["out/copy.txt"], context.sessionID, source],
|
|
["read", ["out"], context.sessionID, source],
|
|
])
|
|
expect(asked[2]?.metadata).toMatchObject({ files: [{ file: "out/copy.txt", status: "added", additions: 1 }] })
|
|
expect(result.output.toolCalls).toEqual([
|
|
{ tool: "fs", status: "completed", input: { method: "readFile", path: "notes.txt" } },
|
|
{ tool: "fs", status: "error", input: { method: "writeFileSync", path: "none/copy.txt" } },
|
|
{ tool: "fs", status: "completed", input: { method: "mkdirSync", path: "out" } },
|
|
{ tool: "fs", status: "completed", input: { method: "writeFileSync", path: "out/copy.txt" } },
|
|
{ tool: "fs", status: "completed", input: { method: "readdirSync", path: "out" } },
|
|
])
|
|
})
|
|
|
|
test("fs follows Node for copy exclusivity, rename onto directories, nested listings, and file URLs", async () => {
|
|
await using tmp = await tmpdir()
|
|
await Bun.write(path.join(tmp.path, "a.txt"), "a")
|
|
await Bun.write(path.join(tmp.path, "full/x.txt"), "x")
|
|
await Bun.write(path.join(tmp.path, "src/nested/b.txt"), "b")
|
|
const result = await Effect.runPromise(
|
|
createCodeMode(new Map(), allowAll, fileServices(tmp.path)).execute(
|
|
{
|
|
code: `const code = (f) => { try { f() } catch (e) { return [e.code, typeof e.errno] } }
|
|
fs.mkdirSync("empty")
|
|
fs.mkdirSync("moved")
|
|
fs.renameSync("empty", "moved")
|
|
return [
|
|
code(() => fs.copyFileSync("a.txt", "full/x.txt", fs.constants.COPYFILE_EXCL)),
|
|
code(() => fs.renameSync("a.txt", "full")),
|
|
code(() => fs.renameSync("moved", "full")),
|
|
fs.readdirSync("src", { withFileTypes: true, recursive: true }).map((e) => [e.parentPath, e.name]),
|
|
fs.readFileSync(new URL(${JSON.stringify(pathToFileURL(path.join(tmp.path, "a.txt")).href)}), "utf8"),
|
|
]`,
|
|
},
|
|
context,
|
|
),
|
|
)
|
|
|
|
expect(JSON.parse(result.output.output)).toEqual([
|
|
["EEXIST", "number"],
|
|
["EISDIR", "number"],
|
|
["ENOTEMPTY", "number"],
|
|
[
|
|
["src", "nested"],
|
|
[path.join("src", "nested"), "b.txt"],
|
|
],
|
|
"a",
|
|
])
|
|
})
|
|
|
|
test("a denied write never touches disk: the sync call throws and the promise rejects", async () => {
|
|
await using tmp = await tmpdir()
|
|
const denyEdits = {
|
|
assert: (input: Permission.AssertInput) =>
|
|
input.action === "edit"
|
|
? Effect.fail(
|
|
new Permission.BlockedError({ rules: [], permission: input.action, resources: input.resources }),
|
|
)
|
|
: Effect.void,
|
|
}
|
|
const result = await Effect.runPromise(
|
|
createCodeMode(new Map(), permissionService(denyEdits), fileServices(tmp.path, denyEdits)).execute(
|
|
{
|
|
code: `let thrown
|
|
try { fs.writeFileSync("a.txt", "x") } catch (e) { thrown = [e.message] }
|
|
const [rejected] = await Promise.allSettled([fs.promises.writeFile("b.txt", "x")])
|
|
return [thrown, rejected.status, fs.existsSync("a.txt")]`,
|
|
},
|
|
context,
|
|
),
|
|
)
|
|
|
|
const [thrown, status, exists] = JSON.parse(result.output.output)
|
|
expect(thrown[0]).toContain("Permission denied")
|
|
expect([status, exists]).toEqual(["rejected", false])
|
|
expect(await fs.readdir(tmp.path)).toEqual([])
|
|
})
|
|
|
|
test("a missing file fails with a Node-shaped ENOENT error", async () => {
|
|
await using tmp = await tmpdir()
|
|
const result = await Effect.runPromise(
|
|
createCodeMode(new Map(), allowAll, fileServices(tmp.path)).execute(
|
|
{
|
|
code: `try { await fs.promises.readFile("missing.txt") } catch (e) {
|
|
return [e instanceof Error, e.code, e.syscall, e.path, e.message]
|
|
}`,
|
|
},
|
|
context,
|
|
),
|
|
)
|
|
|
|
expect(JSON.parse(result.output.output)).toEqual([
|
|
true,
|
|
"ENOENT",
|
|
"open",
|
|
"missing.txt",
|
|
"ENOENT: no such file or directory, open 'missing.txt'",
|
|
])
|
|
})
|
|
|
|
const runFs = async (directory: string, code: string, permission = allowAll, files = fileServices(directory)) => {
|
|
const result = await Effect.runPromise(createCodeMode(new Map(), permission, files).execute({ code }, context))
|
|
return JSON.parse(result.output.output)
|
|
}
|
|
|
|
test("mkdir, mkdtemp, rmdir and truncate behave like Node", async () => {
|
|
await using tmp = await tmpdir()
|
|
await Bun.write(path.join(tmp.path, "long.txt"), "abcdef")
|
|
expect(
|
|
await runFs(
|
|
tmp.path,
|
|
`const first = fs.mkdirSync("a/b/c", { recursive: true })
|
|
const again = fs.mkdirSync("a/b/c", { recursive: true })
|
|
let missingParent
|
|
try { fs.mkdirSync("x/y") } catch (e) { missingParent = e.code }
|
|
const temp = fs.mkdtempSync("tmp-")
|
|
let notEmpty
|
|
try { fs.rmdirSync("a") } catch (e) { notEmpty = e.code }
|
|
fs.rmdirSync("a", { recursive: true })
|
|
fs.truncateSync("long.txt", 3)
|
|
return [first, again ?? null, missingParent, /^tmp-[A-Za-z0-9]{6}$/.test(temp), fs.statSync(temp).isDirectory(),
|
|
notEmpty, fs.existsSync("a"), fs.readFileSync("long.txt", "utf8")]`,
|
|
),
|
|
).toEqual(["a", null, "ENOENT", true, true, "ENOTEMPTY", false, "abc"])
|
|
})
|
|
|
|
test("cp copies files and folders, and glob matches paths like Node", async () => {
|
|
await using tmp = await tmpdir()
|
|
await Bun.write(path.join(tmp.path, "src", "a.ts"), "a")
|
|
await Bun.write(path.join(tmp.path, "src", "nested", "b.ts"), "b")
|
|
await Bun.write(path.join(tmp.path, "src", "nested", "c.md"), "c")
|
|
await Bun.write(path.join(tmp.path, "src", ".hidden", "d.ts"), "d")
|
|
expect(
|
|
await runFs(
|
|
tmp.path,
|
|
`fs.cpSync("src", "copy", { recursive: true })
|
|
fs.cpSync("src/a.ts", "one.ts")
|
|
let needsRecursive
|
|
try { fs.cpSync("src", "nope") } catch (e) { needsRecursive = e.code }
|
|
return [fs.globSync("copy/**/*.ts").sort(), fs.readFileSync("one.ts", "utf8"), needsRecursive,
|
|
fs.globSync("src/*.ts"), fs.globSync("src/**/*", { exclude: ["**/*.md"] }).sort(),
|
|
fs.globSync("src/a.ts", { withFileTypes: true }).map((d) => [d.name, d.isFile()]),
|
|
fs.globSync("src/*/b.ts"), fs.globSync(path.join(${JSON.stringify(tmp.path)}, "src", "*/*.md"))]`,
|
|
),
|
|
).toEqual([
|
|
["copy/a.ts", "copy/nested/b.ts"],
|
|
"a",
|
|
"EISDIR",
|
|
["src/a.ts"],
|
|
["src/a.ts", "src/nested", "src/nested/b.ts"],
|
|
[["a.ts", true]],
|
|
["src/nested/b.ts"],
|
|
[path.join(tmp.path, "src", "nested", "c.md")],
|
|
])
|
|
})
|
|
|
|
test("readFile returns a Buffer, stat can skip a missing path, and writeFile takes append and exclusive flags", async () => {
|
|
await using tmp = await tmpdir()
|
|
await Bun.write(path.join(tmp.path, "log.txt"), "one")
|
|
expect(
|
|
await runFs(
|
|
tmp.path,
|
|
`fs.writeFileSync("log.txt", "two", { flag: "a" })
|
|
let exclusive
|
|
try { fs.writeFileSync("log.txt", "x", { flag: "wx" }) } catch (e) { exclusive = e.code }
|
|
const entry = fs.readdirSync(".", { withFileTypes: true })[0]
|
|
return [Buffer.isBuffer(fs.readFileSync("log.txt")), fs.readFileSync("log.txt").toString(), exclusive,
|
|
fs.statSync("missing", { throwIfNoEntry: false }) ?? null, [entry.name, entry.parentPath, entry.isFIFO()]]`,
|
|
),
|
|
).toEqual([true, "onetwo", "EEXIST", null, ["log.txt", ".", false]])
|
|
})
|
|
|
|
test("writes keep exactly the bytes written: no formatting, no BOM handling, no parent directories", async () => {
|
|
await using tmp = await tmpdir()
|
|
await Bun.write(path.join(tmp.path, "bom.txt"), "\uFEFFold")
|
|
// A formatter that rewrites every file it's given, so a write that ran it would read back "formatted".
|
|
const formatter = (file: string) => Effect.promise(() => fs.writeFile(file, "formatted")).pipe(Effect.as(true))
|
|
const result = await runFs(
|
|
tmp.path,
|
|
`fs.writeFileSync("bom.txt", "new")
|
|
fs.writeFileSync("ugly.ts", "const x =1")
|
|
let missing
|
|
try { fs.writeFileSync("no/such/dir.txt", "x") } catch (e) { missing = e.code }
|
|
fs.appendFileSync("ugly.ts", ";")
|
|
return [missing]`,
|
|
allowAll,
|
|
fileServices(tmp.path, undefined, formatter),
|
|
)
|
|
expect(result).toEqual(["ENOENT"])
|
|
expect([...(await fs.readFile(path.join(tmp.path, "bom.txt")))]).toEqual([...Buffer.from("new")])
|
|
expect(await fs.readFile(path.join(tmp.path, "ugly.ts"), "utf8")).toBe("const x =1;")
|
|
})
|
|
|
|
test("an append asks edit with only the new lines, not a diff of the whole file", async () => {
|
|
await using tmp = await tmpdir()
|
|
await Bun.write(path.join(tmp.path, "log.txt"), "old line 1\nold line 2\n")
|
|
const asked: Array<Permission.AssertInput> = []
|
|
const record = { assert: (input: Permission.AssertInput) => Effect.sync(() => void asked.push(input)) }
|
|
await runFs(
|
|
tmp.path,
|
|
`fs.appendFileSync("log.txt", "new line\\n"); return []`,
|
|
permissionService(record),
|
|
fileServices(tmp.path, record),
|
|
)
|
|
const edit = asked.find((input) => input.action === "edit")
|
|
expect(edit?.metadata).toMatchObject({ files: [{ file: "log.txt", status: "modified", additions: 1, deletions: 0 }] })
|
|
expect(JSON.stringify(edit?.metadata)).not.toContain("old line")
|
|
expect(await fs.readFile(path.join(tmp.path, "log.txt"), "utf8")).toBe("old line 1\nold line 2\nnew line\n")
|
|
})
|
|
|
|
test("concurrent appends to one file keep every chunk", async () => {
|
|
await using tmp = await tmpdir()
|
|
await runFs(
|
|
tmp.path,
|
|
`await Promise.all(Array.from({ length: 20 }, (_, i) => fs.promises.appendFile("log.txt", i + "\\n")))
|
|
return []`,
|
|
)
|
|
const lines = (await fs.readFile(path.join(tmp.path, "log.txt"), "utf8")).trim().split("\n")
|
|
expect(lines.map(Number).toSorted((a, b) => a - b)).toEqual(Array.from({ length: 20 }, (_, i) => i))
|
|
})
|
|
|
|
test("path is the host's path module, resolving against the session's directory", async () => {
|
|
await using tmp = await tmpdir()
|
|
const [resolved, relative, posix, win32, sep] = await runFs(
|
|
tmp.path,
|
|
`return [path.resolve("a", "b"), path.relative("a", "c"), path.posix.join("a", "b"), path.win32.join("a", "b"), path.sep]`,
|
|
)
|
|
expect(resolved).toBe(path.resolve(tmp.path, "a", "b"))
|
|
expect(relative).toBe(path.join("..", "c"))
|
|
expect([posix, win32, sep]).toEqual(["a/b", "a\\b", path.sep])
|
|
})
|
|
|
|
test("existsSync is false for a path it may not check, instead of throwing", async () => {
|
|
await using tmp = await tmpdir()
|
|
await Bun.write(path.join(tmp.path, "secret.txt"), "x")
|
|
const denyReads = {
|
|
assert: (input: Permission.AssertInput) =>
|
|
input.action === "read"
|
|
? Effect.fail(
|
|
new Permission.BlockedError({ rules: [], permission: input.action, resources: input.resources }),
|
|
)
|
|
: Effect.void,
|
|
}
|
|
expect(
|
|
await runFs(
|
|
tmp.path,
|
|
`return fs.existsSync("secret.txt")`,
|
|
permissionService(denyReads),
|
|
fileServices(tmp.path, denyReads),
|
|
),
|
|
).toBe(false)
|
|
})
|
|
|
|
test("readFile without an encoding gives text for UTF-8 files and bytes otherwise", async () => {
|
|
await using tmp = await tmpdir()
|
|
await Bun.write(path.join(tmp.path, "data.json"), '{"a":1}')
|
|
await Bun.write(path.join(tmp.path, "image.bin"), new Uint8Array([0xff, 0xfe, 0x00]))
|
|
const result = await Effect.runPromise(
|
|
createCodeMode(new Map(), allowAll, fileServices(tmp.path)).execute(
|
|
{
|
|
code: `const bin = fs.readFileSync("image.bin")
|
|
return [JSON.parse(fs.readFileSync("data.json")).a, fs.readFileSync("data.json").toString(), bin instanceof Uint8Array, [...bin]]`,
|
|
},
|
|
context,
|
|
),
|
|
)
|
|
|
|
expect(JSON.parse(result.output.output)).toEqual([1, '{"a":1}', true, [255, 254, 0]])
|
|
})
|
|
|
|
test("a path outside the project is approved before anything checks it on disk", async () => {
|
|
await using tmp = await tmpdir()
|
|
await using outside = await tmpdir()
|
|
await Bun.write(path.join(outside.path, "here.txt"), "x")
|
|
await Bun.write(path.join(outside.path, "full", "file.txt"), "x")
|
|
const denyOutside = {
|
|
assert: (input: Permission.AssertInput) =>
|
|
input.action === "external_directory"
|
|
? Effect.fail(
|
|
new Permission.BlockedError({ rules: [], permission: input.action, resources: input.resources }),
|
|
)
|
|
: Effect.void,
|
|
}
|
|
const at = (name: string) => JSON.stringify(path.join(outside.path, name))
|
|
const result = await Effect.runPromise(
|
|
createCodeMode(new Map(), permissionService(denyOutside), fileServices(tmp.path, denyOutside)).execute(
|
|
{
|
|
code: `fs.writeFileSync("a.txt", "a")
|
|
const code = (run) => { try { run(); return "ok" } catch (e) { return e.message } }
|
|
return [
|
|
code(() => fs.rmSync(${at("here.txt")})),
|
|
code(() => fs.rmSync(${at("missing.txt")}, { force: true })),
|
|
code(() => fs.rmSync(${at("missing.txt")})),
|
|
code(() => fs.renameSync("a.txt", ${at("full")})),
|
|
code(() => fs.copyFileSync("a.txt", ${at("here.txt")}, fs.constants.COPYFILE_EXCL)),
|
|
code(() => fs.appendFileSync(${at("here.txt")}, "y")),
|
|
]`,
|
|
},
|
|
context,
|
|
),
|
|
)
|
|
|
|
// Every call fails the same way whether or not the outside path exists, and nothing outside changed.
|
|
expect(JSON.parse(result.output.output)).toEqual(Array(6).fill("Permission denied: external_directory"))
|
|
expect(await Bun.file(path.join(outside.path, "here.txt")).text()).toBe("x")
|
|
})
|
|
})
|
|
|
|
test("canonical execution distinguishes declared, model-only, and raw schema outputs", async () => {
|
|
const declared: Info = {
|
|
name: "declared",
|
|
description: "Declared",
|
|
input: Schema.Struct({ value: Schema.String }),
|
|
output: Schema.Struct({ value: Schema.String }),
|
|
execute: ({ value }) => Effect.succeed({ output: { value } }),
|
|
}
|
|
const modelOnlyInput = Schema.Struct({})
|
|
const modelOnly = {
|
|
name: "model_only",
|
|
description: "Model only",
|
|
input: modelOnlyInput,
|
|
execute: () => Effect.succeed({ content: "visible only", metadata: { kind: "model" } }),
|
|
} satisfies Info<typeof modelOnlyInput, undefined>
|
|
const raw: Info = {
|
|
name: "raw",
|
|
description: "Raw",
|
|
input: {},
|
|
output: {},
|
|
execute: (input) => Effect.succeed({ output: input, content: "raw" }),
|
|
}
|
|
|
|
expect(await Effect.runPromise(execute(declared, { value: "encoded" }, context))).toEqual({
|
|
output: { value: "encoded" },
|
|
content: [{ type: "text", text: '{"value":"encoded"}' }],
|
|
})
|
|
expect(await Effect.runPromise(execute(modelOnly, {}, context))).toEqual({
|
|
output: undefined,
|
|
content: [{ type: "text", text: "visible only" }],
|
|
metadata: { kind: "model" },
|
|
})
|
|
expect(await Effect.runPromise(execute(raw, { unchecked: true }, context))).toEqual({
|
|
output: { unchecked: true },
|
|
content: [{ type: "text", text: "raw" }],
|
|
})
|
|
})
|
|
|
|
test("declared outputs cannot bypass validation and raw outputs stay JSON-compatible", async () => {
|
|
const missing: Info = {
|
|
name: "missing",
|
|
description: "Missing output",
|
|
input: Schema.Struct({}),
|
|
output: Schema.String,
|
|
execute: () => Effect.succeed({ content: "not an output" }),
|
|
}
|
|
const invalid: Info = {
|
|
name: "invalid",
|
|
description: "Invalid raw output",
|
|
input: {},
|
|
output: {},
|
|
execute: () => Effect.succeed({ output: 1n, content: "not JSON" }),
|
|
}
|
|
|
|
expect((await Effect.runPromiseExit(execute(missing, {}, context))).toString()).toContain(
|
|
"Tool did not return its declared output",
|
|
)
|
|
expect((await Effect.runPromiseExit(execute(invalid, {}, context))).toString()).toContain(
|
|
"Tool returned a non-JSON value",
|
|
)
|
|
})
|
|
|
|
test("foreign typed failures settle as Tool.Error at the untrusted boundary", async () => {
|
|
class ForeignFailure extends Schema.TaggedError<ForeignFailure>()("Plugin.ForeignFailure", {
|
|
message: Schema.String,
|
|
}) {}
|
|
const lying: Info = {
|
|
name: "lying",
|
|
description: "Fails with a non-Tool.Error typed failure",
|
|
input: Schema.Struct({}),
|
|
execute: () => new ForeignFailure({ message: "transport died" }) as never,
|
|
}
|
|
|
|
const error = await Effect.runPromise(execute(lying, {}, context).pipe(Effect.flip))
|
|
expect(error).toBeInstanceOf(Tool.Error)
|
|
expect(error.message).toBe("transport died")
|
|
})
|
|
|
|
test("execute supports callable namespace tools", async () => {
|
|
const callable: Info = {
|
|
name: "admin",
|
|
description: "Administer Slack",
|
|
input: Schema.Struct({}),
|
|
output: Schema.String,
|
|
options: { namespace: "slack" },
|
|
execute: () => Effect.succeed({ output: "admin" }),
|
|
}
|
|
const child: Info = {
|
|
name: "create",
|
|
description: "Create a Slack resource",
|
|
input: Schema.Struct({}),
|
|
output: Schema.String,
|
|
options: { namespace: "slack.admin" },
|
|
execute: () => Effect.succeed({ output: "created" }),
|
|
}
|
|
const codeMode = createCodeMode(
|
|
new Map([
|
|
["slack_admin", callable],
|
|
["slack_admin_create", child],
|
|
]),
|
|
)
|
|
const result = await Effect.runPromise(
|
|
codeMode.execute({ code: "return [await tools.slack.admin({}), await tools.slack.admin.create({})]" }, context),
|
|
)
|
|
|
|
expect(result.metadata).toEqual({
|
|
toolCalls: [
|
|
{ tool: "slack.admin", status: "completed" },
|
|
{ tool: "slack.admin.create", status: "completed" },
|
|
],
|
|
})
|
|
expect(result.content).toEqual([{ type: "text", text: '["admin","created"]' }])
|
|
})
|
|
|
|
test("each call in a program gets its own ID and is marked as nested in execute", async () => {
|
|
const ids: string[] = []
|
|
const nested: Array<[string, string]> = []
|
|
const input = Schema.Struct({})
|
|
const record = {
|
|
name: "record",
|
|
description: "Record the call",
|
|
input,
|
|
execute: (_, context) => Effect.sync(() => ids.push(context.id)).pipe(Effect.as({ content: "ok" })),
|
|
} satisfies Info<typeof input>
|
|
await Effect.runPromise(
|
|
createCodeMode(
|
|
new Map<string, Info>([["record", record]]),
|
|
permissionService({
|
|
nested: (call, parent) => Effect.sync(() => void nested.push([call, parent])),
|
|
}),
|
|
).execute({ code: "await Promise.all([tools.record({}), tools.record({})])" }, context),
|
|
)
|
|
expect(new Set(ids).size).toBe(2)
|
|
expect(ids).not.toContain(context.id)
|
|
expect(nested.toSorted()).toEqual(ids.toSorted().map((id) => [id, context.id]))
|
|
})
|
|
|
|
test("executions share the prepared runtime of an inventory while keeping per-call state", async () => {
|
|
let conversions = 0
|
|
const echo: Info = {
|
|
name: "echo",
|
|
description: "Echo a value",
|
|
input: {
|
|
"~standard": {
|
|
version: 1,
|
|
vendor: "test",
|
|
validate: (value: unknown) => ({ value }),
|
|
jsonSchema: {
|
|
input: () => {
|
|
conversions++
|
|
return { type: "object", properties: { value: { type: "string" } }, required: ["value"] }
|
|
},
|
|
output: () => ({}),
|
|
},
|
|
},
|
|
},
|
|
execute: (input) => Effect.succeed({ content: (input as { value: string }).value }),
|
|
}
|
|
const inventory = { tools: new Map([["echo", echo]]) }
|
|
const codeMode = CodeModeTool.create(inventory, (_, tool, input, context) => execute(tool, input, context), allowAll)
|
|
const run = (id: string) => {
|
|
const progress: Array<Tool.Metadata> = []
|
|
return CodeModeTool.create(inventory, (_, tool, input, context) => execute(tool, input, context), allowAll)
|
|
.execute(
|
|
{ code: `return await tools.echo({ value: "${id}" })` },
|
|
{ ...context, id: Tool.CallID.make(id), progress: (update) => Effect.sync(() => progress.push(update)) },
|
|
)
|
|
.pipe(Effect.map((result) => ({ output: result.output.output, progress })))
|
|
}
|
|
|
|
const results = await Effect.runPromise(
|
|
Effect.all([run("first"), run("second")], { concurrency: "unbounded" }).pipe(Effect.provide(TestClock.layer())),
|
|
)
|
|
expect(CodeModeTool.catalog(inventory).tools).toHaveLength(1)
|
|
expect<unknown>(results).toEqual(
|
|
["first", "second"].map((id) => ({
|
|
output: id,
|
|
progress: [{ toolCalls: [{ tool: "echo", status: "running", input: { value: id } }] }],
|
|
})),
|
|
)
|
|
expect(
|
|
(await Effect.runPromise(codeMode.execute({ code: 'return await tools.echo({ value: "x" })' }, context))).output
|
|
.output,
|
|
).toBe("x")
|
|
expect(conversions).toBe(1)
|
|
|
|
await Effect.runPromise(
|
|
createCodeMode(new Map(inventory.tools)).execute({ code: 'return await tools.echo({ value: "next" })' }, context),
|
|
)
|
|
expect(conversions).toBe(2)
|
|
})
|
|
|
|
const progressCodeMode = (started: Deferred.Deferred<void>, wait: Effect.Effect<void>) =>
|
|
createCodeMode(
|
|
new Map<string, Info>([
|
|
[
|
|
"step",
|
|
{
|
|
name: "step",
|
|
description: "Step",
|
|
input: Schema.Struct({}),
|
|
output: Schema.String,
|
|
execute: () => Effect.succeed({ output: "ok" }),
|
|
},
|
|
],
|
|
[
|
|
"wait",
|
|
{
|
|
name: "wait",
|
|
description: "Wait",
|
|
input: Schema.Struct({}),
|
|
output: Schema.String,
|
|
execute: () => Deferred.succeed(started, undefined).pipe(Effect.andThen(wait), Effect.as({ output: "ok" })),
|
|
},
|
|
],
|
|
]),
|
|
)
|
|
|
|
const row = (tool: string, status: string) => ({ tool, status })
|
|
|
|
it.effect("execute sends at most one progress update per 100 ms with the latest rows", () =>
|
|
Effect.gen(function* () {
|
|
const started = yield* Deferred.make<void>()
|
|
const progress: Array<Tool.Metadata> = []
|
|
const fiber = yield* progressCodeMode(started, Effect.sleep("250 millis"))
|
|
.execute(
|
|
{
|
|
code: "for (const i of [1, 2, 3]) await tools.step({}); await tools.wait({}); return await tools.step({})",
|
|
},
|
|
{ ...context, progress: (update) => Effect.sync(() => progress.push(update)) },
|
|
)
|
|
.pipe(Effect.forkChild({ startImmediately: true }))
|
|
yield* Deferred.await(started)
|
|
yield* Effect.yieldNow
|
|
expect(progress).toEqual([{ toolCalls: [row("step", "running")] }])
|
|
|
|
yield* TestClock.adjust("100 millis")
|
|
const steps = [row("step", "completed"), row("step", "completed"), row("step", "completed")]
|
|
expect(progress.slice(1)).toEqual([{ toolCalls: [...steps, row("wait", "running")] }])
|
|
|
|
// The wait ends 150 ms after the trailing update, so its row goes out at once; the last step's never does.
|
|
yield* TestClock.adjust("150 millis")
|
|
const result = yield* Fiber.join(fiber)
|
|
yield* TestClock.adjust("1 second")
|
|
expect(progress.slice(2)).toEqual([{ toolCalls: [...steps, row("wait", "completed")] }])
|
|
expect(result.metadata).toEqual({ toolCalls: [...steps, row("wait", "completed"), row("step", "completed")] })
|
|
}),
|
|
)
|
|
|
|
it.effect("interrupted execute sends its latest progress rows before it settles", () =>
|
|
Effect.gen(function* () {
|
|
const started = yield* Deferred.make<void>()
|
|
const progress: Array<Tool.Metadata> = []
|
|
const fiber = yield* progressCodeMode(started, Effect.never)
|
|
.execute(
|
|
{ code: "await tools.step({}); await tools.step({}); return await tools.wait({})" },
|
|
{ ...context, progress: (update) => Effect.sync(() => progress.push(update)) },
|
|
)
|
|
.pipe(Effect.forkChild({ startImmediately: true }))
|
|
yield* Deferred.await(started)
|
|
yield* Fiber.interrupt(fiber)
|
|
yield* TestClock.adjust("1 second")
|
|
expect(progress).toEqual([
|
|
{ toolCalls: [row("step", "running")] },
|
|
{ toolCalls: [row("step", "completed"), row("step", "completed"), row("wait", "error")] },
|
|
])
|
|
}),
|
|
)
|