fix(server): strip OSC/ANSI escapes from OpenCode CLI inventory and stored agent selections #7755
main fromrefs/pull/7755/head·opened View on GitHubFixes #7754
Problem#
opencode <=1.18 leaks OSC title ESC ]0;<cwd>: ready BEL to stdout for every non-help command even when piped. T3's runOpenCodeCommand captures that stdout and parseModelsCliOutput / parseAgentListCliOutput stored polluted ids like "\u001b]0;imbios: ready\u0007build" in model_selection_json.
Next sendTurn → session.promptAsync({agent: polluted}) → opencode rejects:
Agent not found: "\u001b]0;imbios: ready\u0007build". Available agents: build, explore, general, plan
Surfaced as two session.error per turn: first the polluted-agent message, second the generic UnknownError stack at SessionPrompt.createUserMessage … SessionHttpApi.promptAsync.
Repro evidence in ~/.t3/userdata/logs/provider/events.*.log and projection_threads (3 polluted threads at ImBIOS). Also opencode agent list | cat -v shows ^[]0;tmp: ready^Gbuild (primary) even with env -i/TERM=dumb — leak is in opencode binary, not shell. Same leak pollutes models --verbose (model inventory dropped to 0 pre-fix because SLUG_RE didn't match) and debug skill (JSON parse failed → skills=[]).
Fork fix already landed in ImBIOS/t3code#2 and ImBIOS:main 30d9c19; this is the upstream PR.
Fix#
packages/shared/src/stripTerminalEscapes.ts— shared OSC/CSI/charset sanitizer (stripTerminalEscapes/sanitizeTerminalValue)apps/server/src/provider/opencodeRuntime.ts:208,270,312— strip at entry ofparseModels/Agent/Skills; keeps-verbosefrom dropping models and skills from degradingapps/server/src/provider/Layers/OpenCodeProvider.ts:164,188,393— sanitize inventory agent names/variants +--versionparsingapps/server/src/provider/Layers/OpenCodeAdapter.ts:1476+textGeneration/OpenCodeTextGeneration.ts:411— sanitize storedagent/variantbeforepromptAsync(steer + title generation)packages/shared/src/model.ts:66,313— sanitize persistedProviderOptionSelectionvalues and model slugs on read (transparently repairs polluted threads without DB migration)opencodeRuntime.cliParsers.test.ts— regression cases for OSC/ANSI in both parsers
Polluted threads now succeed at runtime via model.ts sanitizer; optional manual DB cleanup via strip script (see issue).
Upstream#
Should also be fixed in sst/opencode — CLI should write OSC title to /dev/tty or stderr only when isTTY, not stdout pipe. T3 fix is defensive regardless.
Verification#
opencode agent list/models --verbose | cat -vstill shows OSC upstream, butparse*CliOutputnow returns clean ids- Manual bun eval for
stripTerminalEscapes→ "opencode/big-pickle", "build" - New OSC/ANSI regression tests added
Note
Medium Risk Touches OpenCode inventory parsing and persisted model-option reads. Sanitization is limited to terminal control sequences, but a bad strip could drop or rewrite agent/variant/model ids.
Overview
Stops OpenCode CLI OSC/ANSI leaks from poisoning model/agent/skill inventory and later session.promptAsync calls (Agent not found with escape-prefixed names).
Adds shared stripTerminalEscapes / sanitizeTerminalValue and applies them when parsing CLI stdout (models, agents, skills, --version), when building capability option ids, and when sending stored agent/variant values. String option reads and model slug normalization also sanitize on the way in, so already-polluted threads work without a DB migration.
Parser tests cover OSC title sequences and ANSI color codes on slugs and agent headers.
Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 4871e966be4fa5a3e167f8cbbb361485b7d3e605. Bugbot is set up for automated code reviews on this repo. Configure [here](https://www.cursor.com/dashboard/bugbot).Note
Strip OSC/ANSI escapes from OpenCode CLI stdout and stored agent/variant selections#
- Adds shared utilities
stripTerminalEscapesandsanitizeTerminalValuein stripTerminalEscapes.ts to remove terminal control sequences from strings captured from CLIs. - Applies
stripTerminalEscapesto raw stdout inparseModelsCliOutput,parseAgentListCliOutput,parseSkillsCliOutput, andcheckOpenCodeProviderStatusso slugs, agent names, and version strings parse correctly when the CLI leaks OSC/ANSI sequences. - Uses
sanitizeTerminalValueingetProviderOptionStringSelectionValue,normalizeCustomModelSlug, andtrimOrNullto clean model slugs and option selections; empty-after-sanitize results becomeundefinedornull. - Sanitizes
agentandvariantvalues read from model selection inmakeOpenCodeAdapterandmakeOpenCodeTextGenerationbefore constructing requests. - Behavioral Change:
variantvalues that are empty or escape-only now resolve toundefinedinstead of an empty string in OpenCodeAdapter.ts and OpenCodeTextGeneration.ts; callers relying on raw escape-preserved values will see cleaned strings.
- 1
github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:unvouched
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:M
Approvability#
Verdict: Approved at
4871e96Macroscope's review found this PR approvable — This is a focused bug fix that removes leaked terminal control sequences from OpenCode inventory data and stored selections, with regression coverage for the affected parsers. Normal values remain unchanged, and the PR introduces no schema, deployment, security, billing, authentication, product-default, or static-analysis configuration changes.
Notes:
- Diff unchanged. Approvability was decided on eligibility alone.
For anyone blocked on review/
vouch:unvouchedgating and needing this immediately — the fix is consumable now via forkhub, full how-to in #7754 (comment).TL;DR:
- Pre-patched:
ImBIOS/t3code@main(this PR merged) orgh pr checkout 7755 - Intent-patch (auto re-applies on every future upstream release until this PR merges, then
fh cleanup --apply):pnpm add -g "github:ImBIOS/forkhub#canary&path:packages/cli" fh init --target github.com/pingdotgg/t3code fh import https://github.com/ImBIOS/.forkhub/blob/main/repos/github.com/pingdotgg/t3code/patches/fix-t3code-strip-osc-ansi-escapes-from-opencode-cl-y7shx01y/INTENT.md fh re-derive fix-t3code-strip-osc-ansi-escapes-from-opencode-cl-y7shx01y # AI fills realization.diff from the bundle fh apply <bundle-path>
- Pre-patched:
Note: GPT-6 on behalf of shivam (@shivamhwp).
The OSC pattern does not span newlines. A title from a working directory named
my\nproject, emitted asESC ]0;my\nproject: ready BEL build (primary), leavesproject: ready\u0007buildas the parsed agent name, so this path still fails with an unknown agent. Make OSC removal span the complete title through BEL or ST, including embedded newlines, and add that case to the parser regression coverage.juliusmarminge added labelsmacroscope-review
macroscopeapp[bot](GitHub profile, opens in a new tab) approved these changes
Thanks for working on this. We merged the orchestrator V2 rewrite in #2829, and we are closing this PR as part of that transition.
This change touches OpenCodeAdapter.ts, which the V2 merge removed. OpenCode execution now uses V2 adapters and V2 run state.
Sorry for the extra work this creates. If the change is still needed on V2, please rebuild it on current main, verify it there, and open a new PR linking back here. We're closing the current implementation without assuming the underlying request is resolved.
juliusmarminge closed this
Sign in to join this conversation.
Important
Review skipped#
Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the
.coderabbit.yamlfile in this repository. To trigger a single review, invoke the@coderabbitai reviewcommand.⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID:
6a443a18-68b1-4789-bc42-939dde10e355You can disable this status message by setting the
reviews.review_statustofalsein the CodeRabbit configuration file.Use the checkbox below for a quick retry:
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
❤️ Share