Skip to content

Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.

Merge remote-tracking branch 'origin/main' into integrate/dkattan-stack

enesfe3564ac1cbb
diff --cc src/renderer/components/settings/sections/CustomAgentsSection.tsx
index 7d1256e25,f79eb074b..0a3542233
--- a/src/renderer/components/settings/sections/CustomAgentsSection.tsx
+++ b/src/renderer/components/settings/sections/CustomAgentsSection.tsx
@@@ -1,13 -1,7 +1,13 @@@
+import { useMemo, useState } from 'react'
import { useSettings } from '../../../state/settings'
- import { firstEnabledBuiltin } from '../../../state/agentAvailability'
+ import { removeCustomAgent } from '../../../state/agentAvailability'
import type { CustomAgent } from '@shared/types'
-import type { PromptInjectionMode } from '@shared/agents/config'
+import {
+ AGENT_CONFIG,
+ BUILTIN_AGENT_IDS,
+ type AgentId,
+ type PromptInjectionMode
+} from '@shared/agents/config'
import { SettingsSection } from '../SettingsSection'
import { SearchableRow } from '../SearchableRow'
import { FieldRow } from '../FieldRow'
diff --cc src/renderer/nodes/TerminalNode.tsx
index 1276696b4,ac106d6b6..7fa9151a2
--- a/src/renderer/nodes/TerminalNode.tsx
+++ b/src/renderer/nodes/TerminalNode.tsx
@@@ -143,26 -141,9 +143,26 @@@ import { useSshConn } from '../state/ss
import { useWorktrees } from '../state/worktrees'
import { isRemoteSessionNode } from '@shared/worktree'
import { useSession, useActiveSessionPresence } from '../session/session'
- import { accountChipLabel, COLLAPSED_HEIGHT, NODE_COLORS, type CanvasNode } from '../state/workspace'
+ import { accountChipLabel, agentLaunchOverride, COLLAPSED_HEIGHT, NODE_COLORS, type CanvasNode } from '../state/workspace'
-import { hasHooks, canRecur, canContextLink, hasUsage, canChat, canResume, canRename, canReadTitle, createdAgentId, reportsOwnCopy, resumeCommand, agentConfig, agentLaunchProgram } from '@shared/agents/config'
+import {
+ hasHooks,
+ canRecur,
+ canContextLink,
+ hasUsage,
+ canChat,
+ canResume,
+ canRename,
+ canReadTitle,
+ createdAgentId,
+ reportsOwnCopy,
+ agentConfig,
+ capabilityAgentId,
+ type AgentId
+} from '@shared/agents/config'
import { withPermissionMode } from '@shared/agents/approval-mode'
+import { assembleResumeCommand } from '@shared/agents/launch'
+import { agentEnvSnapshot } from '@renderer/lib/agentEnv'
+import { normalizedAgentModel } from '@shared/agents/model-gateway'
import { ensureActivePermissionMode } from '../state/permissionMode'
import { buildSshArgs, sshConnectionIdForProject, sshHostKey, type SshConnection } from '@shared/ssh'
import { hintLabel } from '@shared/platform-utils'
@@@ -2844,40 -2824,30 +2844,43 @@@ export function TerminalNode(
// relaunched empty while their transcripts sat on disk, unreachable.
const st = useAgentStatus.getState().byId[id]
const priorId = st?.sessionId || data.agentSessionId
- // Shared-identity agents resume THROUGH their launcher, so the cold-restored node
- // re-claims its own thread instead of joining as an anonymous client. `data.ssh` is what
- // keeps a remote node on the bare command (no launcher on the host).
- const shared = codexSharedIdentity(data.ssh || data.sshRemoteTmux)
- // The user's launch-command override rides every leg of this relaunch: threaded into
- // `resumeCommand` (its `base` param), and standing in for the builtin launchCmd on the
- // no-session fresh start — otherwise a wrapper user's node comes back on the bare CLI
- // after a reboot, the one moment the wrapper (account env etc.) mattered most.
- const launchOverride = agentLaunchOverride(agentId)
- const base =
- (priorId && resumeCommand(agentId, priorId, shared, launchOverride)) ||
- launchOverride ||
- (agentConfig(agentId) &&
- agentLaunchProgram(agentId, agentConfig(agentId)!.launchCmd, shared))
// Re-resolve the mode at relaunch: it's a property of how a session is launched, not
- // a persisted property of the node, so the current setting wins after a reboot. `base`
- // is always freshly built here — never a command string read back from node data — so
- // it can never end up double-flagged. Awaited (not the sync `activePermissionMode`)
- // because this fires on mount: right after a machine reboot it can beat the CLI version
- // probe, and an unanswered probe would conservatively drop `auto`.
- // Gated on THIS node's agent: claude's `auto` version gate must not decide what a grok
- // (or any other permission-mode-capable agent's) relaunch is flagged with.
- const cmd =
- base && withPermissionMode(base, agentId, await ensureActivePermissionMode(agentId))
+ // a persisted property of the node, so the current setting wins after a reboot. Awaited
+ // (not the sync `activePermissionMode`) because this fires on mount: right after a machine
+ // reboot it can beat the CLI version probe, and an unanswered probe would conservatively
+ // drop `auto`. Gated on THIS node's agent: claude's `auto` version gate must not decide
+ // what a grok (or any other permission-mode-capable agent's) relaunch is flagged with.
+ //
+ // Inheritance-aware: assembleResumeCommand resolves a custom agent's baseAgent/args, so a
+ // claude-base proxy resumes with its own binary + claude's --resume grammar + its custom
+ // args — the SAME builder fresh launch uses, so cold restore and first launch can't drift.
+ // For a builtin this is byte-identical to the old resumeCommand + withPermissionMode path.
+ //
+ // Shared-identity agents (codex) resume THROUGH their launcher, so the cold-restored node
+ // re-claims its own thread instead of joining as an anonymous client. `data.ssh` /
+ // `data.sshRemoteTmux` keep a remote node on the bare command (no launcher on the host).
+ const mode = await ensureActivePermissionMode(agentId)
+ const shared = codexSharedIdentity(data.ssh || data.sshRemoteTmux)
+ const customAgent = agentConfig(agentId)
+ ? undefined
+ : useSettings.getState().settings.customAgents.find((c) => c.id === agentId)
+ const { command: cmd } = assembleResumeCommand(
+ {
+ agentId,
+ customAgent,
+ sessionId: priorId || undefined,
+ permissionMode: mode,
+ model: data.agentModel,
- sharedIdentity: shared
++ sharedIdentity: shared,
++ // The user's launch-command override rides the relaunch too, so a wrapper user's node
++ // comes back through its wrapper after a reboot — the moment env/account setup matters.
++ launchCmdOverride: agentLaunchOverride(agentId)
+ },
+ // The boot-time desktop env snapshot — the same object fresh launch and the Settings
+ // preview expand against, so a ${env:…}-referencing custom agent cold-restores with
+ // the exact line it launched with. Empty on browser/relay by design.
+ agentEnvSnapshot()
+ )
if (cmd) writeWhenShellReady(cmd) // same shell-startup race as initialCommand
}
})
@@@ -3013,34 -2914,14 +3016,37 @@@
// read — exactly as the cold-restore relaunch above does it. Without it a canvas running
// in acceptEdits/plan would come back from a restart in the default mode, silently.
// Re-resolved at call time for the same reason as there: the mode is a property of how a
- // session is launched, not of the node. The launch-command override rides along for the
- // same reason — it is a property of how the agent is launched, read fresh per restart.
- const base = resumeCommand(agentId, agentSessionId, false, agentLaunchOverride(agentId))
- const command = base
- ? withPermissionMode(base, agentId, await ensureActivePermissionMode(agentId))
- : undefined
+ // session is launched, not of the node. Inheritance-aware: a custom agent's baseAgent/args
+ // are re-applied so a restart of a claude-base proxy resumes correctly.
+ // Env for ${env:…} substitution in launchCmd/args. `api` is session-scoped: a LOCAL pane
+ // resolves the desktop window's raw-ipcMain snapshot; a relay tab's host registers no
+ // env-snapshot handler at all (a host env dump must never cross to a peer — the PR #195
+ // leak class), so the request settles empty and the missingEnv gate below refuses instead
+ // of typing a mangled line. Builtins reference no env tokens, so they skip the round-trip.
+ const launchEnv = customTarget
+ ? await api.agent.envSnapshot().catch(() => ({}))
+ : {}
+ const { command, missingEnv } = assembleResumeCommand(
+ {
+ agentId: target,
+ customAgent: customTarget,
+ sessionId: agentSessionId,
+ permissionMode: await ensureActivePermissionMode(target),
- model: selectedModel ?? undefined
++ model: selectedModel ?? undefined,
++ // The per-builtin launch-command override rides the restart too (undefined for a custom
++ // target, which already owns its launchCmd) — it is a property of how the agent launches.
++ launchCmdOverride: agentLaunchOverride(target)
+ },
+ launchEnv
+ )
+ // Never type a knowingly mangled launch line (for example `--token ''`) into the pane.
+ // Settings already surfaces these missing names in its preview; a stale menu after an env
+ // change degrades to the ordinary not-eligible notice and leaves the shell untouched.
+ if (missingEnv.length) return 'not-eligible'
return performRestartResume({
- agentId,
+ // Source and target were proven to share one capability base above, so this resolves to
+ // the same exit + resume grammar while the explicit command selects the target binary.
+ agentId: target,
sessionId: agentSessionId,
io: restartIo,
// An unusable session id leaves this undefined and performRestartResume refuses the
@@@ -3135,21 -3014,9 +3141,24 @@@
// not carry its directory on PATH — naming it there would be `command not found` where a
// plain `codex resume` works. A restarted codex node therefore rejoins as a plain client
// until its next cold start. Fail open, same rule as everywhere else in this feature.
- // The USER's launch-command override is different from the launcher: it lives on their
- // own PATH (or is an absolute path), not in a generated dir, so it rides the wake too.
- const base = resumeCommand(agentId, agentSessionId, false, agentLaunchOverride(agentId))
+ const customAgent = agentConfig(agentId)
+ ? undefined
+ : useSettings.getState().settings.customAgents.find((c) => c.id === agentId)
+ const { command } = assembleResumeCommand(
+ {
+ agentId,
+ customAgent,
+ sessionId: agentSessionId,
+ permissionMode: await ensureActivePermissionMode(agentId),
- sharedIdentity: false
++ sharedIdentity: false,
++ // The USER's launch-command override lives on their own PATH (or is an absolute path),
++ // not in a generated launcher dir, so it rides the wake too.
++ launchCmdOverride: agentLaunchOverride(agentId)
+ },
+ // Same boot-time env snapshot as fresh launch / cold restore, so a wake types the same
+ // line the node launched with (empty on browser/relay by design).
+ agentEnvSnapshot()
+ )
// Refused BEFORE anything is written. `performResumePhase` gates on this same bare command
// and would refuse too — but the KILL_LINE below is ours, so leaving this check to it
// meant an unusable session id erased the pane's line (three times, once per wake trigger)
diff --cc src/renderer/state/workspace.ts
index 8cf214f52,8315ac6b2..3481b6022
--- a/src/renderer/state/workspace.ts
+++ b/src/renderer/state/workspace.ts
@@@ -1,9 -1,8 +1,9 @@@
import type { Node } from '@xyflow/react'
import type { CanvasMutation, CanvasNodeState, ClaudeAccount, NodeKind, PendingLaunch, Project } from '@shared/types'
- import type { AgentId, AgentPermissionMode } from '@shared/agents/config'
+ import type { AgentId, AgentPermissionMode, BuiltinAgentId } from '@shared/agents/config'
-import { agentConfig, agentLaunchProgram, mintsSessionId, withSessionId } from '@shared/agents/config'
-import { withPermissionMode } from '@shared/agents/approval-mode'
+import { agentConfig, supportsSessionIdFlag } from '@shared/agents/config'
+import { assembleLaunchCommand } from '@shared/agents/launch'
+import { agentEnvSnapshot } from '../lib/agentEnv'
import { uuid } from '@renderer/lib/uuid'
import { claudeCliCapsNow } from './permissionMode'
import { codexSharedIdentity } from './codexIdentity'
@@@ -364,7 -379,43 +383,12 @@@ export function createAgentNode
accountId?: string,
permissionMode?: AgentPermissionMode
): CanvasNode {
- const { label, color, launchCmd } = resolveAgent(agentId)
- // A SHARED_IDENTITY_CAPABLE agent (codex) launches through its managed launcher when this
- // machine actually has one — otherwise the bare CLI, byte-identical to before. Asked through the
- // capability helper, never `agentId === 'codex'`; `codexSharedIdentity` folds in the SSH answer
- // (a host has no launcher installed yet, so a remote node must stay on the bare command).
- // A user launch-command override wins over BOTH the builtin default and the managed launcher —
- // an explicit "launch it exactly like this" (see agentLaunchOverride / resumeCommand's `base`).
- const override = agentLaunchOverride(agentId)
- const baseCmd =
- agentId === 'claude'
- ? claudeLaunchCommand()
- : (override ?? agentLaunchProgram(agentId, launchCmd, codexSharedIdentity(ssh)))
- // A flag-prompt agent (opencode) takes the initial prompt via its flag — a bare positional
- // would be misread (opencode treats it as a project path). Everything else keeps the
- // historical argv append, INCLUDING stdin-after-start agents (gemini has always launched
- // via argv here; changing that is a separate decision).
- const promptArg = initialPrompt
- ? shellSingleQuote(initialPrompt.replace(/\s+/g, ' ').trim())
- : null
- // A CLI whose positional prompt shares its slot with subcommands needs a separator, or a
- // one-word prompt runs as a command instead (grok: `grok version` prints the version, `grok --
- // version` asks the model about "version"). Absent for everyone else, so their command line is
- // byte-identical to what it was.
- const sep = agentConfig(agentId)?.argvPromptSeparator
- const isFlagPrompt = agentConfig(agentId)?.promptInjectionMode === 'flag-prompt'
- // The separator only participates when there is actually a prompt to separate (no dangling `--`),
- // and never for a flag-prompt agent, whose prompt is not a positional at all.
- const usesSep = !!promptArg && !!sep && !isFlagPrompt
- // `withPrompt` is the NO-separator shape, and only that: it is read at exactly one place below,
- // in the `!usesSep` arm. Reaching it with a prompt and no flag-prompt mode means `sep` was falsy,
- // so an inline `${sep ? … : ''}` here could only ever expand to '' — the separator's one home is
- // the `usesSep` arm, which spells it out.
- const withPrompt = promptArg
- ? isFlagPrompt
- ? `${baseCmd} --prompt ${promptArg}`
- : `${baseCmd} ${promptArg}`
- : baseCmd
+ const { label, color } = resolveAgent(agentId)
++ // A per-builtin launch-command override (Settings -> Agents -> Launch commands) replaces the bare
++ // CLI in the assembled command. Threaded into the shared assembler below as `launchCmdOverride`
++ // so fresh launch, cold-restore resume and in-place restart all pick it up identically. Custom
++ // agents already own their `launchCmd`, so the helper returns undefined for them.
++ const launchCmdOverride = agentLaunchOverride(agentId)
// The session id is DECIDED here rather than learned from a hook later, so this node always has
// something to resume with — see SESSION_ID_CAPABLE for the failure this closes. `uuid()` (not
// crypto.randomUUID) because the Server Edition serves plain HTTP on a LAN, where randomUUID is
@@@ -373,45 -424,29 +397,50 @@@
// Gated on the CLI actually advertising `--session-id`, because an unknown flag does not degrade
// — it makes claude exit, taking the launch with it. Unprobed or older CLI ⇒ no mint ⇒ the
// command line stays byte-identical to what it has always been, and the node falls back to
- // learning its id from hooks exactly as before.
- const mintedSessionId =
- mintsSessionId(agentId) && claudeCliCapsNow().sessionIdFlag ? uuid() : undefined
- // No mode passed (e.g. a legacy/test call site) = bare command, exactly as before this setting.
- // Both flags ride the same helper so they land on the same side of an argv separator: for grok
- // that is BEFORE `--` (end-of-options), and getting it wrong makes a flag part of the prompt.
- const flagged = (cmd: string): string => {
- const withMode = permissionMode ? withPermissionMode(cmd, agentId, permissionMode) : cmd
- return mintedSessionId ? withSessionId(withMode, agentId, mintedSessionId) : withMode
+ // learning its id from hooks exactly as before. Inheritance-aware: a custom agent with
+ // baseAgent:'claude' mints an id too (capabilityAgentId resolves it to claude).
+ const cliCaps = claudeCliCapsNow()
+ const sessionIdFlagSupported = supportsSessionIdFlag(agentId, cliCaps.sessionIdFlag)
+ const mintedSessionId = sessionIdFlagSupported ? uuid() : undefined
+ // Command assembly is delegated to the ONE shared builder (src/shared/agents/launch.ts), used by
+ // fresh launch AND cold-restore resume, so a custom agent's baseAgent/args/expansion are applied
+ // identically in both paths. ${env:...} in launchCmd/args expands against the boot-time env
+ // snapshot (lib/agentEnv.ts) — the SAME object the Settings preview expands against, so the
+ // typed line is the previewed line. Env-var VALUES (the env map) are separate: pty-manager
+ // injects them as process env main-side, never into the typed command. For a builtin with no
+ // custom args this is byte-identical to the old hand-built command line.
+ const customAgent = agentConfig(agentId)
+ ? undefined
+ : useSettings.getState().settings.customAgents.find((c) => c.id === agentId)
+ const { command: initialCommand, missingEnv } = assembleLaunchCommand(
+ {
+ agentId,
+ customAgent,
+ initialPrompt,
+ permissionMode,
+ sessionId: mintedSessionId,
+ sessionIdFlagSupported,
++ // A per-builtin launch-command override (Settings → Agents → Launch commands) replaces the
++ // program in the assembled line; undefined for a builtin with no override and for custom
++ // agents (they own their launchCmd). Wins over the shared-identity launcher, like a custom
++ // launchCmd — an explicit "launch it exactly like this".
++ launchCmdOverride,
+ // A SHARED_IDENTITY_CAPABLE agent (codex) launches through its managed launcher when this
+ // machine actually has one — otherwise the bare CLI, byte-identical to before. `codexSharedIdentity`
+ // folds in the SSH answer (a host has no launcher installed yet, so a remote node stays bare).
+ sharedIdentity: codexSharedIdentity(ssh)
+ },
+ // The boot-time snapshot of the desktop env (empty on browser/relay by design, where the
+ // missing-env warning below is the honest outcome — the same markers the preview shows).
+ agentEnvSnapshot()
+ )
+ if (missingEnv.length) {
+ // A missing var in the typed command (launchCmd/args) would launch with a blank — surface it,
+ // matching the preview. Env-var VALUES (the env map) are merged main-side and warned there.
+ console.warn(
+ `[custom-agent] ${label}: ${missingEnv.map((m) => '${env:' + m + '}').join(', ')} unset in launch command — expanded to empty.`
+ )
}
- // WHERE the mode flag goes is decided by the agent's prompt convention, and the two conventions
- // are opposites:
- // - No separator (claude): the prompt is a positional that must stay adjacent to the binary, so
- // the flag goes LAST — `claude 'fix the bug' --permission-mode auto`, byte-identical to what
- // nodeterm has always emitted.
- // - With a separator (grok): `--` means END OF OPTIONS, which is the whole reason it is there
- // (`grok -- version` sends "version" to the model instead of running the subcommand). By that
- // same convention anything AFTER it is a positional, so a flag appended last would either be
- // swallowed into the prompt text or rejected by clap as an unexpected argument — the setting
- // would silently do nothing, or the launch would die on a usage message. It therefore goes
- // BEFORE the separator: `grok --permission-mode plan -- 'explain this repo'`, matching grok's
- // own usage line `grok [OPTIONS] [PROMPT] [COMMAND]`.
- const initialCommand = usesSep ? `${flagged(baseCmd)} ${sep} ${promptArg}` : flagged(withPrompt)
const size = terminalNodeSize()
return {
id: nextId('term'),
diff --cc src/shared/agents/config.ts
index ee048094d,a9d941432..3bed6712d
--- a/src/shared/agents/config.ts
+++ b/src/shared/agents/config.ts
@@@ -382,54 -305,30 +382,70 @@@ export function withSessionId(cmd: stri
* `sharedIdentity` routes a SHARED_IDENTITY_CAPABLE agent's resume through the managed launcher,
* so the resumed session re-claims the node's own thread instead of opening it as an anonymous
* client. Default false = the bare command this has always emitted (see `agentLaunchProgram`).
+ *
+ * `base` is the user's launch-command override for this agent (`settings.agentLaunchCommands`,
+ * e.g. an account-switching wrapper), PASSED IN rather than read here: this module is imported by
+ * main/core/server and cannot reach the renderer's settings store, so the renderer resolves the
+ * override and threads it through — the same shape as `performRestartResume`'s `command` param.
+ * When set (non-blank) it replaces the program part outright, INCLUDING codex's shared-identity
+ * launcher: an explicit override is the user saying "launch it exactly like this", and silently
+ * substituting the managed launcher would un-say it. Blank/absent = unchanged behavior.
*/
- export function resumeCommand(id: AgentId, sessionId: string, sharedIdentity = false): string | null {
+ export function resumeCommand(
+ id: AgentId,
+ sessionId: string,
+ sharedIdentity = false,
+ base?: string
+ ): string | null {
- if (!canResume(id)) return null
+ const builtin = agentConfig(id)
+ // A builtin resumes with its own command; a custom agent has no resume grammar here (its
+ // baseAgent-aware path is `resumeCommandWith`, called by the shared launcher).
+ if (!builtin) return null
- // Route a SHARED_IDENTITY_CAPABLE builtin (codex) through its managed launcher when this machine
- // has one, so the resumed session re-claims its own thread instead of joining as an anonymous
- // client. Default false = the bare command this has always emitted.
- const program = agentLaunchProgram(id, builtin.launchCmd, sharedIdentity)
++ // A per-builtin launch-command override (Settings → Agents → Launch commands, threaded here as
++ // `base`) replaces the program outright, INCLUDING codex's shared-identity launcher: an explicit
++ // override is the user saying "launch it exactly like this". Blank/absent → route a
++ // SHARED_IDENTITY_CAPABLE builtin (codex) through its managed launcher when present, else the
++ // bare command this has always emitted.
++ const custom = base?.trim() || undefined
++ const program = custom ?? agentLaunchProgram(id, builtin.launchCmd, sharedIdentity)
+ return resumeCommandWith(program, id, sessionId)
+}
+
+/**
+ * Is `sessionId` one this app would put on a `--resume` command line for `id`? The eligibility GATE
+ * the restart/hibernation choreography uses — WITHOUT building the command (which for a custom agent
+ * needs its `launchCmd` from settings, unavailable here). Inheritance-aware via `canResume`, so a
+ * claude-base custom agent is resumable; the SAFE_SESSION_ID check is the same one `resumeCommand`
+ * applies. Pure companion to `resumeCommand` for the gate-only call sites.
+ */
+export function canResumeWith(id: AgentId, sessionId: string): boolean {
+ if (!canResume(id)) return false
+ const sid = sessionId.trim()
+ return !!sid && SAFE_SESSION_ID.test(sid)
+}
+
+/**
+ * Resume by provider session id, using `launchCmd` as the binary and `grammarId` to pick the
+ * resume flag grammar (`--resume` vs `resume` vs `--session`). `grammarId` is the BASE harness
+ * for an inheriting custom agent (`capabilityAgentId(agentId)`), so a claude-base custom agent
+ * resumes as `<customLaunchCmd> --resume <sid>` — its own binary, claude's flag. Returns null for
+ * a non-resumable base or an unsafe/empty session id.
+ */
+export function resumeCommandWith(
+ launchCmd: string,
+ grammarId: AgentId,
+ sessionId: string
+): string | null {
+ if (!canResume(grammarId)) return null
const sid = sessionId.trim()
if (!sid || !SAFE_SESSION_ID.test(sid)) return null
- const custom = base?.trim() || undefined
- switch (id) {
+ switch (grammarId) {
case 'codex':
- return `${custom ?? agentLaunchProgram('codex', 'codex', sharedIdentity)} resume ${sid}`
+ return `${launchCmd} resume ${sid}`
case 'opencode':
- return `${custom ?? 'opencode'} --session ${sid}`
+ return `${launchCmd} --session ${sid}`
+ case 'copilot':
+ return `${launchCmd} --resume=${sid}`
case 'claude':
case 'gemini':
case 'grok':
diff --cc src/shared/agents/launch.ts
index d36b576a2,000000000..ecf6b1416
mode 100644,000000..100644
--- a/src/shared/agents/launch.ts
+++ b/src/shared/agents/launch.ts
@@@ -1,203 -1,0 +1,224 @@@
+// Pure command assembly — the ONE place an agent's launch / resume command line is built.
+//
+// Used by the renderer only: fresh node creation (`workspace.ts createAgentNode`), cold-restore /
+// wake / variant resume (`TerminalNode.tsx`), and the Settings command preview
+// (`CustomAgentsSection.tsx`). Pure: the environment is an explicit parameter, and every caller
+// passes the SAME boot-time snapshot (src/renderer/lib/agentEnv.ts) — one assembler, one env, so
+// the preview cannot drift from the real launch by construction. There is deliberately no
+// main/server preview IPC: an endpoint that expands ${env:…} for a caller-supplied agent record
+// is an environment-variable oracle for relay peers (the #171/#190 review).
+//
+// Inheritance: a custom agent with a `baseAgent` resolves its prompt convention, separator, and
+// capability flags through that base harness (`capabilityAgentId`), so a claude-compatible proxy
+// gets `--permission-mode` / `--session-id` / `--resume` exactly as claude does — while its own
+// `launchCmd`, `args`, and `env` override the binary and the surroundings.
+
+import type { CustomAgent } from '../types'
+import { shellQuoteIfNeeded, shellSingleQuote, shellSplit } from '../shell-quote'
+import { expandEnvVars } from './expansion'
+import {
+ agentLaunchProgram,
+ capabilityAgentId,
+ mintsSessionId,
+ resumeCommandWith,
+ withSessionId,
+ type AgentId,
+ type AgentPermissionMode
+} from './config'
+import { withPermissionMode } from './approval-mode'
+import { resolveAgentConfig } from './custom-agent'
+import { withAgentModel } from './model-gateway'
+
+export interface LaunchInputs {
+ agentId: AgentId
+ /** The matching `CustomAgent` record when `agentId` is a custom id. `undefined` for builtins. */
+ customAgent?: CustomAgent
++ /** Per-builtin launch-command override (Settings → Agents → Launch commands). When set it
++ * replaces the resolved program outright — a wrapper the user runs the CLI through. Undefined
++ * for a builtin with no override and for custom agents (their `launchCmd` already IS the value).
++ * Trusted verbatim, exactly like a custom agent's `launchCmd`: it is the local user's own
++ * settings and is typed into their own pane. */
++ launchCmdOverride?: string
+ /** First-launch prompt. Empty/undefined = start the agent with no prompt. */
+ initialPrompt?: string
+ /** Permission mode to start in. `undefined` = no flag (the agent's own default). */
+ permissionMode?: AgentPermissionMode
+ /** Per-node model override, applied through the effective base harness. */
+ model?: string
+ /** A minted session id for FIRST launch (claude-base only, when the CLI supports `--session-id`).
+ * Ignored on resume. */
+ sessionId?: string
+ /** Whether the local claude CLI advertises `--session-id` (probe result). When false, no
+ * `--session-id` is emitted even for a claude-base agent — an unknown flag would kill the
+ * launch, so this fails open to the bare command. */
+ sessionIdFlagSupported?: boolean
+ /** Should a SHARED_IDENTITY_CAPABLE agent (codex) name its managed launcher instead of the bare
+ * CLI? The caller's answer to "will the launcher actually be there?" — false (the default) emits
+ * the bare command byte-for-byte. A remote node must pass false (the host has no launcher). */
+ sharedIdentity?: boolean
+}
+
+export interface ResumeInputs {
+ agentId: AgentId
+ customAgent?: CustomAgent
++ /** Per-builtin launch-command override — same meaning as `LaunchInputs.launchCmdOverride`, so a
++ * cold-restore / restart resumes through the same wrapper the fresh launch used. */
++ launchCmdOverride?: string
+ /** The provider session id to resume (live hook id, or the minted id persisted on the node). */
+ sessionId?: string
+ permissionMode?: AgentPermissionMode
+ /** Per-node model override, applied through the effective base harness. */
+ model?: string
+ /** Should a SHARED_IDENTITY_CAPABLE agent (codex) name its managed launcher on resume? Same
+ * semantics as `LaunchInputs.sharedIdentity`. */
+ sharedIdentity?: boolean
+}
+
+export interface AssembledCommand {
+ /** The command string to type into the shell. */
+ command: string
+ /** Env vars referenced in `launchCmd`/`args` that were unset and had no fallback (expanded to
+ * empty). Surfaced for a spawn warning / a red `<unset>` in the preview. */
+ missingEnv: string[]
+}
+
+/** Shell-split + expand + re-quote a custom agent's `args` into a safe argv fragment. The split
+ * runs FIRST, so token boundaries are fixed before any environment value enters the string;
+ * `${env:…}` then expands per token and each token is single-quoted — a resolved value carrying
+ * spaces or metacharacters stays ONE argument, and a stray `;`/`$`/backtick in an env value can
+ * never reach the shell as syntax or smuggle an extra flag. A token whose env references all
+ * expand to nothing vanishes (matching what an unquoted `$VAR` does at a real shell); the names
+ * are still reported in `missing`. Returns '' when there are no args. */
+function expandedArgs(raw: string, env: Record<string, string | undefined>): { fragment: string; missing: string[] } {
+ if (!raw?.trim()) return { fragment: '', missing: [] }
+ const missing: string[] = []
+ const tokens: string[] = []
+ for (const token of shellSplit(raw)) {
+ const r = expandEnvVars(token, env)
+ missing.push(...r.missing)
+ if (r.value === '' && token !== '') continue
+ tokens.push(shellSingleQuote(r.value))
+ }
+ return { fragment: tokens.join(' '), missing }
+}
+
+/** Expand `${env:…}` in a custom `launchCmd`. A launchCmd with no env tokens — every builtin, and
+ * almost every custom agent — is returned byte-for-byte, raw shell text included, exactly as it
+ * always was. When a token DOES reference the environment, the whole command is re-tokenized and
+ * each token re-quoted unless shell-inert: the program position is typed unquoted into the pane,
+ * so an env value expanding to `x; rm -rf ~` must land as literal text, never as syntax. This is
+ * the local-shell-injection hole from the #171/#190 review, closed by construction instead of by
+ * trusting whoever set the variable. */
+function expandedProgram(
+ raw: string,
+ env: Record<string, string | undefined>
+): { value: string; missing: string[] } {
+ if (!raw.includes('${env:')) return { value: raw, missing: [] }
+ const missing: string[] = []
+ const tokens: string[] = []
+ for (const token of shellSplit(raw)) {
+ const r = expandEnvVars(token, env)
+ missing.push(...r.missing)
+ if (r.value === '' && token !== '') continue
+ tokens.push(shellQuoteIfNeeded(r.value))
+ }
+ return { value: tokens.join(' '), missing }
+}
+
+/**
+ * Assemble the FIRST-LAUNCH command: `<launchCmd> <args> [sep] [prompt] [permission flag]
+ * [session-id flag]`. The prompt and flags land per the resolved prompt convention (separator
+ * agents put flags before `--`; positional agents put them last), exactly as the historical
+ * per-builtin path did — byte-identical for a builtin with no custom args.
+ */
+export function assembleLaunchCommand(
+ inputs: LaunchInputs,
+ env: Record<string, string | undefined>
+): AssembledCommand {
+ const eff = resolveAgentConfig(inputs.agentId, inputs.customAgent)
+ const capId = capabilityAgentId(inputs.agentId)
+
- const { value: launchCmd, missing: m1 } = expandedProgram(eff.launchCmd, env)
++ // A per-builtin launch-command override replaces the resolved program (a wrapper the user runs
++ // the CLI through). It is expanded + quoted like any launchCmd, and — like a custom agent's own
++ // launchCmd — is NOT routed through the shared-identity launcher: an explicit override is the
++ // user saying "launch it exactly like this".
++ const overrideCmd = inputs.launchCmdOverride?.trim()
++ const { value: launchCmd, missing: m1 } = expandedProgram(overrideCmd || eff.launchCmd, env)
+ // Route a SHARED_IDENTITY_CAPABLE builtin (codex) through its managed launcher when this machine
+ // has one, so the pane re-claims its own thread. Custom agents are not in that list, so a custom
+ // launchCmd is returned unchanged. Applied to the already-expanded launchCmd (the launcher is a
- // bare program name, never an ${env:…} token).
- const program = agentLaunchProgram(inputs.agentId, launchCmd, inputs.sharedIdentity)
++ // bare program name, never an ${env:…} token). Skipped when an override is set.
++ const program = overrideCmd
++ ? launchCmd
++ : agentLaunchProgram(inputs.agentId, launchCmd, inputs.sharedIdentity)
+ const { fragment: argsFragment, missing: m2 } = expandedArgs(inputs.customAgent?.args ?? '', env)
+ const baseCmd = argsFragment ? `${program} ${argsFragment}` : program
+
+ const promptArg = inputs.initialPrompt
+ ? shellSingleQuote(inputs.initialPrompt.replace(/\s+/g, ' ').trim())
+ : null
+ const sep = eff.argvPromptSeparator
+ const promptFlag =
+ eff.promptInjectionMode === 'flag-prompt'
+ ? '--prompt'
+ : eff.promptInjectionMode === 'flag-interactive'
+ ? '--interactive'
+ : null
+ const isFlagPrompt = !!promptFlag
+ const usesSep = !!promptArg && !!sep && !isFlagPrompt
+ const withPrompt = promptArg
+ ? isFlagPrompt
+ ? `${baseCmd} ${promptFlag} ${promptArg}`
+ : `${baseCmd} ${promptArg}`
+ : baseCmd
+
+ const flagged = (cmd: string): string => {
+ const withMode = inputs.permissionMode
+ ? withPermissionMode(cmd, capId, inputs.permissionMode)
+ : cmd
+ // Session-id minting: claude-base + CLI supports the flag. On resume this branch is never
+ // taken (assembleResumeCommand does not pass sessionId).
+ if (inputs.sessionId && mintsSessionId(capId) && inputs.sessionIdFlagSupported) {
+ return withAgentModel(withSessionId(withMode, capId, inputs.sessionId), capId, inputs.model)
+ }
+ return withAgentModel(withMode, capId, inputs.model)
+ }
+
+ const command = usesSep ? `${flagged(baseCmd)} ${sep} ${promptArg}` : flagged(withPrompt)
+ return { command, missingEnv: [...m1, ...m2] }
+}
+
+/**
+ * Assemble the RESUME command for a cold restore / in-place restart: `<launchCmd> <args>
+ * --resume <sid>` (grammar per the base harness) when a session id is known, else a fresh launch
+ * with no prompt and no minted id. The permission flag is applied in both cases. Returns the
+ * fresh-launch command (no resume) for a non-resumable base, so a vanilla custom agent still
+ * relaunches cleanly.
+ */
+export function assembleResumeCommand(
+ inputs: ResumeInputs,
+ env: Record<string, string | undefined>
+): AssembledCommand {
+ const eff = resolveAgentConfig(inputs.agentId, inputs.customAgent)
+ const capId = capabilityAgentId(inputs.agentId)
+
- const { value: launchCmd, missing: m1 } = expandedProgram(eff.launchCmd, env)
++ // A per-builtin launch-command override wins over the program and the launcher (same rule as the
++ // fresh-launch path), so a cold-restore / restart resumes through the same wrapper.
++ const overrideCmd = inputs.launchCmdOverride?.trim()
++ const { value: launchCmd, missing: m1 } = expandedProgram(overrideCmd || eff.launchCmd, env)
+ // Same launcher routing as the fresh-launch path: a SHARED_IDENTITY_CAPABLE builtin (codex) names
- // its managed launcher so the resumed session re-claims its own thread.
- const program = agentLaunchProgram(inputs.agentId, launchCmd, inputs.sharedIdentity)
++ // its managed launcher so the resumed session re-claims its own thread. Skipped for an override.
++ const program = overrideCmd
++ ? launchCmd
++ : agentLaunchProgram(inputs.agentId, launchCmd, inputs.sharedIdentity)
+ const { fragment: argsFragment, missing: m2 } = expandedArgs(inputs.customAgent?.args ?? '', env)
+ const baseCmd = argsFragment ? `${program} ${argsFragment}` : program
+
+ const resumeBase = inputs.sessionId ? resumeCommandWith(baseCmd, capId, inputs.sessionId) : null
+ const base = resumeBase ?? baseCmd
+ const withMode = inputs.permissionMode
+ ? withPermissionMode(base, capId, inputs.permissionMode)
+ : base
+ const command = withAgentModel(withMode, capId, inputs.model)
+ return { command, missingEnv: [...m1, ...m2] }
+}
diff --cc src/shared/types.ts
index 4ab72f87c,00ca689fd..35a79298b
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@@ -1043,8 -993,13 +1043,15 @@@ export interface Settings
soundVolume: number
/** User-defined agents (BYO CLI) appended to the Add menus. */
customAgents: CustomAgent[]
+ /** One gateway root + non-secret credential reference used by model-switch-capable harnesses. */
+ modelGateway: ModelGatewaySettings
+ /** Per-builtin-agent launch command overrides (Settings → Agents → Launch commands). The value
+ * replaces the bare CLI name everywhere a launch line is built — new sessions, cold-restore
+ * relaunches and in-place restarts, with the usual flags (`--resume`, `--permission-mode`, the
+ * prompt) appended after it — so a wrapper script that picks an account or sets env vars runs
+ * wherever the agent would. Empty/absent = the builtin default, byte-identical to before this
+ * setting existed. Keyed by builtin id only: custom agents already own their `launchCmd`. */
+ agentLaunchCommands: Partial<Record<BuiltinAgentId, string>>
/** Managed Claude accounts (config-dir isolated). See ClaudeAccount. */
claudeAccounts: ClaudeAccount[]
/** Custom display label for the SYSTEM Claude account (~/.claude) in pickers/settings.
@@@ -1192,7 -1144,7 +1199,8 @@@ export const DEFAULT_SETTINGS: Setting
soundEffects: true,
soundVolume: 0.5,
customAgents: [],
+ modelGateway: { baseUrl: '', apiKey: '' },
+ agentLaunchCommands: {},
claudeAccounts: [],
systemAccountLabel: '',
// All three builtin agents (Claude/Codex/Gemini) show in the Add menus out of the box.