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.

feat(engines): install an engine the machine does not have, in the pane that becomes the agent

bubu-duduf2ed57a2379f
diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.ts
index 19c33c1c9..b67e7f644 100644
--- a/cli/src/backendSocket.ts
+++ b/cli/src/backendSocket.ts
@@ -23,6 +23,8 @@ import { registry, projectDisplayName, type RegisteredSession } from './lib/regi
import { ENGINES, type AgentEngine } from './engines/types.js'
import { listDir } from './lib/fsBrowse.js'
import { parseGridLaunchOverride, type GridLaunchOverride } from './lib/gridLaunch.js'
+import { probeEngines } from './lib/engineProbe.js'
+import { engineInstallRecipe } from './lib/engineInstall.js'
import { agentFrame, type AgentFrame } from './lib/agentFrame.js'
import { routeVoiceTask } from './lib/voiceRouter.js'
import { tailFile } from './lib/sessions.js'
@@ -1338,6 +1340,34 @@ export class BackendSocket {
return
}
+ case 'engines_probe': {
+ // Which engines this machine has, asked BEFORE a create rather than discovered by one
+ // failing. Answered here — on the machine in question — because a Mac and the Docker rig
+ // routinely hold different engines, and an availability list computed anywhere else is
+ // wrong for exactly the remote case this request exists to serve.
+ //
+ // `engines` narrows the probe to what the caller is showing; an absent or malformed list
+ // means "all of them", so an older app that sends nothing still gets a usable answer.
+ const asked = Array.isArray(payload.engines)
+ ? payload.engines.filter((id): id is AgentEngine =>
+ typeof id === 'string' && (ENGINES as readonly string[]).includes(id))
+ : undefined
+ const availability = await probeEngines(asked && asked.length > 0 ? asked : undefined)
+ reply(type, requestId, {
+ engines: availability.map((entry) => ({
+ engine: entry.engine,
+ installed: entry.installed,
+ command: entry.command,
+ installable: entry.installable,
+ // The line the user is about to consent to. Sent with the probe so the dialog can name
+ // it without a second round trip — and so the machine that will RUN it is the machine
+ // that said what it is.
+ installCommand: entry.installable ? engineInstallRecipe(entry.engine)?.command ?? null : null,
+ })),
+ })
+ return
+ }
+
case 'agent_recent': {
// Device tile restore at boot: the session's persisted LLM turn-summary (recap + body),
// mirroring the hosted runtime’s SessionService.getRecentEvents. Empty until a turn was summarized
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index 35580ef40..f32d7d547 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -44,7 +44,9 @@ import { AuthSessionError, AuthSessionManager, clearAuthSession, readAuthSession
import { handOffToGrid } from './lib/gridHandoff.js'
import { passThroughToGridLogout } from './lib/gridLogout.js'
import { warnIfGridSignInRemains } from './lib/gridCredentials.js'
-import { ENGINE_CLI_COMMANDS, ENGINES } from './lib/engineBin.js'
+import { ENGINE_CLI_COMMANDS, ENGINES, engineBin } from './lib/engineBin.js'
+import type { AgentEngine } from './engines/types.js'
+import { engineInstallRecipe } from './lib/engineInstall.js'
import { buildEngineCommandArgv, buildEngineLaunchArgv, commandAvailableInInteractiveShell, interactiveEngineShell } from './lib/engineLaunch.js'
import { buildGridEngineLaunch, describeGridLaunch, gridEnvVarNames } from './lib/gridLaunch.js'
import { writeGridConfigDir } from './lib/gridConfigDir.js'
@@ -60,6 +62,7 @@ import {
captureTmuxPane,
clearPaneRemainOnExit,
resolvePaneEngineProcess,
+ resolvePaneRootProcess,
tmuxPaneProcessTree,
tmuxPaneState,
type TmuxPaneState,
@@ -3052,9 +3055,28 @@ async function runForeground(session: AuthSession): Promise<void> {
// normally launched one. The key is never printed.
console.log(describeGridLaunch(engine, grid))
}
- const launchOptions = { bypassPermission, extraArgs: gridLaunch?.args }
+ // Is the engine even here? Asked BEFORE the pane opens, because the answer changes what the pane
+ // is told to run. The New Agent dialog asked the same question through `engines_probe` and showed
+ // the user the line below — but a dialog can sit open for minutes, and the machine is what
+ // decides, so the check is repeated here rather than trusted from the wire. Nothing from the
+ // request reaches `install`: it is looked up from our own table by engine id.
+ const installFirst = await (async (): Promise<string | undefined> => {
+ const recipe = engineInstallRecipe(engine)
+ if (!recipe) return undefined
+ try {
+ if (await commandAvailableInInteractiveShell(engineBin(engine))) return undefined
+ } catch {
+ // The probe failing is not evidence the engine is missing. Launch as we always did and let
+ // the existing diagnosis explain a real absence — prepending an install on a machine that
+ // already has the engine would reinstall it behind the user's back.
+ return undefined
+ }
+ return recipe.command
+ })()
+ const launchOptions = { bypassPermission, extraArgs: gridLaunch?.args, installFirst }
const command = buildEngineCommandArgv(engine, launchOptions)
const argv = buildEngineLaunchArgv(engine, launchOptions)
+ if (installFirst) console.log(`[agent] create ${engine} · installing first · ${installFirst}`)
const spawned = await tmuxBackend.create({
cwd,
label,
@@ -3074,7 +3096,91 @@ async function runForeground(session: AuthSession): Promise<void> {
detail: spawned.reason,
}
}
+ /**
+ * Follow a pane through its install, for the one thing the early return leaves undone.
+ *
+ * `create` sets `remain-on-exit` so a pane that dies can still be read, and the discovery loop
+ * clears it the moment a real agent appears. The install path returns before that loop runs, so
+ * nothing would ever clear it — and an agent whose pane lingers as a corpse after the engine
+ * quits behaves unlike every other agent on the machine.
+ *
+ * The asymmetry is deliberate and is the whole design: cleared on SUCCESS, left in place on
+ * FAILURE. A failed install must keep its pane, because the npm output in it is the only
+ * explanation the person will get, and this feature's answer to a failed install is to show them
+ * the reason rather than retry on their behalf.
+ *
+ * Fire-and-forget, and it must never throw into the caller: this is bookkeeping, and an agent
+ * that installed correctly is not made wrong by a tmux option that stayed set.
+ */
+ async function watchInstallingPane(
+ runtime: TmuxRuntimeRef,
+ installingEngine: AgentEngine,
+ agentId: string,
+ ): Promise<void> {
+ // Generous, because it is bounded by the slowest thing a vendor's installer does on a cold
+ // cache over a bad connection, not by anything the app is waiting for. Nothing blocks on it.
+ const budgetMs = 10 * 60_000
+ const startedAt = Date.now()
+ try {
+ while (Date.now() - startedAt < budgetMs) {
+ await new Promise((resolve) => setTimeout(resolve, 3_000))
+ const paneState = await tmuxPaneState(runtime.paneId)
+ // Dead pane: either the install failed (keep remain-on-exit — the output IS the report) or
+ // the agent was closed. Either way there is nothing left to clear.
+ if (!paneState || paneState.dead) return
+ // Registry entry gone — the agent was deleted while installing. Stop following it.
+ if (!registry.byAgent(agentId)) return
+ const live = await resolvePaneEngineProcess(runtime.paneId, installingEngine)
+ if (!live) continue
+ // The engine exists now. Discovery adopts the record on its own; this only returns the pane
+ // to tmux's normal disposal, the same call the discovery loop makes.
+ await clearPaneRemainOnExit(runtime.paneId)
+ console.log(`[agent] install finished · ${installingEngine} · agent ${agentId}`)
+ return
+ }
+ console.warn(`[agent] install watch gave up after ${Math.round(budgetMs / 60_000)}m · ${installingEngine} · agent ${agentId}`)
+ } catch (error) {
+ console.warn(`[agent] install watch failed · ${installingEngine} · ${error instanceof Error ? error.message : error}`)
+ }
+ }
+
const createdAt = Date.now()
+ if (installFirst) {
+ // An install runs for tens of seconds; the discovery budget below is eight, and the app gives
+ // up on this reply at twenty. Waiting is therefore not on the table — the create would report
+ // ENGINE_DID_NOT_START for a pane that is working perfectly.
+ //
+ // So the agent is registered NOW, against the process that actually owns the pane: the user's
+ // shell, running the installer. That record is what the app opens a terminal onto, which is the
+ // whole point — the install is watched, not waited out behind a spinner.
+ //
+ // It is a placeholder for seconds, not a second kind of agent. When the engine execs, discovery
+ // registers it against this same pane and `openProcessAgent` ADOPTS this record in place — the
+ // `routeAgent` branch in registry.ts, which matches on terminal route exactly while an agent has
+ // no engine session bound. Same agentId, same tile, no flicker.
+ const placeholder = await resolvePaneRootProcess(spawned.runtime.paneId)
+ const opened = placeholder
+ ? registry.openProcessAgent({
+ engine,
+ runtimes: [spawned.runtime],
+ cwd,
+ // Deliberately no `grid`: the registry re-derives that from the LIVE process on every
+ // discovery, never from a declaration. Declaring it here would state, of a pane currently
+ // running npm, which grid its engine is on.
+ processIdentity: placeholder,
+ })
+ : null
+ if (opened) {
+ registry.setTerminalAvailable(opened.entry.agentId, true)
+ void watchInstallingPane(spawned.runtime, engine, opened.entry.agentId)
+ console.log(`[agent] create ${engine} · pane open, installing · agent ${opened.entry.agentId}`)
+ return { ok: true, session: opened.entry }
+ }
+ // No placeholder identity means `ps` or tmux could not be read — not that the pane is bad. Fall
+ // through to the normal path: the install still runs, and the worst case is the reply the app
+ // already knows how to show while the periodic reconcile picks the agent up behind it.
+ console.warn(`[agent] create ${engine} · installing, but the pane's process could not be read; falling back to discovery`)
+ }
// The launch runs the user's INTERACTIVE login shell before `exec`ing the engine, and that shell
// is the slow half: ~0.9s on a plain zsh, before the engine has even begun. Engine startup then
// lands past 1.3s — measured on one machine, grok at 1.38s, codex at 1.41s, claude at 1.52s. The
diff --git a/cli/src/lib/engineInstall.ts b/cli/src/lib/engineInstall.ts
new file mode 100644
index 000000000..2ead2f065
--- /dev/null
+++ b/cli/src/lib/engineInstall.ts
@@ -0,0 +1,115 @@
+/**
+ * Installing an engine that is not on the target machine yet.
+ *
+ * The New Agent dialog lists every engine Harness supports, not every engine the machine HAS — and
+ * until now the difference only surfaced as a failed create: tmux ran a command that did not exist,
+ * the pane said `command not found`, and the daemon reported `ENGINE_NOT_INSTALLED` after the fact
+ * (see the probe in `engineLaunch.ts` and its caller in `cli.ts`). This module is the other half:
+ * what to RUN so that the engine exists, so the dialog can offer the install instead of the failure.
+ *
+ * ## Every entry is the vendor's own published install line
+ *
+ * Nothing here is derived, and nothing is a plausible-looking package name. An engine whose install
+ * could not be verified against the vendor's own registry entry or documentation gets **no entry**,
+ * and the dialog then says the engine is missing without offering to fix it. A missing entry is a
+ * smaller lie than a wrong one.
+ *
+ * Verify against the VENDOR, not against a plausible package name. The unscoped `pi-coding-agent`
+ * on npm is "Placeholder package name reservation" with no bin, while pi.dev publishes
+ * `@earendil-works/pi-coding-agent` — installing the first would leave a machine with no `pi` and
+ * no error, having just reported success.
+ *
+ * ## Why the command is a string, and why it runs in the user's own shell
+ *
+ * These are the lines a person would paste. They are run through the SAME interactive shell that
+ * launches an agent (`interactiveEngineShell`), for the reason that shell exists at all: a detached
+ * daemon does not have the user's PATH, and `npm`, `node` and `curl` frequently arrive through
+ * `.zshrc`/`.bashrc` (nvm, asdf, vendor installers). Installing with the daemon's PATH would either
+ * fail to find npm or install into a prefix the agent's own shell cannot then see — the worst
+ * outcome, because it looks like success and leaves the engine still missing.
+ *
+ * ## What this module deliberately does NOT do
+ *
+ * It does not sudo, does not choose a package manager on the user's behalf beyond what the vendor
+ * publishes, and does not retry. An install that fails leaves its output in the pane and says so;
+ * the person reads the reason and fixes it. A privileged retry is how a tool ends up owning a
+ * machine's global prefix without ever being asked.
+ */
+
+import type { AgentEngine } from '../engines/types.js'
+
+/** One engine's published install line. */
+export interface EngineInstallRecipe {
+ /**
+ * The shell command, exactly as the vendor publishes it.
+ *
+ * Runs in the user's interactive shell on the TARGET machine — which is not necessarily the
+ * machine the person is sitting at, so it must not assume anything about the operating system
+ * beyond a POSIX shell.
+ */
+ readonly command: string
+ /**
+ * Where the line above was read from. Kept in the code rather than a commit message because the
+ * next person to touch this needs to re-verify it, and a URL in a diff is not findable later.
+ */
+ readonly source: string
+}
+
+/**
+ * The engines Harness can install, and how.
+ *
+ * `Partial` on purpose — an absent key is the honest answer for an engine whose install we cannot
+ * cite, and [engineInstallRecipe] returns null for it rather than guessing.
+ */
+export const ENGINE_INSTALL: Partial<Record<AgentEngine, EngineInstallRecipe>> = {
+ claude: {
+ command: 'npm install -g @anthropic-ai/claude-code',
+ source: 'npm: @anthropic-ai/claude-code — the same package the remote-machine rig installs',
+ },
+ codex: {
+ command: 'npm install -g @openai/codex',
+ source: 'npm: @openai/codex — matches the `@openai/codex/bin/codex.js` runtime evidence in engines/README.md',
+ },
+ copilot: {
+ command: 'npm install -g @github/copilot',
+ source: 'npm: @github/copilot — matches the `@github/copilot` npm loader in engines/README.md',
+ },
+ opencode: {
+ command: 'npm install -g opencode-ai',
+ source: 'npm: opencode-ai — matches the `opencode-ai/bin/opencode.exe` runtime evidence in engines/README.md',
+ },
+ hermes: {
+ // Not npm. Hermes is a Python agent whose installer builds a venv and links an entrypoint, which
+ // is why a broken checkout shows up as a DANGLING SYMLINK on ~/.local/bin/hermes rather than a
+ // missing file — and why the availability probe tests `-f` and `-x`, not just `command -v`.
+ command: 'curl -fsSL https://hermes-agent.nousresearch.com/install.sh | bash',
+ source: 'NousResearch/hermes-agent README — "Quick Install", Linux/macOS/WSL2/Termux',
+ },
+ pi: {
+ // `--ignore-scripts` is the vendor's own line, not a hardening we added — pi.dev publishes it
+ // that way, and dropping it is not ours to decide.
+ //
+ // The package is SCOPED, and the unscoped `pi-coding-agent` is a different thing entirely:
+ // "Placeholder package name reservation", version 0.0.1, no bin. Installing that one leaves a
+ // machine with no `pi` and no error, which is the exact failure this comment exists to prevent
+ // the next person from re-introducing by "simplifying" the name.
+ command: 'npm install -g --ignore-scripts @earendil-works/pi-coding-agent',
+ source: 'pi.dev — its published install line; npm @earendil-works/pi-coding-agent ships bin `pi`',
+ },
+}
+
+/** The install line for an engine, or null when Harness has none it can cite. */
+export function engineInstallRecipe(engine: AgentEngine): EngineInstallRecipe | null {
+ return ENGINE_INSTALL[engine] ?? null
+}
+
+/**
+ * The engines an install can be offered for.
+ *
+ * Mirrored by `kInstallableEngines` in the desktop app so the dialog can label a row before it has
+ * asked the machine anything — the same arrangement `kGridCapableEngines` has with `gridLaunch.ts`.
+ * Keep the two in sync.
+ */
+export const INSTALLABLE_ENGINES: ReadonlySet<AgentEngine> = new Set(
+ Object.keys(ENGINE_INSTALL) as AgentEngine[],
+)
diff --git a/cli/src/lib/engineLaunch.spec.ts b/cli/src/lib/engineLaunch.spec.ts
index deb8e4e9c..9a5e2325e 100644
--- a/cli/src/lib/engineLaunch.spec.ts
+++ b/cli/src/lib/engineLaunch.spec.ts
@@ -130,3 +130,76 @@ describe('commandAvailableInInteractiveShell', () => {
await expect(commandAvailableInInteractiveShell('missing-engine', bashProbeShell())).resolves.toBe(false)
})
})
+
+describe('buildEngineLaunchArgv with installFirst', () => {
+ // Everything here is about ONE rule: the engine must not be exec'd after an install that failed.
+ // Doing so reproduces the `command not found` this feature exists to replace, with a screenful of
+ // installer output above it to bury the cause.
+ const script = (install: string): string =>
+ buildEngineLaunchArgv('opencode', { installFirst: install }, '/bin/zsh')[2]
+
+ it('leaves the plain launch alone when nothing has to be installed', () => {
+ expect(buildEngineLaunchArgv('opencode', {}, '/bin/zsh')[2]).toBe('exec "$@"')
+ })
+
+ it('keeps the engine argv positional, so the shell never re-parses a path or a flag', () => {
+ const argv = buildEngineLaunchArgv('opencode', {
+ installFirst: 'npm install -g opencode-ai',
+ bypassPermission: true,
+ }, '/bin/zsh')
+ expect(argv.slice(0, 2)).toEqual(['/bin/zsh', '-lic'])
+ expect(argv.slice(3)).toEqual(['harness-engine', ...buildEngineCommandArgv('opencode', { bypassPermission: true })])
+ expect(argv[2]).toContain('exec "$@"')
+ })
+
+ it('runs the engine only when the install succeeded', async () => {
+ await expect(runPaneScript(script('true'))).resolves.toMatchObject({ code: 0, ranEngine: true })
+ })
+
+ it('does not run the engine when the install returns a failure', async () => {
+ const result = await runPaneScript(script('false'))
+ expect(result.ranEngine).toBe(false)
+ expect(result.code).toBe(1)
+ expect(result.stdout).toContain('the install failed')
+ })
+
+ it('does not run the engine when the install command is not there at all', async () => {
+ const result = await runPaneScript(script('harness-no-such-installer --please'))
+ expect(result.ranEngine).toBe(false)
+ expect(result.code).toBe(1)
+ })
+
+ it('prints the command before running it, so a long install is not a hung pane', () => {
+ expect(script('npm install -g opencode-ai')).toContain('npm install -g opencode-ai')
+ })
+
+ it("survives an install line carrying a quote, rather than ending the shell's string", async () => {
+ // `curl … | bash` is already in the table; a quoted argument is the next shape to arrive, and an
+ // install line is a constant in our own source — so the failure mode is a broken pane, not an
+ // injection. It still must not break.
+ const result = await runPaneScript(script(`sh -c 'exit 3'`))
+ expect(result.ranEngine).toBe(false)
+ expect(result.code).toBe(1)
+ })
+})
+
+/** Run one generated pane script under /bin/sh and report what it did. */
+async function runPaneScript(
+ paneScript: string,
+): Promise<{ code: number; stdout: string; ranEngine: boolean }> {
+ const { execFile } = await import('node:child_process')
+ const marker = 'HARNESS-TEST-ENGINE-RAN'
+ return await new Promise((resolve) => {
+ execFile(
+ '/bin/sh',
+ ['-c', paneScript, 'harness-engine', 'printf', `${marker}\n`],
+ { timeout: 10_000 },
+ (error, stdout) => {
+ const code = error && typeof (error as { code?: unknown }).code === 'number'
+ ? (error as unknown as { code: number }).code
+ : 0
+ resolve({ code, stdout, ranEngine: stdout.includes(marker) })
+ },
+ )
+ })
+}
diff --git a/cli/src/lib/engineLaunch.ts b/cli/src/lib/engineLaunch.ts
index 26510620b..1678374cc 100644
--- a/cli/src/lib/engineLaunch.ts
+++ b/cli/src/lib/engineLaunch.ts
@@ -40,6 +40,21 @@ export interface LaunchCommandOptions {
* never travels this way.
*/
extraArgs?: readonly string[]
+ /**
+ * A shell line to run in the pane BEFORE the engine, from `engineInstall.ts` — the engine is not on
+ * this machine yet and the user agreed to fetch it.
+ *
+ * It runs inside the same interactive shell the engine is about to be exec'd into, which is the
+ * only context where installing helps: `npm`, `node` and `curl` routinely arrive through
+ * `.zshrc`/`.bashrc` (nvm, asdf, vendor installers), and a prefix chosen by the daemon's PATH would
+ * either not find npm or install into a prefix the engine's own shell cannot then see. The second
+ * failure is the dangerous one — it looks like success and leaves the engine still missing.
+ *
+ * Ignored when there is no interactive shell to wrap with: without one there is no launch script to
+ * put it in, and running an installer through a bare `execFile` would use the daemon's PATH, which
+ * is the case above.
+ */
+ installFirst?: string
}
/**
@@ -149,7 +164,37 @@ export function buildEngineLaunchArgv(
const command = buildEngineCommandArgv(engine, opts)
const interactive = interactiveEngineShell(shell)
if (!interactive) return command
- return [interactive.path, ...interactive.args, 'exec "$@"', 'harness-engine', ...command]
+ const script = opts.installFirst
+ ? installThenExecScript(opts.installFirst)
+ : 'exec "$@"'
+ return [interactive.path, ...interactive.args, script, 'harness-engine', ...command]
+}
+
+/**
+ * Install, then become the engine — or say why not, and stop.
+ *
+ * Three things this script gets right, each of which was a way to lose:
+ *
+ * * **`exec` only on success.** Running the engine after a failed install reproduces the exact
+ * `command not found` this feature exists to replace, with a screenful of npm output above it to
+ * bury the cause.
+ * * **The install line is not interpolated into a command.** It is the vendor's own published line
+ * from `engineInstall.ts` — a constant in our source, never anything a user or a peer supplied —
+ * and it is `eval`ed as the shell line it is written as, because `curl … | bash` is one of them.
+ * Nothing from the wire reaches here; if that ever changes, this is the line that must not.
+ * * **`"$@"` still carries the engine argv positionally**, so engine paths and flags are never
+ * re-parsed by the shell. That property is what the plain `exec "$@"` had and it is preserved.
+ *
+ * The banner matters more than it looks. A pane that sits silent for forty seconds of `npm install`
+ * reads as a hung agent, and the person's next move is to kill it.
+ */
+function installThenExecScript(install: string): string {
+ return [
+ `printf '%s\\n' 'harness: installing the engine — this pane becomes the agent when it finishes' 'harness: $ ${install.replace(/'/g, "'\\''")}' ''`,
+ `if eval ${JSON.stringify(install)}; then exec "$@"; fi`,
+ `printf '\\n%s\\n' 'harness: the install failed, so the agent was not started. The command is above; fix it and create the agent again.'`,
+ 'exit 1',
+ ].join('\n')
}
const AVAILABILITY_SCRIPT = 'resolved="$(command -v "$1" 2>/dev/null)" || exit 1\n'
diff --git a/cli/src/lib/engineProbe.ts b/cli/src/lib/engineProbe.ts
new file mode 100644
index 000000000..c869a0a5f
--- /dev/null
+++ b/cli/src/lib/engineProbe.ts
@@ -0,0 +1,118 @@
+/**
+ * Which engines does THIS machine actually have?
+ *
+ * The New Agent dialog lists every engine Harness supports. Whether a given machine has any of them
+ * installed is a different question, and until this module existed it was only ever answered the
+ * expensive way: create the agent, watch tmux run a command that does not exist, and read the
+ * `ENGINE_NOT_INSTALLED` that came back. The dialog can ask first.
+ *
+ * ## It must run on the machine being asked about
+ *
+ * This is the whole reason the answer travels as a request rather than being computed in the app. A
+ * developer's Mac and the Docker rig in `docker/remote-machine` routinely disagree — the rig ships
+ * exactly one engine on purpose — and so do two laptops on one account. An availability list
+ * computed locally and applied to a remote machine is wrong in the one case the feature exists for.
+ *
+ * ## It probes the binary the LAUNCH would use, not an alias
+ *
+ * [engineBin] is what `agent_create` puts in `command[0]`, so it is what has to resolve. Probing
+ * `ENGINE_CLI_ALIASES` instead would let a machine answer "installed" for an alias the launch never
+ * calls, which is a worse failure than no answer at all: the dialog would promise a create that
+ * still cannot work.
+ *
+ * The probe itself is [commandAvailableInInteractiveShell] — the same call `cli.ts` already makes
+ * when a create fails, in the same interactive shell a create launches through. Two different notions
+ * of "installed" between the dialog and the launch is precisely the bug this avoids, so there is one
+ * implementation and both sides call it.
+ *
+ * Note what that probe tests: `command -v`, then `-f` and `-x` on what it resolved. A DANGLING
+ * SYMLINK — `~/.local/bin/hermes` pointing into a venv that was deleted — is therefore correctly
+ * reported as not installed, which is the state a plain `command -v` gets wrong.
+ */
+
+import { ENGINES, type AgentEngine } from '../engines/types.js'
+import { engineBin } from './engineBin.js'
+import { commandAvailableInInteractiveShell } from './engineLaunch.js'
+import { engineInstallRecipe } from './engineInstall.js'
+
+/** One engine's answer for one machine. */
+export interface EngineAvailability {
+ readonly engine: AgentEngine
+ /** Does the launch command resolve, as an existing executable file, in the agent's own shell? */
+ readonly installed: boolean
+ /** The command that was probed — `command[0]` of a launch. Null when the engine has no binary. */
+ readonly command: string | null
+ /** Whether Harness has a citable install line for it (see `engineInstall.ts`). */
+ readonly installable: boolean
+}
+
+/**
+ * How many shells to have in flight at once.
+ *
+ * Each probe spawns an interactive shell, and an interactive shell runs the user's rc files — which
+ * on a real machine sources nvm, completions and vendor installers. Fourteen at once is a thundering
+ * herd on the very startup path the agent launch also needs; one at a time makes the dialog wait for
+ * the slowest rc file fourteen times over. Four is the compromise, and it is a number, not a
+ * principle: raise it if a machine is measured to be idle through the probe.
+ */
+const PROBE_CONCURRENCY = 4
+
+/** The launch command for an engine, or null when it has none we can name. */
+function launchCommand(engine: AgentEngine): string | null {
+ try {
+ const bin = engineBin(engine)
+ return bin && bin.length > 0 ? bin : null
+ } catch {
+ // `engineBin` throws for an engine whose binary is genuinely ambiguous on this machine (the
+ // `agent` alias shared by Cursor and Grok is the live case). Ambiguous is not the same as
+ // absent, but it is equally un-probeable, and reporting it as "not installed" would offer an
+ // install that could not fix it. Null flows through to `installed: false, installable: false`.
+ return null
+ }
+}
+
+/**
+ * Probe a set of engines on this machine.
+ *
+ * Order of the result follows the order asked for, so a caller can zip it against its own list.
+ * Never throws: a machine that cannot answer for one engine still answers for the rest, because a
+ * dialog that renders thirteen rows and one blank is more useful than one that renders an error.
+ */
+export async function probeEngines(
+ engines: readonly AgentEngine[] = ENGINES,
+): Promise<EngineAvailability[]> {
+ const results = new Array<EngineAvailability>(engines.length)
+ let next = 0
+
+ async function worker(): Promise<void> {
+ for (;;) {
+ const index = next++
+ if (index >= engines.length) return
+ const engine = engines[index]
+ const command = launchCommand(engine)
+ let installed = false
+ if (command) {
+ try {
+ installed = await commandAvailableInInteractiveShell(command)
+ } catch {
+ // The probe has its own 5s timeout and resolves false rather than rejecting; this catch is
+ // for the spawn itself failing. Unknown reads as not installed, which is the safe way
+ // round: the dialog then offers an install that is merely redundant, rather than promising
+ // a launch that cannot happen.
+ installed = false
+ }
+ }
+ results[index] = {
+ engine,
+ installed,
+ command,
+ installable: !installed && command !== null && engineInstallRecipe(engine) !== null,
+ }
+ }
+ }
+
+ await Promise.all(
+ Array.from({ length: Math.min(PROBE_CONCURRENCY, engines.length) }, () => worker()),
+ )
+ return results
+}
diff --git a/cli/src/lib/tmux.ts b/cli/src/lib/tmux.ts
index 4381461d0..f9cbc6a2e 100644
--- a/cli/src/lib/tmux.ts
+++ b/cli/src/lib/tmux.ts
@@ -621,6 +621,29 @@ async function lookupPaneEngineProcess(
}
}
+/**
+ * The pane's OWN process — whatever is sitting there, engine or not.
+ *
+ * [resolvePaneEngineProcess] answers "is the engine running here yet", which during an install is
+ * deliberately no: the pane is running the user's shell, and the shell is running `npm`. This one
+ * answers "what is running here", so an agent can be registered for a pane whose engine has not
+ * started — the record the terminal tile attaches to while the install scrolls past.
+ *
+ * The identity is a placeholder by design, and a SHORT-LIVED one. When the engine finally execs,
+ * discovery registers it against the same pane and the registry adopts the record in place — see the
+ * `routeAgent` branch in `registry.ts`, which matches on the terminal route precisely while an agent
+ * has no engine session bound yet. The agentId therefore survives, and so does the tile.
+ */
+export async function resolvePaneRootProcess(pane: string): Promise<ProcessIdentity | null> {
+ const rootPid = await panePid(pane)
+ if (!rootPid) return null
+ const rows = await processRows()
+ if (!rows) return null
+ const row = rows.find((candidate) => candidate.pid === rootPid)
+ if (!row) return null
+ return { pid: row.pid, executable: row.executable, startMarker: row.startMarker }
+}
+
/**
* Every process under a pane, shallowest first — the answer to "then WHAT was running?".
*