feat(codemode): return logs and calls when a run is stopped

This commit is contained in:
Aiden Cline 2026-10-29 22:23:18 -05:00
parent c22c270121
commit 5ea12452bb
5 changed files with 151 additions and 10 deletions

View file

@ -86,8 +86,13 @@ const runtime = CodeMode.make({ tools, limits: { timeoutMs: 30_000 } })
runtime.catalog() // structured tool descriptions
runtime.execute(source) // Effect<CodeMode.Result, never, ToolServices>
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,

View file

@ -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

View file

@ -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<Record<string, DataValue>>
} & 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<void>
}
/** 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<R = never> = {
readonly catalog: ReadonlyArray<ToolDescription>
readonly execute: (code: string, bindings?: Readonly<Record<string, DataValue>>) => Effect.Effect<Result, never, R>
readonly execute: (
code: string,
bindings?: Readonly<Record<string, DataValue>>,
options?: RunOptions,
) => Effect.Effect<Result, never, R>
}
const validateLimit = (name: keyof ExecutionLimits, value: number | undefined, minimum: number): number | undefined => {
@ -156,7 +170,8 @@ export const execute = <
const Extensions extends ReadonlyArray<Extension> = [],
>(
options: ExecuteOptions<Provided, Extensions>,
): Effect.Effect<Result, never, Environment<Provided, Extensions>> => make(options).execute(options.code, options.bindings)
): Effect.Effect<Result, never, Environment<Provided, Extensions>> =>
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,
),
}
}

View file

@ -15,6 +15,7 @@ export const executeProgram = <R>(
limits: ResolvedExecutionLimits,
hooks: ToolRuntime.Hooks<R>,
globals?: (ctx: Interpreter<R>) => ReadonlyArray<readonly [string, Value]>,
stop?: Effect.Effect<void>,
): Effect.Effect<Result, never, R> => {
if (code.trim().length === 0) {
return Effect.succeed({
@ -92,7 +93,24 @@ export const executeProgram = <R>(
}),
)
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

View file

@ -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<never>) =>
@ -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<void>) =>
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<string> = []
const started = Deferred.makeUnsafe<void>()
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<void>()
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<void>()
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", () => {