codemode: "Instructions updated" re-injects the full tool catalog on every tool-tree change (browser attach/detach, MCP reconnect), polluting context
Summary
When the Code Mode tool tree changes, OpenCode re-injects the entire catalog (~8.8k chars) into the conversation as a system message (description: "Instructions updated: core/codemode"), which the provider layer renders to the model as a user message. The tool tree also changes on transient, expected events — desktop-browser connect/disconnect, MCP reconnect, location recycling — so normal usage (opening/closing a session tab, opening/closing the desktop app) repeatedly dumps the full catalog into context. In one 22-day deployment this produced 419 notices / 2.27M chars of injected context, up to 67 notices in a single day.
Environment
- opencode version: v2.0.29
- OS: Linux 6.18.18.c1107-trim (linux x64) — official container image
ghcr.io/anomalyco/opencode:2.0.29 - Terminal: Unavailable — headless server driven by the desktop app over the local server API (TERM=xterm-256color)
- Shell: Unavailable
- Install/channel: release container image
- Active plugins: none (
"plugins": [])
Reproduction
- Run
opencode servewith the desktop app attached to a session (so thebrowsernamespace is registered). - In the desktop app, open and close the session tab (or toggle the embedded browser) a few times.
- Inspect the session: each attach/detach cycle appends a
type:"system"message whosetextis the full catalog and whosedescriptionisInstructions updated: core/codemode.
Observed during a single turn of ~10 tool calls: 4 browser attach/detach cycles → 2 notices, and the catalog alternated browser (45 tools, 5 shown) github (46, 6) nas-ops (35, 6) opencode (8, 7) ↔ github (46, 9) nas-ops (35, 8) opencode (8).
Expected Behavior
A change notification should be proportional to the change and debounced: a short "catalog changed, re-run search" note, or a diff. Transient connect/disconnect of the desktop browser (or MCP) should not be treated as a semantic instruction change, and a flap that immediately reverses should not produce two full-catalog injections.
Actual Behavior
- Every tool-tree change injects the full catalog (~8.8k chars; 14.4k observed max).
- No debounce: attach→detach = two changes = two injections.
- The injected
systemmessage is converted to ausermessage before reaching the model, so the model sees repeated fake user turns. - The notices accumulate in the session context until a compaction drops them.
Data from one deployment (22 days, all sessions):
| metric | value |
|---|---|
| notices total | 419 |
| chars injected total | 2,275,570 |
| largest single notice | 14,403 chars |
| worst day | 67 notices |
| per-day range | 1–67 |
Per-day counts (CST): 09-23:24, 09-24:2, 09-25:1, 09-26:27, 09-27:54, 09-28:29, 09-29:22, 09-30:3, 10-01:7, 10-02:9, 10-03:1, 10-05:4, 10-06:11, 10-07:25, 10-08:1, 10-09:12, 10-10:61, 10-11:15, 10-12:13, 10-13:67, 10-14:22, 10-15:9.
Correlation with desktop-browser attach churn (log POST /api/rpc/experimental.browser/attach … 499): 10-13 had 798 closes → 67 notices; 10-10 had 324 → 61; 10-14 had 326 → 22.
Additional Context
Mechanism (extracted from the v2.0.29 binary):
Vl(e, A={})renders the catalog under a fixed budget (A.budget ?? 2000);jl()callsVl(e)without a budget, so the full catalog is regenerated each time.Rl(prev, next)compares and returns the "changed" text.InstructionState.prepare(observe+commit) runs only for the currently-draining session, at each step boundary — so a session that happens to have a step inside the flap window gets the notice; sessions with no step in the window do not.- The projector appends a
type:"system"message; the AI-SDK adapter convertsrole:"system"torole:"user".
Not a duplicate of the existing "tools unavailable" issues: #51849 / #46190 / #52505 describe a namespace missing (calls fail with Unknown tool). This report is about the repeated full-catalog injection on every flap, regardless of whether the tools are callable.
Workarounds tried: none — the notice is not suppressible from the server side.
Thanks for the detailed report and the numbers. I reproduced this on 2.0.29, and it still happens on the latest dev (13afea6).
The script below builds a Code Mode catalog like yours (github 46, nas-ops 35, opencode 8 tools), then adds and removes a 45-tool browser namespace, as an attach and detach would. It runs the real catalog summary and the code that writes the "catalog changed" notice:
- attach: 8,811-char notice, which is the full catalog
- detach: 8,912-char notice, again the full catalog
- the full catalog alone is 8,709 chars
The catalog is too big to list every tool, so only some are shown. Adding or removing a namespace changes which tools are shown in the other namespaces, so the update logic falls back to re-sending the whole catalog. The short "namespace added/removed" message is never used. Nothing debounces a change that reverses right away, so each attach/detach cycle produces two full copies.
I checked this at the function level, not end to end with the desktop app, but it matches the ~8.8k-char notices you saw.
Related: #55389 (mid-session notices breaking Responses-API sessions), #54408 (instruction baseline and prompt cache), #52309 (browser tools only shown while a desktop is attached).
Reproduction script (catalog-flap.ts)
// Reproduces #55529: a Code Mode namespace appearing/disappearing (e.g. desktop browser
// attach/detach) makes CodeModeInstructions.update() emit the FULL catalog, not a delta.
// Run from an opencode checkout: REPO=/path/to/opencode bun /workspace/repro/catalog-flap.ts
const repo = process.env.REPO ?? "/workspace/repo"
const { CodeModeCatalog } = await import(`${repo}/packages/core/src/codemode/catalog.ts`)
const { CodeModeInstructions } = await import(`${repo}/packages/core/src/codemode/instructions.ts`)
const ns = (name: string, n: number) => ({
type: "namespace" as const,
name,
tools: Array.from({ length: n }, (_, i) => ({
type: "tool" as const,
name: `tool_${String(i).padStart(2, "0")}`,
description: `Does ${name} operation number ${i} with some descriptive text`,
signature: `${name}.tool_${String(i).padStart(2, "0")}(input: { id: string; value?: number }): Promise<unknown>`,
})),
})
const base = [ns("github", 46), ns("nas-ops", 35), ns("opencode", 8)]
const detached = CodeModeCatalog.summarize({ tools: base })
const attached = CodeModeCatalog.summarize({ tools: [ns("browser", 45), ...base] })
const show = (s: any) => s.namespaces.map((n: any) => `${n.name} (${n.count}, ${n.entries.length} shown)`).join(" ")
console.log("detached:", show(detached))
console.log("attached:", show(attached))
const full = CodeModeInstructions.render(attached).length
for (const [label, a, b] of [["attach", detached, attached], ["detach", attached, detached]] as const) {
const text = CodeModeInstructions.update(a, b)
const isFull = text.includes("supersedes the previous Code Mode tool catalog")
console.log(`${label}: notice ${text.length} chars, full replacement=${isFull}`)
}
console.log(`(full catalog render is ${full} chars; ideal delta would just name the added/removed 'browser' namespace)`)
Run it: bun catalog-flap.ts
I'd like to take the catalog-size part of this. CodeModeInstructions.update already has a namespace delta for partial catalogs, but any change to the selected inline entries bypasses it. Adding browser redistributes the shared inline budget, so even unchanged namespaces can trip that fallback.
Proposed first scope: for partial → partial updates with unchanged namespace descriptions, invalidate previous listings/search results only for namespaces whose count or selected entries changed; name added namespaces and explicitly forbid removed ones. Tell the model to search affected namespaces again instead of repeating the catalog. Keep the existing full replacement for empty catalogs, complete ↔ partial transitions, description changes, and when it is shorter than the delta.
This keeps updates at the current step boundary. I would leave debounce and browser attachment lifetime out: #52309 deliberately ties browser availability to a desktop attachment, so delaying removal could advertise unavailable tools. It also leaves Responses message handling (#55389 / #55445) and instruction baseline/revert handling (#54408) separate.
Validation would cover the reported 45-tool attach/detach with a partial catalog, same-count visible listing changes, exact removed-namespace invalidation, and the existing full/partial/empty reset cases. This is based on code inspection; I have not run a desktop reproduction.
Could a maintainer approve this narrower notification design before implementation?
yeah need to fix.
I'll take the proportionate-notice part: when the catalog is partial and its shown entries change, update currently falls back to the full catalog. It will emit a short notice (re-run search(...), plus namespace additions/removals/changed inventories) instead. Debouncing the attach/detach flap itself is a separate mechanism; I'll leave that out so semantic changes still surface immediately.
Opened #57090. The partial-catalog branch now emits a short Re-run search(...) notice plus the namespace inventory details instead of falling back to the full catalog; the test changes one shown entry in a 60-tool partial catalog and asserts a <200-char notice with no tool listings. On the parent it returns the ~9k-char catalog. Debounce is left out so semantic changes still surface immediately.
Follow-up on 2.4.1 with the partial-catalog change in place: the removal side is now short, the addition side is not.
Measured over 151 Code Mode notices in one local DB:
| kind | count | min / avg / max chars |
|---|---|---|
| add ("New tools are available") | 47 | 514 / 4 582 / 13 249 |
remove (browser) |
31 | 207 / 671 / 7 422 |
So a browser detach now costs ~200 bytes, but a re-attach still reprints the namespace with its full description plus tool listings (typically ~4.5 KB, up to 13 KB when several namespaces change at once), and the pairs keep coming: on 2026-11-23 the same session got eight add/remove pairs 5–40 s apart, 51 notices in one day.
The flap itself is tracked separately in #62234 (desktop rebuilds /api/event + browser/attach every ~60 s and on every session step). Two questions:
- Should the add side use the same short form as the remove side (namespace name, tool count, "search to see the tools") instead of reprinting the listing?
- Is a debounce for attach/detach flaps still out of scope, given #62234 keeps producing them?