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.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
feat(custom-agents): env/args/baseAgent inheritance + ${env:VAR} expansion
Darren Kattanef251a451973
diff --git a/src/core/agent-env-ipc.ts b/src/core/agent-env-ipc.tsnew file mode 100644index 000000000..fb9aec065--- /dev/null+++ b/src/core/agent-env-ipc.ts@@ -0,0 +1,26 @@+// Main/server IPC handlers for the custom-agent preview: env-var expansion and command assembly+// run here (against the real `process.env`) because the renderer has no `process.env` of its own.+// The preview is therefore guaranteed to match what `pty-manager` will actually type into the shell.++import { IPC } from '../shared/ipc'+import { platform } from './platform'+import { assembleLaunchCommand, type LaunchInputs } from '../shared/agents/launch'++/** A string-only snapshot of `process.env` (undefined entries omitted), for `${env:VAR}` expansion+ * in the renderer's preview. */+function envSnapshot(): Record<string, string> {+ const out: Record<string, string> = {}+ for (const [k, v] of Object.entries(process.env)) {+ if (typeof v === 'string') out[k] = v+ }+ return out+}++/** Register the env-snapshot + preview-command handlers. Call once at startup, beside the other+ * `registerIpc()` calls (main: src/main/index.ts; server: src/server/index.ts). */+export function registerAgentEnvIpc(): void {+ platform().handle(IPC.envSnapshot, () => envSnapshot())+ platform().handle(IPC.agentPreviewCommand, (inputs: LaunchInputs) =>+ assembleLaunchCommand(inputs, envSnapshot())+ )+}diff --git a/src/core/custom-agent-env.test.ts b/src/core/custom-agent-env.test.tsnew file mode 100644index 000000000..ef2a0b65b--- /dev/null+++ b/src/core/custom-agent-env.test.ts@@ -0,0 +1,132 @@+import { describe, expect, it } from 'vitest'+import { applyCustomAgentEnv, customAgentEnvArgs } from './custom-agent-env'+import type { CustomAgent } from '../shared/types'++const PROC = { MY_TOKEN: 'sk-abc', PATH: '/usr/bin:/bin' }++describe('applyCustomAgentEnv', () => {+ it('returns the env unchanged (shallow copy) when there is no custom agent / no env', () => {+ expect(applyCustomAgentEnv({ A: '1' }, undefined, PROC)).toEqual({+ env: { A: '1' },+ warnings: []+ })+ const noEnv: CustomAgent = { id: 'custom:x', label: 'X', launchCmd: 'x' }+ expect(applyCustomAgentEnv({ A: '1' }, noEnv, PROC)).toEqual({+ env: { A: '1' },+ warnings: []+ })+ })++ it('merges custom env LAST so it wins over the existing env', () => {+ const custom: CustomAgent = {+ id: 'custom:p',+ label: 'Proxy',+ launchCmd: 'claude',+ env: { ANTHROPIC_AUTH_TOKEN: 'proxy-token', NEW: 'n' }+ }+ const r = applyCustomAgentEnv({ ANTHROPIC_AUTH_TOKEN: 'account-token', KEEP: 'k' }, custom, PROC)+ expect(r.env).toEqual({+ ANTHROPIC_AUTH_TOKEN: 'proxy-token',+ KEEP: 'k',+ NEW: 'n'+ })+ expect(r.warnings).toEqual([])+ })++ it('expands ${env:VAR} against the process env', () => {+ const custom: CustomAgent = {+ id: 'custom:p',+ label: 'Proxy',+ launchCmd: 'claude',+ env: { TOKEN: '${env:MY_TOKEN}' }+ }+ expect(applyCustomAgentEnv({}, custom, PROC).env).toEqual({ TOKEN: 'sk-abc' })+ })++ it('warns when a referenced var is unset with no fallback', () => {+ const custom: CustomAgent = {+ id: 'custom:p',+ label: 'Proxy',+ launchCmd: 'claude',+ env: { TOKEN: '${env:MISSING}' }+ }+ const r = applyCustomAgentEnv({}, custom, PROC)+ expect(r.env).toEqual({ TOKEN: '' })+ expect(r.warnings.join('\n')).toContain('${env:MISSING}')+ expect(r.warnings.join('\n')).toContain('Proxy')+ })++ it('uses the fallback and does not warn when the var is unset', () => {+ const custom: CustomAgent = {+ id: 'custom:p',+ label: 'Proxy',+ launchCmd: 'claude',+ env: { TOKEN: '${env:MISSING:dev-key}' }+ }+ const r = applyCustomAgentEnv({}, custom, PROC)+ expect(r.env).toEqual({ TOKEN: 'dev-key' })+ expect(r.warnings).toEqual([])+ })++ it('warns when a custom PATH clobbers the inherited PATH', () => {+ const custom: CustomAgent = {+ id: 'custom:p',+ label: 'Proxy',+ launchCmd: 'claude',+ env: { PATH: '/my/bin' }+ }+ const r = applyCustomAgentEnv({ PATH: '/usr/bin' }, custom, PROC)+ expect(r.env.PATH).toBe('/my/bin')+ expect(r.warnings.join('\n')).toContain('${env:PATH}')+ })++ it('does not warn when a custom PATH preserves the inherited PATH', () => {+ const custom: CustomAgent = {+ id: 'custom:p',+ label: 'Proxy',+ launchCmd: 'claude',+ env: { PATH: '${env:PATH}:/my/bin' }+ }+ const r = applyCustomAgentEnv({ PATH: '/usr/bin' }, custom, PROC)+ expect(r.env.PATH).toBe('/usr/bin:/bin:/my/bin')+ expect(r.warnings).toEqual([])+ })++ it('skipPath drops a custom PATH and warns (remote nodes)', () => {+ const custom: CustomAgent = {+ id: 'custom:p',+ label: 'Proxy',+ launchCmd: 'claude',+ env: { PATH: '${env:PATH}:/my/bin', OTHER: 'x' }+ }+ const r = applyCustomAgentEnv({ PATH: '/usr/bin' }, custom, PROC, { skipPath: true })+ expect(r.env).toEqual({ PATH: '/usr/bin', OTHER: 'x' })+ expect(r.warnings.join('\n')).toContain('not applied to remote')+ })+})++describe('customAgentEnvArgs', () => {+ it('returns KEY=VALUE pairs for the tmux -e list', () => {+ const custom: CustomAgent = {+ id: 'custom:p',+ label: 'Proxy',+ launchCmd: 'claude',+ env: { TOKEN: '${env:MY_TOKEN}', BASE: 'http://x' }+ }+ expect(customAgentEnvArgs(custom, PROC).args).toEqual(['TOKEN=sk-abc', 'BASE=http://x'])+ })+ it('skipPath drops PATH', () => {+ const custom: CustomAgent = {+ id: 'custom:p',+ label: 'Proxy',+ launchCmd: 'claude',+ env: { PATH: '/x', TOKEN: 't' }+ }+ const r = customAgentEnvArgs(custom, PROC, { skipPath: true })+ expect(r.args).toEqual(['TOKEN=t'])+ expect(r.warnings.join('\n')).toContain('remote')+ })+ it('empty for no custom env', () => {+ expect(customAgentEnvArgs(undefined, PROC)).toEqual({ args: [], warnings: [] })+ })+})diff --git a/src/core/custom-agent-env.ts b/src/core/custom-agent-env.tsnew file mode 100644index 000000000..13622c6f8--- /dev/null+++ b/src/core/custom-agent-env.ts@@ -0,0 +1,108 @@+// Pure merge of a custom agent's `env` into a spawn environment — the one place that decides how a+// custom agent's env vars win over nodeterm's own injected env (hooks, account/auth, PATH, LANG).+//+// Used by `pty-manager.spawnSession` for BOTH the local path (merging into the `node-pty` env+// object) and the remote SSH path (merging into the tmux `-e KEY=VALUE` list). Pure + tested so the+// precedence rule — custom env wins LAST, full stop — is verified without spinning a PTY.+//+// The rule exists for the proxy use case: a custom claude-compatible agent sets+// `ANTHROPIC_AUTH_TOKEN` / `ANTHROPIC_BASE_URL` to redirect inference to its own endpoint, and that+// MUST beat whatever the account path set (and the ambient shell env). Merging last is what makes+// the account path's `AUTH_ENV_STRIP` + `CLAUDE_CONFIG_DIR` safe to run first: the account sets up+// its world, then custom env overwrites exactly the vars the user named.++import type { CustomAgent } from '../shared/types'+import { expandEnvVars, preservesInheritedPath } from '../shared/agents/expansion'++export interface EnvMergeResult {+ /** The env with custom vars merged in (a NEW object; the input `env` is not mutated). */+ env: Record<string, string>+ /** Human-readable warnings (missing-var references, PATH-clobber) for the caller to log. */+ warnings: string[]+}++/**+ * Merge `custom?.env` into `env`, expanding `${env:VAR}` / `${env:VAR:fallback}` against+ * `processEnv` and applying each entry LAST so it wins over everything already in `env`.+ *+ * - No custom agent / no env → `env` returned as-is (a shallow copy), no warnings.+ * - A referenced var that is unset and has no fallback → expands to empty; a warning is emitted+ * naming the agent and the missing var (a blanked API key is the failure mode this exists to+ * surface, so it is never silent).+ * - A custom `PATH` that does not reference `${env:PATH}` → a warning that the login-shell PATH is+ * clobbered and CLI resolution may break (suggests `${env:PATH}:/your/bin`).+ * - `skipPath` (remote nodes): a custom `PATH` is DROPPED and a warning emitted — the local machine+ * has no reliable view of the remote box's PATH, so applying a local-resolved PATH remotely would+ * break CLI resolution on the host. Recovering the remote PATH is out of scope.+ */+export function applyCustomAgentEnv(+ env: Record<string, string>,+ custom: CustomAgent | undefined,+ processEnv: Record<string, string | undefined>,+ opts: { skipPath?: boolean } = {}+): EnvMergeResult {+ const out: Record<string, string> = { ...env }+ const warnings: string[] = []+ if (!custom?.env) return { env: out, warnings }+ const who = custom.label || custom.id+ for (const [key, raw] of Object.entries(custom.env)) {+ if (key === 'PATH' && opts.skipPath) {+ warnings.push(+ `[custom-agent] ${who}: custom PATH is not applied to remote sessions (the local machine can't see the remote PATH).`+ )+ continue+ }+ const { value, missing } = expandEnvVars(raw, processEnv)+ out[key] = value+ if (missing.length) {+ warnings.push(+ `[custom-agent] ${who}: env var ${missing.map((m) => '${env:' + m + '}').join(', ')} is unset and has no fallback — expanded to empty.`+ )+ }+ if (key === 'PATH' && !preservesInheritedPath(raw)) {+ warnings.push(+ `[custom-agent] ${who}: custom PATH does not reference \${env:PATH} — the login-shell PATH is clobbered, which may break CLI resolution (e.g. "command not found"). Use \${env:PATH}:/your/bin to augment it.`+ )+ }+ }+ return { env: out, warnings }+}++/**+ * The already-expanded custom-env entries as `KEY=VALUE` strings, for the remote tmux `-e` list.+ * Mirrors `applyCustomAgentEnv`'s expansion + `skipPath` rule but returns pairs instead of merging+ * into an env object (the remote path builds a `-e` arg list, not a process env). `processEnv` is+ * the LOCAL env the expansion runs against — the resolved values travel over SSH, the `${env:…}`+ * tokens never do (the key stays local).+ */+export function customAgentEnvArgs(+ custom: CustomAgent | undefined,+ processEnv: Record<string, string | undefined>,+ opts: { skipPath?: boolean } = {}+): { args: string[]; warnings: string[] } {+ const args: string[] = []+ const warnings: string[] = []+ if (!custom?.env) return { args, warnings }+ const who = custom.label || custom.id+ for (const [key, raw] of Object.entries(custom.env)) {+ if (key === 'PATH' && opts.skipPath) {+ warnings.push(+ `[custom-agent] ${who}: custom PATH is not applied to remote sessions (the local machine can't see the remote PATH).`+ )+ continue+ }+ const { value, missing } = expandEnvVars(raw, processEnv)+ args.push(`${key}=${value}`)+ if (missing.length) {+ warnings.push(+ `[custom-agent] ${who}: env var ${missing.map((m) => '${env:' + m + '}').join(', ')} is unset and has no fallback — expanded to empty.`+ )+ }+ if (key === 'PATH' && !preservesInheritedPath(raw)) {+ warnings.push(+ `[custom-agent] ${who}: custom PATH does not reference \${env:PATH} — the login-shell PATH is clobbered, which may break CLI resolution. Use \${env:PATH}:/your/bin to augment it.`+ )+ }+ }+ return { args, warnings }+}diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.tsindex 147f29e8b..cb8649fa6 100644--- a/src/core/pty-manager.ts+++ b/src/core/pty-manager.ts@@ -72,7 +72,9 @@ import {} from './codex-identity-proxy'import { ensureNodeToken, ensureRemoteNodeToken, sweepNodeToken } from './agents/node-token-service'import { clearNode as clearNodeAgentStatus } from './agent-status-mirror'-import { hasSharedIdentity, type AgentId } from '../shared/agents/config'+import { hasSharedIdentity, setCustomAgentBaseResolver, type AgentId } from '../shared/agents/config'+import { findCustomAgent } from '../shared/agents/custom-agent'+import { applyCustomAgentEnv, customAgentEnvArgs } from './custom-agent-env'// How often we snapshot a live tmux session's scrollback to disk, so a machine reboot (which// kills the tmux server) can still replay recent output on cold restart. A final snapshot also@@ -1190,6 +1192,13 @@ export class PtyManager {/** Must run after app is ready (needs userData path). */init(getSettings: () => Settings): void {this.getSettings = getSettings+ // Register the custom-id → baseAgent resolver so the capability predicates in+ // shared/agents/config (hasHooks, canResume, mintsSessionId, hasPermissionMode,+ // canControlCanvas, …) resolve a custom agent's INHERITED harness. config.ts takes only an id+ // (it cannot import the settings store without a cycle/platform split), so the lookup is+ // injected here: the closure reads LIVE settings, so registering once at init is enough — a+ // settings update is reflected on the next predicate call.+ setCustomAgentBaseResolver((id) => findCustomAgent(this.getSettings().customAgents, id)?.baseAgent)// Prewarm the login-shell PATH probe now so the first terminal spawn doesn't wait on it —// and re-run the tmux probe once it lands: findTmux no longer spawns a login shell of its// own, so a tmux living only on the user's shell PATH is invisible until this resolves.@@ -1993,6 +2002,18 @@ export class PtyManager {for (const k of AUTH_ENV_STRIP) delete env[k]}+ // Custom-agent env: merged LAST so it wins over hook + account + PATH/LANG env (required for+ // the proxy use case — the user's ANTHROPIC_AUTH_TOKEN / ANTHROPIC_BASE_URL must beat whatever+ // the account path set). ${env:VAR} is expanded against the live process env. Only the LOCAL+ // path merges into `env` here; the remote (ssh) path threads the same vars into the tmux `-e`+ // list below (the local ssh client's env does not propagate to the remote tmux session).+ if (!options.sshRemote) {+ const custom = findCustomAgent(this.getSettings().customAgents, options.agentId ?? '')+ const merged = applyCustomAgentEnv(env, custom, process.env as Record<string, string | undefined>)+ for (const [k, v] of Object.entries(merged.env)) env[k] = v+ for (const w of merged.warnings) console.warn(w)+ }+const settings = this.getSettings()let file: stringlet args: string[]@@ -2068,6 +2089,19 @@ export class PtyManager {options.accountId && options.sshRemote.remoteHome? accountTmuxEnvArgs(remoteAccountConfigDirAbs(options.sshRemote.remoteHome, options.accountId)): []+ // Custom-agent env for a REMOTE node: expand ${env:VAR} against the LOCAL process env (the+ // key stays local; only the resolved VALUE travels over SSH) and thread the results into the+ // remote tmux `-e` list. PATH is skipped — the local machine can't see the remote box's PATH,+ // so a locally-resolved PATH would break CLI resolution on the host (recovering it is out of+ // scope). Applied AFTER the account env so custom env still wins, mirroring the local path.+ const remoteCustom = findCustomAgent(this.getSettings().customAgents, options.agentId ?? '')+ const remoteCustomEnv = customAgentEnvArgs(+ remoteCustom,+ process.env as Record<string, string | undefined>,+ { skipPath: true }+ )+ for (const w of remoteCustomEnv.warnings) console.warn(w)+ const remoteCustomEnvArgs = remoteCustomEnv.args.flatMap((kv) => ['-e', kv])args = remoteTmuxPtyArgs(options.sshRemote.conn,options.sshRemote.controlPath,@@ -2079,7 +2113,7 @@ export class PtyManager {// place a foreign value is most at home.reqShell,options.shellArgs,- [...hookExtraEnv, ...remoteAccountEnv],+ [...hookExtraEnv, ...remoteAccountEnv, ...remoteCustomEnvArgs],// Source nodeterm's remote tmux.conf via `-f` (written on connect, Task 2) so a cold-start// session gets mouse/clipboard/scrollback. Fail-open: undefined → remote tmux host defaults.options.sshRemote.tmuxConfPathdiff --git a/src/main/index.ts b/src/main/index.tsindex 5dcaa858a..0b5cebd2e 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -22,6 +22,7 @@ import { PtyManager } from '../core/pty-manager'import { WorkspaceStore } from '../core/workspace-store'import { WorkspaceWatcher } from '../core/workspace-watcher'import { SettingsStore } from '../core/settings-store'+import { registerAgentEnvIpc } from '../core/agent-env-ipc'import { presenceHub } from '../core/presence/hub'import { SshStore } from './ssh-store'import { GitService } from '../core/git-service'@@ -541,6 +542,8 @@ app.whenReady().then(async () => {settingsStore.init()settingsStore.registerIpc()sshStore.registerIpc()+ // Custom-agent preview/expansion IPC (renderer has no process.env; expansion runs here).+ registerAgentEnvIpc()ptyManager.init(() => settingsStore.get())ptyManager.registerIpc()workspaceStore.registerIpc()diff --git a/src/preload/index.ts b/src/preload/index.tsindex ffafcd04e..78da71807 100644--- a/src/preload/index.ts+++ b/src/preload/index.ts@@ -437,6 +437,10 @@ const api: NodeTerminalApi = {readTranscript: (sessionId, cwd, accountId, nodeId) =>ipcRenderer.invoke(IPC.claudeReadTranscript, sessionId, cwd, accountId, nodeId)},+ agent: {+ envSnapshot: () => ipcRenderer.invoke(IPC.envSnapshot),+ previewCommand: (inputs) => ipcRenderer.invoke(IPC.agentPreviewCommand, inputs)+ },chat: {readTranscript: (sessionId, cwd, accountId, nodeId) =>ipcRenderer.invoke(IPC.chatReadTranscript, sessionId, cwd, accountId, nodeId)diff --git a/src/renderer/boot.tsx b/src/renderer/boot.tsxindex d83edb06f..7016ce4ce 100644--- a/src/renderer/boot.tsx+++ b/src/renderer/boot.tsx@@ -3,9 +3,14 @@ import ReactDOM from 'react-dom/client'import App from './App'import { ensureClaudeCliCaps } from './state/permissionMode'import { ensureCodexIdentityCaps } from './state/codexIdentity'+import { initAgentResolver } from './state/agent-resolver'import './styles.css'import './tailwind.css'+// Register the custom-agent → baseAgent resolver so the capability predicates (hasHooks, canResume,+// canControlCanvas, …) resolve a custom agent's inherited harness. Reads the live settings store.+initAgentResolver()+// Probe the local Claude CLI once, up front (never awaited — a launch is never blocked on it):// `--permission-mode auto` only exists in Claude Code >= 2.1.71, and until we know the version we// conservatively omit the flag. The shell warms the same memo at startup, so this normallydiff --git a/src/renderer/bridge/stubs.ts b/src/renderer/bridge/stubs.tsindex e267d0db6..d60db9609 100644--- a/src/renderer/bridge/stubs.ts+++ b/src/renderer/bridge/stubs.ts@@ -272,6 +272,13 @@ export function buildStubApi(): Omit<cliCaps: () => Promise.resolve(UNKNOWN_CLAUDE_CLI_CAPS),readTranscript: U('claude.readTranscript')},+ agent: {+ // The preview/expansion IPC runs main-side (the renderer has no process.env). In the browser+ // (Server Edition) ws-bridge overrides this with the real handler; the stub returns an empty+ // env + unexpanded command so the preview degrades to "unavailable" rather than throwing.+ envSnapshot: () => Promise.resolve({}),+ previewCommand: U('agent.previewCommand')+ },chat: {readTranscript: U('chat.readTranscript')},diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsxindex 6e95ccd49..14a844e49 100644--- a/src/renderer/canvas/Canvas.tsx+++ b/src/renderer/canvas/Canvas.tsx@@ -864,9 +864,6 @@ export function Canvas() {// When pinned the sidebar is docked and stays open (mouse-leave never closes it); `dismissed`// hides it until the next hover/click. When unpinned it is a pure hover-peek.const sessionsOpen = sessionsPinned ? !sessionsDismissed : sessionsHover- // When set, add a terminal to this project once its nodes have loaded into React Flow- // (cross-project "add" from the sidebar, which must switch projects first).- const pendingAddRef = useRef<string | null>(null)// Live relay tabs, keyed by relay connectionId, so a host/relay drop can dispose the right one// (a remote connection is now a project TAB, not a full-surface overlay — Stage 4 Task 6).const relayTabsRef = useRef<Map<string, RelayTab>>(new Map())@@ -1842,12 +1839,6 @@ export function Canvas() {useAgentStatus.getState().clearUnread(pending)}}- // Consume a cross-project "add terminal" request from the sessions sidebar (which had- // to switch projects first). Only act if we landed on the requested project.- if (pendingAddRef.current === useProjects.getState().activeProjectId) {- pendingAddRef.current = null- addTerminal()- }}, 0)return () => clearTimeout(t)// eslint-disable-next-line react-hooks/exhaustive-deps@@ -5339,9 +5330,11 @@ export function Canvas() {const agentCreationItems = useCallback((at?: { x: number; y: number }, groupId?: string): MenuItem[] => {const disabled = useSettings.getState().settings.disabledAgents- // Accounts selectable in the active project: local accounts for a local project, or this- // host's accounts for an SSH project (pending logins always excluded).- const project = useProjects.getState().getProject(activeProjectId)+ // Read the active project LIVE from the store (not the closure value) so a menu built right+ // after a `switchProject` — e.g. the sessions-sidebar "+" opening this menu on a non-active+ // project — resolves accounts against the project the user clicked, not the one that was+ // active when this callback was created. `switchProject` sets the store synchronously.+ const project = useProjects.getState().getProject(useProjects.getState().activeProjectId)const accounts = accountsForProject(useSettings.getState().settings.claudeAccounts, project)// The system entry shows the user's custom label / detected email so it stays// distinguishable from managed accounts (falls back to "System account").@@ -5413,7 +5406,7 @@ export function Canvas() {)]},- [activeProjectId, addAgentNode]+ [addAgentNode])const groupItems = useCallback(@@ -7479,16 +7472,34 @@ export function Canvas() {)const addToProject = useCallback(- (projectId: string) => {- if (projectId === activeProjectId) {- addTerminal()- } else {- // Add once the project's nodes have loaded into React Flow (load effect consumes this).- pendingAddRef.current = projectId- switchProject(projectId)- }+ (projectId: string, e?: { clientX: number; clientY: number }) => {+ // The sessions-sidebar "+" used to open a bare terminal. It now opens the SAME agent menu+ // the canvas right-click uses (with "New terminal" kept on top so the old behavior is a+ // deliberate pick, not lost) — so adding to a project picks an agent instead of always a+ // shell. For a non-active project, switch FIRST (synchronous) so the menu's account rows+ // resolve against the clicked project; the node is only added on the user's later click,+ // well after the project's canvas has loaded, so there is no load-race.+ if (projectId !== activeProjectId) switchProject(projectId)+ const pos = e ? { x: e.clientX, y: e.clientY } : { x: 80, y: 120 }+ setMenu({+ x: pos.x,+ y: pos.y,+ items: [+ {+ label: 'New terminal',+ icon: <IconTerminal />,+ onClick: () => {+ // For a non-active project the switch happened above; addTerminal targets the+ // active project, which is now this one.+ addTerminal()+ }+ },+ { type: 'separator' },+ ...agentCreationItems()+ ]+ })},- [activeProjectId, addTerminal, switchProject]+ [activeProjectId, addTerminal, switchProject, agentCreationItems])// Sidebar drag-to-group: reparent a session into a canvas group (groupId) or out (null).diff --git a/src/renderer/components/Dock.tsx b/src/renderer/components/Dock.tsxindex 380c7bf74..be2e43d2e 100644--- a/src/renderer/components/Dock.tsx+++ b/src/renderer/components/Dock.tsx@@ -1,5 +1,6 @@import { useState } from 'react'-import { AGENT_CONFIG, BUILTIN_AGENT_IDS, type AgentId } from '@shared/agents/config'+import { AGENT_CONFIG, BUILTIN_AGENT_IDS, type AgentId, type BuiltinAgentId } from '@shared/agents/config'+import type { CustomAgent } from '@shared/types'import { formatShortcut, isHoldChord } from '@shared/shortcut'import { hintLabel } from '@shared/platform-utils'import { AgentIcon } from '../lib/agentIcons'@@ -57,6 +58,10 @@ export function Dock({dictateActive}: DockProps) {const [menuOpen, setMenuOpen] = useState(false)+ // Which builtin's flyout submenu is open (at most one). A builtin earns a flyout only when it has+ // ≥1 inheriting custom agent (one with a `baseAgent` matching it); otherwise it stays a flat+ // button, byte-identical to before this nesting existed.+ const [openSub, setOpenSub] = useState<BuiltinAgentId | null>(null)const dictationShortcut = useSettings((s) => s.settings.speech.shortcut)const customAgents = useSettings((s) => s.settings.customAgents)const disabledAgents = useSettings((s) => s.settings.disabledAgents)@@ -72,6 +77,20 @@ export function Dock({? activeProject?.defaultAccountId: undefined+ // Group enabled custom agents by their declared base harness. A builtin with a non-empty group+ // gets a flyout submenu (the base itself + its inheriting customs, and for Claude the account+ // rows); a builtin with an empty group stays flat. Baseless custom agents render flat after the+ // builtins, exactly as they did before.+ const enabledCustoms = customAgents.filter((c) => !disabledAgents.includes(c.id))+ const inheritingByBase = new Map<BuiltinAgentId, CustomAgent[]>()+ for (const c of enabledCustoms) {+ if (!c.baseAgent) continue+ const arr = inheritingByBase.get(c.baseAgent) ?? []+ arr.push(c)+ inheritingByBase.set(c.baseAgent, arr)+ }+ const baselessCustoms = enabledCustoms.filter((c) => !c.baseAgent)+const pick = (fn: () => void) => () => {fn()setMenuOpen(false)@@ -93,48 +112,103 @@ export function Dock({<span>Remote…</span></button>{BUILTIN_AGENT_IDS.filter((aid) => !disabledAgents.includes(aid)).flatMap((aid) => {- const base = (- <button key={aid} onClick={pick(() => onAddAgent(aid))}>- <AgentIcon agentId={aid} size={18} />- <span>{AGENT_CONFIG[aid].label}</span>- </button>- )- if (aid !== 'claude') return [base]- // SSH project with no accounts on its host: a disabled row saying where this- // host's accounts come from (local accounts are correctly invisible here).- const acctHint = sshAccountsHint(activeProject, localAccounts)- if (acctHint) {- return [- base,- <button key={`${aid}-acct-hint`} disabled title={acctHint}>+ const inheriting = inheritingByBase.get(aid) ?? []+ // No inheriting customs → the builtin stays a flat button (with Claude's account+ // rows), byte-identical to before nesting existed.+ if (inheriting.length === 0) {+ const base = (+ <button key={aid} onClick={pick(() => onAddAgent(aid))}><AgentIcon agentId={aid} size={18} />- <span>No accounts on this host yet</span>+ <span>{AGENT_CONFIG[aid].label}</span></button>+ )+ if (aid !== 'claude') return [base]+ // SSH project with no accounts on its host: a disabled row saying where this+ // host's accounts come from (local accounts are correctly invisible here).+ const acctHint = sshAccountsHint(activeProject, localAccounts)+ if (acctHint) {+ return [+ base,+ <button key={`${aid}-acct-hint`} disabled title={acctHint}>+ <AgentIcon agentId={aid} size={18} />+ <span>No accounts on this host yet</span>+ </button>+ ]+ }+ // Claude picks up one flat entry per logged-in local account.+ if (localAccounts.length === 0) return [base]+ return [+ base,+ ...localAccounts.map((a) => (+ <button key={`${aid}-${a.id}`} onClick={pick(() => onAddAgent(aid, a.id))}>+ <AgentIcon agentId={aid} size={18} />+ <span>+ Claude — {a.label}+ {a.id === defaultAccountId ? ' ✓' : ''}+ </span>+ </button>+ ))]}- // Claude picks up one flat entry per logged-in local account (dock can't nest).- if (localAccounts.length === 0) return [base]+ // Has inheriting customs → render as a flyout submenu. The parent button still+ // launches the base harness in one click (preserving today's behavior); hovering it+ // reveals the base's variants — its account rows (Claude) and the inheriting customs.+ const acctHint = sshAccountsHint(activeProject, localAccounts)return [- base,- ...localAccounts.map((a) => (- <button key={`${aid}-${a.id}`} onClick={pick(() => onAddAgent(aid, a.id))}>+ <div+ key={aid}+ className="dock-menu__has-sub"+ onMouseEnter={() => setOpenSub(aid)}+ onMouseLeave={() => setOpenSub((cur) => (cur === aid ? null : cur))}+ >+ <button onClick={pick(() => onAddAgent(aid))}><AgentIcon agentId={aid} size={18} />- <span>- Claude — {a.label}- {a.id === defaultAccountId ? ' ✓' : ''}- </span>+ <span>{AGENT_CONFIG[aid].label}</span>+ <span className="dock-menu__chevron">▸</span></button>- ))+ {openSub === aid && (+ <div className="dock-menu__sub">+ {aid === 'claude' && localAccounts.length > 0 && (+ <>+ <div className="dock-menu__sub-label">Accounts</div>+ {localAccounts.map((a) => (+ <button+ key={a.id}+ onClick={pick(() => onAddAgent(aid, a.id))}+ >+ <AgentIcon agentId={aid} size={18} />+ <span>+ {a.label}+ {a.id === defaultAccountId ? ' ✓' : ''}+ </span>+ </button>+ ))}+ </>+ )}+ {aid === 'claude' && acctHint && (+ <button disabled title={acctHint}>+ <AgentIcon agentId={aid} size={18} />+ <span>No accounts on this host yet</span>+ </button>+ )}+ <div className="dock-menu__sub-label">Custom</div>+ {inheriting.map((c) => (+ <button key={c.id} onClick={pick(() => onAddAgent(c.id))}>+ <AgentIcon agentId={c.id} size={18} />+ <span>{c.label}</span>+ </button>+ ))}+ </div>+ )}+ </div>]})}- {customAgents- .filter((c) => !disabledAgents.includes(c.id))- .map((c) => (- <button key={c.id} onClick={pick(() => onAddAgent(c.id))}>- <AgentIcon agentId={c.id} size={18} />- <span>{c.label}</span>- </button>- ))}+ {baselessCustoms.map((c) => (+ <button key={c.id} onClick={pick(() => onAddAgent(c.id))}>+ <AgentIcon agentId={c.id} size={18} />+ <span>{c.label}</span>+ </button>+ ))}<button onClick={pick(onAddSticky)}><NoteIcon /><span>Sticky Note</span>diff --git a/src/renderer/components/SessionsSidebar.tsx b/src/renderer/components/SessionsSidebar.tsxindex 546838ead..b41ba9bf5 100644--- a/src/renderer/components/SessionsSidebar.tsx+++ b/src/renderer/components/SessionsSidebar.tsx@@ -39,7 +39,9 @@ export interface SessionsSidebarProps {* or the outgoing project's unsaved edits are dropped by the active-project reload and the* new activeProjectId never reaches disk (the app reopens on the old project). */onSwitchProject(projectId: string): void- onAddToProject(projectId: string): void+ /** "+" on a project header: open the agent-creation menu at the cursor (switching to the+ * project first if it isn't active). The event positions the menu. */+ onAddToProject(projectId: string, e: { clientX: number; clientY: number }): void/** Move a node into a canvas group (groupId) or out to the top level (null). */onMoveToGroup(projectId: string, nodeId: string, groupId: string | null): void/** Name a canvas group with AI from its member terminals' output. */@@ -535,10 +537,10 @@ export function SessionsSidebar(props: SessionsSidebarProps): JSX.Element | null<span className="ss-group__count">{projectCount(g)}</span><buttonclassName="ss-group__add"- title="New terminal in this project"+ title="New agent in this project"onClick={(e) => {e.stopPropagation()- props.onAddToProject(g.projectId)+ props.onAddToProject(g.projectId, { clientX: e.clientX, clientY: e.clientY })}}>+diff --git a/src/renderer/components/settings/sections/AgentsSection.tsx b/src/renderer/components/settings/sections/AgentsSection.tsxindex af2972b13..c1fcb7860 100644--- a/src/renderer/components/settings/sections/AgentsSection.tsx+++ b/src/renderer/components/settings/sections/AgentsSection.tsx@@ -234,15 +234,13 @@ export function AgentsSection({ isActive }: { isActive: boolean }): React.JSX.El<div key={row.id} className="flex items-center gap-3 py-1.5"><AgentIcon agentId={row.id} size={18} /><span className="flex-1 text-[13px] text-text">{row.label}</span>- {row.isBuiltin && (- <Button- variant={isDefault ? 'primary' : 'default'}- aria-pressed={isDefault}- onClick={() => update(setDefaultAgent(settings, row.id))}- >- {isDefault ? 'Default' : 'Set default'}- </Button>- )}+ <Button+ variant={isDefault ? 'primary' : 'default'}+ aria-pressed={isDefault}+ onClick={() => update(setDefaultAgent(settings, row.id))}+ >+ {isDefault ? 'Default' : 'Set default'}+ </Button><SegmentedPill<'enabled' | 'disabled'>value={enabled ? 'enabled' : 'disabled'}ariaLabel={`${row.label} availability`}diff --git a/src/renderer/components/settings/sections/CustomAgentsSection.tsx b/src/renderer/components/settings/sections/CustomAgentsSection.tsxindex 0cc8cd4b1..6daef0238 100644--- a/src/renderer/components/settings/sections/CustomAgentsSection.tsx+++ b/src/renderer/components/settings/sections/CustomAgentsSection.tsx@@ -1,6 +1,13 @@+import { useEffect, useState } from 'react'import { useSettings } from '../../../state/settings'+import { firstEnabledBuiltin } 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'@@ -10,17 +17,31 @@ import { Select } from '@renderer/ui/Select'import { uuid } from '@renderer/lib/uuid'const ROWS = {- custom: { title: 'Custom agents', keywords: ['custom', 'agent', 'cli', 'byo', 'aider'] }+ custom: {+ title: 'Custom agents',+ keywords: ['custom', 'agent', 'cli', 'byo', 'aider', 'proxy', 'env', 'base url', 'api key']+ }}const ENTRIES = Object.values(ROWS)+const INJECTION_MODES: PromptInjectionMode[] = ['argv', 'flag-prompt', 'stdin-after-start']+export function CustomAgentsSection({ isActive }: { isActive: boolean }): React.JSX.Element {const customAgents = useSettings((s) => s.settings.customAgents)const update = useSettings((s) => s.update)const patchAgent = (id: string, patch: Partial<CustomAgent>) =>update({ customAgents: customAgents.map((a) => (a.id === id ? { ...a, ...patch } : a)) })const removeAgent = (id: string) =>- update({ customAgents: customAgents.filter((a) => a.id !== id) })+ update((() => {+ // If the removed custom agent WAS the default, reassign to the first enabled builtin so+ // ⌘⇧C never points at a deleted agent. Mirrors setAgentEnabled's disabled-default guard.+ const next = { customAgents: customAgents.filter((a) => a.id !== id) }+ const isDefault = useSettings.getState().settings.defaultAgent === id+ if (isDefault) {+ return { ...next, defaultAgent: firstEnabledBuiltin(useSettings.getState().settings.disabledAgents) }+ }+ return next+ })())const addAgent = () =>update({customAgents: [@@ -33,59 +54,19 @@ export function CustomAgentsSection({ isActive }: { isActive: boolean }): React.}]})+return (<SettingsSectionid="custom-agents"title="Custom agents"- description="Bring your own agent CLI. Custom agents launch in a terminal and show process / title status only (no hooks, branch, or loop)."+ description="Bring your own agent CLI, or wrap a built-in harness (e.g. Claude) to redirect inference to your own proxy. Env values support ${env:VAR} and ${env:VAR:fallback} expansion against your shell environment."isActive={isActive}searchEntries={ENTRIES}><SearchableRow {...ROWS.custom}><div className="space-y-4">{customAgents.map((agent) => (- <div key={agent.id} className="space-y-2 rounded-md border border-border p-3">- <FieldRow- label="Label"- control={- <Input- className="w-56"- placeholder="e.g. Aider"- value={agent.label}- onChange={(e) => patchAgent(agent.id, { label: e.target.value })}- />- }- />- <FieldRow- label="Launch command"- control={- <Input- className="w-56"- placeholder="e.g. aider"- value={agent.launchCmd}- onChange={(e) => patchAgent(agent.id, { launchCmd: e.target.value })}- />- }- />- <FieldRow- label="Prompt injection"- control={- <Select- value={agent.promptInjectionMode}- onChange={(e) =>- patchAgent(agent.id, {- promptInjectionMode: e.target.value as PromptInjectionMode- })- }- >- <option value="argv">argv</option>- <option value="flag-prompt">flag-prompt</option>- <option value="stdin-after-start">stdin-after-start</option>- </Select>- }- />- <Button onClick={() => removeAgent(agent.id)}>Remove</Button>- </div>+ <AgentCard key={agent.id} agent={agent} onPatch={patchAgent} onRemove={removeAgent} />))}<Button onClick={addAgent}>Add agent</Button></div>@@ -93,3 +74,241 @@ export function CustomAgentsSection({ isActive }: { isActive: boolean }): React.</SettingsSection>)}++function AgentCard({+ agent,+ onPatch,+ onRemove+}: {+ agent: CustomAgent+ onPatch: (id: string, patch: Partial<CustomAgent>) => void+ onRemove: (id: string) => void+}): React.JSX.Element {+ const base = agent.baseAgent ? AGENT_CONFIG[agent.baseAgent] : undefined+ const setEnvEntry = (key: string, value: string) => {+ const env = { ...(agent.env ?? {}) }+ if (value === '' && key !== '') delete env[key]+ else env[key] = value+ onPatch(agent.id, { env })+ }+ const addEnvEntry = () => {+ const env = { ...(agent.env ?? {}) }+ let k = 'NEW_VAR'+ let i = 1+ while (env[k] !== undefined) k = `NEW_VAR_${++i}`+ env[k] = ''+ onPatch(agent.id, { env })+ }+ const removeEnvEntry = (key: string) => {+ const env = { ...(agent.env ?? {}) }+ delete env[key]+ onPatch(agent.id, { env })+ }++ return (+ <div className="space-y-2 rounded-md border border-border p-3">+ <FieldRow+ label="Label"+ control={+ <Input+ className="w-56"+ placeholder="e.g. Claude (proxy)"+ value={agent.label}+ onChange={(e) => onPatch(agent.id, { label: e.target.value })}+ />+ }+ />+ <FieldRow+ label="Base harness"+ description={+ base+ ? `Inherits ${base.label}'s hooks, resume, permission modes, and canvas control.`+ : 'Optional: inherit a built-in harness’s integrations. Blank = a standalone CLI.'+ }+ control={+ <Select+ value={agent.baseAgent ?? ''}+ onChange={(e) =>+ onPatch(agent.id, {+ baseAgent: (e.target.value || undefined) as CustomAgent['baseAgent']+ })+ }+ >+ <option value="">None (standalone CLI)</option>+ {BUILTIN_AGENT_IDS.map((id) => (+ <option key={id} value={id}>+ {AGENT_CONFIG[id].label}+ </option>+ ))}+ </Select>+ }+ />+ <FieldRow+ label="Launch command"+ description={+ base && !agent.launchCmd?.trim() ? `Blank uses the base command ("${base.launchCmd}").` : undefined+ }+ control={+ <Input+ className="w-56"+ placeholder={base ? base.launchCmd : 'e.g. aider'}+ value={agent.launchCmd}+ onChange={(e) => onPatch(agent.id, { launchCmd: e.target.value })}+ />+ }+ />+ <FieldRow+ label="Extra args"+ description="Inserted after the command, before the prompt. Supports ${env:VAR}."+ control={+ <Input+ className="w-56"+ placeholder="e.g. --model ${env:MY_MODEL}"+ value={agent.args ?? ''}+ onChange={(e) => onPatch(agent.id, { args: e.target.value })}+ />+ }+ />+ <FieldRow+ label="Prompt injection"+ description={base ? `Inherited from ${base.label}.` : undefined}+ control={+ <Select+ value={agent.promptInjectionMode ?? 'argv'}+ disabled={!!base}+ onChange={(e) =>+ onPatch(agent.id, { promptInjectionMode: e.target.value as PromptInjectionMode })+ }+ >+ {INJECTION_MODES.map((m) => (+ <option key={m} value={m}>+ {m}+ </option>+ ))}+ </Select>+ }+ />++ {/* Env vars editor */}+ <div className="space-y-1.5">+ <div className="flex items-center justify-between">+ <span className="text-sm font-medium text-text">Environment variables</span>+ <Button onClick={addEnvEntry}>Add var</Button>+ </div>+ <p className="text-[13px] leading-relaxed text-muted">+ Merged at spawn and win over nodeterm’s own env (so a proxy token beats an account login).+ Values expand <code className="text-text">${'{env:VAR}'}</code> and+ <code className="text-text"> ${'{env:VAR:fallback}'}</code> against your shell. A custom+ PATH should reference <code className="text-text">{'${env:PATH}'}</code> or CLI resolution+ may break; custom PATH is not applied to remote sessions.+ </p>+ {Object.entries(agent.env ?? {}).map(([key, value]) => (+ <EnvRow+ key={key}+ entryKey={key}+ value={value}+ onKeyChange={(newKey) => {+ if (newKey === key) return+ const env = { ...(agent.env ?? {}) }+ delete env[key]+ env[newKey] = value+ onPatch(agent.id, { env })+ }}+ onValueChange={(v) => setEnvEntry(key, v)}+ onRemove={() => removeEnvEntry(key)}+ />+ ))}+ </div>++ <CommandPreview agent={agent} />++ <Button onClick={() => onRemove(agent.id)}>Remove</Button>+ </div>+ )+}++function EnvRow({+ entryKey,+ value,+ onKeyChange,+ onValueChange,+ onRemove+}: {+ entryKey: string+ value: string+ onKeyChange: (key: string) => void+ onValueChange: (value: string) => void+ onRemove: () => void+}): React.JSX.Element {+ const [revealed, setRevealed] = useState(false)+ const isPathLike = entryKey.toUpperCase() === 'PATH'+ const pathWarn =+ isPathLike && !value.includes('${env:PATH}')+ ? 'Does not reference ${env:PATH} — may break CLI resolution.'+ : undefined+ return (+ <div className="flex items-center gap-2">+ <Input className="w-40 font-mono" value={entryKey} onChange={(e) => onKeyChange(e.target.value)} />+ <Input+ className="w-44 font-mono"+ type={revealed ? 'text' : 'password'}+ placeholder="${env:MY_API_KEY}"+ value={value}+ onChange={(e) => onValueChange(e.target.value)}+ />+ <Button variant="default" onClick={() => setRevealed((v) => !v)}>+ {revealed ? 'Hide' : 'Show'}+ </Button>+ <Button onClick={onRemove}>✕</Button>+ {pathWarn ? <span className="text-[12px] text-[color:var(--warn)]">{pathWarn}</span> : null}+ </div>+ )+}++/**+ * Live, fully-expanded preview of the command nodeterm will run for this agent. Assembled + expanded+ * main-side (the renderer has no process.env) so it is identical to the real launch. Re-fetches on a+ * debounce as the agent's fields change.+ */+function CommandPreview({ agent }: { agent: CustomAgent }): React.JSX.Element | null {+ const [preview, setPreview] = useState<{ command: string; missingEnv: string[] } | null>(null)+ // Re-run when any field that affects the command changes.+ const sig = `${agent.id}|${agent.launchCmd}|${agent.args ?? ''}|${agent.baseAgent ?? ''}|${agent.promptInjectionMode ?? ''}`+ useEffect(() => {+ let alive = true+ const t = setTimeout(() => {+ window.nodeTerminal.agent+ .previewCommand({+ agentId: agent.id as AgentId,+ customAgent: agent,+ initialPrompt: '<your prompt>',+ sessionIdFlagSupported: true+ })+ .then((r) => {+ if (alive) setPreview(r)+ })+ .catch(() => {+ if (alive) setPreview(null)+ })+ }, 250)+ return () => {+ alive = false+ clearTimeout(t)+ }+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [sig])+ if (!preview) return null+ return (+ <div className="rounded-md bg-bg-2 p-2">+ <div className="mb-1 text-[12px] font-medium text-muted">Command preview</div>+ <code className="block break-all text-[12px] text-text">+ {preview.command || <span className="text-muted">(empty)</span>}+ </code>+ {preview.missingEnv.length > 0 ? (+ <div className="mt-1 text-[12px] text-[color:var(--warn)]">+ Unset: {preview.missingEnv.map((m) => `${'{env:' + m + '}'}`).join(', ')}+ </div>+ ) : null}+ </div>+ )+}diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsxindex 013ff9dfd..3eb8b564d 100644--- a/src/renderer/nodes/TerminalNode.tsx+++ b/src/renderer/nodes/TerminalNode.tsx@@ -141,8 +141,9 @@ 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 { 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 } from '@shared/agents/config'import { withPermissionMode } from '@shared/agents/approval-mode'+import { assembleResumeCommand } from '@shared/agents/launch'import { ensureActivePermissionMode } from '../state/permissionMode'import { buildSshArgs, sshConnectionIdForProject, sshHostKey, type SshConnection } from '@shared/ssh'import { hintLabel } from '@shared/platform-utils'@@ -2756,24 +2757,30 @@ 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)- const base =- (priorId && resumeCommand(agentId, priorId, shared)) ||- (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, sharedIdentity: shared },+ {}+ )if (cmd) writeWhenShellReady(cmd) // same shell-startup race as initialCommand}})@@ -2830,16 +2837,25 @@ export function TerminalNode({const agentSessionId = st?.sessionIdconst gate = restartEligibility(agentId, st?.state, agentSessionId)if (!gate.ok || !agentId || !agentSessionId || !restartTarget()) return 'not-eligible'- // Built HERE, not inside the choreography: `withPermissionMode` is the single funnel for- // every CLI launch path (shared/agents/config.ts) and the mode is a renderer-side, async+ // Built HERE, not inside the choreography: the shared assembly builder is the single funnel+ // for every CLI launch path (shared/agents/launch.ts) and the mode is a renderer-side, async// 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.- const base = resumeCommand(agentId, agentSessionId)- 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.+ 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)+ },+ {}+ )return performRestartResume({agentId,sessionId: agentSessionId,@@ -2926,25 +2942,34 @@ export function TerminalNode({// version probe behind `ensureActivePermissionMode` most of all), and whatever is asked// first is stale by the time the delivery runs — so the fact that must be freshest is the// one asked last: what owns the pane we are about to type into.- // Same funnel, same await, same reasoning as the restart closure above: the permission+ // Same builder, same await, same reasoning as the restart closure above: the permission// mode is a property of how a session is LAUNCHED, so it is re-resolved now (a wake can be- // hours after the exit, and days after the node was created).+ // hours after the exit, and days after the node was created). Inheritance-aware via the+ // shared assembler, so a custom agent's baseAgent/args are re-applied on wake.+ //// Deliberately the BARE command, with no shared-identity launcher: this types into a pane// that already exists, and a tmux session created before the launcher was installed does// 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.- const base = resumeCommand(agentId, agentSessionId)+ 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+ },+ {}+ )// 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)// and then declined to resume.- if (!base) return 'not-eligible'- const command = withPermissionMode(- base,- agentId,- await ensureActivePermissionMode(agentId)- )+ if (!command) return 'not-eligible'// THE load-bearing gate of the wake half. Hours can pass between the exit and this// resume, and the pane is a REPL the user can type into: by now it may belong to vim, to// `top`, or to a claude the user launched by hand — and a launch line typed into a livediff --git a/src/renderer/state/agent-resolver.ts b/src/renderer/state/agent-resolver.tsnew file mode 100644index 000000000..ef1bfc2f3--- /dev/null+++ b/src/renderer/state/agent-resolver.ts@@ -0,0 +1,19 @@+// Renderer-side registration of the custom-agent → baseAgent resolver.+//+// The capability predicates in `@shared/agents/config` (hasHooks, canResume, mintsSessionId,+// hasPermissionMode, canControlCanvas, …) take only an `AgentId` and resolve custom inheritance+// through an injected registry (config.ts cannot import the settings store without a cycle). The+// main process registers its own resolver in pty-manager.init; the RENDERER needs one too, because+// it calls those same predicates 60+ times to gate UI (status badges, hibernation, canvas control,+// resume, restart menus). This reads the live Zustand settings store, so registering once at boot+// is enough — a settings update is reflected on the next predicate call.++import { setCustomAgentBaseResolver } from '@shared/agents/config'+import { useSettings } from './settings'++/** Register once at boot (called from boot.tsx). Idempotent. */+export function initAgentResolver(): void {+ setCustomAgentBaseResolver(+ (id) => useSettings.getState().settings.customAgents.find((c) => c.id === id)?.baseAgent+ )+}diff --git a/src/renderer/state/workspace.ts b/src/renderer/state/workspace.tsindex 486d55761..c242263c3 100644--- a/src/renderer/state/workspace.ts+++ b/src/renderer/state/workspace.ts@@ -1,8 +1,8 @@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 { agentConfig, agentLaunchProgram, mintsSessionId, withSessionId } from '@shared/agents/config'-import { withPermissionMode } from '@shared/agents/approval-mode'+import { agentConfig, mintsSessionId } from '@shared/agents/config'+import { assembleLaunchCommand } from '@shared/agents/launch'import { uuid } from '@renderer/lib/uuid'import { claudeCliCapsNow } from './permissionMode'import { codexSharedIdentity } from './codexIdentity'@@ -130,10 +130,11 @@ export interface NodeData {/** React Flow node type string mirrors the persisted NodeKind. */export type CanvasNode = Node<NodeData, NodeKind>-/** Single-quote a string for safe use as one shell argument (POSIX). */-export function shellSingleQuote(s: string): string {- return `'${s.replace(/'/g, `'\\''`)}'`-}+/** Single-quote a string for safe use as one shell argument (POSIX).+ * Imported from `@shared/shell-quote` so the renderer and the shared command-assembly layer share+ * one definition, and re-exported so the renderer keeps its historical import path. */+import { shellSingleQuote } from '@shared/shell-quote'+export { shellSingleQuote }/*** 8 hex characters of CSPRNG — the unique tail of every node and project id.@@ -360,40 +361,7 @@ 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).- const baseCmd =- agentId === 'claude'- ? claudeLaunchCommand()- : 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)// 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@@ -402,29 +370,46 @@ export function createAgentNode(// 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 mintedSessionId = mintsSessionId(agentId) && cliCaps.sessionIdFlag ? 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. The renderer has no process.env, so expansion here runs against an+ // empty snapshot — but the FIRST-LAUNCH command typed into the shell only carries ${env:...} when+ // the user put it in launchCmd/args, and the real env merge happens main-side in pty-manager+ // (env values are injected as process env, NOT typed into the shell, so they never needed+ // renderer-side expansion). 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: cliCaps.sessionIdFlag,+ // 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 renderer has no process.env; pass an empty record. ${env:...} in launchCmd/args resolves+ // to empty here, but that only affects the TYPED command — env-var VALUES are injected as+ // process env by pty-manager (main-side, against the real env), not typed into the shell.+ {}+ )+ 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'),@@ -441,7 +426,8 @@ export function createAgentNode(group: null,tags: [],agentId,- // Accounts are inherently Claude-only — never stamp one onto another agent's node.+ // Accounts are inherently Claude-only — never stamp one onto another agent's node. A custom+ // agent inheriting claude is still its own agent; account binding stays claude-the-builtin....(accountId && agentId === 'claude' ? { accountId } : {}),// Persisted alongside the node (unlike initialCommand, which is consumed on first open), so// a cold restore months later still knows which conversation this node owns.diff --git a/src/renderer/styles.css b/src/renderer/styles.cssindex a0dd8094b..d580a3649 100644--- a/src/renderer/styles.css+++ b/src/renderer/styles.css@@ -641,6 +641,57 @@ body,flex-shrink: 0;}+/* One level of flyout submenu — for a builtin harness that has inheriting custom agents (e.g. a+ * claude-compatible proxy). The parent button carries a ▸ chevron; hovering/focusing it opens the+ * flyout to the right of the menu. Reused only when there is something to nest, so a menu with no+ * inheriting customs is byte-identical to before. */+.dock-menu__has-sub {+ position: relative;+}+.dock-menu__chevron {+ margin-left: auto;+ font-size: 12px;+ color: var(--muted);+}+.dock-menu__sub {+ position: absolute;+ left: 100%;+ top: -6px;+ min-width: 190px;+ display: flex;+ flex-direction: column;+ gap: 2px;+ padding: 6px;+ background: rgba(var(--menu-rgb), 0.98);+ backdrop-filter: blur(10px);+ border: 1px solid var(--border);+ border-radius: 12px;+ box-shadow: 0 12px 36px rgba(0, 0, 0, calc(0.55 * var(--shadow-k)));+}+.dock-menu__sub button {+ display: flex;+ align-items: center;+ gap: 12px;+ padding: 9px 12px;+ background: transparent;+ color: var(--text);+ border: none;+ border-radius: 8px;+ font-size: 14px;+ text-align: left;+ cursor: pointer;+}+.dock-menu__sub button:hover:not(:disabled) {+ background: var(--panel-header);+}+.dock-menu__sub-label {+ padding: 4px 12px 2px;+ font-size: 11px;+ text-transform: uppercase;+ letter-spacing: 0.04em;+ color: var(--muted);+}+/* ---- Dictation overlay: bottom-center floating card above the Dock ---- */.dictation {position: fixed;diff --git a/src/renderer/terminal/agent-restart.ts b/src/renderer/terminal/agent-restart.tsindex 995abd766..bf83a4413 100644--- a/src/renderer/terminal/agent-restart.ts+++ b/src/renderer/terminal/agent-restart.ts@@ -4,7 +4,7 @@* model list without losing the conversation. Kept free of DOM/IPC so the node menu, the bulk* filter and the restart choreography can all share exactly one set of rules.*/-import { canResume, resumeCommand } from '../../shared/agents/config'+import { canResume, canResumeWith, capabilityAgentId, resumeCommand } from '../../shared/agents/config'import { isShellCommand } from '@shared/agents/pane'import {DELIVERY_ATTEMPTS,@@ -36,7 +36,10 @@ const EXIT_SEQUENCES: Record<string, string> = {}export function exitSequence(agentId: string): string | null {- return EXIT_SEQUENCES[agentId] ?? null+ // Resolve through the BASE harness so a custom agent that inherits claude (e.g. a proxy wrapper)+ // exits with claude's `/exit` — its own CLI grammar is claude's. A baseless custom agent has no+ // exit sequence (no safe way to ask an unknown CLI to quit) and returns null, as before.+ return EXIT_SEQUENCES[capabilityAgentId(agentId)] ?? null}/** Re-exported, not redefined: it lives in `@shared/agents/pane` so the main process can ask the@@ -154,10 +157,12 @@ export async function performExitPhase(d: {isLive?: () => boolean}): Promise<ExitPhaseOutcome> {const exit = exitSequence(d.agentId)- const base = resumeCommand(d.agentId, d.sessionId)- // The BARE command is the gate: `resumeCommand` is what validates the session id before it- // reaches a command line, and a session we could not resume must not be quit.- if (!exit || !base) return 'not-eligible'+ // The eligibility GATE (not the command): `canResumeWith` validates the session id the way+ // `resumeCommand` does, without building the command — which for a custom agent needs its+ // `launchCmd` from settings (unavailable in this pure module). The typed resume line is the+ // caller's job (`performResumePhase` takes it as `d.command`); the exit half only needs to know+ // the session is one we WOULD resume into, so it does not quit a conversation it cannot bring back.+ if (!exit || !canResumeWith(d.agentId, d.sessionId)) return 'not-eligible'const timeoutMs = d.timeoutMs ?? RESTART_EXIT_TIMEOUT_MSconst pollMs = d.pollMs ?? RESTART_POLL_MS// A dead session is not a restart that failed — there is no pane left to fail in. `'not-eligible'`@@ -249,11 +254,15 @@ export async function performResumePhase(d: {*/isLive?: () => boolean}): Promise<ResumePhaseOutcome> {+ // The eligibility GATE (see performExitPhase): `canResumeWith` validates the session id without+ // building the command. The typed line is the caller's `d.command`; for a builtin with no+ // override, `resumeCommand` supplies the bare resume command. A custom agent MUST pass+ // `d.command` (its baseAgent-aware line, built by `assembleResumeCommand` in the node) — it has+ // no `resumeCommand` here, so a missing `command` for a custom agent refuses before any write.+ if (!canResumeWith(d.agentId, d.sessionId)) return 'not-eligible'const base = resumeCommand(d.agentId, d.sessionId)- // The BARE command is the gate even when the caller overrides it: `resumeCommand` is what- // validates the session id before it reaches a command line.- if (!base) return 'not-eligible'const cmd = d.command ?? base+ if (!cmd) return 'not-eligible'const gone = (): boolean => !!d.isLive && !d.isLive()// Awaited, not fire-and-forget: see the header. `deliverCommand` is started inside the executor// (synchronously, so `onDelivery` still hands the cancel out before any await) and announces thediff --git a/src/server/index.ts b/src/server/index.tsindex 657cc3786..c84528935 100644--- a/src/server/index.ts+++ b/src/server/index.ts@@ -14,6 +14,7 @@ import type { ServerConfig } from './config'import { initPlatform } from '../core/platform'import { SettingsStore } from '../core/settings-store'import { WorkspaceStore } from '../core/workspace-store'+import { registerAgentEnvIpc } from '../core/agent-env-ipc'import { PtyManager } from '../core/pty-manager'import { registerCoreHandlers } from './handlers'import { registerGitHubIntegration } from '../core/github/integration'@@ -160,6 +161,8 @@ export async function startServer(settingsStore.init()settingsStore.registerIpc()+ // Custom-agent preview/expansion IPC (browser has no process.env; expansion runs server-side).+ registerAgentEnvIpc()ptyManager.init(() => settingsStore.get())ptyManager.registerIpc()workspaceStore.registerIpc()diff --git a/src/shared/agents/config.ts b/src/shared/agents/config.tsindex 1d07a66c0..0a0ae844c 100644--- a/src/shared/agents/config.ts+++ b/src/shared/agents/config.ts@@ -204,7 +204,54 @@ export const PERMISSION_MODE_CAPABLE = ['claude', 'grok', 'gemini', 'codex'] as// copy notice joins by being added here, and nothing else changes.export const SELF_REPORTS_COPY = ['claude'] as const-const includes = (list: readonly string[], id: AgentId): boolean => list.includes(id)+/** Fallback color for custom / unknown agents that have no config-provided color. */+export const FALLBACK_AGENT_COLOR = '#888888'++// ---------------------------------------------------------------------------------------------+// Custom-agent harness inheritance.+//+// A custom agent (`CustomAgent`, id `'custom:<uuid>'`) may declare a `baseAgent` — one of the+// builtins — to inherit that harness's CAPABILITIES (hooks, resume, permission modes, canvas+// control, session-id minting) and prompt convention. The use case is a harness-compatible CLI+// (e.g. a claude wrapper pointed at your own inference proxy) where you want to KEEP nodeterm's+// integration while redirecting the calls.+//+// The capability predicates below take only an `AgentId`. `src/shared/agents/config.ts` cannot+// import the settings store (renderer) or `settings-store` (core) without a cycle / platform+// split, so the custom-id → baseAgent lookup is INJECTED: each runtime registers a resolver at+// init that reads its own live settings. This mirrors the existing mutable-accessor idiom+// (`claudeCliCapsNow`, `shellPathNow`): module-level state, set once at boot, read on every call.+//+// Tests register a resolver (or null) via `setCustomAgentBaseResolverForTests`.+type BaseResolver = (id: AgentId) => BuiltinAgentId | undefined+let customBaseResolver: BaseResolver | null = null++/** Register the custom-id → baseAgent resolver. Called once at app init by the renderer+ * (`state/agent-resolver.ts`) and by main/core (`pty-manager`) and the server shell, each+ * reading its own settings store. Pass `null` to clear (tests). */+export function setCustomAgentBaseResolver(fn: BaseResolver | null): void {+ customBaseResolver = fn+}++/** The builtin harness a custom agent inherits from, or `undefined` for builtins and vanilla+ * (no-`baseAgent`) custom agents. Builtins never resolve through the registry — they ARE the+ * harness — so a custom agent whose id accidentally collides with a builtin name still resolves+ * as the builtin, never as itself. */+export function baseAgentOf(id: AgentId): BuiltinAgentId | undefined {+ if (!customBaseResolver) return undefined+ if ((AGENT_CONFIG as Record<string, AgentConfig>)[id]) return undefined+ return customBaseResolver(id)+}++/** The id whose capabilities apply to `id`: the base harness for an inheriting custom agent, else+ * `id` itself. This is what every capability predicate resolves through, so inheritance is+ * automatic everywhere a predicate is called — no per-call-site plumbing. */+export function capabilityAgentId(id: AgentId): AgentId {+ return baseAgentOf(id) ?? id+}++const includes = (list: readonly string[], id: AgentId): boolean =>+ list.includes(capabilityAgentId(id))export const hasHooks = (id: AgentId): boolean => includes(AGENT_HOOK_TARGETS, id)export const canResume = (id: AgentId): boolean => includes(RESUMABLE_AGENTS, id)@@ -307,18 +354,54 @@ export function withSessionId(cmd: string, id: AgentId, sessionId: string): stri* client. Default false = the bare command this has always emitted (see `agentLaunchProgram`).*/export function resumeCommand(id: AgentId, sessionId: string, sharedIdentity = false): 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)+ 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 nullconst sid = sessionId.trim()if (!sid || !SAFE_SESSION_ID.test(sid)) return null- switch (id) {+ switch (grammarId) {case 'codex':- return `${agentLaunchProgram('codex', 'codex', sharedIdentity)} resume ${sid}`+ return `${launchCmd} resume ${sid}`case 'opencode':- return `opencode --session ${sid}`+ return `${launchCmd} --session ${sid}`case 'claude':case 'gemini':case 'grok':- return `${id} --resume ${sid}`+ return `${launchCmd} --resume ${sid}`default:return null}diff --git a/src/shared/agents/custom-agent.test.ts b/src/shared/agents/custom-agent.test.tsnew file mode 100644index 000000000..61f59c2b9--- /dev/null+++ b/src/shared/agents/custom-agent.test.ts@@ -0,0 +1,114 @@+import { afterEach, describe, expect, it } from 'vitest'+import {+ baseAgentOf,+ canResume,+ capabilityAgentId,+ hasHooks,+ hasPermissionMode,+ mintsSessionId,+ setCustomAgentBaseResolver+} from './config'+import { findCustomAgent, resolveAgentConfig } from './custom-agent'+import type { CustomAgent } from '../types'++const claudeProxy: CustomAgent = {+ id: 'custom:proxy',+ label: 'Claude (proxy)',+ launchCmd: 'claude-wopr',+ baseAgent: 'claude',+ env: { ANTHROPIC_AUTH_TOKEN: '${env:MY_TOKEN}' },+ args: '--model ${env:MY_MODEL}'+}+const vanilla: CustomAgent = {+ id: 'custom:aider',+ label: 'Aider',+ launchCmd: 'aider',+ promptInjectionMode: 'argv'+}++afterEach(() => setCustomAgentBaseResolver(null))++describe('resolveAgentConfig — builtins', () => {+ it('returns the builtin config untouched', () => {+ const c = resolveAgentConfig('claude')+ expect(c).toMatchObject({+ label: 'Claude Code',+ color: '#d97757',+ launchCmd: 'claude',+ promptInjectionMode: 'argv',+ custom: false+ })+ expect(c.argvPromptSeparator).toBeUndefined()+ })+ it('grok carries its separator', () => {+ expect(resolveAgentConfig('grok').argvPromptSeparator).toBe('--')+ })+})++describe('resolveAgentConfig — custom without a base', () => {+ it('uses the custom fields and falls back to grey / argv', () => {+ const c = resolveAgentConfig('custom:aider', vanilla)+ expect(c).toMatchObject({+ label: 'Aider',+ launchCmd: 'aider',+ promptInjectionMode: 'argv',+ color: '#888888',+ custom: true+ })+ expect(c.argvPromptSeparator).toBeUndefined()+ expect(c.expectedProcess).toBeUndefined()+ })+})++describe('resolveAgentConfig — custom with a base harness', () => {+ it('inherits the base command when launchCmd is blank', () => {+ const blank: CustomAgent = { id: 'custom:proxy2', label: 'P', launchCmd: '', baseAgent: 'claude' }+ expect(resolveAgentConfig('custom:proxy2', blank).launchCmd).toBe('claude')+ })+ it('uses the custom launchCmd when set', () => {+ expect(resolveAgentConfig('custom:proxy', claudeProxy).launchCmd).toBe('claude-wopr')+ })+ it('inherits promptInjectionMode / separator / expectedProcess from the base', () => {+ const c = resolveAgentConfig('custom:proxy', claudeProxy)+ expect(c.promptInjectionMode).toBe('argv')+ expect(c.expectedProcess).toBe('claude')+ expect(c.baseAgent).toBe('claude')+ })+ it('inherits color from the base when the custom record has none', () => {+ expect(resolveAgentConfig('custom:proxy', claudeProxy).color).toBe('#d97757')+ })+})++describe('capability inheritance via the resolver registry', () => {+ it('a custom agent with no resolver registered inherits nothing', () => {+ setCustomAgentBaseResolver(null)+ expect(hasHooks('custom:proxy')).toBe(false)+ expect(canResume('custom:proxy')).toBe(false)+ expect(mintsSessionId('custom:proxy')).toBe(false)+ expect(hasPermissionMode('custom:proxy')).toBe(false)+ expect(capabilityAgentId('custom:proxy')).toBe('custom:proxy')+ })+ it('registering a baseAgent resolver makes the custom agent inherit that harness', () => {+ setCustomAgentBaseResolver((id) => (id === 'custom:proxy' ? 'claude' : undefined))+ expect(baseAgentOf('custom:proxy')).toBe('claude')+ expect(baseAgentOf('claude')).toBeUndefined() // builtins never resolve through the registry+ expect(capabilityAgentId('custom:proxy')).toBe('claude')+ expect(hasHooks('custom:proxy')).toBe(true)+ expect(canResume('custom:proxy')).toBe(true)+ expect(mintsSessionId('custom:proxy')).toBe(true)+ expect(hasPermissionMode('custom:proxy')).toBe(true)+ })+ it('builtins are unaffected by the resolver', () => {+ setCustomAgentBaseResolver((id) => (id === 'custom:proxy' ? 'claude' : undefined))+ expect(hasHooks('codex')).toBe(true)+ expect(mintsSessionId('gemini')).toBe(false)+ })+})++describe('findCustomAgent', () => {+ it('finds a custom agent by id and returns undefined for builtins', () => {+ expect(findCustomAgent([claudeProxy, vanilla], 'custom:proxy')).toBe(claudeProxy)+ expect(findCustomAgent([claudeProxy, vanilla], 'claude')).toBeUndefined()+ expect(findCustomAgent([claudeProxy, vanilla], 'custom:nope')).toBeUndefined()+ })+})diff --git a/src/shared/agents/custom-agent.ts b/src/shared/agents/custom-agent.tsnew file mode 100644index 000000000..db89b5301--- /dev/null+++ b/src/shared/agents/custom-agent.ts@@ -0,0 +1,91 @@+// Resolves an agent id to its EFFECTIVE launch config — the one place that knows how a custom+// agent with a `baseAgent` inherits a builtin's prompt convention, color, separator, and+// expected-process name, while letting the custom agent's own fields override.+//+// `agentConfig(id)` (in ./config) still returns `undefined` for custom ids on purpose — many call+// sites rely on "undefined = this is a custom agent" to switch off a feature. THIS function is the+// positive complement: it always returns a usable config for any id, so the command-assembly layer+// and the UI can treat builtins and custom agents uniformly.++import type { CustomAgent } from '../types'+import {+ AGENT_CONFIG,+ FALLBACK_AGENT_COLOR,+ agentConfig,+ baseAgentOf,+ type AgentId,+ type BuiltinAgentId,+ type PromptInjectionMode+} from './config'++/**+ * The launch config an agent actually runs with. Shape mirrors `AgentConfig` but `expectedProcess`+ * and `argvPromptSeparator` are optional (a vanilla custom agent has neither), and `custom` tells+ * the caller whether this came from a `CustomAgent` record.+ */+export interface EffectiveAgentConfig {+ label: string+ color: string+ launchCmd: string+ promptInjectionMode: PromptInjectionMode+ argvPromptSeparator?: string+ expectedProcess?: string+ /** `true` for a custom agent (`CustomAgent`), `false` for a builtin. */+ custom: boolean+ /** The builtin harness this agent inherits from, if any. */+ baseAgent?: BuiltinAgentId+}++/**+ * Resolve `id` to its effective config. For a builtin, returns its `AGENT_CONFIG` entry. For a+ * custom agent, `customAgent` is the matching `CustomAgent` record (the caller looks it up by id+ * from settings); fields inherit from `baseAgent` and the custom record overrides:+ * - `launchCmd`: custom value, else the base harness's command (so a claude-compatible proxy with+ * a blank command runs `claude`), else the id itself (today's fallback for vanilla customs).+ * - `promptInjectionMode`: custom value, else the base's, else `argv`.+ * - `color`: custom value, else the base's, else the fallback grey.+ * - `argvPromptSeparator` / `expectedProcess`: from the base only (a custom record does not set+ * these — inheriting them is the whole point of declaring a base).+ */+export function resolveAgentConfig(+ id: AgentId,+ customAgent?: CustomAgent+): EffectiveAgentConfig {+ const builtin = agentConfig(id)+ if (builtin) {+ return { ...builtin, custom: false }+ }+ const base = customAgent?.baseAgent ? AGENT_CONFIG[customAgent.baseAgent] : undefined+ const launchCmd = customAgent?.launchCmd?.trim() || base?.launchCmd || id+ const promptInjectionMode: PromptInjectionMode =+ customAgent?.promptInjectionMode ?? base?.promptInjectionMode ?? 'argv'+ const color = customAgent?.color || base?.color || FALLBACK_AGENT_COLOR+ return {+ label: customAgent?.label || id,+ color,+ launchCmd,+ promptInjectionMode,+ argvPromptSeparator: base?.argvPromptSeparator,+ expectedProcess: base?.expectedProcess,+ custom: true,+ baseAgent: customAgent?.baseAgent+ }+}++/** Find a custom agent by id in a settings list. Returns `undefined` for builtins / unknowns. */+export function findCustomAgent(+ customAgents: readonly CustomAgent[],+ id: AgentId+): CustomAgent | undefined {+ if ((AGENT_CONFIG as Record<string, unknown>)[id]) return undefined+ return customAgents.find((c) => c.id === id)+}++/** The baseAgent declared on a custom agent record (the static field), without the resolver+ * registry — handy where the record is already in hand. */+export function declaredBaseAgent(customAgent: CustomAgent | undefined): BuiltinAgentId | undefined {+ return customAgent?.baseAgent+}++// Re-export so the launcher can reach the registry through one import.+export { baseAgentOf }diff --git a/src/shared/agents/expansion.test.ts b/src/shared/agents/expansion.test.tsnew file mode 100644index 000000000..52bc11967--- /dev/null+++ b/src/shared/agents/expansion.test.ts@@ -0,0 +1,74 @@+import { describe, expect, it } from 'vitest'+import { expandEnvVars, preservesInheritedPath } from './expansion'++describe('expandEnvVars', () => {+ it('returns the input unchanged when no token is present', () => {+ expect(expandEnvVars('claude --resume abc', { FOO: 'bar' })).toEqual({+ value: 'claude --resume abc',+ missing: []+ })+ })++ it('expands ${env:VAR} to the env value (VS Code colon syntax)', () => {+ expect(expandEnvVars('${env:MY_API_KEY}', { MY_API_KEY: 'sk-123' })).toEqual({+ value: 'sk-123',+ missing: []+ })+ })++ it('uses the fallback when the var is unset (${env:VAR:fallback})', () => {+ expect(expandEnvVars('${env:MISSING:dev-key}', {})).toEqual({+ value: 'dev-key',+ missing: []+ })+ })++ it('records a missing var with no fallback as empty + missing', () => {+ expect(expandEnvVars('${env:NOPE}', {})).toEqual({ value: '', missing: ['NOPE'] })+ })++ it('expands a token embedded in surrounding text', () => {+ expect(+ expandEnvVars('ANTHROPIC_BASE_URL=${env:BASE}/v1', { BASE: 'http://localhost:8080' })+ ).toEqual({ value: 'ANTHROPIC_BASE_URL=http://localhost:8080/v1', missing: [] })+ })++ it('expands multiple tokens and reports only the truly missing ones', () => {+ const r = expandEnvVars('${env:A}/${env:B}:${env:C:default}/${env:D}', {+ A: 'a',+ B: 'b'+ })+ expect(r).toEqual({ value: 'a/b:default/', missing: ['D'] })+ })++ it('treats an empty-string env value as unset (uses fallback / missing)', () => {+ expect(expandEnvVars('${env:EMPTY:fallback}', { EMPTY: '' })).toEqual({+ value: 'fallback',+ missing: []+ })+ expect(expandEnvVars('${env:EMPTY}', { EMPTY: '' })).toEqual({+ value: '',+ missing: ['EMPTY']+ })+ })++ it('only matches the env namespace (does not expand ${config:…})', () => {+ expect(expandEnvVars('${config:foo}', { foo: 'x' })).toEqual({+ value: '${config:foo}',+ missing: []+ })+ })+})++describe('preservesInheritedPath', () => {+ it('true when there is no PATH override', () => {+ expect(preservesInheritedPath(undefined)).toBe(true)+ expect(preservesInheritedPath('')).toBe(true)+ })+ it('true when the value references ${env:PATH}', () => {+ expect(preservesInheritedPath('${env:PATH}:/my/bin')).toBe(true)+ })+ it('false when the value clobbers PATH outright', () => {+ expect(preservesInheritedPath('/my/bin')).toBe(false)+ })+})diff --git a/src/shared/agents/expansion.ts b/src/shared/agents/expansion.tsnew file mode 100644index 000000000..1568fddb1--- /dev/null+++ b/src/shared/agents/expansion.ts@@ -0,0 +1,56 @@+// `${env:VAR}` string expansion — VS Code's variable-substitution syntax, applied to a custom+// agent's `env` values, `args`, and `launchCmd`.+//+// VS Code uses `${env:Name}` (colon, single braces) — confirmed against the official+// variables-reference page; the `${env.Name}` dot form belongs to GitHub Actions (`${{ env.X }}`,+// double braces), not VS Code. We ADD a default-value form VS Code lacks, `${env:VAR:fallback}`,+// because a proxy config often wants a fallback (`${env:MY_TOKEN:dev-key}`) and the alternative —+// a missing var silently blanking the value — is the failure mode that makes proxy setup brittle.+//+// Pure: the environment is an explicit `Record<string, string | undefined>` parameter, never a+// global read, so the same function serves the spawn path (main, `process.env`) and the renderer's+// command-assembly path (an env snapshot fetched over IPC) and tests (a literal object).++/** Matches one `${env:NAME}` or `${env:NAME:fallback}` token. The fallback is everything up to the+ * closing `}` (no nested expansion inside the fallback — keep it literal). */+const ENV_TOKEN = /\$\{env:([A-Za-z_][A-Za-z0-9_]*)(?::([^}]*))?\}/g++export interface ExpansionResult {+ /** The string with every `${env:…}` token replaced. */+ value: string+ /** Variable names that were referenced, had no value, and had NO fallback — i.e. they expanded+ * to empty. Surfaced so the caller can warn (at spawn, or as a red `<unset>` in the preview)+ * rather than silently launching with a blank API key. */+ missing: string[]+}++/**+ * Expand `${env:VAR}` / `${env:VAR:fallback}` tokens in `input` against `env`.+ *+ * - A var that is set → its value.+ * - A var that is unset but has a fallback → the fallback text.+ * - A var that is unset and has no fallback → empty string, and its name is returned in `missing`.+ */+export function expandEnvVars(+ input: string,+ env: Record<string, string | undefined>+): ExpansionResult {+ if (!input.includes('${env:')) return { value: input, missing: [] }+ const missing: string[] = []+ const value = input.replace(ENV_TOKEN, (whole, name: string, fallback: string | undefined) => {+ const v = env[name]+ if (v !== undefined && v !== '') return v+ if (fallback !== undefined) return fallback+ missing.push(name)+ return ''+ })+ return { value, missing }+}++/** Does `value` (a custom `PATH` env entry) preserve the inherited PATH via `${env:PATH}`?+ * Used to warn the user when a custom PATH would clobber the login-shell PATH and break CLI+ * resolution — the classic `command not found: claude` — instead of augmenting it. */+export function preservesInheritedPath(value: string | undefined): boolean {+ if (!value) return true // no override+ return value.includes('${env:PATH}')+}diff --git a/src/shared/agents/launch.test.ts b/src/shared/agents/launch.test.tsnew file mode 100644index 000000000..a7e2f90a5--- /dev/null+++ b/src/shared/agents/launch.test.ts@@ -0,0 +1,120 @@+import { afterEach, describe, expect, it } from 'vitest'+import { assembleLaunchCommand, assembleResumeCommand } from './launch'+import { setCustomAgentBaseResolver } from './config'+import type { CustomAgent } from '../types'++const ENV = { MY_MODEL: 'sonnet', MY_TOKEN: 'sk-abc' }++const claudeProxy: CustomAgent = {+ id: 'custom:proxy',+ label: 'Claude (proxy)',+ launchCmd: 'claude-wopr',+ baseAgent: 'claude',+ args: '--model ${env:MY_MODEL}'+}+const aider: CustomAgent = {+ id: 'custom:aider',+ label: 'Aider',+ launchCmd: 'aider',+ promptInjectionMode: 'argv'+}++afterEach(() => setCustomAgentBaseResolver(null))++describe('assembleLaunchCommand — builtins (byte-identical to the historical path)', () => {+ it('claude bare', () => {+ expect(assembleLaunchCommand({ agentId: 'claude' }, ENV).command).toBe('claude')+ })+ it("claude with a prompt", () => {+ expect(assembleLaunchCommand({ agentId: 'claude', initialPrompt: 'fix the bug' }, ENV).command).toBe(+ "claude 'fix the bug'"+ )+ })+ it('claude with prompt + permission mode + minted session id', () => {+ expect(+ assembleLaunchCommand(+ { agentId: 'claude', initialPrompt: 'fix', permissionMode: 'auto', sessionId: 'abc-123', sessionIdFlagSupported: true },+ ENV+ ).command+ ).toBe("claude 'fix' --permission-mode auto --session-id abc-123")+ })+ it('claude omits --session-id when the CLI does not support it', () => {+ expect(+ assembleLaunchCommand(+ { agentId: 'claude', sessionId: 'abc-123', sessionIdFlagSupported: false },+ ENV+ ).command+ ).toBe('claude')+ })+ it('grok puts the permission flag BEFORE the -- separator', () => {+ expect(+ assembleLaunchCommand({ agentId: 'grok', initialPrompt: 'version', permissionMode: 'plan' }, ENV).command+ ).toBe("grok --permission-mode plan -- 'version'")+ })+ it('opencode uses --prompt (flag-prompt mode)', () => {+ expect(+ assembleLaunchCommand({ agentId: 'opencode', initialPrompt: 'fix it' }, ENV).command+ ).toBe("opencode --prompt 'fix it'")+ })+})++describe('assembleLaunchCommand — custom agents', () => {+ it('a vanilla custom agent launches with its command + prompt', () => {+ expect(+ assembleLaunchCommand({ agentId: 'custom:aider', customAgent: aider, initialPrompt: 'hi' }, ENV).command+ ).toBe("aider 'hi'")+ })+ it('a claude-base proxy inherits the claude command grammar + flags', () => {+ setCustomAgentBaseResolver((id) => (id === 'custom:proxy' ? 'claude' : undefined))+ const r = assembleLaunchCommand(+ { agentId: 'custom:proxy', customAgent: claudeProxy, initialPrompt: 'fix', permissionMode: 'auto', sessionId: 's1', sessionIdFlagSupported: true },+ ENV+ )+ // args are expanded + each token quoted; flags appended like claude.+ expect(r.command).toBe("claude-wopr '--model' 'sonnet' 'fix' --permission-mode auto --session-id s1")+ expect(r.missingEnv).toEqual([])+ })+ it('expands ${env:…} in args and reports missing vars', () => {+ setCustomAgentBaseResolver((id) => (id === 'custom:proxy' ? 'claude' : undefined))+ const r = assembleLaunchCommand(+ { agentId: 'custom:proxy', customAgent: { ...claudeProxy, args: '--model ${env:UNSET}' } },+ {}+ )+ expect(r.missingEnv).toEqual(['UNSET'])+ })+ it('a blank launchCmd with a baseAgent uses the base harness command', () => {+ setCustomAgentBaseResolver((id) => (id === 'custom:blank' ? 'claude' : undefined))+ const blank: CustomAgent = { id: 'custom:blank', label: 'B', launchCmd: '', baseAgent: 'claude' }+ expect(assembleLaunchCommand({ agentId: 'custom:blank', customAgent: blank }, ENV).command).toBe('claude')+ })+})++describe('assembleResumeCommand', () => {+ it('claude resumes with --resume', () => {+ expect(assembleResumeCommand({ agentId: 'claude', sessionId: 'abc-123' }, ENV).command).toBe(+ 'claude --resume abc-123'+ )+ })+ it('codex resumes with the subcommand form', () => {+ expect(assembleResumeCommand({ agentId: 'codex', sessionId: 'abc-123' }, ENV).command).toBe(+ 'codex resume abc-123'+ )+ })+ it('falls back to the bare launch command when there is no session id', () => {+ expect(assembleResumeCommand({ agentId: 'claude' }, ENV).command).toBe('claude')+ })+ it('a claude-base proxy resumes with its own binary + claude grammar + args', () => {+ setCustomAgentBaseResolver((id) => (id === 'custom:proxy' ? 'claude' : undefined))+ expect(+ assembleResumeCommand(+ { agentId: 'custom:proxy', customAgent: claudeProxy, sessionId: 'abc-123', permissionMode: 'plan' },+ ENV+ ).command+ ).toBe("claude-wopr '--model' 'sonnet' --resume abc-123 --permission-mode plan")+ })+ it('a non-resumable vanilla custom agent falls back to its bare launch command', () => {+ expect(+ assembleResumeCommand({ agentId: 'custom:aider', customAgent: aider }, ENV).command+ ).toBe('aider')+ })+})diff --git a/src/shared/agents/launch.ts b/src/shared/agents/launch.tsnew file mode 100644index 000000000..8a7f4f111--- /dev/null+++ b/src/shared/agents/launch.ts@@ -0,0 +1,157 @@+// Pure command assembly — the ONE place an agent's launch / resume command line is built.+//+// Used by the renderer (fresh node creation in `workspace.ts createAgentNode`, cold-restore resume+// in `TerminalNode.tsx`) and by the main process (the preview IPC handler, so the settings card+// can show the exact command nodeterm will run). Pure: the environment is an explicit parameter+// (the renderer passes an IPC-fetched snapshot; main passes `process.env`), so the same function+// serves every caller and the preview can never drift from the real launch.+//+// 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 { 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'++export interface LaunchInputs {+ agentId: AgentId+ /** The matching `CustomAgent` record when `agentId` is a custom id. `undefined` for builtins. */+ customAgent?: CustomAgent+ /** 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+ /** 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+ /** The provider session id to resume (live hook id, or the minted id persisted on the node). */+ sessionId?: string+ permissionMode?: AgentPermissionMode+ /** 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[]+}++/** Expand + shell-split + re-quote a custom agent's `args` into a safe argv fragment. Expansion+ * (`${env:…}`) runs first; the shell-split then tokenizes; each token is single-quoted so a+ * resolved value carrying spaces or metacharacters stays one argument and a stray `;`/`$` in the+ * raw text can never reach the shell as syntax. 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 { value, missing } = expandEnvVars(raw, env)+ const tokens = shellSplit(value).map(shellSingleQuote)+ return { fragment: 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 } = expandEnvVars(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)+ 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 isFlagPrompt = eff.promptInjectionMode === 'flag-prompt'+ const usesSep = !!promptArg && !!sep && !isFlagPrompt+ const withPrompt = promptArg+ ? isFlagPrompt+ ? `${baseCmd} --prompt ${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 withSessionId(withMode, capId, inputs.sessionId)+ }+ return withMode+ }++ 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 } = expandEnvVars(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)+ 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 command = inputs.permissionMode+ ? withPermissionMode(base, capId, inputs.permissionMode)+ : base+ return { command, missingEnv: [...m1, ...m2] }+}diff --git a/src/shared/ipc.ts b/src/shared/ipc.tsindex 9d87416e1..f79c41306 100644--- a/src/shared/ipc.ts+++ b/src/shared/ipc.ts@@ -44,6 +44,15 @@ export const IPC = {/** main/server → renderer: a Codex node's identity mode changed ('shared' | 'plain'). The* 'plain' events are what make the launcher's fallback visible instead of silent. */codexIdentity: 'codex-identity:event',+ /** Renderer → main: a snapshot of the main process's `process.env`, used to expand `${env:VAR}`+ * tokens in the custom-agent settings preview (the renderer has no `process.env` of its own).+ * Values are strings; undefined entries are omitted. */+ envSnapshot: 'env:snapshot',+ /** Renderer → main: assemble + `${env:…}`-expand a custom agent's launch command against the+ * main process env, returning the exact string nodeterm will type into the shell. Powers the+ * live preview in Settings → Custom agents. Payload: `LaunchInputs`; resolves+ * `{ command, missingEnv }`. */+ agentPreviewCommand: 'agent:preview-command',transcriptSearch: 'transcript:search',appToggleMarkdown: 'app:toggle-markdown',appCloseNode: 'app:close-node',diff --git a/src/shared/shell-quote.test.ts b/src/shared/shell-quote.test.tsnew file mode 100644index 000000000..a2998760d--- /dev/null+++ b/src/shared/shell-quote.test.ts@@ -0,0 +1,33 @@+import { describe, expect, it } from 'vitest'+import { shellSingleQuote, shellSplit } from './shell-quote'++describe('shellSingleQuote', () => {+ it('wraps a plain string in single quotes', () => {+ expect(shellSingleQuote('fix the bug')).toBe("'fix the bug'")+ })+ it("escapes embedded single quotes", () => {+ expect(shellSingleQuote("it's")).toBe("'it'\\''s'")+ })+})++describe('shellSplit', () => {+ it('splits on whitespace', () => {+ expect(shellSplit('--model x --api-key foo')).toEqual(['--model', 'x', '--api-key', 'foo'])+ })+ it('preserves quoted substrings as single tokens', () => {+ expect(shellSplit("--msg 'hello world'")).toEqual(['--msg', 'hello world'])+ })+ it('handles double quotes', () => {+ expect(shellSplit('--x "a b" c')).toEqual(['--x', 'a b', 'c'])+ })+ it('honors backslash escapes', () => {+ expect(shellSplit('a\\ b c')).toEqual(['a b', 'c'])+ })+ it('returns [] for empty / whitespace input', () => {+ expect(shellSplit('')).toEqual([])+ expect(shellSplit(' ')).toEqual([])+ })+ it('does NOT perform shell variable expansion ($VAR stays literal)', () => {+ expect(shellSplit('$HOME/x')).toEqual(['$HOME/x'])+ })+})diff --git a/src/shared/shell-quote.ts b/src/shared/shell-quote.tsnew file mode 100644index 000000000..0c1ca51e9--- /dev/null+++ b/src/shared/shell-quote.ts@@ -0,0 +1,71 @@+/** Single-quote a string for safe use as one shell argument (POSIX).+ *+ * Lives in `src/shared` so both the renderer's command assembly and any main/server-side+ * command builder share one definition — a second copy would drift the quoting and let an+ * unescaped quote reach a tmux `send-keys` line. */+export function shellSingleQuote(s: string): string {+ // POSIX single-quote: wrap in single quotes, and replace each embedded single quote with the+ // close-quote/escaped-quote/reopen-quote sequence `'\''`. Plain concatenation (not a template+ // literal) on purpose — a nested-backtick template for the replacement is legal but fragile+ // under tooling, and this is the one function whose correctness every typed command depends on.+ return "'" + s.replace(/'/g, "'\\''") + "'"+}++/**+ * Split a free-text argv string into tokens the way a POSIX shell would, honoring single and+ * double quotes and backslash escapes. Used for a custom agent's `args` field, which the user+ * types as one string (matching `launchCmd`) but which must become discrete argv before the prompt+ * is appended.+ *+ * Deliberately NOT a full shell: no variable expansion, no command substitution, no tilde. The+ * expansion that DOES happen (`${env:VAR}`) is nodeterm's own, run BEFORE this split, so a+ * resolved value containing spaces is indistinguishable from a quoted one only if the user quoted+ * it — i.e. the user keeps the same control they have at a real shell.+ */+export function shellSplit(input: string): string[] {+ const tokens: string[] = []+ let buf = ''+ let i = 0+ let inSingle = false+ let inDouble = false+ let hasToken = false+ const push = () => {+ if (hasToken) tokens.push(buf)+ buf = ''+ hasToken = false+ }+ while (i < input.length) {+ const c = input[i]+ if (inSingle) {+ if (c === "'") inSingle = false+ else buf += c+ } else if (inDouble) {+ if (c === '\\' && input[i + 1] !== undefined) {+ buf += input[i + 1]+ i+++ } else if (c === '"') {+ inDouble = false+ } else {+ buf += c+ }+ } else if (c === '\\' && input[i + 1] !== undefined) {+ buf += input[i + 1]+ hasToken = true+ i+++ } else if (c === "'") {+ inSingle = true+ hasToken = true+ } else if (c === '"') {+ inDouble = true+ hasToken = true+ } else if (/\s/.test(c)) {+ push()+ } else {+ buf += c+ hasToken = true+ }+ i+++ }+ push()+ return tokens+}diff --git a/src/shared/types.ts b/src/shared/types.tsindex 502e367f7..1899e83da 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -2,7 +2,7 @@import type { CloneProgress } from './clone-url'import type { NormalizedAgentEvent } from './agents/normalize'-import type { AgentId, AgentPermissionMode, PromptInjectionMode } from './agents/config'+import type { AgentId, AgentPermissionMode, BuiltinAgentId, PromptInjectionMode } from './agents/config'import type { AgentMessageDeliverRequest, AgentMessageReply } from './agents/agent-messaging'import type { GroupWorktree } from './worktree'import type { ClientId, DinoSnapshot, PeerDiff, PeerIdentity, PeerState } from './presence'@@ -779,14 +779,31 @@ export interface BrowserApi {onBrowserNewWindow(listener: (e: { url: string; sourceNodeId: string }) => void): () => void}-/** A user-defined agent (BYO CLI). In no capability list, so it gets only spawn +- * terminal-title + process status (no hooks/branch/loop/bridge). */+/** A user-defined agent (BYO CLI). With no `baseAgent` it is in no capability list, so it gets+ * only spawn + terminal-title + process status (no hooks/branch/loop/bridge). With a `baseAgent`+ * it inherits that builtin harness's capabilities (hooks, resume, permission modes, canvas+ * control) and prompt convention — the use case being a harness-compatible CLI pointed at your+ * own inference proxy, where you want to KEEP nodeterm's integration while redirecting the calls. */export interface CustomAgent {/** Stable id of the form 'custom:<uuid>'. Used as the node's agentId. */id: stringlabel: string+ /** Base launch command. Blank when `baseAgent` is set means "use the base harness's command"+ * (so a claude-compatible proxy needs zero launch config). */launchCmd: string- promptInjectionMode: PromptInjectionMode+ /** Prompt convention. Optional: inherited from `baseAgent` when set, else defaults to 'argv'. */+ promptInjectionMode?: PromptInjectionMode+ /** Optional builtin harness to inherit capabilities + prompt convention from. */+ baseAgent?: BuiltinAgentId+ /** Env vars injected at spawn, merged LAST so they win over hook/account env (required for the+ * proxy case — your ANTHROPIC_AUTH_TOKEN must beat any account env). Values support+ * `${env:VAR}` / `${env:VAR:fallback}` expansion at spawn time against the live OS env. */+ env?: Record<string, string>+ /** Extra argv inserted after `launchCmd`, before the prompt/flags. Free-text, shell-split.+ * Supports `${env:…}` expansion. Blank = none. */+ args?: string+ /** Node color. Falls back to `baseAgent`'s color (or the default grey). */+ color?: string}/**@@ -2001,6 +2018,27 @@ export interface ClaudeApi {export type HandoffResult = { filePath: string } | { error: string }+/** Agent launch/preview IPC. The renderer has no `process.env`, so env-var expansion for the+ * custom-agent settings preview is done main-side against the real OS environment — guaranteeing+ * the preview matches what `pty-manager` will actually run. */+export interface AgentApi {+ /** A string-only snapshot of the main process environment (undefined entries omitted), for+ * expanding `${env:VAR}` tokens in the preview. */+ envSnapshot(): Promise<Record<string, string>>+ /** Assemble + expand a custom agent's FIRST-LAUNCH command against the main env. Returns the+ * command string and any env vars that were referenced but unset (no fallback) — surfaced as+ * `<unset>` markers in the preview. `inputs` is structurally `LaunchInputs`+ * (src/shared/agents/launch.ts); typed loosely here to avoid a types↔launch import cycle. */+ previewCommand(inputs: {+ agentId: AgentId+ customAgent?: CustomAgent+ initialPrompt?: string+ permissionMode?: AgentPermissionMode+ sessionId?: string+ sessionIdFlagSupported?: boolean+ }): Promise<{ command: string; missingEnv: string[] }>+}+export interface HandoffApi {/*** Render the source agent's full conversation transcript (located by `sessionId`)@@ -2254,6 +2292,8 @@ export interface NodeTerminalApi {canvas: CanvasApicodex: CodexApiclaude: ClaudeApi+ /** Custom-agent launch/preview (env-var expansion + command assembly). */+ agent: AgentApichat: ChatApiclaudeAccounts: ClaudeAccountsApitranscripts: TranscriptsApi