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.

refactor: standardize engine process identification using centralized signatures and improved tree-based PID filtering

0xken15ebf1431a560f
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index 781f34233..54698729c 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -20,7 +20,7 @@ import { join, resolve } from 'path'
import { fileURLToPath } from 'url'
import { spawn } from 'child_process'
import { createServer } from 'http'
-import { createInterface } from 'readline'
+import { createInterface, emitKeypressEvents } from 'readline'
import { homedir, hostname } from 'os'
import { env } from './config/env.js'
import { VERSION } from './version.js'
@@ -228,12 +228,12 @@ Browser end-to-end encryption:
Machine-to-machine linking (lets this machine's relay reach ANOTHER of your machines with the CLI,
not the app, terminating E2EE). A machine's remote password is persistent — set once, reused for
every future connect, until you change or clear it:
- harness remote-password set set/rotate this machine's persistent remote password
- harness remote-password status show whether one is set, and its fingerprint
- harness remote-password clear remove this machine's remote password
- harness link connect <machineId> join a machine using ITS remote password (fully automatic)
- harness link list list machines this one has linked
- harness link unlink <id> remove a linked machine's trust
+ harness remote-password set set/rotate this machine's persistent remote password
+ harness remote-password status show whether one is set, and its fingerprint
+ harness remote-password clear remove this machine's remote password
+ harness link connect <id> join a machine using ITS remote password (fully automatic)
+ harness link list list machines this one has linked
+ harness link unlink <id> remove a linked machine's trust
(both \`remote-password set\` and \`link connect\` prompt for the password interactively, or read one
line from stdin with --stdin; add --json for NDJSON output instead of the human-readable text)
@@ -3590,30 +3590,50 @@ function readStdinLine(): Promise<string> {
})
}
-/** Prompt on stdin with the terminal echo suppressed, for a remote password. Falls back to a plain
- * (echoed) prompt when stdin isn't a TTY (piped input, non-interactive shell) — there's no terminal
- * to suppress echo on, and readline still works correctly for a single piped line. */
+/** Prompt on stdin with masked input (echoes `*` per keystroke), for a remote password. Reads
+ * keypress-by-keypress via the PUBLIC `readline.emitKeypressEvents` + `stdin.setRawMode` APIs rather
+ * than driving a `readline.Interface` and fighting its own internal line-redraw logic through a
+ * private `_writeToOutput` hook: with both stdio streams as TTYs, `readline.Interface` runs in
+ * `terminal: true` mode, so every keystroke (and `question()`'s own setup) re-triggers an internal
+ * `_refreshLine()` redraw that clears and rewrites the current line through that same hook — which,
+ * if muted to suppress echo, wipes out a manually-written prompt before the user ever sees it and
+ * leaves nothing on screen at all. Owning the raw keystrokes here means nothing else is redrawing the
+ * line. Falls back to a plain (unmasked) single-line read when stdin isn't a TTY — there's no
+ * terminal to suppress echo on regardless; `--stdin` is the supported path for scripted/GUI callers,
+ * this only guards a caller that piped input without passing it. */
function promptPassword(prompt: string): Promise<string> {
+ if (!process.stdin.isTTY) {
+ process.stdout.write(prompt)
+ return readStdinLine().then((line) => { process.stdout.write('\n'); return line })
+ }
return new Promise((resolve) => {
- if (!process.stdin.isTTY) {
- const rl = createInterface({ input: process.stdin, output: process.stdout })
- rl.question(prompt, (answer) => { rl.close(); resolve(answer) })
- return
- }
- const rl = createInterface({ input: process.stdin, output: process.stdout })
- // Suppress readline's own echo of typed characters while still letting our prompt text and the
- // trailing newline through — the standard Node trick for masked input without an extra dependency.
- const rlWithOutput = rl as unknown as { _writeToOutput?: (s: string) => void }
- let muted = false
- rlWithOutput._writeToOutput = (s: string) => { if (!muted) process.stdout.write(s) }
process.stdout.write(prompt)
- muted = true
- rl.question('', (answer) => {
- muted = false
- rl.close()
- process.stdout.write('\n')
- resolve(answer)
- })
+ const stdin = process.stdin
+ emitKeypressEvents(stdin)
+ stdin.setRawMode(true)
+ stdin.resume()
+ let value = ''
+ const cleanup = (): void => {
+ stdin.removeListener('keypress', onKeypress)
+ stdin.setRawMode(false)
+ stdin.pause()
+ }
+ const onKeypress = (str: string | undefined, key: { name?: string; ctrl?: boolean; meta?: boolean }): void => {
+ if (key.ctrl && (key.name === 'c' || key.name === 'd')) { cleanup(); process.stdout.write('\n'); process.exit(130) }
+ if (key.name === 'return' || key.name === 'enter') { cleanup(); process.stdout.write('\n'); resolve(value); return }
+ if (key.name === 'backspace') {
+ if (value.length) { value = value.slice(0, -1); process.stdout.write('\b \b') }
+ return
+ }
+ // Anything else that isn't a single printable character — arrows, tab, escape, function keys,
+ // other ctrl/meta combos — is ignored outright rather than risking its raw bytes landing in the
+ // password buffer.
+ if (str && !key.ctrl && !key.meta && str.length === 1 && str.charCodeAt(0) >= 0x20) {
+ value += str
+ process.stdout.write('*')
+ }
+ }
+ stdin.on('keypress', onKeypress)
})
}
@@ -3642,6 +3662,8 @@ async function remotePasswordSetCommand(json: boolean, stdin: boolean): Promise<
return
}
} else {
+ console.log(`\n Set this machine's remote password. Another machine will use it to link here via`)
+ console.log(` \`harness link connect ${session.machineId}\` — nothing needs approving on this side.\n`)
const a = await promptPassword(' New remote password: ')
const b = await promptPassword(' Confirm remote password: ')
if (!a || a !== b) {
@@ -3670,9 +3692,10 @@ async function remotePasswordSetCommand(json: boolean, stdin: boolean): Promise<
result = await store.setRemotePassword(session.machineId, password)
}
if (json) { console.log(JSON.stringify({ ok: true, fingerprint: result.fingerprint })); process.exit(0) }
- console.log('\n ✓ Remote password set for this machine.')
+ console.log(`\n ✓ Remote password set for this machine (${session.machineId}).`)
console.log(` fingerprint ${result.fingerprint} — verify it matches on the joining machine after \`harness link connect\`\n`)
- console.log(' Anyone with this password can link a machine to this one. Keep it private.\n')
+ console.log(` ▸ Run this on the OTHER machine: harness link connect ${session.machineId}`)
+ console.log(' ⚠ Anyone with this password can link a machine to this one. Keep it private.\n')
if (!readPid()) console.log(' Start the adapter with `harness start` if joins are being rejected.\n')
process.exit(0)
}
@@ -3693,8 +3716,9 @@ async function remotePasswordClearCommand(json: boolean): Promise<void> {
store.init()
store.clearRemotePassword()
}
- if (json) console.log(JSON.stringify({ ok: true }))
- else console.log('\n ✓ Remote password cleared. This machine can no longer be linked by password until a new one is set.\n')
+ if (json) { console.log(JSON.stringify({ ok: true })); process.exit(0) }
+ console.log('\n ✓ Remote password cleared. This machine can no longer be linked by password until a new one is set.')
+ console.log(' ▸ Run `harness remote-password set` to set a new one.\n')
process.exit(0)
}
@@ -3720,7 +3744,11 @@ async function remotePasswordStatusCommand(json: boolean): Promise<void> {
status = { hasPassword: store.hasRemotePassword(), fingerprint: store.remotePasswordFingerprint(), setAt: store.remotePasswordSetAt() }
}
if (json) { console.log(JSON.stringify(status)); process.exit(0) }
- if (!status.hasPassword) { console.log('\n No remote password set.\n Run: harness remote-password set\n'); process.exit(0) }
+ if (!status.hasPassword) {
+ console.log('\n No remote password set.')
+ console.log(' ▸ Run `harness remote-password set` to allow another machine to link to this one.\n')
+ process.exit(0)
+ }
console.log('\n Remote password is set.')
console.log(` fingerprint ${status.fingerprint}\n`)
process.exit(0)
@@ -3732,10 +3760,42 @@ async function remotePasswordStatusCommand(json: boolean): Promise<void> {
* daemon required, same as the old `link import`. On success this machine can relay through to that
* machine's data plane with the CLI (not the app) terminating E2EE — see lib/remoteRelay.ts. Fully
* automatic on success: no approval step runs on the target machine beyond having set the password. */
+/** Turn a `connectWithPassword` failure code into a full instructive sentence — mirrors `pairCommand`'s
+ * `messages` map above, extended to handle the two codes that carry extra data (`RATE_LIMITED`'s
+ * `retryAt`, `CONNECTION_CLOSED:<code>`'s embedded close code). Every branch, including the fallback,
+ * sentence-wraps the code — a bare code must never reach the terminal. */
+function humanizeLinkError(error: string, machineId: string, retryAt?: number): string {
+ if (error === 'RATE_LIMITED') {
+ if (typeof retryAt === 'number') {
+ const minutes = Math.ceil((retryAt - Date.now()) / 60_000)
+ return minutes > 0
+ ? `Too many wrong attempts on ${machineId}. Try again in ${minutes} minute${minutes === 1 ? '' : 's'}.`
+ : `Too many wrong attempts on ${machineId}. Try again now.`
+ }
+ return `Too many wrong attempts on ${machineId}. Wait a few minutes and try again.`
+ }
+ if (error.startsWith('CONNECTION_CLOSED:')) {
+ return `The connection closed unexpectedly (code ${error.slice('CONNECTION_CLOSED:'.length)}) before linking finished. Try again.`
+ }
+ const messages: Record<string, string> = {
+ NO_REMOTE_PASSWORD: `Machine ${machineId} has no remote password set. Ask its operator to run \`harness remote-password set\` there first.`,
+ BAD_INTENT: 'The connection request was malformed — this usually means a version mismatch. Update harness on both machines and try again.',
+ WRONG_PASSWORD: 'That password is wrong. Check it against the other machine and try again.',
+ TIMEOUT: `Machine ${machineId} didn't respond in time. Make sure it's running \`harness start\` and reachable, then try again.`,
+ SEND_FAILED: 'Could not reach the relay to start linking. Check your network connection and try again.',
+ DERIVE_FAILED: 'Could not process the password locally. Try again; if it persists, restart harness and retry.',
+ SELECT_FAILED: `Could not find machine ${machineId}, or it isn't reachable right now. Check the id and that it has run \`harness start\`.`,
+ PAIR_FAILED: `Linking failed on ${machineId}'s side. Try again; if it persists, check its status there with \`harness status\`.`,
+ PROTOCOL_ERROR: 'Something unexpected happened during the handshake. Try again; if it persists, update harness on both machines.',
+ CONNECTION_ERROR: 'Could not reach the relay. Check your network connection and try again.',
+ }
+ return messages[error] ?? `Linking failed (${error}). Try again; if it persists, check both machines are on the latest harness version.`
+}
+
async function linkConnectCommand(machineId: string | undefined, stdin: boolean, json: boolean): Promise<void> {
if (!machineId) {
if (json) console.log(JSON.stringify({ ok: false, error: 'MISSING_MACHINE_ID' }))
- else console.error('Usage: harness link connect <machineId> (the remote password is set on that machine via `harness remote-password set`)')
+ else console.error('Usage: harness link connect <machineId> (the remote password is set on that machine via harness remote-password set)')
process.exit(1)
return
}
@@ -3756,6 +3816,9 @@ async function linkConnectCommand(machineId: string | undefined, stdin: boolean,
return
}
} else {
+ console.log(`\n Linking to machine ${machineId}.`)
+ console.log(' Enter the remote password set on THAT machine (`harness remote-password set`) —')
+ console.log(' this proves you know it; nothing needs approving there.\n')
password = await promptPassword(` Remote password for ${machineId}: `)
}
const auth = new AuthSessionManager(backendHttpBase())
@@ -3763,7 +3826,8 @@ async function linkConnectCommand(machineId: string | undefined, stdin: boolean,
try {
accessToken = await auth.accessToken()
} catch (err) {
- const message = `Could not refresh this computer's SSO session: ${err instanceof Error ? err.message : err}`
+ const detail = err instanceof Error ? err.message : String(err)
+ const message = `Could not refresh this computer's SSO session (${detail}). Run: harness login`
if (json) console.log(JSON.stringify({ ok: false, error: 'AUTH_FAILED', message }))
else console.error(`\n ✗ ${message}\n`)
process.exit(1)
@@ -3781,8 +3845,11 @@ async function linkConnectCommand(machineId: string | undefined, stdin: boolean,
onProgress: json ? (stage) => console.log(JSON.stringify({ stage })) : undefined,
})
if (!result.ok) {
- if (json) console.log(JSON.stringify({ ok: false, error: result.error }))
- else console.error(`\n ✗ Link failed: ${result.error}\n`)
+ if (json) {
+ console.log(JSON.stringify({ ok: false, error: result.error, ...(result.retryAt !== undefined ? { retryAt: result.retryAt } : {}) }))
+ } else {
+ console.error(`\n ✗ ${humanizeLinkError(result.error, machineId, result.retryAt)}\n`)
+ }
process.exit(1)
return
}
@@ -3797,7 +3864,8 @@ async function linkConnectCommand(machineId: string | undefined, stdin: boolean,
async function linkListCommand(): Promise<void> {
const peers = new MachinePeerStore().list()
if (!peers.length) {
- console.log('\n No machines linked yet.\n Run `harness remote-password set` on the other machine and `harness link connect <machineId>` here.\n')
+ console.log('\n No machines linked yet.')
+ console.log(' ▸ Run `harness remote-password set` on the other machine, then `harness link connect <machineId>` here.\n')
process.exit(0)
}
console.log('\n Linked machines:\n')
@@ -3812,7 +3880,12 @@ async function linkListCommand(): Promise<void> {
async function linkUnlinkCommand(machineId: string | undefined): Promise<void> {
if (!machineId) { console.error('Usage: harness link unlink <machineId> (see: harness link list)'); process.exit(1) }
const removed = new MachinePeerStore().unlink(machineId)
- if (!removed) { console.error(`\n ✗ No linked machine matches "${machineId}". Run: harness link list\n`); process.exit(1); return }
+ if (!removed) {
+ console.error(`\n ✗ No linked machine matches "${machineId}".`)
+ console.error(' ▸ Run `harness link list` to see what\'s linked.\n')
+ process.exit(1)
+ return
+ }
console.log(`\n ✓ Unlinked ${machineId}\n`)
process.exit(0)
}
diff --git a/cli/src/engines/README.md b/cli/src/engines/README.md
index b6f5de870..7c95b818b 100644
--- a/cli/src/engines/README.md
+++ b/cli/src/engines/README.md
@@ -248,6 +248,34 @@ Either way, two more files:
process is not the name the user typed — Muse's pane shows `muse-bin-<version>`, and matching only
the bare name silently finds nothing.
+### Process identity matrix
+
+Process discovery is evidence-based and shared by tmux and Herdr. Resolve commands in the same
+interactive shell used to launch them, follow symlinks, then compare the running image by local
+`(device,inode)` identity (`/proc/<pid>/exe` on Linux, batched `lsof` on macOS). Basename and package
+entrypoint rules remain fallbacks for launchers that exec an interpreter or rewrite their process title.
+
+| Engine | Supported runtime evidence |
+|---|---|
+| Claude | installed image; `~/.local/share/claude/versions/<version>`; `@anthropic-ai/claude-code/cli.js` |
+| Codex | installed/Homebrew image; platform release name; `@openai/codex/bin/codex.js` |
+| Cursor | `cursor-agent`; versioned Node launcher; file-owned legacy `agent` alias |
+| OpenCode | `opencode`/`opencode.exe`; `opencode-ai/bin/opencode.exe` |
+| Pi | `pi`; `pi-coding-agent/dist/cli.js` |
+| Hermes | `hermes`; Python/venv `hermes-agent` or `hermes_cli` entrypoint |
+| Command Code | `cmd`/`command-code`; npm entrypoint; rewritten `⌘ <title>` process name |
+| Devin | `devin`; versioned `devin/cli/_versions/<version>/bin/devin` image |
+| Muse | launcher or installed image; exec target `muse-bin-<version>` |
+| Amp | installed image; `~/.amp/bin/amp` |
+| Kilo | `kilo`/`kilocode`/`.kilo`; native platform/baseline image; npm entrypoint |
+| Grok | installed/downloaded image; `~/.grok` layout; file-owned legacy `agent` alias |
+| AGY | native `~/.local/bin/agy`; explicitly rejects the IDE `.app` binary |
+| Copilot | installed native image; `@github/copilot` npm loader/entrypoint |
+
+Never add a bare version or generic executable name as proof. When file identities conflict, leave the
+pane ambiguous rather than registering the wrong engine. A pane-scoped hook may resolve an otherwise
+unknown Cursor/Grok `agent` alias, but it may not override conflicting file/package evidence.
+
## Stage C — read the transcript
**This is the actual work, and the only part that is universal.** Claude Code is the default and has
diff --git a/cli/src/lib/e2ee/relayClient.ts b/cli/src/lib/e2ee/relayClient.ts
index 7035658fd..49b49c8f2 100644
--- a/cli/src/lib/e2ee/relayClient.ts
+++ b/cli/src/lib/e2ee/relayClient.ts
@@ -149,7 +149,7 @@ export class RelaySessionCrypto {
export type PwConnectResult =
| { ok: true; peerPub: Uint8Array; fingerprint: string }
- | { ok: false; error: string }
+ | { ok: false; error: string; retryAt?: number }
export type PwConnectProgress = 'connecting' | 'deriving_key' | 'exchanging' | 'verifying'
@@ -223,7 +223,10 @@ export async function connectWithPassword(opts: {
return
}
if (frame.type === 'e2e_pw_pair_result' && payload.requestId === requestId) {
- if (payload.ok !== true) finish({ ok: false, error: typeof payload.error === 'string' ? payload.error : 'PAIR_FAILED' })
+ if (payload.ok !== true) {
+ const retryAt = typeof payload.retryAt === 'number' ? payload.retryAt : undefined
+ finish({ ok: false, error: typeof payload.error === 'string' ? payload.error : 'PAIR_FAILED', retryAt })
+ }
return
}
if (frame.type !== 'e2e_pw_pake' || payload.sid !== sidB64) return
diff --git a/cli/src/lib/e2ee/relayLink.spec.ts b/cli/src/lib/e2ee/relayLink.spec.ts
index 43fd4042a..ec6b68f48 100644
--- a/cli/src/lib/e2ee/relayLink.spec.ts
+++ b/cli/src/lib/e2ee/relayLink.spec.ts
@@ -245,7 +245,9 @@ describe('remote-password link + relay session crypto (interop with the real E2e
autonomousEnv: 'prod',
timeoutMs: 5_000,
})
- expect(locked).toEqual({ ok: false, error: 'RATE_LIMITED' })
+ expect(locked.ok).toBe(false)
+ expect((locked as { error: string }).error).toBe('RATE_LIMITED')
+ expect((locked as { retryAt?: number }).retryAt).toEqual(expect.any(Number))
} finally {
await close()
}
@@ -271,7 +273,8 @@ describe('remote-password link + relay session crypto (interop with the real E2e
targetMachineId: MACHINE_ID, password: REMOTE_PASSWORD, selfIdentity: C.newIdentity(),
accessToken: 'unused', backendWsBase: base, autonomousEnv: 'prod', timeoutMs: 5_000,
})
- expect(stillLocked).toEqual({ ok: false, error: 'RATE_LIMITED' })
+ expect(stillLocked.ok).toBe(false)
+ expect((stillLocked as { error: string }).error).toBe('RATE_LIMITED')
const NEW_PASSWORD = 'a brand new remote password'
await manager.setRemotePassword(NEW_PASSWORD)
diff --git a/cli/src/lib/engineBin.spec.ts b/cli/src/lib/engineBin.spec.ts
index 9576e9ef8..b619ad019 100644
--- a/cli/src/lib/engineBin.spec.ts
+++ b/cli/src/lib/engineBin.spec.ts
@@ -1,4 +1,5 @@
-import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'
+import { spawn } from 'node:child_process'
+import { copyFileSync, mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { delimiter, join } from 'node:path'
import { afterEach, describe, expect, it } from 'vitest'
@@ -8,6 +9,7 @@ import {
cursorRuntimeBin,
ENGINE_CLI_COMMANDS,
ENGINES,
+ executableFileIdentity,
installedEngineBin,
} from './engineBin.js'
@@ -70,4 +72,25 @@ describe('canonical engine CLI commands', () => {
expect(cursorRuntimeBin(snapshot)).toBe('agent')
expect(installedEngineBin('cursor', snapshot)).toBe(join(cursorBin, 'agent'))
})
+
+ const linuxIt = process.platform === 'linux' ? it : it.skip
+ linuxIt('keeps the running native image identity after an updater replaces its pathname', async () => {
+ const root = mkdtempSync(join(tmpdir(), 'engine-bin-deleted-image-'))
+ tempDirs.push(root)
+ const executable = join(root, 'native-agent')
+ copyFileSync('/bin/sleep', executable)
+ const child = spawn(executable, ['30'], { stdio: 'ignore' })
+ await new Promise<void>((resolve, reject) => {
+ child.once('spawn', resolve)
+ child.once('error', reject)
+ })
+ try {
+ rmSync(executable)
+ const identity = executableFileIdentity(`/proc/${child.pid}/exe`)
+ expect(identity?.fileKey).toMatch(/^\d+:\d+$/)
+ expect(identity?.realPath).toContain('native-agent')
+ } finally {
+ child.kill('SIGKILL')
+ }
+ })
})
diff --git a/cli/src/lib/engineBin.ts b/cli/src/lib/engineBin.ts
index f4d66c855..bc0bdc20a 100644
--- a/cli/src/lib/engineBin.ts
+++ b/cli/src/lib/engineBin.ts
@@ -5,9 +5,10 @@
* colliding `agent` alias is never assigned from its basename alone.
*/
-import { accessSync, constants, realpathSync, statSync } from 'node:fs'
+import { execFileSync } from 'node:child_process'
+import { accessSync, constants, readlinkSync, realpathSync, statSync } from 'node:fs'
import { homedir } from 'node:os'
-import { delimiter, isAbsolute, join, normalize, sep } from 'node:path'
+import { basename, delimiter, isAbsolute, join, normalize, sep } from 'node:path'
import { env } from '../config/env.js'
import { ENGINES, type AgentEngine } from '../engines/types.js'
@@ -49,6 +50,9 @@ export type AgentAliasOwner = 'cursor' | 'grok' | 'unknown' | 'conflict'
* order, symlink depth, package-manager prefix, and the name retained in `ps`.
*/
export interface AgentCommandOwnershipSnapshot {
+ /** Installed command/override identities for every engine, not only the colliding `agent` alias. */
+ engineFileKeys?: ReadonlyMap<AgentEngine, ReadonlySet<string>>
+ engineCandidates?: ReadonlyMap<AgentEngine, readonly ExecutableFileIdentity[]>
cursorFileKeys: ReadonlySet<string>
grokFileKeys: ReadonlySet<string>
conflictingFileKeys: ReadonlySet<string>
@@ -57,8 +61,65 @@ export interface AgentCommandOwnershipSnapshot {
grokCandidates: readonly ExecutableFileIdentity[]
}
+/** Commands whose public aliases can legitimately identify the same engine. */
+export const ENGINE_CLI_ALIASES: Readonly<Record<AgentEngine, readonly string[]>> = {
+ claude: ['claude'],
+ codex: ['codex'],
+ cursor: ['agent', 'cursor-agent'],
+ opencode: ['opencode'],
+ pi: ['pi'],
+ hermes: ['hermes', 'hermes-agent'],
+ commandcode: ['cmd', 'command-code', 'commandcode'],
+ devin: ['devin'],
+ muse: ['muse'],
+ amp: ['amp'],
+ kilo: ['kilo', 'kilocode'],
+ grok: ['grok', 'agent'],
+ agy: ['agy'],
+ copilot: ['copilot'],
+}
+
+let interactivePathCache: { shell: string; daemonPath: string; value: string[] } | null = null
+
+/**
+ * Resolve commands from the same shell startup context used by New Agent.
+ *
+ * A GUI/launchd/systemd daemon commonly lacks ~/.local/bin, Homebrew, nvm and vendor installer edits.
+ * Looking only at its PATH made an installed native binary impossible to identify even though the pane
+ * launched it successfully. Tests deliberately use their injected PATH and never read a developer's rc.
+ */
+function interactivePathEntries(): string[] {
+ if (process.env.NODE_ENV === 'test') return []
+ const shell = process.env.SHELL
+ if (!shell || !isAbsolute(shell)) return []
+ const daemonPath = process.env.PATH ?? ''
+ if (interactivePathCache?.shell === shell && interactivePathCache.daemonPath === daemonPath) {
+ return interactivePathCache.value
+ }
+ try {
+ const flag = basename(shell).toLowerCase() === 'zsh' ? '-lic' : '-ic'
+ const marker = '__HARNESS_ENGINE_PATH__='
+ const stdout = execFileSync(shell, [flag, `printf '\n${marker}%s\n' "$PATH"`], {
+ encoding: 'utf8',
+ timeout: 5_000,
+ stdio: ['ignore', 'pipe', 'ignore'],
+ })
+ // Shell startup files are allowed to print banners. Read only our final marked line.
+ const path = stdout.split('\n').reverse().find((line) => line.startsWith(marker))?.slice(marker.length) ?? ''
+ const value = path.split(delimiter).filter(Boolean)
+ interactivePathCache = { shell, daemonPath, value }
+ return value
+ } catch {
+ interactivePathCache = { shell, daemonPath, value: [] }
+ return []
+ }
+}
+
function pathEntries(): string[] {
- return (process.env.PATH ?? '').split(delimiter).filter(Boolean)
+ return [...new Set([
+ ...(process.env.PATH ?? '').split(delimiter).filter(Boolean),
+ ...interactivePathEntries(),
+ ])]
}
function looksLikePath(command: string): boolean {
@@ -85,9 +146,15 @@ function commandCandidates(command: string): ExecutableFileIdentity[] {
/** Stable while a file exists; deliberately local-only and never sent over the wire. */
export function executableFileIdentity(path: string): ExecutableFileIdentity | null {
try {
- const realPath = realpathSync(path)
- const stat = statSync(realPath)
+ // Stat through the supplied path first. `/proc/<pid>/exe` keeps the running inode reachable even
+ // after an auto-updater replaces its pathname; realpath may then end in "(deleted)" and be
+ // unstatable despite the process image still being valid.
+ const stat = statSync(path)
if (!stat.isFile()) return null
+ let realPath: string
+ try { realPath = realpathSync(path) } catch {
+ try { realPath = readlinkSync(path) } catch { realPath = normalize(path) }
+ }
return { path: normalize(path), realPath, fileKey: `${String(stat.dev)}:${String(stat.ino)}` }
} catch {
return null
@@ -103,8 +170,50 @@ function addAll(target: Set<string>, identities: readonly ExecutableFileIdentity
for (const identity of identities) target.add(identity.fileKey)
}
+function vendorFallbackCommands(engine: AgentEngine): string[] {
+ const home = homedir()
+ switch (engine) {
+ case 'claude': return [join(home, '.local', 'bin', 'claude')]
+ case 'cursor': return [join(home, '.local', 'bin', 'agent'), join(home, '.local', 'bin', 'cursor-agent')]
+ case 'opencode': return [join(home, '.opencode', 'bin', 'opencode')]
+ case 'hermes': return [join(home, '.local', 'bin', 'hermes')]
+ case 'devin': return [join(home, '.local', 'bin', 'devin')]
+ case 'muse': return [join(home, '.local', 'bin', 'muse')]
+ case 'amp': return [join(home, '.amp', 'bin', 'amp'), join(home, '.local', 'bin', 'amp')]
+ case 'kilo': return [join(home, '.kilo', 'bin', 'kilo'), join(home, '.local', 'bin', 'kilo')]
+ case 'grok': return [join(env.GROK_HOME, 'bin', 'grok'), join(home, '.local', 'bin', 'grok')]
+ case 'agy': return [join(home, '.local', 'bin', 'agy')]
+ case 'copilot': return [join(home, '.local', 'bin', 'copilot')]
+ default: return []
+ }
+}
+
+function uniqueIdentities(identities: readonly ExecutableFileIdentity[]): ExecutableFileIdentity[] {
+ const seen = new Set<string>()
+ return identities.filter((identity) => {
+ const key = `${identity.path}\0${identity.fileKey}`
+ if (seen.has(key)) return false
+ seen.add(key)
+ return true
+ })
+}
+
/** Build once per process-table pass; callers pass the snapshot through every row comparison. */
-export function agentCommandOwnershipSnapshot(): AgentCommandOwnershipSnapshot {
+export function engineBinaryOwnershipSnapshot(): AgentCommandOwnershipSnapshot {
+ const engineCandidates = new Map<AgentEngine, ExecutableFileIdentity[]>()
+ const engineFileKeys = new Map<AgentEngine, Set<string>>()
+ for (const engine of ENGINES) {
+ const configured = enginePathOverride(engine)
+ const commands = [
+ ...(configured ? [configured] : []),
+ ...ENGINE_CLI_ALIASES[engine],
+ ...vendorFallbackCommands(engine),
+ ]
+ const candidates = uniqueIdentities(commands.flatMap(commandCandidates))
+ engineCandidates.set(engine, candidates)
+ engineFileKeys.set(engine, new Set(candidates.map((candidate) => candidate.fileKey)))
+ }
+
const agentCandidates = commandCandidates('agent')
const cursorAgentCandidates = commandCandidates('cursor-agent')
const grokCandidates = [...commandCandidates('grok')]
@@ -136,7 +245,17 @@ export function agentCommandOwnershipSnapshot(): AgentCommandOwnershipSnapshot {
const conflictingFileKeys = new Set(
[...cursorFileKeys].filter((fileKey) => grokFileKeys.has(fileKey)),
)
+ // `agent` is intentionally present in both public alias lists. Replace the generic sets with the
+ // vendor-qualified ownership derived above so one PATH entry never makes both engines match.
+ engineFileKeys.set('cursor', cursorFileKeys)
+ engineFileKeys.set('grok', grokFileKeys)
+ engineCandidates.set('cursor', (engineCandidates.get('cursor') ?? []).filter((candidate) =>
+ cursorFileKeys.has(candidate.fileKey) && !conflictingFileKeys.has(candidate.fileKey)))
+ engineCandidates.set('grok', (engineCandidates.get('grok') ?? []).filter((candidate) =>
+ grokFileKeys.has(candidate.fileKey) && !conflictingFileKeys.has(candidate.fileKey)))
return {
+ engineFileKeys,
+ engineCandidates,
cursorFileKeys,
grokFileKeys,
conflictingFileKeys,
@@ -146,6 +265,20 @@ export function agentCommandOwnershipSnapshot(): AgentCommandOwnershipSnapshot {
}
}
+/** Historical name retained while callers migrate; the snapshot now covers every engine. */
+export function agentCommandOwnershipSnapshot(): AgentCommandOwnershipSnapshot {
+ return engineBinaryOwnershipSnapshot()
+}
+
+/** Engines owning the observed executable image. Multiple results mean the install itself is ambiguous. */
+export function engineFileOwners(
+ fileKeys: readonly (string | null | undefined)[],
+ snapshot: AgentCommandOwnershipSnapshot,
+): AgentEngine[] {
+ if (!snapshot.engineFileKeys) return []
+ return ENGINES.filter((engine) => fileKeys.some((fileKey) => !!fileKey && snapshot.engineFileKeys!.get(engine)?.has(fileKey)))
+}
+
export function agentAliasOwner(
fileKeys: readonly (string | null | undefined)[],
snapshot: AgentCommandOwnershipSnapshot,
@@ -221,6 +354,8 @@ export function installedEngineBin(
engine: AgentEngine,
snapshot = agentCommandOwnershipSnapshot(),
): string | null {
+ const installed = snapshot.engineCandidates?.get(engine)
+ if (installed?.length && engine !== 'cursor' && engine !== 'grok') return installed[0].path
const command = engine === 'cursor' ? cursorRuntimeBin(snapshot) : engineBin(engine)
if (!command) return null
const candidates = commandCandidates(command)
diff --git a/cli/src/lib/herdrBackend.ts b/cli/src/lib/herdrBackend.ts
index b42a2c907..6aea7437e 100644
--- a/cli/src/lib/herdrBackend.ts
+++ b/cli/src/lib/herdrBackend.ts
@@ -16,7 +16,7 @@ import {
type TerminalProcessExpectation,
type TerminalReadResult,
} from './terminalTypes.js'
-import { engineProcessMatchScore, processRows } from './tmux.js'
+import { engineProcessMatchScore, enrichProcessRows, processRows } from './tmux.js'
import { terminalRouteKey } from './terminalRuntime.js'
interface HerdrPaneInfo {
@@ -242,14 +242,15 @@ export class HerdrBackend implements TerminalBackend<HerdrRuntimeRef> {
|| !Number.isSafeInteger(info.result.process_info?.shell_pid)) {
return { state: 'unknown', reason: 'Herdr process identity could not be verified' }
}
- const expected = rows.find((row) => row.pid === _expected.processIdentity!.pid)
+ const enrichedRows = await enrichProcessRows(rows, new Set([_expected.processIdentity.pid]))
+ const expected = enrichedRows.find((row) => row.pid === _expected.processIdentity!.pid)
if (!expected || expected.startMarker !== _expected.processIdentity.startMarker) {
return { state: 'gone', reason: 'Herdr engine process identity changed' }
}
if (engineProcessMatchScore(expected, _expected.engine) <= 0) {
return { state: 'gone', reason: 'Herdr process no longer matches the registered engine' }
}
- const byPid = new Map(rows.map((row) => [row.pid, row]))
+ const byPid = new Map(enrichedRows.map((row) => [row.pid, row]))
const rootPid = info.result.process_info.shell_pid!
let pid = expected.pid
const visited = new Set<number>()
diff --git a/cli/src/lib/terminalAgentDiscovery.ts b/cli/src/lib/terminalAgentDiscovery.ts
index 5703267fa..442f32f83 100644
--- a/cli/src/lib/terminalAgentDiscovery.ts
+++ b/cli/src/lib/terminalAgentDiscovery.ts
@@ -10,7 +10,9 @@ import type { TerminalBackend } from './terminalBackend.js'
import {
ambiguousAgentProcess,
engineProcessMatchScore,
+ enrichProcessRows,
processRows,
+ processTreePids,
resumeSessionId,
type ProcessRow,
} from './tmux.js'
@@ -218,9 +220,10 @@ export async function probeTerminalAgents(
])
if (!rows) return { processTableAvailable: false, targets, agents: [], ambiguousPlacements: new Set() }
const roots = targets.flatMap((target) => target.result.state === 'available' ? target.result.roots : [])
+ const enrichedRows = await enrichProcessRows(rows, processTreePids(rows, roots.map((root) => root.rootPid)))
const discovered = discoverTerminalAgentsFromSnapshot(
roots,
- rows,
+ enrichedRows,
daemonPid,
backendOrder,
herdrSessionOrder,
diff --git a/cli/src/lib/tmux.spec.ts b/cli/src/lib/tmux.spec.ts
index 9e44329aa..1e016abf8 100644
--- a/cli/src/lib/tmux.spec.ts
+++ b/cli/src/lib/tmux.spec.ts
@@ -2,9 +2,11 @@ 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 type { AgentCommandOwnershipSnapshot } from './engineBin.js'
import {
ambiguousAgentProcess,
+ engineProcessMatch,
engineProcessMatchScore,
parseProcessRow,
resumeSessionId,
@@ -84,6 +86,59 @@ describe('tmux process primitives', () => {
expect(engineProcessMatchScore({ executable: '/Users/demo/.grok/bin/grok', args: 'grok' }, 'grok')).toBe(3)
})
+ it.each([
+ ['codex', 'codex-aarch64-apple-darwin'],
+ ['codex', 'codex-x86_64-unknown-linux-musl'],
+ ['kilo', 'kilo-darwin-arm64'],
+ ['kilo', 'kilo-linux-x64-baseline'],
+ ['grok', 'grok-1.0.5-macos-aarch64'],
+ ['grok', 'grok-linux-x86_64'],
+ ] as const)('recognises the %s standalone release image %s', (engine, executable) => {
+ expect(engineProcessMatchScore({ executable, args: executable }, engine)).toBe(3)
+ })
+
+ it('uses installed executable identity ahead of misleading argv names', () => {
+ const allFiles = new Map([['codex', new Set(['codex-native'])]]) as AgentCommandOwnershipSnapshot['engineFileKeys']
+ const commands: AgentCommandOwnershipSnapshot = {
+ ...ownership(),
+ engineFileKeys: allFiles,
+ engineCandidates: new Map(),
+ }
+ const row = {
+ executable: 'renamed-release-image',
+ args: 'renamed-release-image --some-flag',
+ imagePath: '/custom/native/renamed-release-image',
+ imageFileKey: 'codex-native',
+ }
+ expect(engineProcessMatch(row, 'codex', commands)).toEqual({
+ score: 4,
+ evidence: 'file-identity',
+ imagePath: '/custom/native/renamed-release-image',
+ })
+ expect(engineProcessMatchScore(row, 'claude', commands)).toBe(0)
+ })
+
+ it.each(ENGINES)('recognises a renamed native %s image from installed file identity', (engine) => {
+ const key = `native-${engine}`
+ const commands: AgentCommandOwnershipSnapshot = {
+ ...ownership(),
+ engineFileKeys: new Map([[engine, new Set([key])]]),
+ engineCandidates: new Map(),
+ }
+ expect(engineProcessMatch({
+ executable: 'vendor-rewritten-title',
+ args: 'vendor-rewritten-title',
+ imageFileKey: key,
+ }, engine, commands)).toMatchObject({ score: 4, evidence: 'file-identity' })
+ })
+
+ it('rejects Antigravity IDE binaries even when their basename is agy', () => {
+ expect(engineProcessMatchScore({
+ executable: '/Applications/Antigravity.app/Contents/Resources/bin/agy',
+ args: '/Applications/Antigravity.app/Contents/Resources/bin/agy',
+ }, 'agy')).toBe(0)
+ })
+
it('recognises Claude native installer version targets without accepting a bare semver', () => {
expect(engineProcessMatchScore({
executable: '/Users/demo/.local/share/claude/versions/2.1.246',
diff --git a/cli/src/lib/tmux.ts b/cli/src/lib/tmux.ts
index 392163c32..a1ceea8a6 100644
--- a/cli/src/lib/tmux.ts
+++ b/cli/src/lib/tmux.ts
@@ -9,6 +9,7 @@ import { registry, type ProcessIdentity, type RegisteredSession } from './regist
import {
agentAliasOwner,
agentCommandOwnershipSnapshot,
+ engineFileOwners,
enginePathOverride,
executableFileIdentity,
type AgentCommandOwnershipSnapshot,
@@ -181,7 +182,7 @@ export async function processRows(): Promise<ProcessRow[] | null> {
resolve(rows)
})
})
- return rows ? enrichProcessRows(repairMangledRows(rows)) : null
+ return rows ? repairMangledRows(rows) : null
}
function execText(command: string, args: string[], timeout: number): Promise<string | null> {
@@ -215,26 +216,41 @@ async function darwinProcessImages(pids: readonly number[]): Promise<Map<number,
}
/**
- * Attach file identity only to rows that mention the colliding `agent` alias. The normal discovery pass
- * remains one tmux read plus one ps read; Linux uses /proc and macOS adds at most one batched lsof call.
+ * Attach executable-image and entrypoint identity to selected process rows.
+ *
+ * Callers pass only descendants of terminal roots (or one saved PID during validation), so native
+ * binary ownership is available for every engine without asking lsof to inspect the whole machine.
*/
-export async function enrichProcessRows(rows: ProcessRow[]): Promise<ProcessRow[]> {
- const candidates = rows.filter(agentAliasCandidate)
+export async function enrichProcessRows(
+ rows: ProcessRow[],
+ selectedPids: ReadonlySet<number> = new Set(rows.map((row) => row.pid)),
+): Promise<ProcessRow[]> {
+ const candidates = rows.filter((row) => selectedPids.has(row.pid))
if (!candidates.length) return rows
const imagePaths = new Map<number, string>()
+ const imageIdentities = new Map<number, ReturnType<typeof executableFileIdentity>>()
if (platform() === 'linux') {
await Promise.all(candidates.map(async (row) => {
- const path = await readlink(`/proc/${row.pid}/exe`).catch(() => null)
- if (path) imagePaths.set(row.pid, path)
+ const procImage = `/proc/${row.pid}/exe`
+ const path = await readlink(procImage).catch(() => null)
+ if (path) {
+ imagePaths.set(row.pid, path)
+ // Stat the proc link itself. If an auto-updater replaced the on-disk path, this still identifies
+ // the exact deleted inode executing in the pane rather than the newer file now at that pathname.
+ imageIdentities.set(row.pid, executableFileIdentity(procImage))
+ }
}))
} else if (platform() === 'darwin') {
- for (const [pid, path] of await darwinProcessImages(candidates.map((row) => row.pid))) imagePaths.set(pid, path)
+ for (const [pid, path] of await darwinProcessImages(candidates.map((row) => row.pid))) {
+ imagePaths.set(pid, path)
+ imageIdentities.set(pid, executableFileIdentity(path.replace(/ \(deleted\)$/, '')))
+ }
}
return rows.map((row) => {
- if (!agentAliasCandidate(row)) return row
+ if (!selectedPids.has(row.pid)) return row
const imagePath = imagePaths.get(row.pid)
- const image = imagePath ? executableFileIdentity(imagePath.replace(/ \(deleted\)$/, '')) : null
+ const image = imageIdentities.get(row.pid) ?? null
const entrypoint = processEntrypoint(row.args)
const entrypointIdentity = entrypoint.includes('/') || entrypoint.includes('\\')
? executableFileIdentity(entrypoint)
@@ -248,6 +264,25 @@ export async function enrichProcessRows(rows: ProcessRow[]): Promise<ProcessRow[
})
}
+/** All rows below one or more terminal roots, including the roots themselves. */
+export function processTreePids(rows: readonly ProcessRow[], rootPids: readonly number[]): Set<number> {
+ const children = new Map<number, number[]>()
+ for (const row of rows) {
+ const list = children.get(row.parentPid) ?? []
+ list.push(row.pid)
+ children.set(row.parentPid, list)
+ }
+ const found = new Set<number>()
+ const queue = [...rootPids]
+ while (queue.length) {
+ const pid = queue.shift()!
+ if (found.has(pid)) continue
+ found.add(pid)
+ for (const child of children.get(pid) ?? []) queue.push(child)
+ }
+ return found
+}
+
function panePid(pane: string): Promise<number | null> {
return new Promise((resolve) => {
@@ -283,7 +318,72 @@ function claudeNativeInstallPath(value: string): boolean {
return /(?:^|\/)\.local\/share\/claude\/versions\/[^/]+$/.test(normalized)
}
-export function engineProcessMatchScore(
+interface EngineProcessSignature {
+ basenames: readonly RegExp[]
+ entrypoints: readonly RegExp[]
+}
+
+/** Vendor-supported native names and launcher/package entrypoints, independent of install prefix. */
+export const ENGINE_PROCESS_SIGNATURES: Readonly<Record<RegisteredSession['engine'], EngineProcessSignature>> = {
+ claude: {
+ basenames: [/^claude$/],
+ entrypoints: [/@anthropic-ai[\/\\]claude-code[\/\\]cli\.js$/],
+ },
+ codex: {
+ basenames: [/^codex$/, /^codex-(?:aarch64|x86_64)-(?:apple-darwin|unknown-linux-(?:gnu|musl))$/],
+ entrypoints: [/@openai[\/\\]codex[\/\\]bin[\/\\]codex(?:\.js)?$/],
+ },
+ cursor: {
+ basenames: [/^cursor-agent$/],
+ entrypoints: [/cursor-agent[\/\\]versions[\/\\][^/\\]+[\/\\]index\.js$/],
+ },
+ opencode: {
+ basenames: [/^opencode(?:\.exe)?$/],
+ entrypoints: [/opencode-ai[\/\\]bin[\/\\]opencode(?:\.exe)?$/],
+ },
+ pi: {
+ basenames: [/^pi$/],
+ entrypoints: [/pi-coding-agent[\/\\]dist[\/\\]cli\.js$/],
+ },
+ hermes: {
+ basenames: [/^hermes$/, /^hermes-agent$/],
+ entrypoints: [/hermes-agent[\/\\]hermes$/, /(?:^|[\/\\])hermes_cli(?:[\/\\]|\.|$)/],
+ },
+ commandcode: {
+ basenames: [/^cmd$/, /^command-?code$/],
+ entrypoints: [/command-code[\/\\]dist[\/\\]index\.mjs$/],
+ },
+ devin: {
+ basenames: [/^devin$/],
+ entrypoints: [/devin[\/\\]cli[\/\\]_versions[\/\\][^/\\]+[\/\\]bin[\/\\]devin$/],
+ },
+ muse: {
+ basenames: [/^muse$/, /^muse-bin-/],
+ entrypoints: [],
+ },
+ amp: {
+ basenames: [/^amp$/],
+ entrypoints: [/[\/\\]\.amp[\/\\]bin[\/\\]amp$/],
+ },
+ kilo: {
+ basenames: [/^kilo$/, /^kilocode$/, /^\.kilo$/, /^kilo-(?:darwin|linux)-(?:arm64|x64)(?:-baseline)?$/],
+ entrypoints: [/@kilocode[\/\\]cli[\/\\]bin[\/\\](?:\.kilo|kilo|kilocode)$/],
+ },
+ grok: {
+ basenames: [/^grok$/, /^grok(?:-[^-]+)?-(?:macos|linux)-(?:aarch64|x86_64)$/],
+ entrypoints: [/[\/\\]\.grok[\/\\](?:bin[\/\\]grok|downloads[\/\\]grok[^/\\]*)$/],
+ },
+ agy: {
+ basenames: [/^agy$/],
+ entrypoints: [/[\/\\]\.local[\/\\]bin[\/\\]agy$/],
+ },
+ copilot: {
+ basenames: [/^copilot$/],
+ entrypoints: [/@github[\/\\]copilot[\/\\](?:npm-loader\.js|index\.js|bin[\/\\]copilot)$/],
+ },
+}
+
+function heuristicEngineProcessMatchScore(
row: Pick<ProcessRow, 'executable' | 'args' | 'imageFileKey' | 'entrypointFileKey'>,
engine: RegisteredSession['engine'],
ownership = agentCommandOwnershipSnapshot(),
@@ -291,6 +391,9 @@ export function engineProcessMatchScore(
const executable = basename(row.executable).toLowerCase()
const entrypoint = processEntrypoint(row.args).toLowerCase()
const entrybase = basename(entrypoint).toLowerCase()
+ // Antigravity also ships an IDE-side `agy` inside its .app bundle. It is not the terminal engine,
+ // even when an AGY_PATH override happens to use the same basename.
+ if (engine === 'agy' && /\.app[\/\\]Contents[\/\\]/.test(`${row.executable}\n${entrypoint}`)) return 0
// Only an explicit override is ownership evidence. A default command label is not: both Cursor and
// Grok ship `agent`, which is exactly the collision this matcher must resolve rather than assume away.
const configured = enginePathOverride(engine)?.toLowerCase()
@@ -298,95 +401,83 @@ export function engineProcessMatchScore(
if (configured && configuredBase !== 'agent' && (row.executable.toLowerCase() === configured
|| entrypoint === configured || executable === configuredBase || entrybase === configuredBase
|| commTruncatedPrefixOf(executable, configuredBase))) return 4
- if (engine === 'codex') {
- if (executable === 'codex' || entrybase === 'codex') return 3
- // npm/pnpm/bun global installs may leave node as `comm`; match the package entrypoint without
- // caring which prefix or package manager store contains it.
- return /@openai[\/\\]codex[\/\\]bin[\/\\]codex(?:\.js)?$/.test(entrypoint) ? 2 : 0
- }
+
+ // Command Code rewrites argv/comm to a session title, which becomes its only long-lived marker.
+ if (engine === 'commandcode' && (/^\s*⌘(?:\s|$)/.test(row.executable) || /^\s*⌘(?:\s|$)/.test(row.args))) return 3
+
+ // Cursor's launcher can retain argv[0]=agent while the Node package path appears later in argv.
+ if (engine === 'cursor' && hasCursorPackageEntrypoint(row.args)) return 3
+
+ const signature = ENGINE_PROCESS_SIGNATURES[engine]
+ if (signature.basenames.some((pattern) => pattern.test(executable) || pattern.test(entrybase))) return 3
+ if (signature.entrypoints.some((pattern) => pattern.test(entrypoint))) return 2
+
+ // Native Claude exposes a version-only target; only the vendor layout makes that name meaningful.
+ if (engine === 'claude' && (claudeNativeInstallPath(row.executable) || claudeNativeInstallPath(entrypoint))) return 3
+
if (engine === 'cursor') {
- if (executable === 'cursor-agent' || entrybase === 'cursor-agent') return 3
- if (hasCursorPackageEntrypoint(row.args)) return 3
return agentAliasOwner([row.imageFileKey, row.entrypointFileKey], ownership) === 'cursor' ? 4 : 0
}
- if (engine === 'opencode') {
- if (executable === 'opencode' || executable === 'opencode.exe' || entrybase === 'opencode' || entrybase === 'opencode.exe') return 3
- return /opencode-ai[\/\\]bin[\/\\]opencode(?:\.exe)?$/.test(entrypoint) ? 2 : 0
- }
- if (engine === 'kilo') {
- // `@kilocode/cli` installs the same file under both names, and kilo's own installer puts a second
- // copy at ~/.kilo/bin/kilo. The npm install measured on 2026-08-10 is a shallow
- // `node /usr/local/bin/kilo` wrapper with a `.kilo` child, so recognize both public command names
- // in argv while depth selection keeps the wrapper as the process-agent identity.
- if (executable === 'kilo' || executable === 'kilocode' || executable === '.kilo'
- || entrybase === 'kilo' || entrybase === 'kilocode' || entrybase === '.kilo') return 3
- return /@kilocode[\/\\]cli[\/\\]bin[\/\\](?:\.kilo|kilo|kilocode)$/.test(entrypoint) ? 2 : 0
- }
- if (engine === 'commandcode') {
- // The TUI overwrites its own argv within the first second — `ps` shows `⌘ Command Code · <dir>` and
- // then `⌘ <session title>`, with no trace of the node entrypoint. So the ⌘ (U+2318) prefix is the
- // only marker present for a pane's whole life; without it a live session fails validateSessionRuntime
- // and the reaper evicts it. The entrypoint rules below still cover a non-renaming/wrapped launch.
- if (/^\s*⌘(?:\s|$)/.test(row.executable) || /^\s*⌘(?:\s|$)/.test(row.args)) return 3
- if (executable === 'cmd' || executable === 'commandcode' || executable === 'command-code'
- || entrybase === 'cmd' || entrybase === 'commandcode' || entrybase === 'command-code') return 3
- return /command-code[\/\\]dist[\/\\]index\.mjs$/.test(entrypoint) ? 2 : 0
- }
- if (engine === 'devin') {
- // `~/.local/bin/devin` is a symlink into `…/devin/cli/_versions/<ver>/bin/devin`, but the pane process
- // keeps the bare `devin` argv (verified live: `ps -o command=` prints exactly `devin`), so the
- // basename is the primary signal and the versioned path only covers a direct/wrapped launch.
- if (executable === 'devin' || entrybase === 'devin') return 3
- return /devin[\/\\]cli[\/\\]_versions[\/\\][^/\\]+[\/\\]bin[\/\\]devin$/.test(entrypoint) ? 2 : 0
- }
- if (engine === 'hermes') {
- // The launcher shim `exec`s away, so the pane process is `…/venv/bin/python …/hermes-agent/hermes`.
- if (executable === 'hermes' || entrybase === 'hermes') return 3
- return /hermes-agent[\/\\]hermes$/.test(entrypoint) || /^(?:hermes|hermes_cli)(?:\.|$)/.test(entrypoint) ? 2 : 0
- }
- if (engine === 'pi') {
- // Pi sets process.title = 'pi'; when the platform ignores that it stays `node …/pi-coding-agent/dist/cli.js`.
- if (executable === 'pi' || entrybase === 'pi') return 3
- return /pi-coding-agent[\/\\]dist[\/\\]cli\.js$/.test(entrypoint) ? 2 : 0
- }
- if (engine === 'muse') {
- // `~/.local/bin/muse` is a bash launcher that `exec`s the real binary, so the pane process is
- // `muse-bin-<version>` — the bare name only appears before the exec.
- if (executable === 'muse' || /^muse-bin-/.test(executable) || entrybase === 'muse' || /^muse-bin-/.test(entrybase)) return 3
- return 0
- }
- if (engine === 'amp') {
- // `~/.local/bin/amp` symlinks to `~/.amp/bin/amp`, a single compiled binary that does NOT re-exec:
- // measured live, the pane process is `amp` with argv `amp` and no children at all.
- if (executable === 'amp' || entrybase === 'amp') return 3
- return /\.amp[\/\\]bin[\/\\]amp$/.test(entrypoint) ? 2 : 0
- }
if (engine === 'grok') {
- // Grok's compiled image may retain `agent`, `grok`, or its downloaded target name. File identity
- // against the installed `grok` command is stable across all three and across arbitrary prefixes.
- if (executable === 'grok' || entrybase === 'grok') return 3
if (agentAliasOwner([row.imageFileKey, row.entrypointFileKey], ownership) === 'grok') return 4
- return /\.grok[\/\\]bin[\/\\]grok$/.test(entrypoint) ? 2 : 0
}
- if (engine === 'agy') {
- // Two binaries answer to `agy` on a machine with Antigravity installed: the CLI at
- // ~/.local/bin/agy (a single 177MB Go binary that does NOT re-exec — the pane process stays `agy`)
- // and ~/.antigravity/antigravity/bin/agy, a symlink into the IDE's app bundle. The IDE one is not
- // an engine, so an entrypoint inside a `.app` is rejected rather than scored.
- if (/\.app[\/\\]Contents[\/\\]/.test(entrypoint)) return 0
- if (executable === 'agy' || entrybase === 'agy') return 3
- return /[\/\\]\.local[\/\\]bin[\/\\]agy$/.test(entrypoint) ? 2 : 0
+ return 0
+}
+
+export type EngineProcessMatchEvidence =
+ | 'file-identity'
+ | 'explicit-override'
+ | 'native-or-process-name'
+ | 'package-entrypoint'
+ | 'pane-hook-hint'
+ | 'none'
+
+export interface EngineProcessMatch {
+ score: number
+ evidence: EngineProcessMatchEvidence
+ imagePath?: string
+}
+
+/**
+ * Structured engine evidence for discovery and remote diagnostics.
+ * File identity wins; basename/package rules are compatibility fallbacks for launchers and scripts.
+ */
+export function engineProcessMatch(
+ row: Pick<ProcessRow, 'executable' | 'args' | 'imagePath' | 'imageFileKey' | 'entrypointFileKey'>,
+ engine: RegisteredSession['engine'],
+ ownership = agentCommandOwnershipSnapshot(),
+): EngineProcessMatch {
+ const owners = engineFileOwners([row.imageFileKey, row.entrypointFileKey], ownership)
+ if (owners.length === 1) {
+ return owners[0] === engine
+ ? { score: 4, evidence: 'file-identity', ...(row.imagePath && { imagePath: row.imagePath }) }
+ : { score: 0, evidence: 'none', ...(row.imagePath && { imagePath: row.imagePath }) }
}
- if (engine === 'copilot') {
- // Two builds answer to `copilot` on a typical machine: a compiled binary (~160MB, measured) and
- // the npm loader script that execs it. Both keep the bare `copilot` argv, so the basename is the
- // signal and the install paths only cover a wrapped launch.
- if (executable === 'copilot' || entrybase === 'copilot') return 3
- return /@github[\/\\]copilot[\/\\](?:npm-loader\.js|.*copilot)$/.test(entrypoint) ? 2 : 0
+ // Conflicting identities are never weakened into a basename guess.
+ if (owners.length > 1) return { score: 0, evidence: 'none', ...(row.imagePath && { imagePath: row.imagePath }) }
+
+ const score = heuristicEngineProcessMatchScore(row, engine, ownership)
+ if (score <= 0) return { score: 0, evidence: 'none', ...(row.imagePath && { imagePath: row.imagePath }) }
+ return {
+ score,
+ evidence: score === 4
+ ? 'explicit-override'
+ : score === 2
+ ? 'package-entrypoint'
+ : score === 1
+ ? 'pane-hook-hint'
+ : 'native-or-process-name',
+ ...(row.imagePath && { imagePath: row.imagePath }),
}
- if (executable === 'claude' || entrybase === 'claude') return 3
- if (claudeNativeInstallPath(row.executable) || claudeNativeInstallPath(entrypoint)) return 3
- return /@anthropic-ai[\/\\]claude-code[\/\\]cli\.js$/.test(entrypoint) ? 2 : 0
+}
+
+/** Compatibility surface for callers that only need ordering. */
+export function engineProcessMatchScore(
+ row: Pick<ProcessRow, 'executable' | 'args' | 'imagePath' | 'imageFileKey' | 'entrypointFileKey'>,
+ engine: RegisteredSession['engine'],
+ ownership = agentCommandOwnershipSnapshot(),
+): number {
+ return engineProcessMatch(row, engine, ownership).score
}
/** An unresolved top-level `agent` is a barrier: a nested sub-agent must not steal its tmux pane. */
@@ -503,7 +594,8 @@ async function lookupPaneEngineProcess(
if (!rootPid) return { ok: false, unknown: true, reason: `tmux could not resolve pane ${pane}` }
const rows = await processRows()
if (!rows) return { ok: false, unknown: true, reason: 'the process table could not be read' }
- const process = selectEngineProcess(rows, rootPid, engine)
+ const enrichedRows = await enrichProcessRows(rows, processTreePids(rows, [rootPid]))
+ const process = selectEngineProcess(enrichedRows, rootPid, engine)
if (!process) return { ok: false, unknown: false, reason: `no ${engine} process under pane ${pane}` }
return {
ok: true,
diff --git a/cli/src/lib/tmuxAgentDiscovery.spec.ts b/cli/src/lib/tmuxAgentDiscovery.spec.ts
index 3c6184e09..41152580f 100644
--- a/cli/src/lib/tmuxAgentDiscovery.spec.ts
+++ b/cli/src/lib/tmuxAgentDiscovery.spec.ts
@@ -39,6 +39,8 @@ describe('tmux process agent snapshot discovery', () => {
['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) => {
@@ -122,6 +124,8 @@ describe('tmux process agent snapshot discovery', () => {
['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) => {
diff --git a/cli/src/lib/tmuxAgentDiscovery.ts b/cli/src/lib/tmuxAgentDiscovery.ts
index 0a9aff830..f6955f4e8 100644
--- a/cli/src/lib/tmuxAgentDiscovery.ts
+++ b/cli/src/lib/tmuxAgentDiscovery.ts
@@ -21,6 +21,7 @@ import {
engineProcessMatchScore,
enrichProcessRows,
parseProcessRow,
+ processTreePids,
resumeSessionId,
setPaneMouseOn,
type ProcessRow,
@@ -211,7 +212,7 @@ export async function probeTmuxAgents(
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 = ps.stdout.split('\n').map(parseProcessRow).filter((row): row is ProcessRow => row !== null)
- const rows = await enrichProcessRows(parsed)
+ const rows = await enrichProcessRows(parsed, processTreePids(parsed, tmux.panes.map((pane) => pane.rootPid)))
const probe = discoverTmuxAgentsFromSnapshot(
tmux.panes,
rows,