Repository navigation
feat(codemode): Add tool execution bridge - #2539
Merged
Merged
Conversation
Add runCodeModeScript, which runs a model-written script in pi-codemode's start() mode and sends each tools.x() call through the normal tool pipeline: argument checks, plugin hooks, action review, credentials and auth handling, then the executor. The calls of one VM drain go to reviewToolActions as one batch, with the script source and earlier calls as provenance. A drain over the batch limit fails before any hook or review. Tools with executionMode "sequential" run one at a time; other tools run in parallel. Nested calls count toward the per-turn tool-call limit, use <toolCallId>/c<n> ids, and run under the codemode span with gen_ai.tool.dispatcher.name set to codemode. The result lists every nested call with its status, also after a timeout or abort, and carries the gate's rejection marker for each rejected call. Guardian history restores those markers at the start of a Run. To review per batch and execute per call, the adapter's call flow moves into createToolPipeline with separate prepare and execute steps. The direct path is unchanged. Nothing registers a codemode tool yet. Co-Authored-By: Thomas Jiang <[email protected]>
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
Contributor
|
3 screenshot changes — 3 changed · 0 added · 0 removed Review screenshots in Frameshift
|
thomasjiangcy
approved these changes
Nov 2, 2026
A nested call that ignores the abort before its executor, for example in a plugin hook, kept runCodeModeScript waiting past its deadline. Wait at most 3s for nested calls after the script ends, and report a started call that has no outcome as interrupted. Abort the nested calls also when the VM result rejects.
…en calls overlap Egress auth and permission signals are keyed per egress session, and the proxy cannot tell which command made a request. Two bash commands that run at the same time can clear or read each other's signals. Run the bash commands of one Run one at a time inside the sandbox access. Sandbox acquisition stays shared and cancellable; only clear, run, and consume wait for the earlier command. switchWorkspace read the active Sandbox before it built the candidate. An overlapping switch, or a cold acquisition during the build, replaced it in the meantime, so that Sandbox was never stopped. Read the active Sandbox after the candidate is ready. A Code Mode script can start both calls together; direct calls keep executionMode "sequential". Co-Authored-By: Thomas Jiang <[email protected]>
Remove the bridge's queue for tools with executionMode "sequential". A script now orders its own calls: `await a(); await b()` runs them one after the other, and `Promise.all` runs them at the same time. executionMode still orders direct calls. A tool whose calls must not overlap, such as bash, serializes them in its own executor. Co-Authored-By: Thomas Jiang <[email protected]>
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes and found 1 potential issue.
There are 2 total unresolved issues (including 1 from previous review).
❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.
Reviewed by Cursor Bugbot for commit e824618. Configure here.
A bash call resolves its sandbox before it waits for an earlier command. If a workspace switch or reacquire happened during the wait, the command ran on the old session and cleared or consumed that session's egress signals. Resolve the sandbox again after the wait when the call queued.
…gnals Co-Authored-By: Thomas Jiang <[email protected]>
thomasjiangcy
added a commit
that referenced
this pull request
Nov 2, 2026
Add the `codemode` tool in `packages/junior/src/chat/codemode/tool.ts` and register it with the agent. This is the last Code Mode piece, and it turns Code Mode on with no env gate. The model writes the body of an async JavaScript function that calls other tools with `tools.<name>(args)`. `runCodeModeScript()` from #2539 runs it, and each nested call takes the normal tool path, including action review. **Tool** - Name `codemode`, `exposure: "modelOnly"`, so a script cannot start another script. Input `{ code: string }`. Top-level `await` and `return` work. - The description says when to use it (fan-out with `Promise.all`, or chains where one result picks the next call) and when not to (one call, or calls the model must read before it decides). It gives the limits: 120s (`CODE_MODE_SCRIPT_TIMEOUT_MS`), at most `MAX_TOOL_ACTION_BATCH` calls started before an await, the 40k output cap (`CODE_MODE_MAX_OUTPUT_CHARS`, now exported from the bridge), JSON-serializable args and results, and that only the return value and printed output come back. - It declares the `scriptTools` as TypeScript (pi-codemode `renderToolSignature`) within an estimated 3,000-token budget, the same default that pi uses. Shared envelope fields (`ok`, `truncated`, ...) are removed from result types. - **Tools beyond the budget:** declare the cheapest tools first, so the most tools fit. Tools that do not fit stay callable. The description says that each `searchTools` result is also callable as `tools.<tool_name>(args)` with its `input_schema`. Script-only tools (`exposure: "codemode"`) are declared before the others, because `searchTools` cannot find them. There are none today. With the core tool set, 19 of 27 tools are declared. I picked this over a second discovery tool or a per-Turn selection because it needs no new tool, and the text stays the same between Turns for the same tools. - The codemode call itself has no `approvalMode`. Guardian reviews each nested call in drain batches, as in #2539. **Wiring** - `createPiAgentTools()` takes an optional `codeMode` argument and adds the tool with the Run's pipeline and `scriptTools`. `codemode` is a reserved name, like `searchTools` and `executeTool`. - `wireAgentTools()` passes `resume.countToolCall`, so nested calls count toward `maxToolCallsPerTurn`, and the Sandbox workspace. - The tool result `details` is the `CodeModeResult` (plus `outputPath` when saved), so `guardian/history.ts` restores rejection markers. The text that the model sees lists each call and its status, any error, and for a rejected call Guardian's instructions and reason. It then gives the output and the return value. **Long output** - The bridge stays free of any Sandbox dependency. `runCodeModeScript()` now returns `{ result, untruncated? }`. `untruncated` has the full output and return value only when they were cut. - The tool saves them to `.junior/codemode/<toolCallId>.txt` with `workspace.writeFiles` and returns the path, the same as `webFetch`. If the write fails, the result keeps the cut text and says that the full text was not saved. - **Sandbox note:** `webFetch` overflow goes through `workspace.writeFiles` → `runtime.acquire()`, so it **starts a Sandbox if none exists**. `codemode` uses the same path, so it does the same thing only when output is cut. I kept it the same as `webFetch`. **Bundling.** The placeholder `import "@earendil-works/pi-codemode"` in `app.ts` is gone. `tool.ts` and `bridge.ts` import it for real. **Tests and evals** - `tests/integration/codemode/tool.test.ts`: the registered tool from `createPiAgentTools()` runs `Promise.all` over `systemTime` + `listWatches` and a Guardian-denied write. It checks the hooks for each nested call, the Turn count, `details`, the rendered text, and that history restores the marker from `details`. - `tests/component/codemode/output.test.ts`: long output is saved to a file, and a failed write keeps the cut text. - `tests/integration/codemode/bridge.test.ts`: updated for the new return shape. The history check moved to the tool test. - Behavioral eval `evals/agent/scripts.eval.ts`: a fan-out request uses `codemode`. A single-lookup request does not. - Integration eval `evals/integration/agent/scripts.eval.ts`: parallel calls are listed in the result, and long output names a Sandbox file. - No `ROACH_TOKEN` was available locally, so the new eval cases were not run. CI records them. **Checks run** - `pnpm typecheck`, `pnpm lint`, `pnpm file-length:check`: pass. - Code Mode and tool-support suites: 62 passed. - CI build (`pnpm --filter @sentry/junior-example build` with `JUNIOR_SKIP_SNAPSHOT=1`): pass, and `check-vercel-output.mjs` passes. `quickjs.wasm` and the pi-codemode `worker.js` are in each function. The pnpm-injected `@sentry/junior` dist has `createCodeModeTool` and no placeholder. - `pnpm cli -- chat`: the model wrote one script with `Promise.all` over `systemTime` ×2 + `listWatches`. Nested ids were `…/c1..c3`, all `ok`, and the reply was correct. With 60k characters of output and `JUNIOR_SANDBOX_PROVIDER=docker`, the result named `/vercel/sandbox/.junior/codemode/call_….txt`, and `bash wc -l` read it. Without Sandbox credentials, the write failed, and the reply said the full text was not saved. - Full `@sentry/junior` suite locally: 15 timeouts or `fetch failed` in durable-queue, local-agent-runner, annotation-cards, and similar suites. The same files fail on unmodified `main` in this environment. **Open questions** - Child agents use `wireAgentTools()` too, so they also get `codemode`. Tell me if this should be limited to the root agent. - The description is about 12.5k characters with the core tools. 3,000 tokens is pi's default, not something tuned for Junior. <!-- junior-request-attribution:start --> via @thomasjiangcy. <!-- junior-request-attribution:end --> <!-- junior-session-footer:start --> <!-- junior-conversation-id:agent%3Ab52c5a23d4fb5abb2935891680cbe04a --> -- [View Session](https://junior-prod.sentry.dev/conversations/agent%3Ab52c5a23d4fb5abb2935891680cbe04a) [[Sentry]](https://sentry.sentry.io/explore/conversations/agent%3Ab52c5a23d4fb5abb2935891680cbe04a/?project=4510944073809921) <!-- junior-session-footer:end --> Co-authored-by: sentry-junior[bot] <264270552+sentry-junior[bot]@users.noreply.github.com> Co-authored-by: Thomas Jiang <[email protected]>
thomasjiangcy
pushed a commit
that referenced
this pull request
Nov 5, 2026
In a Code Mode script, every `callMcpTool` call returned `{ objectCards:
[] }` with no MCP data. In [this
thread](https://sentry.slack.com/archives/C09FQH46YA2/p1793811592460889),
a GoCD `pipelines` lookup from a script came back empty. A direct call
to the same tool returned the full list.
The bridge from #2539 gives a script the `details` of a call. It uses
the text content only when `details` is `{}`. The `details` of
`callMcpTool` held only `objectCards`, so the MCP data never reached the
script. #2544 made `callMcpTool` a script tool, and #2578 told the model
to call MCP tools from scripts. Since #2578, many MCP calls go through
this path.
The `details` of `callMcpTool` now include `result`. It holds the MCP
`structuredContent`, or the text content when the tool returns none.
`result` is nested, so an MCP server cannot set root fields that the
runtime reads, such as `objectCards`, `continuation`, or
`permission_denied`. `objectCards` does not change, so reply cards work
as before. The Code Mode tool description tells scripts to read
`result`.
**Open question: duplicate data on direct calls**
Pi keeps `details` in the `toolResult` message, and Junior stores the
full message in the conversation event log. The model reads only
`content`. So on a direct call, `details.result` is a second stored copy
of the data in `content`. Script calls store no copy. The bridge gives
the inner result to the script, and the `codemode` row keeps only the
script value and the call status.
Most Junior tools already store two copies, because
`normalizeToolResult` builds `content` from `details`. Those tools limit
their data at the source, so both copies stay small. MCP is different:
`content` stops at 32 KB, but `details.result` has no limit. For the
GoCD `pipelines` call above, the stored row is 16.8 KB today, and
`result` adds about 10 KB. A large MCP response is stored in full.
A smaller alternative is to add `result` only for script calls.
`callFromScript` would pass a flag in the `execute` options, and
`callMcpTool` would add `result` only when the flag is set. Direct calls
would then store no copy, and scripts would still get the full data.
This PR does not include that change. The reviewer decides between the
two.
**Known gap:** cards from MCP calls in a script do not reach the reply,
because the `codemode` result does not forward nested `objectCards`.
This was true before this change.
<!-- junior-request-attribution:start -->
via @lcian.
<!-- junior-request-attribution:end -->
<!-- junior-session-footer:start -->
<!-- junior-conversation-id:slack%3AC0CCUMX7ET0%3A1793844026.815789 -->
--
[View
Session](https://junior-prod.sentry.dev/conversations/slack%3AC0CCUMX7ET0%3A1793844026.815789)
[[Sentry]](https://sentry.sentry.io/explore/conversations/slack%3AC0CCUMX7ET0%3A1793844026.815789/?project=4510944073809921)
<!-- junior-session-footer:end -->
Co-authored-by: sentry-junior[bot] <264270552+sentry-junior[bot]@users.noreply.github.com>
Co-authored-by: Lorenzo Cian <[email protected]>
This branch was successfully deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.

Add
runCodeModeScript()inpackages/junior/src/chat/codemode/bridge.ts. It runs a model-written script in pi-codemode'sstart()mode and sends eachtools.x()call through the normal tool pipeline. Nothing calls it yet except tests. A later change registers thecodemodetool and removes the placeholder import inapp.ts.Behavior
idlemessages) go toreviewToolActionsas one batch. Each proposal carriesscript: { source, calls }with the script's earlier calls and their status. If a drain has more than 10 calls, the whole drain fails with the gate's error before any hook or review runs.beforeToolExecutehooks, the batch review, credentials and auth handling, then the executor under its owngen_ai.execute_toolspan withgen_ai.tool.dispatcher.name: codemode. Nested calls run under thecodemodespan throughSentry.withActiveSpan, and the bridge sets theapp.codemode.*attributes from feat(codemode): Define Code Mode telemetry names #2528.admit(). Tools withexecutionMode: "sequential"run one at a time. All other tools run in parallel, includingauto/reviewtools: direct calls serialize those only because each one is reviewed alone.CODE_MODE_SCRIPT_TIMEOUT_MS(120s). The Run's abort signal stops the VM and every pending nested call. Each nested call counts towardmaxToolCallsPerTurn. Output and return value share a 40k-character cap (pi's 10k-token default at 4 characters per token).ok | error | rejected | interrupted | not_started). It still lists them after a timeout or abort. A rejected call carries Guardian's instructions and the gate's rejection marker.guardian/history.tsreads those markers fromcodemoderesults, so prior-rejection tracking survives a resume.Adapter change. The per-call flow in
createPiAgentTools()moves intocreateToolPipeline(). It splits preparation (checks, hooks) from reviewed execution, so a script can review per batch and execute per call. The tool list, the execution modes, and the direct andexecuteToolpaths are unchanged. The existing adapter suites pass without edits.Tests (
tests/integration/codemode/bridge.test.ts, real pipeline and gate; only Guardian's reviewer is faked):Promise.allover 3 reviewed tools runs in parallel in one batch and adds to the turn count; a sequential tool queues;handofffromscriptToolsis refused; adenyrejects only that call, and its marker is in the result and restored by history; an 11-call drain fails before any review or hook; the 120s deadline, using fake timers; abort settles a running call (interrupted) and a queued one (not_started).tests/integration/annotation-cards.test.tstimes out locally on unmodifiedmaintoo.via @thomasjiangcy.
--
View Session [Sentry]