Skip to content

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

feat(agents): add Copilot CLI support

Darren Kattan7d16801eff32
diff --git a/CLAUDE.md b/CLAUDE.md
index b3539a390..feb87c391 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -640,7 +640,7 @@ Monaco is wired in `renderer/editor/monaco-setup.ts` (language workers bundled v
`?worker` — no CDN; CSP `worker-src` allows them). Markdown rendering is shared in
`renderer/lib/markdown.ts` (`marked` + DOMPurify sanitize).
-## Agent support (Claude / Codex / Gemini / opencode / Grok / custom)
+## Agent support (Claude / Codex / Gemini / Copilot / opencode / Grok / custom)
The app is a pluggable multi-agent system: Claude Code is one builtin of
several. Extra terminal-node behavior is driven per agent by a registry + capability lists, a
@@ -650,7 +650,7 @@ persisted — only `unread`/`session`/`sessionId` go to localStorage under
`nodeterm.agentStatus`, migrated once from the legacy `nodeterm.claudeStatus` key).
- **Agent registry + capabilities** — `src/shared/agents/config.ts` holds `AGENT_CONFIG`
- (claude/codex/gemini/opencode/grok: id, label, spawn command, color, `promptInjectionMode`, …) keyed
+ (claude/codex/gemini/copilot/opencode/grok: id, label, spawn command, color, `promptInjectionMode`, …) keyed
by an **open** `AgentId`
type (so custom ids fit). Capabilities are membership lists, not flags:
`AGENT_HOOK_TARGETS`, `RESUMABLE_AGENTS`, `SUBAGENT_CAPABLE`, `RECURRING_CAPABLE`,
@@ -667,10 +667,11 @@ persisted — only `unread`/`session`/`sessionId` go to localStorage under
sync is **split in two** — `TITLE_READ_CAPABLE = claude/grok/gemini` (read) ⊇ `RENAME_CAPABLE =
claude/grok` (write), because gemini names its own sessions but has no rename command;
**Context Link** spans four builtins
- (`CONTEXT_LINK_CAPABLE = claude/codex/gemini/opencode`, NOT grok). UI gates
- on these helpers — no hardcoded `=== 'claude'`. **Custom agents** (user-defined in Settings, `customAgents`) are in
- no capability list: spawn + terminal-title + process status only. Per-agent write-ups:
- **`docs/grok-agent.md`**, **`docs/gemini-agent.md`** (there is none for codex — its approval mapping
+ (`CONTEXT_LINK_CAPABLE = claude/codex/gemini/opencode`, NOT grok/copilot). UI gates
+ on these helpers — no hardcoded `=== 'claude'`. **Custom agents** (user-defined in Settings,
+ `customAgents`) inherit the declared `baseAgent` harness through `capabilityAgentId`; a custom
+ agent with no base remains spawn + terminal-title + process status only. Per-agent write-ups:
+ **`docs/grok-agent.md`**, **`docs/gemini-agent.md`**, **`docs/copilot-agent.md`** (there is none for codex — its approval mapping
and every value's reasoning live in `src/shared/agents/approval-mode.ts`);
the distilled rules are **Adding a new agent** at the end of this section.
- **Model gateway / switcher** — `settings.modelGateway` stores one Bifrost-compatible root +
@@ -678,7 +679,7 @@ persisted — only `unread`/`session`/`sessionId` go to localStorage under
routes, env vars, compatible models and safely quoted model flags. It derives `/v1/models`,
`/openai/v1` and `/anthropic`; discovery runs in core (`agent:discover-models`) so browser CORS
cannot block the Server Edition and the key never enters a terminal command. Support is a
- capability (`MODEL_SWITCH_CAPABLE = claude/codex`) resolved through `capabilityAgentId`, so a
+ capability (`MODEL_SWITCH_CAPABLE = claude/codex/copilot`) resolved through `capabilityAgentId`, so a
custom agent with a supported `baseAgent` inherits it automatically — the settings UI and canvas
menu carry no agent allowlist. A model switch cleanly exits the CLI and RECYCLES the tmux session
before cold-resume: an existing shell may predate the gateway setting, and tmux env changes do
@@ -832,7 +833,7 @@ persisted — only `unread`/`session`/`sessionId` go to localStorage under
own gate adds one beside claude's.
- **State via each agent's hooks → shared 4-state model** — detection uses the agent's own
hooks, **not** output parsing. `src/shared/agents/normalize.ts` has per-agent normalizers
- (`normalizeClaude`/`normalizeCodex`/`normalizeGemini`/`normalizeOpencode`/`normalizeGrok`) that map each agent's native hook
+ (`normalizeClaude`/`normalizeCodex`/`normalizeGemini`/`normalizeCopilot`/`normalizeOpencode`/`normalizeGrok`) that map each agent's native hook
events to a `NormalizedAgentEvent` over the shared `AgentState` (`working | waiting | blocked
| done`) plus subagent/recurring/session kinds. Canvas's listener consumes
`NormalizedAgentEvent` from `agent:status`, drives the `agentStatus` store, fires throttled
@@ -1017,7 +1018,7 @@ persisted — only `unread`/`session`/`sessionId` go to localStorage under
the session id already known from hooks; `lib/claudeBranch.ts` is the fallback that parses
`pty.capture` output when the id isn't known. The source node stays on the new branch.
- **Canvas control (manage-nodeterm-canvas)** — agents in `CANVAS_CONTROL_CAPABLE`
- (claude/codex/gemini/opencode/grok) can create/organize/control canvas nodes from inside their
+ (claude/codex/gemini/copilot/opencode/grok) can create/organize/control canvas nodes from inside their
session: a POSIX **sh+curl** shim (`nodeterm.sh`, `CONTROL_SHIM_SCRIPT` in
`main/canvas-control-core.ts` — the Electron-as-Node CLI is retired) POSTs
**form-urlencoded** (`nodeId` + `arg.<flag>` fields; `curl --data-urlencode` is the only
@@ -1026,7 +1027,8 @@ persisted — only `unread`/`session`/`sessionId` go to localStorage under
reply (sh has no JSON parser). Env-gated on `NODETERM_CANVAS_CONTROL` (set by
`buildPtyEnv`/`remoteHookEnvArgs` per `canControlCanvas`). Discovery: claude gets a
`skills/manage-nodeterm-canvas/SKILL.md` (system `~/.claude` + each managed account dir);
- codex/gemini/opencode get a marker block (`<!-- nodeterm:manage-canvas:start/end -->`); **grok needs
+ codex/gemini/opencode plus Copilot's `copilot-instructions.md` get a marker block
+ (`<!-- nodeterm:manage-canvas:start/end -->`); **grok needs
no installer at all** — it scans `~/.claude/skills` by default for Claude compat, so membership alone
(which sets `NODETERM_CANVAS_CONTROL`) is the whole wiring. That premise rests on grok's shipped
docs and is **unverified** (`grok inspect --json` never run); if it does not hold, grok takes the
diff --git a/README.md b/README.md
index 77ad02ce4..6369ef33e 100644
--- a/README.md
+++ b/README.md
@@ -121,7 +121,7 @@ then **Send** (nothing auto-submits). Your voice never leaves the machine.
### Node kinds
🖥 **Terminal** (xterm + tmux, AI naming) · 🤖 **Agent** (Claude Code / Codex / Gemini /
-opencode / custom) · 📝 **Sticky note** (link to an agent as context) · 🗂 **Group**
+GitHub Copilot / opencode / Grok / custom) · 📝 **Sticky note** (link to an agent as context) · 🗂 **Group**
(bind to a **git worktree** for agent-per-branch) · ✏️ **Editor** (Monaco, ⌘S) ·
🔀 **Diff** · 🌐 **Web / Video**
diff --git a/docs/copilot-agent.md b/docs/copilot-agent.md
new file mode 100644
index 000000000..da22fd51e
--- /dev/null
+++ b/docs/copilot-agent.md
@@ -0,0 +1,74 @@
+# GitHub Copilot CLI agent support
+
+Copilot is a builtin base harness. Its integrations live behind the same registry and capability
+predicates as every other agent, so a custom agent with `baseAgent: 'copilot'` inherits its icon,
+launch/resume grammar, hooks, canvas control, and model-gateway mapping without renderer allowlists.
+
+## Verified contracts
+
+The following were checked against the installed Copilot CLI 1.0.80 and GitHub's current official
+CLI reference:
+
+- `copilot --interactive <prompt>` opens the normal interactive TUI and submits the initial prompt;
+ `--prompt` is non-interactive and exits after the response.
+- `--session-id=<uuid>` creates a caller-addressable session, `--resume=<uuid>` resumes it, `/exit`
+ cleanly returns to the shell, and `--model` selects a GitHub-routed model.
+- BYOK mode activates through `COPILOT_PROVIDER_BASE_URL`. The implementation also sets
+ `COPILOT_PROVIDER_TYPE`, `COPILOT_PROVIDER_API_KEY`, `COPILOT_PROVIDER_MODEL_ID`, and
+ `COPILOT_PROVIDER_WIRE_MODEL`; GPT-5-family OpenAI models use
+ `COPILOT_PROVIDER_WIRE_API=responses` as the CLI requires.
+- User hooks are merged from `$COPILOT_HOME/hooks/*.json` (default `~/.copilot/hooks`). PascalCase
+ event aliases emit the snake_case payload nodeterm's shared hook transport expects.
+- Global instructions live at `$COPILOT_HOME/copilot-instructions.md`.
+
+Primary references:
+
+- <https://docs.github.com/en/copilot/reference/copilot-cli-reference/cli-programmatic-reference>
+- <https://docs.github.com/en/copilot/reference/hooks-reference>
+- <https://docs.github.com/en/copilot/how-tos/copilot-cli/customize-copilot/add-custom-instructions>
+
+## Model gateway mapping
+
+The user enters one Bifrost-compatible root and virtual key. Discovery calls `<root>/v1/models`.
+For a selected Copilot model:
+
+- `anthropic/<model>` uses provider type `anthropic`, base URL `<root>/anthropic`, internal model id
+ `<model>`, and wire model `anthropic/<model>`.
+- Every other provider-prefixed model uses provider type `openai`, base URL `<root>/openai/v1`, an
+ unprefixed internal id, and the original provider-prefixed wire id.
+
+Copilot BYOK is not activated merely because gateway settings exist: a model must be selected for
+that node first. This preserves ordinary GitHub Copilot routing for untouched nodes. Model changes
+recycle the tmux session after a clean `/exit`, then cold-resume the same Copilot session under the
+new environment; the key is never typed into the pane.
+
+## Status hooks
+
+Nodeterm owns `nodeterm-status.json` in Copilot's hooks directory and writes the shared guarded
+script to `~/.nodeterm/agent-hooks/copilot.sh`. It observes:
+
+- session start/end;
+- user prompt, pre-tool, post-tool, and failed-tool activity;
+- turn completion (`Stop`);
+- the closed notification types `permission_prompt` and `elicitation_dialog`.
+
+`PermissionRequest` is deliberately not installed because it is a decision hook that can change
+authorization. `ErrorOccurred` is omitted because recoverable errors can occur before a turn
+continues. Unknown notifications are no-ops, preventing sticky NEEDS YOU badges.
+
+## Device checklist
+
+These require an authenticated or real gateway-backed session and were not exercised by the unit
+suite:
+
+1. Start an authenticated Copilot node with an initial prompt; verify interactive TUI behavior and
+ that SessionStart/UserPromptSubmit/Stop update the canvas badge and persisted session id.
+2. Trigger one permission prompt and one `ask_user` elicitation; verify NEEDS YOU clears when work
+ continues and that informational/idle notifications never create a badge.
+3. Select an OpenAI Bifrost model, run a tool-using turn, switch models, and verify the same session
+ resumes through `/openai/v1` using the provider-prefixed wire model.
+4. Repeat with an Anthropic model through `/anthropic`, including one tool call.
+5. Repeat 1–4 on an SSH project whose `COPILOT_HOME` differs from `~/.copilot`; verify both the hook
+ file and `copilot-instructions.md` land under the host-reported directory.
+6. Create a custom agent based on Copilot and verify its base icon, launch/resume behavior, hook
+ status, canvas control, and model switch all match the builtin.
diff --git a/src/core/agents/hook-server.env.test.ts b/src/core/agents/hook-server.env.test.ts
index f4736e93a..e18947ffe 100644
--- a/src/core/agents/hook-server.env.test.ts
+++ b/src/core/agents/hook-server.env.test.ts
@@ -12,6 +12,7 @@ import { hookServer } from './hook-server'
import { nodeAuthToken } from './node-auth-token'
import { initPlatform, resetPlatformForTests } from '../platform'
import { fakePlatform } from '../platform-fake'
+import { CANVAS_CONTROL_CAPABLE } from '../../shared/agents/config'
let dir = ''
@@ -38,8 +39,8 @@ describe('hookServer.buildPtyEnv — canvas control gate', () => {
expect(hookServer.buildPtyEnv('n1', 'grok').NODETERM_CANVAS_CONTROL).toBe('1')
})
- it('arms it for the other capable builtins too', () => {
- for (const id of ['claude', 'codex', 'gemini', 'opencode'])
+ it('arms it for every capable builtin', () => {
+ for (const id of CANVAS_CONTROL_CAPABLE)
expect(hookServer.buildPtyEnv('n1', id).NODETERM_CANVAS_CONTROL, id).toBe('1')
})
diff --git a/src/core/agents/hooks/copilot.test.ts b/src/core/agents/hooks/copilot.test.ts
new file mode 100644
index 000000000..16d262cd4
--- /dev/null
+++ b/src/core/agents/hooks/copilot.test.ts
@@ -0,0 +1,101 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { mkdtempSync, readFileSync, rmSync } from 'fs'
+import { tmpdir } from 'os'
+import path from 'path'
+import { COPILOT_HOOK_EVENTS } from '@shared/agents/hook-events'
+
+let home = ''
+
+vi.mock('os', async (orig) => {
+ const real = (await orig()) as typeof import('os')
+ return {
+ ...real,
+ default: { ...real, homedir: () => home },
+ homedir: () => home
+ }
+})
+
+describe('copilot hook installer', () => {
+ beforeEach(() => {
+ home = mkdtempSync(path.join(tmpdir(), 'nt-copilot-home-'))
+ delete process.env.COPILOT_HOME
+ })
+
+ afterEach(() => {
+ rmSync(home, { recursive: true, force: true })
+ delete process.env.COPILOT_HOME
+ vi.resetModules()
+ })
+
+ it("writes Copilot's native hook-file shape and the shared managed script", async () => {
+ const { copilotHookConfigPath, installCopilotHooks } =
+ await import('./copilot')
+ installCopilotHooks()
+ expect(copilotHookConfigPath()).toBe(
+ path.join(home, '.copilot', 'hooks', 'nodeterm-status.json')
+ )
+ const cfg = JSON.parse(readFileSync(copilotHookConfigPath(), 'utf8'))
+ expect(Object.keys(cfg.hooks).sort()).toEqual(
+ [...COPILOT_HOOK_EVENTS].sort()
+ )
+ expect(cfg.hooks.SessionStart).toEqual([
+ {
+ type: 'command',
+ bash: expect.stringContaining(
+ path.join(home, '.nodeterm', 'agent-hooks', 'copilot.sh')
+ ),
+ timeoutSec: 5
+ }
+ ])
+ expect(cfg.hooks.SessionStart[0].bash).toMatch(/^if \[ -r /)
+ expect(cfg.hooks.SessionStart[0].matcher).toBeUndefined()
+ expect(cfg.hooks.Notification[0].matcher).toBe(
+ 'permission_prompt|elicitation_dialog'
+ )
+ expect(
+ readFileSync(
+ path.join(home, '.nodeterm', 'agent-hooks', 'copilot.sh'),
+ 'utf8'
+ )
+ ).toContain('/hook/copilot')
+ })
+
+ it('honors COPILOT_HOME and is idempotent because nodeterm owns its file', async () => {
+ process.env.COPILOT_HOME = path.join(home, 'custom-copilot')
+ const { copilotHookConfigPath, installCopilotHooks } =
+ await import('./copilot')
+ installCopilotHooks()
+ installCopilotHooks()
+ expect(copilotHookConfigPath()).toBe(
+ path.join(home, 'custom-copilot', 'hooks', 'nodeterm-status.json')
+ )
+ const cfg = JSON.parse(readFileSync(copilotHookConfigPath(), 'utf8'))
+ for (const entries of Object.values(cfg.hooks) as unknown[][])
+ expect(entries).toHaveLength(1)
+ })
+
+ it('accepts only absolute, shell-safe remote COPILOT_HOME values', async () => {
+ const { isSafeRemoteCopilotHome } = await import('./copilot')
+ expect(isSafeRemoteCopilotHome('/opt/copilot home')).toBe(true)
+ for (const value of [
+ 'relative/path',
+ ' /opt/copilot',
+ '/bad\\path',
+ '/bad\npath',
+ ''
+ ]) {
+ expect(isSafeRemoteCopilotHome(value), JSON.stringify(value)).toBe(false)
+ }
+ })
+
+ it('remove disables every managed subscription without touching another hook file', async () => {
+ const { copilotHookConfigPath, installCopilotHooks, removeCopilotHooks } =
+ await import('./copilot')
+ installCopilotHooks()
+ removeCopilotHooks()
+ expect(JSON.parse(readFileSync(copilotHookConfigPath(), 'utf8'))).toEqual({
+ version: 1,
+ hooks: {}
+ })
+ })
+})
diff --git a/src/core/agents/hooks/copilot.ts b/src/core/agents/hooks/copilot.ts
new file mode 100644
index 000000000..2b32a8b53
--- /dev/null
+++ b/src/core/agents/hooks/copilot.ts
@@ -0,0 +1,110 @@
+// GitHub Copilot CLI status-hook installer. Copilot discovers and merges every JSON file under
+// `$COPILOT_HOME/hooks/` (default `~/.copilot/hooks`), so nodeterm owns one file outright. Its JSON
+// grammar is intentionally adapted here rather than pushed into the Claude/Gemini merge helper:
+// Copilot entries are `{ type, bash, timeoutSec }` directly under each event, while those agents
+// nest `{ type, command }` below a matcher-bearing hook definition.
+import fs from 'fs'
+import os from 'os'
+import path from 'path'
+import { COPILOT_HOOK_EVENTS } from '@shared/agents/hook-events'
+import {
+ buildManagedHookCommand,
+ installManagedHookScript
+} from './install-helper'
+
+const SCRIPT_FILE_NAME = 'copilot.sh'
+export const COPILOT_HOOK_FILE = 'nodeterm-status.json'
+
+type CopilotEnv = { COPILOT_HOME?: string }
+const REMOTE_HOME_MAX = 4096
+
+export interface CopilotHookCommand {
+ type: 'command'
+ bash: string
+ timeoutSec: number
+ matcher?: string
+}
+
+export interface CopilotHookConfig {
+ version: 1
+ hooks: Record<string, CopilotHookCommand[]>
+}
+
+export function copilotHomeDir(
+ env: CopilotEnv = process.env as CopilotEnv,
+ home: string = os.homedir()
+): string {
+ return env.COPILOT_HOME?.trim() || path.join(home, '.copilot')
+}
+
+/** Validate a host-reported COPILOT_HOME before it is interpolated into an SSH command. */
+export function isSafeRemoteCopilotHome(value: string | undefined): boolean {
+ const v = value?.trim()
+ if (
+ !v ||
+ v !== value ||
+ !v.startsWith('/') ||
+ v.includes('\\') ||
+ v.length > REMOTE_HOME_MAX
+ ) {
+ return false
+ }
+ return !Array.from(v).some((ch) => {
+ const code = ch.charCodeAt(0)
+ return code <= 0x1f || code === 0x7f
+ })
+}
+
+export function copilotHookConfigPath(): string {
+ return path.join(copilotHomeDir(), 'hooks', COPILOT_HOOK_FILE)
+}
+
+/** Pure config builder shared with the SSH installer, which supplies a remote script path. */
+export function buildCopilotHookConfig(command: string): CopilotHookConfig {
+ const hooks: Record<string, CopilotHookCommand[]> = {}
+ for (const event of COPILOT_HOOK_EVENTS) {
+ hooks[event] = [
+ {
+ type: 'command',
+ bash: command,
+ timeoutSec: 5,
+ // Copilot's notification matcher is a regex on notification_type. These are the only two
+ // notifications that change nodeterm state; filtering at source avoids one process per
+ // background-agent/shell informational notification.
+ ...(event === 'Notification'
+ ? { matcher: 'permission_prompt|elicitation_dialog' }
+ : {})
+ }
+ ]
+ }
+ return { version: 1, hooks }
+}
+
+export function installCopilotHooks(): void {
+ const script = installManagedHookScript('copilot', SCRIPT_FILE_NAME)
+ if (!script) return
+ const configPath = copilotHookConfigPath()
+ try {
+ fs.mkdirSync(path.dirname(configPath), { recursive: true })
+ fs.writeFileSync(
+ configPath,
+ `${JSON.stringify(buildCopilotHookConfig(buildManagedHookCommand(script)), null, 2)}\n`,
+ 'utf8'
+ )
+ } catch (e) {
+ console.warn('[agent-hooks] copilot install failed', e)
+ }
+}
+
+export function removeCopilotHooks(): void {
+ const configPath = copilotHookConfigPath()
+ try {
+ fs.writeFileSync(
+ configPath,
+ `${JSON.stringify({ version: 1, hooks: {} }, null, 2)}\n`,
+ 'utf8'
+ )
+ } catch {
+ /* fail open */
+ }
+}
diff --git a/src/core/agents/hooks/index.ts b/src/core/agents/hooks/index.ts
index 0c4675f80..ed1b355da 100644
--- a/src/core/agents/hooks/index.ts
+++ b/src/core/agents/hooks/index.ts
@@ -6,6 +6,7 @@ import { installCodexHooks, removeCodexHooks } from './codex'
import { installGeminiHooks, removeGeminiHooks } from './gemini'
import { installOpencodeHooks, removeOpencodeHooks } from './opencode'
import { installGrokHooks, removeGrokHooks } from './grok'
+import { installCopilotHooks, removeCopilotHooks } from './copilot'
type HookInstaller = readonly [string, () => void]
@@ -14,7 +15,8 @@ export const MANAGED_HOOK_INSTALLERS: readonly HookInstaller[] = [
['codex', installCodexHooks],
['gemini', installGeminiHooks],
['opencode', installOpencodeHooks],
- ['grok', installGrokHooks]
+ ['grok', installGrokHooks],
+ ['copilot', installCopilotHooks]
]
export const MANAGED_HOOK_REMOVERS: readonly HookInstaller[] = [
@@ -22,7 +24,8 @@ export const MANAGED_HOOK_REMOVERS: readonly HookInstaller[] = [
['codex', removeCodexHooks],
['gemini', removeGeminiHooks],
['opencode', removeOpencodeHooks],
- ['grok', removeGrokHooks]
+ ['grok', removeGrokHooks],
+ ['copilot', removeCopilotHooks]
]
export function installManagedAgentHooks(): void {
diff --git a/src/core/agents/hooks/install-helper.ts b/src/core/agents/hooks/install-helper.ts
index 0cc790e35..d9ac17212 100644
--- a/src/core/agents/hooks/install-helper.ts
+++ b/src/core/agents/hooks/install-helper.ts
@@ -34,10 +34,28 @@ export type HookSettings = Settings
* Every instance now writes identical bytes to the same stable path — which is also where the SSH
* remote installer already puts it (`$HOME/.nodeterm/agent-hooks/`), so local and remote agree.
*/
-function scriptPathFor(scriptFileName: string): string {
+export function managedHookScriptPath(scriptFileName: string): string {
return path.join(homedir(), '.nodeterm', 'agent-hooks', scriptFileName)
}
+/** Write one stable, guarded hook target for any local agent installer. */
+export function installManagedHookScript(agentId: string, scriptFileName: string): string | null {
+ const scriptPath = managedHookScriptPath(scriptFileName)
+ try {
+ mkdirSync(path.dirname(scriptPath), { recursive: true })
+ writeFileSync(scriptPath, buildManagedScript(agentId), 'utf8')
+ } catch (e) {
+ console.warn(`[agent-hooks] ${agentId} script write failed`, e)
+ return null
+ }
+ try {
+ chmodSync(scriptPath, 0o755)
+ } catch {
+ /* fail open */
+ }
+ return scriptPath
+}
+
/**
* The managed hook command: run our script, but ONLY if it is still on disk.
*
@@ -132,19 +150,8 @@ export interface InstallHooksOptions {
export function installHooksInto(opts: InstallHooksOptions): void {
const { agentId, scriptFileName, configPath, events } = opts
- const sp = scriptPathFor(scriptFileName)
- try {
- mkdirSync(path.dirname(sp), { recursive: true })
- writeFileSync(sp, buildManagedScript(agentId), 'utf8')
- } catch (e) {
- console.warn(`[agent-hooks] ${agentId} script write failed`, e)
- return
- }
- try {
- chmodSync(sp, 0o755)
- } catch {
- /* fail open */
- }
+ const sp = installManagedHookScript(agentId, scriptFileName)
+ if (!sp) return
const command = buildManagedHookCommand(sp)
let config: Settings = {}
diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.ts
index b97471277..5092ccf9e 100644
--- a/src/core/pty-manager.ts
+++ b/src/core/pty-manager.ts
@@ -2008,11 +2008,12 @@ export class PtyManager {
// benefits from the one-click gateway by default, but env values it explicitly declares still
// win exactly as they did before this feature. Remote values travel through tmux `-e` below;
// do not leak them into the local ssh client process environment.
- const gatewayEnv = modelGatewayEnv(
- this.getSettings().modelGateway,
- options.agentId ?? 'claude',
- options.agentModel
- )
+ // A plain terminal has no agentId and must never receive provider credentials. The hook env's
+ // historical Claude fallback does not apply here: gateway access is an explicit agent
+ // capability, not a terminal default.
+ const gatewayEnv = options.agentId
+ ? modelGatewayEnv(this.getSettings().modelGateway, options.agentId, options.agentModel)
+ : {}
if (!options.sshRemote) {
for (const [k, v] of Object.entries(gatewayEnv)) env[k] = v
}
diff --git a/src/core/pty-single-user.test.ts b/src/core/pty-single-user.test.ts
index a16ace73f..be2f98af8 100644
--- a/src/core/pty-single-user.test.ts
+++ b/src/core/pty-single-user.test.ts
@@ -253,6 +253,64 @@ describe('SINGLE-USER REGRESSION: co-attach must not change the solo path', () =
)
})
+ it('maps a selected Copilot model into its BYOK environment, never a model flag', async () => {
+ const { PtyManager } = await import('./pty-manager')
+ const m = new PtyManager()
+ m.init(() => ({
+ ...DEFAULT_SETTINGS,
+ modelGateway: { baseUrl: 'https://bifrost.example.test', apiKey: 'vk-secret' }
+ }))
+ m.registerIpc()
+
+ await create(80, 24, 'copilot-gateway-node', {
+ agentId: 'copilot',
+ agentModel: 'openai/gpt-5.5'
+ })
+
+ expect(spawnArgs[0].env).toMatchObject({
+ COPILOT_PROVIDER_BASE_URL: 'https://bifrost.example.test/openai/v1',
+ COPILOT_PROVIDER_TYPE: 'openai',
+ COPILOT_PROVIDER_API_KEY: 'vk-secret',
+ COPILOT_PROVIDER_MODEL_ID: 'gpt-5.5',
+ COPILOT_PROVIDER_WIRE_MODEL: 'openai/gpt-5.5',
+ COPILOT_PROVIDER_WIRE_API: 'responses'
+ })
+ expect(spawnArgs[0].args).toEqual(
+ expect.arrayContaining([
+ '-e',
+ 'COPILOT_PROVIDER_MODEL_ID=gpt-5.5',
+ '-e',
+ 'COPILOT_PROVIDER_WIRE_MODEL=openai/gpt-5.5'
+ ])
+ )
+ expect(spawnArgs[0].args.join(' ')).not.toContain('--model')
+ })
+
+ it('never exposes gateway credentials to a plain terminal', async () => {
+ const inherited = process.env.ANTHROPIC_AUTH_TOKEN
+ process.env.ANTHROPIC_AUTH_TOKEN = 'preexisting-shell-token'
+ try {
+ const { PtyManager } = await import('./pty-manager')
+ const m = new PtyManager()
+ m.init(() => ({
+ ...DEFAULT_SETTINGS,
+ modelGateway: { baseUrl: 'https://bifrost.example.test', apiKey: 'vk-secret' }
+ }))
+ m.registerIpc()
+
+ await create(80, 24, 'plain-terminal')
+
+ // Plain shells still inherit the user's ordinary process environment; the gateway neither
+ // overwrites it nor emits an explicit tmux session value.
+ expect(spawnArgs[0].env.ANTHROPIC_AUTH_TOKEN).toBe('preexisting-shell-token')
+ expect(spawnArgs[0].args.join(' ')).not.toContain('vk-secret')
+ expect(spawnArgs[0].args.join(' ')).not.toContain('bifrost.example.test')
+ } finally {
+ if (inherited === undefined) delete process.env.ANTHROPIC_AUTH_TOKEN
+ else process.env.ANTHROPIC_AUTH_TOKEN = inherited
+ }
+ })
+
// ── `fresh` drives scrollback replay + agent resume: it must still be computed from tmux ──
it('fresh:false on a WARM reattach (tmux session already exists) — no cold restore', async () => {
await tmuxManager()
diff --git a/src/main/canvas-control-core.ts b/src/main/canvas-control-core.ts
index 7358b7262..392757ac6 100644
--- a/src/main/canvas-control-core.ts
+++ b/src/main/canvas-control-core.ts
@@ -2,6 +2,7 @@
// CLI source. No electron imports, so this module + CONTROL_CLI_SCRIPT are unit-testable.
// Electron/ipc/server wiring lives in canvas-control.ts + index.ts + hook-server.ts.
import { HOOK_CURL_HEADERS_SH } from '../core/agents/hook-curl-config-sh'
+import { AGENT_CONFIG, AGENT_HOOK_TARGETS, BUILTIN_AGENT_IDS } from '@shared/agents/config'
import { RETRYABLE } from '../core/agents/agent-message-decide'
import { FANOUT_PER_TURN, PAIR_MIN_INTERVAL_MS } from '../core/agents/agent-message-flow'
@@ -168,6 +169,8 @@ export function mergeCanvasControlBlock(existing: string, block: string): string
/** The instructions body telling codex/gemini how to control the nodeterm canvas.
* Keep the verb list in sync with the skill template in canvas-control.ts. */
export function buildCanvasControlInstructions(shimPath: string): string {
+ const agentChoices = `${BUILTIN_AGENT_IDS.join('|')}|<custom-id>`
+ const statusAgents = AGENT_HOOK_TARGETS.join('/')
return [
'# Managing the nodeterm canvas (manage-nodeterm-canvas)',
'',
@@ -190,12 +193,12 @@ export function buildCanvasControlInstructions(shimPath: string): string {
'- `list` — current nodes (id, kind, title). Start here when you need a node id.',
'- `open-terminal [--count N] [--cwd P] [--cmd C] [--group <id>] [--after <id,id>]` — open N plain terminals.',
'- `open-claude [--count N] [--cwd P] [--prompt T] [--group <id>] [--after <id,id>]` — open N Claude sessions.',
- '- `open-agent --agent claude|codex|gemini|opencode|<custom-id> [--count N] [--cwd P] [--prompt T] [--group <id>] [--after <id,id>]` — open',
+ `- \`open-agent --agent ${agentChoices} [--count N] [--cwd P] [--prompt T] [--group <id>] [--after <id,id>]\` — open`,
' any agent CLI. `--group` parents the node(s) into a group frame; a worktree-bound group also',
' hands its worktree path down as the cwd. `--after <id,id>` opens the node ARMED: it does not',
' start until every listed station has gone idle, and is context-linked to them so it can read',
' their work when it wakes — use it for "B needs what A produced" instead of polling. Only',
- ' status-reporting agent nodes (claude/codex/gemini) may be waited on; a plain terminal never',
+ ` status-reporting agent nodes (${statusAgents}, or custom agents based on them) may be waited on; a plain terminal never`,
' reports finishing, so waiting on one is refused.',
'- `show-image <path>` / `show-video <path>` — open a media file as a node.',
'- `show-web (--url U | --file P.html | --html "<...>")` — open a web viewer.',
@@ -397,9 +400,12 @@ exit 1
* Parameterized because the same skill is installed twice with different paths: into the
* desktop's config dirs, and onto an SSH host for remote agent nodes. */
export function buildCanvasSkillBody(shimPath: string): string {
+ const agentChoices = `${BUILTIN_AGENT_IDS.join('|')}|<custom-id>`
+ const statusAgents = AGENT_HOOK_TARGETS.join('/')
+ const agentLabels = BUILTIN_AGENT_IDS.map((id) => AGENT_CONFIG[id].label).join(' / ')
return `---
name: manage-nodeterm-canvas
-description: Create, organize and control nodes on the nodeterm canvas — open Claude Code / Codex / Gemini / terminal nodes, spawn a team of agents that divide up a task, create git worktrees as bound groups, wrap nodes in labeled groups, arrange/align/rename them, move nodes between frames, link nodes so you can read back what they produced, move session cards between kanban columns to track progress, show an image/video/web page, write to or close a terminal. Use whenever the user says "Build with Nodeterm orchestration", asks to create or open nodes/sessions/terminals, split or parallelize work across subagents/agents/sessions/worktrees, delegate parts of a task to other agents, work on several things at once, build something using multiple Claude (or other agent) sessions, collect or synthesize the results of agents you opened, organize the canvas into groups by topic, move tasks across a kanban board, or visualize code/output you produced. Only works inside a nodeterm agent session.
+description: Create, organize and control nodes on the nodeterm canvas — open ${agentLabels} / terminal nodes, spawn a team of agents that divide up a task, create git worktrees as bound groups, wrap nodes in labeled groups, arrange/align/rename them, move nodes between frames, link nodes so you can read back what they produced, move session cards between kanban columns to track progress, show an image/video/web page, write to or close a terminal. Use whenever the user says "Build with Nodeterm orchestration", asks to create or open nodes/sessions/terminals, split or parallelize work across subagents/agents/sessions/worktrees, delegate parts of a task to other agents, work on several things at once, build something using multiple Claude (or other agent) sessions, collect or synthesize the results of agents you opened, organize the canvas into groups by topic, move tasks across a kanban board, or visualize code/output you produced. Only works inside a nodeterm agent session.
---
# Manage the nodeterm canvas
@@ -422,14 +428,14 @@ Verbs:
- \`list\` — list current nodes (id, kind, title). Start here when you need a node id.
- \`open-terminal [--count N] [--cwd P] [--cmd C] [--group <id>] [--after <id,id>]\` — open N plain terminals (default 1).
- \`open-claude [--count N] [--cwd P] [--prompt T] [--group <id>] [--after <id,id>]\` — open N Claude sessions (default 1).
-- \`open-agent --agent claude|codex|gemini|opencode|<custom-id> [--count N] [--cwd P] [--prompt T] [--group <id>] [--after <id,id>]\` — open N sessions of any agent CLI.
+- \`open-agent --agent ${agentChoices} [--count N] [--cwd P] [--prompt T] [--group <id>] [--after <id,id>]\` — open N sessions of any agent CLI.
\`--group\` parents the node(s) into an existing group frame; a worktree-bound group also
hands its worktree path down as the cwd.
\`--after <id,id>\` opens the node **armed**: it does NOT start yet, and launches itself once
every listed station has gone idle — that is how you express "B needs what A produces" without
sitting in a poll loop. The armed node is also context-linked to each station it waits on, so
it can read their work the moment it wakes. Only agent nodes that report status
- (claude/codex/gemini) can be waited on — waiting on a plain terminal is refused, because a
+ (${statusAgents}, or custom agents based on them) can be waited on — waiting on a plain terminal is refused, because a
plain terminal never reports finishing and the node would hang forever. Note the semantics:
"idle" is the end of a station's TURN, not proof its whole job is done — right for a station
given one self-contained prompt, wrong if you expect a long conversation first.
@@ -523,7 +529,7 @@ Typical requests this skill covers:
workstreams, then either one \`spawn-team\` per subject (each team is already a labeled
group), or \`open-claude\`/\`open-agent\` per node followed by \`group --nodes ... --label\`
per subject and \`arrange\` inside each.
-- "Open a codex/gemini session" → \`open-agent --agent codex|gemini\`.
+- "Open a Codex/Gemini/Copilot session" → \`open-agent --agent codex|gemini|copilot\`.
- "Tidy up / group my terminals" → \`list\`, then \`group --nodes …\`, then \`arrange --nodes <those same ids>\`
to tidy the new frame's contents (grouping keeps each node's scattered spot, so arrange after grouping).
- "Move this node into that group" → \`move --nodes <id> --group <targetGroupId>\` (not \`group\`, which only
diff --git a/src/main/canvas-control.ts b/src/main/canvas-control.ts
index 09685b209..c00e2acaa 100644
--- a/src/main/canvas-control.ts
+++ b/src/main/canvas-control.ts
@@ -17,6 +17,7 @@ import {
mergeCanvasControlBlock
} from './canvas-control-core'
import { opencodeConfigDir } from '../core/agents/hooks/opencode'
+import { copilotHomeDir } from '../core/agents/hooks/copilot'
function dir(): string {
return path.join(app.getPath('userData'), 'canvas-control')
@@ -65,7 +66,7 @@ export function installCanvasSkillInto(configDir: string): void {
}
}
-// Codex/Gemini/opencode have no skill system — merge the canvas-control block into their global
+// Codex/Gemini/Copilot/opencode use global instruction files here — merge the canvas-control block
// instruction files (marker-delimited, idempotent, other content preserved). Same pattern
// as context-link's get-linked-context block. The CLI env-gate keeps the block inert in
// the user's normal (non-nodeterm) codex/gemini/opencode sessions.
@@ -74,6 +75,7 @@ function installAgentInstructions(): void {
const targets = [
path.join(os.homedir(), '.codex', 'AGENTS.md'),
path.join(os.homedir(), '.gemini', 'GEMINI.md'),
+ path.join(copilotHomeDir(), 'copilot-instructions.md'),
path.join(opencodeConfigDir(), 'AGENTS.md')
]
for (const p of targets) {
diff --git a/src/main/remote-ssh/remote-hooks.test.ts b/src/main/remote-ssh/remote-hooks.test.ts
index 8af66d9df..81cd5a8a7 100644
--- a/src/main/remote-ssh/remote-hooks.test.ts
+++ b/src/main/remote-ssh/remote-hooks.test.ts
@@ -395,6 +395,48 @@ describe('RemoteHooks.setup — grok', () => {
})
})
+describe('RemoteHooks.setup — copilot', () => {
+ it('writes Copilot\'s native hook config under the host COPILOT_HOME', async () => {
+ const { rh, conn, runs } = harness({
+ responses: { '$HOME': '/home/dev', COPILOT_HOME: '/opt/copilot-home' }
+ })
+ await rh.setup('p1', conn, '/s.sock', { port: 1234, token: 't', version: '1' })
+ const write = runs.find(
+ (r) => r.cmd.includes('/opt/copilot-home/hooks/nodeterm-status.json') && r.stdin
+ )
+ expect(write).toBeTruthy()
+ const cfg = JSON.parse(write!.stdin!)
+ expect(cfg.version).toBe(1)
+ expect(cfg.hooks.SessionStart[0]).toEqual({
+ type: 'command',
+ bash: expect.stringContaining('/home/dev/.nodeterm/agent-hooks/copilot.sh'),
+ timeoutSec: 5
+ })
+ expect(runs.find((r) => r.cmd.includes('agent-hooks/copilot.sh'))?.stdin).toContain(
+ '/hook/copilot'
+ )
+ expect(runs.some((r) => r.cmd.includes('/home/dev/.copilot'))).toBe(false)
+ })
+
+ it('falls back to $HOME/.copilot for an unsafe host override', async () => {
+ const { rh, conn, runs } = harness({
+ responses: { '$HOME': '/home/dev', COPILOT_HOME: 'relative/copilot' }
+ })
+ await rh.setup('p1', conn, '/s.sock', { port: 1234, token: 't', version: '1' })
+ expect(
+ runs.some((r) => r.cmd.includes('/home/dev/.copilot/hooks/nodeterm-status.json'))
+ ).toBe(true)
+ expect(runs.some((r) => r.cmd.includes('relative/copilot/hooks'))).toBe(false)
+ })
+
+ it('fails open when the Copilot hook write fails', async () => {
+ const { rh, conn } = harness({ failOn: '.copilot/hooks/nodeterm-status.json' })
+ await expect(
+ rh.setup('p1', conn, '/s.sock', { port: 1234, token: 't', version: '1' })
+ ).resolves.toBeTruthy()
+ })
+})
+
describe('RemoteHooks.ensureFullscreenTui', () => {
// Paths are posixQuote'd (single-quoted) in the remote commands; a read is `cat '<path>' …`
// and a write is `… cat > '<path>'`, so we distinguish them by the presence of `cat >`.
@@ -462,7 +504,7 @@ describe('RemoteHooks.teardown', () => {
describe('RemoteHooks.installCanvasControl', () => {
const isWriteTo = (args: string[], p: string) => args.join(' ').includes('cat > ') && args.join(' ').includes(p)
- it('writes an executable shim + the skill, and merges the codex/gemini/opencode blocks', async () => {
+ it('writes an executable shim + the skill, and merges every instruction-file block', async () => {
const { rh, calls } = harness()
await rh.installCanvasControl(conn, '/s.sock', '/home/u')
const joined = calls.map((c) => c.args.join(' '))
@@ -487,6 +529,7 @@ describe('RemoteHooks.installCanvasControl', () => {
// double-quoted expansion (see "the opencode XDG path expression" below).
expect(joined.some((j) => j.includes(`NT_H='/home/u'`))).toBe(true)
expect(joined.some((j) => j.includes('${XDG_CONFIG_HOME:-$NT_H/.config}/opencode/AGENTS.md'))).toBe(true)
+ expect(joined.some((j) => j.includes('/home/u/.copilot/copilot-instructions.md'))).toBe(true)
expect(calls.some((c) => (c.stdin ?? '').includes('nodeterm:manage-canvas:start'))).toBe(true)
// no unexpanded tilde survives in any remote path.
expect(joined.some((j) => j.includes('~/'))).toBe(false)
diff --git a/src/main/remote-ssh/remote-hooks.ts b/src/main/remote-ssh/remote-hooks.ts
index faef0cafc..6792dd4d5 100644
--- a/src/main/remote-ssh/remote-hooks.ts
+++ b/src/main/remote-ssh/remote-hooks.ts
@@ -12,6 +12,11 @@ import { isSafeNodeId, isSafeRemoteHome } from '../../core/remote-safety'
import { hookServer } from '../../core/agents/hook-server'
import { curlHeaderConfigLine } from '../../core/agents/hook-curl-config-sh'
import { buildManagedScript } from '../../core/agents/hooks/managed-script'
+import {
+ buildCopilotHookConfig,
+ COPILOT_HOOK_FILE,
+ isSafeRemoteCopilotHome
+} from '../../core/agents/hooks/copilot'
/**
* Remote hook scripts get NO Codex thread-identity root.
@@ -215,6 +220,8 @@ export class RemoteHooks {
await this.installCodexRemote(conn, controlPath, home, remoteDir)
// 5. grok: our own file in its hooks DIRECTORY, under the HOST's $GROK_HOME.
await this.installGrokRemote(conn, controlPath, home, remoteDir)
+ // 6. copilot: its own file/grammar under the HOST's $COPILOT_HOME hooks directory.
+ await this.installCopilotRemote(conn, controlPath, home, remoteDir)
return { endpointPath: endpoint }
} catch {
return null // fail-open: agent runs without hooks
@@ -489,6 +496,51 @@ export class RemoteHooks {
}
}
+ /** Install Copilot's owned hook file using the same config builder as the local installer. */
+ private async installCopilotRemote(
+ conn: SshConnection,
+ controlPath: string,
+ home: string,
+ remoteDir: string
+ ): Promise<void> {
+ try {
+ const copilotHome = await this.resolveCopilotHome(conn, controlPath, home)
+ const config = `${copilotHome.replace(/\/$/, '')}/hooks/${COPILOT_HOOK_FILE}`
+ const script = `${remoteDir}/agent-hooks/copilot.sh`
+ await this.r.run(
+ childArgs(
+ conn,
+ controlPath,
+ `mkdir -p ${posixQuote(`${remoteDir}/agent-hooks`)} && cat > ${posixQuote(script)} && chmod 755 ${posixQuote(script)}`
+ ),
+ buildManagedScript('copilot', REMOTE_IDENTITY_ROOT)
+ )
+ await this.r.run(
+ childArgs(
+ conn,
+ controlPath,
+ `mkdir -p "$(dirname ${posixQuote(config)})" && cat > ${posixQuote(config)}`
+ ),
+ `${JSON.stringify(buildCopilotHookConfig(buildManagedHookCommand(script)), null, 2)}\n`
+ )
+ } catch {
+ /* fail-open: the remote copilot session simply runs without status hooks */
+ }
+ }
+
+ private async resolveCopilotHome(
+ conn: SshConnection,
+ controlPath: string,
+ home: string
+ ): Promise<string> {
+ const { stdout } = await this.r.run(
+ childArgs(conn, controlPath, 'printf %s "${COPILOT_HOME:-}"')
+ )
+ const reported = stdout.trim()
+ const stripped = reported.replace(/\/+$/, '') || '/'
+ return isSafeRemoteCopilotHome(reported) ? stripped : `${home}/.copilot`
+ }
+
/**
* Merge the managed claude hook into a REMOTE managed-account config dir's `settings.json`, so an
* agent that runs under `CLAUDE_CONFIG_DIR=<accountDir>` reports status like the default
@@ -570,6 +622,11 @@ export class RemoteHooks {
const targets: { pathExpr: string; prelude?: string }[] = [
{ pathExpr: posixQuote(`${remoteHome}/.codex/AGENTS.md`) },
{ pathExpr: posixQuote(`${remoteHome}/.gemini/GEMINI.md`) },
+ {
+ pathExpr: posixQuote(
+ `${await this.resolveCopilotHome(conn, controlPath, remoteHome)}/copilot-instructions.md`
+ )
+ },
openCodeInstructionsTarget(remoteHome)
]
for (const t of targets) {
diff --git a/src/renderer/assets/copilot.svg b/src/renderer/assets/copilot.svg
new file mode 100644
index 000000000..f145e3992
--- /dev/null
+++ b/src/renderer/assets/copilot.svg
@@ -0,0 +1,4 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
+ <path fill="#f0f6fc" d="M23.922 16.992c-.861 1.495-5.859 5.023-11.922 5.023-6.063 0-11.061-3.528-11.922-5.023A.641.641 0 0 1 0 16.736v-2.869a.841.841 0 0 1 .053-.22c.372-.935 1.347-2.292 2.605-2.656.167-.429.414-1.055.644-1.517a10.195 10.195 0 0 1-.052-1.086c0-1.331.282-2.499 1.132-3.368.397-.406.89-.717 1.474-.952 1.399-1.136 3.392-2.093 6.122-2.093 2.731 0 4.767.957 6.166 2.093.584.235 1.077.546 1.474.952.85.869 1.132 2.037 1.132 3.368 0 .368-.014.733-.052 1.086.23.462.477 1.088.644 1.517 1.258.364 2.233 1.721 2.605 2.656a.832.832 0 0 1 .053.22v2.869a.641.641 0 0 1-.078.256ZM12.172 11h-.344a4.323 4.323 0 0 1-.355.508C10.703 12.455 9.555 13 7.965 13c-1.725 0-2.989-.359-3.782-1.259a2.005 2.005 0 0 1-.085-.104L4 11.741v6.585c1.435.779 4.514 2.179 8 2.179 3.486 0 6.565-1.4 8-2.179v-6.585l-.098-.104s-.033.045-.085.104c-.793.9-2.057 1.259-3.782 1.259-1.59 0-2.738-.545-3.508-1.492a4.323 4.323 0 0 1-.355-.508h-.016.016Zm.641-2.935c.136 1.057.403 1.913.878 2.497.442.544 1.134.938 2.344.938 1.573 0 2.292-.337 2.657-.751.384-.435.558-1.15.558-2.361 0-1.14-.243-1.847-.705-2.319-.477-.488-1.319-.862-2.824-1.025-1.487-.161-2.192.138-2.533.529-.269.307-.437.808-.438 1.578v.021c0 .265.021.562.063.893Zm-1.626 0c.042-.331.063-.628.063-.894v-.02c-.001-.77-.169-1.271-.438-1.578-.341-.391-1.046-.69-2.533-.529-1.505.163-2.347.537-2.824 1.025-.462.472-.705 1.179-.705 2.319 0 1.211.175 1.926.558 2.361.365.414 1.084.751 2.657.751 1.21 0 1.902-.394 2.344-.938.475-.584.742-1.44.878-2.497Z"/>
+ <path fill="#f0f6fc" d="M14.5 14.25a1 1 0 0 1 1 1v2a1 1 0 0 1-2 0v-2a1 1 0 0 1 1-1Zm-5 0a1 1 0 0 1 1 1v2a1 1 0 0 1-2 0v-2a1 1 0 0 1 1-1Z"/>
+</svg>
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index 32f8d7d49..18a9182ac 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -203,6 +203,7 @@ import {
guardConcurrentRestart,
planBulkRestart,
restartEligibility,
+ restartSessionId,
settleRestart,
summarizeBulkRestart,
type BulkRestartPlan,
@@ -5372,7 +5373,8 @@ export function Canvas() {
const n = nodesRef.current.find((x) => x.id === ids[0])
const st = useAgentStatus.getState().byId[ids[0]]
const sourceAgentId = restartAgentIdOf(n)
- const gate = restartEligibility(sourceAgentId, st?.state, st?.sessionId)
+ const sessionId = restartSessionId(st?.sessionId, n?.data.agentSessionId)
+ const gate = restartEligibility(sourceAgentId, st?.state, sessionId)
const settings = useSettings.getState().settings
const variants = sourceAgentId
? reopenVariants(sourceAgentId, settings.customAgents, settings.disabledAgents)
@@ -6490,7 +6492,7 @@ export function Canvas() {
if (!depAgent || !hasHooks(depAgent)) {
reply({
ok: false,
- error: `${verb}: --after ${depId} is not an agent session that reports when it is done — only claude/codex/gemini nodes can be waited on`
+ error: `${verb}: --after ${depId} is not an agent session that reports when it is done`
})
return null
}
@@ -6610,8 +6612,8 @@ export function Canvas() {
}
case 'open-claude':
case 'open-agent': {
- // open-claude is the legacy fixed-agent form; open-agent takes any builtin
- // (claude/codex/gemini) or custom agent id — resolveAgent falls back for the rest.
+ // open-claude is the legacy fixed-agent form; open-agent takes any builtin or custom
+ // agent id — resolveAgent is the single registry/base-harness resolver for both.
const agentId = (verb === 'open-agent' ? args.agent : 'claude') as AgentId
const count = Math.max(1, Math.min(5, parseInt(args.count || '1', 10) || 1))
// --group parents the new node(s) into an existing group frame; a worktree-bound
diff --git a/src/renderer/components/onboarding/OnboardingFlow.tsx b/src/renderer/components/onboarding/OnboardingFlow.tsx
index 7065cd663..bb6e88ffe 100644
--- a/src/renderer/components/onboarding/OnboardingFlow.tsx
+++ b/src/renderer/components/onboarding/OnboardingFlow.tsx
@@ -190,7 +190,10 @@ export function OnboardingFlow({ onClose }: { onClose: () => void }) {
<circle cx="12" cy="12" r="3" />
<path d="M12 2v4M12 18v4M2 12h4M18 12h4" />
</svg>
- <span>AI agents are first-class nodes — Claude, Codex, Gemini, opencode</span>
+ <span>
+ AI agents are first-class nodes —{' '}
+ {BUILTIN_AGENT_IDS.map((id) => AGENT_CONFIG[id].label).join(', ')}
+ </span>
</div>
<div className="onb-prop">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">
diff --git a/src/renderer/components/settings/sections/CustomAgentsSection.tsx b/src/renderer/components/settings/sections/CustomAgentsSection.tsx
index 698319c78..98a177cfb 100644
--- a/src/renderer/components/settings/sections/CustomAgentsSection.tsx
+++ b/src/renderer/components/settings/sections/CustomAgentsSection.tsx
@@ -24,7 +24,12 @@ const ROWS = {
}
const ENTRIES = Object.values(ROWS)
-const INJECTION_MODES: PromptInjectionMode[] = ['argv', 'flag-prompt', 'stdin-after-start']
+const INJECTION_MODES: PromptInjectionMode[] = [
+ 'argv',
+ 'flag-prompt',
+ 'flag-interactive',
+ 'stdin-after-start'
+]
export function CustomAgentsSection({ isActive }: { isActive: boolean }): React.JSX.Element {
const customAgents = useSettings((s) => s.settings.customAgents)
diff --git a/src/renderer/components/settings/sections/ProCompare.tsx b/src/renderer/components/settings/sections/ProCompare.tsx
index 1b182a84a..09bf80d87 100644
--- a/src/renderer/components/settings/sections/ProCompare.tsx
+++ b/src/renderer/components/settings/sections/ProCompare.tsx
@@ -1,8 +1,10 @@
+import { AGENT_CONFIG, BUILTIN_AGENT_IDS } from '@shared/agents/config'
+
const CORE = [
'Unlimited local terminals & canvas',
'Unlimited SSH projects',
'Groups, worktrees, git & diff',
- 'Agent nodes (Claude / Codex / Gemini)',
+ `Agent nodes (${BUILTIN_AGENT_IDS.map((id) => AGENT_CONFIG[id].label).join(' / ')})`,
'QR phone pairing on your LAN',
'Remote access from your phone (relay, E2E encrypted)'
]
diff --git a/src/renderer/hud/main.ts b/src/renderer/hud/main.ts
index 7cac160f9..613fbf887 100644
--- a/src/renderer/hud/main.ts
+++ b/src/renderer/hud/main.ts
@@ -161,7 +161,7 @@ function codexMascot(): HTMLElement {
el.style.backgroundImage = `url(${codexPet})`
return el
}
-/** An asset brand mark (gemini/opencode), breathing: a background-image span. These marks carry their
+/** An asset brand mark (gemini/opencode/copilot), breathing: a background-image span. These marks carry their
* own fills, so unlike grok's they cannot be drawn as an inline `currentColor` path — the bloom is
* the strip's label colour rather than their own ink (see lib/brandPulse.ts). */
function brandPulseMascot(src: string, size: number): HTMLElement {
@@ -179,7 +179,7 @@ function brandPulseMascot(src: string, size: number): HTMLElement {
function workingMascot(agentId?: string): Element {
if (agentId === 'claude' && CLAUDE_MASCOT.src) return quadrantMascot(CLAUDE_MASCOT, 'claude')
if (agentId === 'codex') return codexMascot()
- // grok, gemini and opencode breathe their own brand mark instead of walking a critter — the SAME
+ // grok, gemini, opencode and copilot breathe their own brand mark instead of walking a critter — the SAME
// decision the canvas badge makes (lib/brandPulse.ts, shared precisely so one agent is never two
// different things on two surfaces). This renderer stays React-free, so it draws the plan itself.
const plan = brandPulsePlan(agentId, HUD_QUADRANT_H)
diff --git a/src/renderer/lib/agentIcons.test.tsx b/src/renderer/lib/agentIcons.test.tsx
index 54bd1a838..d41827e04 100644
--- a/src/renderer/lib/agentIcons.test.tsx
+++ b/src/renderer/lib/agentIcons.test.tsx
@@ -1,6 +1,7 @@
import { afterEach, describe, expect, it } from 'vitest'
import { renderToStaticMarkup } from 'react-dom/server'
import {
+ BUILTIN_AGENT_IDS,
setCustomAgentBaseResolver,
type AgentId,
type BuiltinAgentId
@@ -14,7 +15,7 @@ afterEach(() => setCustomAgentBaseResolver(null))
describe('AgentIcon custom-agent inheritance', () => {
it('renders the exact base harness icon for inheriting custom agents', () => {
- const bases: BuiltinAgentId[] = ['claude', 'codex', 'gemini', 'opencode', 'grok']
+ const bases: BuiltinAgentId[] = [...BUILTIN_AGENT_IDS]
setCustomAgentBaseResolver((id) => {
const base = id.startsWith('custom:') ? id.slice('custom:'.length) : ''
return bases.includes(base as BuiltinAgentId) ? (base as BuiltinAgentId) : undefined
diff --git a/src/renderer/lib/brandPulse.test.tsx b/src/renderer/lib/brandPulse.test.tsx
index e07116666..5465dad01 100644
--- a/src/renderer/lib/brandPulse.test.tsx
+++ b/src/renderer/lib/brandPulse.test.tsx
@@ -25,8 +25,8 @@ import { BrandPulse } from './agentIcons'
* both surfaces at once; the two thin renderers on top of it are checked separately below.
*/
describe('brandPulsePlan', () => {
- it('gives gemini and opencode their own asset mark', () => {
- for (const agentId of ['gemini', 'opencode'] as const) {
+ it('gives mascot-less asset agents their own mark', () => {
+ for (const agentId of ['gemini', 'opencode', 'copilot'] as const) {
const plan = brandPulsePlan(agentId, 16)
expect(plan, agentId).toEqual({ kind: 'asset', src: expect.any(String), size: 16 })
// A real, non-empty URL — an asset import that silently resolved to '' would render an
@@ -59,7 +59,7 @@ describe('brandPulseBackground', () => {
// marks (backgroundImage came back ''), because Vite inlines them as data URIs carrying literal
// `'` and, for three of them, literal `(`/`)`. The notch strip would have shown an empty box.
it('survives a real CSS parser for every mark', () => {
- for (const agentId of ['claude', 'codex', 'gemini', 'opencode'] as const) {
+ for (const agentId of ['claude', 'codex', 'gemini', 'opencode', 'copilot'] as const) {
const plan = brandPulsePlan(agentId, 13)
const src = plan?.kind === 'asset' ? plan.src : ''
const el = document.createElement('span')
@@ -84,8 +84,8 @@ describe('hasBrandLogo', () => {
expect(hasBrandLogo('grok')).toBe(true)
})
- it('counts the four asset marks and nothing else', () => {
- for (const agentId of ['claude', 'codex', 'gemini', 'opencode'] as const) {
+ it('counts every asset mark and nothing else', () => {
+ for (const agentId of ['claude', 'codex', 'gemini', 'opencode', 'copilot'] as const) {
expect(hasBrandLogo(agentId), agentId).toBe(true)
}
expect(hasBrandLogo('custom:abc')).toBe(false)
diff --git a/src/renderer/lib/brandPulse.ts b/src/renderer/lib/brandPulse.ts
index 03007e88a..d107bdb40 100644
--- a/src/renderer/lib/brandPulse.ts
+++ b/src/renderer/lib/brandPulse.ts
@@ -11,11 +11,12 @@ import claudeIcon from '../assets/claude.svg'
import codexIcon from '../assets/codex-color.svg'
import geminiIcon from '../assets/gemini-color.svg'
import opencodeIcon from '../assets/opencode.svg'
+import copilotIcon from '../assets/copilot.svg'
// Brand logo per builtin agent; custom/unknown agents have none (callers fall back to the terminal
// glyph, or to the plain pulsing dot).
//
-// These four are MULTI-COLOUR marks, so each carries its own fills and is loaded as an `<img src>` /
+// These asset marks carry their own fills and are loaded as an `<img src>` /
// `background-image` (Vite hands us a URL). An SVG loaded that way is an isolated document —
// `currentColor` has nothing to inherit there, which is why none of these assets uses it. Grok is
// the exception: its mark is monochrome, so it is inlined from lib/grokMark.ts instead, and is
@@ -24,7 +25,8 @@ export const AGENT_LOGO: Partial<Record<string, string>> = {
claude: claudeIcon,
codex: codexIcon,
gemini: geminiIcon,
- opencode: opencodeIcon
+ opencode: opencodeIcon,
+ copilot: copilotIcon
}
/**
diff --git a/src/renderer/nodes/AgentMascot.tsx b/src/renderer/nodes/AgentMascot.tsx
index f5f506fcb..ec830fa7f 100644
--- a/src/renderer/nodes/AgentMascot.tsx
+++ b/src/renderer/nodes/AgentMascot.tsx
@@ -12,7 +12,7 @@ const BRAND_BADGE_SIZE = 16
* - claude → the runtime-drawn coral pixel critter (data-URI spritesheet; the walk is CSS
* `steps(1)` over three keyframes, NOT `steps(2)` — see .term-node__mascot--claude).
* - codex → pet-codex.webp, first-row walk cycle (CSS `steps(8)`).
- * - grok / gemini / opencode → their own BRAND MARK, pulsing and blooming rather than walking. Grok
+ * - grok / gemini / opencode / copilot → their own BRAND MARK, pulsing and blooming rather than walking. Grok
* had a quadrant critter first; a hand-drawn creature next to two real mascots read as neither, so
* the glyph the agent actually has is what animates. gemini and opencode used to fall through to
* the plain dot, which says "something is happening" but not WHO. The decision and the bloom's
diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsx
index 0c5acdf11..cde5e94cd 100644
--- a/src/renderer/nodes/TerminalNode.tsx
+++ b/src/renderer/nodes/TerminalNode.tsx
@@ -111,6 +111,7 @@ import {
registerAgentHibernate,
registerAgentRestart,
restartEligibility,
+ restartSessionId,
RESTART_EXIT_TIMEOUT_MS,
type ExitPhaseOutcome,
type ResumePhaseOutcome
@@ -2857,12 +2858,13 @@ export function TerminalNode({
id,
guardConcurrentRestart(id, async (targetAgentId?: AgentId, targetModel?: string, restartShell?: boolean) => {
const st = useAgentStatus.getState().byId[id]
- const agentSessionId = st?.sessionId
+ const currentNode = getNode(id)
+ const agentSessionId = restartSessionId(st?.sessionId, currentNode?.data.agentSessionId)
// `data.agentId` can change after a successful same-base swap while this deliberately
// long-lived terminal effect stays mounted. Read the node NOW instead of trusting the
// value captured when the pane attached, or a later plain Restart would silently reopen
// the old agent again.
- const sourceAgentId = createdAgentId(getNode(id)?.data)
+ const sourceAgentId = createdAgentId(currentNode?.data)
const gate = restartEligibility(sourceAgentId, st?.state, agentSessionId)
if (!gate.ok || !sourceAgentId || !agentSessionId || !restartTarget())
return 'not-eligible'
diff --git a/src/renderer/state/workspace.session-id.test.ts b/src/renderer/state/workspace.session-id.test.ts
index 6b501b7cf..d60057047 100644
--- a/src/renderer/state/workspace.session-id.test.ts
+++ b/src/renderer/state/workspace.session-id.test.ts
@@ -26,7 +26,7 @@ describe('createAgentNode mints a session id when the CLI accepts one', () => {
expect(a.data.agentSessionId).not.toBe(b.data.agentSessionId)
})
- // Only claude accepts a caller-chosen id. For every other agent the command line must stay
+ // Claude and Copilot accept a caller-chosen id. For every other agent the command line must stay
// exactly what it was, or an unknown flag kills the launch.
it('leaves non-capable agents unstamped and their command unchanged', () => {
for (const id of ['codex', 'gemini', 'grok', 'opencode'] as const) {
@@ -36,6 +36,13 @@ describe('createAgentNode mints a session id when the CLI accepts one', () => {
}
})
+ it('mints Copilot ids without borrowing the Claude CLI probe', () => {
+ resetClaudeCliCapsForTests()
+ const n = createAgentNode('copilot', 0)
+ expect(n.data.agentSessionId).toMatch(UUID_RE)
+ expect(n.data.initialCommand).toContain(`--session-id=${n.data.agentSessionId}`)
+ })
+
it('still carries the prompt alongside the flag', () => {
const n = createAgentNode('claude', 0, undefined, undefined, 'fix the bug')
expect(n.data.initialCommand).toContain('fix the bug')
diff --git a/src/renderer/state/workspace.test.ts b/src/renderer/state/workspace.test.ts
index 131253404..11b13d31a 100644
--- a/src/renderer/state/workspace.test.ts
+++ b/src/renderer/state/workspace.test.ts
@@ -769,6 +769,12 @@ describe('createAgentNode prompt injection', () => {
const n = createAgentNode('opencode', 0, undefined, undefined, "rerank the results")
expect(n.data.initialCommand).toBe("opencode --prompt 'rerank the results'")
})
+ it('uses --interactive for Copilot so the prompted session stays open', () => {
+ const n = createAgentNode('copilot', 0, undefined, undefined, 'fix the bug')
+ expect(n.data.initialCommand).toContain("copilot --interactive 'fix the bug'")
+ expect(n.data.initialCommand).toContain('--session-id=')
+ expect(n.data.initialCommand).not.toContain('--prompt')
+ })
it('shell-quotes a flag-prompt safely', () => {
const n = createAgentNode('opencode', 0, undefined, undefined, "it's tricky")
expect(n.data.initialCommand).toBe("opencode --prompt 'it'\\''s tricky'")
diff --git a/src/renderer/state/workspace.ts b/src/renderer/state/workspace.ts
index 989e01835..5a0685db9 100644
--- a/src/renderer/state/workspace.ts
+++ b/src/renderer/state/workspace.ts
@@ -1,7 +1,7 @@
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, mintsSessionId } from '@shared/agents/config'
+import { agentConfig, supportsSessionIdFlag } from '@shared/agents/config'
import { assembleLaunchCommand } from '@shared/agents/launch'
import { uuid } from '@renderer/lib/uuid'
import { claudeCliCapsNow } from './permissionMode'
@@ -375,7 +375,8 @@ export function createAgentNode(
// 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
+ const sessionIdFlagSupported = supportsSessionIdFlag(agentId, cliCaps.sessionIdFlag)
+ const mintedSessionId = sessionIdFlagSupported ? uuid() : undefined
// Command assembly is delegated to the ONE shared builder (src/shared/agents/launch.ts), used by
// fresh launch AND cold-restore resume, so a custom agent's baseAgent/args/expansion are applied
// identically in both paths. The renderer has no process.env, so expansion here runs against an
@@ -394,7 +395,7 @@ export function createAgentNode(
initialPrompt,
permissionMode,
sessionId: mintedSessionId,
- sessionIdFlagSupported: cliCaps.sessionIdFlag,
+ sessionIdFlagSupported,
// 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).
diff --git a/src/renderer/terminal/agent-restart.test.ts b/src/renderer/terminal/agent-restart.test.ts
index b643350be..95261d74f 100644
--- a/src/renderer/terminal/agent-restart.test.ts
+++ b/src/renderer/terminal/agent-restart.test.ts
@@ -16,6 +16,7 @@ import {
registerAgentHibernate,
registerAgentRestart,
restartEligibility,
+ restartSessionId,
settleRestart,
summarizeBulkRestart,
summarizeOutcomes,
@@ -26,7 +27,7 @@ import {
} from './agent-restart'
describe('exitSequence', () => {
- it('knows claude, codex, grok and gemini, refuses others', () => {
+ it('knows the documented exit command for each restartable harness', () => {
expect(exitSequence('claude')).toBe('/exit')
expect(exitSequence('codex')).toBe('/quit')
// grok's documented primary is `/quit` (`/exit` is its alias).
@@ -35,12 +36,21 @@ describe('exitSequence', () => {
// permanently delete the session history we are about to `--resume` into.
expect(exitSequence('gemini')).toBe('/quit')
expect(exitSequence('gemini')).not.toContain('--delete')
+ expect(exitSequence('copilot')).toBe('/exit')
// opencode is resumable but we know no way to ask it to quit, so it is still not a target.
expect(exitSequence('opencode')).toBeNull()
expect(exitSequence('my-custom')).toBeNull()
})
})
+describe('restartSessionId', () => {
+ it('prefers a live hook id and falls back to the persisted minted id', () => {
+ expect(restartSessionId('live-id', 'minted-id')).toBe('live-id')
+ expect(restartSessionId(undefined, ' minted-id ')).toBe('minted-id')
+ expect(restartSessionId('', null)).toBeUndefined()
+ })
+})
+
describe('isShellCommand', () => {
it('matches plain, login-dash and path-prefixed shells', () => {
for (const c of ['zsh', 'bash', 'sh', 'fish', '-zsh', '/bin/bash', '/usr/local/bin/fish'])
@@ -56,6 +66,7 @@ describe('restartEligibility', () => {
it('ok for a resumable agent with a session id in a non-working state', () => {
expect(restartEligibility('claude', 'waiting', 'abc-123')).toEqual({ ok: true })
expect(restartEligibility('codex', 'done', 'abc-123')).toEqual({ ok: true })
+ expect(restartEligibility('copilot', undefined, 'abc-123')).toEqual({ ok: true })
})
it('treats a blocked (permission prompt) session as busy — /exit would answer the prompt', () => {
expect(restartEligibility('claude', 'blocked', 'abc')).toEqual({ ok: false, reason: 'working' })
diff --git a/src/renderer/terminal/agent-restart.ts b/src/renderer/terminal/agent-restart.ts
index 7cc61ab35..1970d4fa5 100644
--- a/src/renderer/terminal/agent-restart.ts
+++ b/src/renderer/terminal/agent-restart.ts
@@ -38,7 +38,8 @@ const EXIT_SEQUENCES: Record<string, string> = {
claude: '/exit',
codex: '/quit',
grok: '/quit',
- gemini: '/quit'
+ gemini: '/quit',
+ copilot: '/exit'
}
export function exitSequence(agentId: string): string | null {
@@ -81,6 +82,18 @@ export function restartEligibility(
return { ok: true }
}
+/**
+ * Prefer the live hook-reported id, then the caller-chosen id persisted on the node. Copilot and
+ * modern Claude can start with a minted id before their first hook lands; making each menu/closure
+ * rediscover this fallback separately would make one of them offer a restart that the other
+ * refuses. `restartEligibility` remains the interpolation guard for the chosen value.
+ */
+export function restartSessionId(live: unknown, persisted: unknown): string | undefined {
+ if (typeof live === 'string' && live.trim()) return live.trim()
+ if (typeof persisted === 'string' && persisted.trim()) return persisted.trim()
+ return undefined
+}
+
export type RestartOutcome = 'restarted' | 'exit-timeout' | 'not-eligible'
export const RESTART_EXIT_TIMEOUT_MS = 6000
diff --git a/src/shared/agents/config.capabilities.test.ts b/src/shared/agents/config.capabilities.test.ts
index 61c021a5b..6ad042df9 100644
--- a/src/shared/agents/config.capabilities.test.ts
+++ b/src/shared/agents/config.capabilities.test.ts
@@ -39,12 +39,47 @@ describe('MODEL_SWITCH_CAPABLE', () => {
it('is centralized on the base harness capability', () => {
expect(canSwitchModel('claude')).toBe(true)
expect(canSwitchModel('codex')).toBe(true)
+ expect(canSwitchModel('copilot')).toBe(true)
for (const id of ['gemini', 'opencode', 'grok', 'custom:plain'] as const) {
expect(canSwitchModel(id), id).toBe(false)
}
})
})
+describe('copilot capabilities', () => {
+ it('is a builtin with measured interactive launch, hooks, resume, and model switching', () => {
+ expect(BUILTIN_AGENT_IDS).toContain('copilot')
+ expect(AGENT_CONFIG.copilot).toEqual({
+ label: 'GitHub Copilot',
+ color: '#8957e5',
+ launchCmd: 'copilot',
+ promptInjectionMode: 'flag-interactive',
+ expectedProcess: 'copilot'
+ })
+ expect(hasHooks('copilot')).toBe(true)
+ expect(canResume('copilot')).toBe(true)
+ expect(canControlCanvas('copilot')).toBe(true)
+ expect(canSwitchModel('copilot')).toBe(true)
+ })
+
+ it('does not claim integrations whose Copilot-specific leaf is not implemented', () => {
+ for (const can of [
+ canContextLink,
+ canSubagent,
+ canRecur,
+ canBranch,
+ hasUsage,
+ canChat,
+ canTransferFrom,
+ canRename,
+ canReadTitle,
+ hasPermissionMode
+ ]) {
+ expect(can('copilot')).toBe(false)
+ }
+ })
+})
+
describe('opencode capabilities', () => {
it('is a builtin with the parity capability set', () => {
expect(BUILTIN_AGENT_IDS).toContain('opencode')
@@ -159,7 +194,8 @@ describe('copy feedback', () => {
it('speaks for every agent that says nothing itself', () => {
// codex leaves the mouse to tmux: the drag copies via OSC 52 and the highlight vanishes on
// release with no word from anyone. That silence is what the pill exists for.
- for (const id of ['codex', 'gemini', 'opencode', 'grok']) expect(reportsOwnCopy(id)).toBe(false)
+ for (const id of ['codex', 'gemini', 'opencode', 'grok', 'copilot'])
+ expect(reportsOwnCopy(id)).toBe(false)
})
it('speaks for a plain terminal and a custom agent (no agent id at all)', () => {
@@ -203,7 +239,7 @@ describe('title read vs rename write', () => {
it('only codex has a shared identity, and it is asked through the helper', () => {
expect(hasSharedIdentity('codex')).toBe(true)
- for (const id of ['claude', 'gemini', 'grok', 'opencode', 'custom:abc'] as const) {
+ for (const id of ['claude', 'gemini', 'grok', 'opencode', 'copilot', 'custom:abc'] as const) {
expect(hasSharedIdentity(id), id).toBe(false)
}
})
diff --git a/src/shared/agents/config.control.test.ts b/src/shared/agents/config.control.test.ts
index ad8009df1..42c36702e 100644
--- a/src/shared/agents/config.control.test.ts
+++ b/src/shared/agents/config.control.test.ts
@@ -1,11 +1,9 @@
import { describe, it, expect } from 'vitest'
-import { canControlCanvas } from './config'
+import { CANVAS_CONTROL_CAPABLE, canControlCanvas } from './config'
describe('canControlCanvas', () => {
- it('is true for the three builtins, not custom agents', () => {
- expect(canControlCanvas('claude')).toBe(true)
- expect(canControlCanvas('codex')).toBe(true)
- expect(canControlCanvas('gemini')).toBe(true)
+ it('is true for every declared builtin, not a vanilla custom agent', () => {
+ for (const id of CANVAS_CONTROL_CAPABLE) expect(canControlCanvas(id), id).toBe(true)
expect(canControlCanvas('custom:abc')).toBe(false)
})
diff --git a/src/shared/agents/config.ts b/src/shared/agents/config.ts
index b9d79a101..ee048094d 100644
--- a/src/shared/agents/config.ts
+++ b/src/shared/agents/config.ts
@@ -2,11 +2,15 @@
// Design: an open AgentId string, a declarative config record, and
// capabilities expressed as const membership lists (not a capability object).
-export type BuiltinAgentId = 'claude' | 'codex' | 'gemini' | 'opencode' | 'grok'
+export type BuiltinAgentId = 'claude' | 'codex' | 'gemini' | 'opencode' | 'grok' | 'copilot'
// Open type — custom agents are any string ('custom:<uuid>'). Never restrict the set.
export type AgentId = BuiltinAgentId | (string & {})
-export type PromptInjectionMode = 'argv' | 'flag-prompt' | 'stdin-after-start'
+export type PromptInjectionMode =
+ | 'argv'
+ | 'flag-prompt'
+ | 'flag-interactive'
+ | 'stdin-after-start'
export interface AgentConfig {
label: string // menu + node title, e.g. 'Claude Code'
@@ -35,7 +39,8 @@ export const BUILTIN_AGENT_IDS: readonly BuiltinAgentId[] = [
'codex',
'gemini',
'opencode',
- 'grok'
+ 'grok',
+ 'copilot'
]
export const AGENT_CONFIG: Record<BuiltinAgentId, AgentConfig> = {
@@ -82,15 +87,25 @@ export const AGENT_CONFIG: Record<BuiltinAgentId, AgentConfig> = {
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'
}
}
-// Capabilities = const membership lists. A custom agent is in no list, so it
-// automatically gets only spawn + terminal-title + process status.
-export const AGENT_HOOK_TARGETS = ['claude', 'codex', 'gemini', 'opencode', 'grok'] as const
-export const RESUMABLE_AGENTS = ['claude', 'codex', 'gemini', 'opencode', 'grok'] as const
-// Agents whose session id we MINT at launch (`--session-id <uuid>`) instead of learning it from
-// hook events. Claude only: it is the one CLI here that accepts a caller-chosen id.
+// 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.
+export const AGENT_HOOK_TARGETS = ['claude', 'codex', 'gemini', 'opencode', 'grok', 'copilot'] as const
+export const RESUMABLE_AGENTS = ['claude', 'codex', 'gemini', 'opencode', 'grok', 'copilot'] 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
@@ -105,7 +120,11 @@ export const RESUMABLE_AGENTS = ['claude', 'codex', 'gemini', 'opencode', 'grok'
// 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'] as const
+export const SESSION_ID_CAPABLE = ['claude', 'copilot'] 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.
+export const UNCONDITIONAL_SESSION_ID_CAPABLE = ['copilot'] as const
export const SUBAGENT_CAPABLE = ['claude'] as const
export const RECURRING_CAPABLE = ['claude'] as const // /loop, /schedule, /cron
export const BRANCH_CAPABLE = ['claude'] as const
@@ -173,7 +192,7 @@ export const SHARED_IDENTITY_CAPABLE = ['codex'] as const
// 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.
-export const CANVAS_CONTROL_CAPABLE = ['claude', 'codex', 'gemini', 'opencode', 'grok'] as const
+export const CANVAS_CONTROL_CAPABLE = ['claude', 'codex', 'gemini', 'opencode', 'grok', 'copilot'] 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
@@ -196,8 +215,8 @@ export const CANVAS_CONTROL_CAPABLE = ['claude', 'codex', 'gemini', 'opencode',
export const PERMISSION_MODE_CAPABLE = ['claude', 'grok', 'gemini', 'codex'] 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 allowlist.
-export const MODEL_SWITCH_CAPABLE = ['claude', 'codex'] as const
+// capability — the renderer never maintains its own Claude/Codex/Copilot allowlist.
+export const MODEL_SWITCH_CAPABLE = ['claude', 'codex', 'copilot'] 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
@@ -260,6 +279,10 @@ const includes = (list: readonly string[], id: AgentId): boolean =>
export const hasHooks = (id: AgentId): boolean => includes(AGENT_HOOK_TARGETS, 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): boolean =>
+ includes(UNCONDITIONAL_SESSION_ID_CAPABLE, id) ||
+ (mintsSessionId(id) && capabilityAgentId(id) === '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)
@@ -345,7 +368,9 @@ export function withSessionId(cmd: string, id: AgentId, sessionId: string): stri
if (!mintsSessionId(id)) return cmd
const sid = sessionId.trim()
if (!sid || !SAFE_SESSION_ID.test(sid)) return cmd
- return `${cmd} --session-id ${sid}`
+ return capabilityAgentId(id) === 'copilot'
+ ? `${cmd} --session-id=${sid}`
+ : `${cmd} --session-id ${sid}`
}
/**
@@ -403,6 +428,8 @@ export function resumeCommandWith(
return `${launchCmd} resume ${sid}`
case 'opencode':
return `${launchCmd} --session ${sid}`
+ case 'copilot':
+ return `${launchCmd} --resume=${sid}`
case 'claude':
case 'gemini':
case 'grok':
diff --git a/src/shared/agents/hook-events.ts b/src/shared/agents/hook-events.ts
index 43158c7b5..13b69f4ff 100644
--- a/src/shared/agents/hook-events.ts
+++ b/src/shared/agents/hook-events.ts
@@ -72,6 +72,28 @@ export const GEMINI_HOOK_EVENTS = [
'SessionEnd'
] as const
+/**
+ * GitHub Copilot CLI hook events (→ normalizeCopilot). Copilot uses the same PascalCase event
+ * names as Claude but a different config-file shape, so the subscription list stays shared while
+ * its installer lives in core/agents/hooks/copilot.ts.
+ *
+ * `PermissionRequest` is deliberately absent. Copilot documents that hook as a decision hook that
+ * can alter the permission result, whereas nodeterm only observes status. Its `Notification`
+ * event carries the closed `permission_prompt` / `elicitation_dialog` signals we need without
+ * participating in authorization. `ErrorOccurred` is also omitted: recoverable API/tool errors
+ * can occur before a turn continues, so treating one as a terminal state would clear RUNNING early.
+ */
+export const COPILOT_HOOK_EVENTS = [
+ 'SessionStart',
+ 'UserPromptSubmit',
+ 'PreToolUse',
+ 'PostToolUse',
+ 'PostToolUseFailure',
+ 'Stop',
+ 'Notification',
+ 'SessionEnd'
+] as const
+
/**
* Grok hook events (→ normalizeGrok). Grok's shipped 1.0.0 docs list fourteen
* (`~/.grok/docs/user-guide/10-hooks.md:84-101`); nine are subscribed — the ones `normalizeGrok` has
diff --git a/src/shared/agents/launch.test.ts b/src/shared/agents/launch.test.ts
index 068e39977..db8864705 100644
--- a/src/shared/agents/launch.test.ts
+++ b/src/shared/agents/launch.test.ts
@@ -56,6 +56,19 @@ describe('assembleLaunchCommand — builtins (byte-identical to the historical p
assembleLaunchCommand({ agentId: 'opencode', initialPrompt: 'fix it' }, ENV).command
).toBe("opencode --prompt 'fix it'")
})
+ it('Copilot keeps an initial prompt interactive', () => {
+ expect(
+ assembleLaunchCommand(
+ {
+ agentId: 'copilot',
+ initialPrompt: 'fix it',
+ sessionId: 'abc-123',
+ sessionIdFlagSupported: true
+ },
+ ENV
+ ).command
+ ).toBe("copilot --interactive 'fix it' --session-id=abc-123")
+ })
it('adds a safely quoted model override after the ordinary Claude launch flags', () => {
expect(
assembleLaunchCommand(
@@ -71,6 +84,17 @@ describe('assembleLaunchCommand — builtins (byte-identical to the historical p
})
})
+describe('assembleResumeCommand — Copilot', () => {
+ it('uses Copilot resume grammar while leaving a gateway model to the environment', () => {
+ expect(
+ assembleResumeCommand(
+ { agentId: 'copilot', sessionId: 'abc-123', model: 'openai/gpt-5.5' },
+ ENV
+ ).command
+ ).toBe('copilot --resume=abc-123')
+ })
+})
+
describe('assembleLaunchCommand — custom agents', () => {
it('a vanilla custom agent launches with its command + prompt', () => {
expect(
diff --git a/src/shared/agents/launch.ts b/src/shared/agents/launch.ts
index 05826582d..50c50c69a 100644
--- a/src/shared/agents/launch.ts
+++ b/src/shared/agents/launch.ts
@@ -108,11 +108,17 @@ export function assembleLaunchCommand(
? shellSingleQuote(inputs.initialPrompt.replace(/\s+/g, ' ').trim())
: null
const sep = eff.argvPromptSeparator
- const isFlagPrompt = eff.promptInjectionMode === 'flag-prompt'
+ const promptFlag =
+ eff.promptInjectionMode === 'flag-prompt'
+ ? '--prompt'
+ : eff.promptInjectionMode === 'flag-interactive'
+ ? '--interactive'
+ : null
+ const isFlagPrompt = !!promptFlag
const usesSep = !!promptArg && !!sep && !isFlagPrompt
const withPrompt = promptArg
? isFlagPrompt
- ? `${baseCmd} --prompt ${promptArg}`
+ ? `${baseCmd} ${promptFlag} ${promptArg}`
: `${baseCmd} ${promptArg}`
: baseCmd
diff --git a/src/shared/agents/model-gateway.test.ts b/src/shared/agents/model-gateway.test.ts
index 600be2dda..d9a84284d 100644
--- a/src/shared/agents/model-gateway.test.ts
+++ b/src/shared/agents/model-gateway.test.ts
@@ -69,6 +69,31 @@ describe('agent mappings', () => {
expect(modelGatewayEnv(gateway, 'gemini')).toEqual({})
})
+ it('maps Copilot BYOK through the protocol route and separates model id from wire id', () => {
+ expect(modelGatewayEnv(gateway, 'copilot', 'anthropic/claude-sonnet-4.6')).toEqual({
+ COPILOT_PROVIDER_BASE_URL: 'https://bifrost.example.test/anthropic',
+ COPILOT_PROVIDER_TYPE: 'anthropic',
+ COPILOT_PROVIDER_API_KEY: 'vk-secret',
+ COPILOT_PROVIDER_MODEL_ID: 'claude-sonnet-4.6',
+ COPILOT_PROVIDER_WIRE_MODEL: 'anthropic/claude-sonnet-4.6'
+ })
+ expect(modelGatewayEnv(gateway, 'copilot', 'openai/gpt-5.5')).toEqual({
+ COPILOT_PROVIDER_BASE_URL: 'https://bifrost.example.test/openai/v1',
+ COPILOT_PROVIDER_TYPE: 'openai',
+ COPILOT_PROVIDER_API_KEY: 'vk-secret',
+ COPILOT_PROVIDER_MODEL_ID: 'gpt-5.5',
+ COPILOT_PROVIDER_WIRE_MODEL: 'openai/gpt-5.5',
+ COPILOT_PROVIDER_WIRE_API: 'responses'
+ })
+ })
+
+ it('does not activate Copilot BYOK until a model is selected', () => {
+ expect(modelGatewayEnv(gateway, 'copilot')).toEqual({})
+ expect(withAgentModel('copilot --resume=abc', 'copilot', 'openai/gpt-5.5')).toBe(
+ 'copilot --resume=abc'
+ )
+ })
+
it('quotes model ids and refuses unsupported/control-bearing values', () => {
expect(withAgentModel('codex resume abc', 'codex', "openai/o'model")).toBe(
"codex resume abc --model 'openai/o'\\''model'"
@@ -94,6 +119,7 @@ describe('agent mappings', () => {
]
expect(modelsForAgent(models, 'claude').map((m) => m.id)).toEqual(all)
expect(modelsForAgent(models, 'codex').map((m) => m.id)).toEqual(all)
+ expect(modelsForAgent(models, 'copilot').map((m) => m.id)).toEqual(all)
expect(modelsForAgent(models, 'gemini')).toEqual([])
})
@@ -113,4 +139,24 @@ describe('agent mappings', () => {
setCustomAgentBaseResolver(null)
}
})
+
+ it('inherits Copilot BYOK grammar through a custom base agent without a frontend exception', () => {
+ setCustomAgentBaseResolver((id: AgentId): BuiltinAgentId | undefined =>
+ id === 'custom:copilot-proxy' ? 'copilot' : undefined
+ )
+ try {
+ expect(
+ modelGatewayEnv(gateway, 'custom:copilot-proxy', 'openai/gpt-5.5')
+ ).toMatchObject({
+ COPILOT_PROVIDER_TYPE: 'openai',
+ COPILOT_PROVIDER_MODEL_ID: 'gpt-5.5',
+ COPILOT_PROVIDER_WIRE_MODEL: 'openai/gpt-5.5'
+ })
+ expect(
+ withAgentModel('copilot-wrapper', 'custom:copilot-proxy', 'openai/gpt-5.5')
+ ).toBe('copilot-wrapper')
+ } finally {
+ setCustomAgentBaseResolver(null)
+ }
+ })
})
diff --git a/src/shared/agents/model-gateway.ts b/src/shared/agents/model-gateway.ts
index 00b9b860a..4d135d9d5 100644
--- a/src/shared/agents/model-gateway.ts
+++ b/src/shared/agents/model-gateway.ts
@@ -92,13 +92,14 @@ export function modelsForAgent(models: GatewayModel[], agentId: AgentId): Gatewa
/**
* Environment applied to a terminal session before custom-agent env (custom values still win).
- * Model selection itself stays a quoted CLI flag for Claude/Codex; the environment contains only
- * the gateway route and credential, so a restart command never exposes the API key in the pane.
+ * Claude/Codex model selection stays a quoted CLI flag. Copilot's BYOK protocol instead carries
+ * its internal + wire model ids in environment variables. Credentials never enter a restart
+ * command, so none are exposed in the pane.
*/
export function modelGatewayEnv(
settings: ModelGatewaySettings,
agentId: AgentId,
- _model?: string
+ model?: string
): Record<string, string> {
const routes = modelGatewayRoutes(settings.baseUrl)
const key = settings.apiKey.trim()
@@ -114,6 +115,30 @@ export function modelGatewayEnv(
OPENAI_BASE_URL: routes.openai,
OPENAI_API_KEY: key
}
+ case 'copilot': {
+ // Copilot's BYOK mode requires a model at startup. Keep an ordinary Copilot node on GitHub's
+ // own routing until the user actually selects one; otherwise merely configuring a gateway
+ // would activate an incomplete provider and make every new Copilot node fail to launch.
+ const wireModel = normalizedAgentModel(agentId, model)
+ if (!wireModel) return {}
+ const slash = wireModel.indexOf('/')
+ const provider = slash > 0 ? wireModel.slice(0, slash).toLowerCase() : ''
+ const modelId = slash > 0 ? wireModel.slice(slash + 1) : wireModel
+ const anthropic = provider === 'anthropic'
+ return {
+ COPILOT_PROVIDER_BASE_URL: anthropic ? routes.anthropic : routes.openai,
+ COPILOT_PROVIDER_TYPE: anthropic ? 'anthropic' : 'openai',
+ COPILOT_PROVIDER_API_KEY: key,
+ // Bifrost needs the provider-prefixed wire id; Copilot's internal catalogue wants the
+ // unprefixed well-known id for token limits/tool strategy. Its official BYOK grammar
+ // explicitly supports separating these two values.
+ COPILOT_PROVIDER_MODEL_ID: modelId,
+ COPILOT_PROVIDER_WIRE_MODEL: wireModel,
+ ...(!anthropic && /^gpt-5(?:[.-]|$)/i.test(modelId)
+ ? { COPILOT_PROVIDER_WIRE_API: 'responses' }
+ : {})
+ }
+ }
default:
return {}
}
@@ -136,5 +161,9 @@ export function normalizedAgentModel(agentId: AgentId, model: string | undefined
export function withAgentModel(cmd: string, agentId: AgentId, model: string | undefined): string {
const value = normalizedAgentModel(agentId, model)
if (!value) return cmd
+ // Copilot receives the model through COPILOT_PROVIDER_MODEL_ID/WIRE_MODEL. Appending --model
+ // would collapse those two distinct values back together and send the unrecognized
+ // provider-prefixed Bifrost id through Copilot's internal catalogue.
+ if (capabilityAgentId(agentId) === 'copilot') return cmd
return `${cmd} --model ${shellSingleQuote(value)}`
}
diff --git a/src/shared/agents/normalize.test.ts b/src/shared/agents/normalize.test.ts
index d034eb304..91bc47120 100644
--- a/src/shared/agents/normalize.test.ts
+++ b/src/shared/agents/normalize.test.ts
@@ -1,10 +1,86 @@
import { describe, it, expect } from 'vitest'
-import { normalizeClaude, normalizeCodex, normalizeFor, type RawHookEnvelope } from './normalize'
+import {
+ normalizeClaude,
+ normalizeCodex,
+ normalizeCopilot,
+ normalizeFor,
+ type RawHookEnvelope
+} from './normalize'
function env(payload: Record<string, unknown>): RawHookEnvelope {
return { nodeId: 'n1', agentId: 'claude', payload }
}
+function copilotEnv(payload: Record<string, unknown>): RawHookEnvelope {
+ return { nodeId: 'n1', agentId: 'copilot', payload }
+}
+
+describe('normalizeCopilot', () => {
+ it('maps session boundaries and captures the CLI session id', () => {
+ expect(normalizeCopilot(copilotEnv({ hook_event_name: 'SessionStart', session_id: 's1' }))).toEqual({
+ nodeId: 'n1',
+ agentId: 'copilot',
+ sessionId: 's1',
+ kind: 'session',
+ sessionPhase: 'start'
+ })
+ expect(normalizeCopilot(copilotEnv({ hook_event_name: 'SessionEnd', session_id: 's1' }))).toMatchObject({
+ kind: 'session',
+ sessionPhase: 'end'
+ })
+ })
+
+ it('maps turn and tool lifecycle without treating a failed tool as a finished turn', () => {
+ expect(
+ normalizeCopilot(copilotEnv({ hook_event_name: 'UserPromptSubmit', prompt: 'fix it' }))
+ ).toMatchObject({ state: 'working', newTurn: true, task: 'fix it' })
+ for (const hook_event_name of ['PreToolUse', 'PostToolUse', 'PostToolUseFailure']) {
+ expect(normalizeCopilot(copilotEnv({ hook_event_name })), hook_event_name).toMatchObject({
+ state: 'working'
+ })
+ }
+ expect(
+ normalizeCopilot(
+ copilotEnv({ hook_event_name: 'Stop', last_assistant_message: 'finished' })
+ )
+ ).toMatchObject({ state: 'done', lastMessage: 'finished' })
+ })
+
+ it('maps only the documented needs-user notifications', () => {
+ expect(
+ normalizeCopilot(
+ copilotEnv({
+ hook_event_name: 'Notification',
+ notification_type: 'permission_prompt',
+ message: 'Approve command?'
+ })
+ )
+ ).toMatchObject({ state: 'blocked', lastMessage: 'Approve command?' })
+ expect(
+ normalizeCopilot(
+ copilotEnv({
+ hook_event_name: 'Notification',
+ notification_type: 'elicitation_dialog',
+ message: 'Which option?'
+ })
+ )
+ ).toMatchObject({ state: 'waiting', lastMessage: 'Which option?' })
+ for (const notification_type of ['agent_idle', 'agent_completed', 'unknown_future_type']) {
+ expect(
+ normalizeCopilot(copilotEnv({ hook_event_name: 'Notification', notification_type })),
+ notification_type
+ ).toBeNull()
+ }
+ })
+
+ it('routes through the shared dispatcher', () => {
+ expect(normalizeFor('copilot', copilotEnv({ hook_event_name: 'Stop' }))).toMatchObject({
+ agentId: 'copilot',
+ state: 'done'
+ })
+ })
+})
+
describe('normalizeClaude — turn-end signals', () => {
it('Stop → done, not interrupted', () => {
const e = normalizeClaude(env({ hook_event_name: 'Stop', session_id: 's1' }))
diff --git a/src/shared/agents/normalize.ts b/src/shared/agents/normalize.ts
index 5d1d7ea8e..e51995538 100644
--- a/src/shared/agents/normalize.ts
+++ b/src/shared/agents/normalize.ts
@@ -399,6 +399,59 @@ export function normalizeGemini(env: RawHookEnvelope): NormalizedAgentEvent | nu
return null
}
+// GitHub Copilot CLI hook payload. Its event names and snake_case envelope intentionally resemble
+// Claude's, but its event set and notification vocabulary are a separate protocol contract. Keep a
+// dedicated normalizer so a future change in one harness cannot silently change the other's state.
+interface CopilotPayload {
+ hook_event_name?: string
+ session_id?: string
+ prompt?: string
+ notification_type?: string
+ message?: string
+ last_assistant_message?: string
+}
+
+export function normalizeCopilot(env: RawHookEnvelope): NormalizedAgentEvent | null {
+ const p = env.payload as CopilotPayload
+ const base = { nodeId: env.nodeId, agentId: env.agentId, sessionId: p.session_id }
+
+ if (p.hook_event_name === 'SessionStart') {
+ return { ...base, kind: 'session', sessionPhase: 'start' }
+ }
+ if (p.hook_event_name === 'SessionEnd') {
+ return { ...base, kind: 'session', sessionPhase: 'end' }
+ }
+ if (p.hook_event_name === 'UserPromptSubmit') {
+ return { ...base, kind: 'state', state: 'working', task: p.prompt, newTurn: true }
+ }
+ if (
+ p.hook_event_name === 'PreToolUse' ||
+ p.hook_event_name === 'PostToolUse' ||
+ p.hook_event_name === 'PostToolUseFailure'
+ ) {
+ return { ...base, kind: 'state', state: 'working' }
+ }
+ if (p.hook_event_name === 'Stop') {
+ return {
+ ...base,
+ kind: 'state',
+ state: 'done',
+ lastMessage: p.last_assistant_message
+ }
+ }
+ if (p.hook_event_name === 'Notification') {
+ // Closed matches only. Informational/background notification types must never create a sticky
+ // NEEDS YOU badge on a finished parent session.
+ if (p.notification_type === 'permission_prompt') {
+ return { ...base, kind: 'state', state: 'blocked', lastMessage: p.message }
+ }
+ if (p.notification_type === 'elicitation_dialog') {
+ return { ...base, kind: 'state', state: 'waiting', lastMessage: p.message }
+ }
+ }
+ return null
+}
+
// opencode plugin payload (see core/agents/hooks/opencode.ts). The managed plugin forwards
// { event, sessionID?, role? } per hook; field names beyond `event` are read defensively —
// opencode's event payload shapes are not a contract, so the event NAME carries the mapping.
@@ -661,5 +714,6 @@ export function normalizeFor(agentId: AgentId, env: RawHookEnvelope): Normalized
if (agentId === 'gemini') return normalizeGemini(env)
if (agentId === 'opencode') return normalizeOpencode(env)
if (agentId === 'grok') return normalizeGrok(env)
+ if (agentId === 'copilot') return normalizeCopilot(env)
return null
}
diff --git a/src/shared/agents/resume.test.ts b/src/shared/agents/resume.test.ts
index dabcc7bb2..9eb0b61f5 100644
--- a/src/shared/agents/resume.test.ts
+++ b/src/shared/agents/resume.test.ts
@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest'
-import { resumeCommand, withSessionId } from './config'
+import { resumeCommand, supportsSessionIdFlag, withSessionId } from './config'
describe('withSessionId', () => {
it('appends the minted id for claude', () => {
@@ -12,6 +12,15 @@ describe('withSessionId', () => {
}
})
+ it('uses Copilot\'s equals-form session id independently of the Claude probe', () => {
+ expect(supportsSessionIdFlag('copilot', false)).toBe(true)
+ expect(supportsSessionIdFlag('claude', false)).toBe(false)
+ expect(supportsSessionIdFlag('claude', true)).toBe(true)
+ expect(withSessionId('copilot', 'copilot', 'abc-123')).toBe(
+ 'copilot --session-id=abc-123'
+ )
+ })
+
// The value reaches a tmux send-keys line, so the type is not the guard — the same reason
// resumeCommand re-validates. A rejected id must yield the bare command, never a broken one.
it('refuses an unsafe or empty id and returns the command unchanged', () => {
@@ -58,6 +67,10 @@ describe('resumeCommand', () => {
it('resumes opencode via --session', () => {
expect(resumeCommand('opencode', 'ses_a1b2c3')).toBe('opencode --session ses_a1b2c3')
})
+
+ it('resumes Copilot via its optional-value equals form', () => {
+ expect(resumeCommand('copilot', 'abc-123')).toBe('copilot --resume=abc-123')
+ })
it('rejects an unsafe opencode session id', () => {
expect(resumeCommand('opencode', 'x; rm -rf /')).toBeNull()
})