Skip to content
Source
Sign inSign up
pingdotgg/t3code

fix(server): strip OSC/ANSI escapes from OpenCode CLI inventory and stored agent selections #7755

ClosedImBIOS(GitHub profile, opens in a new tab)wants to merge 1 commit intomain fromrefs/pull/7755/headopened View on GitHub

Fixes #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 of parseModels/Agent/Skills; keeps -verbose from dropping models and skills from degrading
  • apps/server/src/provider/Layers/OpenCodeProvider.ts:164,188,393 — sanitize inventory agent names/variants + --version parsing
  • apps/server/src/provider/Layers/OpenCodeAdapter.ts:1476 + textGeneration/OpenCodeTextGeneration.ts:411 — sanitize stored agent/variant before promptAsync (steer + title generation)
  • packages/shared/src/model.ts:66,313 — sanitize persisted ProviderOptionSelection values 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 -v still shows OSC upstream, but parse*CliOutput now 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 stripTerminalEscapes and sanitizeTerminalValue in stripTerminalEscapes.ts to remove terminal control sequences from strings captured from CLIs.
  • Applies stripTerminalEscapes to raw stdout in parseModelsCliOutput, parseAgentListCliOutput, parseSkillsCliOutput, and checkOpenCodeProviderStatus so slugs, agent names, and version strings parse correctly when the CLI leaks OSC/ANSI sequences.
  • Uses sanitizeTerminalValue in getProviderOptionStringSelectionValue, normalizeCustomModelSlug, and trimOrNull to clean model slugs and option selections; empty-after-sanitize results become undefined or null.
  • Sanitizes agent and variant values read from model selection in makeOpenCodeAdapter and makeOpenCodeTextGeneration before constructing requests.
  • Behavioral Change: variant values that are empty or escape-only now resolve to undefined instead of an empty string in OpenCodeAdapter.ts and OpenCodeTextGeneration.ts; callers relying on raw escape-preserved values will see cleaned strings.
Macroscope summarized 4871e96.
    1. Important

      Review skipped

      Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

      ⚙️ Run configuration

      Configuration used: Repository UI

      Review profile: CHILL

      Plan: Pro Plus

      Run ID: 6a443a18-68b1-4789-bc42-939dde10e355

      You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

      Use the checkbox below for a quick retry:

      • 🔍 Trigger review

      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
      Comment `@coderabbitai help` to get the list of available commands.
    2. github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:unvouched

    3. macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      Approvability

      Verdict: Approved at 4871e96

      Macroscope'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.
      You can add or adjust custom eligibility rules. [Learn more](https://docs.macroscope.com/approvability#example-custom-eligibility-rules).
    4. For anyone blocked on review/vouch:unvouched gating 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) or gh 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>
    5. 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 as ESC ]0;my\nproject: ready BEL build (primary), leaves project: ready\u0007build as 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.

    6. juliusmarminge added labelsmacroscope-review

    7. 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.

    8. juliusmarminge closed this

Sign in to join this conversation.