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
// Single source of truth for agent launch behavior and capabilities.
// Design: an open AgentId string, a declarative config record, and
// capabilities expressed as const membership lists (not a capability object).
import { SAFE_SESSION_ID_UNBOUNDED } from '../session-id'
export type BuiltinAgentId =
| 'claude'
| 'codex'
| 'gemini'
| 'opencode'
| 'grok'
| 'copilot'
| 'antigravity'
| 'cursor'
// Open type — custom agents are any string ('custom:<uuid>'). Never restrict the set.
export type AgentId = BuiltinAgentId | (string & {})
export type PromptInjectionMode =
| 'argv'
| 'flag-prompt'
| 'flag-interactive'
| 'stdin-after-start'
export interface AgentConfig {
label: string // menu + node title, e.g. 'Claude Code'
color: string // node color
launchCmd: string // base launch command
promptInjectionMode: PromptInjectionMode
/**
* The flag `flag-interactive` emits before the prompt. Absent = `--interactive`, which is
* copilot's spelling and stays byte-identical for it.
*
* antigravity (`agy`) is the case that needs it: its interactive-with-prompt flag is
* `--prompt-interactive` (`-i`), measured with `agy --help` on 1.2.3, and it has NO positional
* prompt at all — the usage lists subcommands instead — so neither `argv` nor
* `stdin-after-start` could deliver a prompt without producing a silently wrong command line.
*/
promptFlag?: string
/**
* A one-sentence caveat shown as the tooltip where the agent is OFFERED (pane/sidebar menus, the
* Dock; not the ⌘K palette, whose right-aligned note does not wrap a sentence this long) — not
* a capability, and never read to decide behaviour. Exists for gemini: Google stopped serving
* Gemini CLI to personal accounts on 2026-06-18 (google-gemini/gemini-cli discussion #27274),
* and a user who picks it with a personal account otherwise meets a sign-in loop with no
* explanation. Absent = nothing to say.
*/
notice?: string
/**
* Put this between the command and an `argv` prompt — in practice `'--'`, and only for a CLI
* whose grammar has BOTH a positional prompt and subcommands.
*
* grok is the case that needs it: its usage is `grok [OPTIONS] [PROMPT] [COMMAND]`, so a
* one-word prompt collides with a subcommand name. Measured against the shipped binary, `grok
* version` PRINTS THE VERSION AND EXITS while `grok -- version` opens a session with "version"
* as the prompt — so without the separator a prompt of `help`, `version`, `login`, `models` or
* `export` is silently executed as a command and never reaches the model.
*
* Omitted for every other agent: claude takes a positional and has no subcommand that could
* shadow one, and adding a `--` there would change a command line that works today.
*/
argvPromptSeparator?: string
expectedProcess: string
/**
* Env var NAME pattern (regex source) to unset so the agent runs against its OWN default
* provider instead of a gateway/inherited override. Matched against the var name only, never
* the value. Stripped at spawn only when the node opts into "clear env" (a one-shot
* context-menu action) or the global `vanillaLaunchDefault` setting is on. Defined per builtin
* so the spawn site and the Settings toggle share one source of truth (a duplicated rule
* drifts). Resolved through the base harness via `vanillaEnvStripPattern`, so a custom agent
* inheriting a builtin (once custom-agent baseAgent lands) gets the same strip set.
*
* SECURITY: builtin patterns are static/trusted literals, but the value is a regex source applied
* to env var names. `vanillaEnvStripPattern` compiles it once behind a try/catch and caches; a
* malformed literal throws at compile (caught) and yields null (no strip). It is only ever
* `regex.test(envVarName)` in core — never `eval`'d or interpolated into a command. This mirrors
* the "re-validate at the interpolation site" rule (`isPermissionMode`, `SAFE_SESSION_ID`): the
* type is compile-time, the runtime match is guarded.
*/
vanillaEnvPattern?: string
}
// ORDER is display order everywhere agents are offered (menus, Dock, palette, Settings, the
// canvas-control help). antigravity sits above gemini: since 2026-06-18 it is Google's agent for
// personal accounts, and gemini remains for Code Assist / Vertex / API-key users.
export const BUILTIN_AGENT_IDS: readonly BuiltinAgentId[] = [
'claude',
'codex',
'antigravity',
'gemini',
'opencode',
'grok',
'copilot',
'cursor'
]
export const AGENT_CONFIG: Record<BuiltinAgentId, AgentConfig> = {
claude: {
label: 'Claude Code',
color: '#d97757',
launchCmd: 'claude',
promptInjectionMode: 'argv',
expectedProcess: 'claude',
// `ANTHROPIC_BASE_URL`/`ANTHROPIC_AUTH_TOKEN`/`ANTHROPIC_API_KEY` (gateway + inherited) + the
// OAuth token. Deliberately EXCLUDES `CLAUDE_CONFIG_DIR` — that is the managed-account dir, not
// a provider credential; stripping it would break account isolation and is unrelated to "run on
// subscription". A broad `CLAUDE_*` is unsafe (`CLAUDE_CONFIG_DIR`, and nodeterm's own
// `CLAUDE_HOOK_EVENTS` etc. are code constants, not env the pane sets).
vanillaEnvPattern: '^(ANTHROPIC_|CLAUDE_CODE_OAUTH_TOKEN$)'
},
codex: {
label: 'Codex',
color: '#10a37f',
launchCmd: 'codex',
promptInjectionMode: 'argv',
expectedProcess: 'codex',
// The gateway vars only. Codex credentials live under `CODEX_HOME` (a config dir, like claude's)
// not `CODEX_*` env, so a broad `CODEX_*` strip is unverified and excluded. Narrowing to the two
// known gateway vars avoids touching unrelated `OPENAI_*` the user may set.
vanillaEnvPattern: '^(OPENAI_BASE_URL|OPENAI_API_KEY)$'
},
gemini: {
label: 'Gemini',
color: '#4285f4',
launchCmd: 'gemini',
promptInjectionMode: 'stdin-after-start',
expectedProcess: 'gemini',
notice:
'Google stopped serving Gemini CLI to personal accounts (free, AI Pro, AI Ultra) on 2026-06-18 — use Antigravity instead. Code Assist Standard/Enterprise, Vertex AI and paid API keys still work.'
},
opencode: {
label: 'opencode',
color: '#a78bfa',
launchCmd: 'opencode',
// A bare positional is a PROJECT PATH for opencode, so the initial prompt must go
// through --prompt (see createAgentNode's flag-prompt branch).
promptInjectionMode: 'flag-prompt',
expectedProcess: 'opencode'
},
grok: {
label: 'Grok',
color: '#64748b',
launchCmd: 'grok',
// Verified against the SHIPPED 1.0.0 binary: usage is `grok [OPTIONS] [PROMPT] [COMMAND]`, so
// the prompt is a positional — but one that shares its slot with the subcommand list, which is
// what the separator is for (see `argvPromptSeparator`). An earlier reading of this file said
// `stdin-after-start`, taken from grok 0.1.220, which had no positional at all; npm's `latest`
// tag on the platform package still points at that old build, so the first binary a `npm pack`
// hands you is NOT the one `@xai-official/grok` installs.
promptInjectionMode: 'argv',
argvPromptSeparator: '--',
expectedProcess: 'grok'
},
copilot: {
label: 'GitHub Copilot',
color: '#8957e5',
launchCmd: 'copilot',
// `--prompt` is explicitly non-interactive and exits after one response. The installed
// 1.0.80 CLI's `--interactive <prompt>` starts the ordinary TUI and submits the prompt there.
promptInjectionMode: 'flag-interactive',
expectedProcess: 'copilot',
// All `COPILOT_PROVIDER_*` gateway vars. Excludes `COPILOT_HOME` (config dir) and
// `COPILOT_HOOK_*` (nodeterm constants).
vanillaEnvPattern: '^COPILOT_PROVIDER_'
},
antigravity: {
// Google Antigravity CLI. Measured on `agy` 1.2.3 (Windows 11) — docs/antigravity-agent.md.
label: 'Antigravity',
color: '#00a3a3',
launchCmd: 'agy',
// `agy` has no positional prompt (its usage lists subcommands in that slot), and its
// interactive-with-prompt flag is `--prompt-interactive`, not copilot's `--interactive`.
promptInjectionMode: 'flag-interactive',
promptFlag: '--prompt-interactive',
expectedProcess: 'agy'
},
cursor: {
// Cursor Agent CLI. Measured on `cursor-agent` 2026.09.23-86fc751 (macOS).
label: 'Cursor',
// Cursor's own mark is monochrome, so there is no brand hue to borrow. The first pick, a neutral
// grey (#6b7280), was OKLab 0.018 from Grok's #64748b: the two swatches looked identical in the
// picker, sidebar, kanban and minimap (review 2026-10-03). This magenta is at least 0.12 OKLab
// from every palette swatch (system, agent and FALLBACK_AGENT_COLOR; nearest: system red), and
// about 4:1 against both the dark (#1e1e1e) and light (#fff) canvas as a dot or border. It is an
// agent colour, so it never carries text (SYSTEM_NODE_COLORS owns those surfaces).
// `node-colors.test.ts` pins the distance.
color: '#d9468f',
// Not `agent`: the CLI installs that alias too, and grok ships a binary of the same name.
launchCmd: 'cursor-agent',
// Usage is `agent [options] [command] [prompt...]`, so a one-word prompt collides with a
// subcommand (`login`, `update`, `ls`, ...). Unlike grok, `--` does NOT help: measured,
// `cursor-agent -- whoami` still runs `whoami`. The `agent` subcommand ("Start the Cursor
// Agent") takes the prompt with no subcommands of its own: `cursor-agent agent whoami` opens
// the TUI with "whoami" as the prompt. `stdin-after-start` is out: a first launch in a folder
// shows a workspace-trust dialog that a typed prompt + Enter would answer.
// MEASURED (2026.09.28): flags BEFORE `agent` reach the session. `agent` is a commander
// subcommand with no options of its own; its action reads the ROOT program's options, and root
// parses `--model` / `--force` / `--mode` wherever they sit (before or after `agent`, both
// measured in the TUI). So the composers' flags-before-separator placement is correct.
promptInjectionMode: 'argv',
argvPromptSeparator: 'agent',
// The wrapper script runs `exec -a "$0" node index.js`, so ps shows argv0 `cursor-agent`.
expectedProcess: 'cursor-agent',
// The two env overrides `cursor-agent --help` names for auth and endpoint.
vanillaEnvPattern: '^CURSOR_API_(KEY|ENDPOINT)$'
}
}
// Capabilities = const builtin membership lists. A custom agent resolves through its declared
// base harness (capabilityAgentId); one with no base automatically gets only spawn + terminal-title
// + process status.
// antigravity joined with ONLY this list: its normalizer (normalizeAntigravity) and its
// installer are the leaves that exist. Every other list below is a separate leaf it does not have
// yet — see the `antigravity capabilities` block in config.capabilities.test.ts for each reason.
// cursor joined the same way (normalizeCursor + hooks/cursor.ts); see docs/cursor-agent.md.
export const AGENT_HOOK_TARGETS = [
'claude',
'codex',
'gemini',
'opencode',
'grok',
'copilot',
'antigravity',
'cursor'
] as const
// antigravity: `agy --conversation=<id>` — the `=` spelling agy prints in its own exit hint
// (`agy --conversation=%s`, 1.2.12 binary). The id is the hook payload's `conversationId`, recorded
// as the node's session id. A dead id is the SAFE failure here: agy logs "Conversation %s not found,
// ignoring --conversation flag" and starts a fresh conversation (1.2.12 binary) — so a wrong id costs
// the history, never the launch. Without membership a cold restore (machine reboot) brought an agy
// node back as a bare shell under an Antigravity badge (`canColdRestore` needs `canResume`).
// UNVERIFIED on a device: that the hook's conversationId is the id `--conversation` accepts.
//
// cursor: `cursor-agent --resume <conversation_id>` (measured 2026.09.28, docs/cursor-agent.md). The
// flag is a root option with an OPTIONAL value, so it goes BEFORE the `agent` subcommand and its id
// must directly follow it. A dead id is the SAFE failure: cursor opens an EMPTY chat that ADOPTS the
// requested id (exit 0, no error), so a wrong id costs the history, never the launch.
export const RESUMABLE_AGENTS = [
'claude',
'codex',
'gemini',
'opencode',
'grok',
'copilot',
'antigravity',
'cursor'
] as const
// Agents whose session id we MINT at launch (`--session-id <uuid>`) instead of learning it only
// from hook events. Each member must have a measured caller-chosen-id grammar below.
//
// Why it matters: everything that resumes a conversation — cold restore after a reboot, the
// session reaper's recovery path, the ⌘M transcript view — needs the id, and the id used to
// arrive ONLY over the hook channel (agent fires a hook → POST → renderer stores it in
// localStorage). For an SSH node that POST rides the reverse tunnel, so a node whose tunnel was
// down, or that simply never ran a tool, never had an id at all. Measured on one host after a
// reboot: 18 of 40 agent nodes relaunched as BLANK conversations because there was nothing to
// resume with, while their transcripts sat intact on disk.
//
// Minting fixes the floor, not the whole problem: `/clear`, `--fork-session` and compaction all
// mint a NEW id inside the CLI (claude's SessionStart hook reports these as source
// clear/fork/compact), so hooks remain the only way to TRACK an id after launch. What minting
// guarantees is that a node always has SOME resumable id, so the worst case degrades from "the
// conversation is gone" to "continuity since the last /clear is gone".
export const SESSION_ID_CAPABLE = ['claude', 'copilot', 'grok', 'cursor'] as const
// Claude's flag is version-gated and comes from the Claude CLI probe. Copilot's installed 1.0.80
// binary and current official reference accept `--session-id=<uuid>`, so it does not borrow an
// unrelated Claude probe result. Custom agents resolve through their declared base harness.
//
// grok is gated too, but on ITS OWN probe (`core/grok-cli.ts` reads `grok --help`) — never on
// claude's. The two CLIs are installed and upgraded independently, so claude's answer is not even
// correlated with grok's, and a gate fed by the wrong agent's probe is a guess wearing a
// measurement's clothes. Its grammar also differs from claude's in three measured ways (1.0.13):
// the UUID must not already exist under the target session directory, so minting one twice is a
// LAUNCH ERROR and never a resume; `--session-id` combines with `--resume`/`--continue` only
// alongside `--fork-session`; and `--resume` accepts a TITLE as well as an id, failing as ambiguous
// on duplicates — which is why nothing in this codebase resumes grok by title.
//
// cursor mints with `--resume <uuid>` and NO probe of its own, unlike grok: the flag is the same one
// resume already depends on (a CLI without it could not resume either), and the behavior is not a
// flag a help probe could see. Measured 2026.09.28 with a paid TUI run: `cursor-agent --resume
// <fresh uuid> --model composer-2.5 --force agent '<prompt>'` answered, and every hook payload's
// `conversation_id` was that uuid; with no prompt the same line opens an empty chat under that id
// (no model call). An id that already exists simply resumes, so a taken id is never a launch error
// (grok's is). If an older CLI ignored the unknown id, the node degrades to hook-learned ids.
export const UNCONDITIONAL_SESSION_ID_CAPABLE = ['copilot', 'cursor'] as const
// claude: Task/Agent tool via hooks (tool_use_id-keyed). codex: spawn_agent collaboration via its
// native SubagentStart/SubagentStop hooks (agent_id-keyed), measured on codex-cli 0.146.0.
// grok: its own native SubagentStart/SubagentStop, keyed by `subagentId` — measured on 1.0.13 by
// running two subagents of the SAME type in parallel, which is the only way to tell an instance
// id from a type. It was assumed to key by `subagentType` (a type, so two children of one type
// would collide); the payloads say otherwise, and `subagentId` is also the ONLY id the start and
// the stop share — on the start `sessionId` is the PARENT's.
// cursor: its `subagentStart`/`subagentStop` hooks never fired (three measured runs, 2026.10.01),
// so the start is the parent's `Task` preToolUse (keyed by `tool_use_id`) and the end is the
// parent's `stop` (core/cursor-subagents.ts). docs/cursor-agent.md "Orchestration parity".
export const SUBAGENT_CAPABLE = ['claude', 'codex', 'grok', 'cursor'] as const
export const RECURRING_CAPABLE = ['claude'] as const // /loop, /schedule, /cron
export const BRANCH_CAPABLE = ['claude'] as const
// grok joins with NO installer of its own: it scans `~/.claude/skills` for Claude Code
// compatibility, which is exactly where `get-linked-context` is already written — the same
// argument `CANVAS_CONTROL_CAPABLE` makes below. That premise used to be marked unverified;
// MEASURED on 1.0.13 (2026-09-01): `grok inspect --json` lists the skill with
// `vendor: 'claude', compatibilityStatus: 'enabled'`, and `externalCompat.cells` reports
// `{surface:'skills', enabled:true, source:'default'}`.
// Two user settings can switch that off — `[compat.claude] skills = false` in
// `~/.grok/config.toml`, and `GROK_CLAUDE_SKILLS_ENABLED=false`. Then the skill is undiscoverable
// however this list reads, and the same `inspect` cell is what says so (`enabled:false`, a
// non-default `source`) rather than leaving support to guess.
// cursor joins with NO installer: cursor-agent 2026.09.28 lists `~/.claude/skills/get-linked-context`
// in the `<agent_skills>` block of a real chat's own context (measured in its store.db), i.e. it reads
// `~/.claude/skills` like grok. Its transcript is a SQLite store read by `core/cursor-chat.ts`.
// UNVERIFIED: a user setting that switches that Claude-compat scan off.
export const CONTEXT_LINK_CAPABLE = [
'claude',
'codex',
'gemini',
'opencode',
'grok',
'cursor',
'antigravity'
] as const
// Agents whose per-node context meter we can fill. Each needs BOTH numbers: a used count and a
// TRUSTWORTHY window.
// - claude: used from its transcript's assistant usage, window INFERRED from the model family
// (core/model-window.ts).
// - codex: states its own denominator — `model_context_window`, right beside the usage in its
// rollout (core/codex-session.ts).
// - gemini: states none, so the window comes from its model id through `geminiWindowFor`, which
// mirrors the CLI's OWN `tokenLimit(model)` — a family rule with a 1M catch-all default, so a
// model we have never heard of still gets the right answer rather than a stale guess.
// - grok: states BOTH numbers and the answer. `contextTokensUsed` and `contextWindowTokens` sit in
// `~/.grok/sessions/<cwd>/<id>/signals.json`, alongside `contextWindowUsage` — the percentage
// grok has already computed. MEASURED on 22 real sessions (1.0.13, 2026-09-02): all three present
// in all 22, and the stated percentage agrees with used/window in all 22. So the window is read,
// never inferred from the model id, which puts grok with codex rather than with gemini.
// - antigravity: states `input_tokens` and `cache_read_tokens` on every `PLANNER_RESPONSE` in
// `~/.gemini/antigravity-cli/brain/<id>/.system_generated/logs/transcript_full.jsonl` (core/
// antigravity-session.ts), and `antigravityWindowFor` (core/model-window.ts) maps its model
// family (`gemini-4-argon-*`, `gemini-3.8-flash-*`, `claude-*`, `gpt-oss-120b-*`) to the known
// context window, returning null for unknown models.
//
// Until 2026-09 this comment explained grok's absence by pointing at a missing parser for the wrong
// file, and concluding there was no used count to divide. Both halves were false, and the first is
// the one worth remembering: the counters never lived in the file it named, so the blocker it
// declared was not the real blocker even on the day it was written. A comment that explains an
// absence with a false cause is worse than no comment — it sends the next reader to build a parser
// nobody needed. What let it survive is that nobody could check it: the integration was written with
// no grok binary on the machine.
//
// signals.json is a METRICS file (66 keys: latencies, GCS queue counters, lines touched, peak RSS).
// `core/grok-signals.ts` reads exactly three of them and nothing else. If a future grok drops
// `contextWindowTokens`, that reader returns null and the meter disappears — no inferred
// denominator, because a percentage over a guessed window is a wrong number presented as a fact.
//
// Cursor joined in 2026-09 with the agent's own numbers, like grok: the store's root protobuf field 5
// (`token_details`: used_tokens, max_tokens), which matches the TUI's `/context` (`core/cursor-chat.ts`).
// It joins the meter ONLY: its ids are not in CLAUDE_TRANSCRIPT_READABLE, so the find bar's index and
// cold-resume stay off claude's cwd-fallback resolver, and `context.ensure` locates a cursor chat by id.
// Account plan limits (CLI `/usage`) are a different, credentialed number and are not read.
export const USAGE_CAPABLE = ['claude', 'codex', 'gemini', 'grok', 'cursor', 'antigravity'] as const
// Agents whose structured transcript we can render as a chat panel (Cmd+M chat mode).
//
// SPLIT from CLAUDE_TRANSCRIPT_READABLE below on 2026-09-02, when grok joined. Until then this one
// list carried TWO facts that happened to coincide while claude was its only member: "we can render
// this agent's conversation ourselves" and "CLAUDE's transcript resolver can locate and parse this
// agent's file". Grok satisfies the first (`linesFromGrok`, core/context-link-render.ts) and NOT the
// second, and merging them is not a cosmetic error: `resolveTranscript` (core/transcript-ipc.ts:58)
// falls back to `transcriptPathForCwd` when the sessionId leg misses — which it ALWAYS does for a
// non-claude id, since no `<that id>.jsonl` exists under `~/.claude/projects` — and hands back the
// newest CLAUDE transcript for that cwd. A grok node in this list would therefore show a stranger's
// conversation in its find bar and rehydrate its meter from it. That exact bug already happened once
// with codex and gemini; transcriptGates.ts documents it.
//
// gemini joined in 2026-09 with its own reader (`core/gemini-chat.ts`): its session file is an upsert
// log, not claude's shape, and it is located strictly by the session id in the file's header.
// codex joined 2026-09-28 with its own reader (core/codex-chat.ts: the rollout's UI stream for what
// the user typed, the model stream for answers and tools), local and over SSH.
// copilot joined 2026-09 with its own leaf, `core/copilot-chat.ts`: `<COPILOT_HOME>/session-state/
// <id>/events.jsonl`, located strictly by session id and routed there before anything claude-shaped
// (`readChatTranscript`). Like the others it is NOT in CLAUDE_TRANSCRIPT_READABLE below.
// opencode joined 2026-09-28: it has no transcript file at all (SQLite since 1.18), so its chat is
// read through `opencode export <id>` (core/opencode-chat.ts) and it stays out of the list below.
// cursor joined with `core/cursor-chat.ts`: a read-only `node:sqlite` read of its chat store, located
// strictly by the whole-UUID chat id and routed before anything claude-shaped. Not in the list below.
// antigravity joined 2026-10 with its own reader (`core/antigravity-chat.ts`), reading
// `~/.gemini/antigravity-cli/brain/<id>/.system_generated/logs/transcript_full.jsonl` strictly by
// conversation id (`locateAntigravity`).
export const CHAT_CAPABLE = [
'claude',
'grok',
'gemini',
'codex',
'copilot',
'opencode',
'cursor',
'antigravity'
] as const
// CHAT_CAPABLE agents whose reader has NO remote leg: a remote (SSH) node's session lives on its
// host, so core answers `unreadable` before touching anything — and the local reader never sets that
// flag (copilot maps a failed local read to not-found for exactly this reason). So an unreadable read
// of one of these can only mean "remote, unsupported", and the ⌘M panel names it from the agent
// alone rather than offering a Retry that can never succeed. grok and codex are NOT here: their
// remote nodes are read on the host (`core/remote-grok-chat.ts`, `main/remote-codex-chat-page.ts`).
// opencode has no remote leg either but is NOT here: its `unreadable` also means a failed LOCAL
// `opencode export`, which Retry heals — the panel gives it its own copy (`exportError`) instead.
export const CHAT_LOCAL_ONLY = ['gemini', 'copilot', 'cursor', 'antigravity'] as const
// CHAT_CAPABLE agents whose chat-view prompts are TYPED as keystrokes instead of pasted
// (core/typed-input.ts): a multi-line paste is recorded by Claude Code as <pasted_content>, content
// its model is told may not be the user's own words. The typed path puts a line break in as tmux's
// M-Enter key — a newline in Claude Code (MEASURED, 2.1.281) but unmeasured in every other CLI,
// where it could just as well SUBMIT, splitting one prompt into several. So only claude; the rest
// keep the paste. An agent joins once someone has measured what its composer does with M-Enter.
export const TYPED_INPUT_CAPABLE = ['claude'] as const
// Agents whose transcript CLAUDE's own resolver can locate and parse — the gate for everything that
// goes through `resolveTranscript` (the find bar's index, the meter's mount-time rehydration).
//
// This is deliberately NOT a superset of CHAT_CAPABLE and must not be "simplified" back into it: the
// question here is not "can we read this agent" but "does this agent's conversation live in a file
// shaped like claude's, under claude's tree". Only claude answers yes, and the failure mode of a
// wrong answer is a read of SOMEONE ELSE'S session (see the comment above), which fails OPEN — it
// shows data rather than hiding it. `config.capabilities.test.ts` pins that grok is absent.
export const CLAUDE_TRANSCRIPT_READABLE = ['claude'] as const
// Agents whose own UI dialogs we can recognize on SCREEN (shared/agents/claude-screen.ts). A CLI's
// built-in dialogs — the folder-trust prompt, /model, one-time setup questions — fire NO hook, so the
// agent state still reads idle while the dialog owns the keyboard, and anything the chat view types
// into the pane is swallowed, or worse: the trust prompt's default is "No, exit". The reader matches
// claude's screen layout (MEASURED on 2.1.283); another CLI's layout would read as a permanent
// dialog and lock its chat view, so each agent needs its own measured reader.
export const SCREEN_DIALOG_READABLE = ['claude'] as const
// Agents whose CLI QUEUES a prompt submitted while a turn is running, instead of treating it as
// input to whatever is on screen. The chat view (⌘M) sends into the pane exactly as typing would, so
// only for these may it send while the agent is `working`. MEASURED for claude (2.1.281, 2026-09-23):
// a prompt submitted mid-turn (pasted or typed) shows "Press up to edit queued messages" and is
// delivered at the next tool boundary of the SAME turn (a `queued_command` transcript attachment, not
// a new user turn). Every other chat-capable agent is unmeasured and keeps "wait for the reply".
export const INPUT_QUEUE_CAPABLE = ['claude'] as const
// Agents the ⌘M chat view may send a lone Esc to while a turn is running, to interrupt it as Esc in
// the terminal would. MEASURED for claude (2.1.318, 2026-11-04): mid-reply it prints "Interrupted ·
// What should Claude do instead?"; text in its own input box stays; a queued message is sent as the
// next turn; an Esc before the first token puts the prompt back into its input box. Must stay within
// SCREEN_DIALOG_READABLE: core reads the screen first, because Esc on a dialog would cancel it.
export const CHAT_INTERRUPT_CAPABLE = ['claude'] as const
// Agents whose native transcript we can read + render for cross-agent transfer.
export const TRANSFER_SOURCE_CAPABLE = [
'claude',
'codex',
'gemini',
'grok',
'cursor',
'antigravity'
] as const
// Agents whose hooks announce that a session ENDED — i.e. whose orderly `/exit` we will hear about.
//
// Derived by reading `normalize.ts`, not by intent: exactly four normalizers map an event to
// `sessionPhase: 'end'` (claude `SessionEnd`, gemini `SessionEnd`, copilot `SessionEnd`, grok
// `sessionend`). `normalizeCodex` and `normalizeOpencode` map none, which is why they are absent
// here — and their absence is load-bearing, not an oversight to tidy up later.
//
// What it gates today is the DROPPED chip (`terminal/agent-liveness.ts`): "the pane went back to a
// shell but nobody told us the session ended" is only evidence of a CRASH for an agent that WOULD
// have told us. On codex and opencode a deliberate `/quit` and an OOM kill leave byte-identical
// evidence, so a chip there could only be a coin flip shown as a fact.
//
// Before adding an id: find its normalizer's `sessionPhase: 'end'` branch. If there isn't one, the
// branch is the change — this list is a consequence of it, never a substitute for it.
//
// cursor: `sessionEnd` fires on an orderly `/quit` (measured 2026.09.28, `reason: "completed"`), and
// `CURSOR_HOOK_EVENTS` subscribes to it; both halves are needed, the list is inert without the event.
export const SESSION_END_CAPABLE = ['claude', 'gemini', 'copilot', 'grok', 'cursor'] as const
// Agents that accept a node title being PUSHED back into the session — the write leg only. The
// write is the same literal `/rename <name>` for both, which grok also accepts as `/title`.
// The READ leg is TITLE_READ_CAPABLE below, which is a superset: an agent can name its own session
// without offering any way to rename it (gemini). Read legs are per-agent (claude: the transcript
// .jsonl; grok: its session summary.json; gemini: its update_topic tool call), routed once in
// core/agent-session-name.ts.
// cursor: `/rename <name>` is a local TUI command (`agentStore.setMetadata("name")`) that lands in
// the store meta TITLE_READ_CAPABLE reads, MEASURED on 2026.10.01. It needs its Enter as a SEPARATE
// write (SEPARATE_SUBMIT_AGENTS), or the line sits unsubmitted in the composer.
export const RENAME_CAPABLE = ['claude', 'grok', 'cursor'] as const
// Agents whose TUI ignores an Enter that arrives in the SAME write as a bracketed paste: the text
// lands in the composer and is never submitted. MEASURED for cursor (2026.10.01): nodeterm's one-shot
// paste+Enter left `/rename x` unsubmitted; the same paste followed by a bare Enter, as a second
// tmux invocation, renamed the chat. `submitsSeparately` is asked by `PtyManager.sendText`, the one
// funnel every one-way write reaches.
export const SEPARATE_SUBMIT_AGENTS = ['cursor'] as const
// Agents that load nodeterm's `get-linked-context` skill from `~/.claude/skills`, so a context link,
// a note push or a verify brief can name the skill instead of spelling out the CLI. claude, and
// cursor (measured: it lists that skill in its own `<agent_skills>`, docs/cursor-agent.md). grok
// reads that root too, but its pickup of this skill is unverified, so it keeps the CLI wording.
export const LINKED_CONTEXT_SKILL_AGENTS = ['claude', 'cursor'] as const
// Agents whose OWN session name we can READ and adopt into the node title.
//
// Separate from RENAME_CAPABLE because the two directions are separate facts, and gemini has only
// this one: it writes a model-generated name into its transcript (the `update_topic` tool's
// `args.title` — core/gemini-session.ts) but has no command to SET one. Its session commands are
// `/chat list|save|resume|delete|share` (measured on 0.54.4), where `save <tag>` is a tagged
// checkpoint, not a title — so one list for both legs would light the rename UI on a node where
// the write silently does nothing.
//
// INVARIANT (pinned in config.capabilities.test.ts): every RENAME_CAPABLE agent is also here. The
// write leg pushes a name and the read leg is what confirms it settled.
//
// codex joined the READ leg only, and for the same reason gemini did: with the shared app-server
// (SHARED_IDENTITY_CAPABLE below) a node owns a THREAD, and that thread carries a `Thread.name` we
// can read over the server's own socket (core/codex-session-name.ts). There is still no measured
// rename command, so it stays out of RENAME_CAPABLE — the read⊇write invariant holds either way.
// cursor: its `name` (AI-generated, or `/rename`) is in the chat store meta; the write leg joined
// RENAME_CAPABLE once `/rename` was measured to land there.
// Agents with an in-session "reach this session from another device" toggle the node header can
// drive. claude only: `/remote-control` (alias `/rc`, measured on 2.1.325) connects the session to
// claude.ai / the Claude mobile app and, run again, offers to disconnect it. State is read from
// the transcript (core/remote-control-scan.ts). No other builtin has a measured equivalent.
export const REMOTE_CONTROL_CAPABLE = ['claude'] as const
export const TITLE_READ_CAPABLE = ['claude', 'codex', 'grok', 'gemini', 'cursor'] as const
// Agents whose canvas nodes share ONE managed CLI server per machine and keep a stable per-node
// identity inside it, instead of each node owning a whole process tree.
//
// Membership is what makes `buildPtyEnv` mint the per-node capability token, what makes
// `pty-manager` install + PATH-expose the generated launcher, and what lets a launch line address
// that launcher at all. Everything downstream asks `hasSharedIdentity(agentId)`; nothing may ask
// `agentId === 'codex'`, which is how this started and is what CLAUDE.md forbids.
//
// Only codex today: it is the only builtin with an app-server mode NodeTerm can attach many
// clients to. A second agent joins by being added here and writing its own launcher body.
export const SHARED_IDENTITY_CAPABLE = ['codex'] as const
// Agents allowed to drive the canvas via the `nodeterm` CLI (open/show/write/close).
// Discovery differs per agent: claude gets the manage-nodeterm-canvas skill; codex/gemini/
// antigravity/opencode a marker block in ~/.codex/AGENTS.md / ~/.gemini/GEMINI.md /
// ~/.config/opencode/AGENTS.md (see canvas-control.ts — agy loads ~/.gemini/GEMINI.md as
// <RULE[user_global]>).
//
// grok needs NO new installer: it scans `~/.claude/skills` by default for Claude Code
// compatibility (its shipped docs, user-guide/08-skills.md; switched off only by
// `[compat.claude] skills = false` or GROK_CLAUDE_SKILLS_ENABLED=false), and that is exactly
// where the manage-nodeterm-canvas skill is already written — locally, and on an SSH host via
// RemoteHooks.installCanvasControl. Membership here is what sets NODETERM_CANVAS_CONTROL in the
// session env (hook-server's buildPtyEnv, remoteHookEnvArgs), i.e. what makes the shim anything
// other than a no-op.
//
// cursor needs no installer either, by the same route: cursor-agent loads `~/.claude/skills` as
// third-party skills (gated by its `thirdPartyExtensibility` setting, default on in the CLI), and
// MEASURED on 2026.10.01 its interactive session listed `~/.claude/skills/manage-nodeterm-canvas`
// right after its own built-ins, ahead of the tail it truncates when the skill list is long.
export const CANVAS_CONTROL_CAPABLE = [
'claude',
'codex',
'gemini',
'opencode',
'grok',
'copilot',
'cursor',
'antigravity'
] as const
// Agents whose TOOL shell on Windows is POSIX: Claude Code runs its Bash tool (and its hooks)
// through Git Bash, so `sh "<shim>.sh"` works there exactly as on macOS/Linux. Every other agent
// runs tools in PowerShell (codex, gemini, copilot — measured in their sources) or cmd.exe, where
// `sh` is not on PATH on a stock Git install; they are told to run the `.cmd` launcher instead
// (`shimDialectFor` in ./shim-invocation.ts). Membership only matters on a win32 host.
export const POSIX_TOOL_SHELL_ON_WINDOWS = ['claude'] as const
// Agents whose session start-up permission mode we can set (see AgentPermissionMode below).
// claude and grok share the flag SPELLING and the value vocabulary
// (`--permission-mode auto|plan|acceptEdits|bypassPermissions`; our `manual` = no flag = grok's own
// `default`). gemini (`--approval-mode default|auto_edit|yolo|plan`), codex
// (`--ask-for-approval untrusted|on-request|never`), and antigravity
// (`--mode accept-edits|auto|plan` plus `--dangerously-skip-permissions`) each spell it their own
// way, so membership here is only half the story — the translation lives in ./approval-mode.ts.
//
// Membership does NOT mean every mode applies: BOTH new vocabularies are narrower than ours — codex
// has no plan and no edit-specific mode, and gemini has nothing meaning "approve most things but not
// edits", i.e. no `auto`. Those modes emit NO flag rather than a substituted nearest match.
// `modeSupported` is what the UI asks so the user is told, instead of being shown "Plan" while
// codex runs in on-request, or "Auto" while gemini auto-approves every edit. That last one is not
// hypothetical: `auto` is DEFAULT_PERMISSION_MODE, so mapping it to gemini's `auto_edit` would have
// switched auto-approve-edits on for every existing gemini node at upgrade time, silently.
//
// NOTE: the `auto` VERSION GATE is claude's alone — see activePermissionMode in
// renderer/state/permissionMode.ts. grok has accepted every mode we emit since 1.0.0, its first
// release, and gemini/codex/antigravity accept theirs on the versions we measured, so none of them
// may inherit a gate fed by a `claude --version` probe.
//
// cursor emits `--auto-review` for `auto` (a server classifier auto-runs safe calls, claude's `auto`
// shape), `--mode plan` and `--force`; `manual` and `acceptEdits` emit no flag (its bare launch is
// `approvalMode: allowlist`). See CURSOR_MODES in approval-mode.ts. `auto` is the DEFAULT mode, which
// widened no existing node only because cursor shipped in the same change.
export const PERMISSION_MODE_CAPABLE = [
'claude',
'grok',
'gemini',
'codex',
'cursor',
'antigravity'
] as const
// Agents whose harness accepts a per-launch model override and whose gateway protocol we know how
// to configure. Custom agents inherit this through `capabilityAgentId`, like every other harness
// capability — the renderer never maintains its own Claude/Codex/Copilot allowlist.
export const MODEL_SWITCH_CAPABLE = [
'claude',
'codex',
'copilot',
'grok',
'cursor',
'antigravity'
] as const
// Members of MODEL_SWITCH_CAPABLE whose models are their OWN CLI's catalogue and can never be
// routed through the model gateway: grok (custom models live in ~/.grok/config.toml), cursor
// (`cursor-agent models` lists ~250 account-scoped ids), and antigravity (`agy models`).
// Offering or defaulting a gateway id to one of these puts a `--model` on the line that names a
// model outside its own catalogue, so every place that hands out GATEWAY models asks
// `hasGatewayModels`, not `canSwitchModel`.
export const OWN_MODEL_CATALOGUE = ['grok', 'cursor', 'antigravity'] as const
// Agents whose own CLI already tells the user when it copies, so nodeterm must not say it again.
// Claude Code captures the mouse itself and prints its own line — "copied N chars to tmux buffer ·
// paste with prefix + ]" — which makes our copy pill a second message for one gesture. Membership
// switches the WHOLE copy-feedback layer off for that agent's terminals: the receipt and the
// one-time "Hold ⌥ to select text" hint alike, since a drag there is not swallowed at all.
//
// This is a list rather than a `=== 'claude'` for the usual reason: the next CLI to grow its own
// copy notice joins by being added here, and nothing else changes.
export const SELF_REPORTS_COPY = ['claude'] as const
/** 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
}
/**
* The compiled env-var-NAME strip pattern for an agent, resolved through its base harness (so a
* custom agent inheriting a builtin gets the builtin's strip set once custom-agent baseAgent lands).
* `null` ⇒ the agent has no strip set (gemini/grok/opencode, or any unknown id) ⇒ the vanilla
* relaunch action is hidden and the strip is a no-op. Compiled once and cached; a malformed
* `vanillaEnvPattern` literal throws at compile, is caught, and yields `null` (no strip) — see the
* security note on `AgentConfig.vanillaEnvPattern`. The cache key is the regex SOURCE string, so two
* agents sharing a pattern share one compiled `RegExp`.
*/
const VANILLA_PATTERN_CACHE = new Map<string, RegExp | null>()
export function vanillaEnvStripPattern(id: AgentId): RegExp | null {
const source = AGENT_CONFIG[capabilityAgentId(id) as BuiltinAgentId]?.vanillaEnvPattern
if (!source) return null
const cached = VANILLA_PATTERN_CACHE.get(source)
if (cached !== undefined) return cached
let compiled: RegExp | null
try {
compiled = new RegExp(source)
} catch {
compiled = null
}
VANILLA_PATTERN_CACHE.set(source, compiled)
return compiled
}
const includes = (list: readonly string[], id: AgentId): boolean =>
list.includes(capabilityAgentId(id))
export const hasHooks = (id: AgentId): boolean => includes(AGENT_HOOK_TARGETS, id)
/**
* Hook-reporting agents whose hooks nodeterm installs on THIS machine only — `RemoteHooks.setup()`
* has no installer for them on an SSH host yet. On an SSH project such a node never reports a
* state, so nothing may WAIT on it (`--after`): the dependant would sit QUEUED forever.
*/
export const LOCAL_ONLY_HOOK_AGENTS = ['antigravity'] as const
/** Does this agent report status when its node runs on an SSH project's host? */
export const hasHooksOverSsh = (id: AgentId): boolean =>
hasHooks(id) && !includes(LOCAL_ONLY_HOOK_AGENTS, id)
export const canResume = (id: AgentId): boolean => includes(RESUMABLE_AGENTS, id)
export const mintsSessionId = (id: AgentId): boolean => includes(SESSION_ID_CAPABLE, id)
/** Is the caller-chosen session-id flag available for this effective base harness? */
export const supportsSessionIdFlag = (
id: AgentId,
claudeFlagSupported: boolean,
// REQUIRED, not defaulted. A default here would let a caller forget grok's probe and silently get
// "grok never mints" — a feature quietly missing, with a green typecheck and no test to notice.
// That is the same shape as the optional prop that let the chat panel's agent id be dropped; the
// lesson taken from it is that the fix for this family is a type that cannot express the broken
// state, not another test somebody has to remember to write.
grokFlagSupported: boolean
): boolean => {
if (includes(UNCONDITIONAL_SESSION_ID_CAPABLE, id)) return true
if (!mintsSessionId(id)) return false
const base = capabilityAgentId(id)
// Each probed agent answers with ITS OWN probe. A missing third argument reads as "grok was not
// probed", which yields a bare command — the safe direction, and the same one an unprobed claude
// gets.
if (base === 'grok') return grokFlagSupported
return base === 'claude' && claudeFlagSupported
}
export const canSubagent = (id: AgentId): boolean => includes(SUBAGENT_CAPABLE, id)
export const canRecur = (id: AgentId): boolean => includes(RECURRING_CAPABLE, id)
export const canBranch = (id: AgentId): boolean => includes(BRANCH_CAPABLE, id)
export const canContextLink = (id: AgentId): boolean => includes(CONTEXT_LINK_CAPABLE, id)
export const hasUsage = (id: AgentId): boolean => includes(USAGE_CAPABLE, id)
export const canChat = (id: AgentId): boolean => includes(CHAT_CAPABLE, id)
export const chatReadsLocalOnly = (id: AgentId): boolean => includes(CHAT_LOCAL_ONLY, id)
export const typesChatInput = (id: AgentId): boolean => includes(TYPED_INPUT_CAPABLE, id)
export const readsScreenDialogs = (id: AgentId): boolean => includes(SCREEN_DIALOG_READABLE, id)
export const queuesInputWhileWorking = (id: AgentId): boolean => includes(INPUT_QUEUE_CAPABLE, id)
export const interruptsFromChat = (id: AgentId): boolean => includes(CHAT_INTERRUPT_CAPABLE, id)
/** Can CLAUDE's transcript resolver locate and parse this agent's conversation? Never widen this
* to mean "can we read this agent" — see CLAUDE_TRANSCRIPT_READABLE. */
export const readsClaudeShapedTranscript = (id: AgentId): boolean =>
includes(CLAUDE_TRANSCRIPT_READABLE, id)
export const canTransferFrom = (id: AgentId): boolean => includes(TRANSFER_SOURCE_CAPABLE, id)
/** Will this agent's hooks tell us when its session ends? See SESSION_END_CAPABLE — the honest
* answer for codex and opencode is no, and callers must degrade rather than assume a crash. */
export const reportsSessionEnd = (id: AgentId): boolean => includes(SESSION_END_CAPABLE, id)
export const canRename = (id: AgentId): boolean => includes(RENAME_CAPABLE, id)
export const submitsSeparately = (id: AgentId): boolean => includes(SEPARATE_SUBMIT_AGENTS, id)
export const readsLinkedContextSkill = (id: AgentId): boolean => includes(LINKED_CONTEXT_SKILL_AGENTS, id)
export const canRemoteControl = (id: AgentId): boolean => includes(REMOTE_CONTROL_CAPABLE, id)
export const canReadTitle = (id: AgentId): boolean => includes(TITLE_READ_CAPABLE, id)
export const canControlCanvas = (id: AgentId): boolean => includes(CANVAS_CONTROL_CAPABLE, id)
export const usesPosixToolShellOnWindows = (id: AgentId): boolean => includes(POSIX_TOOL_SHELL_ON_WINDOWS, id)
export const hasPermissionMode = (id: AgentId): boolean => includes(PERMISSION_MODE_CAPABLE, id)
export const canSwitchModel = (id: AgentId): boolean => includes(MODEL_SWITCH_CAPABLE, id)
/** Can the model GATEWAY's catalogue (its discovered ids, its default model) apply to this agent?
* `canSwitchModel` minus the agents that carry their own catalogue (OWN_MODEL_CATALOGUE). */
export const hasGatewayModels = (id: AgentId): boolean =>
canSwitchModel(id) && !includes(OWN_MODEL_CATALOGUE, id)
export const hasSharedIdentity = (id: AgentId): boolean => includes(SHARED_IDENTITY_CAPABLE, id)
/**
* The program a launch line should name for `id`.
*
* `sharedIdentity` is the caller's answer to "will the managed launcher actually be there?", and
* it is FALSE by default on purpose: every call site that has not opted in emits the bare CLI
* command it always did, byte for byte. This is the same shape as `gatePermissionMode` — an
* unknown or failed probe degrades to the bare command, never to a launch that cannot run.
*
* The launcher is addressed by NAME, not by path: `pty-manager` puts its directory first on the
* session's PATH for exactly the agents in SHARED_IDENTITY_CAPABLE, so the pane shows a readable
* command and a plain terminal's PATH is untouched.
*/
export const SHARED_IDENTITY_LAUNCHERS: Partial<Record<AgentId, string>> = { codex: 'nodeterm-codex' }
export function agentLaunchProgram(id: AgentId, base: string, sharedIdentity = false): string {
if (!sharedIdentity || !hasSharedIdentity(id)) return base
return SHARED_IDENTITY_LAUNCHERS[id] ?? base
}
/** Does this agent's CLI report its own copies? Undefined (a plain terminal, a custom agent) is
* `false` — nobody speaks for those, so nodeterm's own feedback is the only feedback there is. */
export const reportsOwnCopy = (id: AgentId | undefined): boolean =>
!!id && includes(SELF_REPORTS_COPY, id)
// Returns the builtin config for an id, or undefined for custom/unknown agents.
export const agentConfig = (id: AgentId): AgentConfig | undefined =>
(AGENT_CONFIG as Record<string, AgentConfig>)[id]
/**
* The agent a terminal node was CREATED as: `data.agentId`, with the legacy `tags` fallback for
* nodes serialized before `agentId` existed. Node data is deserialized (hand-editable) JSON, so
* the shapes are checked at runtime rather than trusted from the type.
*
* Deliberately NOT a hook-status fallback (Canvas's wider `agentIdOf`), which also reports a plain
* terminal someone typed `claude` into by hand.
*
* ONE definition on purpose: the canvas menu decides from it whether to OFFER an in-place restart,
* and the node's restart closure captures it to decide whether to RUN one. Two copies that drift
* apart silently produce a menu row whose closure refuses every click.
*/
export function createdAgentId(
data: { agentId?: unknown; tags?: unknown } | undefined
): AgentId | undefined {
if (!data) return undefined
if (typeof data.agentId === 'string' && data.agentId) return data.agentId as AgentId
const tags = Array.isArray(data.tags) ? data.tags : []
return tags.includes('claude') ? 'claude' : undefined
}
// Session ids are interpolated into a shell command line (written into the live shell on a
// cold restart), so accept only the safe charset agents actually use (UUIDs etc.) — never a
// flag-like or metacharacter-bearing value. The shared alphabet in its UNBOUNDED form: these
// helpers never capped the length, and capping them now would stop resuming an id that works today
// (see `@shared/session-id`).
const SAFE_SESSION_ID = SAFE_SESSION_ID_UNBOUNDED
/**
* Appends the minted-session-id flag to a FIRST-LAUNCH command, for agents in
* `SESSION_ID_CAPABLE`. Anything else — another agent, an empty or unsafe id — returns `cmd`
* unchanged, so a command line that had no business carrying the flag stays byte-identical.
*
* First launch ONLY. `claude --session-id <uuid>` refuses an id that already exists ("Session ID
* … is already in use.", measured against claude 2.1.226), so a relaunch of the same node must
* resume instead — that is `resumeCommand`'s job, and the two shapes can never be collapsed into
* one idempotent command.
*
* Re-validated against SAFE_SESSION_ID at this interpolation site for the same reason
* `resumeCommand` is: the value ends up on a tmux `send-keys` line, and the caller's type is a
* compile-time promise, not a runtime one.
*/
export function withSessionId(cmd: string, id: AgentId, sessionId: string): string {
if (!mintsSessionId(id)) return cmd
const sid = sessionId.trim()
if (!sid || !SAFE_SESSION_ID.test(sid)) return cmd
const base = capabilityAgentId(id)
if (base === 'copilot') return `${cmd} --session-id=${sid}`
// cursor has no session-id flag: `--resume <unknown uuid>` opens an empty chat that adopts the id
// (measured, docs/cursor-agent.md). A root option with an optional value, so it sits before `agent`.
if (base === 'cursor') return `${cmd} --resume ${sid}`
return `${cmd} --session-id ${sid}`
}
/**
* The command that resumes a resumable agent's prior conversation by its provider session id.
* Used on a cold restart (machine reboot) where the tmux session — and the live agent — are
* gone, so the conversation must be reconstructed via the agent CLI's own `--resume`.
* Returns null for non-resumable/custom agents or an unsafe/empty session id.
*
* `sharedIdentity` routes a SHARED_IDENTITY_CAPABLE agent's resume through the managed launcher,
* so the resumed session re-claims the node's own thread instead of opening it as an anonymous
* client. Default false = the bare command this has always emitted (see `agentLaunchProgram`).
*
* `base` is the user's launch-command override for this agent (`settings.agentLaunchCommands`,
* e.g. an account-switching wrapper), PASSED IN rather than read here: this module is imported by
* main/core/server and cannot reach the renderer's settings store, so the renderer resolves the
* override and threads it through — the same shape as `performRestartResume`'s `command` param.
* When set (non-blank) it replaces the program part outright, INCLUDING codex's shared-identity
* launcher: an explicit override is the user saying "launch it exactly like this", and silently
* substituting the managed launcher would un-say it. Blank/absent = unchanged behavior.
*/
export function resumeCommand(
id: AgentId,
sessionId: string,
sharedIdentity = false,
base?: string
): string | 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
// A per-builtin launch-command override (Settings → Agents → Launch commands, threaded here as
// `base`) replaces the program outright, INCLUDING codex's shared-identity launcher: an explicit
// override is the user saying "launch it exactly like this". Blank/absent → route a
// SHARED_IDENTITY_CAPABLE builtin (codex) through its managed launcher when present, else the
// bare command this has always emitted.
const custom = base?.trim() || undefined
const program = custom ?? agentLaunchProgram(id, builtin.launchCmd, sharedIdentity)
return resumeCommandWith(program, id, sessionId)
}
/**
* Is `sessionId` one this app would put on a `--resume` command line for `id`? The eligibility GATE
* the restart/hibernation choreography uses — WITHOUT building the command (which for a custom agent
* needs its `launchCmd` from settings, unavailable here). Inheritance-aware via `canResume`, so a
* claude-base custom agent is resumable; the SAFE_SESSION_ID check is the same one `resumeCommand`
* applies. Pure companion to `resumeCommand` for the gate-only call sites.
*/
export function canResumeWith(id: AgentId, sessionId: string): boolean {
if (!canResume(id)) return false
const sid = sessionId.trim()
return !!sid && SAFE_SESSION_ID.test(sid)
}
/**
* Resume by provider session id, using `launchCmd` as the binary and `grammarId` to pick the
* resume flag grammar (`--resume` vs `resume` vs `--session`). `grammarId` is the BASE harness
* for an inheriting custom agent (`capabilityAgentId(agentId)`), so a claude-base custom agent
* resumes as `<customLaunchCmd> --resume <sid>` — its own binary, claude's flag. Returns null for
* a non-resumable base or an unsafe/empty session id.
*/
export function resumeCommandWith(
launchCmd: string,
grammarId: AgentId,
sessionId: string
): string | null {
if (!canResume(grammarId)) return null
const sid = sessionId.trim()
if (!sid || !SAFE_SESSION_ID.test(sid)) return null
switch (grammarId) {
case 'codex':
return `${launchCmd} resume ${sid}`
case 'opencode':
return `${launchCmd} --session ${sid}`
case 'copilot':
return `${launchCmd} --resume=${sid}`
case 'antigravity':
return `${launchCmd} --conversation=${sid}`
case 'claude':
case 'gemini':
case 'grok':
case 'cursor':
return `${launchCmd} --resume ${sid}`
default:
return null
}
}
/**
* The permission mode an agent session STARTS in. The user can still cycle modes at runtime
* with Shift+Tab — this only decides the starting state, which is exactly what the CLI's
* `--permission-mode` flag does.
*
* `dontAsk` is deliberately not exposed: from the user's point of view it overlaps `auto`.
*
* VERSION GATE: `auto` is the one value here that older Claude CLIs do NOT accept — see
* AUTO_PERMISSION_MODE_MIN_VERSION / gatePermissionMode below. Never hand a raw `auto` to a
* launch command without running it through `gatePermissionMode` first.
*/
export type AgentPermissionMode = 'manual' | 'auto' | 'acceptEdits' | 'plan' | 'bypassPermissions'
/**
* First Claude Code version whose `--permission-mode` accepts `auto`. Earlier CLIs validate the
* value against their own choices list and EXIT 1:
* error: option '--permission-mode <mode>' argument 'auto' is invalid.
* Allowed choices are acceptEdits, bypassPermissions, default, dontAsk, plan.
* Since `auto` is our default, an ungated flag would break every Claude launch on an older CLI.
* The other four modes are accepted by every CLI we support, so ONLY `auto` is gated.
*
* MEASURED, not guessed: 2.1.0 through 2.1.70 reject `auto`; 2.1.71 is the first published
* version that accepts it (verified by running each published tarball's CLI directly).
*/
export const AUTO_PERMISSION_MODE_MIN_VERSION = '2.1.71'
const MIN_AUTO_VERSION: readonly number[] = AUTO_PERMISSION_MODE_MIN_VERSION.split('.').map(Number)
/**
* Pure numeric-version gate shared by the Claude CLI capability checks: parse the first
* `major.minor.patch` out of a `claude --version` line and answer whether it is >= `min`.
* FAILS OPEN to `false` on anything unreadable — an unknown version is treated as "too old", so
* every caller degrades to the conservative, pre-feature behavior rather than a failed launch.
*/
function versionAtLeast(versionOutput: string | null | undefined, min: readonly number[]): boolean {
const m = (versionOutput ?? '').match(/(\d+)\.(\d+)\.(\d+)/)
if (!m) return false
const v = [Number(m[1]), Number(m[2]), Number(m[3])]
for (let i = 0; i < min.length; i++) {
if (v[i] > min[i]) return true
if (v[i] < min[i]) return false
}
return true // exactly the minimum
}
/**
* Does this `claude --version` output know `--permission-mode auto`? Pure (the probe that feeds it
* lives in core/claude-cli.ts). FAILS OPEN to `false` on anything unreadable — an unknown version
* means we omit the flag and launch the bare command (today's behavior), never a failed launch.
*/
export function supportsAutoPermissionMode(versionOutput: string | null | undefined): boolean {
return versionAtLeast(versionOutput, MIN_AUTO_VERSION)
}
/**
* First Claude Code version whose `settings.json` understands `"tui": "fullscreen"` (the setting
* that makes a session take the alternate screen + mouse, so it behaves natively inside nodeterm's
* tmux instead of dropping drags into tmux copy-mode). Earlier CLIs don't know the key; writing it
* for them risks an unknown-setting warning, so the setting is only written when the CLI is known
* to be at least this version. MEASURED, not guessed.
*/
export const FULLSCREEN_TUI_MIN_VERSION = '2.1.89'
const MIN_FULLSCREEN_TUI_VERSION: readonly number[] = FULLSCREEN_TUI_MIN_VERSION.split('.').map(Number)
/**
* Does this `claude --version` output understand `"tui": "fullscreen"` in settings.json (>= 2.1.89)?
* Pure. FAILS OPEN to `false` — an unknown/older version means nodeterm does NOT write the key.
*/
export function supportsFullscreenTui(versionOutput: string | null | undefined): boolean {
return versionAtLeast(versionOutput, MIN_FULLSCREEN_TUI_VERSION)
}
/**
* The mode a session can ACTUALLY start in on the CLI that will run it. `auto` degrades to
* `manual` — which emits no flag at all, i.e. the bare `claude` command nodeterm shipped before
* this setting existed — when that CLI is too old to know the value (or the probe never
* answered). Every other mode passes through untouched, so a failed probe can never strip
* `plan` / `acceptEdits` / `bypassPermissions`.
*
* The user's SETTING stays `auto`: only the emitted command line changes, and it changes back
* the moment they upgrade the CLI.
*/
export function gatePermissionMode(
mode: AgentPermissionMode,
autoSupported: boolean
): AgentPermissionMode {
return mode === 'auto' && !autoSupported ? 'manual' : mode
}
// Declared first: its `Record<AgentPermissionMode, string>` type forces every member of the
// union to be present, which is what makes ALL_PERMISSION_MODES below impossible to desync.
export const PERMISSION_MODE_LABELS: Record<AgentPermissionMode, string> = {
manual: 'Ask each time',
auto: 'Auto',
acceptEdits: 'Accept edits',
plan: 'Plan',
bypassPermissions: 'Bypass all'
}
// Derived, never hand-maintained: add a mode to the union and the compiler makes you label it,
// which lands it here (and so in the settings dropdown + isPermissionMode) automatically.
export const ALL_PERMISSION_MODES: readonly AgentPermissionMode[] = Object.keys(
PERMISSION_MODE_LABELS
) as AgentPermissionMode[]
/** Fallback whenever a persisted mode is missing or unrecognized. */
export const DEFAULT_PERMISSION_MODE: AgentPermissionMode = 'auto'
/** The ONE validator for a persisted mode. Exported so every interpolation site can re-validate
* through it (see `permissionModeFlag` below and `approvalFlags` in ./approval-mode) rather than
* growing a second copy that drifts from `ALL_PERMISSION_MODES`. */
export const isPermissionMode = (v: unknown): v is AgentPermissionMode =>
typeof v === 'string' && (ALL_PERMISSION_MODES as readonly string[]).includes(v)
/** CLI flags for a mode. `manual` yields NO flags, so the command stays bare — the exact
* command nodeterm shipped before this setting existed.
*
* The mode is re-validated HERE even though the parameter is typed: AgentPermissionMode is
* compile-time only, and the value comes from hand-editable, git-shared JSON (settings.json /
* project.json) before being interpolated into a shell command line. Same rule as
* SAFE_SESSION_ID above — validate at the interpolation site. An unrecognized mode yields the
* safe bare command rather than a flag carrying an unvalidated value. */
export function permissionModeFlag(mode: AgentPermissionMode): string[] {
if (!isPermissionMode(mode) || mode === 'manual') return []
return ['--permission-mode', mode]
}
// `withPermissionMode` — the single funnel every CLI launch path goes through — lives in
// ./approval-mode.ts, one layer UP: since gemini and codex joined, appending the flag needs the
// per-agent mapping, and that table has to import this file. Re-exporting it from here would close
// the cycle, so the funnel moved to the layer that owns the translation instead.
/**
* The mode a new session starts in: the project override, else the global setting.
* Mirrors resolveNewNodeAccount's shape, including its stale-value guard — an unrecognized
* persisted mode must never reach the CLI as a flag value.
*
* Structurally typed (not `Project`/`Settings`) because src/shared/types.ts imports THIS file;
* importing it back would be a cycle.
*/
export function resolvePermissionMode(
project: { defaultPermissionMode?: AgentPermissionMode } | undefined,
settings: { claudePermissionMode: AgentPermissionMode }
): AgentPermissionMode {
return resolvePermissionModeWithSource(project, settings).mode
}
/**
* The same resolution, plus WHO chose the mode — and that second half is a security fact, not a
* nicety.
*
* `project.defaultPermissionMode` is persisted to `.nodeterm/project.json`, which is git-shared:
* a `bypassPermissions` override travels to everyone who clones the repo. So anything that
* LOOSENS a gate on the strength of the mode (today: the canvas-control confirm waiver,
* `decideControlConfirm` in @shared/control-confirm) must be able to tell "the user set this
* globally on this machine" from "this arrived in somebody's repo". `'default'` is its own answer
* rather than being folded into `'global'`: nobody has chosen anything, and a caller that treats
* an unset setting as a deliberate global choice is reading consent into silence.
*
* `resolvePermissionMode` delegates here so the two can never disagree about which half wins.
*/
export function resolvePermissionModeWithSource(
project: { defaultPermissionMode?: AgentPermissionMode } | undefined,
settings: { claudePermissionMode: AgentPermissionMode }
): { mode: AgentPermissionMode; source: 'project' | 'global' | 'default' } {
if (isPermissionMode(project?.defaultPermissionMode)) {
return { mode: project.defaultPermissionMode, source: 'project' }
}
if (isPermissionMode(settings.claudePermissionMode)) {
return { mode: settings.claudePermissionMode, source: 'global' }
}
return { mode: DEFAULT_PERMISSION_MODE, source: 'default' }
}