Skip to content

feat(codemode): Register the codemode tool - #2544

Merged
thomasjiangcy merged 1 commit into
mainfrom
feat/codemode-tool
Nov 2, 2026
Merged

thomasjiangcy merged 1 commit into
mainfrom
feat/codemode-tool

Conversation

@sentry-junior

@sentry-junior sentry-junior Bot commented Nov 2, 2026

Copy link
Copy Markdown
Contributor

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 feat(codemode): Add tool execution bridge #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.

via @thomasjiangcy.

--

View Session [Sentry]

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]>
@vercel

vercel Bot commented Nov 2, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated
junior-docs Ready Ready Preview Nov 2, 2026 2:46pm UTC

Request Review

@github-actions github-actions Bot added the risk: high PR risk score: high label Nov 2, 2026
@thomasjiangcy
thomasjiangcy merged commit b526690 into main Nov 2, 2026
50 of 51 checks passed
@thomasjiangcy
thomasjiangcy deleted the feat/codemode-tool branch November 2, 2026 15:11
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

1 active deployment
Preview – junior-docs — 00c311fb Deployed Nov 2, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

risk: high PR risk score: high

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant