From 5ea12452bbb75cdd9f3753222b4e73c2193fa609 Mon Sep 17 00:00:00 2001 From: Aiden Cline Date: Thu, 29 Oct 2026 22:23:18 -0500 Subject: [PATCH] feat(codemode): return logs and calls when a run is stopped --- packages/codemode/README.md | 5 + packages/codemode/interpreter-support.md | 2 + packages/codemode/src/codemode.ts | 38 ++++++-- packages/codemode/src/interpreter/execute.ts | 20 +++- packages/codemode/test/codemode.test.ts | 96 +++++++++++++++++++- 5 files changed, 151 insertions(+), 10 deletions(-) diff --git a/packages/codemode/README.md b/packages/codemode/README.md index f0b405bb939..fab9ea37496 100644 --- a/packages/codemode/README.md +++ b/packages/codemode/README.md @@ -86,8 +86,13 @@ const runtime = CodeMode.make({ tools, limits: { timeoutMs: 30_000 } }) runtime.catalog() // structured tool descriptions runtime.execute(source) // Effect +runtime.execute(source, bindings, { stop }) // per-run globals and a stop signal ``` +Interrupting the Effect interrupts the program and returns no result. To keep what it did, pass `stop` instead: when +that Effect completes, running calls are interrupted and the execution returns +`{ ok: false, error: { kind: "Interrupted" }, logs, toolCalls }`, bounded like any other failure. + The Effect environment is inferred from the supplied tools. `hooks` surround every call the program makes into the host: `tool.before`/`tool.after` receive `{ name, input }` with decoded input, `extension.before`/`extension.after` receive `{ extension, name, args }`. An `after` hook also receives how the call ended (`success` with its value, diff --git a/packages/codemode/interpreter-support.md b/packages/codemode/interpreter-support.md index ba2be07da7e..fc28e6f2f7d 100644 --- a/packages/codemode/interpreter-support.md +++ b/packages/codemode/interpreter-support.md @@ -34,6 +34,8 @@ the ultimate source of truth. Upstream test262 files run verbatim from `test/tes shadowable by program declarations like other globals. Its result can also be awaited or chained with `then`, `catch`, and `finally`. - [x] Cooperative timeout, an optional total tool-call limit, output bounding, and unrestricted tool-call concurrency. +- [x] A host `stop` signal that interrupts running calls and returns an `Interrupted` failure with the logs and calls + so far. - [x] The timeout fires between interpreter steps, so one built-in is bounded in what it may build: strings up to 2^24 characters (`repeat`, `pad*`, `concat`, `join`, `+`, template literals, `JSON.stringify`), arrays up to 10,000,000 elements (`Array(n)`, `length =`, `Array.from`, `split`, `matchAll`, `concat`, `flat`; below the JS diff --git a/packages/codemode/src/codemode.ts b/packages/codemode/src/codemode.ts index c6637b82573..b872ee03eec 100644 --- a/packages/codemode/src/codemode.ts +++ b/packages/codemode/src/codemode.ts @@ -70,6 +70,15 @@ export type ExecuteOptions< code: string /** Read-only JSON values bound in the program's outer global scope (shadowable by top-level declarations). */ bindings?: Readonly> +} & RunOptions + +/** Options for one run of a program. */ +export type RunOptions = { + /** + * Stops the program when it completes. Running calls are interrupted, and the execution returns an `Interrupted` + * failure with the logs and calls so far instead of being interrupted itself. + */ + stop?: Effect.Effect } /** A JSON value that can cross the confined interpreter boundary. */ @@ -90,9 +99,10 @@ export const DiagnosticKind = Schema.Literals([ "TimeoutExceeded", "ToolFailure", "ExecutionFailure", + "Interrupted", "Truncated", ]) -/** Stable categories produced by program, schema, tool, limit, and truncation diagnostics. */ +/** Stable categories produced by program, schema, tool, limit, stop, and truncation diagnostics. */ export type DiagnosticKind = typeof DiagnosticKind.Type export const Diagnostic = Schema.Struct({ @@ -134,7 +144,11 @@ export type Result = typeof Result.Type /** Reusable confined runtime over explicit tools. */ export type Runtime = { readonly catalog: ReadonlyArray - readonly execute: (code: string, bindings?: Readonly>) => Effect.Effect + readonly execute: ( + code: string, + bindings?: Readonly>, + options?: RunOptions, + ) => Effect.Effect } const validateLimit = (name: keyof ExecutionLimits, value: number | undefined, minimum: number): number | undefined => { @@ -156,7 +170,8 @@ export const execute = < const Extensions extends ReadonlyArray = [], >( options: ExecuteOptions, -): Effect.Effect> => make(options).execute(options.code, options.bindings) +): Effect.Effect> => + make(options).execute(options.code, options.bindings, options) /** Creates an Effect-native runtime over explicit, schema-described tools and extensions. */ export const make = < @@ -181,10 +196,17 @@ export const make = < get catalog() { return prepared.catalog }, - execute: (code, bindings) => - executeProgram(code, prepared, limits, options.hooks ?? {}, (ctx) => [ - ...Object.entries(bindings ?? {}).map(([name, value]) => [name, fromJson(ctx, value)] as const), - ...extensionGlobals(ctx, extensions), - ]), + execute: (code, bindings, run) => + executeProgram( + code, + prepared, + limits, + options.hooks ?? {}, + (ctx) => [ + ...Object.entries(bindings ?? {}).map(([name, value]) => [name, fromJson(ctx, value)] as const), + ...extensionGlobals(ctx, extensions), + ], + run?.stop, + ), } } diff --git a/packages/codemode/src/interpreter/execute.ts b/packages/codemode/src/interpreter/execute.ts index dbad1daa218..5883952e2c2 100644 --- a/packages/codemode/src/interpreter/execute.ts +++ b/packages/codemode/src/interpreter/execute.ts @@ -15,6 +15,7 @@ export const executeProgram = ( limits: ResolvedExecutionLimits, hooks: ToolRuntime.Hooks, globals?: (ctx: Interpreter) => ReadonlyArray, + stop?: Effect.Effect, ): Effect.Effect => { if (code.trim().length === 0) { return Effect.succeed({ @@ -92,7 +93,24 @@ export const executeProgram = ( }), ) - return operation.pipe( + // A stop ends the program like an interrupt, then reports what it had done once its running calls have settled. + const stoppable = + stop === undefined + ? operation + : operation.pipe( + Effect.raceFirst(stop.pipe(Effect.as(undefined))), + Effect.map( + (result): Result => + result ?? { + ok: false, + error: { kind: "Interrupted", message: "Execution was interrupted." }, + ...logged(), + toolCalls: tools.calls, + }, + ), + ) + + return stoppable.pipe( Effect.catchCause((cause) => Cause.hasInterruptsOnly(cause) ? Effect.interrupt diff --git a/packages/codemode/test/codemode.test.ts b/packages/codemode/test/codemode.test.ts index 225805e403f..4873fa0a298 100644 --- a/packages/codemode/test/codemode.test.ts +++ b/packages/codemode/test/codemode.test.ts @@ -1,5 +1,5 @@ import { describe, expect, test } from "bun:test" -import { Cause, Effect, Schema } from "effect" +import { Cause, Deferred, Effect, Exit, Fiber, Schema } from "effect" import { CodeMode, Extension, Tool, toolError } from "../src/index.js" const run = (tool: Tool.Tool) => @@ -392,6 +392,100 @@ describe("CodeMode call hooks", () => { expect(result).toMatchObject({ ok: false, error: { kind: "TimeoutExceeded" } }) expect(events).toEqual(['tool.before {"name":"host.call","input":{}}', "tool.after host.call interrupted"]) }) + + describe("with a stop signal", () => { + const lookup = Tool.make({ + description: "Look up", + input: Schema.Struct({}), + output: Schema.String, + execute: () => Effect.succeed("found"), + }) + const waiting = (started: Deferred.Deferred) => + Tool.make({ + description: "Wait", + input: Schema.Struct({}), + output: Schema.String, + execute: () => Deferred.succeed(started, undefined).pipe(Effect.andThen(Effect.never)), + }) + + test("returns what a stopped program logged and called, after its running calls settle", async () => { + const events: Array = [] + const started = Deferred.makeUnsafe() + const runtime = CodeMode.make({ tools: { lookup, wait: waiting(started) }, hooks: observe(events) }) + + const result = await Effect.runPromise( + runtime.execute('console.log("starting"); await tools.lookup({}); await tools.wait({})', undefined, { + stop: Deferred.await(started), + }), + ) + + expect(result).toEqual({ + ok: false, + error: { kind: "Interrupted", message: "Execution was interrupted." }, + logs: ["starting"], + toolCalls: [{ name: "lookup" }, { name: "wait" }], + }) + expect(events).toEqual([ + 'tool.before {"name":"lookup","input":{}}', + "tool.after lookup success", + 'tool.before {"name":"wait","input":{}}', + "tool.after wait interrupted", + ]) + }) + + test("bounds the logs of a stopped program", async () => { + const started = Deferred.makeUnsafe() + const runtime = CodeMode.make({ tools: { wait: waiting(started) }, limits: { maxOutputBytes: 10 } }) + + const result = await Effect.runPromise( + runtime.execute('console.log("first"); console.log("second"); await tools.wait({})', undefined, { + stop: Deferred.await(started), + }), + ) + + expect(result).toMatchObject({ + ok: false, + error: { kind: "Interrupted" }, + logs: ["first", "[logs truncated: showing 1 of 2 lines]"], + truncated: true, + }) + }) + + test("still ends interrupted by an outside interrupt or a call interrupting itself", async () => { + const started = Deferred.makeUnsafe() + const interrupting = Tool.make({ + description: "Interrupt", + input: Schema.Struct({}), + output: Schema.String, + execute: () => Effect.interrupt, + }) + const runtime = CodeMode.make({ tools: { wait: waiting(started), interrupting } }) + + const outside = await Effect.runPromiseExit( + Effect.gen(function* () { + const execution = yield* runtime + .execute("await tools.wait({})", undefined, { stop: Effect.never }) + .pipe(Effect.forkChild({ startImmediately: true })) + yield* Deferred.await(started) + return yield* Fiber.interrupt(execution).pipe(Effect.andThen(Fiber.join(execution))) + }), + ) + const inside = await Effect.runPromiseExit( + runtime.execute("await tools.interrupting({})", undefined, { stop: Effect.never }), + ) + + expect(Exit.hasInterrupts(outside)).toBe(true) + expect(Exit.hasInterrupts(inside)).toBe(true) + }) + + test("leaves a program that finishes first unchanged", async () => { + const result = await Effect.runPromise( + CodeMode.execute({ tools: { lookup }, code: "return await tools.lookup({})", stop: Effect.never }), + ) + + expect(result).toEqual({ ok: true, value: "found", toolCalls: [{ name: "lookup" }] }) + }) + }) }) describe("CodeMode console capture", () => {