Skip to content

feat(runtime): add restricted CodeMode execution - #1648

Merged
Astro-Han merged 1 commit into
apache:mainfrom
Nyvo-io:feat/1553-codemode-exec
Aug 5, 2026
Merged

Astro-Han merged 1 commit into
apache:mainfrom
Nyvo-io:feat/1553-codemode-exec

Conversation

@Nyvo-io

@Nyvo-io Nyvo-io commented Jul 30, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • add a default-off per-run toolMode with a restricted AST-based CodeMode interpreter
  • expose bounded exec orchestration over the active nestable tool snapshot
  • route nested calls through ToolRuntime with direct-only admission, permissions, abort handling, output/data limits, and durable parent-linked activity
  • mark nested facts as non-model-visible and exclude them from replay, backfill, and recovery projection
  • add restart recovery for an interrupted outer exec, runtime persistence wiring, and focused contract coverage

Verification

  • npm run build
  • npm run lint
  • npm run format:check
  • npm run check:third-party-notices
  • git diff --check
  • CodeMode tests: 33 passed
  • Runtime dist tests: 2846 passed, 9 skipped, 0 failed

Direct mode remains the default and its provider surface is unchanged.

@Astro-Han

Copy link
Copy Markdown
Contributor

I found three P1s and one P2 on b4ef9747.

[P1] Aborting or timing out a cell only rejects the promise held by the interpreter. It does not wait for the underlying ToolRuntime.settleToolCall() to stop. A nested tool that responds late to abort can keep running after exec has settled, perform file or network side effects, and append its durable result afterward. In my reproduction, the outer call rejected after about 25 ms, while the tool performed its side effect and settled around 147 ms.

[P1] Unsupported operators are rejected after their operands have been evaluated. For example, return (await tools.mutate({ id: "x" })) ** 2; calls mutate before returning unsupported_syntax. A retry can therefore repeat an irreversible operation. Please validate the full AST and operator whitelist before executing any tool call.

[P1] The product build paths do not build @maka/code-mode before @maka/runtime. Desktop E2E currently fails before Playwright with Cannot find module "@maka/code-mode". The package-local CLI pretest and desktop smoke paths have the same dependency-order gap, so they depend on a previously populated dist.

[P2] expert_dispatch is missing nesting: "direct_only". It enters the CodeMode tool snapshot and can spawn an expert child from inside exec, unlike the other agent and team tools.

The package boundary itself looks right. I would fix these four production seams and cover the first three with tests rather than redesign the package.

@Nyvo-io

Nyvo-io commented Jul 31, 2026

Copy link
Copy Markdown
Contributor Author

Addressed all four findings in 4ae91a77: aborted or timed-out cells now abort and drain owned host tool operations before exec settles (including fatal errors discovered during drain); the complete AST and operator whitelist are validated before any tool call can execute; every product/test build path now builds @maka/code-mode before @maka/runtime, with a build-order regression test; and expert_dispatch is now direct_only. I also rebased the single commit onto the latest main and added focused coverage for the failure paths. Local build, typecheck, lint, formatting, Code Mode tests (37/37), script tests (228/228), and affected runtime tests pass; GitHub CI typecheck, test, and e2e are all green.

@Nyvo-io
Nyvo-io marked this pull request as ready for review July 31, 2026 05:29
@Astro-Han

Copy link
Copy Markdown
Contributor

I took another pass over 4ae91a77. The package split and the decision to route nested calls through ToolRuntime still make sense to me. I have a few questions about the remaining correctness and test gaps.

P1

  1. Could we make nested dispatch compatible with the production SQLite ledger validator? ToolRuntime now puts parentToolCallId and parentOperationId on the tool_dispatch T1 refs (packages/runtime/src/tool-runtime.ts:1496), while validateToolLedgerEventLane only permits operationId and toolCallId for that lane (packages/core/src/tool-ledger-scanner.ts:446). SqliteRuntimeStore runs that validation before persisting the event (packages/storage/src/sqlite-runtime-store.ts:425), so a real SQLite-backed CodeMode call fails before dispatch. The current backend test uses a permissive in-memory event sink and does not exercise this contract. Would it be simpler to keep parent linkage in a field owned by the ledger schema, or extend the schema and cover the production store path?

  2. Should terminal execution failures be made uncatchable by cell code? A cell can currently convert abort, wall-time, and durable dispatch failures into a successful result. For example, return await Promise.allSettled([tools.hang({})]); can return ok: true after the wall-time limit, and try { await tools.fail({}); } catch { return "suppressed"; } can hide a fatal T2 failure. This comes from routing host failures through ordinary JavaScript promise rejection and try/catch (packages/code-mode/src/interpreter.ts:414, packages/code-mode/src/interpreter.ts:1129). Could the interpreter keep a separate terminal-failure latch and check it before committing success at interpreter.ts:254?

  3. Could hidden nested tool content be excluded from history compaction and summarization? Hidden events are filtered from normal replay, but history-compact.ts currently selects content events by character count alone (packages/runtime/src/history-compact.ts:256, packages/runtime/src/history-compact.ts:984), includes their excerpts (history-compact.ts:890), and sends the folded history to the summarizer (packages/runtime/src/ai-sdk-compaction.ts:455). In a repro, a hidden argument containing DO_NOT_REPLAY appeared verbatim in the generated summary. Would it be safer for visibility to be enforced at the shared compaction input boundary?

P2

  1. Can unsupported syntax and dangerous member access be rejected before evaluating their operands? At the moment the interpreter evaluates the callee/object first and only then rejects the operation (packages/code-mode/src/interpreter.ts:604-708). Both return (await tools.mutate({ id: "x" }))(); and return (await tools.mutate({ id: "x" }))["constructor"]; invoke the tool once before failing. Could validateSyntax cover these shapes so invalid programs remain effect-free?

  2. What should guarantee that the post-failure drain converges? execute() waits for every raw host operation without a deadline (packages/code-mode/src/interpreter.ts:258-263). A non-cooperative tool or a permission-suspended nested call can therefore keep the entire CodeMode invocation pending after the wall-time limit. A simple drain timeout would reopen the late-side-effect problem, so would the cleaner owner be ToolRuntime, with nested admission cancellation plus a settlement contract that the interpreter can safely await?

  3. Do we want explicit bounds for synchronous intermediate amplification? The limits cover source size, steps, wall time at checkpoints, and the final serialized result, but operations such as repeated string growth followed by split() can allocate large intermediates between checkpoints (packages/code-mode/src/interpreter.ts:644, interpreter.ts:1048, interpreter.ts:1074). For example, a one-millisecond cell can build a 1,048,576-element array and still return successfully. Since full RSS containment is outside this issue, would targeted operand and collection-size guards be enough for the restricted subset?

  4. Could maxResultBytes be enforced before publishing the nested result? ToolRuntime currently appends and persists the full result first (packages/runtime/src/tool-runtime.ts:1161, tool-runtime.ts:1200), then the interpreter rejects it as oversized (packages/code-mode/src/interpreter.ts:1186-1187). This means the limit protects the cell result but not the event stream, durable store, or in-memory operation record. Would the result-size policy fit better at the ToolRuntime publication boundary?

  5. Could toolMode be the sole source of truth for CodeMode ownership? There are a few name- and fallback-based paths today: Direct mode rejects a caller-provided tool named exec (packages/runtime/src/ai-sdk-backend.ts:718), recovery infers CodeMode from the tool name (packages/runtime/src/recovery-resolver.ts:123), and any runtime value other than "direct" falls into CodeMode (ai-sdk-backend.ts:239). That can break an existing Direct custom tool named exec, misclassify legacy recovery, and fail open on an invalid mode. Would validating toolMode once on the Run and consulting it everywhere remove these exceptions?

  6. Could the permission test exercise an actual denied nested MCP or custom call? The current gateability assertion only checks that classifyToolUse() returns a category (packages/runtime/src/__tests__/code-mode-backend.test.ts:101-145), while unknown tools already classify as custom_tool (packages/core/src/permission.ts:352-353). It would pass even if nested dispatch bypassed the real policy. A test through the production permission path, with an explicit denial and no tool side effect, seems like the invariant we need here.

  7. Is enabling CodeMode only through the programmatic SessionManager API the intended scope for this PR? SessionManager forwards toolMode, but the Desktop, CLI/TUI, headless public configuration, and Runtime Host entry points do not currently expose it. If this PR is intentionally runtime-only, could that be stated and tracked separately? If it is meant to be usable from product surfaces now, one public edge should probably be covered end to end.

P3

  1. Should var either be rejected or use function scope? It is currently accepted but stored in the same block environment as let and const (packages/code-mode/src/interpreter.ts:302, interpreter.ts:323, interpreter.ts:1248), which gives supported-looking syntax different semantics. Rejecting it may be the smaller option for this subset.

  2. Should zero-argument Array.sort() match JavaScript's default UTF-16 string ordering? The implementation uses localeCompare (packages/code-mode/src/interpreter.ts:644), so results can vary by locale and differ from normal JavaScript. A locale-independent comparator would keep executions deterministic.

  3. Could @maka/code-mode be added to the stale-dist gate? The package builds committed dist output, but scripts/check-stale-dist.mjs does not include it. Without that check, source and published artifacts can drift even while the normal test suite passes.

  4. Are CodeModeToolDefinition.description, inputSchema, and codeModeInputSchema() intended for an upcoming in-cell discovery surface? The interpreter currently consumes tool names only. If no discovery API is planned in this PR, removing the unused metadata would keep the new contract smaller.

I also rechecked the previous review. The build-order fix and the expert_dispatch direct-only fix look complete. The original abort and operator reproductions are fixed, but the broader termination and preflight invariants still have the cases above.

I do not think these require another execution path or a rewrite of the package. Most of them can be fixed at the existing owners: ledger validation, compaction visibility, interpreter termination, ToolRuntime settlement, and Run-level toolMode validation.

@Nyvo-io

Nyvo-io commented Jul 31, 2026

Copy link
Copy Markdown
Contributor Author

Implemented and reviewed in a1dcae3b as one consolidated commit.

This addresses the review round end to end: SQLite-compatible nested T1 parent refs with real-store coverage; fatal nested failure latching; hidden nested events excluded from history compaction; full Code Mode AST/operator/member preflight; bounded intermediate strings and collections; nested result limits enforced before ToolRuntime publication; abort-aware user-question and sandbox-boundary waits; real nested-tool settlement before exec completes; explicit toolMode validation and recovery ownership; expert_dispatch kept direct-only; deterministic UTF-16 sorting; reduced Code Mode metadata; and stale-dist coverage for @maka/code-mode.

Local verification is clean: Code Mode 51/51, Storage 814/814, Runtime 2861 passed (9 environment skips), script tests 228/228, full product build, typecheck, lint, format, stale-dist, and third-party-notice checks. An independent uncommitted review found no introduced correctness issues.

Permission decisions remain owned by the existing host/ToolRuntime permission path; nested Code Mode calls use that path and do not bypass it. This PR intentionally exposes toolMode at the programmatic SessionManager/runtime boundary; Desktop, CLI/TUI, and headless configuration surfaces remain unchanged. Abort draining relies on tool implementations observing ctx.abortSignal and settling; Runtime awaits that settlement rather than detaching with a timeout.

@Astro-Han Astro-Han left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approving this round. I do not think the remaining findings rise to P1 or justify another execution path or package rewrite. The interpreter boundary and the decision to keep nested calls inside ToolRuntime still look like the right design.

I did find a few follow-up issues that seem worth addressing.

P2

  1. Could output copying use a cumulative traversal budget rather than checking only each local collection and the completed result? copyPlainData() removes an object from seen after each branch, so a small shared DAG is expanded once per reference:

    let x = [0];
    for (let i = 0; i < 18; i += 1) x = [x, x];
    return x;

    With maxOutputBytes: 1024, this eventually reports the expected limit error, but only after reaching about 228 MB peak RSS in my repro. The default depth of 32 permits a much larger expansion. This is not general RSS containment, but a running node or serialized-byte budget inside copyPlainData would make the existing output limit effective before the copy is allocated.

  2. Could the hidden-event predicate also be applied to stale-result archiving and synthesis-cache construction? History compaction now excludes hidden events, but collectStaleToolResultArchiveCandidates() accepts hidden function_response events, and buildSynthesisArchiveExcerpts() later includes their contents in a synthesis block whose synthetic RuntimeEvent is visible by default.

    I reproduced the full projection with a hidden nested result containing DO_NOT_REPLAY: it was archived, written into a synthesis summary, and replayed through a default-visible text event. This requires archive retrieval plus synthesis cache to be enabled, so I would not rate it as P1, but it breaks the invariant that the model sees nested results only through the enclosing cell result.

  3. Could Object.fromEntries avoid recomputing Object.keys(output) for every entry? The current loop is O(n²). With 30,000 entries and maxWallTimeMs: 5, the cell blocked for about 6.4 seconds and still returned ok: true. Tracking the unique-key count incrementally would remove most of this cost; a wall-time checkpoint around synchronous helpers would cover similar cases.

  4. Could ToolRuntime and the interpreter share one serialized-byte definition for maxResultBytes? ToolRuntime counts a top-level string as raw UTF-8, while the interpreter counts its JSON representation. Ten NUL characters are 10 raw bytes but 62 serialized bytes; with a 32-byte limit, ToolRuntime publishes the result to T2/messages and the interpreter rejects it afterward. Measuring the persisted representation before publication would close that gap.

  5. Since the cell snapshot and every tools.<name> reference are static, could unknown tool names be included in preflight validation? In this cell:

    await tools.write({});
    return await tools.typo({});

    write executes before the cell reports unknown_tool. A retry can therefore repeat the first side effect even though the missing tool was knowable before execution.

  6. Could the gateability contract exercise a real denied nested MCP or custom tool? The current test proves that classifyToolUse() returns a ToolCategory, but unknown tools always fall back to custom_tool, and that classification is not itself an execution decision. ToolRuntime does not consume it as a common allow/prompt/block gate, while the MCP wrapper calls its provider directly. A denial test that asserts the implementation was not called would establish the intended invariant more directly.

  7. Could toolMode be validated before the AgentRun record is created? The backend now rejects invalid values, but AgentRun assigns the runtime value and writes it into the run header before backend projection. An untyped caller can therefore persist toolMode: "typo" and leave a header that decodeAgentRunHeader() rejects later. The Run boundary seems like the single owner for this validation.

  8. Could sandbox abort cleanup keep the durable denial under lifecycle ownership? The abort handler removes the request from the in-memory registry, then starts the durable deny as fire-and-forget and suppresses rejection. If that write fails, endTurn() can no longer find the request and cleanup still reports success, leaving a durable pending request until restart recovery.

P3

  1. Should an uninitialized let use internal undefined semantics?

    let x;
    return { isNull: x === null, kind: typeof x };

    The interpreter currently returns { isNull: true, kind: "object" }; JavaScript would return { isNull: false, kind: "undefined" }. Converting undefined to null at the final plain-data boundary is fine, but doing it when the variable is declared changes control-flow and default-value behavior inside the cell.

I also rechecked the previous findings. The SQLite ledger path, fatal failure latch, hidden history compaction, AST/operator preflight, result publication ordering for ordinary objects, recovery ownership, deterministic sorting, and stale-dist coverage are now fixed and covered by focused tests.

The remaining issues fit the existing owners: plain-data copying, visibility projection, interpreter helpers and preflight, ToolRuntime result measurement and settlement, and Run-level mode validation. I do not see a reason to redesign the package around them.

@Nyvo-io
Nyvo-io force-pushed the feat/1553-codemode-exec branch from a1dcae3 to 4e8d278 Compare August 1, 2026 10:40
@Nyvo-io

Nyvo-io commented Aug 1, 2026

Copy link
Copy Markdown
Contributor Author

Rebased the consolidated fix onto current main and pushed it as 4e8d278ea (one commit).

Final verification is clean: full build; Code Mode 66/66; Runtime 2806 passed, 9 skipped; typecheck, lint, format, script, stale-dist, third-party-notice, and diff checks all pass. GitHub CI changes, typecheck, test, and e2e are all green. An independent read-only review found no actionable correctness issue.

No further code changes were made after the approved review; the new head is ready for re-review/merge.

@Astro-Han Astro-Han left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the update. I did another fresh-eye pass across the interpreter, runtime recovery, tool boundaries, and tests. The earlier findings appear to be addressed, and the focused tests and CI are green.

I found a few follow-ups worth considering. None of these need to block this PR:

P2

  • Could AgentRun.execute() pass the effective toolMode into AiSdkFlow.run()? The run header and invocation context preserve code_mode, but the flow input currently omits it, so direct users of the exported AgentRun API fall back to Direct mode.

  • Should plan-control tools such as SubmitPlan be marked direct_only for now? A nested call updates the plan store, but its result does not pass through the top-level handlePlanToolResult path, so the approval event, UI handoff, and planning-turn termination do not happen.

  • Could client-capability recovery preserve the original nested activity identity? After a Host restart, the synthesized response currently loses origin: code_mode, modelVisibility: hidden, and its parent references. That may allow the recovered result to be treated as an ordinary visible archive or synthesis candidate.

  • What settlement guarantee do we want when a host tool ignores its abort signal? The interpreter aborts the cell at its wall-time limit, but then waits indefinitely for every host operation to settle. A non-cooperative tool can therefore keep both the cell and user Stop pending.

P3

  • Could the UI materializer retain origin, modelVisibility, parentToolCallId, and parentOperationId? The runtime read model preserves them, but the final ToolActivityItem drops them, so nested activity cannot later be grouped under its outer exec.

Overall, the core design is much stronger after this update: nested calls reuse the existing runtime authority, Direct mode remains unchanged, hidden results are excluded from normal replay, and the limit/abort/durability tests are substantially better. Approving with the follow-ups above.

@Nyvo-io
Nyvo-io force-pushed the feat/1553-codemode-exec branch from 4e8d278 to 47edded Compare August 1, 2026 18:41
@Nyvo-io

Nyvo-io commented Aug 2, 2026

Copy link
Copy Markdown
Contributor Author

Rebased the consolidated fix onto current main as 47edded42 and rechecked the full local suite. The new CI run is green: changes, typecheck, test, e2e, and storybook. No code changes were made after the approved review; this is ready for maintainer re-review and merge.

@Nyvo-io
Nyvo-io force-pushed the feat/1553-codemode-exec branch from 47edded to 543da55 Compare August 2, 2026 09:33
@Nyvo-io

Nyvo-io commented Aug 2, 2026

Copy link
Copy Markdown
Contributor Author

Rebased the PR onto the latest upstream/main (7a124b8) and resolved the only conflict in packages/cli/package.json by preserving the @maka/code-mode build order and upstream runtime-host build step.\n\nCurrent head: 543da55 (one consolidated commit; no fixup commits).\n\nFinal verification:\n- npm ci\n- full product build, typecheck, lint, format, stale-dist, third-party-notice, and diff checks\n- script tests: 14/14\n- full npm test: Code Mode 66/66; 1303 passed, 1 environment skip, 0 failures\n- full desktop E2E locally: 76/76\n\nThe new CI run passed changes, typecheck, test, and storybook. Its E2E job had 75/76 passes and one timeout in the unchanged project-management.spec.ts. The same test and the full E2E suite pass locally, and the immediate upstream/main CI run also passed E2E. No further behavioral changes were made after the approved review. Please re-review the current head and rerun E2E if needed.

@Astro-Han Astro-Han left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review findings (independent deepseek-v4-flash review, 3 passes)

The AST interpreter's sandbox surface and the hidden-fact propagation are genuinely strong. However the earlier approval no longer covers the current head, and one P1 remains open.

P1 — interrupted nested CodeMode tool operations vanish from the recovery projection; the model gets no "side effects may have occurred" warning

  • Predicted failure: when a code_mode run is killed mid-cell (crash / wall-time / fatal error) after a nested tool already produced side effects (bash ran, file written) but before its outcome committed, recovery composes an interrupted message only for the outer exec (buildInterruptedCodeModeOutcomeCommits explicitly skips callEvent.origin === 'code_mode' / hidden calls). The resume projection (projectToolOperations, runtime-resume.ts) then drops the nested operation's indeterminate decision, so buildResumePlanFromRuntimeEvents yields requiresVerification=false, disposition='safe_replay' with no INDETERMINATE_TOOL_RESULT_DIRECTIVE. The model sees only "interrupted" and naturally re-runs the whole exec — re-executing non-idempotent nested tools (bash, write_file, MCP).
  • Violated invariant: same-window interrupted tool calls always carry the indeterminate warning in direct mode; hidden ≠ "never happened" (side effects are not atomic).
  • Fix direction: count nested indeterminate decisions into requiresVerification (or include the caution in the synthetic interrupted message), and add a recovery test with outer exec + nested hidden in-flight op.

P2 — loop-gate state is shared between the outer turn and nested cells

recordLoopGateOutcome in executeTool's finally runs for both provider and nested calls; repeated identical failures inside a cell push the shared failedToolCallStreak, so the outer model's next identical call can be blocked ("This exact call keeps failing…") and vice versa. Two different responsibility subjects share one counter. Consider isolating by origin.

P2 — abort-path drain is unbounded

interpreter.ts execute() catch does Promise.allSettled([...ownedPromises, ...hostToolOperations]) with no timeout; a nested impl that ignores the abort signal hangs the exec call forever. A wall-time-bounded drain is cheap.

P2 — nesting defaults wide open

nesting?: 'nestable' | 'direct_only' defaults to nestable, and nestableToolSnapshot sweeps in every active non-direct_only tool (only 9 marked). Every future tool — including any MCP server — automatically becomes callable inside exec. For a mode sold as "restricted", the safe default is direct_only with explicit opt-in.

P2 — continuation-replay path does not filter hidden nested events

continuation-replay.ts blocks on any indeterminate decision (tool_recovery_unsettled), while runtime-resume.ts was patched in 3 places to skip hidden ops — inconsistent. With safe-boundary resume enabled, a mid-cell interruption parks the session. (Same root class as P1; fix at a single decision point if possible.)

P2 — commitToolOutcome failures can break the best-effort recovery loop

The new code-mode block in recoverAgentRunsFromLedger awaits runtimeCommitSink.commitToolOutcome(outcome) with no try/catch, unlike every other branch (recoverOr semantics). A commit-store write error aborts recovery for all other sessions.

Gate: FAIL — P1 must be fixed (or explicitly deferred with rationale) before merging; P2s should be handled or deferred with reasons.

Suggested minimal merge set: P1 fix + one recovery test; loop-gate isolation; bounded drain; flip nesting default (or document the model explicitly); continuation-replay hidden filter; wrap commitToolOutcome.

@Nyvo-io

Nyvo-io commented Aug 3, 2026

Copy link
Copy Markdown
Contributor Author

Updated the current head in one consolidated commit: cbc67baf.

The P1 recovery gap is fixed. Hidden nested CodeMode calls remain excluded from the model-facing operation projection, but an indeterminate hidden call now produces a pending-tool diagnostic, sets requiresVerification, and blocks automatic replay of the enclosing execution. Added a regression test covering an interrupted outer exec with an in-flight hidden nested call.

Also addressed two related issues:

  • loop-gate signatures are scoped by execution origin, so nested CodeMode failures cannot suppress a later provider call;
  • best-effort startup recovery now isolates commitToolOutcome write failures and continues processing other runs (strict recovery still fails closed).

Validation is clean: Code Mode 66/66, Runtime 2740 passed / 9 skipped, package build/typecheck, Biome, and diff checks.

I rechecked the remaining follow-ups:

  • continuation replay already blocks every indeterminate/parked recovery decision, including hidden nested operations, so no visibility filter is needed there;
  • the abort drain intentionally waits for owned tool settlement to avoid detaching late side effects; a bounded drain needs a separate settlement contract;
  • nesting remains the existing explicit opt-out contract for the current tool inventory; changing the default would be a broader catalog/API change.

@Astro-Han

Copy link
Copy Markdown
Contributor

Nice work on the recovery fix in cbc67baf; routing nested calls through ToolRuntime with the hidden-activity identity was the right call. I took an independent pass over the current head, fresh eyes, re-checking the earlier findings against the code. One P1 and a few P2s came out. None of it changes the architecture.

P1: nested tool arguments have no byte budget

callTool (packages/code-mode/src/interpreter.ts ~:1423-1430) copies arguments with copyPlainData(..., maxCollectionItems) and applies no byte limit, where the result path does (assertByteLimit(copied, maxResultBytes) at ~:1446). A cell can build a value inside every default limit (around 16 doublings of [x, x] over one shared 1 MiB string gives ~65k references, under maxCollectionItems and maxSteps) whose JSON serialization runs to tens of GB. The runtime materializes it: byteLength(persistedArgs) (tool-runtime.ts ~:2626-2629, used at :950) and the JSONL persistence both JSON.stringify the args, expanding the shared references. OOM / Invalid string length before any limit fires.

Fix: assertByteLimit(input, this.limits.maxIntermediateBytes, 'tool arguments') after the copyPlainData in callTool, plus one test asserting a limit_exceeded diagnostic and zero tool side effects.

P2

  1. Continuation-replay keeps hidden events in the replay context. continuation-replay.ts (:193) filters only trimmedIds; the model plan already skips modelVisibility: 'hidden', so hidden nested results stay in replayRuntimeEvents and runtimeContext (persisted in the continuation payload, counted by the context budget), while the resume path filters them (runtime-resume.ts ~:900-902). No model-facing leak, but the two paths diverge. One line in buildContinuationReplaySegment aligns them.

  2. AgentRun.execute() drops toolMode. The flow input at agent-run.ts (~:517-523) does not forward it, and AiSdkFlow.run reads only input.toolMode (ai-sdk-flow.ts :705), so a code_mode run through execute() falls back to direct silently. The kernel path is fine; this seam missed the wiring.

  3. String.split with a regex separator returns the wrong result silently. The separator goes through coerceToIntermediateString (interpreter.ts ~:1160-1162), so 'a1b2c'.split(/\d/) returns ["a1b2c"] with ok: true (JS: ["a","b","c"]). The only silent semantic drift I could reproduce. A loud unsupported_syntax for non-string separators, or delegating regex split, would fit the interpreter's design.

  4. Interrupted-commit failure can wedge a run. In session-manager.ts (~:5291-5305) a transient commitToolOutcome failure is swallowed by recoverOr, then the same pass repairs the run to terminal; later passes hit assertRunNotSealed (sqlite-runtime-store.ts :2234) and the interrupted exec outcome never settles, blocking continuation permanently. Only on the transient-failure path. Skipping terminal repair (or retrying the commit) when the interrupted commit fails would cover it.

Non-blocking

  • The MCP network gate in mcp-tools.ts (~:77-92) also changes direct-mode behavior: managed boundaries with restricted network now ask for approval on every MCP call, and tests only cover the nested path. The gate is sound; it needs an explicit direct-mode decision or a test, since the PR claims direct mode is unchanged.
  • While in these files: sortUtf16Values index tiebreak is dead (sort has been stable since ES2019), normalizeError's conditional type is noise, and the 'registers step admission synchronously before settlement awaits' test in tool-runtime-settlement.test.ts has no assertions.

The unbounded abort drain is a deliberate choice, I take it: await tool settlement rather than detach. Just noting it is the one spot a non-cooperative tool can hold the cell open.

中文版

感谢这轮恢复修复,cbc67baf 的处理是对的:嵌套调用走 ToolRuntime 并带上 hidden 活动身份,方向没问题。我独立过了一遍当前 head,逐条复核了之前的结论。发现 1 个 P1 和几个 P2,都不影响架构。

P1:嵌套工具参数没有字节上限

callTool(packages/code-mode/src/interpreter.ts 约 1423-1430 行)复制参数时只做 copyPlainData(..., maxCollectionItems),没有字节限制;结果路径有(约 1446 行的 assertByteLimit(copied, maxResultBytes))。cell 可以在全部默认限内构造一个 JSON 序列化达数十 GB 的值:对同一 1 MiB 字符串做约 16 次 [x, x] 倍增,约 6.5 万个引用,都在 maxCollectionItems/maxSteps 内。runtime 会物化它:byteLength(persistedArgs)(tool-runtime.ts 约 2626-2629 行,950 行调用)和 JSONL 持久化都会对参数 JSON.stringify,把共享引用展开。任何限流触发前就已 OOM 或 Invalid string length。

修复:callTool 里 copyPlainData 之后加 assertByteLimit(input, this.limits.maxIntermediateBytes, 'tool arguments'),再补一个断言 limit_exceeded 诊断且零工具副作用的测试。

P2

  1. continuation-replay 把 hidden 事件留在重放上下文里。 continuation-replay.ts(193 行)只按 trimmedIds 过滤;模型计划已经跳过 modelVisibility: 'hidden',所以 hidden 嵌套结果留在 replayRuntimeEvents 和 runtimeContext 里(进入 continuation payload、被上下文预算计费),而 resume 路径会过滤(runtime-resume.ts 约 900-902 行)。没有模型面泄漏,但两条路径不一致。buildContinuationReplaySegment 里加一行过滤即可对齐。

  2. AgentRun.execute() 漏传 toolMode。 agent-run.ts(约 517-523 行)构造 flow 输入时没带上它,AiSdkFlow.run 只读 input.toolMode(ai-sdk-flow.ts 705 行),所以走 execute() 的 code_mode run 会静默退回 direct。kernel 路径没问题,只是这个 seam 漏了接线。

  3. String.split 遇正则分隔符时静默返回错误结果。 分隔符经过 coerceToIntermediateString(interpreter.ts 约 1160-1162 行),'a1b2c'.split(/\d/) 返回 ["a1b2c"] 且 ok: true(JS 应为 ["a","b","c"])。这是我复现到的唯一静默语义漂移。对非字符串分隔符抛 unsupported_syntax,或直接支持正则 split,更符合解释器的设计。

  4. 中断提交失败可能卡死 run。 session-manager.ts(约 5291-5305 行)里一次瞬态 commitToolOutcome 失败被 recoverOr 吞掉,同一轮继续把 run 修复为 terminal;后续轮次撞上 assertRunNotSealed(sqlite-runtime-store.ts 2234 行),中断的 exec outcome 永远无法结算,continuation 永久阻塞。只在瞬态失败路径触发。中断提交失败时跳过 terminal 修复(或重试提交)即可覆盖。

非阻断

  • mcp-tools.ts(约 77-92 行)的 MCP 网络门禁也改了 direct 模式行为:managed 边界且网络受限时,每次 MCP 调用都要审批,而测试只覆盖 nested 路径。门禁本身是对的,但既然 PR 声称 direct 模式不变,需要显式的 direct 模式决策或补个测试。
  • 顺手可清理:sortUtf16Values 的 index tiebreak 是死代码(ES2019 起 sort 稳定)、normalizeError 的条件类型、tool-runtime-settlement.test.ts 里那个零断言的 'registers step admission synchronously before settlement awaits'。

无界 abort drain 应该是你刻意选的:等工具结算而不是脱离。只是提醒这是唯一一个不配合的工具能把 cell 挂住的地方。

@Nyvo-io

Nyvo-io commented Aug 3, 2026

Copy link
Copy Markdown
Contributor Author

Following up on the current head cbc67baf: the blocking recovery P1 and the related loop-gate/recovery-write issues are fixed and covered by regression tests. Local Code Mode, Runtime, build/typecheck, Biome, and diff checks are clean. No further code changes are needed after this consolidated commit; the remaining follow-ups are documented above as intentional scope/design boundaries. Please re-review the current head when convenient.

@Nyvo-io

Nyvo-io commented Aug 4, 2026

Copy link
Copy Markdown
Contributor Author

Applied the remaining review fixes in one consolidated commit: 969e8fda0.

  • Enforced maxIntermediateBytes on copied nested tool arguments before ToolRuntime publication, with a zero-side-effect regression test.
  • Excluded hidden events from continuation replay context.
  • Forwarded the effective toolMode through AgentRun.execute().
  • Made regex String.split separators fail explicitly as unsupported syntax.
  • Kept recovery runs non-terminal when interrupted outcome commits fail, with two best-effort attempts (strict recovery remains fail-closed).
  • Regenerated the production third-party notice inventory.

Local verification is clean: full build; Code Mode 68/68; Runtime 2733 passed, 9 skipped, 0 failed; typecheck, lint, format, stale-dist, third-party-notice, and diff checks all pass. An independent read-only review found no actionable correctness issue. Please re-review the current head.

@Nyvo-io
Nyvo-io force-pushed the feat/1553-codemode-exec branch from 969e8fd to 28d258c Compare August 4, 2026 09:12
@Nyvo-io

Nyvo-io commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor Author

Updated the PR in one consolidated commit: 28d258cb. All findings from the latest review are addressed, including bounded nested arguments, hidden-event replay filtering, effective tool-mode propagation, explicit regex split rejection, and retry-safe interrupted recovery. Local review and verification are clean, and all GitHub CI checks are green. @Astro-Han, please re-review the current head.

@Astro-Han Astro-Han left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for working through the previous review rounds. I reviewed the complete PR again at 28d258cb, including the interpreter, ToolRuntime integration, durable recovery, model-visibility projections, and the relevant tests.

The overall architecture still looks sound: the capability-less interpreter is the right boundary, nested calls re-enter the existing ToolRuntime, and the durability/recovery design is coherent. I do not think this needs an architectural rewrite.

I found one remaining P1, left inline, in the same effect-free-preflight invariant as an earlier fix. I’m treating the two reproductions as one grouped finding rather than two separate blockers.

I also found three non-blocking P2 follow-ups:

  1. packages/runtime/src/mcp-tools.ts:75 — the shared network gate also changes Direct-mode MCP behavior under managed restricted-network boundaries. Please either scope it to CodeMode or explicitly document and test the Direct-mode decision.
  2. packages/code-mode/src/interpreter.ts:659 — string indexing silently diverges from JavaScript: "abc"[1] returns undefined/null with ok: true instead of "b". Please support it or reject it loudly.
  3. packages/ui/src/materialize.ts:141 — persisted nested activity retains its parent identity, but ToolActivityItem drops origin, modelVisibility, parentToolCallId, and parentOperationId, so the UI cannot group the child activity under its outer exec.

The new test coverage is otherwise strong, and I verified that the earlier build, recovery, hidden-replay, argument-bound, and fatal-latching findings are fixed on the current head.

Gate: changes requested for the single P1. The P2 items are non-blocking if they are explicitly handled or deferred with rationale.

Comment thread packages/code-mode/src/interpreter.ts Resolved
@Nyvo-io
Nyvo-io force-pushed the feat/1553-codemode-exec branch 3 times, most recently from 31a4195 to eed2103 Compare August 5, 2026 07:19
@Nyvo-io

Nyvo-io commented Aug 5, 2026

Copy link
Copy Markdown
Contributor Author

The consolidated fix is now on eed21030. All GitHub checks, including workspace tests, Runtime Host, headless, E2E, Storybook, package, and typecheck, are green; the local full suite and independent review are also clean. No code changes were made after the reviewed fix set. @Astro-Han, please re-review the current head when convenient.

@Nyvo-io
Nyvo-io force-pushed the feat/1553-codemode-exec branch 2 times, most recently from 7d410ac to 75f7352 Compare August 5, 2026 13:20
@Nyvo-io

Nyvo-io commented Aug 5, 2026

Copy link
Copy Markdown
Contributor Author

Rebased the consolidated change onto current main and resolved the package/runtime conflicts in the existing single commit (75f7352c). The PR is mergeable again and all 13 GitHub checks are green. @Astro-Han, please re-review the current head when convenient.

@Astro-Han

Copy link
Copy Markdown
Contributor

Reviewing Again! Take this comment as a Placeholder.

@Astro-Han Astro-Han left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approve ✅

Thanks for the patience through all these rounds — the head is in really good shape. I did one more independent pass with four parallel reviewers split across the CodeMode package/core contracts, the ToolRuntime orchestration, the event/replay/recovery system, and a test-quality audit. Everything below was checked against the actual code (tests re-run in a sandbox — code-mode 86/86, targeted runtime suites green — plus a few mutation experiments to confirm the assertions have real teeth).

Overall: the design reads well. The capability-less interpreter reusing the full tool path (admission, loop-gate, permissions, durability, limits) is a clean seam, and the hidden-event invariant is carried through replay, compaction, archive, synthesis, and recovery consistently. Test quality is genuinely strong.

A few small things I noticed while reading — none of them blocking, but I think they're worth a look:

1. Token budget estimation doesn't account for modelVisibility: 'hidden'
estimateRuntimeEventChars (packages/runtime/src/context-budget-helpers.ts:27-43) counts function_call/function_response regardless of visibility, while the same PR filters hidden events everywhere else (history-compact, tool-result-archive, synthesis-cache, continuation-replay). The practical effect: budget diagnostics and usage telemetry would count content that never reaches the provider (up to 32×1MB per turn), and buildHistoryCompactCheckpointFailOpenContext (ai-sdk-backend.ts:4118-4119) filters its compactable set with the token estimate — which can drift from what real compaction would keep. If it's not already on your list, a one-line filter in the estimator plus a small test would close the loop.

2. Failure-path drain has no timeout
In execute()'s catch (packages/code-mode/src/interpreter.ts:306-308), the Promise.allSettled drain waits for in-flight tool operations with no bound. If a tool ignores AbortSignal and never settles, the cell never returns — the wall-time/steps limits can't help, and the turn-level watchdog can't either (confirmed empirically: the cell didn't return within 1.5s). The success path is covered by the timer; this one isn't. Racing the drain against min(2s, remaining wall time) would make the failure path symmetric.

3. No test for the depth=1 recursion boundary
The name !== 'exec' filter in nestableToolSnapshot (packages/runtime/src/ai-sdk-backend.ts:472-490) is the only structural guard against nested exec, and I couldn't find a test where a cell actually calls exec — deleting the filter would leave all tests green. A small test asserting exec/INVALID_TOOL_NAME are absent from the cell snapshot would pin this down nicely.

Cheap wins while you're in there:

  • tick() doesn't check terminalFailure (interpreter.ts:1533-1544) — after a caught fatal error, pure computation runs to the end of the cell before stopping. One line.
  • nestableToolSnapshot doesn't exclude provider-native tools — the WebSearch provider tool throws when executed through ToolRuntime, so a cell calling it fails with an unactionable error. One line (!tool.providerTool).
  • recovery-resolver.test.ts ('does not infer Code Mode recovery from a custom direct exec name') passes 'direct' as the tool mode, which only exercises the early return — the test reads like it's checking more than it does. Passing 'code_mode' with a hidden exec call would match the name.
  • code-mode.test.ts:436 (sort wall-time test) stays green even if the in-sort checks are removed (verified by mutation) — the sort just finishes before the next tick(). Worth strengthening like the Object.fromEntries test.

Optional / happy to defer: origin and modelVisibility are always equal in production (tool-runtime.ts:974) but thread through the whole stack — a consistency invariant test would prevent future drift; the UI-side identity fields have no renderer consumer yet — either add the visual treatment or drop them until there's one; [email protected] as a runtime dep (just for transpileModule) pulls the whole compiler into the desktop bundle — fine if intended, but a one-line note in the PR description would help; a short dialect contract doc would make future reviews of the 2381-line interpreter cheaper; and the sticky post-hoc output limit (ai-sdk-backend.ts:2527) is worth a thought — per-call budgeting would make retries more actionable.

One housekeeping ask: the branch is currently 6 commits behind main and the PR is merge-blocked — since merging requires the branch to be up to date, could you rebase the consolidated commit onto the latest main when you get a chance? 🙏

@Nyvo-io
Nyvo-io force-pushed the feat/1553-codemode-exec branch from 75f7352 to 35afcdc Compare August 5, 2026 15:28
@Astro-Han

Copy link
Copy Markdown
Contributor

Hi @Nyvo-io — thanks for rebasing onto the latest main; CI is green and the PR is mergeable. I approved the earlier head (75f7352c) with the P2s marked non-blocking, but since you have since rebased to 35afcdce2 and the P2/P3 items I noted are still open, I want to check before merging:

  • P2-1 token budget estimation missing the modelVisibility: 'hidden' filter (context-budget-helpers.ts:27-43) — budget diagnostics/telemetry would count content that never reaches the provider
  • P2-2 failure-path drain without timeout in interpreter.ts:306-308 — a non-abortable tool can hang the cell past its wall-time/steps limits
  • P2-3 no test for the exec recursion boundary in nestableToolSnapshot
  • plus the cheap wins (tick terminalFailure check, providerTool snapshot exclusion, the vacuous recovery-resolver test, the sort wall-time test)

Would you like to address these (happy to review the updates), or explicitly defer them with a note? Either way works for merge — just want a decision documented before we squash.

@Nyvo-io

Nyvo-io commented Aug 5, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the explicit decision point. I reviewed each item against the current head and will defer the remaining follow-ups for this PR:

  • The hidden-event token estimate is a diagnostics/telemetry consistency improvement; model-facing replay, compaction, archive, and synthesis projections already enforce the visibility boundary.
  • The failure-path drain intentionally waits for owned tool settlement. Adding a timeout without a separate cancellation/settlement contract could detach late side effects, so that needs a dedicated follow-up.
  • The recursion-boundary test and the listed cheap wins are worthwhile hardening and test cleanup, but the production guard and current behavior are already in place and they are outside this PR required contract.

No code changes are needed for this review round. The consolidated head 35afcdc remains CI-green and mergeable, ready to squash and merge.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants