Skip to content

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.

CLI: a terminal is an engine — a shell in a pane that adopts what is typed into it

0xken15fac56f81f40b
diff --git a/cli/src/backendSocket.spec.ts b/cli/src/backendSocket.spec.ts
index 9bef7a600..06383a453 100644
--- a/cli/src/backendSocket.spec.ts
+++ b/cli/src/backendSocket.spec.ts
@@ -1,7 +1,8 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { readFileSync } from 'fs'
+import { homedir } from 'os'
import { fileURLToPath } from 'url'
-import { BackendSocket, compactRuntimePickerModels, deviceAgentListItem, grokHistoryPage } from './backendSocket.js'
+import { BackendSocket, compactRuntimePickerModels, deviceAgentListItem, deviceAgentRow, grokHistoryPage } from './backendSocket.js'
import { AuthSessionError, type AuthSessionManager } from './lib/authSession.js'
import { WS_IDLE_DEADLINE_MS as IDLE_DEADLINE_MS } from './lib/wsLiveness.js'
import type { TerminalStreamManager } from './lib/terminalStreamManager.js'
@@ -809,6 +810,43 @@ describe('BackendSocket outbound queue', () => {
}
})
+ it('creates a terminal with no folder at home, and refuses it a grid or a project to prepare', async () => {
+ const socket = new BackendSocket('token')
+ const frames: Array<Record<string, unknown>> = []
+ socket.registerLocalClient('local:terminal', {
+ sendFrame: (frame) => { frames.push(frame); return true }, sendBinary: () => true,
+ })
+ const pending: RegisteredSession = {
+ schemaVersion: 2, active: true, launch: { state: 'ready' }, terminalHost: true,
+ agentId: 'term-1', sessionId: '', boundAt: null, engine: 'terminal',
+ transcriptPath: null, projectDir: 'nqhieu84', cwd: homedir(),
+ runtimes: [{ backend: 'tmux', paneId: '%9' }], primaryRuntimeKey: 'tmux/%9', tmuxPane: '%9',
+ source: null, title: null, model: null, cliVersion: null, processIdentity: null,
+ registeredAt: 1, updatedAt: 1, lastHookAt: 1, lastTranscriptAt: 1,
+ }
+ const create = vi.fn(async (_input: { engine: string; cwd: string }) => ({ ok: true as const, session: pending }))
+ socket.onCreateAgent = create
+ const ask = (requestId: string, payload: Record<string, unknown>) => socket.handleLocalFrame('local:terminal', {
+ type: 'agent_create', payload: { requestId, engine: 'terminal', ...payload },
+ })
+ const errorOf = (requestId: string) => (frames.find((frame) => frame.type === 'agent_create_result'
+ && (frame.payload as { requestId?: string }).requestId === requestId)?.payload as { error?: string } | undefined)?.error
+ try {
+ ask('home', {})
+ ask('folder', { cwd: '/tmp/work' })
+ await vi.waitFor(() => expect(create).toHaveBeenCalledTimes(2))
+ expect(create.mock.calls.map(([input]) => [input.engine, input.cwd])).toEqual([['terminal', homedir()], ['terminal', '/tmp/work']])
+ ask('relative', { cwd: 'work' })
+ ask('grid', { grid: { networkId: 'n', networkName: 'net', baseUrl: 'https://grid.example', apiKey: 'k' } })
+ ask('prompt', { prompt: 'hello' })
+ await vi.waitFor(() => expect(['relative', 'grid', 'prompt'].map(errorOf)).toEqual(['INVALID_CWD', 'INVALID_GRID', 'PROMPT_UNSUPPORTED']))
+ expect(create).toHaveBeenCalledTimes(2)
+ } finally {
+ await socket.unregisterLocalClient('local:terminal')
+ await socket.stop()
+ }
+ })
+
it('recovers a delayed creation on the same connection without starting another agent', async () => {
const socket = new BackendSocket('token')
const frames: Array<Record<string, unknown>> = []
@@ -1390,6 +1428,12 @@ describe('device agent list contract', () => {
id: 'g1', name: 'Grok agent', engine: 'grok',
})
})
+
+ it('keeps a terminal off the device: not a row for it, and never an engine it would understand', () => {
+ expect(deviceAgentRow({ id: 't1', name: 'Terminal 1', engine: 'terminal' })).toBe(false)
+ expect(deviceAgentRow({ id: 'c1', name: 'Claude 1', engine: 'claude' })).toBe(true)
+ expect(deviceAgentListItem({ id: 't1', name: 'Terminal 1', engine: 'terminal' })).toEqual({ id: 't1', name: 'Terminal 1' })
+ })
})
describe('Grok session_get history', () => {
diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.ts
index 34d200c38..cbc5e250b 100644
--- a/cli/src/backendSocket.ts
+++ b/cli/src/backendSocket.ts
@@ -26,7 +26,7 @@ import { env } from './config/env.js'
import { AuthSessionManager, AuthSessionError } from './lib/authSession.js'
import { VERSION } from './version.js'
import { registry, projectDisplayName, type RegisteredSession } from './lib/registry.js'
-import { ENGINES, type AgentEngine } from './engines/types.js'
+import { ENGINES, PROCESS_ENGINES, isTerminalEngine, type AgentEngine, type ProcessEngine } from './engines/types.js'
import { listDir } from './lib/fsBrowse.js'
import { linkCodexProfile, listCodexProfiles } from './lib/codexProfiles.js'
import { gridCliPresence } from './lib/gridExec.js'
@@ -224,16 +224,29 @@ export function copilotHistoryPage(lines: string[], paginated: boolean):
export function deviceAgentListItem(
raw: unknown,
-): { id: unknown; name?: string; engine?: 'claude' | 'codex' | 'cursor' | 'opencode' | 'pi' | 'hermes' | 'commandcode' | 'devin' | 'muse' | 'amp' | 'kilo' | 'grok' | 'agy' | 'copilot'; selectedModel?: string | null } {
+): { id: unknown; name?: string; engine?: ProcessEngine; selectedModel?: string | null } {
const o = (raw ?? {}) as Record<string, unknown>
- const item: { id: unknown; name?: string; engine?: 'claude' | 'codex' | 'cursor' | 'opencode' | 'pi' | 'hermes' | 'commandcode' | 'devin' | 'muse' | 'amp' | 'kilo' | 'grok' | 'agy' | 'copilot'; selectedModel?: string | null } = { id: o.id }
+ const item: { id: unknown; name?: string; engine?: ProcessEngine; selectedModel?: string | null } = { id: o.id }
if (typeof o.name === 'string') item.name = clipDeviceAgentName(o.name)
- if (o.engine === 'claude' || o.engine === 'codex' || o.engine === 'cursor' || o.engine === 'opencode' || o.engine === 'pi' || o.engine === 'hermes' || o.engine === 'commandcode' || o.engine === 'devin' || o.engine === 'muse' || o.engine === 'amp' || o.engine === 'kilo' || o.engine === 'grok' || o.engine === 'agy' || o.engine === 'copilot') item.engine = o.engine
+ // The dial only ever meets process engines — a terminal never reaches it (see `deviceAgentRow`),
+ // and the union here says so rather than repeating fourteen string literals.
+ if (typeof o.engine === 'string' && (PROCESS_ENGINES as readonly string[]).includes(o.engine)) item.engine = o.engine as ProcessEngine
// Runtime model/effort profile (opaque runtime-v1:...) — lets the device render + change model/effort.
if (typeof o.selectedModel === 'string' || o.selectedModel === null) item.selectedModel = o.selectedModel
return item
}
+/**
+ * Whether an agent row belongs on a device at all. The dial drives agents — a terminal with nobody
+ * running in it has no turn to watch, no question to answer and no model to switch, so it is not
+ * listed there; the same row becomes listable the moment an engine is started inside it and its
+ * `engine` flips (registry `adoptEngine`).
+ */
+export function deviceAgentRow(raw: unknown): boolean {
+ const o = (raw ?? {}) as Record<string, unknown>
+ return !isTerminalEngine(typeof o.engine === 'string' ? o.engine : undefined)
+}
+
/**
* How many models the DEVICE picker may receive. Matches its own PICK_MAX (ui_screens.c) so the wheel
* never renders more rows than it was built for; the web picker is unbounded and still gets everything.
@@ -1393,7 +1406,7 @@ export class BackendSocket {
// sorts by the same rule; the two must stay identical.
projects.sort((a, b) => Date.parse(a.createdAt) - Date.parse(b.createdAt) || a.id.localeCompare(b.id))
if (this.e2ee.sessionRole(connId) === 'device') {
- reply(type, requestId, { agents: projects.slice(0, DEVICE_AGENT_LIST_LIMIT).map(deviceAgentListItem) })
+ reply(type, requestId, { agents: projects.filter(deviceAgentRow).slice(0, DEVICE_AGENT_LIST_LIMIT).map(deviceAgentListItem) })
return
}
reply(type, requestId, { agents: projects })
@@ -1750,7 +1763,7 @@ export class BackendSocket {
installed: entry.installed,
command: entry.command,
installable: entry.installable,
- installCommand: entry.installable ? engineInstallRecipe(entry.engine).command : null,
+ installCommand: entry.installable ? engineInstallRecipe(entry.engine)?.command ?? null : null,
// Static per-CLI-version capability, not a probe result: its mere presence is what
// lets an older CLI (which never sends the field) keep reading as "unknown" rather
// than "no", per the desktop app's `EngineAvailability.fromJson`.
@@ -1868,7 +1881,11 @@ export class BackendSocket {
catch (error) {
reply(type, requestId, { error: error instanceof ProjectFolderError ? error.code : 'INVALID_PROJECT_SOURCE' }); return
}
- if (!projectFolder && (typeof cwd !== 'string' || !isAbsolute(cwd))) { reply(type, requestId, { error: 'INVALID_CWD' }); return }
+ // A terminal opens where a terminal app would — the home directory — when the client names
+ // no folder; every other engine works IN a folder and must be told which.
+ const terminal = isTerminalEngine(engine)
+ if (terminal && projectFolder) { reply(type, requestId, { error: 'INVALID_PROJECT_SOURCE', detail: 'a terminal opens in a folder, it does not prepare one' }); return }
+ if (!projectFolder && !(terminal && cwd === undefined) && (typeof cwd !== 'string' || !isAbsolute(cwd))) { reply(type, requestId, { error: 'INVALID_CWD' }); return }
if (!this.onCreateAgent) { reply(type, requestId, { error: 'UNSUPPORTED_ON_REMOTE' }); return }
const creationId = payload.creationId
if (creationId !== undefined && !validCreationId(creationId)) {
@@ -1882,6 +1899,7 @@ export class BackendSocket {
// that quietly ran on the engine's own login would look like it worked.
const grid = parseGridLaunchOverride(payload.grid)
if (grid.state === 'invalid') { reply(type, requestId, { error: 'INVALID_GRID', detail: grid.reason }); return }
+ if (terminal && grid.state === 'ok') { reply(type, requestId, { error: 'INVALID_GRID', detail: 'a terminal has no engine to point at a grid' }); return }
// Same validation the desktop app already applies client-side (`Agent._safeCodexHome`) —
// repeated here because a client's own check is not a guarantee about what actually
// arrives on the wire.
@@ -1956,7 +1974,7 @@ export class BackendSocket {
}
const input = {
engine,
- cwd: typeof cwd === 'string' ? cwd : '',
+ cwd: typeof cwd === 'string' ? cwd : terminal ? homedir() : '',
// On unless a client says otherwise: a harness works without stopping to ask for each command.
bypassPermission: permissionMode ? permissionModeApproves(permissionMode) : payload.bypassPermission !== false,
permissionMode,
diff --git a/cli/src/cable/cableHost.spec.ts b/cli/src/cable/cableHost.spec.ts
index bbbcf649f..eb6323a3b 100644
--- a/cli/src/cable/cableHost.spec.ts
+++ b/cli/src/cable/cableHost.spec.ts
@@ -246,6 +246,14 @@ describe('DaemonCableHost.listAgentsFlat across machines, and the tab the dial g
expect(agents.map((a) => a.machineId)).toEqual(['mine', 'other', 'third'])
})
+ it('never lists a terminal — a shell with nobody in it is not something the dial can drive', async () => {
+ AGENTS.length = 0
+ AGENTS.push({ agentId: 'term-1', registeredAt: 1, active: true, terminalAvailable: true, engine: 'terminal' })
+ AGENTS.push({ agentId: 'local-1', registeredAt: 2, active: true, terminalAvailable: true, engine: 'claude' })
+ const host = new DaemonCableHost(wiring(), crossFleet({}, []))
+ expect((await settled(host)).map((a) => a.id)).toEqual(['local-1'])
+ })
+
it('keeps a machine\'s agents when the backend cannot be asked', async () => {
// The failure this exists for, measured on the real dial: `unknown` means the backend could not be
// reached — MachineListCache.degrade() marks EVERY machine with it in one go — and reading it as
diff --git a/cli/src/cable/cableHost.ts b/cli/src/cable/cableHost.ts
index 8f602a438..dda960fe2 100644
--- a/cli/src/cable/cableHost.ts
+++ b/cli/src/cable/cableHost.ts
@@ -12,6 +12,7 @@ import { join } from 'node:path'
import { AuthSessionManager, readAuthSession } from '../lib/authSession.js'
import { registry, projectDisplayName, type RegisteredSession } from '../lib/registry.js'
+import { isTerminalEngine } from '../engines/types.js'
import { fetchRelease, loadImage, shouldOffer } from './fwPush.js'
import { routeVoiceTask, type RouterAgent, type RouterContinuity } from '../lib/voiceRouter.js'
import { env } from '../config/env.js'
@@ -280,7 +281,10 @@ export class DaemonCableHost implements CableHost {
// `advertised()`, not `list()` — the SAME set `agents_list` answers the web and the desktop app with. They
// read one registry and must not disagree about what is on it: a dead agent holding a tile on the dial
// and nowhere else is a tile that cannot be driven and cannot be explained.
- const sessions = registry.advertised()
+ // Minus the terminals: the dial drives agents, and a shell with nobody in it has no turn to
+ // watch or model to switch (`deviceAgentRow` keeps `agents_list` to the same set for the
+ // device). A terminal that has adopted an engine is that engine here, as everywhere.
+ const sessions = registry.advertised().filter((s) => !isTerminalEngine(s.engine))
// Oldest → newest, and TOTAL: the id breaks a tie so the order cannot fall through to array position,
// which is Map insertion order and differs between daemon runs. Both producers sort identically, so
// the dial and the app cannot drift apart while reading the same registry.
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index 0eb54074a..af6392d2e 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -64,8 +64,8 @@ import { ensureHarnessGrid } from './lib/gridEnsure.js'
import { passThroughToGridLogout } from './lib/gridLogout.js'
import { clearGridMcpUrlCache } from './lib/gridMcpUrl.js'
import { warnIfGridSignInRemains } from './lib/gridCredentials.js'
-import { ENGINE_CLI_COMMANDS, ENGINES, engineBin, enginePathOverride } from './lib/engineBin.js'
-import type { AgentEngine } from './engines/types.js'
+import { ENGINE_CLI_COMMANDS, ENGINES, PROCESS_ENGINES, engineBin, enginePathOverride } from './lib/engineBin.js'
+import { isTerminalEngine, type AgentEngine } from './engines/types.js'
import { engineInstallRecipe } from './lib/engineInstall.js'
import { buildEngineCommandArgv, buildEngineLaunchArgv, commandAvailableInInteractiveShell, namedAgentArgs } from './lib/engineLaunch.js'
import { buildGridEngineLaunch, describeGridLaunch, gridConflictingEnvToClear, gridEnvVarNames, type GridLaunchMachine, type GridWebSearchStatus } from './lib/gridLaunch.js'
@@ -82,7 +82,8 @@ import { createAndRegisterPane } from './lib/createAgentPane.js'
import { restoreAgents } from './lib/restoreAgents.js'
import { buildLaunchOverrides, validateLaunchOverrides, type LaunchOverrides, type LaunchOverridesDeps, type LaunchOverridesResult, type LaunchSource } from './lib/launchOverrides.js'
import { prepareCodexResume } from './engines/codex/portableHistory.js'
-import { buildHarnessSessionLabel } from './lib/harnessSessionLabel.js'
+import { buildHarnessSessionLabel, isHarnessSessionFor } from './lib/harnessSessionLabel.js'
+import { listTmuxPanes } from './lib/tmuxAgentDiscovery.js'
import { installedDsh } from './dsh/installed.js'
import { dshVerdictPath, dshViewerName } from './dsh/manifest.js'
import { catalogEntry } from './dsh/catalog.js'
@@ -293,7 +294,7 @@ function usage(exitCode = 0): never {
Agents — after "harness start", run the vendor CLI directly inside tmux. Harness discovers supported
top-level processes automatically; it does not launch them or change their permission flags:
-${ENGINES.map((engine) => ` ${ENGINE_CLI_COMMANDS[engine]}`).join('\n')}
+${PROCESS_ENGINES.map((engine) => ` ${ENGINE_CLI_COMMANDS[engine]}`).join('\n')}
A launcher that hands the pane to one of these works the same — "ori claude" is a Claude Code agent.
Machine:
@@ -1420,6 +1421,10 @@ async function runForeground(session: AuthSession): Promise<void> {
// server may fall back to a free port if env.PORT is taken, and the hooks must point at the real one.
const syncSession = (s: RegisteredSession, opts: { device?: boolean } = {}): void => {
+ // A terminal is not the dial's business (see `deviceAgentRow`): it is never upserted there, and
+ // the one time it must be REMOVED from there — the engine it adopted has exited — the caller
+ // sends that `agent_deleted` itself, because this row is still very much alive for the app.
+ if (isTerminalEngine(s.engine)) opts = { ...opts, device: false }
if (!registry.terminalAvailable(s.agentId)) {
backendRef?.send({ type: 'agent_deleted', payload: { agentId: s.agentId } })
if (opts.device !== false) backendRef?.sendCommander({ type: 'agent_deleted', payload: { agentId: s.agentId } })
@@ -1434,6 +1439,7 @@ async function runForeground(session: AuthSession): Promise<void> {
.catch((err) => console.error('[cli] announceSession failed:', err instanceof Error ? err.message : err))
}
const announceRename = (s: RegisteredSession, opts: { device?: boolean } = {}): void => {
+ if (isTerminalEngine(s.engine)) opts = { ...opts, device: false }
const name = projectDisplayName(s)
backendRef?.send({ type: 'agent_renamed', payload: { agentId: s.agentId, name, engine: s.engine } })
if (opts.device !== false) backendRef?.sendCommander({ type: 'agent_renamed', payload: { agentId: s.agentId, name, engine: s.engine } })
@@ -2678,6 +2684,14 @@ async function runForeground(session: AuthSession): Promise<void> {
const gridMoved = observed.grid !== undefined
&& !sameGridAssignment(current.grid ?? null, observed.grid)
const wasLaunching = current.launch?.state !== undefined && current.launch.state !== 'ready'
+ // Somebody typed an engine into a terminal. The row becomes that engine's agent — same id,
+ // same pane — and from here on is handled exactly like one the app launched: bound by its
+ // hooks, watched for turns, listed on the dial. `adopted` makes the announce below
+ // unconditional, since the engine changing is the one fact the app must not miss.
+ const adopted = isTerminalEngine(current.engine) && !isTerminalEngine(observed.engine)
+ ? registry.adoptEngine(current.agentId, observed.engine, observed.processIdentity)
+ : null
+ if (adopted) console.log(`[discovery] ${sid(current.agentId)} terminal → ${observed.engine} · ${observed.primaryRuntimeKey}`)
registry.updateRuntimes(current.agentId, observed.runtimes, observed.primaryRuntimeKey)
registry.updateProcessIdentity(current.agentId, observed.processIdentity, observed.gateway, observed.grid)
// The live argv is the truth about the bypass flag, and this is the one place every running
@@ -2695,7 +2709,7 @@ async function runForeground(session: AuthSession): Promise<void> {
if (withDsh?.dsh) attachDsh(withDsh)
if (wasLaunching) registry.setLaunch(current.agentId, { state: 'ready' })
await bindObservedAgent(observed)
- if (wasDormant || wasLaunching) {
+ if (wasDormant || wasLaunching || adopted) {
const active = registry.byAgent(current.agentId)
if (!active) return
if (active.sessionId && !await attachSession(active)) {
@@ -2718,13 +2732,27 @@ async function runForeground(session: AuthSession): Promise<void> {
},
onDormant: (agent, reason) => {
if (!agent.active) return
- registry.setActive(agent.agentId, false)
invalidateTerminalControl(agent.agentId)
input.forget(agent.agentId)
if (agent.sessionId) {
questionWatcher.stop(agent.sessionId)
stopHeartbeat(agent.sessionId)
}
+ // The engine somebody started inside a terminal has exited: the pane is a shell at its prompt
+ // again, so the row goes back to being a terminal — live, not dormant — and the dial, which
+ // only ever saw it as an agent, is told it is gone. The web/app side gets the same row with
+ // its engine back to `terminal` and draws it as one.
+ if (agent.terminalHost) {
+ const released = registry.releaseEngine(agent.agentId)
+ if (released) {
+ syncRecapPool()
+ console.log(`[discovery] ${sid(agent.agentId)} ${agent.engine} → terminal · ${reason}`)
+ announceSession(released, { device: false })
+ backendRef?.sendCommander({ type: 'agent_deleted', payload: { agentId: agent.agentId } })
+ return
+ }
+ }
+ registry.setActive(agent.agentId, false)
console.log(`[discovery] ${sid(agent.agentId)} dormant · ${reason}`)
announceSession(agent)
},
@@ -3708,6 +3736,13 @@ async function runForeground(session: AuthSession): Promise<void> {
// and a pane that outlived the daemon in a session discovery no longer lists still has its
// engine, which a second pane resuming the same session would collide with.
liveProcess: (entry, runtime) => resolvePaneEngineProcess(runtime.paneId, entry.engine),
+ liveTerminalPane: async (runtime) => {
+ const inventory = await listTmuxPanes()
+ if (!inventory.ok) return false
+ // Its OWN session, not just any harness pane: a new tmux server hands out `%N` from zero
+ // again, and a stale id can name another agent's pane.
+ return inventory.panes.some((pane) => pane.tmuxPane === runtime.paneId && isHarnessSessionFor(pane.tmuxSessionName, 'terminal'))
+ },
buildLaunch: async (entry, opts) => {
// Mirrors `agent_create`: the same grid env/argv (and the same vendor variables cleared), or
// the same Codex profile with its hooks installed; the install check runs inside the pane's
@@ -4047,6 +4082,16 @@ async function runForeground(session: AuthSession): Promise<void> {
})
if (!result.ok) return { ok: false, error: result.error, detail: result.detail }
const { spawned, pending } = result
+ // A terminal is ready the moment its pane is: there is no engine process to wait for, and the
+ // shell exiting is the person closing it — so `remain-on-exit` comes off now, and the pane going
+ // away is what removes the row (reconciler `onRemoved`), exactly as for an engine that quit.
+ if (isTerminalEngine(engine)) {
+ await clearPaneRemainOnExit(spawned.runtime.paneId)
+ const ready = registry.setLaunch(pending.agentId, { state: 'ready' }) ?? pending
+ announceSession(ready)
+ console.log(`[agent] create terminal open · agent ${pending.agentId}`)
+ return { ok: true, session: ready }
+ }
announceSession(pending)
if (pending.dsh) attachDsh(pending)
@@ -4404,6 +4449,21 @@ async function runForeground(session: AuthSession): Promise<void> {
}
forgetSession(sessionId, { force: true })
if (!s) return
+ // Stopping a terminal is closing it: there is no engine pid to signal, the shell IS the thing,
+ // and a shell left running in a pane nobody can see any more is a leak. A terminal that adopted
+ // an engine goes the same way — the person pressed Stop on the tile, not on the engine — so
+ // the pane is killed alongside the engine's own termination below.
+ if (s.terminalHost && tmuxBackend) {
+ const runtimes = s.runtimes.filter((runtime): runtime is TmuxRuntimeRef => runtime.backend === 'tmux')
+ void Promise.all(runtimes.map((runtime) => tmuxBackend.kill(runtime))).then(() => {
+ console.log(`[delete] ${sid(sessionId)} terminal · pane closed`)
+ if (isTerminalEngine(s.engine)) clearDeleted(sessionId)
+ void agentReconciler.trigger()
+ }).catch((err) => {
+ console.error('[delete] terminal pane close failed:', err instanceof Error ? err.message : err)
+ })
+ if (isTerminalEngine(s.engine)) return
+ }
void terminateDeletedAgent(s, {
checkRuntime: checkPidRuntime,
kill: (pid, signal) => process.kill(pid, signal),
@@ -4441,11 +4501,34 @@ async function runForeground(session: AuthSession): Promise<void> {
const session = registry.resolve(agentId)
if (!session) return { ok: false, error: 'AGENT_NOT_FOUND' }
if (!session.tmuxPane || !tmuxBackend) return { ok: false, error: 'RESTART_UNSUPPORTED_BACKEND' }
- if (!session.processIdentity) return { ok: false, error: 'NO_ACTIVE_PROCESS' }
const pane = session.tmuxPane
const engine = session.engine
const runtime: TmuxRuntimeRef = { backend: 'tmux', paneId: pane }
const routeKey = terminalRouteKey(runtime)
+ // Restarting a terminal is a fresh shell in the same pane — `respawn-pane -k` over whatever the
+ // old one was doing. There is no engine to wait for and no session to resume, so none of the
+ // process-swap choreography below applies. A terminal that ADOPTED an engine restarts the
+ // engine, like any agent: the tile said Restart about the engine it shows.
+ if (isTerminalEngine(engine)) {
+ agentReconciler.holdRoute(routeKey)
+ try {
+ const respawned = await tmuxBackend.respawn(runtime, {
+ command: buildEngineLaunchArgv(engine, session.cwd ? { cwd: session.cwd } : {}),
+ cwd: homedir(),
+ })
+ if (respawned.state !== 'succeeded') return { ok: false, error: 'RESTART_FAILED', detail: respawned.reason }
+ await clearPaneRemainOnExit(pane)
+ registry.setActive(session.agentId, true)
+ const refreshed = registry.byAgent(session.agentId)
+ if (!refreshed) return { ok: false, error: 'RESTART_FAILED', detail: 'agent vanished from the registry mid-restart' }
+ announceSession(refreshed)
+ console.log(`[restart] ${sid(session.agentId)} terminal · fresh shell`)
+ return { ok: true, session: refreshed, resumed: false }
+ } finally {
+ agentReconciler.releaseRoute(routeKey)
+ }
+ }
+ if (!session.processIdentity) return { ok: false, error: 'NO_ACTIVE_PROCESS' }
// The replacement is launched WITH what the original was: its grid's env and argv (a bare
// respawn would inherit the tmux session's variables but never the codex `-c …` / pi `--model`
diff --git a/cli/src/engines/types.ts b/cli/src/engines/types.ts
index da7ff8f12..0a2731663 100644
--- a/cli/src/engines/types.ts
+++ b/cli/src/engines/types.ts
@@ -11,10 +11,33 @@ import type { RegisteredSession } from '../lib/registry.js'
export const ENGINES = [
'claude', 'codex', 'cursor', 'opencode', 'pi', 'hermes',
'commandcode', 'devin', 'muse', 'amp', 'kilo', 'grok', 'agy', 'copilot',
+ 'terminal',
] as const
export type AgentEngine = (typeof ENGINES)[number]
+/**
+ * The one engine that is not a program: a plain login shell in a harness pane, opened by the
+ * desktop's New Terminal. It has no binary to launch, no hooks, no session, no process signature —
+ * the pane is the whole agent. When an engine CLI is started INSIDE it the row adopts that engine
+ * (`registry.adoptEngine`) and drops back to `terminal` when it exits (`registry.releaseEngine`).
+ */
+export const TERMINAL_ENGINE = 'terminal' satisfies AgentEngine
+export type TerminalEngine = typeof TERMINAL_ENGINE
+/** An engine that is a program: every engine but the terminal. */
+export type ProcessEngine = Exclude<AgentEngine, TerminalEngine>
+
+export function isTerminalEngine(engine: string | null | undefined): engine is TerminalEngine {
+ return engine === TERMINAL_ENGINE
+}
+
+/**
+ * Every engine that runs as a recognizable process — what discovery scans a pane for. A shell is
+ * deliberately not in it: a pane whose only process is a shell is a terminal, not an engine waiting
+ * to be found.
+ */
+export const PROCESS_ENGINES: readonly ProcessEngine[] = ENGINES.filter((engine): engine is ProcessEngine => !isTerminalEngine(engine))
+
export interface EngineNormalizer {
ingest(line: string): LiveEvent[]
finishReplay(): LiveEvent[]
diff --git a/cli/src/lib/agentNames.ts b/cli/src/lib/agentNames.ts
index 619f15ce3..3d98edf5e 100644
--- a/cli/src/lib/agentNames.ts
+++ b/cli/src/lib/agentNames.ts
@@ -27,6 +27,7 @@ const ENGINE_LABELS: Record<AgentEngine, string> = {
grok: 'Grok',
agy: 'Antigravity',
copilot: 'Copilot',
+ terminal: 'Terminal',
}
export function engineLabel(engine: string): string {
diff --git a/cli/src/lib/engineBin.spec.ts b/cli/src/lib/engineBin.spec.ts
index 2b8949bf9..1ae7b17a1 100644
--- a/cli/src/lib/engineBin.spec.ts
+++ b/cli/src/lib/engineBin.spec.ts
@@ -8,7 +8,7 @@ import {
agentCommandOwnershipSnapshot,
cursorRuntimeBin,
ENGINE_CLI_COMMANDS,
- ENGINES,
+ PROCESS_ENGINES,
executableFileIdentity,
installedEngineBin,
} from './engineBin.js'
@@ -23,7 +23,7 @@ afterEach(() => {
describe('canonical engine CLI commands', () => {
it('keeps the user-facing 14-engine command contract exact and ordered', () => {
- expect(ENGINES.map((engine) => [engine, ENGINE_CLI_COMMANDS[engine]])).toEqual([
+ expect(PROCESS_ENGINES.map((engine) => [engine, ENGINE_CLI_COMMANDS[engine]])).toEqual([
['claude', 'claude'],
['codex', 'codex'],
['cursor', 'cursor-agent'],
diff --git a/cli/src/lib/engineBin.ts b/cli/src/lib/engineBin.ts
index 3a38ab823..2f1cc432e 100644
--- a/cli/src/lib/engineBin.ts
+++ b/cli/src/lib/engineBin.ts
@@ -10,11 +10,11 @@ import { accessSync, constants, readlinkSync, realpathSync, statSync } from 'nod
import { homedir } from 'node:os'
import { basename, delimiter, isAbsolute, join, normalize, sep } from 'node:path'
import { env } from '../config/env.js'
-import { ENGINES, type AgentEngine } from '../engines/types.js'
+import { ENGINES, PROCESS_ENGINES, type AgentEngine } from '../engines/types.js'
// Keep this historical import surface for callers, but never duplicate the
// catalog here. `engines/types.ts` is the one iterable source of truth.
-export { ENGINES }
+export { ENGINES, PROCESS_ENGINES }
/** Public vendor command shown to users and matched by the real-binary smoke matrix. */
export const ENGINE_CLI_COMMANDS: Readonly<Record<AgentEngine, string>> = {
@@ -34,6 +34,9 @@ export const ENGINE_CLI_COMMANDS: Readonly<Record<AgentEngine, string>> = {
grok: 'grok',
agy: 'agy',
copilot: 'copilot',
+ // A terminal has no command: the pane runs the user's login shell (engineLaunch.ts). The empty
+ // string is what keeps every "is this binary installed" probe honest — nothing to look for.
+ terminal: '',
}
export interface ExecutableFileIdentity {
@@ -79,6 +82,7 @@ export const ENGINE_CLI_ALIASES: Readonly<Record<AgentEngine, readonly string[]>
grok: ['grok', 'agent'],
agy: ['agy'],
copilot: ['copilot'],
+ terminal: [],
}
let interactivePathCache: { shell: string; daemonPath: string; value: string[] } | null = null
@@ -210,7 +214,7 @@ function uniqueIdentities(identities: readonly ExecutableFileIdentity[]): Execut
export function engineBinaryOwnershipSnapshot(): AgentCommandOwnershipSnapshot {
const engineCandidates = new Map<AgentEngine, ExecutableFileIdentity[]>()
const engineFileKeys = new Map<AgentEngine, Set<string>>()
- for (const engine of ENGINES) {
+ for (const engine of PROCESS_ENGINES) {
const configured = enginePathOverride(engine)
const commands = [
...(configured ? [configured] : []),
@@ -284,7 +288,7 @@ export function engineFileOwners(
snapshot: AgentCommandOwnershipSnapshot,
): AgentEngine[] {
if (!snapshot.engineFileKeys) return []
- return ENGINES.filter((engine) => fileKeys.some((fileKey) => !!fileKey && snapshot.engineFileKeys!.get(engine)?.has(fileKey)))
+ return PROCESS_ENGINES.filter((engine) => fileKeys.some((fileKey) => !!fileKey && snapshot.engineFileKeys!.get(engine)?.has(fileKey)))
}
export function agentAliasOwner(
@@ -408,6 +412,7 @@ export function enginePathOverride(engine: AgentEngine): string | undefined {
case 'grok': return env.GROK_PATH
case 'agy': return env.AGY_PATH
case 'copilot': return env.COPILOT_PATH
+ case 'terminal': return undefined
}
}
@@ -430,5 +435,7 @@ export function engineBin(engine: AgentEngine): string {
case 'grok': return env.GROK_PATH || ENGINE_CLI_COMMANDS.grok
case 'agy': return env.AGY_PATH || ENGINE_CLI_COMMANDS.agy
case 'copilot': return env.COPILOT_PATH || ENGINE_CLI_COMMANDS.copilot
+ // Never launched by name — `buildEngineLaunchArgv` builds the shell argv itself.
+ case 'terminal': return ENGINE_CLI_COMMANDS.terminal
}
}
diff --git a/cli/src/lib/engineInstall.spec.ts b/cli/src/lib/engineInstall.spec.ts
index af9356d16..7ee1686c9 100644
--- a/cli/src/lib/engineInstall.spec.ts
+++ b/cli/src/lib/engineInstall.spec.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest'
import { execFileSync } from 'node:child_process'
-import { ENGINES } from '../engines/types.js'
+import { PROCESS_ENGINES } from '../engines/types.js'
import { ENGINE_INSTALL } from './engineInstall.js'
import { buildEngineLaunchArgv } from './engineLaunch.js'
@@ -23,7 +23,7 @@ const OFFICIAL_COMMANDS = {
describe('ENGINE_INSTALL', () => {
it('has one first-party recipe for every supported engine', () => {
- expect(Object.keys(ENGINE_INSTALL)).toEqual(ENGINES)
+ expect(Object.keys(ENGINE_INSTALL)).toEqual(PROCESS_ENGINES)
expect(Object.fromEntries(
Object.entries(ENGINE_INSTALL).map(([engine, recipe]) => [engine, recipe.command]),
)).toEqual(OFFICIAL_COMMANDS)
@@ -40,7 +40,7 @@ describe('ENGINE_INSTALL', () => {
})
it('generates valid POSIX pane scripts for every recipe', () => {
- for (const engine of ENGINES) {
+ for (const engine of PROCESS_ENGINES) {
const script = buildEngineLaunchArgv(
engine,
{ installIfMissing: ENGINE_INSTALL[engine] },
diff --git a/cli/src/lib/engineInstall.ts b/cli/src/lib/engineInstall.ts
index 116d4ccb7..42ca5f046 100644
--- a/cli/src/lib/engineInstall.ts
+++ b/cli/src/lib/engineInstall.ts
@@ -6,7 +6,7 @@
* installs successfully but does not provide the expected executable is worse than no recipe.
*/
-import type { AgentEngine } from '../engines/types.js'
+import { isTerminalEngine, type AgentEngine, type ProcessEngine } from '../engines/types.js'
/** How to find the executable after the installer returns. */
export interface EngineInstallExecutable {
@@ -33,7 +33,7 @@ export interface EngineInstallRecipe {
* Exhaustive on purpose. Adding an engine without deciding how it is installed must fail typecheck
* rather than silently creating another unsupported row in Desktop.
*/
-export const ENGINE_INSTALL: Readonly<Record<AgentEngine, EngineInstallRecipe>> = {
+export const ENGINE_INSTALL: Readonly<Record<ProcessEngine, EngineInstallRecipe>> = {
claude: {
command: 'npm install -g @anthropic-ai/claude-code',
source: 'https://docs.anthropic.com/en/docs/claude-code/getting-started',
@@ -118,8 +118,9 @@ export const ENGINE_INSTALL: Readonly<Record<AgentEngine, EngineInstallRecipe>>
},
}
-export function engineInstallRecipe(engine: AgentEngine): EngineInstallRecipe {
- return ENGINE_INSTALL[engine]
+/** A terminal has nothing to install — the login shell is already there — hence `undefined`. */
+export function engineInstallRecipe(engine: AgentEngine): EngineInstallRecipe | undefined {
+ return isTerminalEngine(engine) ? undefined : ENGINE_INSTALL[engine]
}
export const INSTALLABLE_ENGINES: ReadonlySet<AgentEngine> = new Set(
diff --git a/cli/src/lib/engineLaunch.spec.ts b/cli/src/lib/engineLaunch.spec.ts
index f7744529e..541957bd5 100644
--- a/cli/src/lib/engineLaunch.spec.ts
+++ b/cli/src/lib/engineLaunch.spec.ts
@@ -61,6 +61,46 @@ describe('buildEngineLaunchArgv', () => {
])
})
+ describe('a terminal (engine `terminal`)', () => {
+ it('is the login shell itself behind a non-interactive wrapper that only raises the limit and enters the folder', () => {
+ expect(buildEngineLaunchArgv('terminal', { cwd: '/work/project' }, '/bin/zsh')).toEqual([
+ '/bin/zsh', '-c',
+ `${RAISE_OPEN_FILES_SH}if ! cd -- "$1"; then printf '%s\\n' 'harness: the selected working directory is unavailable.' >&2; fi\nshift\nexec "$@"`,
+ 'harness-terminal', '/work/project', '/bin/zsh', '-l',
+ ])
+ })
+
+ it('gives bash no login flag (its rc file is where Ubuntu keeps PATH edits), and no folder means no cd', () => {
+ expect(buildEngineLaunchArgv('terminal', {}, '/bin/bash')).toEqual([
+ '/bin/bash', '-c', `${RAISE_OPEN_FILES_SH}shift\nexec "$@"`, 'harness-terminal', '', '/bin/bash',
+ ])
+ })
+
+ it('falls back to /bin/sh rather than to an engine command when no shell resolves', () => {
+ expect(buildEngineLaunchArgv('terminal', {}, 'relative-shell')).toEqual([
+ '/bin/sh', '-c', `${RAISE_OPEN_FILES_SH}shift\nexec "$@"`, 'harness-terminal', '', '/bin/sh',
+ ])
+ })
+
+ it('ignores every engine option: nothing to bypass, resume, prompt or install', () => {
+ const argv = buildEngineLaunchArgv('terminal', {
+ cwd: '/w', bypassPermission: true, resumeSessionId: 'abc', firstPrompt: 'hi', extraArgs: ['--x'],
+ }, '/bin/zsh')
+ expect(argv.slice(-2)).toEqual(['/bin/zsh', '-l'])
+ expect(argv.join(' ')).not.toContain('abc')
+ expect(argv.join(' ')).not.toContain('--x')
+ })
+
+ it('is a script a real shell accepts and that keeps a cd failure from ending the terminal', () => {
+ const script = buildEngineLaunchArgv('terminal', { cwd: '/nowhere/at/all' }, '/bin/sh')[2]
+ expect(() => execFileSync('/bin/sh', ['-n', '-c', script])).not.toThrow()
+ // The wrapper's `exec "$@"` runs the shell handed in argv; `true` in its place proves the
+ // wrapper reaches the exec even when the cd failed (the terminal still opens, at $HOME).
+ const out = execFileSync('/bin/sh', ['-c', script, 'harness-terminal', '/nowhere/at/all', '/bin/sh', '-c', 'echo reached'], { stdio: ['ignore', 'pipe', 'pipe'] })
+ expect(out.toString()).toContain('reached')
+ })
+ })
+
it('hands the engine a soft open-files limit fit for it, however low the pane started', async () => {
// A tmux server started by the desktop app passes launchd's 256 to every pane; Claude Code will
// not start under that. The pane's own shell lifts it before exec, so the server never has to.
diff --git a/cli/src/lib/engineLaunch.ts b/cli/src/lib/engineLaunch.ts
index fc974173f..9605b3896 100644
--- a/cli/src/lib/engineLaunch.ts
+++ b/cli/src/lib/engineLaunch.ts
@@ -1,7 +1,7 @@
import { execFile } from 'node:child_process'
import { homedir, userInfo } from 'node:os'
import { isAbsolute, basename, dirname, join } from 'node:path'
-import type { AgentEngine } from '../engines/types.js'
+import { isTerminalEngine, type AgentEngine } from '../engines/types.js'
import { binaryOnPath } from './binaryOnPath.js'
import { engineBin } from './engineBin.js'
import type { EngineInstallRecipe } from './engineInstall.js'
@@ -33,6 +33,8 @@ export const BYPASS_PERMISSION_FLAGS: Readonly<Record<AgentEngine, string[] | nu
grok: null,
agy: null,
copilot: null,
+ // A shell has no permissions to bypass.
+ terminal: null,
}
/**
@@ -104,6 +106,7 @@ export const FIRST_PROMPT_ARGS: Readonly<Record<AgentEngine, readonly string[] |
grok: null,
agy: null,
copilot: null,
+ terminal: null,
}
/** A first prompt is a message, not a document. Enforced at the wire (`agent_create`) before any pane
@@ -158,6 +161,7 @@ export const NAMED_AGENT_ARGS: Readonly<Record<AgentEngine, readonly string[] |
grok: null,
agy: null,
copilot: null,
+ terminal: null,
}
/** An agent name is an identifier the engine looks a file up by — never a path, never prose. */
@@ -361,6 +365,7 @@ export function buildEngineLaunchArgv(
runtimeNode: string = managedNodePath(),
gridBinary: string = gridBinaryPath(),
): string[] {
+ if (isTerminalEngine(engine)) return buildTerminalLaunchArgv(opts, shell)
const command = buildEngineCommandArgv(engine, opts)
const interactive = interactiveEngineShell(shell)
if (!interactive) return command
@@ -391,6 +396,31 @@ export function buildEngineLaunchArgv(
return [interactive.path, ...interactive.args, RAISE_OPEN_FILES_SH + prelude + cwdPrelude + body, 'harness-engine', ...(opts.cwd ? [opts.cwd] : []), ...command]
}
+/**
+ * Full argv for a plain terminal pane: the user's login shell, nothing exec'd over it.
+ *
+ * The outer `-c` shell is non-interactive on purpose — it loads no rc files, only raises the
+ * open-files limit (a `claude` typed into this terminal later would otherwise refuse under
+ * launchd's 256, exactly as a launched engine would) and enters the workspace — then `exec`s the
+ * interactive shell, which loads the user's startup files once, the way Terminal.app would. zsh
+ * gets `-l` so its login files run; bash reads .bashrc on an interactive non-login start, which is
+ * where Ubuntu keeps nvm and vendor PATH edits, so it gets no flag (same reasoning as
+ * `interactiveEngineShell`). Without a resolvable shell the pane runs `/bin/sh`, which at least
+ * gives the person a prompt.
+ */
+export function buildTerminalLaunchArgv(
+ opts: Pick<LaunchCommandOptions, 'cwd'> = {},
+ shell: string | undefined = undefined,
+): string[] {
+ const candidate = shell === undefined ? currentUserShell() : shell
+ const path = candidate && isAbsolute(candidate) ? candidate : '/bin/sh'
+ const loginArgs = basename(path).toLowerCase() === 'zsh' ? ['-l'] : []
+ const cwdPrelude = opts.cwd
+ ? `if ! cd -- "$1"; then printf '%s\\n' 'harness: the selected working directory is unavailable.' >&2; fi\n`
+ : ''
+ return [path, '-c', RAISE_OPEN_FILES_SH + cwdPrelude + 'shift\nexec "$@"', 'harness-terminal', opts.cwd ?? '', path, ...loginArgs]
+}
+
/**
* Refuse a workspace the shell could enter but cannot read, and say why — before the engine finds
* out on its own terms.
diff --git a/cli/src/lib/gridLaunch.ts b/cli/src/lib/gridLaunch.ts
index 4b92dec04..1ca1be3c3 100644
--- a/cli/src/lib/gridLaunch.ts
+++ b/cli/src/lib/gridLaunch.ts
@@ -892,6 +892,7 @@ const GRID_ENGINE_REFUSALS: Partial<Record<AgentEngine, string>> = {
devin: 'Devin runs on its own hosted service and documents no endpoint override',
muse: 'Muse Code documents no way to change its endpoint',
commandcode: 'Command Code documents no way to change its endpoint',
+ terminal: 'a terminal runs no engine to point at a grid — start one inside it and it will use its own login',
}
/** Engines that can be pointed at a grid today, for error text that names what to pick instead. */
diff --git a/cli/src/lib/harnessSessionLabel.ts b/cli/src/lib/harnessSessionLabel.ts
index bb3c0fc48..b7732eda2 100644
--- a/cli/src/lib/harnessSessionLabel.ts
+++ b/cli/src/lib/harnessSessionLabel.ts
@@ -16,3 +16,8 @@ export function buildHarnessSessionLabel(engine: string, now: number = Date.now(
export function isHarnessSession(sessionName: string): boolean {
return sessionName.startsWith(HARNESS_SESSION_PREFIX)
}
+
+/** Whether a harness session was created FOR this engine — `harness-<engine>-<ts>` — rather than another. */
+export function isHarnessSessionFor(sessionName: string, engine: string): boolean {
+ return sessionName.startsWith(`${HARNESS_SESSION_PREFIX}${engine}-`)
+}
diff --git a/cli/src/lib/registry.spec.ts b/cli/src/lib/registry.spec.ts
index b73606005..39e3d450a 100644
--- a/cli/src/lib/registry.spec.ts
+++ b/cli/src/lib/registry.spec.ts
@@ -1567,3 +1567,95 @@ describe('registry across a reboot and pane loss', () => {
expect(registry.list()).toHaveLength(1)
})
})
+
+describe('a terminal: a pane that becomes an engine and back', () => {
+ beforeEach(() => {
+ vi.useFakeTimers()
+ dataDir = mkdtempSync(join(tmpdir(), 'adapter-registry-terminal-'))
+ })
+
+ afterEach(() => {
+ vi.useRealTimers()
+ rmSync(dataDir, { recursive: true, force: true })
+ delete process.env.ADAPTER_DATA_DIR
+ delete process.env.CLAUDE_PROJECTS_DIR
+ delete process.env.CODEX_HOME
+ delete process.env.CURSOR_HOME
+ })
+
+ const pane = { backend: 'tmux' as const, paneId: '%9' }
+
+ it('opens as engine `terminal`, marked terminalHost, and survives a reload that way', async () => {
+ const { registry } = await loadRegistryModule()
+ registry.load()
+ const opened = registry.openPendingAgent({ engine: 'terminal', runtimes: [pane], cwd: '/tmp/work' })!
+ expect(opened).toMatchObject({ engine: 'terminal', terminalHost: true, sessionId: '', processIdentity: null })
+ expect(opened.defaultName).toMatch(/^Terminal /)
+ expect(registry.byRuntimeTerminal(pane)?.agentId).toBe(opened.agentId)
+
+ const { registry: reloaded } = await loadRegistryModule()
+ reloaded.load()
+ expect(reloaded.byAgent(opened.agentId)).toMatchObject({ engine: 'terminal', terminalHost: true })
+ })
+
+ it('adopts the engine started inside it — same agentId, process indexed under the engine — then a hook binds to it', async () => {
+ const transcriptPath = join(dataDir, 'session-t.jsonl')
+ writeFileSync(transcriptPath, '{}\n')
+ const { registry } = await loadRegistryModule()
+ registry.load()
+ const opened = registry.openPendingAgent({ engine: 'terminal', runtimes: [pane], cwd: '/tmp/work' })!
+
+ const adopted = registry.adoptEngine(opened.agentId, 'claude', processIdentity(909))!
+ expect(adopted.agentId).toBe(opened.agentId)
+ expect(adopted).toMatchObject({ engine: 'claude', terminalHost: true, launch: { state: 'ready' }, active: true })
+ expect(registry.byProcess('claude', processIdentity(909))?.agentId).toBe(opened.agentId)
+ expect(registry.byRuntimeTerminal(pane)).toBeUndefined()
+ expect(registry.byRuntimeEngine(pane, 'claude')?.agentId).toBe(opened.agentId)
+ // An agent already running an engine is never re-labelled.
+ expect(registry.adoptEngine(opened.agentId, 'codex', processIdentity(910))).toBeNull()
+
+ const bound = registry.register({ engine: 'claude', sessionId: 'session-t', transcriptPath, tmuxPane: '%9', processIdentity: processIdentity(909) })
+ expect(bound?.entry.agentId).toBe(opened.agentId)
+ expect(bound?.entry.terminalHost).toBe(true)
+ expect(registry.list()).toHaveLength(1)
+ })
+
+ it('a SessionStart hook that beats the reconciler adopts the terminal at its pane rather than minting nothing', async () => {
+ const transcriptPath = join(dataDir, 'session-h.jsonl')
+ writeFileSync(transcriptPath, '{}\n')
+ const { registry } = await loadRegistryModule()
+ registry.load()
+ const opened = registry.openPendingAgent({ engine: 'terminal', runtimes: [pane], cwd: '/tmp/work' })!
+ const bound = registry.register({ engine: 'claude', sessionId: 'session-h', transcriptPath, tmuxPane: '%9', processIdentity: processIdentity(911) })
+ expect(bound?.entry.agentId).toBe(opened.agentId)
+ expect(bound?.entry).toMatchObject({ engine: 'claude', terminalHost: true })
+ expect(registry.list()).toHaveLength(1)
+ })
+
+ it('releases the engine when it exits: a live terminal again, with nothing of the engine left on it', async () => {
+ const transcriptPath = join(dataDir, 'session-r.jsonl')
+ writeFileSync(transcriptPath, '{}\n')
+ const { registry } = await loadRegistryModule()
+ registry.load()
+ const opened = registry.openPendingAgent({ engine: 'terminal', runtimes: [pane], cwd: '/tmp/work' })!
+ registry.adoptEngine(opened.agentId, 'claude', processIdentity(912))
+ registry.register({ engine: 'claude', sessionId: 'session-r', transcriptPath, tmuxPane: '%9', processIdentity: processIdentity(912) })
+ registry.setBypassPermission(opened.agentId, true)
+
+ const released = registry.releaseEngine(opened.agentId)!
+ expect(released.agentId).toBe(opened.agentId)
+ expect(released).toMatchObject({ engine: 'terminal', terminalHost: true, active: true, launch: { state: 'ready' }, sessionId: '', processIdentity: null, transcriptPath: null })
+ expect(released.bypassPermission).toBeUndefined()
+ expect(registry.bySession('session-r')).toBeUndefined()
+ expect(registry.byProcess('claude', processIdentity(912))).toBeUndefined()
+ expect(registry.byRuntimeTerminal(pane)?.agentId).toBe(opened.agentId)
+ expect(registry.terminalAvailable(opened.agentId)).toBe(true)
+ // Not a terminal any more? Nothing to release. A plain agent? Never.
+ expect(registry.releaseEngine(opened.agentId)).toBeNull()
+ const plain = registry.openPendingAgent({ engine: 'codex', runtimes: [{ backend: 'tmux', paneId: '%10' }], cwd: '/tmp/x' })!
+ expect(registry.releaseEngine(plain.agentId)).toBeNull()
+
+ // And the next engine typed into the same shell is adopted just the same.
+ expect(registry.adoptEngine(opened.agentId, 'codex', processIdentity(913))).toMatchObject({ engine: 'codex' })
+ })
+})
diff --git a/cli/src/lib/registry.ts b/cli/src/lib/registry.ts
index bd4d0daa5..c08878bb5 100644
--- a/cli/src/lib/registry.ts
+++ b/cli/src/lib/registry.ts
@@ -38,7 +38,7 @@ import { join, basename, dirname, relative } from 'path'
import { hostname, uptime } from 'os'
import { env } from '../config/env.js'
import { readCodexRolloutMeta, resolveCodexRollout } from '../engines/codex/rollout.js'
-import { ENGINES, type AgentEngine } from '../engines/types.js'
+import { ENGINES, isTerminalEngine, type AgentEngine } from '../engines/types.js'
import type { GridAssignment } from './gridAssignment.js'
import { parseGridLaunchOverride, type GridLaunchOverride, type GridLaunchRecord, type GridWebSearchStatus } from './gridLaunch.js'
import { commandcodeTranscriptPath } from '../engines/commandcode/transcript.js'
@@ -169,6 +169,14 @@ export interface RegisteredSession {
* existed and on agents Harness did not launch; those relaunch from `bypassPermission`.
*/
permissionMode?: string
+ /**
+ * The pane was opened as a terminal (engine `terminal`, the desktop's New Terminal) rather than
+ * for an engine. Set once at creation and kept for the row's whole life, whichever engine is
+ * running in it now: this is what tells the reconciler that an engine exiting means "back to a
+ * shell" (`releaseEngine`) rather than "dormant", and what tells `restoreAgents` to bring back
+ * a shell rather than a `claude`. Not a type — `engine` still says what the pane IS right now.
+ */
+ terminalHost?: boolean
/** Legacy launcher-owned snapshots may still contain this field. New records never write it. */
launcherId?: string
transcriptPath: string | null
@@ -473,6 +481,7 @@ function strictPersistedRow(value: unknown): RegisteredSession | null {
model: modelString(row.model),
cliVersion: typeof row.cliVersion === 'string' ? row.cliVersion : null,
processIdentity: row.processIdentity ?? null,
+ ...(row.terminalHost === true || row.engine === 'terminal' ? { terminalHost: true } : {}),
registeredAt: typeof row.registeredAt === 'number' ? row.registeredAt : Date.now(),
updatedAt: typeof row.updatedAt === 'number' ? row.updatedAt : Date.now(),
lastHookAt: typeof row.lastHookAt === 'number' ? row.lastHookAt : Date.now(),
@@ -854,6 +863,7 @@ class Registry {
: {}),
...(raw.bypassPermission === true ? { bypassPermission: true } : {}),
...(permissionModeName(raw.permissionMode) ? { permissionMode: raw.permissionMode } : {}),
+ ...(raw.terminalHost === true || engine === 'terminal' ? { terminalHost: true } : {}),
transcriptPath,
defaultName: normalizedDefaultName(raw.defaultName),
title: titleDisplayName(typeof raw.title === 'string' ? raw.title : null),
@@ -1111,6 +1121,7 @@ class Registry {
agent: normalizedAgentName(input.agent),
...(input.bypassPermission ? { bypassPermission: true } : {}),
...(permissionModeName(input.permissionMode) ? { permissionMode: input.permissionMode } : {}),
+ ...(isTerminalEngine(input.engine) ? { terminalHost: true } : {}),
transcriptPath: null,
projectDir: basename(input.cwd ?? '') || agentId,
cwd: input.cwd ?? null,
@@ -1194,6 +1205,14 @@ class Registry {
? this.byProcess(engine, input.processIdentity)
: undefined)
?? inputRuntimes.map((runtime) => this.byRuntimeEngine(runtime, engine)).find(Boolean)
+ // An engine started by hand inside a terminal, whose SessionStart hook beat the reconciler to
+ // it: the terminal at that route is the agent, and it becomes this engine's here and now —
+ // the same flip the reconciler would make a scan later (cli.ts `onObserved`).
+ ?? (isTerminalEngine(engine) ? undefined : inputRuntimes
+ .map((runtime) => this.byRuntimeTerminal(runtime))
+ .filter((agent): agent is RegisteredSession => !!agent)
+ .map((agent) => this.adoptEngine(agent.agentId, engine, validProcessIdentity(input.processIdentity) ? input.processIdentity : null))
+ .find((agent): agent is RegisteredSession => !!agent))
const agentId = processAgent?.agentId ?? ''
if (
!sessionId
@@ -1303,6 +1322,7 @@ class Registry {
agent: existing?.agent ?? null,
...(existing?.bypassPermission ? { bypassPermission: true } : {}),
...(existing?.permissionMode ? { permissionMode: existing.permissionMode } : {}),
+ ...(existing?.terminalHost ? { terminalHost: true } : {}),
processIdentity: validProcessIdentity(input.processIdentity) ? input.processIdentity : existing?.processIdentity ?? null,
registeredAt: existing?.registeredAt ?? now,
updatedAt: now,
@@ -1374,6 +1394,72 @@ class Registry {
return agentId ? this.agents.get(agentId) : undefined
}
+ /** The terminal (engine `terminal`, nobody running in it yet) that owns this route, if that is what owns it. */
+ byRuntimeTerminal(runtime: TerminalRuntimeRef): RegisteredSession | undefined {
+ return this.byRuntimeEngine(runtime, 'terminal')
+ }
+
+ /**
+ * An engine CLI was started inside a terminal: the row becomes that engine's agent, in place.
+ *
+ * Same agentId, same pane, same tile — the desktop only sees `engine` change on the next
+ * `agent_synced`. The process identity is indexed under the NEW engine (the key is engine-scoped),
+ * which is what lets the hook that follows (`register`, `byProcess(engine, …)`) land on this row
+ * rather than mint another. `terminalHost` stays set so the exit is recognised (`releaseEngine`).
+ * Refused for anything but a terminal: an agent already running one engine is never re-labelled.
+ */
+ adoptEngine(agentId: string, engine: AgentEngine, processIdentity?: ProcessIdentity | null): RegisteredSession | null {
+ const entry = this.agents.get(agentId)
+ if (!entry || !isTerminalEngine(entry.engine) || isTerminalEngine(engine)) return null
+ this.drop(entry)
+ entry.engine = engine
+ entry.terminalHost = true
+ entry.launch = { state: 'ready' }
+ entry.active = true
+ if (validProcessIdentity(processIdentity)) entry.processIdentity = processIdentity
+ entry.updatedAt = Date.now()
+ this.index(entry)
+ this.terminalAvailableAgents.add(entry.agentId)
+ this.save()
+ return entry
+ }
+
+ /**
+ * The engine that was started inside a terminal has exited: the row is a terminal again.
+ *
+ * Everything that belonged to the engine goes — session, transcript, process, grid, profile,
+ * model, permission choices — 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. The row itself,
+ * its id, its pane and its name stay: this is the opposite of dormant, the terminal is live.
+ */
+ releaseEngine(agentId: string): RegisteredSession | null {
+ const entry = this.agents.get(agentId)
+ if (!entry || !entry.terminalHost || isTerminalEngine(entry.engine)) return null
+ this.drop(entry)
+ this.releaseBinding(entry)
+ entry.engine = 'terminal'
+ entry.processIdentity = null
+ entry.launch = { state: 'ready' }
+ entry.active = true
+ entry.gateway = null
+ entry.grid = null
+ entry.gridLaunch = null
+ entry.gridWebSearch = null
+ entry.subscriptionModel = null
+ entry.codexHome = null
+ entry.dsh = null
+ entry.agent = null
+ entry.model = null
+ entry.title = null
+ delete entry.bypassPermission
+ delete entry.permissionMode
+ entry.updatedAt = Date.now()
+ this.index(entry)
+ this.terminalAvailableAgents.add(entry.agentId)
+ this.save()
+ return entry
+ }
+
updateRuntimes(agentId: string, runtimes: readonly TerminalRuntimeRef[], primaryRuntimeKey?: string): boolean {
const entry = this.agents.get(agentId)
const normalized = normalizedRuntimes(runtimes)
diff --git a/cli/src/lib/restoreAgents.spec.ts b/cli/src/lib/restoreAgents.spec.ts
index 5a1bee982..892295600 100644
--- a/cli/src/lib/restoreAgents.spec.ts
+++ b/cli/src/lib/restoreAgents.spec.ts
@@ -58,7 +58,7 @@ interface Harness {
released: string[]
}
-function harness(rows: RegisteredSession[], opts: { livePanes?: string[]; failCreate?: boolean; refuseLaunch?: boolean; budgetMs?: number; settleMs?: number } = {}): Harness {
+function harness(rows: RegisteredSession[], opts: { livePanes?: string[]; liveTerminalPanes?: string[]; failCreate?: boolean; refuseLaunch?: boolean; budgetMs?: number; settleMs?: number } = {}): Harness {
const h: Harness = {
calls: [],
rows: new Map(rows.map((r) => [r.agentId, r])),
@@ -98,7 +98,14 @@ function harness(rows: RegisteredSession[], opts: { livePanes?: string[]; failCr
updateProcessIdentity: (id, pi) => { note(`updateIdentity:${id}:${pi.pid}`); const r = h.rows.get(id); if (r) r.processIdentity = pi; return !!r },
unbindSession: (sid) => { note(`unbind:${sid}`); return true },
inheritName: (from, to) => { note(`inheritName:${from}->${to}`) },
+ releaseEngine: (id) => {
+ note(`releaseEngine:${id}`)
+ const r = h.rows.get(id); if (!r || !r.terminalHost) return null
+ r.engine = 'terminal'; r.sessionId = ''; r.processIdentity = null; r.launch = { state: 'ready' }; r.active = true
+ return r
+ },
},
+ liveTerminalPane: async (runtime) => (opts.liveTerminalPanes ?? []).includes(runtime.paneId),
liveProcess: async (_entry, runtime) => live.has(runtime.paneId) ? identity(1000 + Number(runtime.paneId.slice(1))) : null,
buildLaunch: async (entry, o) => {
h.launches.push({ agentId: entry.agentId, ...(o.resumeSessionId ? { resumeSessionId: o.resumeSessionId } : {}) })
@@ -376,3 +383,57 @@ describe('restoreAgents — waiting for the engine', () => {
expect(h.calls.filter((c) => c.startsWith('setLaunch:agent-a:failed'))).toEqual([])
})
})
+
+describe('restoreAgents — terminals', () => {
+ const terminal = (overrides: Partial<RegisteredSession> = {}) =>
+ row({ agentId: 'term-1', engine: 'terminal', terminalHost: true, sessionId: '', boundAt: null, ...overrides })
+
+ it('leaves a terminal whose pane is still there alone — a shell has no engine process to look for', async () => {
+ const h = harness([terminal()], { liveTerminalPanes: ['%3'] })
+ const summary = await restoreAgents(h.deps)
+ expect(summary).toEqual({ restored: [], skipped: [], failed: [] })
+ expect(h.paneCreates).toBe(0)
+ expect(h.calls).toEqual([])
+ })
+
+ it('recreates a terminal whose pane is gone as a ready shell: no hold, no engine watch', async () => {
+ const h = harness([terminal()])
+ const summary = await restoreAgents(h.deps)
+ expect(summary).toEqual({ restored: ['term-1'], skipped: [], failed: [] })
+ expect(h.launches).toEqual([{ agentId: 'term-1' }])
+ expect(h.calls).toEqual([
+ 'clearIdentity:term-1@tx',
+ 'createPane:term-1@tx',
+ 'updateRuntimes:term-1:%0@tx',
+ 'setLaunch:term-1:ready@tx',
+ 'clearRemainOnExit:%0@tx',
+ ])
+ expect(h.rows.get('term-1')?.launch).toEqual({ state: 'ready' })
+ })
+
+ it('puts a terminal whose adopted engine exited while the daemon was down back to a shell, pane kept', async () => {
+ const h = harness([terminal({ engine: 'claude', sessionId: 'session-t', boundAt: 1, processIdentity: identity(7) })], { liveTerminalPanes: ['%3'] })
+ const summary = await restoreAgents(h.deps)
+ expect(summary).toEqual({ restored: [], skipped: [], failed: [] })
+ expect(h.calls).toEqual(['releaseEngine:term-1'])
+ expect(h.rows.get('term-1')).toMatchObject({ engine: 'terminal', sessionId: '' })
+ })
+
+ it('keeps a terminal whose adopted engine is still running exactly as an agent', async () => {
+ const h = harness([terminal({ engine: 'claude', sessionId: 'session-t', boundAt: 1 })], { liveTerminalPanes: ['%3'], livePanes: ['%3'] })
+ const summary = await restoreAgents(h.deps)
+ expect(summary).toEqual({ restored: [], skipped: [], failed: [] })
+ expect(h.calls).toEqual(['updateIdentity:term-1:1003'])
+ expect(h.rows.get('term-1')?.engine).toBe('claude')
+ })
+
+ it('brings a terminal whose adopted engine AND pane are gone back as a shell, never as the engine', async () => {
+ const h = harness([terminal({ engine: 'claude', sessionId: 'session-t', boundAt: 1 })])
+ const summary = await restoreAgents(h.deps)
+ expect(summary).toEqual({ restored: ['term-1'], skipped: [], failed: [] })
+ expect(h.calls[0]).toBe('releaseEngine:term-1')
+ expect(h.launches).toEqual([{ agentId: 'term-1' }])
+ expect(h.launched[0].launch.argv[0]).toBe('terminal')
+ expect(h.rows.get('term-1')).toMatchObject({ engine: 'terminal', launch: { state: 'ready' } })
+ })
+})
diff --git a/cli/src/lib/restoreAgents.ts b/cli/src/lib/restoreAgents.ts
index 988828204..575315bac 100644
--- a/cli/src/lib/restoreAgents.ts
+++ b/cli/src/lib/restoreAgents.ts
@@ -27,7 +27,7 @@
* spend the wrong account while looking identical — and is marked so the app can say why.
*/
-import type { AgentEngine } from '../engines/types.js'
+import { isTerminalEngine, type AgentEngine } from '../engines/types.js'
import type { AgentLaunch, ProcessIdentity, RegisteredSession } from './registry.js'
import type { TerminalRuntimeRef, TmuxRuntimeRef } from './terminalTypes.js'
import { terminalRouteKey } from './terminalRuntime.js'
@@ -53,7 +53,16 @@ export interface RestoreAgentsDeps {
updateProcessIdentity(agentId: string, processIdentity: ProcessIdentity): boolean
unbindSession(sessionId: string): boolean
inheritName(fromSessionId: string, toSessionId: string): void
+ /** A terminal's adopted engine is gone: back to a shell (registry.ts). */
+ releaseEngine(agentId: string): RegisteredSession | null
}
+ /**
+ * Whether a TERMINAL's pane is still there — a live pane in a session this daemon named for a
+ * terminal. A terminal has no engine process to find (`liveProcess` answers null for one by
+ * construction), so pane existence is its liveness. Optional so a caller without tmux inventory
+ * (tests) treats every terminal pane as gone.
+ */
+ liveTerminalPane?: (runtime: TmuxRuntimeRef) => Promise<boolean>
/** The engine process still running in this row's pane, or null when tmux does not know the pane
* at all — including when no tmux server is running — or the pane has become something else. */
liveProcess: (entry: RegisteredSession, runtime: TmuxRuntimeRef) => Promise<ProcessIdentity | null>
@@ -131,6 +140,27 @@ export async function restoreAgents(deps: RestoreAgentsDeps): Promise<RestoreSum
const runtime = tmuxRuntime(entry)
if (!runtime) { summary.skipped.push({ agentId: entry.agentId, reason: 'no tmux pane' }); continue }
if (entry.launch?.state === 'failed') { summary.skipped.push({ agentId: entry.agentId, reason: 'last launch failed' }); continue }
+ // A terminal — bare, or one that adopted an engine — is alive as long as its PANE is: the shell
+ // is what the person opened, and it survives whatever was typed into it. An adopted engine that
+ // exited while the daemon was down is exactly the exit the reconciler would have caught, so the
+ // row is put back to a terminal here; a pane that is gone comes back below as a terminal, too,
+ // never as the engine (its session is gone with the pane).
+ if (entry.terminalHost) {
+ const paneAlive = await deps.liveTerminalPane?.(runtime) ?? false
+ if (paneAlive) {
+ const engineLive = isTerminalEngine(entry.engine) ? null : await deps.liveProcess(entry, runtime)
+ if (engineLive) {
+ if (!entry.processIdentity) deps.registry.updateProcessIdentity(entry.agentId, engineLive)
+ } else if (!isTerminalEngine(entry.engine)) {
+ deps.registry.releaseEngine(entry.agentId)
+ deps.log(`[restore] ${entry.engine} → terminal · agent ${entry.agentId} · its engine exited while the daemon was down`)
+ }
+ continue
+ }
+ if (!isTerminalEngine(entry.engine)) deps.registry.releaseEngine(entry.agentId)
+ missing.push({ entry: deps.registry.byAgent(entry.agentId) ?? entry, runtime })
+ continue
+ }
const live = await deps.liveProcess(entry, runtime)
if (live) {
// Still running. A row that lost its identity without losing its pane (a reboot the boot
@@ -181,6 +211,15 @@ export async function restoreAgents(deps: RestoreAgentsDeps): Promise<RestoreSum
continue
}
const key = terminalRouteKey(created.runtime)
+ // A terminal is up the moment its pane is — no engine to wait for, no route to hold.
+ if (isTerminalEngine(entry.engine)) {
+ deps.registry.updateRuntimes(entry.agentId, [created.runtime], key)
+ deps.registry.setLaunch(entry.agentId, { state: 'ready' })
+ await deps.clearRemainOnExit(created.runtime)
+ summary.restored.push(entry.agentId)
+ deps.log(`[restore] terminal · agent ${entry.agentId} · pane ${dead.paneId} → ${created.runtime.paneId}`)
+ continue
+ }
deps.holdRoute(key, budgetMs + HOLD_SLACK_MS)
deps.registry.updateRuntimes(entry.agentId, [created.runtime], key)
deps.registry.setLaunch(entry.agentId, { state: 'starting' })
diff --git a/cli/src/lib/summarize.ts b/cli/src/lib/summarize.ts
index 1d3494c36..ab7494722 100644
--- a/cli/src/lib/summarize.ts
+++ b/cli/src/lib/summarize.ts
@@ -71,7 +71,8 @@ export function syncSummaryPoolSessions(sessions: Array<{ engine: AgentEngine }>
// Hermes, Devin, Muse and Amp take their recap prompt as argv (`muse exec <prompt>`, `amp -x <prompt>`),
// so they cannot be pre-warmed the way a stdin-fed CLI can — no pooled worker for them.
if (session.engine === 'hermes' || session.engine === 'devin' || session.engine === 'muse'
- || session.engine === 'amp' || session.engine === 'grok' || session.engine === 'agy' || session.engine === 'copilot') continue
+ || session.engine === 'amp' || session.engine === 'grok' || session.engine === 'agy' || session.engine === 'copilot'
+ || session.engine === 'terminal') continue
counts[session.engine]++
}
setOneShotPoolActiveCounts(counts)
diff --git a/cli/src/lib/terminalAgentDiscovery.ts b/cli/src/lib/terminalAgentDiscovery.ts
index c8433784a..2317b35fd 100644
--- a/cli/src/lib/terminalAgentDiscovery.ts
+++ b/cli/src/lib/terminalAgentDiscovery.ts
@@ -2,7 +2,7 @@ import type { AgentEngine } from '../engines/types.js'
import {
agentAliasOwner,
agentCommandOwnershipSnapshot,
- ENGINES,
+ PROCESS_ENGINES,
type AgentCommandOwnershipSnapshot,
} from './engineBin.js'
import { probeGatewayRuntime } from './gatewayRuntime.js'
@@ -125,7 +125,7 @@ function rootOwner(
const current = queue.shift()!
const row = byPid.get(current.pid)
if (row && !excluded.has(row.pid)) {
- for (const engine of ENGINES) {
+ for (const engine of PROCESS_ENGINES) {
const score = engineProcessMatchScore(row, engine, ownership)
if (score > 0) matches.push({ row, engine, depth: current.depth, score })
}
diff --git a/cli/src/lib/terminalAgentReconciler.spec.ts b/cli/src/lib/terminalAgentReconciler.spec.ts
index f16776a49..19a5fcf77 100644
--- a/cli/src/lib/terminalAgentReconciler.spec.ts
+++ b/cli/src/lib/terminalAgentReconciler.spec.ts
@@ -403,3 +403,71 @@ describe('verified process adoption', () => {
expect(onDiscovered).toHaveBeenCalledOnce()
})
})
+
+describe('a terminal pane (engine `terminal`)', () => {
+ const live = [{ instanceId: 'tmux:default', result: { state: 'available' as const, roots: [{ runtime: tmux, rootPid: 1, cwd: '/work' }] } }]
+ function terminal(overrides: Partial<RegisteredSession> = {}): RegisteredSession {
+ return { ...session([tmux]), engine: 'terminal', terminalHost: true, processIdentity: null, ...overrides }
+ }
+
+ it('is never marked dormant for having no engine process — a shell at its prompt is the normal state', async () => {
+ const current = terminal()
+ const onDormant = vi.fn()
+ const onRemoved = vi.fn()
+ const reconciler = new TerminalAgentReconciler({
+ current: () => [current], backends: [], backendOrder: ['tmux'], herdrSessionOrder: [],
+ onDiscovered: vi.fn(), onObserved: vi.fn(), onDormant, onRemoved,
+ probe: async () => probe(live),
+ })
+ for (let i = 0; i < 4; i++) await reconciler.trigger()
+ expect(onDormant).not.toHaveBeenCalled()
+ expect(onRemoved).not.toHaveBeenCalled()
+ })
+
+ it('owns an engine process that appears in its pane: observed for THIS row, never discovered as a new agent', async () => {
+ const current = terminal()
+ const onDiscovered = vi.fn()
+ const onObserved = vi.fn()
+ const claude = observed([tmux])
+ const reconciler = new TerminalAgentReconciler({
+ current: () => [current], backends: [], backendOrder: ['tmux'], herdrSessionOrder: [],
+ onDiscovered, onObserved, onDormant: vi.fn(), onRemoved: vi.fn(),
+ probe: async () => probe(live, [claude]),
+ })
+ await reconciler.trigger()
+ expect(onDiscovered).not.toHaveBeenCalled()
+ expect(onObserved).toHaveBeenCalledTimes(1)
+ expect(onObserved.mock.calls[0][1]).toBe(current)
+ expect(onObserved.mock.calls[0][0]).toMatchObject({ engine: 'claude', processIdentity: identity })
+ })
+
+ it('reports the adopted engine dormant when it exits and the pane lives on (the handler turns it back into a terminal)', async () => {
+ const current = terminal({ engine: 'claude', processIdentity: identity })
+ const onDormant = vi.fn()
+ const onRemoved = vi.fn()
+ const reconciler = new TerminalAgentReconciler({
+ current: () => [current], backends: [], backendOrder: ['tmux'], herdrSessionOrder: [],
+ onDiscovered: vi.fn(), onObserved: vi.fn(), onDormant, onRemoved,
+ probe: async () => probe(live),
+ })
+ await reconciler.trigger()
+ expect(onDormant).not.toHaveBeenCalled()
+ await reconciler.trigger()
+ expect(onDormant).toHaveBeenCalledWith(current, 'engine process absent after 2 confirmed scans')
+ expect(onRemoved).not.toHaveBeenCalled()
+ })
+
+ it('is removed like any agent once its pane is gone — the shell exited', async () => {
+ const current = terminal()
+ const onRemoved = vi.fn()
+ const reconciler = new TerminalAgentReconciler({
+ current: () => [current], backends: [], backendOrder: ['tmux'], herdrSessionOrder: [],
+ onDiscovered: vi.fn(), onObserved: vi.fn(), onDormant: vi.fn(), onRemoved,
+ probe: async () => probe([{ instanceId: 'tmux:default', result: { state: 'available', roots: [] } }]),
+ })
+ await reconciler.trigger()
+ expect(onRemoved).not.toHaveBeenCalled()
+ await reconciler.trigger()
+ expect(onRemoved).toHaveBeenCalledWith(current, 'terminal runtime absent after 2 confirmed scans')
+ })
+})
diff --git a/cli/src/lib/terminalAgentReconciler.ts b/cli/src/lib/terminalAgentReconciler.ts
index 3ed22deff..e1190082c 100644
--- a/cli/src/lib/terminalAgentReconciler.ts
+++ b/cli/src/lib/terminalAgentReconciler.ts
@@ -1,4 +1,4 @@
-import type { AgentEngine } from '../engines/types.js'
+import { isTerminalEngine, type AgentEngine } from '../engines/types.js'
import type { RegisteredSession } from './registry.js'
import {
probeTerminalAgents,
@@ -48,13 +48,23 @@ function sharesPlacement(
* a first-run prompt (Claude folder trust is the common case). Once a session binds, process identity is
* authoritative again so a different process in the same pane cannot inherit an existing transcript.
*/
+/**
+ * Whether a row may own an observed engine process at its own route. The same engine, or a
+ * terminal — a shell somebody typed `claude` into: the process is what the terminal is running now,
+ * and the row adopts the engine (cli.ts `onObserved` → `registry.adoptEngine`) rather than a second
+ * agent being minted for the same pane.
+ */
+function routeEngineMatches(current: Pick<RegisteredSession, 'engine'>, observed: Pick<DiscoveredTerminalAgent, 'engine'>): boolean {
+ return current.engine === observed.engine || isTerminalEngine(current.engine)
+}
+
function unboundRouteOwner(
current: readonly RegisteredSession[],
observed: DiscoveredTerminalAgent,
): RegisteredSession | undefined {
const matches = current.filter((candidate) => (
!candidate.sessionId
- && candidate.engine === observed.engine
+ && routeEngineMatches(candidate, observed)
&& sharesPlacement(candidate, observed)
))
return matches.length === 1 ? matches[0] : undefined
@@ -66,7 +76,7 @@ function unboundRouteObservation(
): DiscoveredTerminalAgent | undefined {
if (current.sessionId) return undefined
const matches = observed.filter((candidate) => (
- candidate.engine === current.engine && sharesPlacement(current, candidate)
+ routeEngineMatches(current, candidate) && sharesPlacement(current, candidate)
))
return matches.length === 1 ? matches[0] : undefined
}
@@ -304,8 +314,13 @@ export class TerminalAgentReconciler {
if (terminalVerified) await this.deps.onTerminalAvailability?.(current, true)
if (observed) {
this.engineMisses.delete(current.agentId)
- } else if (current.active && terminalVerified && !current.runtimes.some((runtime) =>
+ } else if (current.active && terminalVerified && !isTerminalEngine(current.engine) && !current.runtimes.some((runtime) =>
probe.ambiguousPlacements.has(terminalPlacementKey(runtime)))) {
+ // A live pane with no engine process in it. For an agent that is a dormant engine; for a
+ // terminal (`engine === 'terminal'`) it is simply a shell at its prompt, which is why the
+ // branch is skipped for one. A terminal that ADOPTED an engine (`terminalHost`, engine no
+ // longer `terminal`) does come through here when that engine exits — the handler turns it
+ // back into a terminal rather than marking it dormant (cli.ts `onDormant`).
const misses = (this.engineMisses.get(current.agentId) ?? 0) + 1
if (misses >= MISS_LIMIT) {
this.engineMisses.delete(current.agentId)
diff --git a/cli/src/lib/tmux.spec.ts b/cli/src/lib/tmux.spec.ts
index cb1072663..576d5caf9 100644
--- a/cli/src/lib/tmux.spec.ts
+++ b/cli/src/lib/tmux.spec.ts
@@ -2,7 +2,7 @@ import { chmodSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'nod
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { describe, expect, it, vi } from 'vitest'
-import { ENGINES } from '../engines/types.js'
+import { PROCESS_ENGINES } from '../engines/types.js'
import type { AgentCommandOwnershipSnapshot } from './engineBin.js'
import {
ambiguousAgentProcess,
@@ -168,7 +168,7 @@ describe('tmux process primitives', () => {
expect(engineProcessMatchScore(row, 'claude', commands)).toBe(0)
})
- it.each(ENGINES)('recognises a renamed native %s image from installed file identity', (engine) => {
+ it.each(PROCESS_ENGINES)('recognises a renamed native %s image from installed file identity', (engine) => {
const key = `native-${engine}`
const commands: AgentCommandOwnershipSnapshot = {
...ownership(),
diff --git a/cli/src/lib/tmux.ts b/cli/src/lib/tmux.ts
index e8ed7709e..5145f3686 100644
--- a/cli/src/lib/tmux.ts
+++ b/cli/src/lib/tmux.ts
@@ -391,6 +391,9 @@ export const ENGINE_PROCESS_SIGNATURES: Readonly<Record<RegisteredSession['engin
basenames: [/^copilot$/],
entrypoints: [/@github[\/\\]copilot[\/\\](?:npm-loader\.js|index\.js|bin[\/\\]copilot)$/],
},
+ // A terminal is a shell, and a shell is what every pane starts as — so nothing matches it, ever.
+ // Discovery walks PROCESS_ENGINES and never asks; this entry exists for the Record's sake.
+ terminal: { basenames: [], entrypoints: [] },
}
function heuristicEngineProcessMatchScore(
diff --git a/cli/src/lib/tmuxAgentDiscovery.ts b/cli/src/lib/tmuxAgentDiscovery.ts
index e53029e00..3e7ff73c4 100644
--- a/cli/src/lib/tmuxAgentDiscovery.ts
+++ b/cli/src/lib/tmuxAgentDiscovery.ts
@@ -10,7 +10,7 @@ import { execFile } from 'node:child_process'
import {
agentAliasOwner,
agentCommandOwnershipSnapshot,
- ENGINES,
+ PROCESS_ENGINES,
type AgentCommandOwnershipSnapshot,
} from './engineBin.js'
import type { AgentEngine } from '../engines/types.js'
@@ -177,7 +177,7 @@ function paneOwner(
const current = queue.shift()!
const row = byPid.get(current.pid)
if (row && !excluded.has(row.pid)) {
- for (const engine of ENGINES) {
+ for (const engine of PROCESS_ENGINES) {
const score = engineProcessMatchScore(row, engine, ownership)
if (score > 0) matches.push({ row, engine, depth: current.depth, score })
}