Skip to content

fix: accept normalized Code Mode programs without charging refused ones - #78

Merged
systemfsoftware-bot merged 12 commits into
mainfrom
fix/code-mode-program-normalize
Dec 2, 2026
Merged

systemfsoftware-bot merged 12 commits into
mainfrom
fix/code-mode-program-normalize

Conversation

@systemfsoftware-maker

@systemfsoftware-maker systemfsoftware-maker commented Dec 1, 2026 •

Copy link
Copy Markdown
Contributor

Reproduction

A model's Code Mode program is refused before it runs whenever it is not exactly one bare function expression. Any of these reach the Worker Loader as export default (<source>); and fail as a module syntax error in roughly 11-21 ms, before entrypoint.run and before any allowlisted tool is invoked:

  • a trailing semicolon: async () => ({ ok: true });
  • a markdown code fence around the program
  • TypeScript annotations: async (count: number) => count
  • a fenced program that also carries TypeScript annotations
  • export default <expression>, an IIFE, a function declaration, or a statement list with top-level await

The failure is returned to the model as a source error, but the declared Tool Call is already charged at the model-response seam, so repeated refused programs consume the Run's Tool-call budget while doing no work. Observed on a model whose Code Mode calls were refused this way: it exhausted its Tool-call budget before saving any work.

Root cause

  • packages/platform-cloudflare/src/CloudflareCodeMode.ts:646 (base 32fc0fdc) built the loaded module as `export default (\n${request.source}\n);`. That is valid only for one expression: a trailing ; produces (async () => {…};), a fence and TypeScript text are not JavaScript, and a statement list is not an expression.
  • CloudflareCodeMode.ts:674-682 and :839-846 classified the lazy WorkerLoader.load() compile diagnostic as CodeSourceError(reason: 'invalid'), so the failure surfaced before the harness existed.
  • The harness itself refused non-functions at :194-196 (source-not-a-function), independently rejecting an IIFE (a Promise) or an export default value even when the module compiled.
  • Budget accounting was unconditional: consumeUsage charged toolCalls: trace.toolCalls.size after the model response and before any Tool ran, and durable policy usage added every declared call, so a refusal could not avoid the charge.

What changed

Normalization

  • platform-cloudflare/src/CodeModeProgram.ts: a surrounding markdown fence is stripped first, then sucrase strips TypeScript annotations, then normalizeCode from @cloudflare/codemode turns the program into one async arrow, and the resulting export default module is parsed with acorn before it reaches the Worker Loader. Fence-first ordering is what lets a fenced TypeScript program reach normalizeCode as plain JavaScript.
  • A still-invalid program becomes CodeSourceError (reason: 'invalid') whose message carries the parser message, its line and column, the offending line, and Example: async () => ({ ok: true }).
  • CloudflareCodeMode.ts maps the normalizer's Invalid result to that tagged source error; the sandbox, bindings, limits, and invoke-once contract are unchanged.

Refusal accounting

  • CodeModeFailure gains boundaryRefusal: true when the executor returned CodeSourceError; a shared schema predicate (core/internal/code-mode-refusal.schema.ts) classifies the settled Tool result in the engine and the durable layers.
  • Budget.releaseToolCalls (and optional RunBudgetHook.releaseToolCalls) return the charged Tool Call at every hierarchy level. The engine refunds each refusal, excludes refusals from the declared-call count carried to the next Turn, and durable policy usage (journal, continuation fold, child usage summary) subtracts them, so policy limits and host budgets never count a refused program.
  • Refusals have their own consecutive counter (cap 3). Reaching it fails the Run with the dedicated CodeModeBoundaryRefusalLimitExceeded tag carrying limit, refusals, and message — not a limit kind inside AgentPolicyError, a budget error, or any step-stall tag. Ordinary Tool failures keep the existing repeatedFailureLimit policy; a refusal neither advances nor resets the ordinary failure streak.

Decisions and rejected alternatives

  • Adopt, not hand-roll. normalizeCode is Cloudflare's own normalizer for this Worker Loader substrate; sucrase is the TypeScript transform @tanstack/ai-code-mode@1.2.0 uses.
  • Validate after normalizing. normalizeCode catches its own parse errors and wraps the raw source, so the normalized module is parsed again; sucrase failures take the same refusal path.
  • Dedicated stop tag, no new PolicyLimit literal. A new PolicyLimit member changes the durable settlement enum and the record-format guard rejects that without an approved fresh-store format change. A dedicated Schema.TaggedError travels as the bounded errorTag in the settlement diagnostic and keeps policyLimit undefined, so existing records and goldens stay byte-stable while the stop value stays distinguishable.
  • No new executor error variant. CodeSourceError remains the sandbox contract's tagged source failure, distinct from runtime and host-call failures.
  • Fence first, then TypeScript. The boundary strips a recognized markdown fence (js, javascript, typescript, ts, tsx, jsx, or bare) before sucrase runs, so a fenced TypeScript program is transformed as plain TypeScript and normalized like any other program; normalizeCode's own fence handling then applies to the already-unfenced source.

Dependency vetting (primary sources)

  • @cloudflare/codemode@0.5.6 (exact): MIT; Cloudflare publishing accounts as npm maintainers; SLSA provenance attestation present (slsa.dev/provenance/v1); about 943k weekly downloads; depends on acorn@^8.17.0.
  • sucrase@^3.35.1 (installed 3.35.1): MIT; maintainer alangpierce; about 56.6M weekly downloads; no registry attestation was returned for 3.35.1. @tanstack/ai-code-mode@1.2.0 depends on sucrase@^3.35.0, the same transform this boundary uses.
  • acorn@^8.19.0 stays a direct dependency for the post-normalization parse; it was already resolved in the workspace lockfile at that version.

Verification

  • pnpm check:record-format -> "Record format compatibility verified".
  • pnpm --filter @systemfsoftware/agent typecheck -> pass; pnpm --filter @systemfsoftware/agent-platform-cloudflare typecheck -> pass.
  • pnpm exec effect-tsgo oxlint <changed files> --type-aware -> no findings; pnpm exec dprint check <changed files> -> pass.
  • pnpm exec vitest run test/engine/agent-runtime.test.ts test/durable/run-journal.test.ts test/durable/worker-host.test.ts -> 44 passed, including: a refusal refunds its charged Tool Call with maxToolCalls: 1; a later valid program runs after one refusal; three consecutive refusals fail with CodeModeBoundaryRefusalLimitExceeded (limit: 3, refusals: 3); the next model prompt carries { _tag: 'CodeModeFailure', errorTag: 'CodeSourceError', boundaryRefusal: true } with the syntax message and line 1, column 14.
  • pnpm exec vitest run --project code-mode test/code-mode/code-mode-executor.test.ts -> 3 passed, including the shape corpus through the real CodeExecutor under Miniflare/workerd (function expression, trailing semicolon, fence, top-level await, IIFE, export default arrow/value/function declaration, function declaration then call, TypeScript-annotated statements and arrow, a fenced TypeScript statement list with top-level await, statement list calling a tool, invalid syntax).

Pending off-host acceptance (CI's): checks / check (pnpm ready) and squash message.

Rollback

Revert the commits; no persisted record format, binding, or configuration changed. The new failure tag, CodeModeFailure field, and RunBudgetHook method are additive; omitting releaseToolCalls on a custom hook keeps refusals charged and is the only behavior a host can opt out of.

Review findings and dispositions (head f84ee6d)

Fixed in 26cf62c:

  • The durable classifiers ignored the failure flag. journal-metadata.ts, RunContinuation.ts and the child usage count in DurableAgentRuntime.ts matched the refusal envelope on the settled result alone, while the journal's refusal streak in RunJournal.ts also required isFailure. A successful result with the envelope's shape would have been refunded on one side and would have reset the streak on the other. The continuation/journal accounting check would then have refused the resume. isCodeModeBoundaryRefusal now matches a failed settlement (isFailure: true plus the envelope), and every engine and durable site passes the settlement.

Refuted:

  • "The continuation fold drops consecutiveBoundaryRefusals, so resume loses the streak." Resume reads the streak from the journal projection (DurableAgentRuntime.ts, resumeUsage.consecutiveBoundaryRefusals: journal.consecutiveBoundaryRefusals). The continuation/journal consistency check compares only its policyFields, and the streak is not one of them.
  • "releaseToolCalls mishandles a negative count." Every caller passes the .length of a filtered list, so the count is never negative.
  • "boundaryRefusalCount can count budget-rejected or provider-executed calls." applicationToolResults holds only application results, and a budget-rejected call never runs, so it can never carry boundaryRefusal.

Kept as follow-ups (P2/P3, no behaviour change):

  • Positions in a parse error after normalization are reported in the coordinates of the normalized module, not the model's source; the offending line is printed, so the program is still locatable.
  • The fence pattern accepts only a program wrapped entirely in one fence.
  • boundaryRefusalCount could reuse turnToolOutcomes, and the deduction is repeated at three call sites.
  • Test failure assertions could use expect.

Verification at 26cf62c:

  • pnpm --filter @systemfsoftware/agent typecheck and pnpm --filter @systemfsoftware/agent-platform-cloudflare typecheck pass.
  • effect-tsgo oxlint packages/effect-agent/src --type-aware exits 0.
  • dprint check passes, and pnpm check:record-format reports "Record format compatibility verified".
  • vitest on agent-runtime, run-journal and worker-host: 46 passed.
  • pre-push passed.

AGENTS.md

main has failed format:check since 0ba08c5 (#79), which left the Boundaries table in AGENTS.md misaligned; this pull request carries dprint fmt AGENTS.md: whitespace and separator dashes only, no wording.

Break glass

Merged with --admin: the approval tooling cannot approve a pull request in a public repository that touches AGENTS.md. Its policy stage requires a verdict citation in the body, and its publication stage refuses that same citation in a public body, so the merge queue never receives an approval. Review is complete on this head: one model review (its one real finding fixed in 26cf62c), two follow-up code reviews with no findings, a policy verdict of "ship" on 4326ba7 for the AGENTS.md realignment, and every CI check green on 4326ba7.

systemfsoftware-bot and others added 10 commits December 1, 2026 20:41
- 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.
… 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.
- 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.
- 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`.
- 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.
- 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.
… 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.
- 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.
- 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.
…ement

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.
kiro-systemf[bot]
kiro-systemf Bot previously approved these changes Dec 2, 2026
main has failed format:check since 0ba08c5 left the table misaligned, and CI
checks this pull request merged with main.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants