The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
Dead code leaves the core: what only tests reached, and two cases nothing sends (#845)
Deed7039faf6b41
diff --git a/cli/src/architecture.spec.ts b/cli/src/architecture.spec.tsindex 0c799032e..0bf3c12dc 100644--- a/cli/src/architecture.spec.ts+++ b/cli/src/architecture.spec.ts@@ -66,7 +66,7 @@ function runForegroundLines(): number {* those moves, and runForeground gained 28.*/const RUN_FOREGROUND_BUDGET = 2_600-const BACKEND_SOCKET_BUDGET = 2_370+const BACKEND_SOCKET_BUDGET = 2_320/** Exceptions, each with its reason. Keep this short. */const SERVICE_MAY_IMPORT: Record<string, string> = {diff --git a/cli/src/backendSocket.spec.ts b/cli/src/backendSocket.spec.tsindex a88107343..aa3203e15 100644--- a/cli/src/backendSocket.spec.ts+++ b/cli/src/backendSocket.spec.ts@@ -1105,9 +1105,9 @@ describe('BackendSocket outbound queue', () => {await socket.stop()})- it('seals what a pane runs and where a spoken task went to a requester that holds a session, and to it alone', async () => {- // A pane's folder, pid and tty, and the router's restatement of a spoken task, used to go to every- // web client in the clear. Every client that holds a session opens a sealed payload of any type.+ it('seals what a pane runs to a requester that holds a session, and to it alone', async () => {+ // A pane's folder, pid and tty used to go to every web client in the clear. Every client that holds a+ // session opens a sealed payload of any type.const socket = new BackendSocket('token')// `terminal_info` is the core's (core/terminals/requests.ts), bound here as the daemon binds it.bindTerminalRequests(socket)@@ -1121,28 +1121,23 @@ describe('BackendSocket outbound queue', () => {unwrap.mockReturnValueOnce({ type, payload })ws.message({ t: 'down', connId, frame: { type, payload: { __e2e: { v: 1, k: 's', n: 1, ct: 'ciphertext' } } } })}- const answers = () => parseSent(ws).filter((item) => ['terminal_info_result', 'voice_route_result'].includes(String((item.frame as { type?: unknown })?.type)))+ const answers = () => parseSent(ws).filter((item) => (item.frame as { type?: unknown })?.type === 'terminal_info_result')ask('web-1', 'terminal_info', { requestId: 'info-1', agentId: 'no-such-agent' })- ask('web-1', 'voice_route', { requestId: 'route-1', transcript: '' })- await vi.waitFor(() => expect(answers()).toHaveLength(2))+ await vi.waitFor(() => expect(answers()).toHaveLength(1))expect(wrap).toHaveBeenCalledWith('web-1', 'terminal_info_result', 'info-1', { error: 'AGENT_NOT_FOUND' })- expect(wrap).toHaveBeenCalledWith('web-1', 'voice_route_result', 'route-1', { error: 'MISSING_TRANSCRIPT' })const sealed = { __e2e: { v: 1, k: 'p', n: 1, ct: 'ciphertext' } }expect(answers()).toEqual([{ t: 'up', targetConnId: 'web-1', frame: { type: 'terminal_info_result', payload: sealed } },- { t: 'up', targetConnId: 'web-1', frame: { type: 'voice_route_result', payload: sealed } },])// A requester whose session went away meanwhile gets the bare refusal a refused request gets, never// the answer in the clear.ask('web-2', 'terminal_info', { requestId: 'info-2', agentId: 'no-such-agent' })- await vi.waitFor(() => expect(answers()).toHaveLength(3))- expect(answers()[2]).toEqual({ t: 'up', targetConnId: 'web-2', frame: { type: 'terminal_info_result', payload: { requestId: 'info-2', error: 'E2EE_REQUIRED' } } })- // Only the replies: the requests keep the rule they had, since an older daemon reads a sealed one as empty.- for (const type of ['terminal_info', 'voice_route']) {- expect(encryptDownFrame(type)).toBe(false)- expect(encryptDownFrameFor(type, { strictDown: true })).toBe(false)- expect(encryptRpcResult(`${type}_result`)).toBe(true)- }+ await vi.waitFor(() => expect(answers()).toHaveLength(2))+ expect(answers()[1]).toEqual({ t: 'up', targetConnId: 'web-2', frame: { type: 'terminal_info_result', payload: { requestId: 'info-2', error: 'E2EE_REQUIRED' } } })+ // Only the reply: the request keeps the rule it had, since an older daemon reads a sealed one as empty.+ expect(encryptDownFrame('terminal_info')).toBe(false)+ expect(encryptDownFrameFor('terminal_info', { strictDown: true })).toBe(false)+ expect(encryptRpcResult('terminal_info_result')).toBe(true)await socket.stop()})diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.tsindex 4c6103635..ea7d754f1 100644--- a/cli/src/backendSocket.ts+++ b/cli/src/backendSocket.ts@@ -74,7 +74,6 @@ import { Address, Id, OperationId, Receipt, TeamError, type MemberRuntime } fromimport { shellQuote } from './orchestrator/prompts.js'import type { SessionInputDelivery } from './lib/sessionInput.js'import { terminalHandoffRequest } from './lib/terminalHandoff.js'-import { routeVoiceTask } from './lib/voiceRouter.js'import { MediaPreviewError, readMediaPreviewChunk } from './lib/mediaPreview.js'import { ViewerForwarder } from './lib/viewerForwarder.js'import { InteractiveViewers } from './lib/interactiveViewer.js'@@ -103,10 +102,6 @@ import {type TerminalP2pSignal,} from './lib/terminalP2p.js'-/** Answers the device `project_recent` RPC — set by cli.ts to the CommanderMirror's `recent`. */-export type RecentProvider = (sessionId: string, n: number) => Array<{ kind: string; text: string; recap?: string }>--const APP_PING_MS = 15_000// Floor between two `app_presence` up-frames while a window is attached. Rides the 15s app-ping// tick; the backend only needs to hear about it about once a minute (it floors its own Mongo write@@ -517,8 +512,6 @@ export class BackendSocket {/** Called when this machine is already connected from ANOTHER computer (HTTP 409 on the upgrade) — the* SSO session is valid, so CLI keeps it and stops without a retry loop. */onBusy: (() => void) | null = null- /** An agent's last turn summaries, which `voice_route` routes by (cli.ts wires this to the recaps). */- recentProvider: RecentProvider | null = null/** Answers `agent_recent` with the whole reply: an agent's last turn summaries and the person's last* questions, for a device's tiles (cli.ts binds core/turns/recaps.ts). Null answers UNSUPPORTED. */agentRecentProvider: ((payload: Record<string, unknown>) => Record<string, unknown>) | null = null@@ -1988,34 +1981,6 @@ export class BackendSocket {else answer({ error: 'UNSUPPORTED' })return- case 'voice_route': {- // Voice router (REMOTE machine): pick the best-fit agent for a transcribed Overview voice task,- // using each agent's name + recent-turn recap. Once asked plaintext by the backend's legacy- // device-ws voice path; that path no longer reaches a harness machine, and the relay gate now- // refuses it unsealed like any other RPC.- const transcript = typeof payload.transcript === 'string' ? payload.transcript : ''- if (!transcript.trim()) {- console.log('[voice-route] backend sent an empty transcript — nothing to route')- reply(type, requestId, { error: 'MISSING_TRANSCRIPT' })- return- }- const projects = (await Promise.all(registry.advertised().map((s) => this.toProject(s)))).slice(0, 24) // cap the router prompt (mirror the hosted runtime path)- const agents = projects.map((p) => {- // Use the last 3 turns' recaps (not just 1) — a single turn can misrepresent what the agent is- // actually working on; 3 gives the router a more stable picture.- const recents = this.recentProvider?.(p.id, 3) ?? []- const recentSummary = recents.map((r) => r?.recap || r?.text || '').filter(Boolean).join(' · ')- // engine: the router classifies with a CLI the machine actually runs (a live agent proves it is- // installed and logged in), so it has to travel with the agent.- const session = registry.resolve(p.id)- return { id: p.id, name: p.name, recentSummary, engine: session?.engine, gateway: session?.gateway }- })- const decision = await routeVoiceTask(transcript, agents) // logs the task, candidates and pick- const chosen = projects.find((p) => p.id === decision.agentId)- reply(type, requestId, { ...decision, agentName: chosen?.name ?? '' })- return- }-// A rename, a model and effort, or an app opening the agent (core/agents/update.ts, bound by cli.ts).case 'agent_update':if (this.agentUpdateProvider) await this.agentUpdateProvider(payload, answer)@@ -2263,22 +2228,6 @@ export class BackendSocket {// A person interrupting an agent's turn (core/turns/cancel.ts, bound by cli.ts).case 'cancel': this.cancelProvider?.(payload); return- case 'speaking': {- // A device is capturing a voice instruction. Mirror the hosted runtime: re-broadcast the presence- // signal to the web (indicator) + other devices. Ephemeral, no requestId.- const p = payload as { speaking?: boolean; agentId?: string; sessionId?: string }- const sessionId = p.sessionId ?? p.agentId- const projectId = p.agentId ?? p.sessionId ?? null- const on = p.speaking !== false- // Echo the canonical agent id, whichever id the sender used to address it.- const speaker = projectId ? registry.resolve(projectId) : undefined- const speakerAgentId = speaker?.agentId ?? projectId- const evt = { type: 'speaking', dbSessionId: speaker?.sessionId ?? sessionId, agentId: speakerAgentId, payload: { speaking: on, agentId: speakerAgentId, sessionId: speaker?.sessionId ?? sessionId } }- this.send(evt) // web- this.sendCommander(evt) // other devices (firmware ignores its own echo; matches node forwardToCommander)- return- }-// A person's answer to an agent's question, keyed into its dialog (core/questions.ts, bound by cli.ts).case 'question_response':this.questionProvider?.(payload, answer)diff --git a/cli/src/cli.ts b/cli/src/cli.tsindex dc09a5805..dbe6827c9 100644--- a/cli/src/cli.ts+++ b/cli/src/cli.ts@@ -2286,7 +2286,6 @@ async function runForeground(session: AuthSession | null): Promise<void> {// Recaps are STORED under the engine session id — that is what lets `--resume` bring the last recap// back under a brand-new agent — but they are ASKED FOR by agent id, which is the only id the device// and the voice router know. Resolve across the two, or every tile restores empty.- backend.recentProvider = recaps.recentbackend.agentRecentProvider = recaps.agentRecent// "Change agent": the desktop asks for the structured handoff file (lib/agentHandoff.ts) before itdiff --git a/cli/src/dsh/manifest.spec.ts b/cli/src/dsh/manifest.spec.tsindex c21ee361c..1e67bccd1 100644--- a/cli/src/dsh/manifest.spec.ts+++ b/cli/src/dsh/manifest.spec.ts@@ -2,7 +2,7 @@ import { PROCESS_ENGINES } from '../engines/types.js'import { describe, expect, it } from 'vitest'import { readFileSync } from 'node:fs'import { fileURLToPath } from 'node:url'-import { DshManifestSchema, dshSupportedEngines, dshTier, dshVerdictPath, dshViewerName, expandDshValue, parseDshManifest, readDshManifest , isViewerPackage, dshEngine, viewerUse} from './manifest.js'+import { DshManifestSchema, dshSupportedEngines, dshTier, dshVerdictPath, dshViewerName, expandDshValue, parseDshManifest, readDshManifest , isViewerPackage, viewerUse} from './manifest.js'const STARTER = fileURLToPath(new URL('../../../store/starter', import.meta.url))@@ -110,7 +110,7 @@ describe('spec 1.1: package kinds and viewer.use', () => {expect(viewer.ok).toBe(true)if (viewer.ok) {expect(isViewerPackage(viewer.manifest)).toBe(true)- expect(dshEngine(viewer.manifest)).toBeNull()+ expect(viewer.manifest.engine).toBeUndefined()expect(dshTier(viewer.manifest)).toBe(2)}expect(parseDshManifest(JSON.stringify({ ...base, kind: 'viewer' })).ok).toBe(false)diff --git a/cli/src/dsh/manifest.ts b/cli/src/dsh/manifest.tsindex d7015f6e8..ab0c6f174 100644--- a/cli/src/dsh/manifest.ts+++ b/cli/src/dsh/manifest.ts@@ -98,8 +98,6 @@ export const DshManifestSchema = z.strictObject({export type DshManifest = z.infer<typeof DshManifestSchema>-export type DshViewerSpec = z.infer<typeof OwnViewerSchema>-export type DshViewerUse = z.infer<typeof UsedViewerSchema>/** True for a viewer package: a pane others point at, never a tile. */export function isViewerPackage(manifest: DshManifest): boolean {@@ -124,11 +122,6 @@ export function dshViewerName(manifest: DshManifest, nameOf: (id: string) => strreturn `${manifest.name} Viewer`}-/** The base engine of an agent package; a viewer package answers null. */-export function dshEngine(manifest: DshManifest): DshManifest['engine'] | null {- return manifest.engine ?? null-}-/*** The `agent.env` key a harness names its permission mode in (`PERMISSION_MODES`), run whatever New* Harness picked — for a harness whose job the engine's sandbox cannot do (Grid starts model serversdiff --git a/cli/src/dsh/registry.spec.ts b/cli/src/dsh/registry.spec.tsindex d57ee31c8..84575fd85 100644--- a/cli/src/dsh/registry.spec.ts+++ b/cli/src/dsh/registry.spec.ts@@ -9,7 +9,7 @@ import { join } from 'node:path'import { pathToFileURL } from 'node:url'import { env } from '../config/env.js'import {- bundledDshRegistry, HARNESS_MONOREPO, readRegistryDir, readStoreDir, registryEntry, registrySourceUrl,+ bundledDshRegistry, HARNESS_MONOREPO, readRegistryDir, readStoreDir, registrySourceUrl,resetBundledDshRegistry, storeEntry, StoreExampleSchema, StoreFactsSchema,} from './registry.js'@@ -177,8 +177,6 @@ describe('bundledDshRegistry, as baked into a release', () => {const first = bundledDshRegistry()expect(first.map((entry) => `${entry.id} ${entry.name}`)).toEqual(['alpha/one Alpha', 'pane/viewer Pane', 'zeta/one Zeta'])expect(bundledDshRegistry()).toBe(first)- expect(registryEntry('zeta/one')?.repo).toBe('https://example.com/zeta')- expect(registryEntry('nobody/here')).toBeUndefined()})it('a malformed bake is an empty registry, not a crash', () => {diff --git a/cli/src/dsh/registry.ts b/cli/src/dsh/registry.tsindex 35ae1b595..d6feaffbf 100644--- a/cli/src/dsh/registry.ts+++ b/cli/src/dsh/registry.ts@@ -37,7 +37,6 @@ export const StoreExampleSchema = z.object({caption: z.string().trim().min(1).max(120).optional(),})-export type StoreExample = z.infer<typeof StoreExampleSchema>/** A folder inside a repo: relative, forward slashes, no `.`/`..` segments, no trailing slash. */export const PACKAGE_PATH_RE = /^(?!\/)(?!.*\/$)(?!.*\/\/)(?!(?:.*\/)?\.{1,2}(?:\/|$))[A-Za-z0-9._\-/]+$/@@ -100,7 +99,6 @@ export const StoreFactsSchema = z.strictObject({listed: z.boolean().optional(),})-export type StoreFacts = z.infer<typeof StoreFactsSchema>/** The shelf's two folders and the kind each holds. */export const STORE_KINDS = [['agents', 'agent'], ['viewers', 'viewer']] as const@@ -225,10 +223,6 @@ export function registrySourceUrl(entry: Pick<DshRegistryEntry, 'repo' | 'ref' |return `${repo}/tree/${entry.ref ?? 'main'}/${entry.path}`}-export function registryEntry(id: string): DshRegistryEntry | undefined {- return bundledDshRegistry().find((entry) => entry.id === id)-}-/** Test seam. */export function resetBundledDshRegistry(): void {cached = nulldiff --git a/cli/src/dsh/verdict.spec.ts b/cli/src/dsh/verdict.spec.tsindex 677ba3c71..58af249d3 100644--- a/cli/src/dsh/verdict.spec.ts+++ b/cli/src/dsh/verdict.spec.ts@@ -3,7 +3,7 @@ import type { EventEmitter } from 'node:events'import { mkdtempSync, rmSync, writeFileSync, mkdirSync } from 'node:fs'import { tmpdir } from 'node:os'import { join } from 'node:path'-import { DshVerdictWatcher, parseVerdict, readVerdictFile, type DshVerdict } from './verdict.js'+import { DshVerdictWatcher, parseVerdict, type DshVerdict } from './verdict.js'describe('parseVerdict', () => {it('reduces a spec-1 verdict to the wire shape', () => {@@ -113,16 +113,10 @@ describe('DshVerdictWatcher', () => {})})-describe('readVerdictFile and the edges of parseVerdict', () => {- it('reads a verdict off disk, or null when there is no file', () => {- const dir = mkdtempSync(join(tmpdir(), 'dsh-verdict-file-'))- try {- writeFileSync(join(dir, 'verdict.json'), JSON.stringify({ spec: 1, ready: true, summary: ' ', findings: 'none', artifact: '' }))- expect(readVerdictFile(join(dir, 'verdict.json'))).toEqual({ ready: true, summary: null, errors: 0, warnings: 0, artifact: null, phases: [], updatedAt: null })- expect(readVerdictFile(join(dir, 'missing.json'))).toBeNull()- } finally {- rmSync(dir, { recursive: true, force: true })- }+describe('the edges of parseVerdict', () => {+ it('reads a blank summary, no findings and an empty artifact as nothing', () => {+ expect(parseVerdict(JSON.stringify({ spec: 1, ready: true, summary: ' ', findings: 'none', artifact: '' })))+ .toEqual({ ready: true, summary: null, errors: 0, warnings: 0, artifact: null, phases: [], updatedAt: null })})it('caps the summary, refuses an overlong artifact, and skips a phase that is a list', () => {diff --git a/cli/src/dsh/verdict.ts b/cli/src/dsh/verdict.tsindex 354d51c94..741be4ef7 100644--- a/cli/src/dsh/verdict.ts+++ b/cli/src/dsh/verdict.ts@@ -97,14 +97,6 @@ export function parseVerdict(text: string): DshVerdict | null {}}-export function readVerdictFile(file: string): DshVerdict | null {- try {- return parseVerdict(readFileSync(file, 'utf8'))- } catch {- return null- }-}-const DEBOUNCE_MS = 150interface Watched {diff --git a/cli/src/lib/e2ee/applicationFrames.ts b/cli/src/lib/e2ee/applicationFrames.tsindex f194ac376..22072f97c 100644--- a/cli/src/lib/e2ee/applicationFrames.ts+++ b/cli/src/lib/e2ee/applicationFrames.ts@@ -86,8 +86,6 @@ const QUESTION_RESULT = 'question_response_result'const SEALED_REPLIES = new Set([// What a pane runs and where: its folder, pid and tty.'terminal_info_result',- // Which agent a spoken task went to, and the router's reason, which restates the task.- 'voice_route_result',// The rest of what a machine tells the client that asked about it: its Store harnesses, its engines// and their versions, its grids and models, the login an engine uses (with the computer's name), a// move onto a model, and a terminal handed between machines (refused over the relay).diff --git a/cli/src/lib/goalCommand.ts b/cli/src/lib/goalCommand.tsindex fdcb6b851..23ee3cdb8 100644--- a/cli/src/lib/goalCommand.ts+++ b/cli/src/lib/goalCommand.ts@@ -9,7 +9,7 @@ import type { AgentEngine } from '../engines/types.js'* unknown-command error in the user's terminal, so each is adapted per engine.** The backend prepends UNCONDITIONALLY — it does not know the engine. On the routed path it picks the- * agent only after transcribing, and `voice_route` replies without an engine field; the fixed-agent and+ * agent only after transcribing, and its router answers without the engine; the fixed-agent and* route_confirm paths would each need their own lookup. This module is the one place that always knows* the engine (`registry.get(sessionId).engine`), so the filtering lives here for every path at once.*/diff --git a/cli/src/lib/gridAssignment.spec.ts b/cli/src/lib/gridAssignment.spec.tsindex b5bb04546..666408e78 100644--- a/cli/src/lib/gridAssignment.spec.ts+++ b/cli/src/lib/gridAssignment.spec.ts@@ -2,7 +2,7 @@ import { afterEach, describe, expect, it } from 'vitest'import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'import { tmpdir } from 'node:os'import { join } from 'node:path'-import { assignmentMatches, classifyGridAssignment, probeGridAssignment, readOpencodeGridAssignment, readPiGridAssignment } from './gridAssignment.js'+import { classifyGridAssignment, probeGridAssignment, readOpencodeGridAssignment, readPiGridAssignment } from './gridAssignment.js'import { buildGridEngineLaunch, gridCapableEngines, type GridLaunchOverride } from './gridLaunch.js'import type { AgentEngine } from '../engines/types.js'import { clearProcessEnvCache, parsePsEnviron } from './processEnv.js'@@ -77,9 +77,9 @@ describe('classifyGridAssignment', () => {.toEqual({ baseUrl: RELAY_V1, model: 'DeepSeek-V4-Flash-0731' })// ⚠️ Grok ALWAYS carries `-m`, unlike codex: its grid credential rides on a declared model block,// so "let the grid route" is spelled `-m Auto` rather than by omitting the flag. Reporting that id- // verbatim would print `Auto` where the app prints its own Auto row from null, and- // `assignmentMatches` would compare 'Auto' against null and call every routed agent misplaced,- // forever — the same trap opencode's reader documents.+ // verbatim would print `Auto` where the app prints its own Auto row from null, and a check that the+ // agent is where the person put it would compare 'Auto' against null and call every routed agent+ // misplaced, forever — the same trap opencode's reader documents.expect(classifyGridAssignment('grok', env, 'grok -m Auto')).toEqual({ baseUrl: RELAY_V1, model: null })})@@ -128,9 +128,6 @@ describe('Pi, whose endpoint lives in a file', () => {baseUrl: RELAY_V1,model: 'GLM-4.7-Flash',})- await expect(readPiGridAssignment(env, args)).resolves.toSatisfy(- (a: { baseUrl: string; model: string | null }) => assignmentMatches(a, NETWORK_ID, 'GLM-4.7-Flash'),- )})it('a config directory that is gone reads as unknown, not as fine', async () => {@@ -156,33 +153,6 @@ describe('Pi, whose endpoint lives in a file', () => {})})-describe('assignmentMatches', () => {- const assignment = { baseUrl: RELAY, model: 'GLM-4.7-Flash' }-- it('matches the grid and the model the user picked', () => {- expect(assignmentMatches(assignment, NETWORK_ID, 'GLM-4.7-Flash')).toBe(true)- })-- it('does not match a different grid, or the same grid on a different model', () => {- expect(assignmentMatches(assignment, 'grid-e3b210eacc5b4cdf', 'GLM-4.7-Flash')).toBe(false)- expect(assignmentMatches(assignment, NETWORK_ID, 'DeepSeek-V4-Flash-0731')).toBe(false)- expect(assignmentMatches(assignment, NETWORK_ID, null)).toBe(false)- })-- it('treats an unknown assignment as not matching, never as fine', () => {- // The whole point: "we could not tell" must cost a needless move offer, never a silent claim that- // an agent is already where the user asked for.- expect(assignmentMatches(null, NETWORK_ID, null)).toBe(false)- expect(assignmentMatches(undefined, NETWORK_ID, null)).toBe(false)- })-- it('matches an unpinned model only against an unpinned choice', () => {- const unpinned = { baseUrl: RELAY, model: null }- expect(assignmentMatches(unpinned, NETWORK_ID, null)).toBe(true)- expect(assignmentMatches(unpinned, NETWORK_ID, 'GLM-4.7-Flash')).toBe(false)- })-})-describe('readOpencodeGridAssignment', () => {const dirs: string[] = []afterEach(() => {@@ -237,8 +207,8 @@ describe('readOpencodeGridAssignment', () => {it('reports the router as NO model, the way every other engine does', async () => {// OpenCode is the only engine whose provider block must name something, so a launch with no// model picked writes the relay's router id there. Letting that id back out would be the app's- // own "Auto" under a second name: the header would print the raw id, and `assignmentMatches`- // would compare it against null and call every such agent mis-targeted forever.+ // own "Auto" under a second name: the header would print the raw id, and a check that the agent is+ // where the person put it would compare it against null and call every such agent mis-targeted forever.const path = write(config(RELAY, ['Auto']))await expect(readOpencodeGridAssignment({ OPENCODE_CONFIG: path })).resolves.toEqual({ baseUrl: RELAY, model: null })diff --git a/cli/src/lib/gridAssignment.ts b/cli/src/lib/gridAssignment.tsindex 3f3a32b4b..106f15a7a 100644--- a/cli/src/lib/gridAssignment.ts+++ b/cli/src/lib/gridAssignment.ts@@ -125,8 +125,9 @@ export function classifyGridAssignment(// Grok's launch always passes `-m`, unlike every other argv engine: its grid credential rides on a// declared `[model.<id>]` block, so "let the grid route" is spelled by declaring the ROUTER rather// than by omitting the flag. Reporting that id verbatim would print `Auto` where the app prints its- // own Auto row from null, and `assignmentMatches` would compare 'Auto' against null and call every- // routed grok agent misplaced, forever — the trap `readOpencodeGridAssignment` documents below.+ // own Auto row from null, and a check that the agent is where the person put it would compare 'Auto'+ // against null and call every routed grok agent misplaced, forever — the trap+ // `readOpencodeGridAssignment` documents below.//// Scoped to grok because for anyone else a model literally named `Auto` is a model, and blanking it// would be this function inventing a meaning the launch never gave it. Opencode reaches the same@@ -210,9 +211,9 @@ export async function readOpencodeGridAssignment(// OpenCode is the only engine whose provider block has to name something, so a launch with no// model picked writes the relay's router id there. That is an OpenCode implementation detail and// must not leak: the app's own "Auto" is `model: null`, and a raw `Auto` coming back would be the- // same state under a different name — the header would print the id instead of "Auto", and- // `assignmentMatches` would compare 'Auto' against null and report every such agent as being on- // the wrong target, forever. See the desktop's `kAutoModelId`, and the commit that stopped the+ // same state under a different name — the header would print the id instead of "Auto", and a check+ // that the agent is where the person put it would compare 'Auto' against null and report every such+ // agent as being on the wrong target, forever. See the desktop's `kAutoModelId`, and the commit that stopped the// model menu offering the router beside its own Auto row.const model = models[0]return { baseUrl, model: model.toLowerCase() === GRID_ROUTER_MODEL.toLowerCase() ? null : model }@@ -281,18 +282,3 @@ export function sameGridAssignment(a: GridAssignment | null, b: GridAssignment |if (a === null || b === null) return a === breturn a.baseUrl === b.baseUrl && (a.model ?? null) === (b.model ?? null)}--/** Is this agent already where `networkId` is served, on `model`? */-export function assignmentMatches(- assignment: GridAssignment | null | undefined,- networkId: string,- model: string | null,-): boolean {- if (!assignment) return false- // Containment rather than a parsed id: the grid id IS a path segment of the relay URL today, and- // asking "does this endpoint name the grid I picked" survives a control plane that rearranges the- // rest of the path. A false negative costs one needless move; a false positive would leave an agent- // somewhere the user did not choose and say it was fine.- if (!assignment.baseUrl.includes(networkId)) return false- return (assignment.model ?? null) === (model ?? null)-}diff --git a/cli/src/lib/registry.ts b/cli/src/lib/registry.tsindex 37263e5ba..556be3120 100644--- a/cli/src/lib/registry.ts+++ b/cli/src/lib/registry.ts@@ -1753,11 +1753,11 @@ class Registry {** What goes is what described the PROCESS and its session — session id, transcript, pid,* gateway, grid assignment, model, title — because the next thing typed into this shell may be a- * different engine, and `unboundRouteOwner` only claims a route for a row with no session. What- * stays is what describes the PANE's launch — `gridLaunch`, `codexHome`, `dsh`, `agent`, the- * permission choice: the tmux session's environment still carries the grid endpoint and the- * Codex profile, the workspace is still that harness's, and a restart or a relaunch after a- * reboot puts the same engine back with the same shape. Dropping `gridLaunch` in particular made+ * different engine, and the reconciler hands a pane's engine to a row by its route only when the row+ * lacks a session or a process (`unboundRouteObservation`). What stays is what describes the PANE's+ * launch — `gridLaunch`, `codexHome`, `dsh`, `agent`, the permission choice: the tmux session's+ * environment still carries the grid endpoint and the Codex profile, the workspace is still that+ * harness's, and a restart or a relaunch after a reboot puts the same engine back with the same shape. Dropping `gridLaunch` in particular made* a released grid agent unrestorable ("credential not persisted"). The row itself, its id, its* pane and its name stay: this is the opposite of dormant, the terminal is live. `terminalHost`* is set from here on, since that is what the pane now is.diff --git a/cli/src/lib/runtimeProfile.ts b/cli/src/lib/runtimeProfile.tsindex 9af5defd3..694fe02d7 100644--- a/cli/src/lib/runtimeProfile.ts+++ b/cli/src/lib/runtimeProfile.ts@@ -640,37 +640,6 @@ function claudeStartupBanner(pane: string): { model: string; effort?: string } |}}-/**- * Read-only evidence for a ready, pre-conversation CLI. Callers must scope this to the live process;- * it deliberately never enters RuntimeProfileManager's conversation cache under an empty session ID.- */-export async function readStartupProfile(session: RegisteredSession, pane: string): Promise<string | null> {- if (session.sessionId || !session.active || session.grid || session.gridLaunch || session.gateway) return null- pane = stripAnsi(pane).trimEnd()- // A banner above an onboarding dialog is not a ready agent. Do not accept a numbered menu cursor.- if (/trust this (?:folder|directory)|trust the files|sign in|log in|select a login|choose.*theme/i.test(pane)) return null- if (session.engine === 'claude') {- const banner = claudeStartupBanner(pane)- if (!banner || !/^\s*❯\s*(?:Try\s+[^\n]*)?$/mu.test(pane)) return null- // Slash commands can change the selection before a first conversational turn binds the session.- const change = [...pane.matchAll(/(?:^|\n)\s*(?:⎿\s*)?Set model to\s+([^\n]+)/gi)].at(-1)- const model = change ? normalizeClaudeDisplay(change[1]) : banner.model- if (!model) return null- const effort = banner.effort ?? await claudeConfiguredEffort(session)- return encodeRuntimeProfile({ sessionId: session.agentId, engine: 'claude',- model: claudeAliasForModel(model) ?? model, effort })- }- if (session.engine === 'codex') {- if (!/\bOpenAI Codex\b/.test(pane) || !/^\s*›(?!\s*\d+\.)[^\n]*$/mu.test(pane)) return null- const matches = [...pane.matchAll(/\b(gpt-[a-z0-9][a-z0-9._-]*)\s+(low|medium|high|xhigh|max|ultra|persistent|default)\s*[·│]/gi)]- const match = matches.at(-1)- if (!match) return null- return encodeRuntimeProfile({ sessionId: session.agentId, engine: 'codex', model: match[1].toLowerCase(),- effort: match[2].toLowerCase() === 'default' ? 'auto' : match[2].toLowerCase() })- }- return null-}-function addOption(output: RuntimeModelOption[],seen: Set<string>,@@ -1227,9 +1196,7 @@ export class RuntimeProfileManager {* answered "There's an issue with the selected model (opencode/big-pickle). It may not exist".** So `''` gets no entry in this conversation cache, and writes land in a throwaway rather than a- * bucket the next agent will read. A ready startup banner can be read separately with- * readStartupProfile, whose caller must scope that observation to the live process. Transcript- * state is re-read once a real conversation binds.+ * bucket the next agent will read. Transcript state is re-read once a real conversation binds.*/private unbound(sessionId: string): boolean {return !sessionIddiff --git a/cli/src/lib/subscriptionModel.spec.ts b/cli/src/lib/subscriptionModel.spec.tsindex 06c14bcb3..bdbd2f364 100644--- a/cli/src/lib/subscriptionModel.spec.ts+++ b/cli/src/lib/subscriptionModel.spec.ts@@ -1,5 +1,6 @@import { describe, expect, it } from 'vitest'-import { subscriptionModelLaunch, subscriptionModelEngines } from './subscriptionModel.js'+import { ENGINES } from './engineBin.js'+import { subscriptionModelLaunch } from './subscriptionModel.js'/*** The point of this module is that coming back from a grid returns a person to the model they were@@ -59,6 +60,8 @@ describe('subscriptionModelLaunch', () => {})it('only claims engines it can actually steer', () => {- expect(subscriptionModelEngines().sort()).toEqual(['claude', 'codex', 'hermes', 'opencode'])+ // A `provider/model` any of them could take: only an engine with a cited mechanism says how.+ expect(ENGINES.filter((engine) => subscriptionModelLaunch(engine, 'acme/some-model') !== null).sort())+ .toEqual(['claude', 'codex', 'hermes', 'opencode'])})})diff --git a/cli/src/lib/subscriptionModel.ts b/cli/src/lib/subscriptionModel.tsindex cbd40a561..40c62ceff 100644--- a/cli/src/lib/subscriptionModel.ts+++ b/cli/src/lib/subscriptionModel.ts@@ -74,11 +74,6 @@ const CONTRACTS: Partial<Record<AgentEngine, (model: string, opencodeMajor: numb},}-/** Engines that can be returned to a specific model. Everything else relaunches as it always did. */-export function subscriptionModelEngines(): AgentEngine[] {- return Object.keys(CONTRACTS) as AgentEngine[]-}-/*** How to relaunch `engine` on its own login with `model` selected, or null when there is nothing* this module can say — an engine with no cited mechanism, or a model string it cannot use.diff --git a/cli/src/lib/terminalAgentDiscovery.engines.spec.ts b/cli/src/lib/terminalAgentDiscovery.engines.spec.tsnew file mode 100644index 000000000..de0e3e2e3--- /dev/null+++ b/cli/src/lib/terminalAgentDiscovery.engines.spec.ts@@ -0,0 +1,328 @@+/**+ * Which engine process owns a pane, for every engine and the ways each is installed and run, through the+ * daemon's own scan (discoverTerminalAgentsFromSnapshot) over panes as the tmux backend reports them.+ * These cases were written against tmuxAgentDiscovery.ts's copy of the same rules, which nothing but its+ * tests ran; they now hold the code that runs.+ */+import { describe, expect, it } from 'vitest'+import type { AgentEngine } from '../engines/types.js'+import { agentCommandOwnershipSnapshot, type AgentCommandOwnershipSnapshot } from './engineBin.js'+import type { ProcessRow } from './tmux.js'+import { discoverTerminalAgentsFromSnapshot, type DiscoveredTerminalAgent } from './terminalAgentDiscovery.js'+import { terminalPlacementKey, terminalRouteKey } from './terminalRuntime.js'+import type { TerminalRootObservation } from './terminalTypes.js'++const START = 'Mon Aug 10 12:00:00 2026'+/** A tmux pane as the backend reports it: its root process and folder. */+const paneRoot = (paneId: string, rootPid: number, cwd = '/work/demo'): TerminalRootObservation => ({+ runtime: { backend: 'tmux', paneId }, rootPid, cwd,+})+const pane = paneRoot('%1', 1)+const row = (pid: number, parentPid: number, executable: string, args = executable): ProcessRow => ({+ pid, parentPid, executable, args, startMarker: START,+})+const ownership = (cursor: string[] = [], grok: string[] = []): AgentCommandOwnershipSnapshot => ({+ cursorFileKeys: new Set(cursor),+ grokFileKeys: new Set(grok),+ conflictingFileKeys: new Set(cursor.filter((key) => grok.includes(key))),+ agentCandidates: [],+ cursorAgentCandidates: [],+ grokCandidates: [],+})++/** The scan of these panes; `hints` are pane-scoped engine hints by pane id, as a vendor hook gives them. */+function discover(+ roots: readonly TerminalRootObservation[],+ rows: readonly ProcessRow[],+ daemonPid: number,+ commands: AgentCommandOwnershipSnapshot = agentCommandOwnershipSnapshot(),+ hints: ReadonlyMap<string, AgentEngine> = new Map(),+): ReturnType<typeof discoverTerminalAgentsFromSnapshot> {+ const byRoute = new Map([...hints].map(([paneId, engine]) => [terminalRouteKey({ backend: 'tmux', paneId }), engine]))+ return discoverTerminalAgentsFromSnapshot(roots, rows, daemonPid, ['tmux'], byRoute, commands)+}++/** The scan could not tell who owns the pane, and said so rather than guessing. */+const ambiguous = (result: ReturnType<typeof discover>, paneId: string): boolean =>+ result.ambiguousPlacements.has(terminalPlacementKey({ backend: 'tmux', paneId }))++/** What makes two scans' agents the same agent: the engine, its pane and its process. */+const identity = (agent: DiscoveredTerminalAgent | undefined): unknown =>+ agent && { engine: agent.engine, primaryRuntimeKey: agent.primaryRuntimeKey, processIdentity: agent.processIdentity }++describe('which engine process owns a pane', () => {+ const fixtures: Array<[AgentEngine, string, string]> = [+ ['claude', 'claude', 'claude'],+ ['codex', 'codex', 'codex'],+ ['cursor', 'cursor-agent', 'cursor-agent'],+ ['opencode', 'opencode', 'opencode'],+ ['pi', 'pi', 'pi'],+ ['hermes', 'python', '/opt/hermes-agent/hermes'],+ ['hermes', 'python3', "python3 -I -I -c import sys, runpy; sys.path.insert(0, '/opt/custom'); runpy.run_module('hermes_cli.main', run_name='__main__')"],+ ['commandcode', '⌘ Project', '⌘ Project'],+ ['devin', 'devin', 'devin'],+ ['muse', 'muse-bin-1.2.3', 'muse-bin-1.2.3'],+ ['amp', 'amp', 'amp'],+ ['kilo', 'kilo', 'kilo'],+ ['grok', 'grok', 'grok'],+ ['agy', 'agy', 'agy'],+ ['copilot', 'copilot', 'copilot'],+ ]++ it.each(fixtures)('recognizes the plain %s CLI process', (engine, executable, args) => {+ const result = discover([pane], [row(1, 0, 'zsh'), row(2, 1, executable, args)], 900)+ expect(result.agents).toHaveLength(1)+ expect(result.agents[0]).toMatchObject({ engine, cwd: '/work/demo', runtimes: [{ backend: 'tmux', paneId: '%1' }] })+ })++ it('classifies each vendor agent alias from the executable file identity', () => {+ const commands = ownership(['cursor-file'], ['grok-file'])+ const cursorRow = { ...row(2, 1, 'agent'), imageFileKey: 'cursor-file' }+ const grokRow = { ...row(2, 1, 'agent'), imageFileKey: 'grok-file' }++ expect(discover([pane], [row(1, 0, 'zsh'), cursorRow], 900, commands)+ .agents[0]?.engine).toBe('cursor')+ expect(discover([pane], [row(1, 0, 'zsh'), grokRow], 900, commands)+ .agents[0]?.engine).toBe('grok')+ })++ it('does not guess an unresolved agent alias and lets a pane-scoped vendor hook resolve it', () => {+ const commands = ownership(['cursor-file'], ['grok-file'])+ const rows = [row(1, 0, 'zsh'), row(2, 1, 'agent')]+ const unresolved = discover([pane], rows, 900, commands)+ expect(unresolved.agents).toEqual([])+ expect(ambiguous(unresolved, '%1')).toBe(true)++ const hinted = discover(+ [pane], rows, 900, commands, new Map([['%1', 'grok']]),+ )+ expect(hinted.agents[0]?.engine).toBe('grok')++ const conflict = ownership(['same-file'], ['same-file'])+ const conflicted = discover(+ [pane], [row(1, 0, 'zsh'), { ...row(2, 1, 'agent'), imageFileKey: 'same-file' }],+ 900, conflict, new Map([['%1', 'grok']]),+ )+ expect(conflicted.agents).toEqual([])+ expect(ambiguous(conflicted, '%1')).toBe(true)+ })++ it('does not let a nested sub-agent steal a pane from an unresolved top-level agent alias', () => {+ const result = discover(+ [pane],+ [row(1, 0, 'zsh'), row(2, 1, 'agent'), row(3, 2, 'codex')],+ 900,+ ownership(),+ )+ expect(result.agents).toEqual([])+ expect(ambiguous(result, '%1')).toBe(true)+ })++ it('keeps a file-identified Grok parent while agent-named sub-agent PIDs churn', () => {+ const commands = ownership(['cursor-file'], ['grok-file'])+ const first = discover(+ [pane],+ [row(1, 0, 'zsh'), { ...row(2, 1, 'agent'), imageFileKey: 'grok-file' }, row(3, 2, 'cursor-agent')],+ 900,+ commands,+ )+ const second = discover(+ [pane],+ [row(1, 0, 'zsh'), { ...row(2, 1, 'agent'), imageFileKey: 'grok-file' }, row(30, 2, 'cursor-agent')],+ 900,+ commands,+ )+ expect(first.agents[0]?.engine).toBe('grok')+ expect(first.agents[0]?.processIdentity.pid).toBe(2)+ expect(identity(first.agents[0])).toEqual(identity(second.agents[0]))+ })++ const wrappers: Array<[AgentEngine, string, string]> = [+ ['claude', 'node', '/opt/lib/node_modules/@anthropic-ai/claude-code/cli.js'],+ ['codex', 'node', '/opt/lib/node_modules/@openai/codex/bin/codex.js'],+ ['cursor', 'node', '/opt/cursor-agent/versions/1.2.3/index.js'],+ ['opencode', 'opencode.exe', '/opt/lib/node_modules/opencode-ai/bin/opencode.exe'],+ ['pi', 'node', '/opt/lib/node_modules/pi-coding-agent/dist/cli.js'],+ ['hermes', 'python3', '/opt/hermes-agent/hermes'],+ ['commandcode', 'node', '/opt/lib/node_modules/command-code/dist/index.mjs'],+ ['devin', 'python3', '/opt/devin/cli/_versions/1.2.3/bin/devin'],+ ['muse', 'muse-bin-0.1.0-R708.1', 'muse-bin-0.1.0-R708.1'],+ ['amp', 'node', '/opt/.amp/bin/amp'],+ ['kilo', 'node', '/opt/lib/node_modules/@kilocode/cli/bin/kilo'],+ ['grok', 'node', '/opt/.grok/bin/grok'],+ ['agy', 'agy', '/home/demo/.local/bin/agy'],+ ['copilot', 'node', '/opt/lib/node_modules/@github/copilot/npm-loader.js'],+ ]++ it.each(wrappers)('recognizes the installed/wrapper form for %s', (engine, executable, args) => {+ const result = discover([pane], [row(1, 0, 'zsh'), row(2, 1, executable, args)], 900)+ expect(result.agents).toHaveLength(1)+ expect(result.agents[0].engine).toBe(engine)+ })++ it('discovers a native Claude version target before it rewrites argv to claude', () => {+ const native = '/home/demo/.local/share/claude/versions/2.1.246'+ const result = discover(+ [pane],+ [row(1, 0, 'zsh'), row(2, 1, '2.1.246', native)],+ 900,+ )+ expect(result.agents).toHaveLength(1)+ expect(result.agents[0]).toMatchObject({ engine: 'claude', runtimes: [{ backend: 'tmux', paneId: '%1' }] })+ })++ const installPrefixes = [+ '/usr/local',+ '/opt/homebrew',+ '/nix/store/abc123-agent-cli',+ '/home/test/.local/share/pnpm/global/5',+ ]++ it.each(wrappers.flatMap(([engine, executable, args]) => installPrefixes.map((prefix) => [+ engine,+ executable,+ args.replace('/opt', prefix),+ ] as const)))('recognizes %s under arbitrary install prefix (%s)', (engine, executable, args) => {+ const result = discover(+ [pane],+ [row(1, 0, 'zsh'), row(2, 1, executable, args)],+ 900,+ )+ expect(result.agents[0]?.engine).toBe(engine)+ })++ it('recognizes an interpreter entrypoint under a quoted install prefix with spaces', () => {+ const result = discover(+ [pane],+ [row(1, 0, 'zsh'), row(2, 1, 'node', 'node "/Applications/Agent Tools/lib/node_modules/@openai/codex/bin/codex.js"')],+ 900,+ )+ expect(result.agents[0]?.engine).toBe('codex')+ })++ it('honors a configured engine path with a custom executable name', () => {+ const previous = process.env.CODEX_PATH+ process.env.CODEX_PATH = '/srv/company-tools/company-coding-agent'+ try {+ const result = discover(+ [pane],+ [row(1, 0, 'zsh'), row(2, 1, 'company-coding-agent', '/srv/company-tools/company-coding-agent')],+ 900,+ )+ expect(result.agents[0]?.engine).toBe('codex')+ } finally {+ if (previous === undefined) delete process.env.CODEX_PATH+ else process.env.CODEX_PATH = previous+ }+ })++ it('never treats engine names in prompt arguments as process entrypoints', () => {+ const result = discover(+ [pane],+ [row(1, 0, 'zsh'), row(2, 1, 'python3', 'python3 /work/runner.py compare claude codex agent opencode pi hermes cmd devin muse amp kilo grok')],+ 900,+ )+ expect(result.agents).toEqual([])+ })++ it('does not infer an agent from an engine-named repository path', () => {+ const result = discover(+ [pane],+ [row(1, 0, 'zsh'), row(2, 1, 'node', 'node /work/codex/tests/runner.js')],+ 900,+ )+ expect(result.agents).toEqual([])+ })++ it('does not treat inline shell source as the process entrypoint', () => {+ const result = discover(+ [pane],+ [row(1, 0, 'zsh'), row(2, 1, 'bash', 'bash -c "printf claude codex kilo"')],+ 900,+ )+ expect(result.agents).toEqual([])+ })++ it.each(['kilo', 'kilocode'])('recognizes the public %s wrapper command', (command) => {+ const result = discover(+ [pane],+ [row(1, 0, 'zsh'), row(2, 1, 'node', `node /any/prefix/bin/${command}`)],+ 900,+ )+ expect(result.agents[0]?.engine).toBe('kilo')+ })++ it('recognizes Command Code after it rewrites its process title', () => {+ const result = discover(+ [pane],+ [row(1, 0, 'zsh'), row(2, 1, '⌘ Implement lifecycle plan', '⌘ Implement lifecycle plan')],+ 900,+ )+ expect(result.agents[0]?.engine).toBe('commandcode')+ })++ it('creates independent agents for two panes running the same engine', () => {+ const result = discover(+ [pane, paneRoot('%2', 10, '/work/other')],+ [row(1, 0, 'zsh'), row(2, 1, 'claude'), row(10, 0, 'zsh'), row(11, 10, 'claude')],+ 900,+ )+ expect(result.agents.map((agent) => [agent.runtimes[0].paneId, agent.engine])).toEqual([+ ['%1', 'claude'], ['%2', 'claude'],+ ])+ })++ it('keeps the shallow supported parent and ignores a nested supported sub-agent', () => {+ const result = discover(+ [pane],+ [row(1, 0, 'zsh'), row(2, 1, 'claude'), row(3, 2, 'codex')],+ 900,+ )+ expect(result.agents.map((agent) => agent.engine)).toEqual(['claude'])+ })++ it('keeps the same parent identity while nested sub-agent PIDs churn', () => {+ const first = discover(+ [pane],+ [+ row(1, 0, 'zsh'),+ row(2, 1, 'claude'),+ row(3, 2, 'node', 'node /work/helper.js'),+ row(4, 3, 'codex'),+ ],+ 900,+ )+ const second = discover(+ [pane],+ [+ row(1, 0, 'zsh'),+ row(2, 1, 'claude'),+ row(30, 2, 'node', 'node /work/helper.js'),+ row(40, 30, 'agent'),+ ],+ 900,+ )+ expect(first.agents[0]?.processIdentity.pid).toBe(2)+ expect(second.agents[0]?.processIdentity.pid).toBe(2)+ expect(identity(first.agents[0])).toEqual(identity(second.agents[0]))+ })++ it('excludes recap/voice/one-shot descendants of the harness daemon', () => {+ const result = discover(+ [pane],+ [row(1, 0, 'zsh'), row(20, 1, 'node', 'node cli.js __run'), row(21, 20, 'codex', 'codex exec recap')],+ 20,+ )+ expect(result.agents).toEqual([])+ })++ it('does not guess when two top-level supported processes tie', () => {+ const result = discover(+ [pane],+ [row(1, 0, 'zsh'), row(2, 1, 'claude'), row(3, 1, 'codex')],+ 900,+ )+ expect(result.agents).toEqual([])+ expect(ambiguous(result, '%1')).toBe(true)+ })+})diff --git a/cli/src/lib/terminalAgentDiscovery.gateway.spec.ts b/cli/src/lib/terminalAgentDiscovery.gateway.spec.tsindex bc724db6a..6b7ca9cc5 100644--- a/cli/src/lib/terminalAgentDiscovery.gateway.spec.ts+++ b/cli/src/lib/terminalAgentDiscovery.gateway.spec.ts@@ -6,9 +6,9 @@ import type { TerminalRootObservation, TerminalRuntimeRef } from './terminalType/*** The gateway flag has to ride the LIVE discovery path, not just the tmux-only one it was born on.*- * This is the regression that a backend refactor produces for free: `probeTmuxAgents` keeps its probe- * and its tests keep passing, while the reconciler has quietly moved to `probeTerminalAgents` and every- * agent arrives with `gateway: undefined`. Nothing goes red — an `ori claude` pane just starts offering+ * This is the regression a backend refactor produced for free: `probeTmuxAgents` (since deleted) kept+ * its probe and its tests kept passing, while the reconciler had quietly moved to `probeTerminalAgents`+ * and every agent arrived with `gateway: undefined`. Nothing goes red — an `ori claude` pane just starts offering* the native Claude catalog again, accepts `/model` it cannot honour, and loses its recap. So the wiring* is pinned here, on both backends, rather than the classifier (which `gatewayRuntime.spec.ts` covers).*/diff --git a/cli/src/lib/terminalAgentReconciler.spec.ts b/cli/src/lib/terminalAgentReconciler.spec.tsindex 5688f761c..f77f209eb 100644--- a/cli/src/lib/terminalAgentReconciler.spec.ts+++ b/cli/src/lib/terminalAgentReconciler.spec.ts@@ -406,51 +406,7 @@ describe('restart route hold', () => {})})-describe('verified process adoption', () => {- it('opens a sessionless agent through the normal discovery callback without another inventory scan', async () => {- let current: RegisteredSession[] = []- const candidate = observed([tmux])- const onDiscovered = vi.fn(async () => { current = [session([tmux])] })- const probeSnapshot = vi.fn(async () => {- throw new Error('verified adoption must not run the general probe')- })- let transactionCalls = 0- const transaction = async <T>(apply: () => T | Promise<T>): Promise<T> => {- transactionCalls += 1- return await apply()- }- const reconciler = new TerminalAgentReconciler({- current: () => current, backends: [], backendOrder: ['tmux'],- onDiscovered, onObserved: vi.fn(), onDormant: vi.fn(), onRemoved: vi.fn(),- probe: probeSnapshot, transaction,- })-- const adopted = await reconciler.adoptVerified(candidate)-- expect(adopted).toBe(current[0])- expect(adopted?.sessionId).toBe('')- expect(adopted?.processIdentity).toEqual(identity)- expect(onDiscovered).toHaveBeenCalledWith(candidate)- expect(transactionCalls).toBe(1)- expect(probeSnapshot).not.toHaveBeenCalled()- })-- it('refreshes an already adopted process instead of opening a duplicate agent', async () => {- const existing = session([tmux])- const onDiscovered = vi.fn()- const onObserved = vi.fn()- const reconciler = new TerminalAgentReconciler({- current: () => [existing], backends: [], backendOrder: ['tmux'],- onDiscovered, onObserved, onDormant: vi.fn(), onRemoved: vi.fn(),- })-- const adopted = await reconciler.adoptVerified(observed([tmux]))-- expect(adopted).toBe(existing)- expect(onObserved).toHaveBeenCalledWith(observed([tmux]), existing)- expect(onDiscovered).not.toHaveBeenCalled()- })-+describe('a row matched by its route, before or without its process', () => {it('keeps a sessionless agent when the engine replaces its process inside the same pane', async () => {const existing = session([tmux])const replacement = {@@ -547,16 +503,6 @@ describe('verified process adoption', () => {expect(onObserved).not.toHaveBeenCalled()})- it('reports no adopted agent when the registry callback rejects the process', async () => {- const onDiscovered = vi.fn()- const reconciler = new TerminalAgentReconciler({- current: () => [], backends: [], backendOrder: ['tmux'],- onDiscovered, onObserved: vi.fn(), onDormant: vi.fn(), onRemoved: vi.fn(),- })-- expect(await reconciler.adoptVerified(observed([tmux]))).toBeUndefined()- expect(onDiscovered).toHaveBeenCalledOnce()- })})describe('start()', () => {diff --git a/cli/src/lib/terminalAgentReconciler.ts b/cli/src/lib/terminalAgentReconciler.tsindex 7e490d586..7e40f9744 100644--- a/cli/src/lib/terminalAgentReconciler.ts+++ b/cli/src/lib/terminalAgentReconciler.ts@@ -87,18 +87,6 @@ function routeEngineMatches(current: Pick<RegisteredSession, 'engine'>, observedreturn current.engine === observed.engine || isTerminalEngine(current.engine)}-function unboundRouteOwner(- current: readonly RegisteredSession[],- observed: DiscoveredTerminalAgent,-): RegisteredSession | undefined {- const matches = current.filter((candidate) => (- !candidate.sessionId- && routeEngineMatches(candidate, observed)- && sharesPlacement(candidate, observed)- ))- return matches.length === 1 ? matches[0] : undefined-}-/*** The observation for a row that cannot be matched by process identity, because it does not have one* yet. Its terminal route is the only identity it has.@@ -180,30 +168,6 @@ export class TerminalAgentReconciler {return this.trigger()}- /**- * Adopt an engine process that a backend-specific, pane-scoped probe already verified.- *- * New-agent creation has stronger evidence than the periodic inventory scan: it owns the exact- * runtime it just created and resolves the requested engine beneath that runtime. Passing that- * observation through the same callbacks used by reconciliation keeps process-agent creation and- * later session binding on one path, while avoiding a second best-effort inventory snapshot.- */- async adoptVerified(observed: DiscoveredTerminalAgent): Promise<RegisteredSession | undefined> {- const apply = async (): Promise<RegisteredSession | undefined> => {- const key = processIdentityKey(observed.engine, observed.processIdentity)- const before = this.deps.current()- const current = before.find((candidate) => currentProcessKey(candidate) === key)- ?? unboundRouteOwner(before, observed)- if (current) await this.deps.onTerminalAvailability?.(current, true)- if (current) await this.deps.onObserved(observed, current)- else await this.deps.onDiscovered(observed)- const after = this.deps.current()- return after.find((candidate) => currentProcessKey(candidate) === key)- ?? unboundRouteOwner(after, observed)- }- return this.deps.transaction ? this.deps.transaction(apply) : apply()- }-/** Hide an explicitly deleted process until an authoritative scan proves that process exited. */suppress(session: Pick<RegisteredSession, 'engine' | 'processIdentity'>): void {if (session.processIdentity) this.suppressed.add(processIdentityKey(session.engine, session.processIdentity))diff --git a/cli/src/lib/tmuxAgentDiscovery.real.spec.ts b/cli/src/lib/tmuxAgentDiscovery.real.spec.tsindex 84aecb1e3..e2cbb89dd 100644--- a/cli/src/lib/tmuxAgentDiscovery.real.spec.ts+++ b/cli/src/lib/tmuxAgentDiscovery.real.spec.ts@@ -12,8 +12,7 @@ import {installedEngineBin,} from './engineBin.js'import { TmuxBackend } from './tmuxBackend.js'-import { probeTmuxAgents } from './tmuxAgentDiscovery.js'-import { probeTerminalAgents } from './terminalAgentDiscovery.js'+import { probeTerminalAgents, type DiscoveredTerminalAgent } from './terminalAgentDiscovery.js'import { HARNESS_SESSION_PREFIX } from './harnessSessionLabel.js'import { isolatedTmux, type IsolatedTmux } from '../testing/isolatedTmux.js'@@ -49,6 +48,13 @@ async function tmux(args: string[]): Promise<string> {return server.run(...args)}+/** The daemon's own scan (probeTerminalAgents over the tmux backend), narrowed to one pane. */+async function agentsInPane(pane: string): Promise<DiscoveredTerminalAgent[]> {+ const result = await probeTerminalAgents([new TmuxBackend()], ['tmux'])+ if (!result.processTableAvailable) throw new Error('the process table could not be read')+ return result.agents.filter((agent) => agent.runtimes.some((runtime) => runtime.paneId === pane))+}+async function eventually<T>(read: () => Promise<T | null>, timeoutMs = 20_000): Promise<T | null> {const deadline = Date.now() + timeoutMswhile (Date.now() < deadline) {@@ -108,22 +114,16 @@ realDescribe.sequential('real installed CLI process discovery', () => {await tmux(['send-keys', '-t', pane, 'C-m'])const discovered = await eventually(async () => {- const result = await probeTmuxAgents()- if (!result.ok) throw new Error(result.error)- const inPane = result.agents.filter((candidate) => candidate.tmuxPane === pane)+ const inPane = await agentsInPane(pane)return inPane.length === 1 && inPane[0].engine === engine ? inPane[0] : null})const capture = await tmux(['capture-pane', '-p', '-t', pane]).catch(() => '')expect(discovered, `${bin} was not discovered in ${pane}\n${capture}`).not.toBeNull()- // The daemon uses the backend-neutral scan. Exercise it against the same real process,- // not only the older tmux-specific reader, before checking that stop preserves the pane.- const current = await probeTerminalAgents([new TmuxBackend()], ['tmux'])- expect(current.processTableAvailable).toBe(true)- const matches = current.agents.filter(agent => agent.runtimes.some(runtime => runtime.paneId === pane))+ // A second scan finds the same process. Node engines may change their process title between+ // snapshots; the PID and birth stamp prove this is still the same launched process.+ const matches = await agentsInPane(pane)expect(matches).toHaveLength(1)- // Node engines may change their process title between these snapshots.- // The PID and birth stamp prove this is still the same launched process.expect(matches[0]).toMatchObject({ engine, processIdentity: {pid: discovered!.processIdentity.pid,startMarker: discovered!.processIdentity.startMarker,@@ -141,11 +141,7 @@ realDescribe.sequential('real installed CLI process discovery', () => {}}- const absent = await eventually(async () => {- const result = await probeTmuxAgents()- if (!result.ok) throw new Error(result.error)- return result.agents.some((candidate) => candidate.tmuxPane === pane) ? null : true- }, 5_000)+ const absent = await eventually(async () => (await agentsInPane(pane)).length > 0 ? null : true, 5_000)expect(absent, `${bin} remained discoverable after its exact saved PID was terminated`).toBe(true)await expect(tmux(['display-message', '-p', '-t', pane, '#{pane_id}'])).resolves.toBe(pane)} finally {@@ -193,9 +189,7 @@ realDescribe.sequential('real installed CLI process discovery', () => {await tmux(['send-keys', '-t', pane, '-l', '--', path])await tmux(['send-keys', '-t', pane, 'C-m'])const discovered = await eventually(async () => {- const result = await probeTmuxAgents()- if (!result.ok) throw new Error(result.error)- const inPane = result.agents.filter((candidate) => candidate.tmuxPane === pane)+ const inPane = await agentsInPane(pane)return inPane.length === 1 && inPane[0].engine === engine ? inPane[0] : null})const capture = await tmux(['capture-pane', '-p', '-t', pane]).catch(() => '')diff --git a/cli/src/lib/tmuxAgentDiscovery.spec.ts b/cli/src/lib/tmuxAgentDiscovery.spec.tsindex 2b2e43b6d..0467bb62a 100644--- a/cli/src/lib/tmuxAgentDiscovery.spec.ts+++ b/cli/src/lib/tmuxAgentDiscovery.spec.ts@@ -1,30 +1,5 @@-import { describe, expect, it, vi } from 'vitest'-import type { AgentEngine } from '../engines/types.js'-import type { AgentCommandOwnershipSnapshot } from './engineBin.js'-import type { ProcessRow } from './tmux.js'-import type { RegisteredSession } from './registry.js'-import {- TmuxAgentReconciler,- discoverTmuxAgentsFromSnapshot,- parsePanes,- runtimeKey,- type DiscoveredTmuxAgent,- type TmuxAgentProbe,-} from './tmuxAgentDiscovery.js'--const START = 'Mon Aug 10 12:00:00 2026'-const pane = { tmuxPane: '%1', rootPid: 1, tmuxSessionName: 'harness-claude-1', cwd: '/work/demo' }-const row = (pid: number, parentPid: number, executable: string, args = executable): ProcessRow => ({- pid, parentPid, executable, args, startMarker: START,-})-const ownership = (cursor: string[] = [], grok: string[] = []): AgentCommandOwnershipSnapshot => ({- cursorFileKeys: new Set(cursor),- grokFileKeys: new Set(grok),- conflictingFileKeys: new Set(cursor.filter((key) => grok.includes(key))),- agentCandidates: [],- cursorAgentCandidates: [],- grokCandidates: [],-})+import { expect, it } from 'vitest'+import { parsePanes } from './tmuxAgentDiscovery.js'it('parses printable tmux separators without truncating a pipe in cwd, and the owner tag after it', () => {expect(parsePanes('%1|42|harness-claude-1|/work/a|b|\n%2|84|mysession|/tmp|0123abcd\n')).toEqual([@@ -36,484 +11,3 @@ it('parses printable tmux separators without truncating a pipe in cwd, and the o{ tmuxPane: '%3', rootPid: 7, tmuxSessionName: 'harness-codex-1', cwd: '/work', owner: '' },])})--describe('tmux process agent snapshot discovery', () => {- const fixtures: Array<[AgentEngine, string, string]> = [- ['claude', 'claude', 'claude'],- ['codex', 'codex', 'codex'],- ['cursor', 'cursor-agent', 'cursor-agent'],- ['opencode', 'opencode', 'opencode'],- ['pi', 'pi', 'pi'],- ['hermes', 'python', '/opt/hermes-agent/hermes'],- ['hermes', 'python3', "python3 -I -I -c import sys, runpy; sys.path.insert(0, '/opt/custom'); runpy.run_module('hermes_cli.main', run_name='__main__')"],- ['commandcode', '⌘ Project', '⌘ Project'],- ['devin', 'devin', 'devin'],- ['muse', 'muse-bin-1.2.3', 'muse-bin-1.2.3'],- ['amp', 'amp', 'amp'],- ['kilo', 'kilo', 'kilo'],- ['grok', 'grok', 'grok'],- ['agy', 'agy', 'agy'],- ['copilot', 'copilot', 'copilot'],- ]-- it.each(fixtures)('recognizes the plain %s CLI process', (engine, executable, args) => {- const result = discoverTmuxAgentsFromSnapshot([pane], [row(1, 0, 'zsh'), row(2, 1, executable, args)], 900)- expect(result.agents).toHaveLength(1)- expect(result.agents[0]).toMatchObject({ engine, tmuxPane: '%1', cwd: '/work/demo' })- })-- it('classifies each vendor agent alias from the executable file identity', () => {- const commands = ownership(['cursor-file'], ['grok-file'])- const cursorRow = { ...row(2, 1, 'agent'), imageFileKey: 'cursor-file' }- const grokRow = { ...row(2, 1, 'agent'), imageFileKey: 'grok-file' }-- expect(discoverTmuxAgentsFromSnapshot([pane], [row(1, 0, 'zsh'), cursorRow], 900, commands)- .agents[0]?.engine).toBe('cursor')- expect(discoverTmuxAgentsFromSnapshot([pane], [row(1, 0, 'zsh'), grokRow], 900, commands)- .agents[0]?.engine).toBe('grok')- })-- it('does not guess an unresolved agent alias and lets a pane-scoped vendor hook resolve it', () => {- const commands = ownership(['cursor-file'], ['grok-file'])- const rows = [row(1, 0, 'zsh'), row(2, 1, 'agent')]- const unresolved = discoverTmuxAgentsFromSnapshot([pane], rows, 900, commands)- expect(unresolved.agents).toEqual([])- expect(unresolved.ambiguousPanes.has('%1')).toBe(true)-- const hinted = discoverTmuxAgentsFromSnapshot(- [pane], rows, 900, commands, new Map([['%1', 'grok']]),- )- expect(hinted.agents[0]?.engine).toBe('grok')-- const conflict = ownership(['same-file'], ['same-file'])- const conflicted = discoverTmuxAgentsFromSnapshot(- [pane], [row(1, 0, 'zsh'), { ...row(2, 1, 'agent'), imageFileKey: 'same-file' }],- 900, conflict, new Map([['%1', 'grok']]),- )- expect(conflicted.agents).toEqual([])- expect(conflicted.ambiguousPanes.has('%1')).toBe(true)- })-- it('does not let a nested sub-agent steal a pane from an unresolved top-level agent alias', () => {- const result = discoverTmuxAgentsFromSnapshot(- [pane],- [row(1, 0, 'zsh'), row(2, 1, 'agent'), row(3, 2, 'codex')],- 900,- ownership(),- )- expect(result.agents).toEqual([])- expect(result.ambiguousPanes.has('%1')).toBe(true)- })-- it('keeps a file-identified Grok parent while agent-named sub-agent PIDs churn', () => {- const commands = ownership(['cursor-file'], ['grok-file'])- const first = discoverTmuxAgentsFromSnapshot(- [pane],- [row(1, 0, 'zsh'), { ...row(2, 1, 'agent'), imageFileKey: 'grok-file' }, row(3, 2, 'cursor-agent')],- 900,- commands,- )- const second = discoverTmuxAgentsFromSnapshot(- [pane],- [row(1, 0, 'zsh'), { ...row(2, 1, 'agent'), imageFileKey: 'grok-file' }, row(30, 2, 'cursor-agent')],- 900,- commands,- )- expect(first.agents[0]?.engine).toBe('grok')- expect(first.agents[0]?.processIdentity.pid).toBe(2)- expect(runtimeKey(first.agents[0])).toBe(runtimeKey(second.agents[0]))- })-- const wrappers: Array<[AgentEngine, string, string]> = [- ['claude', 'node', '/opt/lib/node_modules/@anthropic-ai/claude-code/cli.js'],- ['codex', 'node', '/opt/lib/node_modules/@openai/codex/bin/codex.js'],- ['cursor', 'node', '/opt/cursor-agent/versions/1.2.3/index.js'],- ['opencode', 'opencode.exe', '/opt/lib/node_modules/opencode-ai/bin/opencode.exe'],- ['pi', 'node', '/opt/lib/node_modules/pi-coding-agent/dist/cli.js'],- ['hermes', 'python3', '/opt/hermes-agent/hermes'],- ['commandcode', 'node', '/opt/lib/node_modules/command-code/dist/index.mjs'],- ['devin', 'python3', '/opt/devin/cli/_versions/1.2.3/bin/devin'],- ['muse', 'muse-bin-0.1.0-R708.1', 'muse-bin-0.1.0-R708.1'],- ['amp', 'node', '/opt/.amp/bin/amp'],- ['kilo', 'node', '/opt/lib/node_modules/@kilocode/cli/bin/kilo'],- ['grok', 'node', '/opt/.grok/bin/grok'],- ['agy', 'agy', '/home/demo/.local/bin/agy'],- ['copilot', 'node', '/opt/lib/node_modules/@github/copilot/npm-loader.js'],- ]-- it.each(wrappers)('recognizes the installed/wrapper form for %s', (engine, executable, args) => {- const result = discoverTmuxAgentsFromSnapshot([pane], [row(1, 0, 'zsh'), row(2, 1, executable, args)], 900)- expect(result.agents).toHaveLength(1)- expect(result.agents[0].engine).toBe(engine)- })-- it('discovers a native Claude version target before it rewrites argv to claude', () => {- const native = '/home/demo/.local/share/claude/versions/2.1.246'- const result = discoverTmuxAgentsFromSnapshot(- [pane],- [row(1, 0, 'zsh'), row(2, 1, '2.1.246', native)],- 900,- )- expect(result.agents).toHaveLength(1)- expect(result.agents[0]).toMatchObject({ engine: 'claude', tmuxPane: '%1' })- })-- const installPrefixes = [- '/usr/local',- '/opt/homebrew',- '/nix/store/abc123-agent-cli',- '/home/test/.local/share/pnpm/global/5',- ]-- it.each(wrappers.flatMap(([engine, executable, args]) => installPrefixes.map((prefix) => [- engine,- executable,- args.replace('/opt', prefix),- ] as const)))('recognizes %s under arbitrary install prefix (%s)', (engine, executable, args) => {- const result = discoverTmuxAgentsFromSnapshot(- [pane],- [row(1, 0, 'zsh'), row(2, 1, executable, args)],- 900,- )- expect(result.agents[0]?.engine).toBe(engine)- })-- it('recognizes an interpreter entrypoint under a quoted install prefix with spaces', () => {- const result = discoverTmuxAgentsFromSnapshot(- [pane],- [row(1, 0, 'zsh'), row(2, 1, 'node', 'node "/Applications/Agent Tools/lib/node_modules/@openai/codex/bin/codex.js"')],- 900,- )- expect(result.agents[0]?.engine).toBe('codex')- })-- it('honors a configured engine path with a custom executable name', () => {- const previous = process.env.CODEX_PATH- process.env.CODEX_PATH = '/srv/company-tools/company-coding-agent'- try {- const result = discoverTmuxAgentsFromSnapshot(- [pane],- [row(1, 0, 'zsh'), row(2, 1, 'company-coding-agent', '/srv/company-tools/company-coding-agent')],- 900,- )- expect(result.agents[0]?.engine).toBe('codex')- } finally {- if (previous === undefined) delete process.env.CODEX_PATH- else process.env.CODEX_PATH = previous- }- })-- it('never treats engine names in prompt arguments as process entrypoints', () => {- const result = discoverTmuxAgentsFromSnapshot(- [pane],- [row(1, 0, 'zsh'), row(2, 1, 'python3', 'python3 /work/runner.py compare claude codex agent opencode pi hermes cmd devin muse amp kilo grok')],- 900,- )- expect(result.agents).toEqual([])- })-- it('does not infer an agent from an engine-named repository path', () => {- const result = discoverTmuxAgentsFromSnapshot(- [pane],- [row(1, 0, 'zsh'), row(2, 1, 'node', 'node /work/codex/tests/runner.js')],- 900,- )- expect(result.agents).toEqual([])- })-- it('does not treat inline shell source as the process entrypoint', () => {- const result = discoverTmuxAgentsFromSnapshot(- [pane],- [row(1, 0, 'zsh'), row(2, 1, 'bash', 'bash -c "printf claude codex kilo"')],- 900,- )- expect(result.agents).toEqual([])- })-- it.each(['kilo', 'kilocode'])('recognizes the public %s wrapper command', (command) => {- const result = discoverTmuxAgentsFromSnapshot(- [pane],- [row(1, 0, 'zsh'), row(2, 1, 'node', `node /any/prefix/bin/${command}`)],- 900,- )- expect(result.agents[0]?.engine).toBe('kilo')- })-- it('recognizes Command Code after it rewrites its process title', () => {- const result = discoverTmuxAgentsFromSnapshot(- [pane],- [row(1, 0, 'zsh'), row(2, 1, '⌘ Implement lifecycle plan', '⌘ Implement lifecycle plan')],- 900,- )- expect(result.agents[0]?.engine).toBe('commandcode')- })-- it('creates independent agents for two panes running the same engine', () => {- const result = discoverTmuxAgentsFromSnapshot(- [pane, { tmuxPane: '%2', rootPid: 10, tmuxSessionName: 'harness-claude-2', cwd: '/work/other' }],- [row(1, 0, 'zsh'), row(2, 1, 'claude'), row(10, 0, 'zsh'), row(11, 10, 'claude')],- 900,- )- expect(result.agents.map((agent) => [agent.tmuxPane, agent.engine])).toEqual([- ['%1', 'claude'], ['%2', 'claude'],- ])- })-- it('keeps the shallow supported parent and ignores a nested supported sub-agent', () => {- const result = discoverTmuxAgentsFromSnapshot(- [pane],- [row(1, 0, 'zsh'), row(2, 1, 'claude'), row(3, 2, 'codex')],- 900,- )- expect(result.agents.map((agent) => agent.engine)).toEqual(['claude'])- })-- it('keeps the same parent identity while nested sub-agent PIDs churn', () => {- const first = discoverTmuxAgentsFromSnapshot(- [pane],- [- row(1, 0, 'zsh'),- row(2, 1, 'claude'),- row(3, 2, 'node', 'node /work/helper.js'),- row(4, 3, 'codex'),- ],- 900,- )- const second = discoverTmuxAgentsFromSnapshot(- [pane],- [- row(1, 0, 'zsh'),- row(2, 1, 'claude'),- row(30, 2, 'node', 'node /work/helper.js'),- row(40, 30, 'agent'),- ],- 900,- )- expect(first.agents[0]?.processIdentity.pid).toBe(2)- expect(second.agents[0]?.processIdentity.pid).toBe(2)- expect(runtimeKey(first.agents[0])).toBe(runtimeKey(second.agents[0]))- })-- it('excludes recap/voice/one-shot descendants of the harness daemon', () => {- const result = discoverTmuxAgentsFromSnapshot(- [pane],- [row(1, 0, 'zsh'), row(20, 1, 'node', 'node cli.js __run'), row(21, 20, 'codex', 'codex exec recap')],- 20,- )- expect(result.agents).toEqual([])- })-- it('does not guess when two top-level supported processes tie', () => {- const result = discoverTmuxAgentsFromSnapshot(- [pane],- [row(1, 0, 'zsh'), row(2, 1, 'claude'), row(3, 1, 'codex')],- 900,- )- expect(result.agents).toEqual([])- expect(result.ambiguousPanes.has('%1')).toBe(true)- })-})--function observed(pid: number, engine: AgentEngine = 'claude'): DiscoveredTmuxAgent {- return {- engine,- tmuxPane: '%1',- cwd: '/work/demo',- processIdentity: { pid, executable: engine, startMarker: `${START} ${pid}` },- args: engine,- resumeSessionId: null,- }-}--function registered(agent: DiscoveredTmuxAgent, agentId = 'agent-1'): RegisteredSession {- return {- schemaVersion: 2,- active: true,- agentId,- sessionId: '',- boundAt: null,- engine: agent.engine,- transcriptPath: null,- projectDir: 'demo',- cwd: agent.cwd,- tmuxPane: agent.tmuxPane,- runtimes: [{ backend: 'tmux', paneId: agent.tmuxPane }],- primaryRuntimeKey: `tmux\u0000${agent.tmuxPane}`,- source: null,- title: null,- model: null,- cliVersion: null,- processIdentity: agent.processIdentity,- registeredAt: 1,- touchedAt: 1,- lastHookAt: 1,- lastTranscriptAt: 1,- }-}--const success = (agents: DiscoveredTmuxAgent[], panes = new Set(['%1'])): TmuxAgentProbe => ({- ok: true,- agents,- panes,- ambiguousPanes: new Set(),-})--describe('tmux process agent lifecycle reconciliation', () => {- it('creates on the first positive scan and removes only after two confirmed misses', async () => {- let current: RegisteredSession[] = []- const live = observed(10)- const probes = [success([live]), success([]), success([])]- const removed: string[] = []- const reconciler = new TmuxAgentReconciler({- current: () => current,- probe: async () => probes.shift()!,- onDiscovered: (agent) => { current = [registered(agent)] },- onObserved: () => {},- onRemoved: (agent) => { removed.push(agent.agentId); current = [] },- })- await reconciler.trigger()- expect(current).toHaveLength(1)- await reconciler.trigger()- expect(removed).toEqual([])- await reconciler.trigger()- expect(removed).toEqual(['agent-1'])- })-- it('does not count a failed probe as a miss', async () => {- const live = observed(10)- let current = [registered(live)]- const probes: TmuxAgentProbe[] = [- { ok: false, error: 'ps timed out' },- success([]),- success([]),- ]- const removed = vi.fn(() => { current = [] })- const reconciler = new TmuxAgentReconciler({- current: () => current,- probe: async () => probes.shift()!,- onDiscovered: () => {},- onObserved: () => {},- onRemoved: removed,- })- await reconciler.trigger()- await reconciler.trigger()- expect(removed).not.toHaveBeenCalled()- await reconciler.trigger()- expect(removed).toHaveBeenCalledTimes(1)- })-- it('holds the current agent through a detached same-depth sub-agent ambiguity', async () => {- const live = observed(10)- const current = [registered(live)]- const ambiguous: TmuxAgentProbe = {- ok: true,- agents: [],- panes: new Set(['%1']),- ambiguousPanes: new Set(['%1']),- }- const probes = [ambiguous, ambiguous, success([live])]- const discovered = vi.fn()- const removed = vi.fn()- const observedAgain = vi.fn()- const reconciler = new TmuxAgentReconciler({- current: () => current,- probe: async () => probes.shift()!,- onDiscovered: discovered,- onObserved: observedAgain,- onRemoved: removed,- })-- await reconciler.trigger()- await reconciler.trigger()- expect(discovered).not.toHaveBeenCalled()- expect(removed).not.toHaveBeenCalled()- await reconciler.trigger()- expect(observedAgain).toHaveBeenCalledWith(live, current[0])- expect(removed).not.toHaveBeenCalled()- })-- it('serializes scans and coalesces every trigger received during one slow pass', async () => {- let releaseFirst!: () => void- const firstGate = new Promise<void>((resolve) => { releaseFirst = resolve })- let calls = 0- let active = 0- let maxActive = 0- const reconciler = new TmuxAgentReconciler({- current: () => [],- probe: async () => {- calls++- active++- maxActive = Math.max(maxActive, active)- if (calls === 1) await firstGate- active--- return success([])- },- onDiscovered: () => {},- onObserved: () => {},- onRemoved: () => {},- })-- const first = reconciler.trigger()- const second = reconciler.trigger()- const third = reconciler.trigger()- expect(calls).toBe(1)- releaseFirst()- await Promise.all([first, second, third])- expect(calls).toBe(2)- expect(maxActive).toBe(1)- })-- it('replaces a changed process in the same pane immediately', async () => {- const old = observed(10)- const replacement = observed(11, 'codex')- let current = [registered(old)]- const order: string[] = []- const reconciler = new TmuxAgentReconciler({- current: () => current,- probe: async () => success([replacement]),- onDiscovered: (agent) => { order.push('add'); current = [registered(agent, 'agent-2')] },- onObserved: () => {},- onRemoved: () => { order.push('remove'); current = [] },- })- await reconciler.trigger()- expect(order).toEqual(['remove', 'add'])- expect(current[0]).toMatchObject({ agentId: 'agent-2', engine: 'codex' })- })-- it('treats PID reuse with a new start marker as immediate replacement', async () => {- const old = observed(10)- const replacement = { ...observed(10), processIdentity: { ...observed(10).processIdentity, startMarker: `${START} reused` } }- let current = [registered(old)]- const order: string[] = []- const reconciler = new TmuxAgentReconciler({- current: () => current,- probe: async () => success([replacement]),- onDiscovered: (agent) => { order.push('add'); current = [registered(agent, 'agent-2')] },- onObserved: () => {},- onRemoved: () => { order.push('remove'); current = [] },- })- await reconciler.trigger()- expect(order).toEqual(['remove', 'add'])- expect(current[0].agentId).toBe('agent-2')- })-- it('suppresses a deleted runtime until that exact identity disappears', async () => {- const live = observed(10)- let current: RegisteredSession[] = []- const probes = [success([live]), success([]), success([observed(11)])]- const added: string[] = []- const reconciler = new TmuxAgentReconciler({- current: () => current,- probe: async () => probes.shift()!,- onDiscovered: (agent) => { added.push(runtimeKey(agent)); current = [registered(agent)] },- onObserved: () => {},- onRemoved: () => { current = [] },- })- reconciler.suppress(live)- await reconciler.trigger()- expect(added).toEqual([])- await reconciler.trigger()- await reconciler.trigger()- expect(added).toEqual([runtimeKey(observed(11))])- })-})diff --git a/cli/src/lib/tmuxAgentDiscovery.ts b/cli/src/lib/tmuxAgentDiscovery.tsindex c7a79c15b..5c46d5c5d 100644--- a/cli/src/lib/tmuxAgentDiscovery.ts+++ b/cli/src/lib/tmuxAgentDiscovery.ts@@ -1,44 +1,17 @@/**- * Discover the top-level supported coding-agent process in every tmux pane.- *- * The process is the agent. A launcher, hook, transcript, or session id may describe it, but none of- * those owns its lifetime. One successful reconciliation reads tmux once and ps once, then applies the- * same snapshot to every pane so a slow machine cannot turn N agents into N independent timeout risks.+ * The tmux panes this daemon owns, in one bounded read, and the renaming of sessions an older build named.+ * Which engine process owns each pane is decided over this listing, by lib/terminalAgentDiscovery.ts+ * through the tmux backend (lib/tmuxBackend.ts).*/import { execFile } from 'node:child_process'import { patientExec } from './patientExec.js'-import {- agentAliasOwner,- agentCommandOwnershipSnapshot,- PROCESS_ENGINES,- type AgentCommandOwnershipSnapshot,-} from './engineBin.js'-import type { AgentEngine } from '../engines/types.js'-import { probeGatewayRuntime } from './gatewayRuntime.js'-import { probeGridAssignment, type GridAssignment } from './gridAssignment.js'-import { probeCodexHome } from './codexHomeProbe.js'import { env } from '../config/env.js'import {buildHarnessSessionLabel, harnessPaneOwner, isLegacyHarnessSession, ownedHere, paneOwnerFormat, paneOwnerOf,} from './harnessSessionLabel.js'import { tmuxFeatures } from './tmuxVersion.js'-import { psEnv } from './childLocale.js'-import type { ProcessIdentity, RegisteredSession } from './registry.js'-import {- ambiguousAgentProcess,- engineProcessMatchScore,- enrichProcessRows,- liveProcessRows,- parseProcessRow,- processTreePids,- isNoTmuxServerError,- rememberTmuxServer,- resumeSessionId,- reviveRemovedTmuxSocket,- setPaneMouseOn,- type ProcessRow,-} from './tmux.js'+import { isNoTmuxServerError, rememberTmuxServer, reviveRemovedTmuxSocket } from './tmux.js'export interface TmuxPaneSnapshot {tmuxPane: string@@ -49,44 +22,6 @@ export interface TmuxPaneSnapshot {owner?: string}-export interface DiscoveredTmuxAgent {- engine: AgentEngine- tmuxPane: string- cwd: string- processIdentity: ProcessIdentity- /** The stable engine process argv, used only to bind an explicit `--resume <id>` after discovery. */- args: string- resumeSessionId: string | null- /**- * 'ori' when this process is pointed at OpenRouter (`ori claude` and friends). undefined = the probe- * could not read the process; the registry then keeps whatever it already knew.- */- gateway?: 'ori' | null- /**- * The grid this pane's engine is actually talking to, read off the same environment. `null` = read,- * and on no grid. `undefined` = could not be read, which must NOT overwrite a stored assignment —- * see `probeGridAssignment`.- */- grid?: GridAssignment | null- /** Codex only: the non-default CODEX_HOME the process runs under; same three answers as `grid`. */- codexHome?: string | null-}--export type TmuxAgentProbe =- | { ok: true; agents: DiscoveredTmuxAgent[]; panes: Set<string>; ambiguousPanes: Set<string> }- | { ok: false; error: string }--export interface TmuxAgentDiscoveryDeps {- current: () => RegisteredSession[]- onDiscovered: (agent: DiscoveredTmuxAgent) => void | Promise<void>- onObserved: (agent: DiscoveredTmuxAgent, current: RegisteredSession) => void | Promise<void>- onRemoved: (agent: RegisteredSession, reason: string) => void | Promise<void>- probe?: (daemonPid: number, hints?: ReadonlyMap<string, AgentEngine>) => Promise<TmuxAgentProbe>- daemonPid?: number-}--const MISS_LIMIT = 2-// The rule for "no server is running", shared with every other tmux read (lib/tmux.ts).export { isNoTmuxServerError } from './tmux.js'@@ -216,290 +151,3 @@ export async function adoptLegacyHarnessSessions(}return adopted}--function childrenByParent(rows: readonly ProcessRow[]): Map<number, ProcessRow[]> {- const children = new Map<number, ProcessRow[]>()- for (const row of rows) {- const list = children.get(row.parentPid) ?? []- list.push(row)- children.set(row.parentPid, list)- }- return children-}--function daemonDescendants(rows: readonly ProcessRow[], daemonPid: number): Set<number> {- const children = childrenByParent(rows)- const excluded = new Set<number>()- const queue = [daemonPid]- while (queue.length) {- const pid = queue.shift()!- if (excluded.has(pid)) continue- excluded.add(pid)- for (const child of children.get(pid) ?? []) queue.push(child.pid)- }- return excluded-}--/**- * Pick one pane owner from an already-read process tree.- *- * Depth outranks score: a supported CLI nested below another supported CLI is a sub-agent/tool child and- * must not steal the pane. Score only distinguishes wrappers at the same depth. A remaining tie is- * ambiguous and deliberately produces no agent.- */-function paneOwner(- pane: TmuxPaneSnapshot,- rows: readonly ProcessRow[],- excluded: ReadonlySet<number>,- ownership: AgentCommandOwnershipSnapshot,- hintedEngine?: AgentEngine,-): { agent: DiscoveredTmuxAgent | null; ambiguous: boolean } {- const byPid = new Map(rows.map((row) => [row.pid, row]))- const children = childrenByParent(rows)- const queue: Array<{ pid: number; depth: number }> = [{ pid: pane.rootPid, depth: 0 }]- const matches: Array<{ row: ProcessRow; engine: AgentEngine; depth: number; score: number }> = []- let unresolvedAliasDepth = Number.POSITIVE_INFINITY-- while (queue.length) {- const current = queue.shift()!- const row = byPid.get(current.pid)- if (row && !excluded.has(row.pid)) {- for (const engine of PROCESS_ENGINES) {- const score = engineProcessMatchScore(row, engine, ownership)- if (score > 0) matches.push({ row, engine, depth: current.depth, score })- }- if (ambiguousAgentProcess(row, ownership)) {- // A vendor hook is pane-scoped evidence from the running CLI. It may resolve an otherwise bare- // `agent`, but can never override strong file/package evidence for the other vendor.- const aliasOwner = agentAliasOwner([row.imageFileKey, row.entrypointFileKey], ownership)- if (aliasOwner === 'unknown' && (hintedEngine === 'cursor' || hintedEngine === 'grok')) {- matches.push({ row, engine: hintedEngine, depth: current.depth, score: 1 })- } else {- unresolvedAliasDepth = Math.min(unresolvedAliasDepth, current.depth)- }- }- }- for (const child of children.get(current.pid) ?? []) queue.push({ pid: child.pid, depth: current.depth + 1 })- }-- if (!matches.length) return { agent: null, ambiguous: Number.isFinite(unresolvedAliasDepth) }- const shallowest = Math.min(...matches.map((match) => match.depth))- if (unresolvedAliasDepth <= shallowest) return { agent: null, ambiguous: true }- const atDepth = matches.filter((match) => match.depth === shallowest)- const strongest = Math.max(...atDepth.map((match) => match.score))- const finalists = atDepth.filter((match) => match.score === strongest)- const unique = new Map(finalists.map((match) => [`${match.row.pid}:${match.engine}`, match]))- if (unique.size !== 1) return { agent: null, ambiguous: true }-- const [{ row, engine }] = [...unique.values()]- return {- ambiguous: false,- agent: {- engine,- tmuxPane: pane.tmuxPane,- cwd: pane.cwd,- processIdentity: { pid: row.pid, executable: row.executable, startMarker: row.startMarker },- args: row.args,- resumeSessionId: resumeSessionId(engine, row.args),- },- }-}--/** Pure snapshot form used by the reconciler and process-table fixtures. */-export function discoverTmuxAgentsFromSnapshot(- panes: readonly TmuxPaneSnapshot[],- rows: readonly ProcessRow[],- daemonPid: number,- ownership = agentCommandOwnershipSnapshot(),- hints: ReadonlyMap<string, AgentEngine> = new Map(),-): Extract<TmuxAgentProbe, { ok: true }> {- const excluded = daemonDescendants(rows, daemonPid)- const agents: DiscoveredTmuxAgent[] = []- const ambiguousPanes = new Set<string>()- for (const pane of panes) {- const owner = paneOwner(pane, rows, excluded, ownership, hints.get(pane.tmuxPane))- if (owner.ambiguous) ambiguousPanes.add(pane.tmuxPane)- else if (owner.agent) agents.push(owner.agent)- }- return { ok: true, agents, panes: new Set(panes.map((pane) => pane.tmuxPane)), ambiguousPanes }-}--/** One tmux call plus one ps call for a complete reconciliation pass. */-export async function probeTmuxAgents(- daemonPid = process.pid,- hints: ReadonlyMap<string, AgentEngine> = new Map(),-): Promise<TmuxAgentProbe> {- const [tmux, ps] = await Promise.all([- listTmuxPanes(),- // parseProcessRow below anchors on the `lstart` column, which only has its documented shape- // under LC_TIME=C — see psEnv (lib/childLocale.ts).- execText('ps', ['-axo', 'pid=,ppid=,comm=,lstart=,args='], 3_000, psEnv()),- ])- if (!tmux.ok) return { ok: false, error: `tmux list-panes failed: ${tmux.error}` }- if (!ps.ok) return { ok: false, error: `process table failed: ${ps.error}` }- const parsed = liveProcessRows(ps.stdout.split('\n').map(parseProcessRow).filter((row): row is ProcessRow => row !== null))- const rows = await enrichProcessRows(parsed, processTreePids(parsed, tmux.panes.map((pane) => pane.rootPid)))- const probe = discoverTmuxAgentsFromSnapshot(- tmux.panes,- rows,- daemonPid,- agentCommandOwnershipSnapshot(),- hints,- )- // Which endpoint each agent is pointed at, and which grid. Both read the same process environment- // through the same cache, so this stays one read per agent for its whole life rather than one per- // pass — and a failed read leaves `gateway` undefined rather than false.- await Promise.all(probe.agents.map(async (agent) => {- const runtime = await probeGatewayRuntime(agent.processIdentity, agent.args)- agent.gateway = runtime.kind- agent.grid = await probeGridAssignment(agent.processIdentity, agent.engine, agent.args)- // And, for Codex, the profile it runs under — a fact about the process the row cannot otherwise learn.- agent.codexHome = await probeCodexHome(agent.processIdentity, agent.engine)- }))- return probe-}--export function sameRuntime(- current: Pick<RegisteredSession, 'engine' | 'tmuxPane' | 'processIdentity'>,- observed: Pick<DiscoveredTmuxAgent, 'engine' | 'tmuxPane' | 'processIdentity'>,-): boolean {- const saved = current.processIdentity- const live = observed.processIdentity- return current.engine === observed.engine- && current.tmuxPane === observed.tmuxPane- && !!saved- && saved.pid === live.pid- && saved.startMarker === live.startMarker-}--export function runtimeKey(runtime: Pick<DiscoveredTmuxAgent, 'engine' | 'tmuxPane' | 'processIdentity'>): string {- return `${runtime.tmuxPane}\u0000${runtime.engine}\u0000${runtime.processIdentity.pid}\u0000${runtime.processIdentity.startMarker}`-}--/**- * Serialized/coalesced lifecycle loop. Successful negative observations count; probe failures and- * ambiguous panes leave both the agent and its miss count untouched.- */-export class TmuxAgentReconciler {- private readonly misses = new Map<string, number>()- private readonly suppressed = new Set<string>()- private pending = false- private inFlight: Promise<void> | null = null- private timer: NodeJS.Timeout | null = null- private readonly hints = new Map<string, AgentEngine>()- private readonly warnedAmbiguousPanes = new Set<string>()- /** Panes already confirmed `mouse on` this run — set once per pane, not re-checked every scan. A- * pane surviving a daemon restart (or created by an older build, before this existed) starts- * outside this set, so the very next scan that sees it fixes it — not just brand-new panes. */- private readonly mouseEnabledPanes = new Set<string>()-- constructor(private readonly deps: TmuxAgentDiscoveryDeps) {}-- start(intervalMs: number): void {- void this.trigger()- this.timer = setInterval(() => { void this.trigger() }, intervalMs)- this.timer.unref?.()- }-- stop(): void {- if (this.timer) clearInterval(this.timer)- this.timer = null- }-- /** Hide an explicitly deleted runtime until a successful scan proves that exact process is gone. */- suppress(runtime: Pick<DiscoveredTmuxAgent, 'engine' | 'tmuxPane' | 'processIdentity'>): void {- this.suppressed.add(runtimeKey(runtime))- }-- trigger(): Promise<void> {- this.pending = true- if (!this.inFlight) this.inFlight = this.drain().finally(() => { this.inFlight = null })- return this.inFlight- }-- /** A validated vendor hook may resolve the otherwise colliding bare `agent` command in one pane. */- triggerHint(tmuxPane: string, engine: AgentEngine): Promise<void> {- this.hints.set(tmuxPane, engine)- return this.trigger()- }-- private async drain(): Promise<void> {- while (this.pending) {- this.pending = false- await this.reconcileOnce()- }- }-- private async reconcileOnce(): Promise<void> {- const hints = new Map(this.hints)- const probe = await (this.deps.probe ?? probeTmuxAgents)(this.deps.daemonPid ?? process.pid, hints)- if (!probe.ok) {- console.warn(`[discovery] ${probe.error}; keeping ${this.deps.current().length} agent(s)`)- return- }- // Retroactive: a pane from an older build (before tmuxBackend.create() started doing this itself)- // or one that survived a daemon restart never got `mouse on` set. Fire-and-forget — a scan that- // misses one because tmux was briefly slow just catches it on the next pass.- for (const pane of probe.panes) {- if (this.mouseEnabledPanes.has(pane)) continue- this.mouseEnabledPanes.add(pane)- void setPaneMouseOn(pane)- }- for (const pane of [...this.mouseEnabledPanes]) {- if (!probe.panes.has(pane)) this.mouseEnabledPanes.delete(pane)- }- for (const pane of hints.keys()) this.hints.delete(pane)- for (const pane of probe.ambiguousPanes) {- if (this.warnedAmbiguousPanes.has(pane)) continue- this.warnedAmbiguousPanes.add(pane)- console.warn(`[discovery] ${pane} has an unresolved agent command; set CURSOR_PATH or GROK_PATH to an absolute vendor CLI path`)- }- for (const pane of [...this.warnedAmbiguousPanes]) {- if (!probe.ambiguousPanes.has(pane)) this.warnedAmbiguousPanes.delete(pane)- }-- const observedKeys = new Set(probe.agents.map(runtimeKey))- for (const key of [...this.suppressed]) if (!observedKeys.has(key)) this.suppressed.delete(key)-- const before = this.deps.current()- const byPane = new Map(before.map((agent) => [agent.tmuxPane, agent]))- const observedAgentIds = new Set<string>()-- for (const observed of probe.agents) {- if (this.suppressed.has(runtimeKey(observed))) continue- const current = byPane.get(observed.tmuxPane)- if (!current) {- await this.deps.onDiscovered(observed)- continue- }- // One-time migration from a launcher-owned record that did not persist a process identity.- const legacyMatch = !current.processIdentity && current.engine === observed.engine- if (legacyMatch || sameRuntime(current, observed)) {- observedAgentIds.add(current.agentId)- this.misses.delete(current.agentId)- await this.deps.onObserved(observed, current)- continue- }- this.misses.delete(current.agentId)- await this.deps.onRemoved(current, `process replaced in ${observed.tmuxPane}`)- await this.deps.onDiscovered(observed)- }-- for (const current of before) {- if (observedAgentIds.has(current.agentId)) continue- if (probe.ambiguousPanes.has(current.tmuxPane)) continue- const observed = probe.agents.find((candidate) => candidate.tmuxPane === current.tmuxPane)- if (observed) continue // replacement already handled above- const misses = (this.misses.get(current.agentId) ?? 0) + 1- if (misses < MISS_LIMIT) {- this.misses.set(current.agentId, misses)- continue- }- this.misses.delete(current.agentId)- const reason = probe.panes.has(current.tmuxPane)- ? `no supported engine process in ${current.tmuxPane} after ${MISS_LIMIT} confirmed scans`- : `tmux pane ${current.tmuxPane} absent after ${MISS_LIMIT} confirmed scans`- await this.deps.onRemoved(current, reason)- }- }-}diff --git a/cli/src/testing/isolatedTmux.spec.ts b/cli/src/testing/isolatedTmux.spec.tsindex 947947178..7768038a1 100644--- a/cli/src/testing/isolatedTmux.spec.ts+++ b/cli/src/testing/isolatedTmux.spec.ts@@ -22,7 +22,7 @@ describe.skipIf(!hasTmux)('real tmux test isolation', () => {expect(wrong.stdout.trim()).toBe(parent.socket)await child.run('new-session', '-d', '-s', 'fixture', 'sleep 600')- // TmuxBackend/probeTmuxAgents use bare commands; prove their environment selects the child.+ // TmuxBackend uses bare commands; prove its environment selects the child.const actual = await exec('tmux', ['display-message', '-p', '-t', 'fixture', '#{socket_path}'], {env: child.env, timeout: 5_000,})diff --git a/docs/cli.md b/docs/cli.mdindex 2f772433a..185569c17 100644--- a/docs/cli.md+++ b/docs/cli.md@@ -48,7 +48,7 @@ through this daemon's link to it.What it answers: `agents_list`, `agent_create`, `agent_restart`, `agent_retarget`, `agent_delete`,`agent_update`, `agent_recent`, `agent_handoff_prepare`, `agent_read_file` (media previews, in 128 KiB chunks),`fs_list_dir`, `engines_probe`, `codex_profiles_list`, `codex_profile_link`, `models_list`,-`usage_read`, `question_response`, `voice_route`, `message`, `cancel`, and `terminal_open` for a+`usage_read`, `question_response`, `message`, `cancel`, and `terminal_open` for abinary terminal channel with scroll, resync and paste. The same frames travel from the web clientover the relay.