Files
orca/src/shared/draft-paste-ready-scanner.ts
T
Neil 45f3512a33 feat(agents): add first-class DeepSeek Harness (dsh) support (#22468)
* feat(agents): add first-class DeepSeek Harness (dsh) support

Register DSH as a supervised Orca agent: catalog entry and detection for its
dsh-tui profile, status/question hooks through DeepSeek's own Claude-Code hook
bridge, composer-ready prompt delivery, session resume, headless Source Control
AI, and title identity that no longer collides with Gemini's.

* fix(dsh): reach Orca through DSH's credential scrub and stop reading its title as Gemini

DSH runs command hooks through its own shell executor, which drops every env var whose
name contains KEY, TOKEN, SECRET or PASSWORD — taking ORCA_PANE_KEY and
ORCA_AGENT_LAUNCH_TOKEN with it, so every hook exited without posting. Mirror both onto
scrub-safe aliases at spawn and restore them at the top of the DSH hook script.

Its title collided too: DSH rests on the same glyph Gemini works on, so a resting DSH
pane was relabelled Gemini CLI and reported working forever. Defer both the Gemini
classifier and the title status detector on DSH's whale, in the base module both copies
of that classifier read.

* test(mobile): repin the session-route closure for the DSH agent icon

* fix(dsh): address review — never splice user rows, cover remote panes, keep the diff off argv

- findManagedDshPatchRegion paired an orphan start marker with a later block's end, so a
  truncated write made install/remove delete the user's own rows. Pair each end with the
  nearest preceding start; regression test fails without the fix.
- The relay PTY env builder never applied the scrub-safe aliases, so remote DSH status
  silently never appeared even with the remote hook installed.
- Source Control AI sent the whole diff on argv; send it over stdin with DSH's '-' marker.
- dsh-tui/dst already chose the interactive profile, so a workspace folder named 'web' or
  'plugin' no longer marks a live agent pane non-interactive.
- Isolate USERPROFILE as well as HOME so a Windows run cannot edit the real home.
- Drop the duplicate README badge and revert an incidental doc reformat.

* refactor(dsh): share the managed-hooks reader and tighten the new modules

Reuse before reimplementing: readManagedDshHookEvents was a near-verbatim copy of Muse's,
with byte-identical private helpers. Both now call one readManagedHookEventsFromJson.

Also: one readTextOrAbsent instead of two spellings of the same read (dropping an
existsSync TOCTOU), one status() builder instead of four inline literals, rmSync(force)
instead of exists-then-unlink, and a redundant empty-string guard before JSON.parse.
The patch-file transforms lose their index juggling for a predicate plus a filter.

* fix(dsh): refuse a flow-style patch file, keep its mode, and stop the relay inheriting a pane

- applyManagedDshPatch matched only an exact `[]`, so `[] # keep empty` or a non-empty
  flow sequence got a block entry appended after it — invalid YAML that would leave DSH
  unable to load the user's own patch layer either. It now strips the token from an empty
  sequence (keeping a trailing comment) and returns null for a non-empty one; install
  reports that and changes nothing.
- The patch rewrite dropped an owner-only file to the umask default (CWE-732); pass
  preserveMode.
- The relay PTY env never dropped inherited pane identity the way the local and daemon
  builders do, so a spawn that specified none could inherit the relay's own and every
  agent's hook would report against that pane.

* fix(dsh): keep the flow-style refusal in every status read, and scope the mode test to POSIX

A refused patch file carries no managed region, so getStatus() fell through to a bare
not_installed with detail null — the actionable 'rewrite it as a block sequence' message
only ever reached the one-shot install() return. Export the predicate and check it first,
behind one shared message constant.

The owner-only mode assertion cannot hold on Windows, where chmod only toggles the
read-only attribute and mode & 0o777 reads 0o666 for any writable file.

* docs(readme): restore the DeepSeek Harness badge lost in the rebase

* test(mobile): repin the session-route closure to the measured 4221

Measured, not derived: 4220 without the DSH icon entry, 4221 with it. Two of the three
modules above main's 4218 pin are not this change's — they arrived with the mobile work
after #22570 and were never repinned; the changelog records that split explicitly.

* fix(dsh): settle tui-idle on the agent's own hook, so supervised workers see it ready

Reported by a tester on the adhoc build: `terminal wait --for tui-idle` ran to its 90s
timeout against an already-ready DSH composer, so a supervised worker never sees the agent
as ready.

Every existing tier reads the title, and DSH deliberately carries no title status: its rest
prefix is Gemini's working glyph, so the detector reports none. A fresh first-party `done`
is better evidence than any title anyway — it is the agent's own account of its own turn,
and normalizeDshEvent drops subagent events, so it is the lead's. Scoped to DSH: for agents
whose hooks report child turns, a mid-turn `done` is the #6011 class this file prevents.

* test(daemon): record the DSH transcript's true-colour I2 divergences

Adding the dsh-tui capture to __fixtures__ enrolled it in the serialize replay sweep, where
it reports 10 I2 divergences and failed the unlisted-transcript default of 0.

Every one is the same shape — visible-grid row=0, a 24-bit background the round trip does
not restore to default — which is DSH's whale intro painting whole rows of true colour.
Verified as an upstream limitation rather than a regression by replaying against the
previous build (build-serialize-addon-at-ref.mjs --ref origin/main): I1 and I3 both hold.

* fix(dsh): return the new tui-idle verdict from the first-party done lane

Main refactored isTuiIdleSatisfied into evaluateTuiIdle, which returns a verdict rather
than a boolean. The DSH lane still returned `true`; it is tier-1 positive evidence, so it
returns READY_STRONG like the title/body lane above it. Re-verified the regression test
still fails without the lane.

* test(relay): pin the scrub-safe pane-identity aliases on the relay spawn path

The relay builds a remote pane's env itself, so the alias mirroring there had no
test: removing the call left every suite green while remote DSH status silently
vanished. Both cases fail without it.

* docs(dsh): point the hook service at the integration reference

The reference doc had no inbound link from anywhere in the repo.
2026-09-27 22:44:18 -07:00

290 lines
14 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import type { DraftPasteReadySignal } from './tui-agent-config'
// Why: agents enable bracketed paste (DECSET 2004) before their composer is
// actually mounted/focused. These markers let the scanner detect the real
// "input is ready" moment per agent instead of guessing from output silence.
const DECSET_BRACKETED_PASTE = '\x1b[?2004h'
const CODEX_COMPOSER_PROMPT = '›'
// Why: opencode emits the DECTCEM show-cursor only once the composer row is
// mounted and the text cursor is placed in it — a "composer ready" signal,
// analogous to Codex's prompt glyph. It fires ~2s after bracketed paste is
// enabled, so gating on it (instead of a quiet window) stops the paste from
// racing the composer mount under slow/noisy startup. mimo-code uses the same
// signal by parity; the quiet-window fallback covers any agent that differs.
const DECTCEM_SHOW_CURSOR = '\x1b[?25h'
// Why: grok's composer prompt glyph (U+276F), rendered once the input box
// mounts. It is also the default glyph of popular shell prompts (starship,
// pure), so it is anchored on the alternate-screen switch below — the shell
// prompt that precedes the launch command is always in the normal buffer.
// grok swaps it for `> ` on legacy Windows consoles, which is too generic to
// match; those fall back to the quiet window and the caller's hard timeout.
const GROK_COMPOSER_PROMPT = '❯'
// Why: ZCode's composer box top-left corner (U+256D), painted once the input box mounts.
// It is locale-independent — ZCode translates the placeholder and the mode label in the
// box title, but not the frame — and its modal dialogs draw SQUARE corners, so this glyph
// means the composer specifically. Anchored on the alternate-screen switch for the same
// reason as grok: a powerline shell prompt can also draw `╭`.
const ZCODE_COMPOSER_BOX_CORNER = '╭'
const DECSET_ALT_SCREEN = '\x1b[?1049h'
const DECRST_ALT_SCREEN = '\x1b[?1049l'
type DraftPasteReadySignalSpec = {
/** Bytes that must precede `marker` for it to count; null when there is no marker. */
markerAnchor: string | null
/** Bytes that revoke `markerAnchor` again, for anchors that describe a mode the agent can leave. */
markerAnchorEnd: string | null
/** Composer-ready marker, or null for signals that only use the quiet window. */
marker: string | null
/** Bytes that arm the quiet-window fallback, or null when the signal has none. */
quietAnchor: string | null
}
const DRAFT_PASTE_READY_SIGNALS: Record<DraftPasteReadySignal, DraftPasteReadySignalSpec> = {
'codex-composer-prompt': {
markerAnchor: DECSET_BRACKETED_PASTE,
markerAnchorEnd: null,
marker: CODEX_COMPOSER_PROMPT,
quietAnchor: null
},
'render-cursor-after-bracketed-paste': {
markerAnchor: DECSET_BRACKETED_PASTE,
markerAnchorEnd: null,
marker: DECTCEM_SHOW_CURSOR,
quietAnchor: null
},
'grok-composer-prompt': {
markerAnchor: DECSET_ALT_SCREEN,
// Why: leaving the alternate screen hands the terminal back to the shell, whose
// prompt may be `❯`. Without revoking the anchor, a grok that entered the alt
// screen and then died — or a pager run from the user's shell rc before grok even
// launched — would leave the glyph armed forever and paste into the shell.
markerAnchorEnd: DECRST_ALT_SCREEN,
marker: GROK_COMPOSER_PROMPT,
// Why: the quiet window stays on DECSET 2004, independent of the alt-screen
// marker anchor. grok can be configured to render inline (`--no-alt-screen`,
// `[ui] screen_mode = "minimal"`), where 1049h never arrives — anchoring the
// fallback there too would leave the draft with no delivery path at all, and
// the main-process caller drops the draft when readiness never resolves.
quietAnchor: DECSET_BRACKETED_PASTE
},
// Why: DSH-TUI draws the same U+276F composer glyph inside the alternate screen, and
// animates its intro continuously behind it, so it needs grok's marker-plus-quiet shape
// rather than the default quiet window. Its own entry (not grok's) so the two agents'
// evidence — and any future divergence — stay separable.
'dsh-composer-prompt': {
markerAnchor: DECSET_ALT_SCREEN,
markerAnchorEnd: DECRST_ALT_SCREEN,
marker: GROK_COMPOSER_PROMPT,
quietAnchor: DECSET_BRACKETED_PASTE
},
'zcode-composer-prompt': {
markerAnchor: DECSET_ALT_SCREEN,
markerAnchorEnd: DECRST_ALT_SCREEN,
marker: ZCODE_COMPOSER_BOX_CORNER,
// Why: ZCode animates its ASCII banner forever, so the quiet window never settles on
// its own — but keep it armed as the floor for a build that renders inline and never
// switches to the alternate screen, where the marker anchor would never arm.
quietAnchor: DECSET_BRACKETED_PASTE
},
'render-quiet-after-bracketed-paste': {
markerAnchor: null,
markerAnchorEnd: null,
marker: null,
quietAnchor: DECSET_BRACKETED_PASTE
}
}
/** Longest anchor sequence minus one — the carry needed to rejoin one split across chunks. */
const ANCHOR_CARRY_CHARS = 7
export type DraftPasteReadyScanResult = {
/** The agent-specific ready signal fired — caller should deliver the paste now. */
ready: boolean
/** Caller should (re)arm the quiet-window fallback timer for this chunk. */
armQuietTimer: boolean
}
/**
* Pure, incremental scanner shared by the renderer and main-process draft-paste
* readiness waiters so the two delivery paths (desktop-local vs runtime/SSH/
* remote) cannot drift. It only parses the PTY byte stream; timers, the PTY
* subscription, and resolution stay with each caller because their transports
* and return types differ.
*
* Per agent signal:
* - `codex-composer-prompt`: ready when the `›` glyph renders after DECSET
* 2004, or when DECSET follows a glyph rendered while Codex owns the
* alternate screen; never arms the quiet window.
* - `render-cursor-after-bracketed-paste`: ready when DECTCEM show-cursor
* (`\x1b[?25h`) renders after DECSET 2004. Like Codex it does NOT arm the
* quiet window: opencode stays silent for ~1.5-2s between enabling
* bracketed paste and mounting its composer, so a quiet window would fire
* during that gap and pre-empt the marker. opencode re-emits show-cursor on
* every render frame once mounted, so the marker is effectively guaranteed;
* the caller's hard timeout is the backstop if it never appears.
* - `grok-composer-prompt`: ready when grok's `❯` glyph renders after the
* alternate-screen switch (`\x1b[?1049h`). grok shimmers its startup logo
* until the session opens, so the quiet window alone never settles and the
* draft waited out the full hard timeout (~8s). The glyph is anchored on the
* alt-screen switch rather than DECSET 2004 because the shell that runs the
* launch command emits 2004 too and its own prompt may be `❯` (starship,
* pure) — anchoring there could paste into the shell. This is the only
* signal with both a marker and a quiet window, and they use DIFFERENT
* anchors: grok can render inline (`--no-alt-screen`, `[ui] screen_mode =
* "minimal"`) and on legacy Windows consoles draws `> ` instead of `❯`, so
* the marker is best-effort and the 2004-anchored quiet window is the floor
* that keeps those launches on the pre-existing delivery path. The alt-screen
* anchor is revoked on `\x1b[?1049l`: leaving it hands the terminal back to
* the shell, so a glyph after that is the shell's prompt, not grok's composer.
* - `dsh-composer-prompt`: the grok shape applied to DSH-TUI, whose composer draws the
* same `❯` inside the alternate screen. The committed
* `dsh-tui-ready-no-key.txt` transcript is the evidence: DECSET 2004 at byte 6,
* `\x1b[?1049h` at byte 40, and the first `❯` at byte 5910.
* - `zcode-composer-prompt`: ready when ZCode's composer box corner (`╭`) renders
* after the alternate-screen switch. ZCode repaints its animated ASCII banner
* indefinitely — the captured transcript is still repainting 30s after the composer
* mounted — so the quiet window alone never settles and a launch draft would wait out
* the whole hard timeout, exactly as grok did. Same alt-screen anchoring and
* revocation as grok, because a powerline shell prompt can draw `╭` too.
* - `render-quiet-after-bracketed-paste` (default): no signal marker; arms the
* quiet window once DECSET 2004 is seen.
*
* A 512-byte ring (`recent` / `postAnchorRecent`) covers escape sequences
* split across chunk boundaries without retaining terminal scrollback.
*/
export function createDraftPasteReadyScanner(readySignal: DraftPasteReadySignal): {
observe: (data: string) => DraftPasteReadyScanResult
} {
let recent = ''
let postAnchorRecent = ''
let anchorCarry = ''
let codexCarry = ''
let sawMarkerAnchor = false
let sawQuietAnchor = false
let codexAltScreen = false
let sawCodexPromptInAltScreen = false
const {
markerAnchor,
markerAnchorEnd,
marker: signalMarker,
quietAnchor
} = DRAFT_PASTE_READY_SIGNALS[readySignal]
/**
* Why: an anchor the agent can leave (the alternate screen) has to be tracked in
* stream ORDER, not as "seen once". Walk the chunk segment by segment so a marker
* only counts while the anchor is actually held, and re-entering re-arms it.
* Only reachable for signals that define `markerAnchorEnd`.
*/
const scanRevocableAnchorSegments = (window: string, anchor: string, end: string): boolean => {
let cursor = 0
while (cursor < window.length) {
if (!sawMarkerAnchor) {
const enterIndex = window.indexOf(anchor, cursor)
if (enterIndex === -1) {
return false
}
sawMarkerAnchor = true
postAnchorRecent = ''
cursor = enterIndex + anchor.length
continue
}
const leaveIndex = window.indexOf(end, cursor)
const segment = leaveIndex === -1 ? window.slice(cursor) : window.slice(cursor, leaveIndex)
if ((postAnchorRecent + segment).includes(signalMarker ?? '')) {
return true
}
if (leaveIndex === -1) {
postAnchorRecent = (postAnchorRecent + segment).slice(-512)
return false
}
sawMarkerAnchor = false
postAnchorRecent = ''
cursor = leaveIndex + end.length
}
return false
}
const scanCodexPreAnchorPrompt = (data: string): void => {
const window = codexCarry + data
codexCarry = window.slice(-ANCHOR_CARRY_CHARS)
let cursor = 0
while (cursor < window.length) {
const enterIndex = window.indexOf(DECSET_ALT_SCREEN, cursor)
const leaveIndex = window.indexOf(DECRST_ALT_SCREEN, cursor)
const promptIndex = window.indexOf(CODEX_COMPOSER_PROMPT, cursor)
const nextIndex = Math.min(
...[enterIndex, leaveIndex, promptIndex].filter((index) => index !== -1)
)
if (!Number.isFinite(nextIndex)) {
return
}
if (nextIndex === enterIndex) {
codexAltScreen = true
sawCodexPromptInAltScreen = false
cursor = nextIndex + DECSET_ALT_SCREEN.length
} else if (nextIndex === leaveIndex) {
codexAltScreen = false
sawCodexPromptInAltScreen = false
cursor = nextIndex + DECRST_ALT_SCREEN.length
} else {
if (codexAltScreen) {
sawCodexPromptInAltScreen = true
}
cursor = nextIndex + CODEX_COMPOSER_PROMPT.length
}
}
}
return {
observe(data: string): DraftPasteReadyScanResult {
const combined = recent + data
recent = combined.slice(-512)
if (!sawQuietAnchor && quietAnchor !== null && combined.includes(quietAnchor)) {
sawQuietAnchor = true
}
if (readySignal === 'codex-composer-prompt' && !sawMarkerAnchor) {
scanCodexPreAnchorPrompt(data)
}
if (signalMarker !== null && markerAnchor !== null) {
if (markerAnchorEnd !== null) {
// Why: carry only the bytes an anchor could straddle, so already-scanned
// output is never re-walked into a second enter/leave transition.
const window = anchorCarry + data
anchorCarry = window.slice(-ANCHOR_CARRY_CHARS)
if (scanRevocableAnchorSegments(window, markerAnchor, markerAnchorEnd)) {
return { ready: true, armQuietTimer: false }
}
} else if (!sawMarkerAnchor) {
const anchorIndex = combined.indexOf(markerAnchor)
if (anchorIndex !== -1) {
sawMarkerAnchor = true
if (readySignal === 'codex-composer-prompt' && sawCodexPromptInAltScreen) {
return { ready: true, armQuietTimer: false }
}
const postAnchorChunk = combined.slice(anchorIndex + markerAnchor.length)
if (postAnchorChunk.includes(signalMarker)) {
return { ready: true, armQuietTimer: false }
}
postAnchorRecent = postAnchorChunk.slice(-512)
}
} else {
if (data.includes(signalMarker) || (postAnchorRecent + data).includes(signalMarker)) {
return { ready: true, armQuietTimer: false }
}
postAnchorRecent = (postAnchorRecent + data).slice(-512)
}
}
// Why: the Codex glyph and opencode show-cursor signals must NOT arm the
// quiet window (they carry no quiet anchor). opencode goes silent for
// ~1.5-2s between enabling bracketed paste and mounting its composer, so a
// quiet window would fire during that gap — before the composer exists —
// and pre-empt the marker. Those signals wait for their marker, bounded
// only by the caller's hard timeout (and its best-effort
// process-ownership paste after that).
return { ready: false, armQuietTimer: sawQuietAnchor }
}
}
}