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.

fix(cli): disambiguate Cursor and Grok agent aliases

0xken151cb4b127383b
diff --git a/cli/hook/notify.mjs b/cli/hook/notify.mjs
index db7158fd0..8a8d120df 100644
--- a/cli/hook/notify.mjs
+++ b/cli/hook/notify.mjs
@@ -18,7 +18,9 @@ import http from 'node:http'
import { execFile } from 'node:child_process'
import { randomUUID } from 'node:crypto'
import {
+ accessSync,
closeSync,
+ constants,
mkdirSync,
openSync,
readFileSync,
@@ -30,7 +32,7 @@ import {
statSync,
writeFileSync,
} from 'node:fs'
-import { basename, dirname, join, relative } from 'node:path'
+import { basename, delimiter, dirname, isAbsolute, join, relative, sep } from 'node:path'
import { homedir, uptime } from 'node:os'
const BOOT_TOLERANCE_SEC = 120
@@ -83,6 +85,7 @@ function paths() {
bootFile: join(dataDir, 'registry-boot'),
claudeProjectsDir,
codexSessionsDir: join(codexHome, 'sessions'),
+ grokHome,
grokSessionsDir: join(grokHome, 'sessions'),
cursorProjectsDir: join(cursorHome, 'projects'),
hermesDb: join(hermesHome, 'state.db'),
@@ -243,18 +246,76 @@ const ENGINE_PATH_ENV = {
commandcode: 'COMMANDCODE_PATH', devin: 'DEVIN_PATH', muse: 'MUSE_PATH', grok: 'GROK_PATH',
}
-function processMatchScore(row, engine) {
+function executableIdentity(path) {
+ try {
+ const realPath = realpathSync(path)
+ const stat = statSync(realPath)
+ return stat.isFile() ? { realPath, fileKey: `${String(stat.dev)}:${String(stat.ino)}` } : null
+ } catch {
+ return null
+ }
+}
+
+function commandIdentity(command) {
+ if (!command) return null
+ if (isAbsolute(command) || command.includes('/') || command.includes('\\')) {
+ try { accessSync(command, constants.X_OK) } catch { return null }
+ return executableIdentity(command)
+ }
+ for (const dir of String(process.env.PATH || '').split(delimiter).filter(Boolean)) {
+ const path = join(dir, command)
+ try { accessSync(path, constants.X_OK) } catch { continue }
+ const identity = executableIdentity(path)
+ if (identity) return identity
+ }
+ return null
+}
+
+function hookCommandOwnership(p) {
+ const agent = commandIdentity('agent')
+ const cursor = commandIdentity(process.env.CURSOR_PATH || 'cursor-agent')
+ const grok = commandIdentity(process.env.GROK_PATH || 'grok') || commandIdentity(join(p.grokHome, 'bin', 'grok'))
+ const cursorKeys = new Set(cursor ? [cursor.fileKey] : [])
+ const grokKeys = new Set(grok ? [grok.fileKey] : [])
+ if (agent && /\/cursor-agent\/versions\/[^/]+\/cursor-agent$/.test(agent.realPath.split(sep).join('/'))) {
+ cursorKeys.add(agent.fileKey)
+ }
+ return { agentFileKey: agent?.fileKey, cursorKeys, grokKeys }
+}
+
+function hookFileOwner(fileKey, ownership) {
+ if (!fileKey) return 'unknown'
+ const isCursor = ownership.cursorKeys.has(fileKey)
+ const isGrok = ownership.grokKeys.has(fileKey)
+ if (isCursor && isGrok) return 'conflict'
+ if (isCursor) return 'cursor'
+ if (isGrok) return 'grok'
+ return 'unknown'
+}
+
+function processMatchScore(row, engine, ownership, allowAgentHint = false) {
const executable = basename(row.executable).toLowerCase()
const entrypoint = processEntrypoint(row.args).toLowerCase()
const entrybase = basename(entrypoint).toLowerCase()
- const configured = String(process.env[ENGINE_PATH_ENV[engine]] || ENGINE_COMMANDS[engine] || '').toLowerCase()
+ const explicit = process.env[ENGINE_PATH_ENV[engine]]
+ const configured = String(explicit || ENGINE_COMMANDS[engine] || '').toLowerCase()
const configuredBase = basename(configured).toLowerCase()
- if (configuredBase && (executable === configuredBase || entrybase === configuredBase
- || row.executable.toLowerCase() === configured || entrypoint === configured)) return 4
+ if (configuredBase && configuredBase !== 'agent' && (row.executable.toLowerCase() === configured
+ || entrypoint === configured || executable === configuredBase || entrybase === configuredBase)) return 4
if (engine === 'codex') return /@openai[\/\\]codex[\/\\]bin[\/\\]codex(?:\.js)?$/.test(entrypoint) ? 2 : 0
if (engine === 'cursor') {
if (executable === 'cursor-agent' || entrybase === 'cursor-agent') return 3
- return /cursor-agent[\/\\]versions[\/\\][^/\\]+[\/\\]index\.js$/.test(entrypoint) ? 2 : 0
+ if (argvTokens(row.args).slice(0, 8).some((token) =>
+ /cursor-agent[\/\\]versions[\/\\][^/\\]+[\/\\]index\.js$/i.test(token))) return 3
+ if (executable === 'agent' || entrybase === 'agent') {
+ const aliasOwner = hookFileOwner(row.imageFileKey, ownership) !== 'unknown'
+ ? hookFileOwner(row.imageFileKey, ownership)
+ : hookFileOwner(ownership.agentFileKey, ownership)
+ if (aliasOwner === 'cursor') return 4
+ if (aliasOwner === 'grok' || aliasOwner === 'conflict') return 0
+ return allowAgentHint ? 1 : 0
+ }
+ return 0
}
if (engine === 'commandcode') {
if (/^\s*⌘(?:\s|$)/.test(row.executable) || /^\s*⌘(?:\s|$)/.test(row.args)
@@ -266,7 +327,18 @@ function processMatchScore(row, engine) {
if (engine === 'hermes') return /hermes-agent[\/\\]hermes$/.test(entrypoint)
|| /^(?:hermes|hermes_cli)(?:\.|$)/.test(entrypoint) ? 2 : 0
if (engine === 'muse') return /^muse-bin-/.test(executable) || /^muse-bin-/.test(entrybase) ? 3 : 0
- if (engine === 'grok') return /\.grok[\/\\]bin[\/\\]grok$/.test(entrypoint) ? 2 : 0
+ if (engine === 'grok') {
+ if (executable === 'grok' || entrybase === 'grok') return 3
+ if (executable === 'agent' || entrybase === 'agent') {
+ const aliasOwner = hookFileOwner(row.imageFileKey, ownership) !== 'unknown'
+ ? hookFileOwner(row.imageFileKey, ownership)
+ : hookFileOwner(ownership.agentFileKey, ownership)
+ if (aliasOwner === 'grok') return 4
+ if (aliasOwner === 'cursor' || aliasOwner === 'conflict') return 0
+ return allowAgentHint ? 1 : 0
+ }
+ return /\.grok[\/\\]bin[\/\\]grok$/.test(entrypoint) ? 2 : 0
+ }
return /@anthropic-ai[\/\\]claude-code[\/\\]cli\.js$/.test(entrypoint) ? 2 : 0
}
@@ -288,12 +360,48 @@ async function processRows() {
return rows
}
+function aliasRows(rows) {
+ return rows.filter((row) => basename(row.executable).toLowerCase() === 'agent'
+ || basename(processEntrypoint(row.args)).toLowerCase() === 'agent')
+}
+
+async function enrichProcessImages(rows) {
+ const candidates = aliasRows(rows)
+ if (!candidates.length) return rows
+ const images = new Map()
+ if (process.platform === 'linux') {
+ for (const row of candidates) {
+ const identity = executableIdentity(`/proc/${row.pid}/exe`)
+ if (identity) images.set(row.pid, identity.fileKey)
+ }
+ } else if (process.platform === 'darwin') {
+ const stdout = await execFileText('lsof', ['-a', '-p', candidates.map((row) => row.pid).join(','), '-d', 'txt', '-Fn'], 1500)
+ let pid = null
+ let textFile = false
+ for (const line of String(stdout || '').split('\n')) {
+ if (/^p\d+$/.test(line)) {
+ pid = Number(line.slice(1))
+ textFile = false
+ } else if (line === 'ftxt') {
+ textFile = true
+ } else if (textFile && pid && line.startsWith('n') && !images.has(pid)) {
+ const identity = executableIdentity(line.slice(1).replace(/ \(deleted\)$/, ''))
+ if (identity) images.set(pid, identity.fileKey)
+ textFile = false
+ }
+ }
+ }
+ return rows.map((row) => images.has(row.pid) ? { ...row, imageFileKey: images.get(row.pid) } : row)
+}
+
async function paneEngineProcess(pane, engine) {
const rootPid = await panePid(pane)
if (rootPid === undefined) return { state: 'unknown' }
if (!rootPid) return { state: 'gone' }
- const rows = await processRows()
- if (!rows) return { state: 'unknown' }
+ const rawRows = await processRows()
+ if (!rawRows) return { state: 'unknown' }
+ const rows = await enrichProcessImages(rawRows)
+ const ownership = hookCommandOwnership(paths())
const children = new Map()
const byPid = new Map(rows.map((row) => [row.pid, row]))
for (const row of rows) {
@@ -306,7 +414,7 @@ async function paneEngineProcess(pane, engine) {
while (queue.length > 0) {
const current = queue.shift()
const row = byPid.get(current.pid)
- const score = row ? processMatchScore(row, engine) : 0
+ const score = row ? processMatchScore(row, engine, ownership, true) : 0
if (row && score > 0 && (!best || current.depth < best.depth || (current.depth === best.depth && score > best.score))) {
best = { row, depth: current.depth, score }
}
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index 1543abc7b..7bbadb838 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -1158,7 +1158,7 @@ async function runForeground(token: string): Promise<void> {
const { server: hookServer, port: hookPort } = await startHookServer(env.PORT, {
resolveHookAgent: async ({ engine, tmuxPane }) => {
- await agentReconciler.trigger()
+ await agentReconciler.triggerHint(tmuxPane, engine)
return registry.byPaneEngine(tmuxPane, engine) ?? null
},
onRegistered: handleRegistered,
diff --git a/cli/src/config/env.ts b/cli/src/config/env.ts
index 803773f94..d9b265483 100644
--- a/cli/src/config/env.ts
+++ b/cli/src/config/env.ts
@@ -174,7 +174,7 @@ const envSchema = z.object({
TMUX_REAP_INTERVAL_MS: z.string().default('5000').transform(Number),
// Path to the `claude` CLI for the device turn-recap one-shot (else resolved from PATH).
CLAUDE_PATH: z.string().optional(),
- // Path to the Cursor Agent CLI for Cursor recap one-shots (else `agent` is resolved from PATH).
+ // Path to the Cursor Agent CLI for recap one-shots (else a verified `agent`/`cursor-agent` is used).
CURSOR_PATH: z.string().optional(),
// Path to the `opencode` CLI for OpenCode recap one-shots (else `opencode` is resolved from PATH).
OPENCODE_PATH: z.string().optional(),
diff --git a/cli/src/hookNotify.spec.ts b/cli/src/hookNotify.spec.ts
index f77e1294b..679d36633 100644
--- a/cli/src/hookNotify.spec.ts
+++ b/cli/src/hookNotify.spec.ts
@@ -1,6 +1,6 @@
import { spawn } from 'child_process'
import { createServer } from 'http'
-import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'fs'
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'fs'
import { tmpdir } from 'os'
import { join } from 'path'
import { fileURLToPath } from 'url'
@@ -54,6 +54,17 @@ function runHook(opts: RunHookOpts): Promise<string> {
const processArgs = opts.processArgs ?? executable
writeFileSync(join(binDir, 'tmux'), '#!/bin/sh\necho 7000\n', { mode: 0o755 })
writeFileSync(join(binDir, 'ps'), `#!/bin/sh\nprintf '%s\\n' '7000 1 zsh Mon Aug 10 10:00:00 2026 -zsh' '7001 7000 ${executable} Mon Aug 10 10:00:01 2026 ${processArgs}'\n`, { mode: 0o755 })
+ if (opts.processEngine === 'cursor') {
+ const target = join(binDir, 'cursor-agent-target')
+ writeFileSync(target, '#!/bin/sh\n', { mode: 0o755 })
+ symlinkSync(target, join(binDir, 'agent'))
+ symlinkSync(target, join(binDir, 'cursor-agent'))
+ } else if (opts.processEngine === 'grok') {
+ const target = join(binDir, 'grok-target')
+ writeFileSync(target, '#!/bin/sh\n', { mode: 0o755 })
+ symlinkSync(target, join(binDir, 'agent'))
+ symlinkSync(target, join(binDir, 'grok'))
+ }
if (opts.hermesSource !== undefined) {
const rows = opts.hermesSource === null ? '[]' : JSON.stringify([{ source: opts.hermesSource }])
writeFileSync(join(binDir, 'sqlite3'), `#!/bin/sh\nprintf '%s\\n' '${rows}'\n`, { mode: 0o755 })
@@ -608,12 +619,21 @@ describe('hook notify Grok lifecycle', () => {
writeFileSync(transcript, '{}\n')
await runHook({
- port: 9, tmuxPane: '%45', engine: 'grok', processEngine: 'grok', grokHome, dataDir,
+ port: 9, tmuxPane: '%45', engine: 'grok', processEngine: 'grok',
+ processExecutable: 'agent', processArgs: 'agent', grokHome, dataDir,
input: { hookEventName: 'session_start', sessionId, cwd },
})
expect(JSON.parse(readFileSync(join(dataDir, 'registry.json'), 'utf8'))).toMatchObject([{
sessionId, engine: 'grok', transcriptPath: transcript, projectDir: 'grok-offline', cwd, tmuxPane: '%45',
}])
+
+ const rejectedDataDir = join(dir, 'cursor-owned-agent-data')
+ await runHook({
+ port: 9, tmuxPane: '%46', engine: 'grok', processEngine: 'cursor',
+ processExecutable: 'agent', processArgs: 'agent', grokHome, dataDir: rejectedDataDir,
+ input: { hookEventName: 'session_start', sessionId, cwd },
+ })
+ expect(() => readFileSync(join(rejectedDataDir, 'registry.json'), 'utf8')).toThrow()
})
})
diff --git a/cli/src/lib/engineBin.spec.ts b/cli/src/lib/engineBin.spec.ts
index 8fedab72f..20325aee2 100644
--- a/cli/src/lib/engineBin.spec.ts
+++ b/cli/src/lib/engineBin.spec.ts
@@ -1,5 +1,22 @@
-import { describe, expect, it } from 'vitest'
-import { ENGINE_CLI_COMMANDS, ENGINES } from './engineBin.js'
+import { 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'
+import {
+ agentAliasOwner,
+ agentCommandOwnershipSnapshot,
+ cursorRuntimeBin,
+ ENGINE_CLI_COMMANDS,
+ ENGINES,
+} from './engineBin.js'
+
+const originalPath = process.env.PATH
+const tempDirs: string[] = []
+
+afterEach(() => {
+ process.env.PATH = originalPath
+ for (const dir of tempDirs.splice(0)) rmSync(dir, { recursive: true, force: true })
+})
describe('canonical engine CLI commands', () => {
it('keeps the user-facing 12-engine command contract exact and ordered', () => {
@@ -18,4 +35,34 @@ describe('canonical engine CLI commands', () => {
['grok', 'grok'],
])
})
+
+ it('adapts agent ownership and Cursor recap command to PATH order without install-path assumptions', () => {
+ const root = mkdtempSync(join(tmpdir(), 'engine-bin-ownership-'))
+ tempDirs.push(root)
+ const cursorBin = join(root, 'custom-cursor-prefix', 'bin')
+ const grokBin = join(root, 'custom-grok-prefix', 'bin')
+ const cursorTarget = join(root, 'share', 'cursor-agent', 'versions', '2099.01.01', 'cursor-agent')
+ const grokTarget = join(root, 'downloads', 'renamed-grok-image')
+ mkdirSync(cursorBin, { recursive: true })
+ mkdirSync(grokBin, { recursive: true })
+ mkdirSync(join(cursorTarget, '..'), { recursive: true })
+ mkdirSync(join(grokTarget, '..'), { recursive: true })
+ writeFileSync(cursorTarget, '#!/bin/sh\n', { mode: 0o755 })
+ writeFileSync(grokTarget, 'grok', { mode: 0o755 })
+ symlinkSync(cursorTarget, join(cursorBin, 'agent'))
+ symlinkSync(cursorTarget, join(cursorBin, 'cursor-agent'))
+ symlinkSync(grokTarget, join(grokBin, 'agent'))
+ symlinkSync(grokTarget, join(grokBin, 'grok'))
+
+ process.env.PATH = [grokBin, cursorBin].join(delimiter)
+ let snapshot = agentCommandOwnershipSnapshot()
+ expect(agentAliasOwner([snapshot.agentCandidates[0]?.fileKey], snapshot)).toBe('grok')
+ expect(agentAliasOwner([snapshot.agentCandidates[1]?.fileKey], snapshot)).toBe('cursor')
+ expect(cursorRuntimeBin(snapshot)).toBe('cursor-agent')
+
+ process.env.PATH = [cursorBin, grokBin].join(delimiter)
+ snapshot = agentCommandOwnershipSnapshot()
+ expect(agentAliasOwner([snapshot.agentCandidates[0]?.fileKey], snapshot)).toBe('cursor')
+ expect(cursorRuntimeBin(snapshot)).toBe('agent')
+ })
})
diff --git a/cli/src/lib/engineBin.ts b/cli/src/lib/engineBin.ts
index 8c1abb620..a253d4a73 100644
--- a/cli/src/lib/engineBin.ts
+++ b/cli/src/lib/engineBin.ts
@@ -1,12 +1,12 @@
/**
- * Per-engine CLI binary resolution — the single source of truth shared by the recap one-shots
- * (`oneshot.ts`) plus process discovery and user-facing command hints.
+ * Per-engine command labels, explicit binary overrides, and local executable ownership.
*
- * Each engine honours its own `*_PATH` override (see `config/env.ts`) and otherwise resolves the plain
- * command name from PATH. `codex` reads `process.env` directly because it has no entry in the validated
- * env schema (only `CODEX_HOME` does) — kept as-is so behaviour matches what oneshot.ts already shipped.
+ * User-facing labels stay stable, while process discovery and Cursor recap use file identity so the
+ * colliding `agent` alias is never assigned from its basename alone.
*/
+import { accessSync, constants, realpathSync, statSync } from 'node:fs'
+import { delimiter, isAbsolute, join, normalize, sep } from 'node:path'
import { env } from '../config/env.js'
import type { AgentEngine } from '../engines/types.js'
@@ -31,6 +31,176 @@ export const ENGINE_CLI_COMMANDS: Readonly<Record<AgentEngine, string>> = {
grok: 'grok',
}
+export interface ExecutableFileIdentity {
+ path: string
+ realPath: string
+ fileKey: string
+}
+
+export type AgentAliasOwner = 'cursor' | 'grok' | 'unknown' | 'conflict'
+
+/**
+ * Per-machine evidence used only for the colliding `agent` command.
+ *
+ * Cursor installs `agent` and `cursor-agent` as aliases of one launcher. Grok Build installs `agent`
+ * and `grok` as aliases of one compiled binary. Comparing the resolved file is independent of PATH
+ * order, symlink depth, package-manager prefix, and the name retained in `ps`.
+ */
+export interface AgentCommandOwnershipSnapshot {
+ cursorFileKeys: ReadonlySet<string>
+ grokFileKeys: ReadonlySet<string>
+ conflictingFileKeys: ReadonlySet<string>
+ agentCandidates: readonly ExecutableFileIdentity[]
+ cursorAgentCandidates: readonly ExecutableFileIdentity[]
+ grokCandidates: readonly ExecutableFileIdentity[]
+}
+
+function pathEntries(): string[] {
+ return (process.env.PATH ?? '').split(delimiter).filter(Boolean)
+}
+
+function looksLikePath(command: string): boolean {
+ return isAbsolute(command) || command.includes('/') || command.includes('\\')
+}
+
+/** Resolve every visible command candidate, not only the first PATH hit. */
+function commandCandidates(command: string): ExecutableFileIdentity[] {
+ const paths = looksLikePath(command)
+ ? [command]
+ : pathEntries().map((entry) => join(entry, command))
+ const seen = new Set<string>()
+ const result: ExecutableFileIdentity[] = []
+ for (const path of paths) {
+ try { accessSync(path, constants.X_OK) } catch { continue }
+ const identity = executableFileIdentity(path)
+ if (!identity || seen.has(identity.path)) continue
+ seen.add(identity.path)
+ result.push(identity)
+ }
+ return result
+}
+
+/** 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)
+ if (!stat.isFile()) return null
+ return { path: normalize(path), realPath, fileKey: `${String(stat.dev)}:${String(stat.ino)}` }
+ } catch {
+ return null
+ }
+}
+
+function cursorInstallLayout(path: string): boolean {
+ const normalized = path.split(sep).join('/')
+ return /\/cursor-agent\/versions\/[^/]+\/cursor-agent$/.test(normalized)
+}
+
+function addAll(target: Set<string>, identities: readonly ExecutableFileIdentity[]): void {
+ for (const identity of identities) target.add(identity.fileKey)
+}
+
+/** Build once per process-table pass; callers pass the snapshot through every row comparison. */
+export function agentCommandOwnershipSnapshot(): AgentCommandOwnershipSnapshot {
+ const agentCandidates = commandCandidates('agent')
+ const cursorAgentCandidates = commandCandidates('cursor-agent')
+ const grokCandidates = [...commandCandidates('grok')]
+
+ const cursorFileKeys = new Set<string>()
+ const grokFileKeys = new Set<string>()
+ addAll(cursorFileKeys, cursorAgentCandidates)
+ addAll(grokFileKeys, grokCandidates)
+
+ // Existing explicit overrides are ownership declarations, but a declaration that resolves to the
+ // other vendor's canonical binary becomes a conflict below instead of silently winning by basename.
+ if (env.CURSOR_PATH) addAll(cursorFileKeys, commandCandidates(env.CURSOR_PATH))
+ if (env.GROK_PATH) addAll(grokFileKeys, commandCandidates(env.GROK_PATH))
+
+ // Grok's own state-root override already describes its standard installer root. This seed keeps
+ // discovery correct when the daemon PATH differs from an interactive tmux shell's PATH.
+ const grokHomeBin = commandCandidates(join(env.GROK_HOME, 'bin', 'grok'))[0]
+ if (grokHomeBin) {
+ grokFileKeys.add(grokHomeBin.fileKey)
+ if (!grokCandidates.some((candidate) => candidate.path === grokHomeBin.path)) grokCandidates.push(grokHomeBin)
+ }
+
+ // Cursor's launcher target carries a vendor-specific package layout even when `cursor-agent` itself
+ // is absent from the daemon PATH (for example, a pane inherited a newer interactive shell PATH).
+ for (const candidate of agentCandidates) {
+ if (cursorInstallLayout(candidate.realPath)) cursorFileKeys.add(candidate.fileKey)
+ }
+
+ const conflictingFileKeys = new Set(
+ [...cursorFileKeys].filter((fileKey) => grokFileKeys.has(fileKey)),
+ )
+ return {
+ cursorFileKeys,
+ grokFileKeys,
+ conflictingFileKeys,
+ agentCandidates,
+ cursorAgentCandidates,
+ grokCandidates,
+ }
+}
+
+export function agentAliasOwner(
+ fileKeys: readonly (string | null | undefined)[],
+ snapshot: AgentCommandOwnershipSnapshot,
+): AgentAliasOwner {
+ let cursor = false
+ let grok = false
+ for (const fileKey of fileKeys) {
+ if (!fileKey) continue
+ if (snapshot.conflictingFileKeys.has(fileKey)) return 'conflict'
+ if (snapshot.cursorFileKeys.has(fileKey)) cursor = true
+ if (snapshot.grokFileKeys.has(fileKey)) grok = true
+ }
+ if (cursor && grok) return 'conflict'
+ if (cursor) return 'cursor'
+ if (grok) return 'grok'
+ return 'unknown'
+}
+
+/**
+ * Cursor recap must never spawn Grok merely because Grok won the `agent` name in this daemon's PATH.
+ * Return null when the machine offers no verified Cursor command; the worker then fails explicitly.
+ */
+export function cursorRuntimeBin(snapshot = agentCommandOwnershipSnapshot()): string | null {
+ if (env.CURSOR_PATH) {
+ const configured = commandCandidates(env.CURSOR_PATH)[0]
+ if (!configured) return null
+ return agentAliasOwner([configured.fileKey], snapshot) === 'grok'
+ || agentAliasOwner([configured.fileKey], snapshot) === 'conflict'
+ ? null
+ : env.CURSOR_PATH
+ }
+
+ const agent = snapshot.agentCandidates[0]
+ if (agent && agentAliasOwner([agent.fileKey], snapshot) === 'cursor') return 'agent'
+ const cursorAgent = snapshot.cursorAgentCandidates[0]
+ if (cursorAgent && agentAliasOwner([cursorAgent.fileKey], snapshot) === 'cursor') return 'cursor-agent'
+ return null
+}
+
+/** Existing env override only; process matching must not treat a default basename as ownership proof. */
+export function enginePathOverride(engine: AgentEngine): string | undefined {
+ switch (engine) {
+ case 'claude': return env.CLAUDE_PATH
+ case 'codex': return process.env.CODEX_PATH
+ case 'cursor': return env.CURSOR_PATH
+ case 'opencode': return env.OPENCODE_PATH
+ case 'pi': return env.PI_PATH
+ case 'hermes': return env.HERMES_PATH
+ case 'commandcode': return env.COMMANDCODE_PATH
+ case 'devin': return env.DEVIN_PATH
+ case 'muse': return env.MUSE_PATH
+ case 'amp': return env.AMP_PATH
+ case 'kilo': return env.KILO_PATH
+ case 'grok': return env.GROK_PATH
+ }
+}
+
export function engineBin(engine: AgentEngine): string {
switch (engine) {
case 'claude': return env.CLAUDE_PATH || ENGINE_CLI_COMMANDS.claude
diff --git a/cli/src/lib/oneshot.ts b/cli/src/lib/oneshot.ts
index 573d24149..244aa3078 100644
--- a/cli/src/lib/oneshot.ts
+++ b/cli/src/lib/oneshot.ts
@@ -8,6 +8,7 @@ import { randomUUID } from 'crypto'
import { homedir, tmpdir, userInfo } from 'os'
import { env } from '../config/env.js'
import { findCursorTranscript } from '../engines/cursor/discovery.js'
+import { cursorRuntimeBin } from './engineBin.js'
import {
DisposableOneShotPool,
type ActiveEngineCounts,
@@ -55,7 +56,9 @@ export function trustDevinWorkspace(dir: string, onError?: (message: string) =>
}
function cursorBin(): string {
- return env.CURSOR_PATH || 'agent'
+ const bin = cursorRuntimeBin()
+ if (bin) return bin
+ throw new Error('Cursor CLI command is ambiguous or unavailable; install cursor-agent or set CURSOR_PATH to its absolute path')
}
function buildEnv(): NodeJS.ProcessEnv {
diff --git a/cli/src/lib/tmux.spec.ts b/cli/src/lib/tmux.spec.ts
index e2b4f7407..a1da5ad34 100644
--- a/cli/src/lib/tmux.spec.ts
+++ b/cli/src/lib/tmux.spec.ts
@@ -1,6 +1,16 @@
import { describe, expect, it } from 'vitest'
+import type { AgentCommandOwnershipSnapshot } from './engineBin.js'
import { engineProcessMatchScore, parseProcessRow, resumeSessionId } from './tmux.js'
+const ownership = (cursor: string[] = [], grok: string[] = []): AgentCommandOwnershipSnapshot => ({
+ cursorFileKeys: new Set(cursor),
+ grokFileKeys: new Set(grok),
+ conflictingFileKeys: new Set(cursor.filter((key) => grok.includes(key))),
+ agentCandidates: [],
+ cursorAgentCandidates: [],
+ grokCandidates: [],
+})
+
describe('tmux process primitives', () => {
it('parses a process whose comm field contains spaces', () => {
expect(parseProcessRow('4242 100 ⌘ Greeting Thu Jul 30 11:00:03 2026 cmd -r abcdef12-3456-7890-abcd-ef1234567890')).toEqual({
@@ -13,10 +23,25 @@ describe('tmux process primitives', () => {
})
it('recognises stable installed binary forms', () => {
- // Exact canonical/configured commands outrank vendor package-layout heuristics.
- expect(engineProcessMatchScore({ executable: 'devin', args: 'devin' }, 'devin')).toBe(4)
+ expect(engineProcessMatchScore({ executable: 'devin', args: 'devin' }, 'devin')).toBe(3)
expect(engineProcessMatchScore({ executable: 'muse-bin-0.1.0-R708.1', args: 'muse-bin-0.1.0-R708.1' }, 'muse')).toBe(3)
- expect(engineProcessMatchScore({ executable: '/Users/demo/.grok/bin/grok', args: 'grok' }, 'grok')).toBe(4)
+ expect(engineProcessMatchScore({ executable: '/Users/demo/.grok/bin/grok', args: 'grok' }, 'grok')).toBe(3)
+ })
+
+ it('assigns the colliding agent basename only from executable ownership', () => {
+ const cursor = ownership(['cursor-file'], ['grok-file'])
+ const grok = ownership(['cursor-file'], ['grok-file'])
+ const cursorRow = { executable: 'agent', args: 'agent', imageFileKey: 'cursor-file' }
+ const grokRow = { executable: 'agent', args: 'agent', imageFileKey: 'grok-file' }
+
+ expect(engineProcessMatchScore(cursorRow, 'cursor', cursor)).toBe(4)
+ expect(engineProcessMatchScore(cursorRow, 'grok', cursor)).toBe(0)
+ expect(engineProcessMatchScore(grokRow, 'grok', grok)).toBe(4)
+ expect(engineProcessMatchScore(grokRow, 'cursor', grok)).toBe(0)
+ expect(engineProcessMatchScore({ executable: 'agent', args: 'agent' }, 'cursor', cursor)).toBe(0)
+ const conflict = ownership(['same-file'], ['same-file'])
+ expect(engineProcessMatchScore({ executable: 'agent', args: 'agent', imageFileKey: 'same-file' }, 'cursor', conflict)).toBe(0)
+ expect(engineProcessMatchScore({ executable: 'agent', args: 'agent', imageFileKey: 'same-file' }, 'grok', conflict)).toBe(0)
})
it('extracts only explicit resume ids', () => {
diff --git a/cli/src/lib/tmux.ts b/cli/src/lib/tmux.ts
index 984f55cfb..c9100461b 100644
--- a/cli/src/lib/tmux.ts
+++ b/cli/src/lib/tmux.ts
@@ -1,9 +1,17 @@
/** tmux process matching, runtime validation, pane capture, and input injection. */
import { execFile, spawn } from 'child_process'
+import { readlink } from 'node:fs/promises'
+import { platform } from 'node:os'
import { basename } from 'path'
import { registry, type ProcessIdentity, type RegisteredSession } from './registry.js'
-import { engineBin } from './engineBin.js'
+import {
+ agentAliasOwner,
+ agentCommandOwnershipSnapshot,
+ enginePathOverride,
+ executableFileIdentity,
+ type AgentCommandOwnershipSnapshot,
+} from './engineBin.js'
function cleanPaneTitle(title: string): string | null {
const cleaned = title
@@ -34,6 +42,10 @@ export function listPaneTitles(): Promise<Map<string, string>> {
export interface ProcessRow extends ProcessIdentity {
parentPid: number
args: string
+ /** Ephemeral evidence only; never persisted or sent to another machine. */
+ imagePath?: string
+ imageFileKey?: string
+ entrypointFileKey?: string
}
function argvTokens(args: string): string[] {
@@ -79,6 +91,18 @@ function processEntrypoint(args: string): string {
return tokens[index] ?? ''
}
+function hasCursorPackageEntrypoint(args: string): boolean {
+ // Cursor's launcher uses `exec -a "$0" node .../index.js`, so argv[0] may stay `agent` instead of
+ // `node`. Restrict this scan to the executable prefix: prompt text can appear later and is not proof.
+ return argvTokens(args).slice(0, 8).some((token) =>
+ /cursor-agent[\/\\]versions[\/\\][^/\\]+[\/\\]index\.js$/i.test(token))
+}
+
+function agentAliasCandidate(row: Pick<ProcessRow, 'executable' | 'args'>): boolean {
+ if (basename(row.executable).toLowerCase() === 'agent') return true
+ return argvTokens(row.args).slice(0, 8).some((token) => basename(token).toLowerCase() === 'agent')
+}
+
/**
* One `ps -axo pid=,ppid=,comm=,lstart=,args=` line → a row.
@@ -107,8 +131,8 @@ export function parseProcessRow(line: string): ProcessRow | null {
}
/** The process table, or null when `ps` itself failed — "we could not look" is not "nothing is there". */
-function processRows(): Promise<ProcessRow[] | null> {
- return new Promise((resolve) => {
+async function processRows(): Promise<ProcessRow[] | null> {
+ const rows = await new Promise<ProcessRow[] | null>((resolve) => {
execFile('ps', ['-axo', 'pid=,ppid=,comm=,lstart=,args='], { timeout: 3000 }, (err, stdout) => {
if (err) { resolve(null); return }
const rows: ProcessRow[] = []
@@ -119,6 +143,69 @@ function processRows(): Promise<ProcessRow[] | null> {
resolve(rows)
})
})
+ return rows ? enrichProcessRows(rows) : null
+}
+
+function execText(command: string, args: string[], timeout: number): Promise<string | null> {
+ return new Promise((resolve) => {
+ execFile(command, args, { timeout }, (err, stdout) => resolve(err ? null : stdout))
+ })
+}
+
+/** macOS has no /proc; one lsof call resolves every collision candidate's executable image. */
+async function darwinProcessImages(pids: readonly number[]): Promise<Map<number, string>> {
+ if (!pids.length) return new Map()
+ const stdout = await execText('lsof', ['-a', '-p', pids.join(','), '-d', 'txt', '-Fn'], 3000)
+ const images = new Map<number, string>()
+ if (stdout === null) return images
+ let pid: number | null = null
+ let textFile = false
+ for (const line of stdout.split('\n')) {
+ if (/^p\d+$/.test(line)) {
+ pid = Number(line.slice(1))
+ textFile = false
+ } else if (line === 'ftxt') {
+ textFile = true
+ } else if (textFile && pid && line.startsWith('n') && !images.has(pid)) {
+ images.set(pid, line.slice(1))
+ textFile = false
+ }
+ }
+ return images
+}
+
+/**
+ * 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.
+ */
+export async function enrichProcessRows(rows: ProcessRow[]): Promise<ProcessRow[]> {
+ const candidates = rows.filter(agentAliasCandidate)
+ if (!candidates.length) return rows
+ const imagePaths = new Map<number, string>()
+ 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)
+ }))
+ } else if (platform() === 'darwin') {
+ for (const [pid, path] of await darwinProcessImages(candidates.map((row) => row.pid))) imagePaths.set(pid, path)
+ }
+
+ return rows.map((row) => {
+ if (!agentAliasCandidate(row)) return row
+ const imagePath = imagePaths.get(row.pid)
+ const image = imagePath ? executableFileIdentity(imagePath.replace(/ \(deleted\)$/, '')) : null
+ const entrypoint = processEntrypoint(row.args)
+ const entrypointIdentity = entrypoint.includes('/') || entrypoint.includes('\\')
+ ? executableFileIdentity(entrypoint)
+ : null
+ return {
+ ...row,
+ ...(imagePath && { imagePath }),
+ ...(image && { imageFileKey: image.fileKey }),
+ ...(entrypointIdentity && { entrypointFileKey: entrypointIdentity.fileKey }),
+ }
+ })
}
@@ -132,18 +219,19 @@ function panePid(pane: string): Promise<number | null> {
}
export function engineProcessMatchScore(
- row: Pick<ProcessRow, 'executable' | 'args'>,
+ row: Pick<ProcessRow, 'executable' | 'args' | 'imageFileKey' | 'entrypointFileKey'>,
engine: RegisteredSession['engine'],
+ ownership = agentCommandOwnershipSnapshot(),
): number {
const executable = basename(row.executable).toLowerCase()
const entrypoint = processEntrypoint(row.args).toLowerCase()
const entrybase = basename(entrypoint).toLowerCase()
- // A user may point an engine at a symlink/custom install through `<ENGINE>_PATH`. Treat that configured
- // executable exactly like the vendor command without baking its machine-specific directory into rules.
- const configured = engineBin(engine).toLowerCase()
- const configuredBase = basename(configured).toLowerCase()
- if (configuredBase && (executable === configuredBase || entrybase === configuredBase
- || row.executable.toLowerCase() === configured || entrypoint === configured)) return 4
+ // 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()
+ const configuredBase = basename(configured ?? '').toLowerCase()
+ if (configured && configuredBase !== 'agent' && (row.executable.toLowerCase() === configured
+ || entrypoint === configured || executable === configuredBase || entrybase === 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
@@ -151,8 +239,9 @@ export function engineProcessMatchScore(
return /@openai[\/\\]codex[\/\\]bin[\/\\]codex(?:\.js)?$/.test(entrypoint) ? 2 : 0
}
if (engine === 'cursor') {
- if (executable === 'agent' || executable === 'cursor-agent' || entrybase === 'agent' || entrybase === 'cursor-agent') return 3
- return /cursor-agent[\/\\]versions[\/\\][^/\\]+[\/\\]index\.js$/.test(entrypoint) ? 2 : 0
+ 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
@@ -207,19 +296,35 @@ export function engineProcessMatchScore(
return /\.amp[\/\\]bin[\/\\]amp$/.test(entrypoint) ? 2 : 0
}
if (engine === 'grok') {
- // Grok ships as a single binary at ~/.grok/bin/grok and keeps the bare executable name in tmux.
+ // 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 (executable === 'claude' || entrybase === 'claude') return 3
return /@anthropic-ai[\/\\]claude-code[\/\\]cli\.js$/.test(entrypoint) ? 2 : 0
}
+/** An unresolved top-level `agent` is a barrier: a nested sub-agent must not steal its tmux pane. */
+export function ambiguousAgentProcess(
+ row: Pick<ProcessRow, 'executable' | 'args' | 'imageFileKey' | 'entrypointFileKey'>,
+ ownership = agentCommandOwnershipSnapshot(),
+): boolean {
+ if (!agentAliasCandidate(row) || hasCursorPackageEntrypoint(row.args)) return false
+ const executable = basename(row.executable).toLowerCase()
+ const entrybase = basename(processEntrypoint(row.args)).toLowerCase()
+ if (executable === 'cursor-agent' || entrybase === 'cursor-agent' || executable === 'grok' || entrybase === 'grok') return false
+ const owner = agentAliasOwner([row.imageFileKey, row.entrypointFileKey], ownership)
+ return owner === 'unknown' || owner === 'conflict'
+}
+
function selectEngineProcess(
rows: ProcessRow[],
rootPid: number,
engine: RegisteredSession['engine'],
): ProcessRow | null {
+ const ownership = agentCommandOwnershipSnapshot()
const byPid = new Map(rows.map((row) => [row.pid, row]))
const children = new Map<number, ProcessRow[]>()
for (const row of rows) {
@@ -232,7 +337,7 @@ function selectEngineProcess(
while (queue.length > 0) {
const current = queue.shift()!
const row = byPid.get(current.pid)
- const score = row ? engineProcessMatchScore(row, engine) : 0
+ const score = row ? engineProcessMatchScore(row, engine, ownership) : 0
if (row && score > 0 && (!best || current.depth < best.depth || (current.depth === best.depth && score > best.score))) {
best = { row, depth: current.depth, score }
}
diff --git a/cli/src/lib/tmuxAgentDiscovery.real.spec.ts b/cli/src/lib/tmuxAgentDiscovery.real.spec.ts
index 66308b5db..8d100a315 100644
--- a/cli/src/lib/tmuxAgentDiscovery.real.spec.ts
+++ b/cli/src/lib/tmuxAgentDiscovery.real.spec.ts
@@ -1,11 +1,17 @@
import { execFile } from 'node:child_process'
import { mkdtemp, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
-import { join } from 'node:path'
+import { dirname, join } from 'node:path'
import { promisify } from 'node:util'
import { afterAll, describe, expect, it } from 'vitest'
import type { AgentEngine } from '../engines/types.js'
-import { ENGINE_CLI_COMMANDS, ENGINES } from './engineBin.js'
+import {
+ agentAliasOwner,
+ agentCommandOwnershipSnapshot,
+ ENGINE_CLI_COMMANDS,
+ ENGINES,
+ executableFileIdentity,
+} from './engineBin.js'
import { probeTmuxAgents } from './tmuxAgentDiscovery.js'
const exec = promisify(execFile)
@@ -13,6 +19,20 @@ const realDescribe = process.env.RUN_REAL_TMUX_DISCOVERY === '1' ? describe : de
const createdSessions = new Set<string>()
const engines: Array<[AgentEngine, string]> = ENGINES.map((engine) => [engine, ENGINE_CLI_COMMANDS[engine]])
+const ownership = agentCommandOwnershipSnapshot()
+const installedAgentAliases: Array<[AgentEngine, string]> = []
+const seenAgentAliases = new Set<string>()
+for (const [engine, candidates] of [
+ ['cursor', ownership.cursorAgentCandidates],
+ ['grok', ownership.grokCandidates],
+] as const) {
+ for (const candidate of candidates) {
+ const alias = executableFileIdentity(join(dirname(candidate.path), 'agent'))
+ if (!alias || seenAgentAliases.has(alias.realPath) || agentAliasOwner([alias.fileKey], ownership) !== engine) continue
+ seenAgentAliases.add(alias.realPath)
+ installedAgentAliases.push([engine, alias.path])
+ }
+}
async function tmux(args: string[]): Promise<string> {
return (await exec('tmux', args, { timeout: 5_000 })).stdout.trim()
@@ -88,4 +108,28 @@ realDescribe.sequential('real installed CLI process discovery', () => {
await rm(dir, { recursive: true, force: true })
}
}, 35_000)
+
+ it.each(installedAgentAliases)('classifies installed %s alias named agent from its executable identity', async (engine, path) => {
+ const dir = await mkdtemp(join(tmpdir(), `harness-real-agent-alias-${engine}-`))
+ const session = `harness-real-${process.pid}-${engine}-agent-alias`
+ createdSessions.add(session)
+ try {
+ await tmux(['new-session', '-d', '-s', session, '-c', dir])
+ const pane = await tmux(['list-panes', '-t', session, '-F', '#{pane_id}'])
+ await tmux(['send-keys', '-t', pane, '-l', '--', path])
+ await tmux(['send-keys', '-t', pane, 'C-m'])
+ const discovered = await eventually(async () => {
+ const result = await probeTmuxAgents()
+ if (!result.ok) throw new Error(result.error)
+ const inPane = result.agents.filter((candidate) => candidate.tmuxPane === pane)
+ return inPane.length === 1 && inPane[0].engine === engine ? inPane[0] : null
+ })
+ const capture = await tmux(['capture-pane', '-p', '-t', pane]).catch(() => '')
+ expect(discovered, `${path} was not classified as ${engine} in ${pane}\n${capture}`).not.toBeNull()
+ } finally {
+ await exec('tmux', ['kill-session', '-t', session], { timeout: 5_000 }).catch(() => {})
+ createdSessions.delete(session)
+ await rm(dir, { recursive: true, force: true })
+ }
+ }, 35_000)
})
diff --git a/cli/src/lib/tmuxAgentDiscovery.spec.ts b/cli/src/lib/tmuxAgentDiscovery.spec.ts
index 4cd28eab2..40caf288f 100644
--- a/cli/src/lib/tmuxAgentDiscovery.spec.ts
+++ b/cli/src/lib/tmuxAgentDiscovery.spec.ts
@@ -1,5 +1,6 @@
import { describe, expect, it, vi } from 'vitest'
import type { AgentEngine } from '../engines/types.js'
+import type { AgentCommandOwnershipSnapshot } from './engineBin.js'
import type { ProcessRow } from './tmux.js'
import type { RegisteredSession } from './registry.js'
import {
@@ -15,12 +16,20 @@ const pane = { tmuxPane: '%1', rootPid: 1, cwd: '/work/demo' }
const row = (pid: number, parentPid: number, executable: string, args = executable): ProcessRow => ({
pid, parentPid, executable, args, startMarker: START,
})
+const ownership = (cursor: string[] = [], grok: string[] = []): AgentCommandOwnershipSnapshot => ({
+ cursorFileKeys: new Set(cursor),
+ grokFileKeys: new Set(grok),
+ conflictingFileKeys: new Set(cursor.filter((key) => grok.includes(key))),
+ agentCandidates: [],
+ cursorAgentCandidates: [],
+ grokCandidates: [],
+})
describe('tmux process agent snapshot discovery', () => {
const fixtures: Array<[AgentEngine, string, string]> = [
['claude', 'claude', 'claude'],
['codex', 'codex', 'codex'],
- ['cursor', 'agent', 'agent'],
+ ['cursor', 'cursor-agent', 'cursor-agent'],
['opencode', 'opencode', 'opencode'],
['pi', 'pi', 'pi'],
['hermes', 'python', '/opt/hermes-agent/hermes'],
@@ -38,6 +47,68 @@ describe('tmux process agent snapshot discovery', () => {
expect(result.agents[0]).toMatchObject({ engine, tmuxPane: '%1', cwd: '/work/demo' })
})
+ it('classifies each vendor agent alias from the executable file identity', () => {
+ const commands = ownership(['cursor-file'], ['grok-file'])
+ const cursorRow = { ...row(2, 1, 'agent'), imageFileKey: 'cursor-file' }
+ const grokRow = { ...row(2, 1, 'agent'), imageFileKey: 'grok-file' }
+
+ expect(discoverTmuxAgentsFromSnapshot([pane], [row(1, 0, 'zsh'), cursorRow], 900, commands)
+ .agents[0]?.engine).toBe('cursor')
+ expect(discoverTmuxAgentsFromSnapshot([pane], [row(1, 0, 'zsh'), grokRow], 900, commands)
+ .agents[0]?.engine).toBe('grok')
+ })
+
+ it('does not guess an unresolved agent alias and lets a pane-scoped vendor hook resolve it', () => {
+ const commands = ownership(['cursor-file'], ['grok-file'])
+ const rows = [row(1, 0, 'zsh'), row(2, 1, 'agent')]
+ const unresolved = discoverTmuxAgentsFromSnapshot([pane], rows, 900, commands)
+ expect(unresolved.agents).toEqual([])
+ expect(unresolved.ambiguousPanes.has('%1')).toBe(true)
+
+ const hinted = discoverTmuxAgentsFromSnapshot(
+ [pane], rows, 900, commands, new Map([['%1', 'grok']]),
+ )
+ expect(hinted.agents[0]?.engine).toBe('grok')
+
+ const conflict = ownership(['same-file'], ['same-file'])
+ const conflicted = discoverTmuxAgentsFromSnapshot(
+ [pane], [row(1, 0, 'zsh'), { ...row(2, 1, 'agent'), imageFileKey: 'same-file' }],
+ 900, conflict, new Map([['%1', 'grok']]),
+ )
+ expect(conflicted.agents).toEqual([])
+ expect(conflicted.ambiguousPanes.has('%1')).toBe(true)
+ })
+
+ it('does not let a nested sub-agent steal a pane from an unresolved top-level agent alias', () => {
+ const result = discoverTmuxAgentsFromSnapshot(
+ [pane],
+ [row(1, 0, 'zsh'), row(2, 1, 'agent'), row(3, 2, 'codex')],
+ 900,
+ ownership(),
+ )
+ expect(result.agents).toEqual([])
+ expect(result.ambiguousPanes.has('%1')).toBe(true)
+ })
+
+ it('keeps a file-identified Grok parent while agent-named sub-agent PIDs churn', () => {
+ const commands = ownership(['cursor-file'], ['grok-file'])
+ const first = discoverTmuxAgentsFromSnapshot(
+ [pane],
+ [row(1, 0, 'zsh'), { ...row(2, 1, 'agent'), imageFileKey: 'grok-file' }, row(3, 2, 'cursor-agent')],
+ 900,
+ commands,
+ )
+ const second = discoverTmuxAgentsFromSnapshot(
+ [pane],
+ [row(1, 0, 'zsh'), { ...row(2, 1, 'agent'), imageFileKey: 'grok-file' }, row(30, 2, 'cursor-agent')],
+ 900,
+ commands,
+ )
+ expect(first.agents[0]?.engine).toBe('grok')
+ expect(first.agents[0]?.processIdentity.pid).toBe(2)
+ expect(runtimeKey(first.agents[0])).toBe(runtimeKey(second.agents[0]))
+ })
+
const wrappers: Array<[AgentEngine, string, string]> = [
['claude', 'node', '/opt/lib/node_modules/@anthropic-ai/claude-code/cli.js'],
['codex', 'node', '/opt/lib/node_modules/@openai/codex/bin/codex.js'],
diff --git a/cli/src/lib/tmuxAgentDiscovery.ts b/cli/src/lib/tmuxAgentDiscovery.ts
index eba62eec5..6aa89efcd 100644
--- a/cli/src/lib/tmuxAgentDiscovery.ts
+++ b/cli/src/lib/tmuxAgentDiscovery.ts
@@ -7,10 +7,22 @@
*/
import { execFile } from 'node:child_process'
-import { ENGINES } from './engineBin.js'
+import {
+ agentAliasOwner,
+ agentCommandOwnershipSnapshot,
+ ENGINES,
+ type AgentCommandOwnershipSnapshot,
+} from './engineBin.js'
import type { AgentEngine } from '../engines/types.js'
import type { ProcessIdentity, RegisteredSession } from './registry.js'
-import { engineProcessMatchScore, parseProcessRow, resumeSessionId, type ProcessRow } from './tmux.js'
+import {
+ ambiguousAgentProcess,
+ engineProcessMatchScore,
+ enrichProcessRows,
+ parseProcessRow,
+ resumeSessionId,
+ type ProcessRow,
+} from './tmux.js'
export interface TmuxPaneSnapshot {
tmuxPane: string
@@ -37,7 +49,7 @@ export interface TmuxAgentDiscoveryDeps {
onDiscovered: (agent: DiscoveredTmuxAgent) => void | Promise<void>
onObserved: (agent: DiscoveredTmuxAgent, current: RegisteredSession) => void | Promise<void>
onRemoved: (agent: RegisteredSession, reason: string) => void | Promise<void>
- probe?: (daemonPid: number) => Promise<TmuxAgentProbe>
+ probe?: (daemonPid: number, hints?: ReadonlyMap<string, AgentEngine>) => Promise<TmuxAgentProbe>
daemonPid?: number
}
@@ -97,26 +109,40 @@ function paneOwner(
pane: TmuxPaneSnapshot,
rows: readonly ProcessRow[],
excluded: ReadonlySet<number>,
+ ownership: AgentCommandOwnershipSnapshot,
+ hintedEngine?: AgentEngine,
): { agent: DiscoveredTmuxAgent | null; ambiguous: boolean } {
const byPid = new Map(rows.map((row) => [row.pid, row]))
const children = childrenByParent(rows)
const queue: Array<{ pid: number; depth: number }> = [{ pid: pane.rootPid, depth: 0 }]
const matches: Array<{ row: ProcessRow; engine: AgentEngine; depth: number; score: number }> = []
+ let unresolvedAliasDepth = Number.POSITIVE_INFINITY
while (queue.length) {
const current = queue.shift()!
const row = byPid.get(current.pid)
if (row && !excluded.has(row.pid)) {
for (const engine of ENGINES) {
- const score = engineProcessMatchScore(row, engine)
+ const score = engineProcessMatchScore(row, engine, ownership)
if (score > 0) matches.push({ row, engine, depth: current.depth, score })
}
+ if (ambiguousAgentProcess(row, ownership)) {
+ // A vendor hook is pane-scoped evidence from the running CLI. It may resolve an otherwise bare
+ // `agent`, but can never override strong file/package evidence for the other vendor.
+ const aliasOwner = agentAliasOwner([row.imageFileKey, row.entrypointFileKey], ownership)
+ if (aliasOwner === 'unknown' && (hintedEngine === 'cursor' || hintedEngine === 'grok')) {
+ matches.push({ row, engine: hintedEngine, depth: current.depth, score: 1 })
+ } else {
+ unresolvedAliasDepth = Math.min(unresolvedAliasDepth, current.depth)
+ }
+ }
}
for (const child of children.get(current.pid) ?? []) queue.push({ pid: child.pid, depth: current.depth + 1 })
}
- if (!matches.length) return { agent: null, ambiguous: false }
+ if (!matches.length) return { agent: null, ambiguous: Number.isFinite(unresolvedAliasDepth) }
const shallowest = Math.min(...matches.map((match) => match.depth))
+ if (unresolvedAliasDepth <= shallowest) return { agent: null, ambiguous: true }
const atDepth = matches.filter((match) => match.depth === shallowest)
const strongest = Math.max(...atDepth.map((match) => match.score))
const finalists = atDepth.filter((match) => match.score === strongest)
@@ -142,12 +168,14 @@ export function discoverTmuxAgentsFromSnapshot(
panes: readonly TmuxPaneSnapshot[],
rows: readonly ProcessRow[],
daemonPid: number,
+ ownership = agentCommandOwnershipSnapshot(),
+ hints: ReadonlyMap<string, AgentEngine> = new Map(),
): Extract<TmuxAgentProbe, { ok: true }> {
const excluded = daemonDescendants(rows, daemonPid)
const agents: DiscoveredTmuxAgent[] = []
const ambiguousPanes = new Set<string>()
for (const pane of panes) {
- const owner = paneOwner(pane, rows, excluded)
+ const owner = paneOwner(pane, rows, excluded, ownership, hints.get(pane.tmuxPane))
if (owner.ambiguous) ambiguousPanes.add(pane.tmuxPane)
else if (owner.agent) agents.push(owner.agent)
}
@@ -155,15 +183,25 @@ export function discoverTmuxAgentsFromSnapshot(
}
/** One tmux call plus one ps call for a complete reconciliation pass. */
-export async function probeTmuxAgents(daemonPid = process.pid): Promise<TmuxAgentProbe> {
+export async function probeTmuxAgents(
+ daemonPid = process.pid,
+ hints: ReadonlyMap<string, AgentEngine> = new Map(),
+): Promise<TmuxAgentProbe> {
const [tmux, ps] = await Promise.all([
execText('tmux', ['list-panes', '-a', '-F', '#{pane_id}\t#{pane_pid}\t#{pane_current_path}'], 2_000),
execText('ps', ['-axo', 'pid=,ppid=,comm=,lstart=,args='], 3_000),
])
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 rows = ps.stdout.split('\n').map(parseProcessRow).filter((row): row is ProcessRow => row !== null)
- return discoverTmuxAgentsFromSnapshot(parsePanes(tmux.stdout), rows, daemonPid)
+ const parsed = ps.stdout.split('\n').map(parseProcessRow).filter((row): row is ProcessRow => row !== null)
+ const rows = await enrichProcessRows(parsed)
+ return discoverTmuxAgentsFromSnapshot(
+ parsePanes(tmux.stdout),
+ rows,
+ daemonPid,
+ agentCommandOwnershipSnapshot(),
+ hints,
+ )
}
export function sameRuntime(
@@ -193,6 +231,8 @@ export class TmuxAgentReconciler {
private pending = false
private inFlight: Promise<void> | null = null
private timer: NodeJS.Timeout | null = null
+ private readonly hints = new Map<string, AgentEngine>()
+ private readonly warnedAmbiguousPanes = new Set<string>()
constructor(private readonly deps: TmuxAgentDiscoveryDeps) {}
@@ -218,6 +258,12 @@ export class TmuxAgentReconciler {
return this.inFlight
}
+ /** A validated vendor hook may resolve the otherwise colliding bare `agent` command in one pane. */
+ triggerHint(tmuxPane: string, engine: AgentEngine): Promise<void> {
+ this.hints.set(tmuxPane, engine)
+ return this.trigger()
+ }
+
private async drain(): Promise<void> {
while (this.pending) {
this.pending = false
@@ -226,11 +272,21 @@ export class TmuxAgentReconciler {
}
private async reconcileOnce(): Promise<void> {
- const probe = await (this.deps.probe ?? probeTmuxAgents)(this.deps.daemonPid ?? process.pid)
+ const hints = new Map(this.hints)
+ const probe = await (this.deps.probe ?? probeTmuxAgents)(this.deps.daemonPid ?? process.pid, hints)
if (!probe.ok) {
console.warn(`[discovery] ${probe.error}; keeping ${this.deps.current().length} agent(s)`)
return
}
+ for (const pane of hints.keys()) this.hints.delete(pane)
+ for (const pane of probe.ambiguousPanes) {
+ if (this.warnedAmbiguousPanes.has(pane)) continue
+ this.warnedAmbiguousPanes.add(pane)
+ console.warn(`[discovery] ${pane} has an unresolved agent command; set CURSOR_PATH or GROK_PATH to an absolute vendor CLI path`)
+ }
+ for (const pane of [...this.warnedAmbiguousPanes]) {
+ if (!probe.ambiguousPanes.has(pane)) this.warnedAmbiguousPanes.delete(pane)
+ }
const observedKeys = new Set(probe.agents.map(runtimeKey))
for (const key of [...this.suppressed]) if (!observedKeys.has(key)) this.suppressed.delete(key)