diff --git a/.changeset/code-mode-program-normalize.md b/.changeset/code-mode-program-normalize.md new file mode 100644 index 00000000..bdad2273 --- /dev/null +++ b/.changeset/code-mode-program-normalize.md @@ -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. diff --git a/AGENTS.md b/AGENTS.md index 6210a4c9..2bbbe045 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. 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 00000000..7a8ab794 --- /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. diff --git a/packages/effect-agent/src/capabilities/Budget.ts b/packages/effect-agent/src/capabilities/Budget.ts index 70b388ee..f0fb2f8e 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 2d31ef86..6de0680a 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 90e805b2..d0f5834d 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/AgentError.ts b/packages/effect-agent/src/core/AgentError.ts index 61da4c51..300535e5 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/core/internal/code-mode-refusal.schema.ts b/packages/effect-agent/src/core/internal/code-mode-refusal.schema.ts new file mode 100644 index 00000000..0d14fae5 --- /dev/null +++ b/packages/effect-agent/src/core/internal/code-mode-refusal.schema.ts @@ -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) diff --git a/packages/effect-agent/src/durable/DurableAgentRuntime.ts b/packages/effect-agent/src/durable/DurableAgentRuntime.ts index 3a64b8f0..4affe3ec 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 ({ @@ -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, @@ -1189,7 +1192,13 @@ export const projectRunJournalStream = Effect.fnUntraced(function*< ? candidate.id : undefined - policyUsage.toolCalls += calls.length + const refusals = calls.filter((call) => + !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) { @@ -1205,6 +1214,11 @@ export const projectRunJournalStream = Effect.fnUntraced(function*< continue } if (!('isFailure' in result)) continue + if ('boundaryRefusal' in result && result.boundaryRefusal === true) { + consecutiveBoundaryRefusals += 1 + continue + } + consecutiveBoundaryRefusals = 0 if (!result.isFailure && 'toolSelection' in result && result.toolSelection !== undefined) { toolSelection = result.toolSelection } @@ -1614,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/durable/internal/journal-metadata.ts b/packages/effect-agent/src/durable/internal/journal-metadata.ts index ed66089d..dcbb6a0d 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), ...(!('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 aec3bd98..fe0df56e 100644 --- a/packages/effect-agent/src/engine/RunOptions.ts +++ b/packages/effect-agent/src/engine/RunOptions.ts @@ -396,6 +396,7 @@ 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 b6f03e33..e9955d51 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, @@ -74,6 +75,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' @@ -436,6 +438,7 @@ export type AgentRuntimeFailure< | Agent.Failure | ([Agent.UpdatesSchema] extends [never] ? never : UpdateError) | AgentPolicyError + | CodeModeBoundaryRefusalLimitExceeded | ContextBudgetError | ContextOverflowError | CompactionError @@ -563,6 +566,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 +716,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 @@ -1554,6 +1559,7 @@ const decodeResumeUsage = Effect.fnUntraced(function*(input: unknown) { 'children', 'modelRestarts', 'webSearchCalls', + 'consecutiveBoundaryRefusals', ] satisfies ReadonlyArray ) { const value = yield* readSnapshotProperty(input, key, invalid, true) @@ -2295,6 +2301,9 @@ const executePreparedToolCall = Effect.fnUntraced(function*< name: call.name, encodedResult, isFailure: result.isFailure, + ...(isCodeModeBoundaryRefusal({ isFailure: result.isFailure, result: result.encodedResult }) + ? { boundaryRefusal: true } + : {}), ...(failureCause === undefined ? {} : { cause: failureCause }), } terminalResultCommitted = true @@ -2959,19 +2968,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 +2992,58 @@ 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 = ( context: RunContext, trace: TurnTrace, repeatedFailureLimit: number, -): Effect.Effect => - Effect.suspend(() => { - for (const isFailure of turnToolFailures(trace)) { - context.consecutiveToolFailures = isFailure ? context.consecutiveToolFailures + 1 : 0 + budget: + | { readonly releaseToolCalls?: (count: number) => Effect.Effect } + | undefined, +): 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 && budget?.releaseToolCalls !== undefined) { + yield* budget.releaseToolCalls(refusals) + } + if (context.consecutiveBoundaryRefusals >= BOUNDARY_REFUSAL_LIMIT) { + 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`, + }) } if (repeatedFailureLimit > 0 && context.consecutiveToolFailures >= repeatedFailureLimit) { const cause = Cause.fromReasons( @@ -3014,18 +3054,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 +7211,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 +7265,12 @@ const makeTurn = < context, trace, agent.definition.policy.repeatedFailureLimit, + options.budget, ) 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 +7424,13 @@ const makeTurn = < context, trace, agent.definition.policy.repeatedFailureLimit, + options.budget, ) 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 +7793,7 @@ const toolBatchContinuation = < context, trace, agent.definition.policy.repeatedFailureLimit, + options.budget, ) const rolloverResult = orderedResults.length === 1 ? orderedResults[0] : undefined @@ -7818,7 +7857,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 +7887,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 +8261,9 @@ const makeResumeTurn = < name: declared.name, encodedResult: settledCall.result, isFailure: settledCall.isFailure, + ...(isCodeModeBoundaryRefusal(settledCall) + ? { boundaryRefusal: true } + : {}), ...(settledCall.budgetRejected === undefined ? {} : { budgetRejected: settledCall.budgetRejected }), @@ -8796,6 +8838,7 @@ function executeWithCompletion< ), liveChildren: new Set(), consecutiveToolFailures: resumeUsage?.consecutiveToolFailures ?? 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 11b074b7..a55f0b76 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 cdf3f6bc..5e6e49ca 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 3e75d4c6..13adba56 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' @@ -23,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' @@ -104,6 +113,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 +648,140 @@ 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 !== 'CodeModeBoundaryRefusalLimitExceeded') { + throw new Error(`Expected CodeModeBoundaryRefusalLimitExceeded, received ${failure._tag}`) + } + 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) + + 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('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([ + 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 } }) + })) }) diff --git a/packages/platform-cloudflare/package.json b/packages/platform-cloudflare/package.json index 162e14a8..ce7d3e38 100644 --- a/packages/platform-cloudflare/package.json +++ b/packages/platform-cloudflare/package.json @@ -134,12 +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:*", - "puppeteer-core": "catalog:" + "acorn": "^8.19.0", + "puppeteer-core": "catalog:", + "sucrase": "^3.35.1" }, "devDependencies": { "@arethetypeswrong/cli": "catalog:", diff --git a/packages/platform-cloudflare/src/CloudflareCodeMode.ts b/packages/platform-cloudflare/src/CloudflareCodeMode.ts index 1f6c1125..c393b75b 100644 --- a/packages/platform-cloudflare/src/CloudflareCodeMode.ts +++ b/packages/platform-cloudflare/src/CloudflareCodeMode.ts @@ -30,6 +30,7 @@ import * as Queue from 'effect/Queue' import * as Schema from 'effect/Schema' import { safeCauseDiagnostic, safeCauseMessage } from './internal/boundary' +import { normalizeCodeModeProgram } from './internal/CodeModeProgram' /** * The Cloudflare Dynamic Worker `CodeExecutor` adapter (C4 of ADR-0017; @@ -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/internal/CodeModeProgram.schema.ts b/packages/platform-cloudflare/src/internal/CodeModeProgram.schema.ts new file mode 100644 index 00000000..82025f6e --- /dev/null +++ b/packages/platform-cloudflare/src/internal/CodeModeProgram.schema.ts @@ -0,0 +1,8 @@ +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]) + +/** @internal */ +export type CodeModeProgram = typeof CodeModeProgramSchema.Type diff --git a/packages/platform-cloudflare/src/internal/CodeModeProgram.ts b/packages/platform-cloudflare/src/internal/CodeModeProgram.ts new file mode 100644 index 00000000..52c48890 --- /dev/null +++ b/packages/platform-cloudflare/src/internal/CodeModeProgram.ts @@ -0,0 +1,92 @@ +import { normalizeCode } from '@cloudflare/codemode' +import { parse } from 'acorn' +import { transform } from 'sucrase' + +import type { CodeModeProgram } from './CodeModeProgram.schema' + +const PARSE_OPTIONS = { ecmaVersion: 'latest', sourceType: 'module', locations: true } as const +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 PositionedSyntaxError extends SyntaxError { + readonly loc: SourcePosition +} + +const isPositionedSyntaxError = (cause: unknown): cause is PositionedSyntaxError => cause instanceof SyntaxError + +const invalidProgram = (message: string): CodeModeProgram => ({ + _tag: 'Invalid', + message: message.slice(0, MAX_MESSAGE), +}) + +const offendingLine = (text: string, line: number): string => + (text.split('\n')[line - 1] ?? '').trim().slice(0, MAX_OFFENDING_LINE) + +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}`, + ) + +// Acorn reports a zero-based column; sucrase already reports a one-based one. +const syntaxFailure = ( + cause: Cause, + text: string, + columnOffset: number, +): CodeModeProgram => + isPositionedSyntaxError(cause) + ? positionedFailure(cause, text, columnOffset) + : invalidProgram(`SyntaxError: the program could not be parsed\nExample: ${VALID_EXAMPLE}`) + +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(plainSource)) + } catch (cause) { + return syntaxFailure(cause, plainSource, 0) + } +} + +const normalizedModule = (normalized: string): CodeModeProgram => { + const moduleSource = `export default ${normalized}` + + try { + parse(moduleSource, PARSE_OPTIONS) + + return { _tag: 'Normalized', moduleSource } + } catch (cause) { + return syntaxFailure(cause, moduleSource, 1) + } +} + +/** @internal */ +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 da7031ef..a15916ce 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,48 @@ 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' } }, + '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' }, + }) + 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: // 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 8e1c7cd8..23bcaef8 100644 --- a/packages/platform-cloudflare/test/code-mode/conformance-worker.ts +++ b/packages/platform-cloudflare/test/code-mode/conformance-worker.ts @@ -82,6 +82,110 @@ 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: '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: '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 })`, + 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 +355,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 bbbdb0e9..c2fcdbfa 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) @@ -1003,9 +1006,15 @@ 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) + sucrase: + specifier: ^3.35.1 + version: 3.35.1 devDependencies: '@arethetypeswrong/cli': specifier: 'catalog:' @@ -2125,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==} @@ -6587,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'} @@ -8595,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==} @@ -9055,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'} @@ -9155,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} @@ -10375,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': {} @@ -14165,6 +14214,8 @@ snapshots: commander@15.1.0: {} + commander@4.1.1: {} + commander@7.2.0: {} commander@8.3.0: {} @@ -16451,6 +16502,8 @@ snapshots: pify@4.0.1: {} + pirates@4.0.7: {} + platform@1.3.6: {} points-on-curve@0.2.0: {} @@ -17165,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: @@ -17253,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