From d585e851134e62d4379ab70af65e3f08dfef5844 Mon Sep 17 00:00:00 2001 From: systemfsoftware-bot Date: Tue, 1 Dec 2026 20:41:04 +0000 Subject: [PATCH 01/11] fix(platform-cloudflare): normalize Code Mode programs before loading - Normalize model-authored program text at the executor boundary: strip a markdown code fence, parse in module mode with acorn, and emit one default export the harness invokes once. - Accept a function expression with a trailing semicolon, an export default (called when it is a function, else awaited), an IIFE, and statement lists with top-level await, returning the final expression statement. - Refuse source that does not parse with the parser message and its line and column instead of sending it to the Worker Loader. --- .changeset/code-mode-program-normalize.md | 5 + packages/platform-cloudflare/package.json | 1 + .../src/CloudflareCodeMode.ts | 20 ++- .../src/CodeModeProgram.schema.ts | 7 + .../src/CodeModeProgram.ts | 139 ++++++++++++++++++ .../test/code-mode/code-mode-executor.test.ts | 34 +++++ .../test/code-mode/conformance-worker.ts | 94 ++++++++++++ pnpm-lock.yaml | 3 + 8 files changed, 298 insertions(+), 5 deletions(-) create mode 100644 .changeset/code-mode-program-normalize.md create mode 100644 packages/platform-cloudflare/src/CodeModeProgram.schema.ts create mode 100644 packages/platform-cloudflare/src/CodeModeProgram.ts diff --git a/.changeset/code-mode-program-normalize.md b/.changeset/code-mode-program-normalize.md new file mode 100644 index 000000000..e57bead00 --- /dev/null +++ b/.changeset/code-mode-program-normalize.md @@ -0,0 +1,5 @@ +--- +"@systemfsoftware/agent-platform-cloudflare": patch +--- + +The Dynamic Worker Code Mode executor now accepts a program written as a function expression with a trailing semicolon, inside a markdown code fence, as an `export default`, as an IIFE, or as a statement list with top-level `await`, invoking the normalized entry once; source that does not parse is refused with the parser's message and its line and column before the Worker Loader sees it. diff --git a/packages/platform-cloudflare/package.json b/packages/platform-cloudflare/package.json index 162e14a8d..53ff075c7 100644 --- a/packages/platform-cloudflare/package.json +++ b/packages/platform-cloudflare/package.json @@ -139,6 +139,7 @@ "@systemfsoftware/agent": "workspace:*", "@systemfsoftware/agent-storage-cloudflare": "workspace:*", "@systemfsoftware/agent-storage-sql": "workspace:*", + "acorn": "^8.19.0", "puppeteer-core": "catalog:" }, "devDependencies": { diff --git a/packages/platform-cloudflare/src/CloudflareCodeMode.ts b/packages/platform-cloudflare/src/CloudflareCodeMode.ts index 1f6c11251..c27e9915b 100644 --- a/packages/platform-cloudflare/src/CloudflareCodeMode.ts +++ b/packages/platform-cloudflare/src/CloudflareCodeMode.ts @@ -29,6 +29,7 @@ import * as Option from 'effect/Option' import * as Queue from 'effect/Queue' import * as Schema from 'effect/Schema' +import { normalizeCodeModeProgram } from './CodeModeProgram' import { safeCauseDiagnostic, safeCauseMessage } from './internal/boundary' /** @@ -84,10 +85,10 @@ class CodeModePassHostTarget extends RpcTarget implements CodeModePassHost { /** * The fixed harness loaded as the dynamic worker's main module. The generated - * source becomes `program.mjs` (`export default ();`) — a module, - * never `eval`. The harness installs namespace globals and a bounded console, - * imports the program, invokes it exactly once, and returns one envelope the - * host validates through Effect Schema. + * source becomes `program.js` — a module, never `eval` — holding one default + * export. The harness installs namespace globals and a bounded console, imports + * the program, invokes it exactly once, and returns one envelope the host + * validates through Effect Schema. */ const HARNESS_MODULE = String.raw` import { WorkerEntrypoint } from "cloudflare:workers"; @@ -446,6 +447,15 @@ const makeExecute = ( message: `Source is ${sourceBytes} bytes; the request allows ${request.limits.maxSourceBytes}`, }) } + const program = normalizeCodeModeProgram(request.source) + + if (program._tag === 'Invalid') { + return yield* CodeSourceError.make({ + implementation: dynamicWorkerImplementation, + reason: 'invalid', + message: program.message, + }) + } for (const namespace of request.namespaces) { if (reservedHarnessGlobals.has(namespace.name)) { return yield* CodeExecutorUnsupportedError.make({ @@ -643,7 +653,7 @@ const makeExecute = ( mainModule: 'harness.js', modules: { 'harness.js': HARNESS_MODULE, - 'program.js': `export default (\n${request.source}\n);`, + 'program.js': program.moduleSource, }, env: { CODE_MODE_PASS: encodeHarnessPassConfig({ diff --git a/packages/platform-cloudflare/src/CodeModeProgram.schema.ts b/packages/platform-cloudflare/src/CodeModeProgram.schema.ts new file mode 100644 index 000000000..4cb59c52a --- /dev/null +++ b/packages/platform-cloudflare/src/CodeModeProgram.schema.ts @@ -0,0 +1,7 @@ +import * as Schema from 'effect/Schema' + +const NormalizedProgram = Schema.TaggedStruct('Normalized', { moduleSource: Schema.String }) +const InvalidProgram = Schema.TaggedStruct('Invalid', { message: Schema.String }) +const CodeModeProgramSchema = Schema.Union([NormalizedProgram, InvalidProgram]) + +export type CodeModeProgram = typeof CodeModeProgramSchema.Type diff --git a/packages/platform-cloudflare/src/CodeModeProgram.ts b/packages/platform-cloudflare/src/CodeModeProgram.ts new file mode 100644 index 000000000..6fb09cf87 --- /dev/null +++ b/packages/platform-cloudflare/src/CodeModeProgram.ts @@ -0,0 +1,139 @@ +import { + type ExportDefaultDeclaration, + type Expression, + type ExpressionStatement, + type ModuleDeclaration, + parse, + type Program, + type Statement, +} from 'acorn' + +import type { CodeModeProgram } from './CodeModeProgram.schema' + +type BodyEntry = Statement | ModuleDeclaration + +const PARSE_OPTIONS = { ecmaVersion: 'latest', sourceType: 'module', locations: true } as const +const FENCE_OPEN = /^\s*(?:```|~~~)[^\n]*\n/ +const FENCE_CLOSE = /\n\s*(?:```|~~~)\s*$/ +const TRAILING_POSITION = /\s*\(\d+:\d+\)\s*$/ +const MAX_MESSAGE = 2_000 + +interface SourcePosition { + readonly line: number + readonly column: number +} + +interface AcornSyntaxError extends SyntaxError { + readonly loc: SourcePosition +} + +const isAcornSyntaxError = (cause: unknown): cause is AcornSyntaxError => cause instanceof SyntaxError + +const stripMarkdownFence = (source: string): string => + FENCE_OPEN.test(source) ? source.replace(FENCE_OPEN, '').replace(FENCE_CLOSE, '') : source + +const isFunctionExpression = (expression: Expression): boolean => + expression.type === 'FunctionExpression' || expression.type === 'ArrowFunctionExpression' + +const isFunctionExpressionStatement = (entry: BodyEntry): entry is ExpressionStatement => + entry.type === 'ExpressionStatement' && isFunctionExpression(entry.expression) + +const positionText = (position: SourcePosition): string => `line ${position.line}, column ${position.column + 1}` + +const invalidProgram = (message: string): CodeModeProgram => ({ + _tag: 'Invalid', + message: message.slice(0, MAX_MESSAGE), +}) + +const emptyFailure = (): CodeModeProgram => + invalidProgram( + 'The program is empty; write one JavaScript async function expression, or a statement list whose last expression is the JSON value to return', + ) + +const unparsableFailure = (): CodeModeProgram => invalidProgram('SyntaxError: The program is not valid JavaScript') + +const syntaxFailure = (cause: Cause): CodeModeProgram => { + if (!isAcornSyntaxError(cause)) return unparsableFailure() + + return invalidProgram( + `SyntaxError: ${cause.message.replace(TRAILING_POSITION, '')} at ${positionText(cause.loc)}`, + ) +} + +const withoutTerminator = (text: string): string => text.replace(/;\s*$/, '') + +const statementExpression = (statement: ExpressionStatement, source: string): string => + withoutTerminator(source.slice(statement.start, statement.end)) + +const defaultExportExpression = ( + declaration: ExportDefaultDeclaration, + source: string, +): string => withoutTerminator(source.slice(declaration.start, declaration.end).replace(/^export\s+default\s+/, '')) + +const moduleOf = (expression: string): CodeModeProgram => ({ + _tag: 'Normalized', + moduleSource: `export default (${expression});`, +}) + +const statementListModule = (head: string): CodeModeProgram => ({ + _tag: 'Normalized', + moduleSource: `export default async () => {\n${head}\n};\n`, +}) + +const defaultExportModule = (expression: string): CodeModeProgram => ({ + _tag: 'Normalized', + moduleSource: [ + 'export default async () => {', + ` const program = (${expression});`, + ' return typeof program === "function" ? await program() : await program;', + '};', + '', + ].join('\n'), +}) + +const normalizeDefaultExport = ( + declaration: ExportDefaultDeclaration, + source: string, +): CodeModeProgram => + declaration.declaration.type === 'FunctionDeclaration' + ? moduleOf(defaultExportExpression(declaration, source)) + : defaultExportModule(defaultExportExpression(declaration, source)) + +const normalizeStatements = ( + body: ReadonlyArray, + source: string, +): CodeModeProgram => { + const last = body[body.length - 1] + + return last.type === 'ExpressionStatement' + ? statementListModule( + `${source.slice(0, last.start)}return (${statementExpression(last, source)});`, + ) + : statementListModule(source.slice(0, last.end)) +} + +const functionEntry = (entry: BodyEntry, source: string): CodeModeProgram => + isFunctionExpressionStatement(entry) + ? moduleOf(statementExpression(entry, source)) + : normalizeStatements([entry], source) + +const normalizeSingle = (entry: BodyEntry, source: string): CodeModeProgram => + entry.type === 'ExportDefaultDeclaration' + ? normalizeDefaultExport(entry, source) + : functionEntry(entry, source) + +const normalizeBody = (body: ReadonlyArray, source: string): CodeModeProgram => + body.length === 1 ? normalizeSingle(body[0], source) : normalizeStatements(body, source) + +const normalizeParsed = (program: Program, source: string): CodeModeProgram => + program.body.length === 0 ? emptyFailure() : normalizeBody(program.body, source) + +const parseProgram = (source: string): CodeModeProgram => { + try { + return normalizeParsed(parse(source, PARSE_OPTIONS), source) + } catch (cause) { + return syntaxFailure(cause) + } +} + +export const normalizeCodeModeProgram = (source: string): CodeModeProgram => parseProgram(stripMarkdownFence(source)) diff --git a/packages/platform-cloudflare/test/code-mode/code-mode-executor.test.ts b/packages/platform-cloudflare/test/code-mode/code-mode-executor.test.ts index da7031ef7..5457f720d 100644 --- a/packages/platform-cloudflare/test/code-mode/code-mode-executor.test.ts +++ b/packages/platform-cloudflare/test/code-mode/code-mode-executor.test.ts @@ -1,5 +1,6 @@ import { join } from 'node:path' +import type * as Schema from 'effect/Schema' import { build } from 'esbuild' import { convertV4MiniflareOptions, Miniflare } from 'miniflare' import { afterAll, beforeAll, describe, expect, it } from 'vitest' @@ -80,6 +81,39 @@ describe('DEPLOY-011 Cloudflare Dynamic Worker CodeExecutor', () => { expect(payload.failures).toEqual([]) }, 120_000) + it('normalizes model-authored program shapes before the Worker Loader compiles them', async () => { + const response = await runtime.dispatchFetch('http://placeholder/program-corpus') + + expect(response.ok).toBe(true) + const payload = (await response.json()) as { + readonly outcomes: ReadonlyArray<{ + readonly label: string + readonly tag: string + readonly value: Schema.Json + readonly reason: Schema.Json + readonly message: Schema.Json + }> + } + const byLabel = Object.fromEntries( + payload.outcomes.map((outcome) => [outcome.label, outcome]), + ) + + expect(byLabel).toMatchObject({ + 'function-expression': { tag: 'success', value: { shape: 'function' } }, + 'trailing-semicolon': { tag: 'success', value: { shape: 'semicolon' } }, + 'markdown-fence': { tag: 'success', value: { shape: 'fence' } }, + 'top-level-await': { tag: 'success', value: 42 }, + 'iife': { tag: 'success', value: { shape: 'iife' } }, + 'export-default-function': { tag: 'success', value: { shape: 'export' } }, + 'export-default-value': { tag: 'success', value: 7 }, + 'export-default-declaration': { tag: 'success', value: { shape: 'declaration' } }, + 'function-declaration-called': { tag: 'success', value: { shape: 'called' } }, + 'statement-list-with-tool': { tag: 'success', value: { first: 'ledger' } }, + 'invalid-syntax': { tag: 'CodeSourceError', reason: 'invalid' }, + }) + expect(byLabel['invalid-syntax'].message).toEqual(expect.stringMatching(/line 1, column \d+/)) + }, 120_000) + // Regression evidence: // https://github.com/reve-ai/kommunikasie/actions/runs/32474947060 // https://github.com/reve-ai/kommunikasie/actions/runs/32483559567 diff --git a/packages/platform-cloudflare/test/code-mode/conformance-worker.ts b/packages/platform-cloudflare/test/code-mode/conformance-worker.ts index 8e1c7cd81..854894712 100644 --- a/packages/platform-cloudflare/test/code-mode/conformance-worker.ts +++ b/packages/platform-cloudflare/test/code-mode/conformance-worker.ts @@ -82,6 +82,95 @@ const runOutcome = ( ): Effect.Effect<{ readonly tag: string; readonly detail: unknown }> => executeOutcome(req, host).pipe(Effect.provide(layer)) +interface ProgramCase { + readonly label: string + readonly source: string + readonly callsHost: boolean +} + +const programCases: ReadonlyArray = [ + { label: 'function-expression', source: `async () => ({ shape: 'function' })`, callsHost: false }, + { + label: 'trailing-semicolon', + source: `async () => ({ shape: 'semicolon' });`, + callsHost: false, + }, + { + label: 'markdown-fence', + source: '```js\nasync () => ({ shape: "fence" });\n```', + callsHost: false, + }, + { + label: 'top-level-await', + source: `const doubled = await Promise.resolve(21);\ndoubled * 2`, + callsHost: false, + }, + { label: 'iife', source: `(async () => ({ shape: 'iife' }))()`, callsHost: false }, + { + label: 'export-default-function', + source: `export default async () => ({ shape: 'export' })`, + callsHost: false, + }, + { label: 'export-default-value', source: `export default 7;`, callsHost: false }, + { + label: 'export-default-declaration', + source: `export default async function () { return { shape: 'declaration' }; }`, + callsHost: false, + }, + { + label: 'function-declaration-called', + source: `async function main() { return { shape: 'called' }; }\nmain()`, + callsHost: false, + }, + { + label: 'statement-list-with-tool', + source: `const first = await warehouse.query({ sql: 'select 1' });\n({ first })`, + callsHost: true, + }, + { label: 'invalid-syntax', source: `async () => {`, callsHost: false }, +] + +interface ProgramOutcome { + readonly label: string + readonly tag: string + readonly value: unknown + readonly reason: unknown + readonly message: unknown +} + +const outcomeField = (detail: unknown, field: string): unknown => + Predicate.isObject(detail) && field in detail ? detail[field] : null + +const runProgramCorpus = (env: WorkerEnv): Effect.Effect> => + Effect.gen(function*() { + const layer = executorLayerFor(env) + const namespace = CodeExecutionNamespace.make({ name: 'warehouse', methods: ['query'] }) + const host: CodeExecutionHost['Service'] = { + call: () => Effect.succeed(CodeHostCallSuccess.make({ value: 'ledger' })), + } + const outcomes: Array = [] + + for (const programCase of programCases) { + const outcome = yield* runOutcome( + request(programCase.source, { + namespaces: programCase.callsHost ? [namespace] : [], + }), + layer, + programCase.callsHost ? host : unusedHost, + ) + + outcomes.push({ + label: programCase.label, + tag: outcome.tag, + value: outcomeField(outcome.detail, 'value'), + reason: outcomeField(outcome.detail, 'reason'), + message: outcomeField(outcome.detail, 'message'), + }) + } + + return outcomes + }) + const runAllChecks = (env: WorkerEnv): Effect.Effect> => Effect.gen(function*() { const layer = executorLayerFor(env) @@ -251,6 +340,11 @@ export default { return Response.json({ outcomes }) } + if (new URL(request.url).pathname === '/program-corpus') { + const outcomes = await Effect.runPromise(runProgramCorpus(env)) + + return Response.json({ outcomes }) + } const failures = await Effect.runPromise(runAllChecks(env)) return Response.json({ failures }) diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index bbbdb0e91..6301c1858 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -1003,6 +1003,9 @@ importers: '@systemfsoftware/agent-storage-sql': specifier: workspace:* version: link:../storage-sql + acorn: + specifier: ^8.19.0 + version: 8.19.0 puppeteer-core: specifier: 'catalog:' version: 25.18.1(yauzl@3.4.0) From f0b52c80733e63817ade3b656485283c6b962004 Mon Sep 17 00:00:00 2001 From: systemfsoftware-bot Date: Tue, 1 Dec 2026 20:50:43 +0000 Subject: [PATCH 02/11] fix(platform-cloudflare): adopt Cloudflare Code Mode normalization at the boundary - Strip TypeScript annotations with sucrase, then normalize the program with `normalizeCode` from `@cloudflare/codemode` before the Worker Loader module is built, instead of the hand-rolled parser. - Validate the normalized module with acorn; a program that still does not parse is refused with a `CodeSourceError` carrying the parser message, line and column, the offending line, and a valid example. - Keep the sandbox, its bindings, limits, and the invoke-once contract unchanged; extend the corpus with TypeScript-annotated shapes. --- .changeset/code-mode-program-normalize.md | 2 +- packages/platform-cloudflare/package.json | 4 +- .../src/CodeModeProgram.ts | 150 ++++++------------ .../test/code-mode/code-mode-executor.test.ts | 10 +- .../test/code-mode/conformance-worker.ts | 10 ++ pnpm-lock.yaml | 62 ++++++++ 6 files changed, 130 insertions(+), 108 deletions(-) diff --git a/.changeset/code-mode-program-normalize.md b/.changeset/code-mode-program-normalize.md index e57bead00..08a6263c6 100644 --- a/.changeset/code-mode-program-normalize.md +++ b/.changeset/code-mode-program-normalize.md @@ -2,4 +2,4 @@ "@systemfsoftware/agent-platform-cloudflare": patch --- -The Dynamic Worker Code Mode executor now accepts a program written as a function expression with a trailing semicolon, inside a markdown code fence, as an `export default`, as an IIFE, or as a statement list with top-level `await`, invoking the normalized entry once; source that does not parse is refused with the parser's message and its line and column before the Worker Loader sees it. +The Dynamic Worker Code Mode executor now normalizes a program with `normalizeCode` from `@cloudflare/codemode` after stripping TypeScript annotations with `sucrase`, so a function expression, a trailing semicolon, a markdown code fence, `export default`, an IIFE, a statement list with top-level `await`, and a TypeScript-annotated program all run; a program that still does not parse is refused with a `CodeSourceError` carrying the parser message, its line and column, the offending line, and a valid example, instead of reaching the Worker Loader. diff --git a/packages/platform-cloudflare/package.json b/packages/platform-cloudflare/package.json index 53ff075c7..ce7d3e38b 100644 --- a/packages/platform-cloudflare/package.json +++ b/packages/platform-cloudflare/package.json @@ -134,13 +134,15 @@ "check:pack": "pnpm pack --pack-destination .pack && attw .pack/*.tgz --profile esm-only; s=$?; rm -rf .pack; exit $s" }, "dependencies": { + "@cloudflare/codemode": "0.5.6", "@effect/platform-browser": "catalog:", "@effect/sql-sqlite-do": "catalog:", "@systemfsoftware/agent": "workspace:*", "@systemfsoftware/agent-storage-cloudflare": "workspace:*", "@systemfsoftware/agent-storage-sql": "workspace:*", "acorn": "^8.19.0", - "puppeteer-core": "catalog:" + "puppeteer-core": "catalog:", + "sucrase": "^3.35.1" }, "devDependencies": { "@arethetypeswrong/cli": "catalog:", diff --git a/packages/platform-cloudflare/src/CodeModeProgram.ts b/packages/platform-cloudflare/src/CodeModeProgram.ts index 6fb09cf87..a94015252 100644 --- a/packages/platform-cloudflare/src/CodeModeProgram.ts +++ b/packages/platform-cloudflare/src/CodeModeProgram.ts @@ -1,139 +1,79 @@ -import { - type ExportDefaultDeclaration, - type Expression, - type ExpressionStatement, - type ModuleDeclaration, - parse, - type Program, - type Statement, -} from 'acorn' +import { normalizeCode } from '@cloudflare/codemode' +import { parse } from 'acorn' +import { transform } from 'sucrase' import type { CodeModeProgram } from './CodeModeProgram.schema' -type BodyEntry = Statement | ModuleDeclaration - const PARSE_OPTIONS = { ecmaVersion: 'latest', sourceType: 'module', locations: true } as const -const FENCE_OPEN = /^\s*(?:```|~~~)[^\n]*\n/ -const FENCE_CLOSE = /\n\s*(?:```|~~~)\s*$/ const TRAILING_POSITION = /\s*\(\d+:\d+\)\s*$/ const MAX_MESSAGE = 2_000 +const MAX_OFFENDING_LINE = 300 +const VALID_EXAMPLE = 'async () => ({ ok: true })' interface SourcePosition { readonly line: number readonly column: number } -interface AcornSyntaxError extends SyntaxError { +interface PositionedSyntaxError extends SyntaxError { readonly loc: SourcePosition } -const isAcornSyntaxError = (cause: unknown): cause is AcornSyntaxError => cause instanceof SyntaxError - -const stripMarkdownFence = (source: string): string => - FENCE_OPEN.test(source) ? source.replace(FENCE_OPEN, '').replace(FENCE_CLOSE, '') : source - -const isFunctionExpression = (expression: Expression): boolean => - expression.type === 'FunctionExpression' || expression.type === 'ArrowFunctionExpression' - -const isFunctionExpressionStatement = (entry: BodyEntry): entry is ExpressionStatement => - entry.type === 'ExpressionStatement' && isFunctionExpression(entry.expression) - -const positionText = (position: SourcePosition): string => `line ${position.line}, column ${position.column + 1}` +const isPositionedSyntaxError = (cause: unknown): cause is PositionedSyntaxError => cause instanceof SyntaxError const invalidProgram = (message: string): CodeModeProgram => ({ _tag: 'Invalid', message: message.slice(0, MAX_MESSAGE), }) -const emptyFailure = (): CodeModeProgram => - invalidProgram( - 'The program is empty; write one JavaScript async function expression, or a statement list whose last expression is the JSON value to return', - ) - -const unparsableFailure = (): CodeModeProgram => invalidProgram('SyntaxError: The program is not valid JavaScript') +const offendingLine = (text: string, line: number): string => + (text.split('\n')[line - 1] ?? '').trim().slice(0, MAX_OFFENDING_LINE) -const syntaxFailure = (cause: Cause): CodeModeProgram => { - if (!isAcornSyntaxError(cause)) return unparsableFailure() - - return invalidProgram( - `SyntaxError: ${cause.message.replace(TRAILING_POSITION, '')} at ${positionText(cause.loc)}`, +const positionedFailure = ( + cause: PositionedSyntaxError, + text: string, + columnOffset: number, +): CodeModeProgram => + invalidProgram( + `SyntaxError: ${cause.message.replace(TRAILING_POSITION, '')} (line ${cause.loc.line}, column ${ + cause.loc.column + columnOffset + })\n ${offendingLine(text, cause.loc.line)}\nExample: ${VALID_EXAMPLE}`, ) -} - -const withoutTerminator = (text: string): string => text.replace(/;\s*$/, '') - -const statementExpression = (statement: ExpressionStatement, source: string): string => - withoutTerminator(source.slice(statement.start, statement.end)) - -const defaultExportExpression = ( - declaration: ExportDefaultDeclaration, - source: string, -): string => withoutTerminator(source.slice(declaration.start, declaration.end).replace(/^export\s+default\s+/, '')) -const moduleOf = (expression: string): CodeModeProgram => ({ - _tag: 'Normalized', - moduleSource: `export default (${expression});`, -}) - -const statementListModule = (head: string): CodeModeProgram => ({ - _tag: 'Normalized', - moduleSource: `export default async () => {\n${head}\n};\n`, -}) - -const defaultExportModule = (expression: string): CodeModeProgram => ({ - _tag: 'Normalized', - moduleSource: [ - 'export default async () => {', - ` const program = (${expression});`, - ' return typeof program === "function" ? await program() : await program;', - '};', - '', - ].join('\n'), -}) - -const normalizeDefaultExport = ( - declaration: ExportDefaultDeclaration, - source: string, +// Acorn reports a zero-based column; sucrase already reports a one-based one. +const syntaxFailure = ( + cause: Cause, + text: string, + columnOffset: number, ): CodeModeProgram => - declaration.declaration.type === 'FunctionDeclaration' - ? moduleOf(defaultExportExpression(declaration, source)) - : defaultExportModule(defaultExportExpression(declaration, source)) - -const normalizeStatements = ( - body: ReadonlyArray, - source: string, -): CodeModeProgram => { - const last = body[body.length - 1] - - return last.type === 'ExpressionStatement' - ? statementListModule( - `${source.slice(0, last.start)}return (${statementExpression(last, source)});`, - ) - : statementListModule(source.slice(0, last.end)) -} - -const functionEntry = (entry: BodyEntry, source: string): CodeModeProgram => - isFunctionExpressionStatement(entry) - ? moduleOf(statementExpression(entry, source)) - : normalizeStatements([entry], source) + isPositionedSyntaxError(cause) + ? positionedFailure(cause, text, columnOffset) + : invalidProgram(`SyntaxError: the program could not be parsed\nExample: ${VALID_EXAMPLE}`) -const normalizeSingle = (entry: BodyEntry, source: string): CodeModeProgram => - entry.type === 'ExportDefaultDeclaration' - ? normalizeDefaultExport(entry, source) - : functionEntry(entry, source) +const stripTypeScript = (source: string): string => transform(source, { transforms: ['typescript'] }).code -const normalizeBody = (body: ReadonlyArray, source: string): CodeModeProgram => - body.length === 1 ? normalizeSingle(body[0], source) : normalizeStatements(body, source) +const normalizedProgram = (source: string): string | CodeModeProgram => { + try { + return normalizeCode(stripTypeScript(source)) + } catch (cause) { + return syntaxFailure(cause, source, 0) + } +} -const normalizeParsed = (program: Program, source: string): CodeModeProgram => - program.body.length === 0 ? emptyFailure() : normalizeBody(program.body, source) +const normalizedModule = (normalized: string): CodeModeProgram => { + const moduleSource = `export default ${normalized}` -const parseProgram = (source: string): CodeModeProgram => { try { - return normalizeParsed(parse(source, PARSE_OPTIONS), source) + parse(moduleSource, PARSE_OPTIONS) + + return { _tag: 'Normalized', moduleSource } } catch (cause) { - return syntaxFailure(cause) + return syntaxFailure(cause, moduleSource, 1) } } -export const normalizeCodeModeProgram = (source: string): CodeModeProgram => parseProgram(stripMarkdownFence(source)) +export const normalizeCodeModeProgram = (source: string): CodeModeProgram => { + const result = normalizedProgram(source) + + return typeof result === 'string' ? normalizedModule(result) : result +} diff --git a/packages/platform-cloudflare/test/code-mode/code-mode-executor.test.ts b/packages/platform-cloudflare/test/code-mode/code-mode-executor.test.ts index 5457f720d..05be58d9f 100644 --- a/packages/platform-cloudflare/test/code-mode/code-mode-executor.test.ts +++ b/packages/platform-cloudflare/test/code-mode/code-mode-executor.test.ts @@ -108,10 +108,18 @@ describe('DEPLOY-011 Cloudflare Dynamic Worker CodeExecutor', () => { 'export-default-value': { tag: 'success', value: 7 }, 'export-default-declaration': { tag: 'success', value: { shape: 'declaration' } }, 'function-declaration-called': { tag: 'success', value: { shape: 'called' } }, + 'typescript-annotations': { tag: 'success', value: 'a-b' }, + 'typescript-arrow': { tag: 'success', value: { shape: 'ts' } }, 'statement-list-with-tool': { tag: 'success', value: { first: 'ledger' } }, 'invalid-syntax': { tag: 'CodeSourceError', reason: 'invalid' }, }) - expect(byLabel['invalid-syntax'].message).toEqual(expect.stringMatching(/line 1, column \d+/)) + expect(byLabel['invalid-syntax'].message).toEqual(expect.stringMatching(/line 1, column 14/)) + expect(byLabel['invalid-syntax'].message).toEqual( + expect.stringContaining('async () => {'), + ) + expect(byLabel['invalid-syntax'].message).toEqual( + expect.stringContaining('Example: async () => ({ ok: true })'), + ) }, 120_000) // Regression evidence: diff --git a/packages/platform-cloudflare/test/code-mode/conformance-worker.ts b/packages/platform-cloudflare/test/code-mode/conformance-worker.ts index 854894712..5235dc806 100644 --- a/packages/platform-cloudflare/test/code-mode/conformance-worker.ts +++ b/packages/platform-cloudflare/test/code-mode/conformance-worker.ts @@ -122,6 +122,16 @@ const programCases: ReadonlyArray = [ source: `async function main() { return { shape: 'called' }; }\nmain()`, callsHost: false, }, + { + label: 'typescript-annotations', + source: `const parts: string[] = await Promise.resolve(['a', 'b']);\nparts.join('-')`, + callsHost: false, + }, + { + label: 'typescript-arrow', + source: `async (): Promise<{ shape: 'ts' }> => ({ shape: 'ts' })`, + callsHost: false, + }, { label: 'statement-list-with-tool', source: `const first = await warehouse.query({ sql: 'select 1' });\n({ first })`, diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 6301c1858..c2fcdbfa9 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -988,6 +988,9 @@ importers: packages/platform-cloudflare: dependencies: + '@cloudflare/codemode': + specifier: 0.5.6 + version: 0.5.6(zod@4.6.7) '@effect/platform-browser': specifier: 'catalog:' version: 4.1.5(effect@4.1.5) @@ -1009,6 +1012,9 @@ importers: puppeteer-core: specifier: 'catalog:' version: 25.18.1(yauzl@3.4.0) + sucrase: + specifier: ^3.35.1 + version: 3.35.1 devDependencies: '@arethetypeswrong/cli': specifier: 'catalog:' @@ -2128,6 +2134,23 @@ packages: resolution: {integrity: sha512-tEj8X2No2A1c9NDnZECxiiJ8TP3vmFlN9tLlLeSaMqVW4tUmVG2R4qpv/eP4zymWxnymYLkLcIYVV0VcWj3RCQ==} engines: {node: '>= 20.12.0'} + '@cloudflare/codemode@0.5.6': + resolution: {integrity: sha512-86CoZvDrXWpcmieDoFqHvt1NWt3F75LnsxlUteIzftbU2GZCoLn3yB4n7Jd+7OcMfsA4lNxDBrNcOYcBuINv7A==} + peerDependencies: + '@modelcontextprotocol/sdk': ^1.25.0 + '@tanstack/ai': '>=0.8.0 <2.0.0' + ai: ^6.0.0 || ^7.0.0 + zod: ^4.0.0 + peerDependenciesMeta: + '@modelcontextprotocol/sdk': + optional: true + '@tanstack/ai': + optional: true + ai: + optional: true + zod: + optional: true + '@cloudflare/containers@0.3.7': resolution: {integrity: sha512-DM9dm3FnIBSyiSJ1FLavKwl/lk3oAmTaynCzZQ9pZR0ncRPquSxkxd8Nu2MFILxmDDsPkxKsSNEh9mHHMty4Fw==} @@ -6590,6 +6613,10 @@ packages: resolution: {integrity: sha512-cgnQ88TRrWcC7pVq46RzJVRMktu3W2RcbnoidnfBsl1bmDCBwJS/udcIZpKoCrbAYYaCqsz1yZCVIgbIaU3ddQ==} engines: {node: '>=22.12.0'} + commander@4.1.1: + resolution: {integrity: sha512-NOKm8xhkzAjzFx8B2v5OAHT+u5pRQc2UCa2Vq9jYL/31o2wi9mxBA7LIFs3sV5VSC49z6pEhfbMULvShKj26WA==} + engines: {node: '>= 6'} + commander@7.2.0: resolution: {integrity: sha512-QrWXB+ZQSVPmIWIhtEO9H+gwHaMGYiF5ChvoJ+K9ZGHG/sVsa6yiesAD1GC/x46sET00Xlwo1u49RVVVzvcSkw==} engines: {node: '>= 10'} @@ -8598,6 +8625,10 @@ packages: resolution: {integrity: sha512-uB80kBFb/tfd68bVleG9T5GGsGPjJrLAUpR5PZIrhBnIaRTQRjqdJSsIKkOP6OAIFbj7GOrcudc5pNjZ+geV2g==} engines: {node: '>=6'} + pirates@4.0.7: + resolution: {integrity: sha512-TfySrs/5nm8fQJDcBDuUng3VOUKsd7S+zqvbOTiGXHfxX4wK31ard+hoNuvkicM/2YFzlpDgABOevKSsB4G/FA==} + engines: {node: '>= 6'} + platform@1.3.6: resolution: {integrity: sha512-fnWVljUchTro6RiCFvCXBbNhJc2NijN7oIQxbwsyL0buWJPG85v81ehlHI9fXrJsMNgTofEoWIQeClKpgxFLrg==} @@ -9058,6 +9089,11 @@ packages: stylis@4.4.0: resolution: {integrity: sha512-5Z9ZpRzfuH6l/UAvCPAPUo3665Nk2wLaZU3x+TLHKVzIz33+sbJqbtrYoC3KD4/uVOr2Zp+L0LySezP9OHV9yA==} + sucrase@3.35.1: + resolution: {integrity: sha512-DhuTmvZWux4H1UOnWMB3sk0sbaCVOoQZjv8u1rDoTV0HTdGem9hkAZtl4JZy8P2z4Bg0nT+YMeOFyVr4zcG5Tw==} + engines: {node: '>=16 || 14 >=14.17'} + hasBin: true + supports-color@10.2.2: resolution: {integrity: sha512-SS+jx45GF1QjgEXQx4NJZV9ImqmO2NPz5FNsIHrsDjh2YsHnawpan7SNQ1o8NuhrbHZy9AZhIoCUiCeaW/C80g==} engines: {node: '>=18'} @@ -9158,6 +9194,9 @@ packages: resolution: {integrity: sha512-JfJeIHke7y2egdGGgRAvpCwYFUsHlM2gPcrVOxFkznt/4uzQ7HFmvE63iFHVLBJNDuyDOQgijDK/tXH/f6Msjg==} engines: {node: '>=6.10'} + ts-interface-checker@0.1.13: + resolution: {integrity: sha512-Y/arvbn+rrz3JCKl9C4kVNfTfSm2/mEp5FSz5EsZSANGPSlQrpRI5M4PKF+mJnE52jOO90PnPSc3Ur3bTQw0gA==} + tsdown@0.23.7: resolution: {integrity: sha512-w9nmWyEimfqQ7/HpVeKTldAeBvWGXiaWyNP7xaxSrr0GhKxsngEyTWqk1nOruRqvqRSkdpMMkpV2BcoWfLB4Uw==} engines: {node: ^22.18.0 || ^24.11.0 || >=26.0.0} @@ -10378,6 +10417,13 @@ snapshots: fast-wrap-ansi: 0.2.2 sisteransi: 2.0.0 + '@cloudflare/codemode@0.5.6(zod@4.6.7)': + dependencies: + '@types/json-schema': 7.0.15 + acorn: 8.19.0 + optionalDependencies: + zod: 4.6.7 + '@cloudflare/containers@0.3.7': {} '@cloudflare/kv-asset-handler@0.5.0': {} @@ -14168,6 +14214,8 @@ snapshots: commander@15.1.0: {} + commander@4.1.1: {} + commander@7.2.0: {} commander@8.3.0: {} @@ -16454,6 +16502,8 @@ snapshots: pify@4.0.1: {} + pirates@4.0.7: {} + platform@1.3.6: {} points-on-curve@0.2.0: {} @@ -17168,6 +17218,16 @@ snapshots: stylis@4.4.0: {} + sucrase@3.35.1: + dependencies: + '@jridgewell/gen-mapping': 0.3.13 + commander: 4.1.1 + lines-and-columns: 1.2.4 + mz: 2.7.0 + pirates: 4.0.7 + tinyglobby: 0.2.17 + ts-interface-checker: 0.1.13 + supports-color@10.2.2: {} supports-color@7.2.0: @@ -17256,6 +17316,8 @@ snapshots: ts-dedent@2.3.0: {} + ts-interface-checker@0.1.13: {} + tsdown@0.23.7(@arethetypeswrong/core@0.18.5)(@vue/language-core@3.3.14)(tsrs@0.18.0-ts7.1.0-dev.20260929)(typescript@7.0.2): dependencies: cac: 7.1.1 From 03164fdcc7186d325c70280ccd6faaa18f95cf73 Mon Sep 17 00:00:00 2001 From: systemfsoftware-bot Date: Tue, 1 Dec 2026 21:10:07 +0000 Subject: [PATCH 03/11] fix(agent): stop charging Tool Calls for Code Mode boundary refusals - Mark a Code Mode failure the executor refused before the program started (`CodeSourceError`) as a boundary refusal on the failure envelope. - Return the charged Tool Call through a new `Budget.releaseToolCalls` / `RunBudgetHook.releaseToolCalls` seam, and exclude refusals from the engine's declared-call accounting and the durable policy usage, so a consumer never has to raise a budget for refused programs. - Fold refusals into their own consecutive counter: three consecutive boundary refusals stop the Run with an `AgentPolicyError` naming the Code Mode boundary-refusal limit; ordinary tool failures keep their existing repeated-failure policy. - Extend the engine suite with the refund, the stop, and a later valid program running after a refusal. --- .changeset/code-mode-program-normalize.md | 3 +- .../effect-agent/src/capabilities/Budget.ts | 43 +++- .../effect-agent/src/capabilities/CodeMode.ts | 5 + .../effect-agent/src/capabilities/RunHooks.ts | 1 + .../core/internal/code-mode-refusal.schema.ts | 8 + .../src/durable/DurableAgentRuntime.ts | 9 +- .../src/durable/RunContinuation.ts | 8 + .../effect-agent/src/durable/RunJournal.ts | 8 +- .../src/durable/internal/journal-metadata.ts | 10 +- .../effect-agent/src/engine/RunOptions.ts | 3 + .../src/engine/internal/agent-runtime.ts | 97 ++++++--- .../test/engine/agent-runtime.test.ts | 198 ++++++++++++++++++ 12 files changed, 352 insertions(+), 41 deletions(-) create mode 100644 packages/effect-agent/src/core/internal/code-mode-refusal.schema.ts diff --git a/.changeset/code-mode-program-normalize.md b/.changeset/code-mode-program-normalize.md index 08a6263c6..3f81e615f 100644 --- a/.changeset/code-mode-program-normalize.md +++ b/.changeset/code-mode-program-normalize.md @@ -1,5 +1,6 @@ --- +"@systemfsoftware/agent": patch "@systemfsoftware/agent-platform-cloudflare": patch --- -The Dynamic Worker Code Mode executor now normalizes a program with `normalizeCode` from `@cloudflare/codemode` after stripping TypeScript annotations with `sucrase`, so a function expression, a trailing semicolon, a markdown code fence, `export default`, an IIFE, a statement list with top-level `await`, and a TypeScript-annotated program all run; a program that still does not parse is refused with a `CodeSourceError` carrying the parser message, its line and column, the offending line, and a valid example, instead of reaching the Worker Loader. +The Dynamic Worker Code Mode executor now normalizes a model program written with TypeScript annotations, a markdown code fence, a bare or semicolon-terminated function expression, an `export default`, an IIFE, or a statement list with top-level `await`, and refuses a program that still does not parse with a `CodeSourceError` carrying the parser message, its line and column, the offending line, and a valid example. A program refused at that boundary never started, so its Tool Call no longer consumes the Run's Tool-call budget; three consecutive boundary refusals end the Run with an `AgentPolicyError` naming the Code Mode boundary-refusal limit. diff --git a/packages/effect-agent/src/capabilities/Budget.ts b/packages/effect-agent/src/capabilities/Budget.ts index 70b388ee1..f0fb2f8e4 100644 --- a/packages/effect-agent/src/capabilities/Budget.ts +++ b/packages/effect-agent/src/capabilities/Budget.ts @@ -100,6 +100,7 @@ export interface UsageBudgetNode { */ readonly retire: Effect.Effect readonly consume: (delta: UsageDelta) => Effect.Effect + readonly releaseToolCalls: (count: number) => Effect.Effect readonly snapshot: Effect.Effect /** * Guard stalled model/tool work with the earliest configured ancestor deadline. @@ -281,12 +282,12 @@ const makeNode = ( ): UsageBudgetNode => { const hierarchy = [...ancestors, key] - const retiredDefect = () => - Effect.die( - RetiredBudgetHandle.make({ - message: `Usage budget handle ${config.level}:${config.id} was used after retirement`, - }), - ) + const retiredHandle = () => + RetiredBudgetHandle.make({ + message: `Usage budget handle ${config.level}:${config.id} was used after retirement`, + }) + + const retiredDefect = () => Effect.die(retiredHandle()) const liveHierarchy = (state: BudgetLedger): ReadonlyArray | undefined => { const current = state.nodes.get(key) @@ -506,6 +507,36 @@ const makeNode = ( ), ), snapshot, + releaseToolCalls: (count) => + Ref.modify(ledger, (state): readonly [UsageTotals | undefined, BudgetLedger] => { + if (liveHierarchy(state) === undefined) return [undefined, state] + const updates = new Map() + + for (const ancestorKey of hierarchy) { + const node = state.nodes.get(ancestorKey) + + if (node === undefined) return [undefined, state] + updates.set(ancestorKey, { + ...node, + totals: UsageTotals.make({ + ...node.totals, + toolCalls: Math.max(0, node.totals.toolCalls - count), + }), + }) + } + const nextNodes = new Map(state.nodes) + + for (const [updatedKey, updatedNode] of updates) nextNodes.set(updatedKey, updatedNode) + const value = updates.get(key)?.totals + + return [value, { nodes: nextNodes }] + }).pipe( + Effect.filterOrFail( + (value): value is UsageTotals => value !== undefined, + () => retiredHandle(), + ), + Effect.orDie, + ), guard, } } diff --git a/packages/effect-agent/src/capabilities/CodeMode.ts b/packages/effect-agent/src/capabilities/CodeMode.ts index 2d31ef86e..6de0680af 100644 --- a/packages/effect-agent/src/capabilities/CodeMode.ts +++ b/packages/effect-agent/src/capabilities/CodeMode.ts @@ -102,6 +102,7 @@ export class CodeModeFailure extends Schema.TaggedError()('Code /** Invocation-ordered evidence that fits the egress budget. This is not a replay plan. */ calls: Schema.optionalKey(Schema.Array(ProgrammaticCallRecord)), omittedCalls: Schema.optionalKey(Schema.Natural), + boundaryRefusal: Schema.optionalKey(Schema.Literal(true)), }) {} /** A selective documentation request is invalid or cannot fit its declared byte budget. */ @@ -928,6 +929,7 @@ const make = < message, logs: budgetedLogs(logs, remaining), ...(includeThrown ? { thrown: candidateThrown } : {}), + ...(error._tag === 'CodeSourceError' ? { boundaryRefusal: true } : {}), }) }) @@ -1012,6 +1014,9 @@ const make = < message: failure.message, logs: failure.logs, ...(failure.thrown === undefined ? {} : { thrown: failure.thrown }), + ...(failure.boundaryRefusal === undefined + ? {} + : { boundaryRefusal: failure.boundaryRefusal }), calls, omittedCalls: 0, }) diff --git a/packages/effect-agent/src/capabilities/RunHooks.ts b/packages/effect-agent/src/capabilities/RunHooks.ts index 90e805b24..d0f5834dc 100644 --- a/packages/effect-agent/src/capabilities/RunHooks.ts +++ b/packages/effect-agent/src/capabilities/RunHooks.ts @@ -50,6 +50,7 @@ export const toRunBudgetHook = ( Effect.flatMap((usage) => budget.consume(usage)), Effect.asVoid, ), + releaseToolCalls: (count) => budget.releaseToolCalls(count).pipe(Effect.asVoid), }) export type ThreadAdapterError = diff --git a/packages/effect-agent/src/core/internal/code-mode-refusal.schema.ts b/packages/effect-agent/src/core/internal/code-mode-refusal.schema.ts new file mode 100644 index 000000000..fb076812d --- /dev/null +++ b/packages/effect-agent/src/core/internal/code-mode-refusal.schema.ts @@ -0,0 +1,8 @@ +import * as Schema from 'effect/Schema' + +const CodeModeBoundaryRefusalEnvelope = Schema.TaggedStruct('CodeModeFailure', { + boundaryRefusal: Schema.Literal(true), +}) + +/** @internal */ +export const isCodeModeBoundaryRefusal = Schema.is(CodeModeBoundaryRefusalEnvelope) diff --git a/packages/effect-agent/src/durable/DurableAgentRuntime.ts b/packages/effect-agent/src/durable/DurableAgentRuntime.ts index 3a64b8f05..fd32ce8d1 100644 --- a/packages/effect-agent/src/durable/DurableAgentRuntime.ts +++ b/packages/effect-agent/src/durable/DurableAgentRuntime.ts @@ -48,6 +48,7 @@ import { type TurnId, } from '../core/Identifiers' import { IdGenerator } from '../core/IdGenerator' +import { isCodeModeBoundaryRefusal } from '../core/internal/code-mode-refusal.schema' import { copyJson } from '../core/internal/json' import { utf8ByteLength } from '../core/internal/utf8' import { Receipt } from '../core/Receipt' @@ -4084,7 +4085,13 @@ const make = Effect.fnUntraced(function*(bindings: ReadonlyArray + !call.providerExecuted && + settledById.get(`tool-settled:${ownerRunId}:${payload.turn}:${call.id}`)?.boundaryRefusal === + true + ).length + + policyUsage.toolCalls += calls.length - refusals if (payload.toolExposure !== undefined) toolSelection = payload.toolExposure.selection if (incompleteToolTurns.has(record.recordId)) return for (const call of calls) { diff --git a/packages/effect-agent/src/durable/internal/journal-metadata.ts b/packages/effect-agent/src/durable/internal/journal-metadata.ts index ed66089da..2486e1d58 100644 --- a/packages/effect-agent/src/durable/internal/journal-metadata.ts +++ b/packages/effect-agent/src/durable/internal/journal-metadata.ts @@ -1,6 +1,7 @@ import * as Brand from 'effect/Brand' import { type RunId, type ToolCallId } from '../../core/Identifiers' +import { isCodeModeBoundaryRefusal } from '../../core/internal/code-mode-refusal.schema' import { type CanonicalRecordEnvelope, type CompactionCreated, @@ -38,7 +39,9 @@ export interface JournalMetadata { readonly settledToolCallRecordIds: ReadonlySet readonly settledById: ReadonlyMap< string, - Pick + Pick & { + readonly boundaryRefusal: boolean + } > readonly compactions: ReadonlyArray<{ readonly payload: CompactionCreated @@ -81,7 +84,9 @@ export const makeJournalMetadata = (ownerRunId: RunId | undefined) => { const settledById = new Map< string, - Pick + Pick & { + readonly boundaryRefusal: boolean + } >() const compactions: Array<{ readonly payload: CompactionCreated; readonly sequence: number }> = [] @@ -139,6 +144,7 @@ export const makeJournalMetadata = (ownerRunId: RunId | undefined) => { if (payload.runId === ownerRunId) { settledById.set(envelope.record.recordId, { isFailure: payload.isFailure, + boundaryRefusal: isCodeModeBoundaryRefusal(payload.result), ...(!('toolSelection' in payload) || payload.toolSelection === undefined ? {} : { toolSelection: payload.toolSelection }), diff --git a/packages/effect-agent/src/engine/RunOptions.ts b/packages/effect-agent/src/engine/RunOptions.ts index aec3bd98c..895f59f0b 100644 --- a/packages/effect-agent/src/engine/RunOptions.ts +++ b/packages/effect-agent/src/engine/RunOptions.ts @@ -396,6 +396,9 @@ export interface RunBudgetHook { effect: Effect.Effect, ) => Effect.Effect readonly consume: (delta: RunUsageDelta) => Effect.Effect + readonly releaseToolCalls?: ( + count: number, + ) => Effect.Effect } /** diff --git a/packages/effect-agent/src/engine/internal/agent-runtime.ts b/packages/effect-agent/src/engine/internal/agent-runtime.ts index b6f03e332..97557a831 100644 --- a/packages/effect-agent/src/engine/internal/agent-runtime.ts +++ b/packages/effect-agent/src/engine/internal/agent-runtime.ts @@ -74,6 +74,7 @@ import { } from '../../core/Identifiers' import { IdGenerator } from '../../core/IdGenerator' import { nativeUpdateId } from '../../core/internal/agent-updates' +import { isCodeModeBoundaryRefusal } from '../../core/internal/code-mode-refusal.schema' import { completionDispositionCheck, CompletionMetadata, completionMetadataCheck } from '../../core/internal/completion' import { copyJson } from '../../core/internal/json' import { utf8ByteLength } from '../../core/internal/utf8' @@ -563,6 +564,7 @@ interface RunContext { readonly childUsage: Map> readonly liveChildren: Set consecutiveToolFailures: number + consecutiveBoundaryRefusals: number inputTokens: number outputTokens: number /** The most recent model call's provider-reported tokens — the live-context estimate (RUN-023). */ @@ -712,6 +714,7 @@ interface TurnTrace { readonly name: string readonly encodedResult: unknown readonly isFailure: boolean + readonly boundaryRefusal?: boolean readonly cause?: Cause.Cause | undefined /** Settled synthetically by budget rejection: no handler ran, exempt from repeated-failure folding. */ readonly budgetRejected?: boolean @@ -2295,6 +2298,9 @@ const executePreparedToolCall = Effect.fnUntraced(function*< name: call.name, encodedResult, isFailure: result.isFailure, + ...(result.isFailure && isCodeModeBoundaryRefusal(result.encodedResult) + ? { boundaryRefusal: true } + : {}), ...(failureCause === undefined ? {} : { cause: failureCause }), } terminalResultCommitted = true @@ -2959,19 +2965,23 @@ const schedulingConcurrency = Effect.fnUntraced(function*( return Math.min(configured, concurrency) }) +type ToolOutcome = 'success' | 'failure' | 'refused' + +const BOUNDARY_REFUSAL_LIMIT = 3 + /** * One terminal outcome per declared Tool Call of the completed Turn, in * declaration order. Provider-executed results are read from the response * parts; application results from the settled batch. */ -const turnToolFailures = (trace: TurnTrace): ReadonlyArray => { - const outcomes: Array = [] +const turnToolOutcomes = (trace: TurnTrace): ReadonlyArray => { + const outcomes: Array = [] for (const [id, call] of trace.toolCalls) { if (call.providerExecuted) { for (const part of trace.parts) { if (part.type === 'tool-result' && part.id === id && part.preliminary !== true) { - outcomes.push(part.isFailure) + outcomes.push(part.isFailure ? 'failure' : 'success') break } } @@ -2979,31 +2989,55 @@ const turnToolFailures = (trace: TurnTrace): ReadonlyArray => { } const result = trace.applicationToolResults.find((candidate) => candidate?.id === id) - // Budget-rejected calls never ran a handler; they neither advance nor - // reset the consecutive-failure counter. if (result !== undefined && result.budgetRejected !== true) { - outcomes.push(result.isFailure) + outcomes.push( + result.boundaryRefusal === true ? 'refused' : result.isFailure ? 'failure' : 'success', + ) } } return outcomes } +const boundaryRefusalCount = (trace: TurnTrace): number => + trace.applicationToolResults.filter((result) => result?.boundaryRefusal === true).length + /** * Fold the completed Turn's terminal Tool outcomes into the Run's - * consecutive-failure counter in declaration order, then enforce the - * repeated-failure Stop Policy before the next model request. A terminal - * success resets the counter; a `repeatedFailureLimit` of `0` disables the - * bound. + * consecutive-failure and boundary-refusal counters in declaration order, then + * enforce both Stop Policies before the next model request. A terminal success + * resets both counters; a `repeatedFailureLimit` of `0` disables only the + * failure bound. A boundary refusal returns the Tool Call it charged, because + * the program never ran. */ -const applyRepeatedFailurePolicy = ( +const applyRepeatedFailurePolicy = ( context: RunContext, trace: TurnTrace, repeatedFailureLimit: number, -): Effect.Effect => - Effect.suspend(() => { - for (const isFailure of turnToolFailures(trace)) { - context.consecutiveToolFailures = isFailure ? context.consecutiveToolFailures + 1 : 0 + options: RunOptions, +): Effect.Effect => + Effect.gen(function*() { + let refusals = 0 + + for (const outcome of turnToolOutcomes(trace)) { + if (outcome === 'refused') { + refusals += 1 + context.consecutiveBoundaryRefusals += 1 + continue + } + context.consecutiveBoundaryRefusals = 0 + context.consecutiveToolFailures = outcome === 'success' ? 0 : context.consecutiveToolFailures + 1 + } + + if (refusals > 0 && options.budget?.releaseToolCalls !== undefined) { + yield* options.budget.releaseToolCalls(refusals) + } + if (context.consecutiveBoundaryRefusals >= BOUNDARY_REFUSAL_LIMIT) { + return yield* AgentPolicyError.make({ + limit: 'repeated-failures', + message: + `Agent reached its ${BOUNDARY_REFUSAL_LIMIT} consecutive Code Mode boundary refusal limit; the refused program never started and its refusal reports the syntax error`, + }) } if (repeatedFailureLimit > 0 && context.consecutiveToolFailures >= repeatedFailureLimit) { const cause = Cause.fromReasons( @@ -3014,18 +3048,14 @@ const applyRepeatedFailurePolicy = ( ), ) - return Effect.fail( - FailureDiagnostic.withCause( - AgentPolicyError.make({ - limit: 'repeated-failures', - message: `Agent reached its ${repeatedFailureLimit} consecutive Tool Call failure limit`, - }), - cause, - ), + return yield* FailureDiagnostic.withCause( + AgentPolicyError.make({ + limit: 'repeated-failures', + message: `Agent reached its ${repeatedFailureLimit} consecutive Tool Call failure limit`, + }), + cause, ) } - - return Effect.void }) const inputsToPrompt = ( @@ -7175,7 +7205,7 @@ const makeTurn = < const steering = yield* drainInputs(context, options) const nextPrompt = yield* appendDrainedInputs(context, history, steering, options) - return yield* Effect.succeed(nextTurn(nextPrompt, turn + 1, toolCalls)) + return yield* Effect.succeed(nextTurn(nextPrompt, turn + 1, toolCalls - boundaryRefusalCount(trace))) }) /** @@ -7229,11 +7259,12 @@ const makeTurn = < context, trace, agent.definition.policy.repeatedFailureLimit, + options, ) yield* settleTurn(context, trace, turn, turnId, options) const nextPrompt = yield* appendDrainedInputs(context, history, queued, options) - return yield* Effect.succeed(nextTurn(nextPrompt, turn + 1, toolCalls)) + return yield* Effect.succeed(nextTurn(nextPrompt, turn + 1, toolCalls - boundaryRefusalCount(trace))) } const output = yield* prepareWithinDeadline( @@ -7387,12 +7418,13 @@ const makeTurn = < context, trace, agent.definition.policy.repeatedFailureLimit, + options, ) const steering = yield* drainInputs(context, options) const nextPrompt = yield* appendDrainedInputs(context, history, steering, options) - return yield* Effect.succeed(nextTurn(nextPrompt, turn + 1, toolCalls)) + return yield* Effect.succeed(nextTurn(nextPrompt, turn + 1, toolCalls - boundaryRefusalCount(trace))) }), ) } @@ -7755,6 +7787,7 @@ const toolBatchContinuation = < context, trace, agent.definition.policy.repeatedFailureLimit, + options, ) const rolloverResult = orderedResults.length === 1 ? orderedResults[0] : undefined @@ -7818,7 +7851,7 @@ const toolBatchContinuation = < ? 'tokens' : turn > bounds.maxTurns ? 'turns' - : toolCalls + context.programmaticToolCalls > bounds.maxToolCalls + : toolCalls - boundaryRefusalCount(trace) + context.programmaticToolCalls > bounds.maxToolCalls ? 'tool-calls' : context.exhaustedDimension @@ -7848,7 +7881,7 @@ const toolBatchContinuation = < } const nextPrompt = yield* appendDrainedInputs(context, history, steering, options) - return yield* Effect.succeed(nextTurn(nextPrompt, turn + 1, toolCalls)) + return yield* Effect.succeed(nextTurn(nextPrompt, turn + 1, toolCalls - boundaryRefusalCount(trace))) }), ).pipe( Effect.catchCauseIf( @@ -8222,6 +8255,9 @@ const makeResumeTurn = < name: declared.name, encodedResult: settledCall.result, isFailure: settledCall.isFailure, + ...(settledCall.isFailure && isCodeModeBoundaryRefusal(settledCall.result) + ? { boundaryRefusal: true } + : {}), ...(settledCall.budgetRejected === undefined ? {} : { budgetRejected: settledCall.budgetRejected }), @@ -8796,6 +8832,7 @@ function executeWithCompletion< ), liveChildren: new Set(), consecutiveToolFailures: resumeUsage?.consecutiveToolFailures ?? 0, + consecutiveBoundaryRefusals: 0, inputTokens: resumeUsage?.inputTokens ?? 0, outputTokens: resumeUsage?.outputTokens ?? 0, lastInputTokens: resumeUsage?.lastInputTokens ?? 0, diff --git a/packages/effect-agent/test/engine/agent-runtime.test.ts b/packages/effect-agent/test/engine/agent-runtime.test.ts index 3e75d4c6b..9fe83190b 100644 --- a/packages/effect-agent/test/engine/agent-runtime.test.ts +++ b/packages/effect-agent/test/engine/agent-runtime.test.ts @@ -3,16 +3,24 @@ import * as Agent from '@systemfsoftware/agent/agent' import { ModelProtocolError } from '@systemfsoftware/agent/agent-error' import { AgentPolicy } from '@systemfsoftware/agent/agent-policy' import * as AgentRuntime from '@systemfsoftware/agent/agent-runtime' +import { makeUsageBudget, UsageBudgetLimits } from '@systemfsoftware/agent/budget' +import { CodeExecutionResult, CodeExecutor, CodeSourceError } from '@systemfsoftware/agent/code-executor' +import * as CodeMode from '@systemfsoftware/agent/code-mode' +import { ToolExecutionClass } from '@systemfsoftware/agent/durable-step' import { IdGenerator } from '@systemfsoftware/agent/id-generator' import { RunId, ThreadId, TurnId } from '@systemfsoftware/agent/identifiers' import { type RunEvent } from '@systemfsoftware/agent/run-event' +import { toRunBudgetHook } from '@systemfsoftware/agent/run-hooks' +import { SandboxImplementation } from '@systemfsoftware/agent/sandbox' import * as AiError from 'effect/ai/AiError' import * as LanguageModel from 'effect/ai/LanguageModel' import * as Model from 'effect/ai/Model' +import type * as Prompt from 'effect/ai/Prompt' import type * as Response from 'effect/ai/Response' import * as Tool from 'effect/ai/Tool' import * as Toolkit from 'effect/ai/Toolkit' import * as Cause from 'effect/Cause' +import * as Duration from 'effect/Duration' import * as Effect from 'effect/Effect' import * as ErrorReporter from 'effect/ErrorReporter' import * as Exit from 'effect/Exit' @@ -104,6 +112,101 @@ const testLayer = Layer.mergeAll( RunContextPreparationPassthrough, ) +const RefusalQuery = Tool.make('query_warehouse', { + parameters: Schema.Struct({ sql: Schema.String }), + success: Schema.Struct({ rows: Schema.Array(Schema.Int), truncated: Schema.Boolean }), +}).annotate(ToolExecutionClass, 'readonly') + +const refusalSandbox = SandboxImplementation.make({ + isolation: 'unisolated', + identity: 'scripted-refusal-executor', +}) + +const refusalMessage = (source: string): string => + `SyntaxError: Unexpected token (line 1, column 14)\n ${source}\nExample: async () => ({ ok: true })` + +const refusalScriptedModel = (script: ReadonlyArray>) => { + const requests: Array = [] + + const model = Model.make( + 'scripted', + 'refusal-engine-test', + Layer.effect( + LanguageModel.LanguageModel, + LanguageModel.make({ + generateText: () => Effect.succeed([]), + streamText: (request) => { + requests.push(request.prompt) + + return Stream.fromIterable(script[Math.min(requests.length - 1, script.length - 1)] ?? []) + }, + }), + ), + ) + + return { model, requests } +} + +const refusalToolResults = (prompt: Prompt.Prompt | undefined): ReadonlyArray => + prompt === undefined + ? [] + : prompt.content.flatMap((message) => + typeof message.content === 'string' + ? [] + : message.content.flatMap((part) => part.type === 'tool-result' ? [part.result] : []) + ) + +const refusalCodeMode = (executor: Layer.Layer) => { + const definition = CodeMode.make('run_program', { + description: 'Run one JavaScript program that may call warehouse.query.', + tools: { warehouse: { query: RefusalQuery } }, + }) + + const agent = Agent.make('code-mode-refusal', { + input: Schema.String, + output: Schema.Struct({ answer: Schema.String }), + instructions: 'Use the program Tool.', + toolkit: Toolkit.make(definition.tool), + policy: AgentPolicy.make({ + maxTurns: 6, + maxToolCalls: 24, + maxDuration: '30 seconds', + toolConcurrency: 1, + }), + }) + + const handlers = definition.handlers.pipe( + Layer.provide(executor), + Layer.provide( + Toolkit.make(RefusalQuery).toLayer({ + query_warehouse: () => Effect.succeed({ rows: [], truncated: false }), + }), + ), + ) + + return { definition, agent, handlers } +} + +const refusalParts = ( + id: string, + name: string, + code: string, +): ReadonlyArray => [ + { type: 'tool-call', id, name, params: { code }, providerExecuted: false }, + { type: 'finish', reason: 'tool-calls', usage }, +] + +const refusedExecutor = CodeExecutor.of({ + execute: (request) => + Effect.fail( + CodeSourceError.make({ + implementation: refusalSandbox, + reason: 'invalid', + message: refusalMessage(request.source), + }), + ), +}) + layer(testLayer)('RUN-001 Phase 1 AgentRuntime', (it) => { it.effect( 'keeps completed Tool results when canonical span create, wrap, or close defects', @@ -544,4 +647,99 @@ layer(testLayer)('RUN-001 Phase 1 AgentRuntime', (it) => { expect(observed.filter((event) => event._tag === 'ToolCallSucceeded')).toHaveLength(0) expect(observed.filter((event) => event._tag === 'RunFailed')).toHaveLength(1) })) + + it.effect('refunds boundary refusals and stops after three consecutive ones', () => + Effect.gen(function*() { + const { definition, agent, handlers } = refusalCodeMode( + Layer.succeed(CodeExecutor, refusedExecutor), + ) + const { model, requests } = refusalScriptedModel([ + refusalParts('code-1', definition.name, 'async () => {'), + refusalParts('code-2', definition.name, 'async () => {'), + refusalParts('code-3', definition.name, 'async () => {'), + finalParts('{"answer":"never"}'), + ]) + const budget = yield* makeUsageBudget(UsageBudgetLimits.make({ maxToolCalls: 1 })) + + const exit = yield* AgentRuntime.run(Agent.withModel(agent, model), 'go', { + budget: toRunBudgetHook(budget), + }).pipe( + Effect.provide(handlers), + Effect.exit, + ) + + const failure = failureFrom(exit) + + if (failure._tag !== 'AgentPolicyError') { + throw new Error(`Expected AgentPolicyError, received ${failure._tag}`) + } + expect(failure.limit).toBe('repeated-failures') + expect(failure.message).toContain('Code Mode boundary refusal limit') + expect(requests).toHaveLength(3) + expect((yield* budget.snapshot).toolCalls).toBe(0) + + const firstRefusal = refusalToolResults(requests[1]) + + expect(firstRefusal[0]).toMatchObject({ + _tag: 'CodeModeFailure', + errorTag: 'CodeSourceError', + boundaryRefusal: true, + }) + expect(firstRefusal[0]).toMatchObject({ + message: expect.stringContaining('line 1, column 14'), + }) + })) + + it.effect('runs a later valid program after one refusal without charging it', () => + Effect.gen(function*() { + const { model, requests } = refusalScriptedModel([ + refusalParts('code-1', 'run_program', 'async () => {'), + refusalParts('code-2', 'run_program', 'async () => ({ ok: true })'), + finalParts('{"answer":"done"}'), + ]) + const budget = yield* makeUsageBudget(UsageBudgetLimits.make({ maxToolCalls: 1 })) + let attempts = 0 + + const executor = CodeExecutor.of({ + execute: (request) => + Effect.suspend(() => { + attempts += 1 + + return attempts === 1 + ? Effect.fail( + CodeSourceError.make({ + implementation: refusalSandbox, + reason: 'invalid', + message: refusalMessage(request.source), + }), + ) + : Effect.succeed( + CodeExecutionResult.make({ + implementation: refusalSandbox, + value: { ok: true }, + logs: [], + resourceUse: { + wallTime: Duration.millis(1), + hostCalls: 0, + logBytes: 0, + resultBytes: 11, + }, + }), + ) + }), + }) + const { agent, handlers } = refusalCodeMode(Layer.succeed(CodeExecutor, executor)) + + const events = yield* AgentRuntime.stream(Agent.withModel(agent, model), 'go', { + budget: toRunBudgetHook(budget), + }).pipe( + Stream.runCollect, + Effect.provide(handlers), + ) + + expect(attempts).toBe(2) + expect((yield* budget.snapshot).toolCalls).toBe(1) + expect(Array.from(events).at(-1)).toMatchObject({ _tag: 'RunCompleted' }) + expect(refusalToolResults(requests[2])[1]).toMatchObject({ result: { ok: true } }) + })) }) From 3b40d046ec66209e70f9e2d239f638fa527d4004 Mon Sep 17 00:00:00 2001 From: systemfsoftware-bot Date: Tue, 1 Dec 2026 21:12:30 +0000 Subject: [PATCH 04/11] fix(agent): give the repeated boundary-refusal stop its own tag - Add `CodeModeBoundaryRefusalLimitExceeded` to the framework error schema and the runtime failure union, carrying the refusal limit, the observed consecutive count, and a bounded message. - Fail with that dedicated tag when the consecutive Code Mode boundary-refusal cap is reached, instead of an `AgentPolicyError` with a `repeated-failures` limit, so a consumer can distinguish the stop from every policy, budget, and runtime stop. - Assert the dedicated tag, limit, and count in the engine suite; durable settlement keeps it as a generic bounded failure diagnostic with no `policyLimit`. --- .changeset/code-mode-program-normalize.md | 2 +- packages/effect-agent/src/core/AgentError.ts | 9 +++++++++ .../effect-agent/src/engine/internal/agent-runtime.ts | 9 ++++++--- packages/effect-agent/test/engine/agent-runtime.test.ts | 7 ++++--- 4 files changed, 20 insertions(+), 7 deletions(-) diff --git a/.changeset/code-mode-program-normalize.md b/.changeset/code-mode-program-normalize.md index 3f81e615f..bdad22735 100644 --- a/.changeset/code-mode-program-normalize.md +++ b/.changeset/code-mode-program-normalize.md @@ -3,4 +3,4 @@ "@systemfsoftware/agent-platform-cloudflare": patch --- -The Dynamic Worker Code Mode executor now normalizes a model program written with TypeScript annotations, a markdown code fence, a bare or semicolon-terminated function expression, an `export default`, an IIFE, or a statement list with top-level `await`, and refuses a program that still does not parse with a `CodeSourceError` carrying the parser message, its line and column, the offending line, and a valid example. A program refused at that boundary never started, so its Tool Call no longer consumes the Run's Tool-call budget; three consecutive boundary refusals end the Run with an `AgentPolicyError` naming the Code Mode boundary-refusal limit. +The Dynamic Worker Code Mode executor now normalizes a model program written with TypeScript annotations, a markdown code fence, a bare or semicolon-terminated function expression, an `export default`, an IIFE, or a statement list with top-level `await`, and refuses a program that still does not parse with a `CodeSourceError` carrying the parser message, its line and column, the offending line, and a valid example. A program refused at that boundary never started, so its Tool Call no longer consumes the Run's Tool-call budget; three consecutive boundary refusals end the Run with its own `CodeModeBoundaryRefusalLimitExceeded` stop tag, carrying the refusal limit and observed count, instead of a generic policy or budget stop. diff --git a/packages/effect-agent/src/core/AgentError.ts b/packages/effect-agent/src/core/AgentError.ts index 61da4c51f..300535e5b 100644 --- a/packages/effect-agent/src/core/AgentError.ts +++ b/packages/effect-agent/src/core/AgentError.ts @@ -71,6 +71,14 @@ export class AgentPolicyError extends Schema.TaggedError()('Ag declare readonly cause?: unknown } +export class CodeModeBoundaryRefusalLimitExceeded extends Schema.TaggedError< + CodeModeBoundaryRefusalLimitExceeded +>()('CodeModeBoundaryRefusalLimitExceeded', { + limit: Schema.Natural, + refusals: Schema.Natural, + message: Schema.String, +}) {} + /** A native Effect AI Tool approval was explicitly denied before its Handler started. */ export class AgentApprovalDenied extends Schema.TaggedError()( 'AgentApprovalDenied', @@ -191,6 +199,7 @@ export const AgentError = Schema.Union([ AgentOutputError, AgentRunDispositionError, AgentPolicyError, + CodeModeBoundaryRefusalLimitExceeded, AgentApprovalDenied, AgentToolAuthorizationDenied, AgentToolAuthorizationCheckError, diff --git a/packages/effect-agent/src/engine/internal/agent-runtime.ts b/packages/effect-agent/src/engine/internal/agent-runtime.ts index 97557a831..ab094c30b 100644 --- a/packages/effect-agent/src/engine/internal/agent-runtime.ts +++ b/packages/effect-agent/src/engine/internal/agent-runtime.ts @@ -55,6 +55,7 @@ import { AgentRunDispositionError, type AgentToolAuthorizationCheckError, AgentToolAuthorizationDenied, + CodeModeBoundaryRefusalLimitExceeded, ContextBudgetError, ContextOverflowError, ModelProtocolError, @@ -437,6 +438,7 @@ export type AgentRuntimeFailure< | Agent.Failure | ([Agent.UpdatesSchema] extends [never] ? never : UpdateError) | AgentPolicyError + | CodeModeBoundaryRefusalLimitExceeded | ContextBudgetError | ContextOverflowError | CompactionError @@ -3015,7 +3017,7 @@ const applyRepeatedFailurePolicy = ( trace: TurnTrace, repeatedFailureLimit: number, options: RunOptions, -): Effect.Effect => +): Effect.Effect => Effect.gen(function*() { let refusals = 0 @@ -3033,8 +3035,9 @@ const applyRepeatedFailurePolicy = ( yield* options.budget.releaseToolCalls(refusals) } if (context.consecutiveBoundaryRefusals >= BOUNDARY_REFUSAL_LIMIT) { - return yield* AgentPolicyError.make({ - limit: 'repeated-failures', + return yield* CodeModeBoundaryRefusalLimitExceeded.make({ + limit: BOUNDARY_REFUSAL_LIMIT, + refusals: context.consecutiveBoundaryRefusals, message: `Agent reached its ${BOUNDARY_REFUSAL_LIMIT} consecutive Code Mode boundary refusal limit; the refused program never started and its refusal reports the syntax error`, }) diff --git a/packages/effect-agent/test/engine/agent-runtime.test.ts b/packages/effect-agent/test/engine/agent-runtime.test.ts index 9fe83190b..9806de01a 100644 --- a/packages/effect-agent/test/engine/agent-runtime.test.ts +++ b/packages/effect-agent/test/engine/agent-runtime.test.ts @@ -670,10 +670,11 @@ layer(testLayer)('RUN-001 Phase 1 AgentRuntime', (it) => { const failure = failureFrom(exit) - if (failure._tag !== 'AgentPolicyError') { - throw new Error(`Expected AgentPolicyError, received ${failure._tag}`) + if (failure._tag !== 'CodeModeBoundaryRefusalLimitExceeded') { + throw new Error(`Expected CodeModeBoundaryRefusalLimitExceeded, received ${failure._tag}`) } - expect(failure.limit).toBe('repeated-failures') + expect(failure.limit).toBe(3) + expect(failure.refusals).toBe(3) expect(failure.message).toContain('Code Mode boundary refusal limit') expect(requests).toHaveLength(3) expect((yield* budget.snapshot).toolCalls).toBe(0) From 05b664bd5a527c3e80892a7339dd77d271359600 Mon Sep 17 00:00:00 2001 From: systemfsoftware-bot Date: Tue, 1 Dec 2026 21:16:11 +0000 Subject: [PATCH 05/11] fix(platform-cloudflare): strip a code fence before TypeScript stripping - Remove one surrounding markdown fence (`js`, `javascript`, `typescript`, `ts`, `tsx`, `jsx`, or bare) before the sucrase TypeScript transform, so a fenced TypeScript program reaches `normalizeCode` as plain JavaScript instead of being refused by the post-normalization parse. - Report sucrase failures against the unfenced source so the line and column match the program body. - Add a fenced TypeScript statement list with top-level await to the workerd shape corpus. --- .../platform-cloudflare/src/CodeModeProgram.ts | 16 ++++++++++++++-- .../test/code-mode/code-mode-executor.test.ts | 1 + .../test/code-mode/conformance-worker.ts | 5 +++++ 3 files changed, 20 insertions(+), 2 deletions(-) diff --git a/packages/platform-cloudflare/src/CodeModeProgram.ts b/packages/platform-cloudflare/src/CodeModeProgram.ts index a94015252..eb7c78e21 100644 --- a/packages/platform-cloudflare/src/CodeModeProgram.ts +++ b/packages/platform-cloudflare/src/CodeModeProgram.ts @@ -52,11 +52,23 @@ const syntaxFailure = ( const stripTypeScript = (source: string): string => transform(source, { transforms: ['typescript'] }).code +const CODE_FENCE = /^```(?:js|javascript|typescript|ts|tsx|jsx)?\s*\n([\s\S]*?)```\s*$/ + +const fencedBody = (source: string): string | undefined => { + const match = CODE_FENCE.exec(source.trim()) + + return match === null ? undefined : match[1] +} + +const stripCodeFence = (source: string): string => fencedBody(source) ?? source + const normalizedProgram = (source: string): string | CodeModeProgram => { + const plainSource = stripCodeFence(source) + try { - return normalizeCode(stripTypeScript(source)) + return normalizeCode(stripTypeScript(plainSource)) } catch (cause) { - return syntaxFailure(cause, source, 0) + return syntaxFailure(cause, plainSource, 0) } } diff --git a/packages/platform-cloudflare/test/code-mode/code-mode-executor.test.ts b/packages/platform-cloudflare/test/code-mode/code-mode-executor.test.ts index 05be58d9f..a15916ce9 100644 --- a/packages/platform-cloudflare/test/code-mode/code-mode-executor.test.ts +++ b/packages/platform-cloudflare/test/code-mode/code-mode-executor.test.ts @@ -110,6 +110,7 @@ describe('DEPLOY-011 Cloudflare Dynamic Worker CodeExecutor', () => { 'function-declaration-called': { tag: 'success', value: { shape: 'called' } }, 'typescript-annotations': { tag: 'success', value: 'a-b' }, 'typescript-arrow': { tag: 'success', value: { shape: 'ts' } }, + 'typescript-fence': { tag: 'success', value: 'a-b' }, 'statement-list-with-tool': { tag: 'success', value: { first: 'ledger' } }, 'invalid-syntax': { tag: 'CodeSourceError', reason: 'invalid' }, }) diff --git a/packages/platform-cloudflare/test/code-mode/conformance-worker.ts b/packages/platform-cloudflare/test/code-mode/conformance-worker.ts index 5235dc806..23bcaef8b 100644 --- a/packages/platform-cloudflare/test/code-mode/conformance-worker.ts +++ b/packages/platform-cloudflare/test/code-mode/conformance-worker.ts @@ -132,6 +132,11 @@ const programCases: ReadonlyArray = [ source: `async (): Promise<{ shape: 'ts' }> => ({ shape: 'ts' })`, callsHost: false, }, + { + label: 'typescript-fence', + source: "```ts\nconst parts: string[] = await Promise.resolve(['a', 'b']);\nparts.join('-')\n```", + callsHost: false, + }, { label: 'statement-list-with-tool', source: `const first = await warehouse.query({ sql: 'select 1' });\n({ first })`, From 76c408e19641fc595402948d1752d07b6b0742ed Mon Sep 17 00:00:00 2001 From: systemfsoftware-bot Date: Tue, 1 Dec 2026 22:13:55 +0000 Subject: [PATCH 06/11] fix(agent): keep the refusal refund off the run's type channels - Make `RunBudgetHook.releaseToolCalls` infallible and requirement-free: the refund only rewrites the in-memory budget ledger, so it must not widen a host's Run error or requirement types. - Pass only that refund seam to the repeated-outcome policy instead of the whole `RunOptions`, so adding the dedicated boundary-refusal stop leaves the Run's error and requirement channels as they were for every consumer. - Restores the dependents that spread a budget hook into child runs (`pr-review`, `pr-review-eval`) without casts at their call sites. --- packages/effect-agent/src/engine/RunOptions.ts | 4 +--- .../src/engine/internal/agent-runtime.ts | 18 ++++++++++-------- 2 files changed, 11 insertions(+), 11 deletions(-) diff --git a/packages/effect-agent/src/engine/RunOptions.ts b/packages/effect-agent/src/engine/RunOptions.ts index 895f59f0b..fe0df56eb 100644 --- a/packages/effect-agent/src/engine/RunOptions.ts +++ b/packages/effect-agent/src/engine/RunOptions.ts @@ -396,9 +396,7 @@ export interface RunBudgetHook { effect: Effect.Effect, ) => Effect.Effect readonly consume: (delta: RunUsageDelta) => Effect.Effect - readonly releaseToolCalls?: ( - count: number, - ) => Effect.Effect + readonly releaseToolCalls?: (count: number) => Effect.Effect } /** diff --git a/packages/effect-agent/src/engine/internal/agent-runtime.ts b/packages/effect-agent/src/engine/internal/agent-runtime.ts index ab094c30b..74c4ab82b 100644 --- a/packages/effect-agent/src/engine/internal/agent-runtime.ts +++ b/packages/effect-agent/src/engine/internal/agent-runtime.ts @@ -3012,12 +3012,14 @@ const boundaryRefusalCount = (trace: TurnTrace): number => * failure bound. A boundary refusal returns the Tool Call it charged, because * the program never ran. */ -const applyRepeatedFailurePolicy = ( +const applyRepeatedFailurePolicy = ( context: RunContext, trace: TurnTrace, repeatedFailureLimit: number, - options: RunOptions, -): Effect.Effect => + budget: + | { readonly releaseToolCalls?: (count: number) => Effect.Effect } + | undefined, +): Effect.Effect => Effect.gen(function*() { let refusals = 0 @@ -3031,8 +3033,8 @@ const applyRepeatedFailurePolicy = ( context.consecutiveToolFailures = outcome === 'success' ? 0 : context.consecutiveToolFailures + 1 } - if (refusals > 0 && options.budget?.releaseToolCalls !== undefined) { - yield* options.budget.releaseToolCalls(refusals) + if (refusals > 0 && budget?.releaseToolCalls !== undefined) { + yield* budget.releaseToolCalls(refusals) } if (context.consecutiveBoundaryRefusals >= BOUNDARY_REFUSAL_LIMIT) { return yield* CodeModeBoundaryRefusalLimitExceeded.make({ @@ -7262,7 +7264,7 @@ const makeTurn = < context, trace, agent.definition.policy.repeatedFailureLimit, - options, + options.budget, ) yield* settleTurn(context, trace, turn, turnId, options) const nextPrompt = yield* appendDrainedInputs(context, history, queued, options) @@ -7421,7 +7423,7 @@ const makeTurn = < context, trace, agent.definition.policy.repeatedFailureLimit, - options, + options.budget, ) const steering = yield* drainInputs(context, options) @@ -7790,7 +7792,7 @@ const toolBatchContinuation = < context, trace, agent.definition.policy.repeatedFailureLimit, - options, + options.budget, ) const rolloverResult = orderedResults.length === 1 ? orderedResults[0] : undefined From 96fc5fd8ed5c6e02af29575d0c2d3c48907e12da Mon Sep 17 00:00:00 2001 From: systemfsoftware-bot Date: Tue, 1 Dec 2026 22:20:09 +0000 Subject: [PATCH 07/11] fix(platform-cloudflare): move the Code Mode program normalizer under internal - `pnpm check:exports` requires unpublished source-root modules to live under `internal/`; move `CodeModeProgram.ts` and its Schema beside the package's other internal modules and update the executor import. - Tag both internal exports `@internal` per the repository's internal-export rule. - No behavior change: the module source, schema union, and executor wiring are identical. --- packages/platform-cloudflare/src/CloudflareCodeMode.ts | 2 +- .../src/{ => internal}/CodeModeProgram.schema.ts | 1 + .../platform-cloudflare/src/{ => internal}/CodeModeProgram.ts | 1 + 3 files changed, 3 insertions(+), 1 deletion(-) rename packages/platform-cloudflare/src/{ => internal}/CodeModeProgram.schema.ts (95%) rename packages/platform-cloudflare/src/{ => internal}/CodeModeProgram.ts (99%) diff --git a/packages/platform-cloudflare/src/CloudflareCodeMode.ts b/packages/platform-cloudflare/src/CloudflareCodeMode.ts index c27e9915b..c393b75b4 100644 --- a/packages/platform-cloudflare/src/CloudflareCodeMode.ts +++ b/packages/platform-cloudflare/src/CloudflareCodeMode.ts @@ -29,8 +29,8 @@ import * as Option from 'effect/Option' import * as Queue from 'effect/Queue' import * as Schema from 'effect/Schema' -import { normalizeCodeModeProgram } from './CodeModeProgram' import { safeCauseDiagnostic, safeCauseMessage } from './internal/boundary' +import { normalizeCodeModeProgram } from './internal/CodeModeProgram' /** * The Cloudflare Dynamic Worker `CodeExecutor` adapter (C4 of ADR-0017; diff --git a/packages/platform-cloudflare/src/CodeModeProgram.schema.ts b/packages/platform-cloudflare/src/internal/CodeModeProgram.schema.ts similarity index 95% rename from packages/platform-cloudflare/src/CodeModeProgram.schema.ts rename to packages/platform-cloudflare/src/internal/CodeModeProgram.schema.ts index 4cb59c52a..82025f6ec 100644 --- a/packages/platform-cloudflare/src/CodeModeProgram.schema.ts +++ b/packages/platform-cloudflare/src/internal/CodeModeProgram.schema.ts @@ -4,4 +4,5 @@ const NormalizedProgram = Schema.TaggedStruct('Normalized', { moduleSource: Sche const InvalidProgram = Schema.TaggedStruct('Invalid', { message: Schema.String }) const CodeModeProgramSchema = Schema.Union([NormalizedProgram, InvalidProgram]) +/** @internal */ export type CodeModeProgram = typeof CodeModeProgramSchema.Type diff --git a/packages/platform-cloudflare/src/CodeModeProgram.ts b/packages/platform-cloudflare/src/internal/CodeModeProgram.ts similarity index 99% rename from packages/platform-cloudflare/src/CodeModeProgram.ts rename to packages/platform-cloudflare/src/internal/CodeModeProgram.ts index eb7c78e21..52c48890e 100644 --- a/packages/platform-cloudflare/src/CodeModeProgram.ts +++ b/packages/platform-cloudflare/src/internal/CodeModeProgram.ts @@ -84,6 +84,7 @@ const normalizedModule = (normalized: string): CodeModeProgram => { } } +/** @internal */ export const normalizeCodeModeProgram = (source: string): CodeModeProgram => { const result = normalizedProgram(source) From 76a57c38ebf815204b40322edca869f18da5848e Mon Sep 17 00:00:00 2001 From: systemfsoftware-bot Date: Tue, 1 Dec 2026 22:46:52 +0000 Subject: [PATCH 08/11] fix(agent): carry the boundary-refusal streak across resume - Derive the consecutive Code Mode boundary-refusal count in the run-journal projection from settled Tool outcomes, refusing results increment and any other terminal outcome resets, matching the engine's fold order. - Feed that projection into `resumeUsage` and seed the run context from it, so a resumed Attempt continues the streak instead of restarting at zero and looping past the cap. - Keep the durable record schema untouched: the count is recomputed from canonical records, so the record format stays compatible. - Test the journal derivation (two refusals count, a success resets) and a resumed Attempt that refuses once more and stops at the three-refusal cap. --- .../src/durable/DurableAgentRuntime.ts | 1 + .../effect-agent/src/durable/RunJournal.ts | 9 +++ .../src/engine/internal/agent-runtime.ts | 3 +- .../engine/internal/interpreter-options.ts | 1 + .../test/durable/run-journal.test.ts | 72 +++++++++++++++++++ .../test/engine/agent-runtime.test.ts | 41 +++++++++++ 6 files changed, 126 insertions(+), 1 deletion(-) diff --git a/packages/effect-agent/src/durable/DurableAgentRuntime.ts b/packages/effect-agent/src/durable/DurableAgentRuntime.ts index fd32ce8d1..99f3f1b6c 100644 --- a/packages/effect-agent/src/durable/DurableAgentRuntime.ts +++ b/packages/effect-agent/src/durable/DurableAgentRuntime.ts @@ -8104,6 +8104,7 @@ const make = Effect.fnUntraced(function*(bindings: ReadonlyArray ({ @@ -446,6 +447,7 @@ export const initialRunJournal = (history: Prompt.Prompt): RunJournalProjection historyBefore: history, historyFrom: CanonicalSequence.make(1), committedTurns: 0, + consecutiveBoundaryRefusals: 0, }) interface ProjectedResponseUsage { @@ -1091,6 +1093,7 @@ export const projectRunJournalStream = Effect.fnUntraced(function*< let ownerTerminated = false const policyUsage = initialPolicyUsage() + let consecutiveBoundaryRefusals = 0 const accountResponse = Effect.fnUntraced(function*( envelope: JournalRecordEnvelope, @@ -1211,6 +1214,11 @@ export const projectRunJournalStream = Effect.fnUntraced(function*< continue } if (!('isFailure' in result)) continue + if (result.isFailure && 'boundaryRefusal' in result && result.boundaryRefusal === true) { + consecutiveBoundaryRefusals += 1 + continue + } + consecutiveBoundaryRefusals = 0 if (!result.isFailure && 'toolSelection' in result && result.toolSelection !== undefined) { toolSelection = result.toolSelection } @@ -1620,6 +1628,7 @@ export const projectRunJournalStream = Effect.fnUntraced(function*< historyFrom, committedTurns: state.committedTurns, usage: unobservedModelCalls === 0 ? usage : { ...usage, unobservedModelCalls }, + consecutiveBoundaryRefusals, ...(latestWindowId === undefined ? {} : { contextWindowId: latestWindowId }), ...(protectedContext === undefined ? {} : { protectedContext }), ...(ownerTerminated || pendingContextToolCallId === undefined diff --git a/packages/effect-agent/src/engine/internal/agent-runtime.ts b/packages/effect-agent/src/engine/internal/agent-runtime.ts index 74c4ab82b..632083a31 100644 --- a/packages/effect-agent/src/engine/internal/agent-runtime.ts +++ b/packages/effect-agent/src/engine/internal/agent-runtime.ts @@ -1559,6 +1559,7 @@ const decodeResumeUsage = Effect.fnUntraced(function*(input: unknown) { 'children', 'modelRestarts', 'webSearchCalls', + 'consecutiveBoundaryRefusals', ] satisfies ReadonlyArray ) { const value = yield* readSnapshotProperty(input, key, invalid, true) @@ -8837,7 +8838,7 @@ function executeWithCompletion< ), liveChildren: new Set(), consecutiveToolFailures: resumeUsage?.consecutiveToolFailures ?? 0, - consecutiveBoundaryRefusals: 0, + consecutiveBoundaryRefusals: resumeUsage?.consecutiveBoundaryRefusals ?? 0, inputTokens: resumeUsage?.inputTokens ?? 0, outputTokens: resumeUsage?.outputTokens ?? 0, lastInputTokens: resumeUsage?.lastInputTokens ?? 0, diff --git a/packages/effect-agent/src/engine/internal/interpreter-options.ts b/packages/effect-agent/src/engine/internal/interpreter-options.ts index 11b074b78..a55f0b768 100644 --- a/packages/effect-agent/src/engine/internal/interpreter-options.ts +++ b/packages/effect-agent/src/engine/internal/interpreter-options.ts @@ -406,6 +406,7 @@ export type RunTurnResumeSettledCall = typeof RunTurnResumeSettledCallSchema.Typ */ export const RunResumeUsageSchema = Schema.Struct({ ...RunPolicyUsage.fields, + consecutiveBoundaryRefusals: Schema.optionalKey(Schema.Natural), modelCalls: Schema.Natural, webSearchCalls: Schema.optionalKey(Schema.Natural), inputTokens: Schema.Natural, diff --git a/packages/effect-agent/test/durable/run-journal.test.ts b/packages/effect-agent/test/durable/run-journal.test.ts index cdf3f6bc9..5e6e49ca8 100644 --- a/packages/effect-agent/test/durable/run-journal.test.ts +++ b/packages/effect-agent/test/durable/run-journal.test.ts @@ -230,6 +230,78 @@ const toolResults = (prompt: Prompt.Prompt): ReadonlyArray => describe('run journal batch split (plan §2.1)', () => { layer(NodeCrypto.layer)((it) => { + it.effect('counts consecutive boundary refusals for resume', () => + Effect.gen(function*() { + const refusal = { + _tag: 'CodeModeFailure', + errorTag: 'CodeSourceError', + boundaryRefusal: true, + message: 'SyntaxError: Unexpected token', + } + const refusalTurn: ReadonlyArray = [ + Prompt.makeMessage('assistant', { + content: [ + Prompt.makePart('tool-call', { + id: 'call-1', + name: 'run_program', + params: { code: 'async () => {' }, + providerExecuted: false, + }), + ], + }), + Prompt.makeMessage('tool', { + content: [ + Prompt.makePart('tool-result', { + id: 'call-1', + name: 'run_program', + result: refusal, + isFailure: true, + providerExecuted: false, + }), + ], + }), + ] + const successTurn: ReadonlyArray = [ + Prompt.makeMessage('assistant', { + content: [ + Prompt.makePart('tool-call', { + id: 'call-1', + name: 'run_program', + params: { code: 'async () => ({ ok: true })' }, + providerExecuted: false, + }), + ], + }), + Prompt.makeMessage('tool', { + content: [ + Prompt.makePart('tool-result', { + id: 'call-1', + name: 'run_program', + result: { ok: true }, + isFailure: false, + providerExecuted: false, + }), + ], + }), + ] + + const first = yield* turnCanonicalBatch(turnInput(refusalTurn)) + const second = yield* turnCanonicalBatch(turnInput(refusalTurn, 2)) + const third = yield* turnCanonicalBatch(turnInput(successTurn, 3)) + + expect( + (yield* projectRunJournal(envelopesOf([first]), RUN_ID)).consecutiveBoundaryRefusals, + ).toBe(1) + expect( + (yield* projectRunJournal(envelopesOf([first, second]), RUN_ID)) + .consecutiveBoundaryRefusals, + ).toBe(2) + expect( + (yield* projectRunJournal(envelopesOf([first, second, third]), RUN_ID)) + .consecutiveBoundaryRefusals, + ).toBe(0) + })) + it.effect( 'journals native provider results after the engine freezes snapshot array prototypes', () => diff --git a/packages/effect-agent/test/engine/agent-runtime.test.ts b/packages/effect-agent/test/engine/agent-runtime.test.ts index 9806de01a..13adba56e 100644 --- a/packages/effect-agent/test/engine/agent-runtime.test.ts +++ b/packages/effect-agent/test/engine/agent-runtime.test.ts @@ -31,6 +31,7 @@ import * as Schema from 'effect/Schema' import * as Stream from 'effect/Stream' import * as Tracer from 'effect/Tracer' +import * as EngineRuntime from '../../src/engine/internal/agent-runtime' import { RunContextPreparationPassthrough } from '../../src/engine/RunOptions' import { ThreadHistory } from '../../src/engine/ThreadHistory' @@ -691,6 +692,46 @@ layer(testLayer)('RUN-001 Phase 1 AgentRuntime', (it) => { }) })) + it.effect('keeps the consecutive refusal count across a resumed Attempt', () => + Effect.gen(function*() { + const { definition, agent, handlers } = refusalCodeMode( + Layer.succeed(CodeExecutor, refusedExecutor), + ) + const { model, requests } = refusalScriptedModel([ + refusalParts('code-3', definition.name, 'async () => {'), + finalParts('{"answer":"never"}'), + ]) + + const exit = yield* EngineRuntime.run(Agent.withModel(agent, model), 'go', { + resumeUsage: { + committedTurns: 2, + toolCalls: 0, + programmaticToolCalls: 0, + consecutiveToolFailures: 0, + finalizationUsed: false, + consecutiveBoundaryRefusals: 2, + modelCalls: 2, + inputTokens: 0, + outputTokens: 0, + lastInputTokens: 0, + lastOutputTokens: 0, + costMicrousd: 0, + }, + }).pipe( + Effect.provide(handlers), + Effect.exit, + ) + + const failure = failureFrom(exit) + + if (failure._tag !== 'CodeModeBoundaryRefusalLimitExceeded') { + throw new Error(`Expected CodeModeBoundaryRefusalLimitExceeded, received ${failure._tag}`) + } + expect(failure.limit).toBe(3) + expect(failure.refusals).toBe(3) + expect(requests).toHaveLength(1) + })) + it.effect('runs a later valid program after one refusal without charging it', () => Effect.gen(function*() { const { model, requests } = refusalScriptedModel([ From f84ee6d66a456edbfc1b26116d4560419eccb60a Mon Sep 17 00:00:00 2001 From: systemfsoftware-bot Date: Wed, 2 Dec 2026 00:06:29 +0000 Subject: [PATCH 09/11] docs(solutions): record Code Mode refusal normalization and refund - Document the boundary defect: programs were wrapped as one expression, so statement lists and fenced TypeScript were refused, and every refusal was charged to the Tool-call budget. - Name the fix by package and exported symbol: `CloudflareCodeMode` normalization, `boundaryRefusal` on `CodeModeFailure`, the budget hook refund, the dedicated `CodeModeBoundaryRefusalLimitExceeded` stop, and the journal-derived refusal streak on resume. - Record the invariants and the gates that prevent recurrence: shape corpus, refund test, record format, and `check:exports` placement. --- ...-boundary-refusals-normalize-and-refund.md | 145 ++++++++++++++++++ 1 file changed, 145 insertions(+) create mode 100644 docs/solutions/logic-errors/code-mode-boundary-refusals-normalize-and-refund.md diff --git a/docs/solutions/logic-errors/code-mode-boundary-refusals-normalize-and-refund.md b/docs/solutions/logic-errors/code-mode-boundary-refusals-normalize-and-refund.md new file mode 100644 index 000000000..7a8ab794b --- /dev/null +++ b/docs/solutions/logic-errors/code-mode-boundary-refusals-normalize-and-refund.md @@ -0,0 +1,145 @@ +--- +title: Code Mode boundary refusals must normalize model program shapes and refund the tool-call budget +date: 2026-12-02 +category: logic-errors +module: agent runtime and platform-cloudflare Code Mode executor +problem_type: logic_error +component: service_layer +symptoms: + - "A statement-list or top-level-await program fails with CodeSourceError reason 'invalid' before the sandbox starts" + - "The boundary reports source-not-a-function for a program that is not a single function expression" + - "Fenced TypeScript the model emits as a code block is refused by the parser" + - "Each refusal consumes a Tool-call budget unit, so retries exhaust the budget without running any program" + - "A durable Attempt resumed between refusals restarts the refusal streak and never reaches the stop limit" +root_cause: wrong_api +resolution_type: code_fix +severity: high +tags: [code-mode, sandbox, tool-call-budget, refusal, durable-resume, cloudflare-workers] +--- + +# Code Mode boundary refusals must normalize model program shapes and refund the tool-call budget + +## Problem + +The Code Mode boundary accepted a model-authored program only when it was a single expression, then +wrapped it as `export default ()` before loading it in the sandbox. Any other normal program +shape — a statement list, a `const` plus a return, top-level `await`, or a fenced TypeScript block — +failed at module compile time and surfaced as `CodeSourceError` before the program started. The same +boundary then booked each refusal as a normal Tool call, so a model retrying a refused shape spent its +Tool-call budget on programs that never ran, and a durable resume could restart the refusal streak and +loop forever. + +**Where it lives.** The executor boundary is the `CloudflareCodeMode` object and the +`dynamicWorkerCodeExecutorLayer` export of `@systemfsoftware/agent-platform-cloudflare` (the +`cloudflare-code-mode` entry point). Program normalization is an internal module of that package, not a +public export. Refusal classification is the `boundaryRefusal` field of `CodeModeFailure` from +`@systemfsoftware/agent/code-mode`; the budget refund is the `releaseToolCalls` seam of the budget +hook built by `toRunBudgetHook` from `@systemfsoftware/agent/run-hooks`, implemented by +`UsageBudgetNode.releaseToolCalls` from `@systemfsoftware/agent/budget`. The dedicated stop is +`CodeModeBoundaryRefusalLimitExceeded` from `@systemfsoftware/agent/agent-error`. Durable re-seeding is +`RunJournalProjection` and `projectRunJournal` from `@systemfsoftware/agent/run-journal`. + +## Symptoms + +- `CodeSourceError` with `reason: 'invalid'` and a `SyntaxError` for a program that is a valid + JavaScript statement list, before any sandbox starts. +- The boundary harness's own `source-not-a-function` check rejecting a program whose default export is + not a function expression. +- Fenced TypeScript (a code block plus a type annotation) refused even though the model produced + runnable logic. +- Tool-call budget charges for refusals: `requests` longer than the program executions, and a budget + exhausted while every outcome was a refusal. +- After a durable resume, the consecutive-refusal streak resets to zero, so alternating + refusal/resume cycles never reach the stop limit. + +## What Didn't Work + +- **`export default ()` wrapping.** A parenthesized expression accepts exactly one expression. + Statements, declarations, and top-level `await` are module-level syntax and cannot be parenthesized. +- **A hand-rolled normalizer.** It grew shape-by-shape and still missed fenced TypeScript. Replaced + with the published normalizer from `@cloudflare/codemode`, then TypeScript stripped with `sucrase`. +- **Trusting the normalizer's output without parsing it.** `normalizeCode` swallows parse errors and + returns the raw source wrapped, so the normalized `export default` module is parsed again with + `acorn`; sucrase and acorn failures take the same structured refusal path. +- **Stripping the code fence after the TypeScript transform.** Sucrase then sees fence markers as + syntax and fails. The fence must be stripped first, so fenced TypeScript reaches the normalizer as + plain JavaScript. +- **Charging a refusal as an ordinary Tool failure.** The program never started, no host call happened, + and no sandbox resource was spent, so a budget unit and a failure-streak entry both mislabel the + event. + +## Solution + +Normalize the model's program shape at the boundary before constructing the module: + +1. Strip one recognized code fence (`js`, `javascript`, `typescript`, `ts`, `tsx`, `jsx`, or bare). +2. Run `normalizeCode` from `@cloudflare/codemode` on the unfenced source. +3. Strip TypeScript with `sucrase`, reporting transform failures against the unfenced source. +4. Parse the resulting `export default` module with `acorn` to catch what the normalizer swallowed. + +An invalid program becomes `CodeSourceError` from `@systemfsoftware/agent/code-executor` with +`reason: 'invalid'`, a `line L, column C` message, the offending line, and a valid +`async () => ({ ok: true })` example. + +Classify the refusal as its own boundary outcome instead of a Tool failure: + +- `CodeModeFailure` carries `boundaryRefusal: true`; the engine sees the source error as a refusal, not + as a program that ran and failed. +- The engine refunds the charged Tool calls through the `releaseToolCalls` seam of the budget hook + built by `toRunBudgetHook`; the seam is infallible and requirement-free, so spreading a budget hook + into a child Run cannot widen that Run's error or requirement types. +- Refunded calls are excluded from declared-call policy usage in the journal and continuation + projections, so they never appear as executed calls. +- Three consecutive refusals stop the Run with `CodeModeBoundaryRefusalLimitExceeded`; any other + terminal outcome resets the streak. + +Make the streak survive durable resume without changing the record format: + +- `RunJournalProjection` and `projectRunJournal` derive `consecutiveBoundaryRefusals` from the settled + Tool results in declaration order, refusing results increment and any other terminal outcome resets. +- `DurableAgentRuntime` seeds `RunResumeUsage` from that projection, so a resumed Attempt continues the + count instead of restarting at zero. +- No durable record schema gains a field; `pnpm check:record-format` stays compatible. + +Keep unpublished boundary modules out of the package source root: `pnpm check:exports` requires them +under the package's internal directory. + +## Why This Works + +The original defect conflated three separate decisions: what a model program may look like, whether a +refusal consumed runtime resources, and how a stop policy survives resume. Normalizing before wrapping +makes the module contract match the producer's real output instead of one shape of it. Separating a +refusal from a Tool failure keeps budget and policy accounting honest: a program that never started +cannot spend a unit or advance a failure streak. Deriving the refusal streak from canonical records +makes resume continuity a projection, not new durable state, so the stop policy holds across Attempts +without a format migration. + +### Invariants + +- **Normalization precedes module construction.** A boundary that wraps model output must first accept + every shape its producer emits, and validate the normalized module rather than the raw source. +- **A refusal that never started code consumes no runtime resource.** It is not a Tool call, not a + failure streak entry, and not a budget unit; it advances only its own dedicated counter. +- **A counter that gates a stop must survive resume.** Persist it in the record format or derive it + from canonical records; never reset it to zero at Attempt start. +- **New durable state needs a format decision.** If the value can be derived from records already + owned by the Run, derive it instead of growing the record schema. + +## Prevention + +- Keep the executor shape corpus covering a bare expression, a statement list with declarations, and a + fenced TypeScript program with a type annotation and top-level `await`. The corpus lives in the + platform package's Code Mode executor test. +- Keep engine tests that assert both sides of the refund: a refusal leaves the budget untouched and a + resumed Attempt continues the refusal streak until the dedicated stop fires. +- Treat `pnpm check:exports` as the placement gate: an unpublished module at a package source root fails + it, and internal boundary modules belong under the package's internal directory. +- Run `pnpm check:record-format` whenever durable state changes; prefer record-derived projections over + new persisted fields. +- In review, require a boundary rejection to be classified before it is charged: if the program never + ran, refund the Tool call and count it toward the dedicated refusal stop. + +## Related Issues + +- PR #78 (open, unmerged as of this writing): accepts normalized Code Mode programs and stops repeated + boundary refusals without charging them. From 26cf62cd5a675fbff6948a7972a39038c39a8372 Mon Sep 17 00:00:00 2001 From: systemfsoftware-bot <318394648+systemfsoftware-bot@users.noreply.github.com> Date: Wed, 2 Dec 2026 14:34:37 -0500 Subject: [PATCH 10/11] fix(agent): a boundary refusal is classified only from a failed settlement Three durable classifiers (the journal's settled-call metadata, the continuation fold and the child usage count) matched the refusal envelope on the result alone, while the journal's refusal streak also required a failure. A successful result with the envelope's shape would then have been refunded on one side and reset the streak on the other, and the continuation/journal accounting check would have refused the resume. The one predicate now matches a failed settlement carrying the envelope, and every engine and durable site passes the settlement. --- .../src/core/internal/code-mode-refusal.schema.ts | 7 ++++++- packages/effect-agent/src/durable/DurableAgentRuntime.ts | 2 +- packages/effect-agent/src/durable/RunContinuation.ts | 2 +- packages/effect-agent/src/durable/RunJournal.ts | 2 +- .../effect-agent/src/durable/internal/journal-metadata.ts | 2 +- packages/effect-agent/src/engine/internal/agent-runtime.ts | 4 ++-- 6 files changed, 12 insertions(+), 7 deletions(-) diff --git a/packages/effect-agent/src/core/internal/code-mode-refusal.schema.ts b/packages/effect-agent/src/core/internal/code-mode-refusal.schema.ts index fb076812d..0d14fae50 100644 --- a/packages/effect-agent/src/core/internal/code-mode-refusal.schema.ts +++ b/packages/effect-agent/src/core/internal/code-mode-refusal.schema.ts @@ -4,5 +4,10 @@ const CodeModeBoundaryRefusalEnvelope = Schema.TaggedStruct('CodeModeFailure', { boundaryRefusal: Schema.Literal(true), }) +const CodeModeBoundaryRefusalSettlement = Schema.Struct({ + isFailure: Schema.Literal(true), + result: CodeModeBoundaryRefusalEnvelope, +}) + /** @internal */ -export const isCodeModeBoundaryRefusal = Schema.is(CodeModeBoundaryRefusalEnvelope) +export const isCodeModeBoundaryRefusal = Schema.is(CodeModeBoundaryRefusalSettlement) diff --git a/packages/effect-agent/src/durable/DurableAgentRuntime.ts b/packages/effect-agent/src/durable/DurableAgentRuntime.ts index 99f3f1b6c..4affe3ecb 100644 --- a/packages/effect-agent/src/durable/DurableAgentRuntime.ts +++ b/packages/effect-agent/src/durable/DurableAgentRuntime.ts @@ -4088,7 +4088,7 @@ const make = Effect.fnUntraced(function*(bindings: ReadonlyArray { if (payload.runId === ownerRunId) { settledById.set(envelope.record.recordId, { isFailure: payload.isFailure, - boundaryRefusal: isCodeModeBoundaryRefusal(payload.result), + boundaryRefusal: isCodeModeBoundaryRefusal(payload), ...(!('toolSelection' in payload) || payload.toolSelection === undefined ? {} : { toolSelection: payload.toolSelection }), diff --git a/packages/effect-agent/src/engine/internal/agent-runtime.ts b/packages/effect-agent/src/engine/internal/agent-runtime.ts index 632083a31..e9955d517 100644 --- a/packages/effect-agent/src/engine/internal/agent-runtime.ts +++ b/packages/effect-agent/src/engine/internal/agent-runtime.ts @@ -2301,7 +2301,7 @@ const executePreparedToolCall = Effect.fnUntraced(function*< name: call.name, encodedResult, isFailure: result.isFailure, - ...(result.isFailure && isCodeModeBoundaryRefusal(result.encodedResult) + ...(isCodeModeBoundaryRefusal({ isFailure: result.isFailure, result: result.encodedResult }) ? { boundaryRefusal: true } : {}), ...(failureCause === undefined ? {} : { cause: failureCause }), @@ -8261,7 +8261,7 @@ const makeResumeTurn = < name: declared.name, encodedResult: settledCall.result, isFailure: settledCall.isFailure, - ...(settledCall.isFailure && isCodeModeBoundaryRefusal(settledCall.result) + ...(isCodeModeBoundaryRefusal(settledCall) ? { boundaryRefusal: true } : {}), ...(settledCall.budgetRejected === undefined From 4326ba74a7cb28e52901ace3809a0e6c2ffab1f4 Mon Sep 17 00:00:00 2001 From: systemfsoftware-bot <318394648+systemfsoftware-bot@users.noreply.github.com> Date: Wed, 2 Dec 2026 14:43:32 -0500 Subject: [PATCH 11/11] style(agents): realign the Boundaries table so dprint passes main has failed format:check since 0ba08c5 left the table misaligned, and CI checks this pull request merged with main. --- AGENTS.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 6210a4c9e..2bbbe0458 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -50,12 +50,12 @@ Load a doc when its trigger fires, not before. ## Boundaries -| Surface | Your limit | -| ---------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------- | -| Graders: the oxlint, dprint and commitlint configs, `oxlint.baseline.json`, `.github/workflows/`, `.mergify.yml` | Never change one to make your work pass; change the implementation. | -| Law: `CODING_STANDARDS.md`, `REVIEW.md`, this file | Change only when the task is to change the law. | -| Vendored: `repos/**` | Read only; update with `git subtree pull`. | -| Everything else | Edit as the task needs. | +| Surface | Your limit | +| ---------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------- | +| Graders: the oxlint, dprint and commitlint configs, `oxlint.baseline.json`, `.github/workflows/`, `.mergify.yml` | Never change one to make your work pass; change the implementation. | +| Law: `CODING_STANDARDS.md`, `REVIEW.md`, this file | Change only when the task is to change the law. | +| Vendored: `repos/**` | Read only; update with `git subtree pull`. | +| Everything else | Edit as the task needs. | Doppler is the only credential store. Never print a secret.