Skip to content

an open-source alternative to the dots, bots and muses of the world, run an office of claude code/codex like agents on your laptop, sandboxes or anywhere, uses your existing subscriptions

feat(pty): run engine-CLI installer visibly when the binary is missing

Chaitanya Giricc49e1edf9a6
diff --git a/src/main/index.ts b/src/main/index.ts
index c5636a45..d1c1d974 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -37,7 +37,9 @@ import {
isClaudeProvider,
nonInteractiveEnvForProvider,
providerPreset,
- type AgentProvider
+ installInfoForProvider,
+ type AgentProvider,
+ type ProviderInstallInfo
} from '../shared/agentProvider';
const isDev = !!process.env.ELECTRON_RENDERER_URL;
@@ -1467,6 +1469,90 @@ function installAppMenu(): void {
Menu.setApplicationMenu(Menu.buildFromTemplate(template));
}
+/** Build the shell script the missing-CLI auto-install path runs IN PLACE of a
+ * missing engine CLI. When the provider has a known installer it prints a banner
+ * then RUNS the install visibly (so the user can watch + finish any sign-in);
+ * otherwise it prints a manual instruction only and runs nothing. The script is
+ * emitted in the current platform shell's syntax ($SHELL on unix, cmd.exe on
+ * Windows). The only user-derived value (the missing binary name) is sanitized to
+ * a safe identifier; the install command itself is a trusted hardcoded constant. */
+function buildMissingCliScript(bin: string, provider: AgentProvider): string {
+ const info: ProviderInstallInfo = installInfoForProvider(provider);
+ const safeBin = (bin || provider).replace(/[^A-Za-z0-9._-]/g, '') || provider;
+ const cmd = info.command; // trusted constant, or undefined → manual hint only
+ const label = info.label;
+ const docs = info.docsUrl;
+ const rule = '------------------------------------------------------------';
+
+ if (process.platform === 'win32') {
+ // ONE cmd.exe line: `&` chains steps, `^&` prints a literal ampersand, and the
+ // script carries NO double-quotes (it is wrapped verbatim in `/d /s /c "..."`).
+ // We avoid `if errorlevel` branching (untestable here) — a combined success/
+ // failure hint after the install is robust and satisfies the manual-fallback DoD.
+ const parts: string[] = ['echo.', `echo ${rule}`, `echo Engine CLI not found: ${safeBin}`, 'echo.'];
+ if (cmd) {
+ parts.push(
+ `echo Installing the ${label} CLI now so you can watch:`,
+ 'echo.',
+ `echo ${cmd}`,
+ `echo ${rule}`,
+ 'echo.',
+ cmd,
+ 'echo.',
+ 'echo If it succeeded, click restart ^& continue to launch the agent.',
+ 'echo If it failed, run the command above manually, then restart ^& continue.'
+ );
+ } else {
+ parts.push(
+ `echo No bundled installer for the ${label} provider.`,
+ 'echo Install it manually, then click restart ^& continue.'
+ );
+ if (docs) parts.push(`echo Docs: ${docs}`);
+ parts.push(`echo ${rule}`);
+ }
+ return parts.join(' & ');
+ }
+
+ // unix ($SHELL -lc <script>): one statement per line, single-quoted echo text so
+ // no shell metacharacter expands. We avoid `!` so any shell with history
+ // expansion never fires. npm is found via the interactive PATH spawn() injects.
+ const lines: string[] = [
+ `echo ''`,
+ `echo '${rule}'`,
+ `echo ' Engine CLI not found: ${safeBin}'`,
+ `echo ''`
+ ];
+ if (cmd) {
+ lines.push(
+ `echo ' Installing the ${label} CLI now so you can watch — finish any'`,
+ `echo ' sign-in it prompts for, then come back to this terminal.'`,
+ `echo ''`,
+ `echo ' ${cmd}'`,
+ `echo '${rule}'`,
+ `echo ''`,
+ cmd,
+ `__clirc=$?`,
+ `echo ''`,
+ `if [ $__clirc -eq 0 ]; then`,
+ ` echo ' [done] Installed. Click restart & continue to launch the agent.'`,
+ `else`,
+ ` echo " [x] Install exited with code $__clirc — finish it manually:"`,
+ ` echo ' ${cmd}'`,
+ ...(docs ? [` echo ' Docs: ${docs}'`] : []),
+ ` echo ' Then click restart & continue.'`,
+ `fi`
+ );
+ } else {
+ lines.push(
+ `echo ' No bundled installer for the ${label} provider.'`,
+ `echo ' Install it manually, then click restart & continue.'`,
+ ...(docs ? [`echo ' Docs: ${docs}'`] : []),
+ `echo '${rule}'`
+ );
+ }
+ return lines.join(String.fromCharCode(10));
+}
+
// ─── IPC: pty lifecycle ─────────────────────────────────────────────────────
ipcMain.handle('pty:spawn', async (evt, opts: SpawnOptions & { hive?: AgentMeta; isolate?: boolean; resume?: boolean; resumeSessionId?: string; provider?: AgentProvider }) => {
if (!opts || typeof opts.id !== 'string' || typeof opts.cwd !== 'string' || typeof opts.command !== 'string') {
@@ -1480,6 +1566,37 @@ ipcMain.handle('pty:spawn', async (evt, opts: SpawnOptions & { hive?: AgentMeta;
const claudeProvider = isClaudeProvider(provider);
opts.provider = provider;
if (opts.hive) opts.hive = { ...opts.hive, provider };
+ // ── Missing engine CLI → run its installer visibly (pre-spawn) ───────────────
+ // If the agent's engine binary (claude/codex/…) isn't installed, spawning it
+ // just dies with "— process exited (code 1) —" and the user has no idea why.
+ // Detect the absent binary BEFORE spawning and, in this SAME terminal, print a
+ // banner + RUN the provider's install command so the user can watch it (and
+ // complete any interactive sign-in), then restart the agent. STRICTLY pre-spawn:
+ // a non-zero exit from a CLI that DID start never reaches here, so there is no
+ // install loop. Providers with no known installer get a manual hint only —
+ // nothing arbitrary is ever auto-run. We short-circuit BEFORE worktree/hive/
+ // Claude-flag setup: ptyToAgent + worktreePaths stay unset for this id, so when
+ // the install PTY exits teardownPty is a harmless no-op (the agent isn't archived
+ // and no worktree is torn down) — the user just clicks "restart & continue".
+ {
+ const bin = opts.command.trim().split(/\s+/)[0] || opts.command;
+ if (bin && !ptyManager.isCommandAvailable(bin)) {
+ const installOwner = BrowserWindow.fromWebContents(evt.sender)?.webContents ?? null;
+ const res = ptyManager.spawn(
+ {
+ id: opts.id,
+ cwd: opts.cwd,
+ command: bin,
+ cols: opts.cols,
+ rows: opts.rows,
+ shellScript: buildMissingCliScript(bin, provider)
+ },
+ installOwner
+ );
+ syncKeepAwake();
+ return res;
+ }
+ }
// Git isolation: when requested and the cwd is a real repo, give this agent
// its own worktree on an `agent/<id>` branch so it can't clobber other agents'
// (or the user's) working tree. Best-effort — a failure falls back to the
diff --git a/src/main/pty.ts b/src/main/pty.ts
index 347b88c5..028d3b56 100644
--- a/src/main/pty.ts
+++ b/src/main/pty.ts
@@ -31,6 +31,13 @@ export interface SpawnOptions {
rows?: number;
/** Extra environment for the child (merged over the resolved shell env). */
env?: Record<string, string>;
+ /** When set, run this string as a VISIBLE shell script instead of resolving/
+ * spawning `command`. Used by the missing-CLI auto-install path: the script
+ * (a banner + an install command) streams to the same Terminal tab. Routed
+ * through `$SHELL -lc` on unix and `cmd.exe /d /s /c` on Windows. The script
+ * MUST contain no embedded double-quotes (it is wrapped verbatim on Windows).
+ * `command` is still recorded for display but is not executed. */
+ shellScript?: string;
}
/**
@@ -114,12 +121,25 @@ export class PtyManager {
try { wc.send(channel, payload); } catch { /* window tore down mid-send */ }
}
+ /** Whether an engine CLI is actually installed/locatable on this machine.
+ * Used PRE-SPAWN by the missing-CLI auto-install path: a bare `claude`/`codex`
+ * that resolveCommand can't locate would otherwise be spawned and die with
+ * "process exited (code 1)". Reuses the exact same `which`/`where` +
+ * candidate-dir logic as spawn(), so detection and spawning never disagree. */
+ isCommandAvailable(command: string): boolean {
+ return this.resolveCommand(command).found;
+ }
+
/** Resolve a bare command (e.g. 'claude') against the user's PATH +
* common install locations. Needed because Electron's spawn env on
- * macOS launches without the user's interactive shell PATH. */
- private resolveCommand(command: string): string {
- // Already an absolute/relative path (Unix `/` or Windows `\`) — pass through.
- if (command.includes('/') || command.includes('\\')) return command;
+ * macOS launches without the user's interactive shell PATH. Returns the
+ * best path AND whether an existing executable was actually located (`found`):
+ * when nothing is found, `path` falls back to the bare command (spawn would
+ * ENOENT) and `found` is false — the signal the missing-CLI path keys on. */
+ private resolveCommand(command: string): { path: string; found: boolean } {
+ // Already an absolute/relative path (Unix `/` or Windows `\`) — pass through;
+ // `found` reflects whether that path actually exists on disk.
+ if (command.includes('/') || command.includes('\\')) return { path: command, found: existsSync(command) };
if (process.platform === 'win32') {
// `where` is the Windows equivalent of `which`; runs via cmd.exe (shell:true).
// It can return MULTIPLE matches in PATH order; the first is often an
@@ -139,7 +159,7 @@ export class PtyManager {
return pathExts.includes(p.slice(dot).toUpperCase());
};
const exe = lines.find((p) => isExecutable(p) && existsSync(p));
- if (exe) return exe;
+ if (exe) return { path: exe, found: true };
} catch { /* fall through */ }
// Common Windows install locations (npm global = %APPDATA%\npm\<cmd>.cmd).
const appData = process.env.APPDATA ?? '';
@@ -152,9 +172,9 @@ export class PtyManager {
`${home}\\.claude\\local\\${command}.cmd`,
`${home}\\.claude\\local\\${command}`
];
- for (const c of winCandidates) if (existsSync(c)) return c;
+ for (const c of winCandidates) if (existsSync(c)) return { path: c, found: true };
// Last resort — let node-pty try; will fail with ENOENT if missing.
- return command;
+ return { path: command, found: false };
}
// macOS / Linux — `which` against an interactive shell so we pick up nvm/asdf/brew paths.
try {
@@ -163,7 +183,7 @@ export class PtyManager {
timeout: 3000
});
const path = res.stdout.trim().split('\n').pop();
- if (path && existsSync(path)) return path;
+ if (path && existsSync(path)) return { path, found: true };
} catch { /* fall through */ }
// Common explicit locations
const candidates = [
@@ -173,9 +193,9 @@ export class PtyManager {
`${process.env.HOME ?? ''}/.claude/local/${command}`,
`${process.env.HOME ?? ''}/.volta/bin/${command}`
];
- for (const c of candidates) if (existsSync(c)) return c;
+ for (const c of candidates) if (existsSync(c)) return { path: c, found: true };
// Last resort — let node-pty try; will fail with ENOENT if missing.
- return command;
+ return { path: command, found: false };
}
spawn(opts: SpawnOptions, owner: WebContents | null = null): { ok: boolean; error?: string } {
@@ -185,7 +205,7 @@ export class PtyManager {
if (!existsSync(opts.cwd)) {
return { ok: false, error: `cwd does not exist: ${opts.cwd}` };
}
- const resolved = this.resolveCommand(opts.command);
+ const resolved = this.resolveCommand(opts.command).path;
try {
// Build a user-shell PATH so child can resolve subprocess deps.
const userPath = (() => {
@@ -208,21 +228,43 @@ export class PtyManager {
const lower = resolved.toLowerCase();
const directExe = lower.endsWith('.exe') || lower.endsWith('.com');
const needsCmd = isWin && !directExe;
- const file = needsCmd ? (process.env.ComSpec || 'cmd.exe') : resolved;
- // #55: when routing through cmd.exe we must NOT pass `resolved` as a bare,
- // unquoted array element. A Program-Files path (`C:\Program Files\nodejs\node`)
- // would split on its space under cmd.exe → "C:\Program is not recognized" and
- // every Windows agent terminal dies. Build a single, fully-quoted command line
- // and hand it to node-pty as a STRING (not an array): node-pty's
- // argsToCommandLine() only re-escapes ARRAY args; a string is passed through
- // verbatim (isCommandLine === true → `file + " " + args`), so our quoting is
- // never double-wrapped. We mirror Node's own child_process form,
- // `cmd.exe /d /s /c "<command>"`, wrapping the WHOLE inner command in one outer
- // quote pair — cmd's /s flag strips exactly that pair and runs the remainder
- // (where the resolved path keeps its own quotes) literally. /d skips AutoRun.
- const spawnArgs: string[] | string = needsCmd
- ? buildCmdCommandLine(resolved, opts.args ?? [])
- : (opts.args ?? []);
+ let file: string;
+ let spawnArgs: string[] | string;
+ if (typeof opts.shellScript === 'string') {
+ // Missing-CLI auto-install: run a banner + install command through the
+ // platform shell so it streams to this same Terminal tab. On Windows we
+ // hand cmd.exe a verbatim STRING (`/d /s /c "<script>"`) — node-pty passes
+ // strings through unescaped, and `/s` strips exactly the outer quote pair,
+ // so the `&`-chained script runs as-is (the script carries no embedded `"`).
+ // On unix we use `$SHELL -lc <script>` (login, non-interactive): npm is
+ // already on PATH because spawn() sets env.PATH to the captured interactive
+ // shell PATH (nvm/asdf/brew included), and skipping `-i` avoids dumping the
+ // user's interactive-rc session-restore noise into the install terminal. The
+ // script is one argv element, so no shell-quoting is needed here.
+ if (isWin) {
+ file = process.env.ComSpec || 'cmd.exe';
+ spawnArgs = `/d /s /c "${opts.shellScript}"`;
+ } else {
+ file = process.env.SHELL || '/bin/sh';
+ spawnArgs = ['-lc', opts.shellScript];
+ }
+ } else {
+ file = needsCmd ? (process.env.ComSpec || 'cmd.exe') : resolved;
+ // #55: when routing through cmd.exe we must NOT pass `resolved` as a bare,
+ // unquoted array element. A Program-Files path (`C:\Program Files\nodejs\node`)
+ // would split on its space under cmd.exe → "C:\Program is not recognized" and
+ // every Windows agent terminal dies. Build a single, fully-quoted command line
+ // and hand it to node-pty as a STRING (not an array): node-pty's
+ // argsToCommandLine() only re-escapes ARRAY args; a string is passed through
+ // verbatim (isCommandLine === true → `file + " " + args`), so our quoting is
+ // never double-wrapped. We mirror Node's own child_process form,
+ // `cmd.exe /d /s /c "<command>"`, wrapping the WHOLE inner command in one outer
+ // quote pair — cmd's /s flag strips exactly that pair and runs the remainder
+ // (where the resolved path keeps its own quotes) literally. /d skips AutoRun.
+ spawnArgs = needsCmd
+ ? buildCmdCommandLine(resolved, opts.args ?? [])
+ : (opts.args ?? []);
+ }
const proc = pty.spawn(file, spawnArgs, {
name: 'xterm-256color',
cols: opts.cols ?? 100,
diff --git a/src/shared/agentProvider.ts b/src/shared/agentProvider.ts
index fa376773..7a93b8d9 100644
--- a/src/shared/agentProvider.ts
+++ b/src/shared/agentProvider.ts
@@ -108,6 +108,14 @@ export interface AgentProviderPreset {
* (Claude `--resume <sid>`, Antigravity `--conversation <id>`). undefined = no
* resume support, spawn fresh. */
resumeFlag?: string;
+ /** Shell command that installs this provider's engine CLI when it's missing,
+ * e.g. `npm install -g @anthropic-ai/claude-code`. When set, the missing-CLI
+ * path may RUN it visibly in the agent terminal (after pre-spawn detection);
+ * when undefined, the user is shown a manual instruction only and nothing is
+ * auto-run. MUST be a trusted, hardcoded constant — never user/manifest input. */
+ installCommand?: string;
+ /** Optional docs URL surfaced as a manual-setup hint in the missing-CLI banner. */
+ docsUrl?: string;
}
export const AGENT_PROVIDER_PRESETS: AgentProviderPreset[] = [
@@ -125,7 +133,10 @@ export const AGENT_PROVIDER_PRESETS: AgentProviderPreset[] = [
// Longest-context Claude variant — matches the "give Michael a bigger model"
// advisory and the Recommended tag on the orchestrator picker.
recommendedOrchestratorModel: 'claude-opus-4-8[1m]',
- resumeFlag: '--resume'
+ resumeFlag: '--resume',
+ // Official Claude Code install (npm global). Used by the missing-CLI auto-install.
+ installCommand: 'npm install -g @anthropic-ai/claude-code',
+ docsUrl: 'https://docs.claude.com/en/docs/claude-code'
},
{
id: 'codex',
@@ -161,7 +172,10 @@ export const AGENT_PROVIDER_PRESETS: AgentProviderPreset[] = [
recommendedOrchestratorModel: 'gpt-5-codex',
// Codex has no stable session-resume CLI flag in the curated reference; spawn
// fresh on respawn (the protocol is re-injected as the initial prompt anyway).
- resumeFlag: undefined
+ resumeFlag: undefined,
+ // Official OpenAI Codex CLI install (npm global). Used by the missing-CLI auto-install.
+ installCommand: 'npm install -g @openai/codex',
+ docsUrl: 'https://github.com/openai/codex'
},
{
id: 'antigravity',
@@ -335,3 +349,18 @@ export function nonInteractiveEnvForProvider(provider: AgentProvider): Record<st
export function commandGroupsForProvider(provider: AgentProvider): CmdGroup[] {
return providerPreset(provider).commandGroups ?? [];
}
+
+/** Install metadata for a provider's engine CLI, consumed by the missing-CLI
+ * auto-install path. `command` is the (trusted, hardcoded) installer to run when
+ * present; when undefined the caller shows a manual hint and runs NOTHING. `label`
+ * is the friendly CLI name; `docsUrl` is an optional manual-setup link. */
+export interface ProviderInstallInfo {
+ command?: string;
+ label: string;
+ docsUrl?: string;
+}
+
+export function installInfoForProvider(provider: AgentProvider): ProviderInstallInfo {
+ const p = providerPreset(provider);
+ return { command: p.installCommand, label: p.label, docsUrl: p.docsUrl };
+}