Repository navigation
fix: accept normalized Code Mode programs without charging refused ones - #78
Merged
Merged
Conversation
- 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.
main has failed format:check since 0ba08c5 left the table misaligned, and CI checks this pull request merged with main.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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, beforeentrypoint.runand before any allowlisted tool is invoked:async () => ({ ok: true });async (count: number) => countexport default <expression>, an IIFE, a function declaration, or a statement list with top-levelawaitThe 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(base32fc0fdc) 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-682and:839-846classified the lazyWorkerLoader.load()compile diagnostic asCodeSourceError(reason: 'invalid'), so the failure surfaced before the harness existed.:194-196(source-not-a-function), independently rejecting an IIFE (a Promise) or anexport defaultvalue even when the module compiled.consumeUsagechargedtoolCalls: trace.toolCalls.sizeafter 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, thensucrasestrips TypeScript annotations, thennormalizeCodefrom@cloudflare/codemodeturns the program into one async arrow, and the resultingexport defaultmodule is parsed with acorn before it reaches the Worker Loader. Fence-first ordering is what lets a fenced TypeScript program reachnormalizeCodeas plain JavaScript.CodeSourceError(reason: 'invalid') whose message carries the parser message, its line and column, the offending line, andExample: async () => ({ ok: true }).CloudflareCodeMode.tsmaps the normalizer'sInvalidresult to that tagged source error; the sandbox, bindings, limits, and invoke-once contract are unchanged.Refusal accounting
CodeModeFailuregainsboundaryRefusal: truewhen the executor returnedCodeSourceError; 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 optionalRunBudgetHook.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.CodeModeBoundaryRefusalLimitExceededtag carryinglimit,refusals, andmessage— not a limit kind insideAgentPolicyError, a budget error, or any step-stall tag. Ordinary Tool failures keep the existingrepeatedFailureLimitpolicy; a refusal neither advances nor resets the ordinary failure streak.Decisions and rejected alternatives
normalizeCodeis Cloudflare's own normalizer for this Worker Loader substrate;sucraseis the TypeScript transform@tanstack/ai-code-mode@1.2.0uses.normalizeCodecatches its own parse errors and wraps the raw source, so the normalized module is parsed again; sucrase failures take the same refusal path.PolicyLimitliteral. A newPolicyLimitmember changes the durable settlement enum and the record-format guard rejects that without an approved fresh-store format change. A dedicatedSchema.TaggedErrortravels as the boundederrorTagin the settlement diagnostic and keepspolicyLimitundefined, so existing records and goldens stay byte-stable while the stop value stays distinguishable.CodeSourceErrorremains the sandbox contract's tagged source failure, distinct from runtime and host-call failures.js,javascript,typescript,ts,tsx,jsx, or bare) beforesucraseruns, 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 onacorn@^8.17.0.sucrase@^3.35.1(installed 3.35.1): MIT; maintaineralangpierce; about 56.6M weekly downloads; no registry attestation was returned for 3.35.1.@tanstack/ai-code-mode@1.2.0depends onsucrase@^3.35.0, the same transform this boundary uses.acorn@^8.19.0stays 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 withmaxToolCalls: 1; a later valid program runs after one refusal; three consecutive refusals fail withCodeModeBoundaryRefusalLimitExceeded(limit: 3,refusals: 3); the next model prompt carries{ _tag: 'CodeModeFailure', errorTag: 'CodeSourceError', boundaryRefusal: true }with the syntax message andline 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 realCodeExecutorunder Miniflare/workerd (function expression, trailing semicolon, fence, top-level await, IIFE,export defaultarrow/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) andsquash message.Rollback
Revert the commits; no persisted record format, binding, or configuration changed. The new failure tag,
CodeModeFailurefield, andRunBudgetHookmethod are additive; omittingreleaseToolCallson 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:
journal-metadata.ts,RunContinuation.tsand the child usage count inDurableAgentRuntime.tsmatched the refusal envelope on the settled result alone, while the journal's refusal streak inRunJournal.tsalso requiredisFailure. 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.isCodeModeBoundaryRefusalnow matches a failed settlement (isFailure: trueplus the envelope), and every engine and durable site passes the settlement.Refuted:
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 itspolicyFields, and the streak is not one of them.releaseToolCallsmishandles a negative count." Every caller passes the.lengthof a filtered list, so the count is never negative.boundaryRefusalCountcan count budget-rejected or provider-executed calls."applicationToolResultsholds only application results, and a budget-rejected call never runs, so it can never carryboundaryRefusal.Kept as follow-ups (P2/P3, no behaviour change):
boundaryRefusalCountcould reuseturnToolOutcomes, and the deduction is repeated at three call sites.expect.Verification at 26cf62c:
pnpm --filter @systemfsoftware/agent typecheckandpnpm --filter @systemfsoftware/agent-platform-cloudflare typecheckpass.effect-tsgo oxlint packages/effect-agent/src --type-awareexits 0.dprint checkpasses, andpnpm check:record-formatreports "Record format compatibility verified".AGENTS.md
mainhas failedformat:checksince 0ba08c5 (#79), which left the Boundaries table inAGENTS.mdmisaligned; this pull request carriesdprint 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 touchesAGENTS.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.