Repository navigation
feat(codemode): Register the codemode tool - #2544
Merged
Merged
Conversation
Add the `codemode` tool and register it with the agent. This turns Code Mode on. The model writes an async JavaScript function body that calls other tools with `tools.<name>(args)`. The bridge runs the script, and each nested call takes the normal tool path, including action review. The tool is `modelOnly`, so a script cannot start another script. Its description gives the limits and the TypeScript declarations of the script tools that fit a 3,000-token budget. Nested calls count toward the Turn's tool-call limit. The tool result has one status line for each call, the rejection instructions, the output, and the return value. Its details keep the `CodeModeResult`, so history restores rejection markers. When output is cut, the bridge returns the full text and the tool saves it to `.junior/codemode/<toolCallId>.txt` in the Sandbox. If the write fails, the result keeps the cut text and says so. The real pi-codemode import replaces the placeholder import in `app.ts`. Co-Authored-By: Thomas Jiang <[email protected]>
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
thomasjiangcy
approved these changes
Nov 2, 2026
thomasjiangcy
added a commit
that referenced
this pull request
Nov 2, 2026
…ool paths (#2545) Fixes the regression from #2544 in the integration eval `subagents.eval.ts` > "when a child agent uses its turn budget, it reports its progress instead of failing". It failed live twice on run 41465177791. In both runs the child Turn failed with `Agent turn exceeded execution limit (3 tool calls)` and did not wrap up. **What happened** With Code Mode, the model can reach a tool in two ways: a direct call or a `codemode` script. The turn-limit text covered only one of them: - **Direct path.** The gate blocked the first step past the limit with `systemTime is disabled in this Turn. … Do not call it again in this Turn.` The text names one tool. If the model then makes a tool call through the other path, that second over-limit step gets `stop`, and the Turn fails. - **Script path.** The bridge failed each nested call past the limit with the terminal text `Agent turn exceeded execution limit (N tool calls)`. It never told the model to reply with its progress. Evidence from the CI artifacts (`integration-results-2.json`): - In the failing and the passing runs (for example 41441056295 and 41424882348), the case made the same number of gateway requests (`/v1/messages: 9`). The passing child made 5 model steps: `systemTime` ×3, a 4th `systemTime` that was blocked, then a reply. The failing child also made 5 steps. Its `systemTime` request count was more than 3, and it ended on `stop`. So the child made a tool call in the step after the wrap-up block. - Only the `stop` branch in `agent/index.ts` throws `TurnToolCallLimitExceededError`. A local repro confirmed that the bridge's nested failures stay inside the script result. - The eval reports do not keep the child transcript, and Roach dropped the failed sessions. So the tool that the 5th step called is **not recorded**. The step counts fit "4 direct calls, then `codemode`" best (hypothesis b). They also fit a few other orders that mix a script and direct calls. A local repro with fixed model output gives the same failed Turn and the same error for each order. **Change** - `services/turn-limit.ts`: `TURN_LIMIT_DISABLED_REASON` becomes `TURN_LIMIT_WRAP_UP_MESSAGE`. The text names no single tool and says that `codemode` scripts are also disabled. It still asks for a progress reply. - `agent/index.ts`: the `wrap_up` block returns that message, not `disabledToolMessage(toolCall.name, …)`. - `codemode/bridge.ts`: a nested call past the limit fails with the same message, not the terminal error text. - No change to `createTurnLimitGate`, the `wrap_up`/`stop` steps, bridge concurrency, or Guardian. **Tests** - `tests/integration/codemode/bridge.test.ts`: when a script reaches the limit, the call that fits runs, and later calls fail with the wrap-up message. - `evals/integration/agent/scripts.eval.ts`: new case. When a script reaches the turn limit (`maxToolCallsPerTurn: 3`), the script result shows the wrap-up message, the Turn succeeds, and there is one reply. `tests/` cannot run the agent (`test-architecture:check`), so the Turn-level check is an eval. **Checks** - `pnpm typecheck`, `pnpm lint`, `pnpm file-length:check`: pass. - Vitest: `tests/integration/codemode`, `tests/component/codemode`, `tests/unit/services`, `tests/component/runtime`, `tests/component/config`, and the tool-support suites: 44 files, 388 tests pass. - Not run locally: the evals and `pnpm cli -- chat` QA. This sandbox has no `ROACH_TOKEN` and no AI Gateway credentials. CI records the new eval case and runs the `turn budget` case again live. The wording change is model-facing, so CI is the real check. **Open question** After a wrap-up, the gate still ends the Turn on the next tool call. If the model keeps trying after this change, the next step is a policy decision. One option is to allow a bounded second wrap-up step before `stop`. I did not make that change here. <!-- junior-request-attribution:start --> via @thomasjiangcy. <!-- junior-request-attribution:end --> <!-- junior-session-footer:start --> <!-- junior-conversation-id:agent%3A17c7c39901ff667f431cf03b5725959f --> -- [View Session](https://junior-prod.sentry.dev/conversations/agent%3A17c7c39901ff667f431cf03b5725959f) [[Sentry]](https://sentry.sentry.io/explore/conversations/agent%3A17c7c39901ff667f431cf03b5725959f/?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 the
codemodetool inpackages/junior/src/chat/codemode/tool.tsand 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 withtools.<name>(args).runCodeModeScript()from #2539 runs it, and each nested call takes the normal tool path, including action review.Tool
codemode,exposure: "modelOnly", so a script cannot start another script. Input{ code: string }. Top-levelawaitandreturnwork.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 mostMAX_TOOL_ACTION_BATCHcalls 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.scriptToolsas TypeScript (pi-codemoderenderToolSignature) within an estimated 3,000-token budget, the same default that pi uses. Shared envelope fields (ok,truncated, ...) are removed from result types.searchToolsresult is also callable astools.<tool_name>(args)with itsinput_schema. Script-only tools (exposure: "codemode") are declared before the others, becausesearchToolscannot 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.approvalMode. Guardian reviews each nested call in drain batches, as in feat(codemode): Add tool execution bridge #2539.Wiring
createPiAgentTools()takes an optionalcodeModeargument and adds the tool with the Run's pipeline andscriptTools.codemodeis a reserved name, likesearchToolsandexecuteTool.wireAgentTools()passesresume.countToolCall, so nested calls count towardmaxToolCallsPerTurn, and the Sandbox workspace.detailsis theCodeModeResult(plusoutputPathwhen saved), soguardian/history.tsrestores 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
runCodeModeScript()now returns{ result, untruncated? }.untruncatedhas the full output and return value only when they were cut..junior/codemode/<toolCallId>.txtwithworkspace.writeFilesand returns the path, the same aswebFetch. If the write fails, the result keeps the cut text and says that the full text was not saved.webFetchoverflow goes throughworkspace.writeFiles→runtime.acquire(), so it starts a Sandbox if none exists.codemodeuses the same path, so it does the same thing only when output is cut. I kept it the same aswebFetch.Bundling. The placeholder
import "@earendil-works/pi-codemode"inapp.tsis gone.tool.tsandbridge.tsimport it for real.Tests and evals
tests/integration/codemode/tool.test.ts: the registered tool fromcreatePiAgentTools()runsPromise.alloversystemTime+listWatchesand 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 fromdetails.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.evals/agent/scripts.eval.ts: a fan-out request usescodemode. A single-lookup request does not.evals/integration/agent/scripts.eval.ts: parallel calls are listed in the result, and long output names a Sandbox file.ROACH_TOKENwas available locally, so the new eval cases were not run. CI records them.Checks run
pnpm typecheck,pnpm lint,pnpm file-length:check: pass.pnpm --filter @sentry/junior-example buildwithJUNIOR_SKIP_SNAPSHOT=1): pass, andcheck-vercel-output.mjspasses.quickjs.wasmand the pi-codemodeworker.jsare in each function. The pnpm-injected@sentry/juniordist hascreateCodeModeTooland no placeholder.pnpm cli -- chat: the model wrote one script withPromise.alloversystemTime×2 +listWatches. Nested ids were…/c1..c3, allok, and the reply was correct. With 60k characters of output andJUNIOR_SANDBOX_PROVIDER=docker, the result named/vercel/sandbox/.junior/codemode/call_….txt, andbash wc -lread it. Without Sandbox credentials, the write failed, and the reply said the full text was not saved.@sentry/juniorsuite locally: 15 timeouts orfetch failedin durable-queue, local-agent-runner, annotation-cards, and similar suites. The same files fail on unmodifiedmainin this environment.Open questions
wireAgentTools()too, so they also getcodemode. Tell me if this should be limited to the root agent.via @thomasjiangcy.
--
View Session [Sentry]