Repository navigation
feat(runtime): add restricted CodeMode execution - #1648
Conversation
|
I found three P1s and one P2 on [P1] Aborting or timing out a cell only rejects the promise held by the interpreter. It does not wait for the underlying [P1] Unsupported operators are rejected after their operands have been evaluated. For example, [P1] The product build paths do not build [P2] 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. |
b4ef974 to
4ae91a7
Compare
|
Addressed all four findings in |
|
I took another pass over P1
P2
P3
I also rechecked the previous review. The build-order fix and the 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, |
|
Implemented and reviewed in 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 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 |
Astro-Han
left a comment
There was a problem hiding this comment.
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
-
Could output copying use a cumulative traversal budget rather than checking only each local collection and the completed result?
copyPlainData()removes an object fromseenafter 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 insidecopyPlainDatawould make the existing output limit effective before the copy is allocated. -
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 hiddenfunction_responseevents, andbuildSynthesisArchiveExcerpts()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. -
Could
Object.fromEntriesavoid recomputingObject.keys(output)for every entry? The current loop is O(n²). With 30,000 entries andmaxWallTimeMs: 5, the cell blocked for about 6.4 seconds and still returnedok: true. Tracking the unique-key count incrementally would remove most of this cost; a wall-time checkpoint around synchronous helpers would cover similar cases. -
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. -
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({});
writeexecutes before the cell reportsunknown_tool. A retry can therefore repeat the first side effect even though the missing tool was knowable before execution. -
Could the gateability contract exercise a real denied nested MCP or custom tool? The current test proves that
classifyToolUse()returns aToolCategory, but unknown tools always fall back tocustom_tool, and that classification is not itself an execution decision.ToolRuntimedoes 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. -
Could
toolModebe validated before the AgentRun record is created? The backend now rejects invalid values, butAgentRunassigns the runtime value and writes it into the run header before backend projection. An untyped caller can therefore persisttoolMode: "typo"and leave a header thatdecodeAgentRunHeader()rejects later. The Run boundary seems like the single owner for this validation. -
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
-
Should an uninitialized
letuse internalundefinedsemantics?let x; return { isNull: x === null, kind: typeof x };
The interpreter currently returns
{ isNull: true, kind: "object" }; JavaScript would return{ isNull: false, kind: "undefined" }. Convertingundefinedtonullat 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.
a1dcae3 to
4e8d278
Compare
|
Rebased the consolidated fix onto current Final verification is clean: full build; Code Mode No further code changes were made after the approved review; the new head is ready for re-review/merge. |
Astro-Han
left a comment
There was a problem hiding this comment.
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 effectivetoolModeintoAiSdkFlow.run()? The run header and invocation context preservecode_mode, but the flow input currently omits it, so direct users of the exportedAgentRunAPI fall back to Direct mode. -
Should plan-control tools such as
SubmitPlanbe markeddirect_onlyfor now? A nested call updates the plan store, but its result does not pass through the top-levelhandlePlanToolResultpath, 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, andparentOperationId? The runtime read model preserves them, but the finalToolActivityItemdrops them, so nested activity cannot later be grouped under its outerexec.
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.
4e8d278 to
47edded
Compare
|
Rebased the consolidated fix onto current main as |
47edded to
543da55
Compare
|
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
left a comment
There was a problem hiding this comment.
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(buildInterruptedCodeModeOutcomeCommitsexplicitly skipscallEvent.origin === 'code_mode'/ hidden calls). The resume projection (projectToolOperations,runtime-resume.ts) then drops the nested operation'sindeterminatedecision, sobuildResumePlanFromRuntimeEventsyieldsrequiresVerification=false, disposition='safe_replay'with noINDETERMINATE_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.
|
Updated the current head in one consolidated commit: 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 Also addressed two related issues:
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:
|
|
Nice work on the recovery fix in P1: nested tool arguments have no byte budget
Fix: P2
Non-blocking
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. 中文版感谢这轮恢复修复, P1:嵌套工具参数没有字节上限
修复: P2
非阻断
无界 abort drain 应该是你刻意选的:等工具结算而不是脱离。只是提醒这是唯一一个不配合的工具能把 cell 挂住的地方。 |
|
Following up on the current head |
|
Applied the remaining review fixes in one consolidated commit:
Local verification is clean: full build; Code Mode |
969e8fd to
28d258c
Compare
|
Updated the PR in one consolidated commit: |
Astro-Han
left a comment
There was a problem hiding this comment.
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:
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.packages/code-mode/src/interpreter.ts:659— string indexing silently diverges from JavaScript:"abc"[1]returnsundefined/nullwithok: trueinstead of"b". Please support it or reject it loudly.packages/ui/src/materialize.ts:141— persisted nested activity retains its parent identity, butToolActivityItemdropsorigin,modelVisibility,parentToolCallId, andparentOperationId, so the UI cannot group the child activity under its outerexec.
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.
31a4195 to
eed2103
Compare
|
The consolidated fix is now on |
7d410ac to
75f7352
Compare
|
Rebased the consolidated change onto current |
|
Reviewing Again! Take this comment as a Placeholder. |
Astro-Han
left a comment
There was a problem hiding this comment.
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 checkterminalFailure(interpreter.ts:1533-1544) — after a caught fatal error, pure computation runs to the end of the cell before stopping. One line.nestableToolSnapshotdoesn'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 nexttick(). 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? 🙏
75f7352 to
35afcdc
Compare
|
Hi @Nyvo-io — thanks for rebasing onto the latest
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. |
|
Thanks for the explicit decision point. I reviewed each item against the current head and will defer the remaining follow-ups for this PR:
No code changes are needed for this review round. The consolidated head 35afcdc remains CI-green and mergeable, ready to squash and merge. |
Summary
toolModewith a restricted AST-based CodeMode interpreterexecorchestration over the active nestable tool snapshotToolRuntimewith direct-only admission, permissions, abort handling, output/data limits, and durable parent-linked activityexec, runtime persistence wiring, and focused contract coverageVerification
npm run buildnpm run lintnpm run format:checknpm run check:third-party-noticesgit diff --checkDirect mode remains the default and its provider surface is unchanged.