Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .changeset/code-mode-program-normalize.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
"@systemfsoftware/agent": patch
"@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 its own `CodeModeBoundaryRefusalLimitExceeded` stop tag, carrying the refusal limit and observed count, instead of a generic policy or budget stop.
12 changes: 6 additions & 6 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
Original file line number Diff line number Diff line change
@@ -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 (<source>)` 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 (<source>)` 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.
43 changes: 37 additions & 6 deletions packages/effect-agent/src/capabilities/Budget.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,7 @@ export interface UsageBudgetNode {
*/
readonly retire: Effect.Effect<void>
readonly consume: (delta: UsageDelta) => Effect.Effect<UsageTotals, BudgetExceeded>
readonly releaseToolCalls: (count: number) => Effect.Effect<UsageTotals>
readonly snapshot: Effect.Effect<UsageTotals>
/**
* Guard stalled model/tool work with the earliest configured ancestor deadline.
Expand Down Expand Up @@ -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<LedgerNode> | undefined => {
const current = state.nodes.get(key)
Expand Down Expand Up @@ -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<string, LedgerNode>()

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,
}
}
Expand Down
5 changes: 5 additions & 0 deletions packages/effect-agent/src/capabilities/CodeMode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,7 @@ export class CodeModeFailure extends Schema.TaggedError<CodeModeFailure>()('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. */
Expand Down Expand Up @@ -928,6 +929,7 @@ const make = <
message,
logs: budgetedLogs(logs, remaining),
...(includeThrown ? { thrown: candidateThrown } : {}),
...(error._tag === 'CodeSourceError' ? { boundaryRefusal: true } : {}),
})
})

Expand Down Expand Up @@ -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,
})
Expand Down
1 change: 1 addition & 0 deletions packages/effect-agent/src/capabilities/RunHooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 =
Expand Down
9 changes: 9 additions & 0 deletions packages/effect-agent/src/core/AgentError.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,14 @@ export class AgentPolicyError extends Schema.TaggedError<AgentPolicyError>()('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>()(
'AgentApprovalDenied',
Expand Down Expand Up @@ -191,6 +199,7 @@ export const AgentError = Schema.Union([
AgentOutputError,
AgentRunDispositionError,
AgentPolicyError,
CodeModeBoundaryRefusalLimitExceeded,
AgentApprovalDenied,
AgentToolAuthorizationDenied,
AgentToolAuthorizationCheckError,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import * as Schema from 'effect/Schema'

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(CodeModeBoundaryRefusalSettlement)
10 changes: 9 additions & 1 deletion packages/effect-agent/src/durable/DurableAgentRuntime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down Expand Up @@ -4084,7 +4085,13 @@ const make = Effect.fnUntraced(function*(bindings: ReadonlyArray<ResolvedBinding
const payload = envelope.record.payload

if (payload._tag === 'ModelResponseRecorded' && payload.runId === childRunId) turns += 1
if (payload._tag === 'ToolCallSettled' && payload.runId === childRunId) toolCalls += 1
if (
payload._tag === 'ToolCallSettled' &&
payload.runId === childRunId &&
!isCodeModeBoundaryRefusal(payload)
) {
toolCalls += 1
}
}

return decodePersisted({ turns, toolCalls }).pipe(Effect.orDie)
Expand Down Expand Up @@ -8097,6 +8104,7 @@ const make = Effect.fnUntraced(function*(bindings: ReadonlyArray<ResolvedBinding
resumeUsage: {
...journal.usage,
...journal.policyUsage,
consecutiveBoundaryRefusals: journal.consecutiveBoundaryRefusals,
...(journal.usage.modelCalls === 0 &&
(journal.usage.unobservedModelCalls ?? 0) === 0 &&
!records.some(
Expand Down
8 changes: 8 additions & 0 deletions packages/effect-agent/src/durable/RunContinuation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import * as Stream from 'effect/Stream'
import { AgentPersistenceCapacityError } from '../core/AgentError'
import type { RunId, SubmissionId, ThreadId } from '../core/Identifiers'
import { ToolCallId } from '../core/Identifiers'
import { isCodeModeBoundaryRefusal } from '../core/internal/code-mode-refusal.schema'
import { utf8ByteLength } from '../core/internal/utf8'
import { resolveEvidence } from './internal/evidence'
import { continuationUsage } from './internal/usage-totals'
Expand Down Expand Up @@ -861,6 +862,8 @@ const advanceFacts = Effect.fnUntraced(function*(
message.role === 'assistant' && typeof message.content !== 'string' ? message.content : []
)

let refusals = 0

for (const call of parts) {
if (call.type !== 'tool-call') continue

Expand All @@ -876,10 +879,15 @@ const advanceFacts = Effect.fnUntraced(function*(
) {
continue
}
if (!call.providerExecuted && isCodeModeBoundaryRefusal(result)) {
refusals += 1
continue
}
accounting.consecutiveToolFailures = result.isFailure
? accounting.consecutiveToolFailures + 1
: 0
}
accounting.toolCalls = Math.max(0, accounting.toolCalls - refusals)
accounting.accountedToolTurn = response.turn
results.clear()
if (position !== 'settling' && position !== 'settled') position = 'awaiting-model'
Expand Down
Loading
Loading