#1 Persistent memory for AI coding agents based on real-world benchmarks
TypeScript agentmemoryagentsaiclaudeclaudecodecodexcopilotcursorgenaiharnesshermesmemoryompopenclawopencodepi
Add GitHub Copilot CLI support (#534)
Ross Storya0da02b6b3dd
diff --git a/AGENTS.md b/AGENTS.mdindex 4f57eaa5..36569e60 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -19,6 +19,7 @@ agentmemory is a persistent memory system for AI coding agents, built on iii-eng5. `test/mcp-standalone.test.ts` — tool count assertion6. `README.md` — tool counts (search for "MCP tools")7. `plugin/.claude-plugin/plugin.json` — tool count in description+8. `plugin/plugin.json` and `plugin/.mcp.copilot.json` (when present) — tool count or MCP exposure**When adding REST endpoints, you MUST update:**1. `src/triggers/api.ts` — endpoint registration@@ -32,6 +33,7 @@ agentmemory is a persistent memory system for AI coding agents, built on iii-eng4. `src/functions/export-import.ts` — supportedVersions set5. `test/export-import.test.ts` — version assertion6. `plugin/.claude-plugin/plugin.json` — version field+7. `plugin/plugin.json` (when present) — version field**When adding new KV scopes:**1. `src/state/schema.ts` — add to the KV objectdiff --git a/README.md b/README.mdindex da5a2dc1..830914c2 100644--- a/README.md+++ b/README.md@@ -7,7 +7,7 @@Your coding agent remembers everything. No more re-explaining.Built on <a href="https://github.com/iii-hq/iii">iii engine</a></strong><br/>- Persistent memory for Claude Code, Cursor, Gemini CLI, Codex CLI, Hermes, OpenClaw, pi, OpenCode, and any MCP client.+ Persistent memory for Claude Code, GitHub Copilot CLI, Cursor, Gemini CLI, Codex CLI, Hermes, OpenClaw, pi, OpenCode, and any MCP client.</p><p align="center">@@ -93,7 +93,7 @@ npm install -g @agentmemory/agentmemory # once — bare `agentmemory` o# sudo npm install -g @agentmemory/agentmemoryagentmemory # start the memory server on :3111agentmemory demo # seed sample sessions + prove recall-agentmemory connect claude-code # wire your agent (also: codex, cursor, gemini-cli, ...)+agentmemory connect claude-code # wire your agent (also: copilot-cli, codex, cursor, gemini-cli, ...)```Or via `npx` (no install):@@ -125,6 +125,11 @@ agentmemory works with any agent that supports hooks, MCP, or REST API. All agen<sub>native plugin + 6 hooks + MCP</sub></td><td align="center" width="12.5%">+<a href="https://github.com/features/copilot"><img src="https://github.githubassets.com/images/modules/site/copilot/copilot.png" alt="GitHub Copilot CLI" width="48" height="48" /></a><br/>+<strong>GitHub Copilot CLI</strong><br/>+<sub>MCP + plugin hooks/skills</sub>+</td>+<td align="center" width="12.5%"><a href="integrations/openclaw/"><img src="https://github.com/openclaw.png?size=120" alt="OpenClaw" width="48" height="48" /></a><br/><strong>OpenClaw</strong><br/><sub>native plugin + MCP</sub>@@ -483,6 +488,18 @@ agentmemory connect codex --with-hooksThis adds an idempotent block to `~/.codex/hooks.json` referencing absolute paths to the bundled scripts (no `${CLAUDE_PLUGIN_ROOT}` expansion needed at user-scope). Re-run the same command after upgrading agentmemory to refresh paths. User entries in the same file are preserved; only previous agentmemory entries are replaced.+### GitHub Copilot CLI++```bash+# MCP-only wiring+agentmemory connect copilot-cli++# Full hooks/skills plugin from the GitHub subdir+copilot plugin install rohitg00/agentmemory:plugin+```++`agentmemory connect copilot-cli` merges `mcpServers.agentmemory` into `~/.copilot/mcp-config.json` (or `$COPILOT_HOME/mcp-config.json` when `COPILOT_HOME` is set) and preserves existing servers. This adapter is Windows-safe even though other `connect` adapters still require manual Windows setup. Copilot picks up the MCP server on next launch or after `/mcp`. Install the plugin as well when you want the full hook/skill experience.+<details><summary><b>OpenClaw (paste this prompt)</b></summary>@@ -555,6 +572,8 @@ The agentmemory entry is the **same MCP server block** across every host that us| **Cline / Roo Code / Kilo Code** | Cline MCP settings (Settings UI → MCP Servers → Edit) | Same `mcpServers` block. || **Windsurf** | `~/.codeium/windsurf/mcp_config.json` | Same `mcpServers` block. || **Gemini CLI** | `~/.gemini/settings.json` | `gemini mcp add agentmemory npx -y @agentmemory/mcp --scope user` (auto-merges). |+| **GitHub Copilot CLI (MCP only)** | `~/.copilot/mcp-config.json` | `agentmemory connect copilot-cli` merges `mcpServers.agentmemory`; Copilot picks it up on next launch or `/mcp`. |+| **GitHub Copilot CLI (full plugin)** | Copilot plugin install | `copilot plugin install rohitg00/agentmemory:plugin` for the plugin from the GitHub subdir. || **OpenClaw** | OpenClaw MCP config | Same `mcpServers` block, or use the deeper [memory plugin](integrations/openclaw/). || **Codex CLI (MCP only)** | `.codex/config.toml` | TOML shape: `codex mcp add agentmemory -- npx -y @agentmemory/mcp`, or add `[mcp_servers.agentmemory]` manually. || **Codex CLI (full plugin)** | Codex plugin marketplace | `codex plugin marketplace add rohitg00/agentmemory` then `codex plugin add agentmemory@agentmemory`. Registers MCP + 6 lifecycle hooks (SessionStart, UserPromptSubmit, PreToolUse, PostToolUse, PreCompact, Stop) + 8 skills. On Codex Desktop, also run `agentmemory connect codex --with-hooks` until [openai/codex#16430](https://github.com/openai/codex/issues/16430) lands — plugin hooks are currently silent there. |diff --git a/plugin/.mcp.copilot.json b/plugin/.mcp.copilot.jsonnew file mode 100644index 00000000..827330ad--- /dev/null+++ b/plugin/.mcp.copilot.json@@ -0,0 +1,15 @@+{+ "mcpServers": {+ "agentmemory": {+ "type": "local",+ "command": "npx",+ "args": ["-y", "@agentmemory/mcp"],+ "env": {+ "AGENTMEMORY_URL": "${AGENTMEMORY_URL:-http://localhost:3111}",+ "AGENTMEMORY_SECRET": "${AGENTMEMORY_SECRET:-}",+ "AGENTMEMORY_TOOLS": "${AGENTMEMORY_TOOLS:-all}"+ },+ "tools": ["*"]+ }+ }+}diff --git a/plugin/hooks/hooks.copilot.json b/plugin/hooks/hooks.copilot.jsonnew file mode 100644index 00000000..b7d09f8b--- /dev/null+++ b/plugin/hooks/hooks.copilot.json@@ -0,0 +1,72 @@+{+ "version": 1,+ "hooks": {+ "sessionStart": [+ {+ "type": "command",+ "command": "node ${COPILOT_PLUGIN_ROOT}/scripts/session-start.mjs"+ }+ ],+ "userPromptSubmitted": [+ {+ "type": "command",+ "command": "node ${COPILOT_PLUGIN_ROOT}/scripts/prompt-submit.mjs"+ }+ ],+ "preToolUse": [+ {+ "type": "command",+ "matcher": "edit|write|create|read|view|glob|grep",+ "command": "node ${COPILOT_PLUGIN_ROOT}/scripts/pre-tool-use.mjs"+ }+ ],+ "postToolUse": [+ {+ "type": "command",+ "command": "node ${COPILOT_PLUGIN_ROOT}/scripts/post-tool-use.mjs"+ }+ ],+ "postToolUseFailure": [+ {+ "type": "command",+ "command": "node ${COPILOT_PLUGIN_ROOT}/scripts/post-tool-failure.mjs"+ }+ ],+ "preCompact": [+ {+ "type": "command",+ "command": "node ${COPILOT_PLUGIN_ROOT}/scripts/pre-compact.mjs"+ }+ ],+ "agentStop": [+ {+ "type": "command",+ "command": "node ${COPILOT_PLUGIN_ROOT}/scripts/stop.mjs"+ }+ ],+ "sessionEnd": [+ {+ "type": "command",+ "command": "node ${COPILOT_PLUGIN_ROOT}/scripts/session-end.mjs"+ }+ ],+ "subagentStart": [+ {+ "type": "command",+ "command": "node ${COPILOT_PLUGIN_ROOT}/scripts/subagent-start.mjs"+ }+ ],+ "subagentStop": [+ {+ "type": "command",+ "command": "node ${COPILOT_PLUGIN_ROOT}/scripts/subagent-stop.mjs"+ }+ ],+ "notification": [+ {+ "type": "command",+ "command": "node ${COPILOT_PLUGIN_ROOT}/scripts/notification.mjs"+ }+ ]+ }+}diff --git a/plugin/plugin.json b/plugin/plugin.jsonnew file mode 100644index 00000000..4410f8ca--- /dev/null+++ b/plugin/plugin.json@@ -0,0 +1,15 @@+{+ "name": "agentmemory",+ "version": "0.9.22",+ "description": "Persistent memory for AI coding agents -- captures tool usage, compresses via LLM, injects context into future sessions. 12 hooks, 53 MCP tools, 8 skills, real-time viewer.",+ "author": {+ "name": "Rohit Ghumare",+ "url": "https://github.com/rohitg00"+ },+ "license": "Apache-2.0",+ "homepage": "https://github.com/rohitg00/agentmemory",+ "repository": "https://github.com/rohitg00/agentmemory",+ "skills": "skills/",+ "mcpServers": ".mcp.copilot.json",+ "hooks": "hooks/hooks.copilot.json"+}diff --git a/plugin/scripts/notification.mjs b/plugin/scripts/notification.mjsindex b1cb5906..3967158c 100755--- a/plugin/scripts/notification.mjs+++ b/plugin/scripts/notification.mjs@@ -46,8 +46,10 @@ async function main() {return;}if (isSdkChildContext(data)) return;- if (data.notification_type !== "permission_prompt") return;- const sessionId = data.session_id || "unknown";+ const notificationType = data.notification_type ?? data.notificationType;+ if (notificationType !== "permission_prompt") return;+ const rawSessionId = data.session_id ?? data.sessionId;+ const sessionId = typeof rawSessionId === "string" && rawSessionId.length > 0 ? rawSessionId : "unknown";fetch(`${REST_URL}/agentmemory/observe`, {method: "POST",headers: authHeaders(),@@ -58,7 +60,7 @@ async function main() {cwd: data.cwd || process.cwd(),timestamp: (/* @__PURE__ */ new Date()).toISOString(),data: {- notification_type: data.notification_type,+ notification_type: notificationType,title: data.title,message: data.message}diff --git a/plugin/scripts/post-tool-failure.mjs b/plugin/scripts/post-tool-failure.mjsindex b584d26a..6fdad8d9 100755--- a/plugin/scripts/post-tool-failure.mjs+++ b/plugin/scripts/post-tool-failure.mjs@@ -46,8 +46,11 @@ async function main() {return;}if (isSdkChildContext(data)) return;- if (data.is_interrupt) return;- const sessionId = data.session_id || "unknown";+ if (data.is_interrupt || data.isInterrupt) return;+ const sessionId = data.session_id || data.sessionId || "unknown";+ const toolName = data.tool_name ?? data.toolName;+ const toolInput = data.tool_input ?? data.toolArgs;+ const error = data.error ?? data.errorMessage;fetch(`${REST_URL}/agentmemory/observe`, {method: "POST",headers: authHeaders(),@@ -58,9 +61,9 @@ async function main() {cwd: data.cwd || process.cwd(),timestamp: (/* @__PURE__ */ new Date()).toISOString(),data: {- tool_name: data.tool_name,- tool_input: typeof data.tool_input === "string" ? data.tool_input.slice(0, 4e3) : JSON.stringify(data.tool_input ?? "").slice(0, 4e3),- error: typeof data.error === "string" ? data.error.slice(0, 4e3) : JSON.stringify(data.error ?? "").slice(0, 4e3)+ tool_name: toolName,+ tool_input: typeof toolInput === "string" ? toolInput.slice(0, 4e3) : JSON.stringify(toolInput ?? "").slice(0, 4e3),+ error: typeof error === "string" ? error.slice(0, 4e3) : JSON.stringify(error ?? "").slice(0, 4e3)}}),signal: AbortSignal.timeout(3e3)diff --git a/plugin/scripts/post-tool-use.mjs b/plugin/scripts/post-tool-use.mjsindex 76add3b9..b4aef9c9 100755--- a/plugin/scripts/post-tool-use.mjs+++ b/plugin/scripts/post-tool-use.mjs@@ -46,8 +46,10 @@ async function main() {return;}if (isSdkChildContext(data)) return;- const sessionId = data.session_id || "unknown";- const { imageData, cleanOutput } = extractImageData(data.tool_response ?? data.tool_output);+ const sessionId = data.session_id || data.sessionId || "unknown";+ const toolName = data.tool_name ?? data.toolName;+ const toolInput = data.tool_input ?? data.toolArgs;+ const { imageData, cleanOutput } = extractImageData(toolOutput(data));fetch(`${REST_URL}/agentmemory/observe`, {method: "POST",headers: authHeaders(),@@ -58,8 +60,8 @@ async function main() {cwd: data.cwd || process.cwd(),timestamp: (/* @__PURE__ */ new Date()).toISOString(),data: {- tool_name: data.tool_name,- tool_input: data.tool_input,+ tool_name: toolName,+ tool_input: toolInput,tool_output: truncate(cleanOutput, 8e3),...imageData ? { image_data: imageData } : {}}@@ -68,6 +70,16 @@ async function main() {}).catch(() => {});setTimeout(() => process.exit(0), 500).unref();}+function toolOutput(data) {+ if (data.tool_response !== void 0) return data.tool_response;+ if (data.tool_output !== void 0) return data.tool_output;+ const result = data.tool_result ?? data.toolResult;+ if (typeof result === "object" && result !== null) {+ const obj = result;+ return obj.text_result_for_llm ?? obj.textResultForLlm ?? result;+ }+ return result;+}function isBase64Image(val) {return typeof val === "string" && (val.startsWith("data:image/") || val.startsWith("iVBORw0KGgo") || val.startsWith("/9j/"));}diff --git a/plugin/scripts/pre-compact.mjs b/plugin/scripts/pre-compact.mjsindex c520eb2f..0afdcb0b 100755--- a/plugin/scripts/pre-compact.mjs+++ b/plugin/scripts/pre-compact.mjs@@ -46,7 +46,7 @@ async function main() {return;}if (isSdkChildContext(data)) return;- const sessionId = data.session_id || "unknown";+ const sessionId = data.session_id || data.sessionId || "unknown";const project = resolveProject(data.cwd);if (process.env["CLAUDE_MEMORY_BRIDGE"] === "true") try {await fetch(`${REST_URL}/agentmemory/claude-bridge/sync`, {diff --git a/plugin/scripts/pre-tool-use.mjs b/plugin/scripts/pre-tool-use.mjsindex 6e31633d..d70c166e 100755--- a/plugin/scripts/pre-tool-use.mjs+++ b/plugin/scripts/pre-tool-use.mjs@@ -24,18 +24,22 @@ async function main() {return;}if (isSdkChildContext(data)) return;- const toolName = data.tool_name;+ const toolName = typeof data.tool_name === "string" ? data.tool_name : typeof data.toolName === "string" ? data.toolName : void 0;if (!toolName) return;+ const normalizedToolName = toolName.toLowerCase();if (![- "Edit",- "Write",- "Read",- "Glob",- "Grep"- ].includes(toolName)) return;- const toolInput = data.tool_input || {};+ "edit",+ "write",+ "create",+ "read",+ "view",+ "glob",+ "grep"+ ].includes(normalizedToolName)) return;+ const rawToolInput = data.tool_input ?? data.toolArgs;+ const toolInput = typeof rawToolInput === "object" && rawToolInput !== null && !Array.isArray(rawToolInput) ? rawToolInput : {};const files = [];- const fileKeys = toolName === "Grep" ? ["path", "file"] : [+ const fileKeys = normalizedToolName === "grep" ? ["path", "file"] : ["file_path","path","file",@@ -47,11 +51,12 @@ async function main() {}if (files.length === 0) return;const terms = [];- if (toolName === "Grep" || toolName === "Glob") {+ if (normalizedToolName === "grep" || normalizedToolName === "glob") {const pattern = toolInput["pattern"];if (typeof pattern === "string" && pattern.length > 0) terms.push(pattern);}- const sessionId = data.session_id || "unknown";+ const rawSessionId = data.session_id || data.sessionId;+ const sessionId = typeof rawSessionId === "string" && rawSessionId.length > 0 ? rawSessionId : "unknown";const project = typeof data.project === "string" && data.project.trim().length > 0 ? data.project.trim() : void 0;try {const res = await fetch(`${REST_URL}/agentmemory/enrich`, {diff --git a/plugin/scripts/prompt-submit.mjs b/plugin/scripts/prompt-submit.mjsindex 7d7f380d..1a4147e6 100755--- a/plugin/scripts/prompt-submit.mjs+++ b/plugin/scripts/prompt-submit.mjs@@ -46,7 +46,7 @@ async function main() {return;}if (isSdkChildContext(data)) return;- const sessionId = data.session_id || "unknown";+ const sessionId = data.session_id || data.sessionId || "unknown";fetch(`${REST_URL}/agentmemory/observe`, {method: "POST",headers: authHeaders(),@@ -56,7 +56,7 @@ async function main() {project: resolveProject(data.cwd),cwd: data.cwd || process.cwd(),timestamp: (/* @__PURE__ */ new Date()).toISOString(),- data: { prompt: data.prompt }+ data: { prompt: data.prompt ?? data.userPrompt }}),signal: AbortSignal.timeout(3e3)}).catch(() => {});diff --git a/plugin/scripts/session-end.mjs b/plugin/scripts/session-end.mjsindex 45fd11af..019149c3 100755--- a/plugin/scripts/session-end.mjs+++ b/plugin/scripts/session-end.mjs@@ -22,7 +22,7 @@ async function main() {return;}if (isSdkChildContext(data)) return;- const sessionId = data.session_id || "unknown";+ const sessionId = data.session_id || data.sessionId || "unknown";fetch(`${REST_URL}/agentmemory/session/end`, {method: "POST",headers: authHeaders(),diff --git a/plugin/scripts/session-start.mjs b/plugin/scripts/session-start.mjsindex ad0aa829..51b70eb4 100755--- a/plugin/scripts/session-start.mjs+++ b/plugin/scripts/session-start.mjs@@ -49,7 +49,7 @@ async function main() {return;}if (isSdkChildContext(data)) return;- const sessionId = data.session_id || `ses_${Date.now().toString(36)}`;+ const sessionId = data.session_id || data.sessionId || `ses_${Date.now().toString(36)}`;const cwd = data.cwd || process.cwd();const project = resolveProject(data.cwd);const url = `${REST_URL}/agentmemory/session/start`;diff --git a/plugin/scripts/stop.mjs b/plugin/scripts/stop.mjsindex 51630ca9..03d30c64 100755--- a/plugin/scripts/stop.mjs+++ b/plugin/scripts/stop.mjs@@ -22,7 +22,7 @@ async function main() {return;}if (isSdkChildContext(data)) return;- const sessionId = data.session_id || "unknown";+ const sessionId = data.session_id || data.sessionId || "unknown";fetch(`${REST_URL}/agentmemory/summarize`, {method: "POST",headers: authHeaders(),diff --git a/plugin/scripts/subagent-start.mjs b/plugin/scripts/subagent-start.mjsindex 96fc4636..2359a1c6 100755--- a/plugin/scripts/subagent-start.mjs+++ b/plugin/scripts/subagent-start.mjs@@ -47,7 +47,9 @@ async function main() {return;}if (isSdkChildContext(data)) return;- const sessionId = data.session_id || "unknown";+ const sessionId = data.session_id || data.sessionId || "unknown";+ const agentId = data.agent_id || data.agentName;+ const agentType = data.agent_type || data.agentDisplayName || data.agentName;fetch(`${REST_URL}/agentmemory/observe`, {method: "POST",headers: authHeaders(),@@ -58,8 +60,8 @@ async function main() {cwd: data.cwd || process.cwd(),timestamp: (/* @__PURE__ */ new Date()).toISOString(),data: {- agent_id: data.agent_id,- agent_type: data.agent_type+ agent_id: agentId,+ agent_type: agentType}}),signal: AbortSignal.timeout(TIMEOUT_MS)diff --git a/plugin/scripts/subagent-stop.mjs b/plugin/scripts/subagent-stop.mjsindex 7210c2b4..2ba1b002 100755--- a/plugin/scripts/subagent-stop.mjs+++ b/plugin/scripts/subagent-stop.mjs@@ -46,7 +46,9 @@ async function main() {return;}if (isSdkChildContext(data)) return;- const sessionId = data.session_id || "unknown";+ const sessionId = data.session_id || data.sessionId || "unknown";+ const agentId = data.agent_id || data.agentName;+ const agentType = data.agent_type || data.agentDisplayName || data.agentName;const lastMsg = typeof data.last_assistant_message === "string" ? data.last_assistant_message.slice(0, 4e3) : "";fetch(`${REST_URL}/agentmemory/observe`, {method: "POST",@@ -58,8 +60,8 @@ async function main() {cwd: data.cwd || process.cwd(),timestamp: (/* @__PURE__ */ new Date()).toISOString(),data: {- agent_id: data.agent_id,- agent_type: data.agent_type,+ agent_id: agentId,+ agent_type: agentType,last_message: lastMsg}}),diff --git a/src/cli.ts b/src/cli.tsindex d97d655e..1b36cfd4 100644--- a/src/cli.ts+++ b/src/cli.ts@@ -117,8 +117,9 @@ Usage: agentmemory [command] [options]Commands:(default) Start agentmemory workerinit Copy bundled .env.example to ~/.agentmemory/.env if absent- connect [agent] Wire agentmemory into an installed agent (claude-code, codex,- cursor, gemini-cli, openclaw, hermes, pi, openhuman).+ connect [agent] Wire agentmemory into an installed agent (claude-code,+ copilot-cli, codex, cursor, gemini-cli, openclaw,+ hermes, pi, openhuman).No arg = interactive picker. --all wires every detected agent.--dry-run shows what would change. --force re-installs.status Show connection status, memory count, flags, and healthdiff --git a/src/cli/connect/codex-hooks.ts b/src/cli/connect/codex-hooks.tsindex 2f17715f..ad19877b 100644--- a/src/cli/connect/codex-hooks.ts+++ b/src/cli/connect/codex-hooks.ts@@ -97,5 +97,12 @@ export function buildMergedHooks(}function isAgentmemoryEntry(entry: HookEntry, scriptsDir: string): boolean {- return entry.hooks.some((handler) => handler.command.includes(scriptsDir));+ const normalizedScriptsDir = normalizePathForCommandMatch(scriptsDir);+ return entry.hooks.some((handler) =>+ normalizePathForCommandMatch(handler.command).includes(normalizedScriptsDir),+ );+}++function normalizePathForCommandMatch(value: string): string {+ return value.replace(/\\/g, "/");}diff --git a/src/cli/connect/copilot-cli.ts b/src/cli/connect/copilot-cli.tsnew file mode 100644index 00000000..8cce5a54--- /dev/null+++ b/src/cli/connect/copilot-cli.ts@@ -0,0 +1,91 @@+import { existsSync, mkdirSync } from "node:fs";+import { homedir } from "node:os";+import { dirname, join } from "node:path";+import * as p from "@clack/prompts";+import type { ConnectAdapter, ConnectOptions, ConnectResult } from "./types.js";+import {+ AGENTMEMORY_COPILOT_MCP_BLOCK,+ backupFile,+ logAlreadyWired,+ logBackup,+ logInstalled,+ readJsonSafe,+ writeJsonAtomic,+} from "./util.js";++const COPILOT_DIR = process.env["COPILOT_HOME"] || join(homedir(), ".copilot");+const COPILOT_MCP_JSON = join(COPILOT_DIR, "mcp-config.json");++type CopilotMcpEntry = typeof AGENTMEMORY_COPILOT_MCP_BLOCK;+type CopilotConfig = {+ mcpServers?: Record<string, CopilotMcpEntry>;+ [key: string]: unknown;+};++function entryMatches(entry: unknown): boolean {+ if (!entry || typeof entry !== "object") return false;+ return JSON.stringify(entry) === JSON.stringify(AGENTMEMORY_COPILOT_MCP_BLOCK);+}++export const adapter: ConnectAdapter = {+ name: "copilot-cli",+ displayName: "GitHub Copilot CLI",+ docs: "https://github.com/rohitg00/agentmemory#github-copilot-cli",+ protocolNote:+ "→ Using MCP. Install the plugin too for full hooks/skills coverage.",++ detect(): boolean {+ return existsSync(COPILOT_DIR);+ },++ async install(opts: ConnectOptions): Promise<ConnectResult> {+ const existing = readJsonSafe<CopilotConfig>(COPILOT_MCP_JSON);+ const next: CopilotConfig = existing ? { ...existing } : {};+ const servers: Record<string, CopilotMcpEntry> = {+ ...((next.mcpServers as Record<string, CopilotMcpEntry>) ?? {}),+ };++ const alreadyHas = entryMatches(servers["agentmemory"]);+ if (alreadyHas && !opts.force) {+ logAlreadyWired("GitHub Copilot CLI", COPILOT_MCP_JSON);+ return { kind: "already-wired", mutatedPath: COPILOT_MCP_JSON };+ }++ if (opts.dryRun) {+ p.log.info(+ `[dry-run] Would ${alreadyHas ? "overwrite" : "add"} mcpServers.agentmemory in ${COPILOT_MCP_JSON}`,+ );+ return { kind: "installed", mutatedPath: COPILOT_MCP_JSON };+ }++ let backupPath: string | undefined;+ if (existsSync(COPILOT_MCP_JSON)) {+ backupPath = backupFile(COPILOT_MCP_JSON, "copilot-cli");+ logBackup(backupPath);+ } else {+ mkdirSync(dirname(COPILOT_MCP_JSON), { recursive: true });+ }++ servers["agentmemory"] = AGENTMEMORY_COPILOT_MCP_BLOCK;+ next.mcpServers = servers;+ writeJsonAtomic(COPILOT_MCP_JSON, next);++ const verify = readJsonSafe<CopilotConfig>(COPILOT_MCP_JSON);+ if (!entryMatches(verify?.mcpServers?.["agentmemory"])) {+ p.log.error(+ `Verification failed: ${COPILOT_MCP_JSON} did not contain mcpServers.agentmemory after write.`,+ );+ return { kind: "skipped", reason: "verification-failed" };+ }++ logInstalled("GitHub Copilot CLI", COPILOT_MCP_JSON);+ p.log.info(+ "Copilot picks up MCP servers on next launch or after `/mcp`. Install the plugin too for full hooks/skills.",+ );+ return {+ kind: "installed",+ mutatedPath: COPILOT_MCP_JSON,+ ...(backupPath !== undefined && { backupPath }),+ };+ },+};diff --git a/src/cli/connect/index.ts b/src/cli/connect/index.tsindex 6fe4f54f..9af6b7d1 100644--- a/src/cli/connect/index.ts+++ b/src/cli/connect/index.ts@@ -4,6 +4,7 @@ import type { ConnectAdapter, ConnectOptions, ConnectResult } from "./types.js";import { adapter as antigravity } from "./antigravity.js";import { adapter as claudeCode } from "./claude-code.js";import { adapter as cline } from "./cline.js";+import { adapter as copilotCli } from "./copilot-cli.js";import { adapter as codex } from "./codex.js";import { adapter as continueDev } from "./continue.js";import { adapter as cursor } from "./cursor.js";@@ -20,6 +21,7 @@ import { adapter as zed } from "./zed.js";export const ADAPTERS: readonly ConnectAdapter[] = [claudeCode,+ copilotCli,codex,cursor,geminiCli,@@ -93,7 +95,10 @@ export async function runAdapter(}export async function runConnect(args: string[]): Promise<void> {- if (platform() === "win32") {+ const { dryRun, force, all, withHooks, positional } = parseFlags(args);+ const allowWindowsAdapter =+ positional.length === 1 && positional[0]?.toLowerCase() === "copilot-cli";+ if (platform() === "win32" && !allowWindowsAdapter) {p.intro("agentmemory connect");p.log.warn("Windows: automated `connect` is not supported yet. See https://github.com/rohitg00/agentmemory#other-agents for manual install steps.",@@ -102,7 +107,6 @@ export async function runConnect(args: string[]): Promise<void> {return;}- const { dryRun, force, all, withHooks, positional } = parseFlags(args);const opts: ConnectOptions = { dryRun, force, withHooks };p.intro("agentmemory connect");diff --git a/src/cli/connect/util.ts b/src/cli/connect/util.tsindex 3a9eda1a..580cd4ee 100644--- a/src/cli/connect/util.ts+++ b/src/cli/connect/util.ts@@ -32,6 +32,28 @@ export const AGENTMEMORY_MCP_BLOCK = {},};+const COPILOT_MCP_COMMAND =+ process.platform === "win32"+ ? {+ command: process.env["ComSpec"] || process.env["COMSPEC"] || "cmd.exe",+ args: ["/d", "/s", "/c", "npx", "-y", "@agentmemory/mcp"],+ }+ : {+ command: "npx",+ args: ["-y", "@agentmemory/mcp"],+ };++export const AGENTMEMORY_COPILOT_MCP_BLOCK = {+ type: "local" as const,+ ...COPILOT_MCP_COMMAND,+ env: {+ AGENTMEMORY_URL: "${AGENTMEMORY_URL:-http://localhost:3111}",+ AGENTMEMORY_SECRET: "${AGENTMEMORY_SECRET:-}",+ AGENTMEMORY_TOOLS: "${AGENTMEMORY_TOOLS:-all}",+ },+ tools: ["*"],+};+export function backupsDir(): string {return join(homedir(), ".agentmemory", "backups");}diff --git a/src/cli/onboarding.ts b/src/cli/onboarding.tsindex 48bbf4cc..2e148a1b 100644--- a/src/cli/onboarding.ts+++ b/src/cli/onboarding.ts@@ -36,6 +36,7 @@ const __dirname = dirname(fileURLToPath(import.meta.url));// where they overlap; the rest fall back to the generic `◇`.const NATIVE_AGENTS: { value: string; label: string; glyph: string }[] = [{ value: "claude-code", label: "Claude Code", glyph: "⟁" },+ { value: "copilot-cli", label: "GitHub Copilot CLI", glyph: "◈" },{ value: "codex", label: "Codex", glyph: "◎" },{ value: "openhuman", label: "OpenHuman", glyph: "◇" },{ value: "openclaw", label: "OpenClaw", glyph: "◇" },@@ -67,7 +68,7 @@ const PROVIDERS: { value: string; label: string; envKey: string | null }[] = [{ value: "skip", label: "Skip — BM25-only mode (no LLM key)", envKey: null },];-function buildAgentOptions(): { value: string; label: string; hint?: string }[] {+export function buildAgentOptions(): { value: string; label: string; hint?: string }[] {return [...NATIVE_AGENTS.map((a) => ({value: a.value,@@ -82,6 +83,15 @@ function buildAgentOptions(): { value: string; label: string; hint?: string }[]];}+export function getInitialAgentValues(+ env: Record<string, string | undefined> = process.env,+): string[] {+ if (env["COPILOT_CLI"] === "1" || env["COPILOT_AGENT_SESSION_ID"]) {+ return ["copilot-cli"];+ }+ return ["claude-code"];+}+// Mirror src/cli.ts findEnvExample so onboarding ships the same .env// skeleton whether called directly or via `agentmemory init`. We// duplicate (rather than import) so the onboarding module doesn't@@ -177,7 +187,7 @@ export async function runOnboarding(): Promise<OnboardingResult> {message: "Which agents will use agentmemory? (space to toggle, enter to confirm)",options: buildAgentOptions(),required: false,- initialValues: ["claude-code"],+ initialValues: getInitialAgentValues(),});if (p.isCancel(agentsPicked)) {p.cancel("Setup cancelled. Re-run any time with: agentmemory --reset");@@ -190,7 +200,7 @@ export async function runOnboarding(): Promise<OnboardingResult> {["━ how this works ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━","All selected agents share the same memory at :3111.",- "A memory saved by Claude Code is visible to Codex + Cursor instantly.",+ "A memory saved by Claude Code is visible to Copilot + Codex + Cursor instantly.","━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━",].join("\n"),);diff --git a/src/hooks/notification.ts b/src/hooks/notification.tsindex daa5a913..9ad77042 100644--- a/src/hooks/notification.ts+++ b/src/hooks/notification.ts@@ -30,9 +30,14 @@ async function main() {}if (isSdkChildContext(data)) return;- if (data.notification_type !== "permission_prompt") return;+ const notificationType = data.notification_type ?? data.notificationType;+ if (notificationType !== "permission_prompt") return;- const sessionId = (data.session_id as string) || "unknown";+ const rawSessionId = data.session_id ?? data.sessionId;+ const sessionId =+ typeof rawSessionId === "string" && rawSessionId.length > 0+ ? rawSessionId+ : "unknown";fetch(`${REST_URL}/agentmemory/observe`, {method: "POST",@@ -44,7 +49,7 @@ async function main() {cwd: (data.cwd as string | undefined) || process.cwd(),timestamp: new Date().toISOString(),data: {- notification_type: data.notification_type,+ notification_type: notificationType,title: data.title,message: data.message,},diff --git a/src/hooks/post-tool-failure.ts b/src/hooks/post-tool-failure.tsindex 9208c415..f0295b3e 100644--- a/src/hooks/post-tool-failure.ts+++ b/src/hooks/post-tool-failure.ts@@ -30,9 +30,12 @@ async function main() {}if (isSdkChildContext(data)) return;- if (data.is_interrupt) return;+ if (data.is_interrupt || data.isInterrupt) return;- const sessionId = (data.session_id as string) || "unknown";+ const sessionId = ((data.session_id || data.sessionId) as string) || "unknown";+ const toolName = data.tool_name ?? data.toolName;+ const toolInput = data.tool_input ?? data.toolArgs;+ const error = data.error ?? data.errorMessage;fetch(`${REST_URL}/agentmemory/observe`, {method: "POST",@@ -44,15 +47,15 @@ async function main() {cwd: (data.cwd as string | undefined) || process.cwd(),timestamp: new Date().toISOString(),data: {- tool_name: data.tool_name,+ tool_name: toolName,tool_input:- typeof data.tool_input === "string"- ? data.tool_input.slice(0, 4000)- : JSON.stringify(data.tool_input ?? "").slice(0, 4000),+ typeof toolInput === "string"+ ? toolInput.slice(0, 4000)+ : JSON.stringify(toolInput ?? "").slice(0, 4000),error:- typeof data.error === "string"- ? data.error.slice(0, 4000)- : JSON.stringify(data.error ?? "").slice(0, 4000),+ typeof error === "string"+ ? error.slice(0, 4000)+ : JSON.stringify(error ?? "").slice(0, 4000),},}),signal: AbortSignal.timeout(3000),diff --git a/src/hooks/post-tool-use.ts b/src/hooks/post-tool-use.tsindex d3e94866..c68a7731 100644--- a/src/hooks/post-tool-use.ts+++ b/src/hooks/post-tool-use.ts@@ -31,11 +31,11 @@ async function main() {if (isSdkChildContext(data)) return;- const sessionId = (data.session_id as string) || "unknown";+ const sessionId = ((data.session_id || data.sessionId) as string) || "unknown";+ const toolName = data.tool_name ?? data.toolName;+ const toolInput = data.tool_input ?? data.toolArgs;- const { imageData, cleanOutput } = extractImageData(- data.tool_response ?? data.tool_output,- );+ const { imageData, cleanOutput } = extractImageData(toolOutput(data));fetch(`${REST_URL}/agentmemory/observe`, {method: "POST",@@ -47,8 +47,8 @@ async function main() {cwd: (data.cwd as string | undefined) || process.cwd(),timestamp: new Date().toISOString(),data: {- tool_name: data.tool_name,- tool_input: data.tool_input,+ tool_name: toolName,+ tool_input: toolInput,tool_output: truncate(cleanOutput, 8000),...(imageData ? { image_data: imageData } : {}),},@@ -58,6 +58,17 @@ async function main() {setTimeout(() => process.exit(0), 500).unref();}+function toolOutput(data: Record<string, unknown>): unknown {+ if (data.tool_response !== undefined) return data.tool_response;+ if (data.tool_output !== undefined) return data.tool_output;+ const result = data.tool_result ?? data.toolResult;+ if (typeof result === "object" && result !== null) {+ const obj = result as Record<string, unknown>;+ return obj.text_result_for_llm ?? obj.textResultForLlm ?? result;+ }+ return result;+}+function isBase64Image(val: unknown): val is string {return typeof val === "string" && (val.startsWith("data:image/") ||diff --git a/src/hooks/pre-compact.ts b/src/hooks/pre-compact.tsindex adcbe9cc..8bb2660c 100644--- a/src/hooks/pre-compact.ts+++ b/src/hooks/pre-compact.ts@@ -31,7 +31,7 @@ async function main() {if (isSdkChildContext(data)) return;- const sessionId = (data.session_id as string) || "unknown";+ const sessionId = ((data.session_id || data.sessionId) as string) || "unknown";const project = resolveProject(data.cwd as string | undefined);if (process.env["CLAUDE_MEMORY_BRIDGE"] === "true") {diff --git a/src/hooks/pre-tool-use.ts b/src/hooks/pre-tool-use.tsindex 38daefc0..277d7799 100644--- a/src/hooks/pre-tool-use.ts+++ b/src/hooks/pre-tool-use.ts@@ -50,16 +50,28 @@ async function main() {if (isSdkChildContext(data)) return;- const toolName = data.tool_name as string;+ const toolName =+ typeof data.tool_name === "string"+ ? data.tool_name+ : typeof data.toolName === "string"+ ? data.toolName+ : undefined;if (!toolName) return;- const fileTools = ["Edit", "Write", "Read", "Glob", "Grep"];- if (!fileTools.includes(toolName)) return;-- const toolInput = (data.tool_input || {}) as Record<string, unknown>;+ const normalizedToolName = toolName.toLowerCase();+ const fileTools = ["edit", "write", "create", "read", "view", "glob", "grep"];+ if (!fileTools.includes(normalizedToolName)) return;++ const rawToolInput = data.tool_input ?? data.toolArgs;+ const toolInput =+ typeof rawToolInput === "object" &&+ rawToolInput !== null &&+ !Array.isArray(rawToolInput)+ ? (rawToolInput as Record<string, unknown>)+ : {};const files: string[] = [];const fileKeys =- toolName === "Grep"+ normalizedToolName === "grep"? ["path", "file"]: ["file_path", "path", "file", "pattern"];for (const key of fileKeys) {@@ -69,19 +81,18 @@ async function main() {if (files.length === 0) return;const terms: string[] = [];- if (toolName === "Grep" || toolName === "Glob") {+ if (normalizedToolName === "grep" || normalizedToolName === "glob") {const pattern = toolInput["pattern"];if (typeof pattern === "string" && pattern.length > 0) {terms.push(pattern);}}- const sessionId = (data.session_id as string) || "unknown";- // Only forward an explicit project field. cwd is an absolute filesystem path- // and must not be used as a project identifier — memories are scoped by short- // project names (e.g. "api", "web"), not paths. Sending a cwd-path as project- // would cause all scoped memories to be incorrectly filtered out on the server- // because the path never matches the stored project name.+ const rawSessionId = data.session_id || data.sessionId;+ const sessionId =+ typeof rawSessionId === "string" && rawSessionId.length > 0+ ? rawSessionId+ : "unknown";const project =typeof data.project === "string" && data.project.trim().length > 0? data.project.trim()diff --git a/src/hooks/prompt-submit.ts b/src/hooks/prompt-submit.tsindex 39ebf4ce..2da8ea6a 100644--- a/src/hooks/prompt-submit.ts+++ b/src/hooks/prompt-submit.ts@@ -31,7 +31,7 @@ async function main() {if (isSdkChildContext(data)) return;- const sessionId = (data.session_id as string) || "unknown";+ const sessionId = ((data.session_id || data.sessionId) as string) || "unknown";fetch(`${REST_URL}/agentmemory/observe`, {method: "POST",@@ -42,7 +42,7 @@ async function main() {project: resolveProject(data.cwd as string | undefined),cwd: (data.cwd as string | undefined) || process.cwd(),timestamp: new Date().toISOString(),- data: { prompt: data.prompt },+ data: { prompt: data.prompt ?? data.userPrompt },}),signal: AbortSignal.timeout(3000),}).catch(() => {});diff --git a/src/hooks/session-end.ts b/src/hooks/session-end.tsindex 60bd9795..6a9fc429 100644--- a/src/hooks/session-end.ts+++ b/src/hooks/session-end.ts@@ -30,7 +30,7 @@ async function main() {if (isSdkChildContext(data)) return;- const sessionId = (data.session_id as string) || "unknown";+ const sessionId = ((data.session_id || data.sessionId) as string) || "unknown";fetch(`${REST_URL}/agentmemory/session/end`, {method: "POST",@@ -66,4 +66,4 @@ async function main() {setTimeout(() => process.exit(0), 1500).unref();}-main();\ No newline at end of file+main();diff --git a/src/hooks/session-start.ts b/src/hooks/session-start.tsindex b20e11be..573c092b 100644--- a/src/hooks/session-start.ts+++ b/src/hooks/session-start.ts@@ -50,7 +50,8 @@ async function main() {if (isSdkChildContext(data)) return;const sessionId =- (data.session_id as string) || `ses_${Date.now().toString(36)}`;+ ((data.session_id || data.sessionId) as string) ||+ `ses_${Date.now().toString(36)}`;const cwd = (data.cwd as string) || process.cwd();const project = resolveProject(data.cwd as string | undefined);diff --git a/src/hooks/stop.ts b/src/hooks/stop.tsindex 2aa39d04..4103796e 100644--- a/src/hooks/stop.ts+++ b/src/hooks/stop.ts@@ -37,7 +37,7 @@ async function main() {return;}- const sessionId = (data.session_id as string) || "unknown";+ const sessionId = ((data.session_id || data.sessionId) as string) || "unknown";fetch(`${REST_URL}/agentmemory/summarize`, {method: "POST",@@ -56,4 +56,4 @@ async function main() {setTimeout(() => process.exit(0), 1500).unref();}-main();\ No newline at end of file+main();diff --git a/src/hooks/subagent-start.ts b/src/hooks/subagent-start.tsindex 53462a74..44c87c85 100644--- a/src/hooks/subagent-start.ts+++ b/src/hooks/subagent-start.ts@@ -39,7 +39,9 @@ async function main() {if (isSdkChildContext(data)) return;- const sessionId = (data.session_id as string) || "unknown";+ const sessionId = ((data.session_id || data.sessionId) as string) || "unknown";+ const agentId = data.agent_id || data.agentName;+ const agentType = data.agent_type || data.agentDisplayName || data.agentName;fetch(`${REST_URL}/agentmemory/observe`, {method: "POST",@@ -51,8 +53,8 @@ async function main() {cwd: (data.cwd as string | undefined) || process.cwd(),timestamp: new Date().toISOString(),data: {- agent_id: data.agent_id,- agent_type: data.agent_type,+ agent_id: agentId,+ agent_type: agentType,},}),signal: AbortSignal.timeout(TIMEOUT_MS),diff --git a/src/hooks/subagent-stop.ts b/src/hooks/subagent-stop.tsindex f03853b0..5a437c9f 100644--- a/src/hooks/subagent-stop.ts+++ b/src/hooks/subagent-stop.ts@@ -31,7 +31,9 @@ async function main() {if (isSdkChildContext(data)) return;- const sessionId = (data.session_id as string) || "unknown";+ const sessionId = ((data.session_id || data.sessionId) as string) || "unknown";+ const agentId = data.agent_id || data.agentName;+ const agentType = data.agent_type || data.agentDisplayName || data.agentName;const lastMsg =typeof data.last_assistant_message === "string"? data.last_assistant_message.slice(0, 4000)@@ -47,8 +49,8 @@ async function main() {cwd: (data.cwd as string | undefined) || process.cwd(),timestamp: new Date().toISOString(),data: {- agent_id: data.agent_id,- agent_type: data.agent_type,+ agent_id: agentId,+ agent_type: agentType,last_message: lastMsg,},}),diff --git a/src/mcp/transport.ts b/src/mcp/transport.tsindex 766e6472..759ed019 100644--- a/src/mcp/transport.ts+++ b/src/mcp/transport.ts@@ -1,5 +1,3 @@-import { createInterface } from "node:readline";-export interface JsonRpcRequest {jsonrpc: "2.0";id?: string | number;@@ -19,6 +17,11 @@ export type RequestHandler = (params: Record<string, unknown>,) => Promise<unknown>;+export interface StdioMessageParser {+ push: (chunk: Buffer | string) => void;+ isFramed: () => boolean;+}+// JSON-RPC 2.0 notifications are messages without an `id` field. The spec// (and the MCP transport contract) requires the server to NOT send a// response for notifications. Some clients tolerate spurious responses;@@ -130,26 +133,131 @@ export async function processLine(}}+function findHeaderEnd(buffer: Buffer): { headerEnd: number; bodyStart: number } | null {+ const crlf = buffer.indexOf("\r\n\r\n");+ const lf = buffer.indexOf("\n\n");+ if (crlf === -1 && lf === -1) return null;+ if (crlf !== -1 && (lf === -1 || crlf <= lf)) {+ return { headerEnd: crlf, bodyStart: crlf + 4 };+ }+ return { headerEnd: lf, bodyStart: lf + 2 };+}++function parseContentLength(header: string): number | null {+ for (const line of header.split(/\r?\n/)) {+ const match = line.match(/^content-length:\s*(\d+)\s*$/i);+ if (match) return Number(match[1]);+ }+ return null;+}++export function formatResponse(+ response: JsonRpcResponse,+ framed: boolean,+): string | Buffer[] {+ const body = JSON.stringify(response);+ if (!framed) return `${body}\n`;+ const bytes = Buffer.from(body, "utf8");+ return [Buffer.from(`Content-Length: ${bytes.length}\r\n\r\n`, "ascii"), bytes];+}++export function createMessageParser(+ onMessage: (message: string) => void,+ writeErr: (msg: string) => void = (msg) => process.stderr.write(msg),+): StdioMessageParser {+ let buffer = Buffer.alloc(0);+ let framed = false;++ function processBuffer(): void {+ while (buffer.length > 0) {+ if (buffer[0] === 10 || buffer[0] === 13) {+ buffer = buffer.subarray(1);+ continue;+ }++ const preview = buffer.toString("ascii", 0, Math.min(buffer.length, 32));+ if (/^content-length:/i.test(preview)) {+ const header = findHeaderEnd(buffer);+ if (!header) return;++ const headerText = buffer.subarray(0, header.headerEnd).toString("ascii");+ const contentLength = parseContentLength(headerText);+ if (contentLength === null) {+ writeErr("[mcp-transport] missing Content-Length header\n");+ buffer = buffer.subarray(header.bodyStart);+ continue;+ }++ const messageEnd = header.bodyStart + contentLength;+ if (buffer.length < messageEnd) return;++ framed = true;+ const message = buffer.subarray(header.bodyStart, messageEnd).toString("utf8");+ buffer = buffer.subarray(messageEnd);+ onMessage(message);+ continue;+ }++ const newline = buffer.indexOf(10);+ if (newline === -1) return;+ const line = buffer+ .subarray(0, newline)+ .toString("utf8")+ .replace(/\r$/, "");+ buffer = buffer.subarray(newline + 1);+ onMessage(line);+ }+ }++ return {+ push(chunk) {+ const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, "utf8");+ buffer = Buffer.concat([buffer, bytes]);+ processBuffer();+ },+ isFramed() {+ return framed;+ },+ };+}+export function createStdioTransport(handler: RequestHandler): {start: () => void;stop: () => void;} {- let rl: ReturnType<typeof createInterface> | null = null;+ let parser: StdioMessageParser | null = null;+ let queue = Promise.resolve();const writeResponse = (response: JsonRpcResponse) => {- process.stdout.write(JSON.stringify(response) + "\n");+ const formatted = formatResponse(response, parser?.isFramed() ?? false);+ if (typeof formatted === "string") {+ process.stdout.write(formatted);+ return;+ }+ for (const chunk of formatted) {+ process.stdout.write(chunk);+ }};- const onLine = (line: string) => processLine(line, handler, writeResponse);+ const onData = (chunk: Buffer) => parser?.push(chunk);return {start() {- rl = createInterface({ input: process.stdin });- rl.on("line", onLine);+ parser = createMessageParser((message) => {+ queue = queue.then(() => processLine(message, handler, writeResponse));+ void queue.catch((err) => {+ process.stderr.write(+ `[mcp-transport] request processing failed: ${+ err instanceof Error ? err.message : String(err)+ }\n`,+ );+ });+ });+ process.stdin.on("data", onData);},stop() {- rl?.close();- rl = null;+ process.stdin.off("data", onData);+ parser = null;},};}diff --git a/test/cli-connect.test.ts b/test/cli-connect.test.tsindex 5f4faff6..49d71919 100644--- a/test/cli-connect.test.ts+++ b/test/cli-connect.test.ts@@ -10,6 +10,17 @@ import {} from "../src/cli/connect/index.js";import type { ConnectAdapter } from "../src/cli/connect/types.js";+const EXPECTED_COPILOT_MCP_COMMAND =+ process.platform === "win32"+ ? {+ command: process.env["ComSpec"] || process.env["COMSPEC"] || "cmd.exe",+ args: ["/d", "/s", "/c", "npx", "-y", "@agentmemory/mcp"],+ }+ : {+ command: "npx",+ args: ["-y", "@agentmemory/mcp"],+ };+describe("agentmemory connect — dispatcher", () => {it("resolves every known agent by lowercase name", () => {for (const name of knownAgents()) {@@ -35,6 +46,7 @@ describe("agentmemory connect — dispatcher", () => {"antigravity","claude-code","cline",+ "copilot-cli","codex","continue","cursor",@@ -50,7 +62,7 @@ describe("agentmemory connect — dispatcher", () => {"zed",].sort(),);- expect(ADAPTERS.length).toBe(16);+ expect(ADAPTERS.length).toBe(17);});it("every adapter exposes detect() and install()", () => {@@ -190,7 +202,198 @@ describe("agentmemory connect — claude-code adapter (mock filesystem)", () =>if (result.kind === "installed") {expect(result.backupPath).toBeDefined();expect(existsSync(result.backupPath!)).toBe(true);- expect(result.backupPath!).toContain(".agentmemory/backups");+ expect(result.backupPath!).toContain(join(".agentmemory", "backups"));+ }+ });+});++describe("agentmemory connect — copilot-cli adapter (mock filesystem)", () => {+ let tmpHome: string;+ let originalHome: string | undefined;+ let originalUserprofile: string | undefined;+ let originalCopilotHome: string | undefined;+ let importCounter = 0;++ beforeEach(() => {+ tmpHome = mkdtempSync(join(tmpdir(), "am-connect-"));+ originalHome = process.env["HOME"];+ originalUserprofile = process.env["USERPROFILE"];+ originalCopilotHome = process.env["COPILOT_HOME"];+ process.env["HOME"] = tmpHome;+ process.env["USERPROFILE"] = tmpHome;+ delete process.env["COPILOT_HOME"];+ vi.resetModules();+ });++ afterEach(() => {+ if (originalHome !== undefined) process.env["HOME"] = originalHome;+ else delete process.env["HOME"];+ if (originalUserprofile !== undefined)+ process.env["USERPROFILE"] = originalUserprofile;+ else delete process.env["USERPROFILE"];+ if (originalCopilotHome !== undefined)+ process.env["COPILOT_HOME"] = originalCopilotHome;+ else delete process.env["COPILOT_HOME"];+ rmSync(tmpHome, { recursive: true, force: true });+ vi.resetModules();+ });++ async function loadAdapter(): Promise<ConnectAdapter> {+ const mod = await import(+ "../src/cli/connect/copilot-cli.js?t=" + Date.now() + "-" + importCounter+++ );+ return (mod as { adapter: ConnectAdapter }).adapter;+ }++ it("detect() returns false when ~/.copilot doesn't exist", async () => {+ const a = await loadAdapter();+ expect(a.detect()).toBe(false);+ });++ it("install() writes mcpServers.agentmemory into ~/.copilot/mcp-config.json and is idempotent", async () => {+ require("node:fs").mkdirSync(join(tmpHome, ".copilot"), { recursive: true });++ const a = await loadAdapter();+ expect(a.detect()).toBe(true);++ const first = await a.install({ dryRun: false, force: false });+ expect(first.kind).toBe("installed");++ const config = JSON.parse(+ readFileSync(join(tmpHome, ".copilot", "mcp-config.json"), "utf-8"),+ );+ expect(config.mcpServers.agentmemory).toEqual({+ type: "local",+ ...EXPECTED_COPILOT_MCP_COMMAND,+ env: {+ AGENTMEMORY_URL: "${AGENTMEMORY_URL:-http://localhost:3111}",+ AGENTMEMORY_SECRET: "${AGENTMEMORY_SECRET:-}",+ AGENTMEMORY_TOOLS: "${AGENTMEMORY_TOOLS:-all}",+ },+ tools: ["*"],+ });++ const second = await a.install({ dryRun: false, force: false });+ expect(second.kind).toBe("already-wired");+ });++ it("honors COPILOT_HOME when locating mcp-config.json", async () => {+ const customCopilotHome = join(tmpHome, "custom-copilot-home");+ process.env["COPILOT_HOME"] = customCopilotHome;+ require("node:fs").mkdirSync(customCopilotHome, { recursive: true });++ const a = await loadAdapter();+ expect(a.detect()).toBe(true);++ const result = await a.install({ dryRun: false, force: false });+ expect(result.kind).toBe("installed");+ expect(result.mutatedPath).toBe(join(customCopilotHome, "mcp-config.json"));+ expect(existsSync(join(customCopilotHome, "mcp-config.json"))).toBe(true);+ expect(existsSync(join(tmpHome, ".copilot", "mcp-config.json"))).toBe(false);+ });++ it("install() preserves unrelated top-level keys and mcpServers entries", async () => {+ require("node:fs").mkdirSync(join(tmpHome, ".copilot"), { recursive: true });+ writeFileSync(+ join(tmpHome, ".copilot", "mcp-config.json"),+ JSON.stringify({+ otherTopLevel: { keep: true },+ mcpServers: { other: { type: "local", command: "other" } },+ }),+ );++ const a = await loadAdapter();+ const result = await a.install({ dryRun: false, force: false });+ expect(result.kind).toBe("installed");++ const config = JSON.parse(+ readFileSync(join(tmpHome, ".copilot", "mcp-config.json"), "utf-8"),+ );+ expect(config.otherTopLevel).toEqual({ keep: true });+ expect(config.mcpServers.other).toEqual({ type: "local", command: "other" });+ expect(config.mcpServers.agentmemory.command).toBe(+ EXPECTED_COPILOT_MCP_COMMAND.command,+ );+ });++ it("install() writes env passthrough block for AGENTMEMORY_URL + AGENTMEMORY_SECRET", async () => {+ require("node:fs").mkdirSync(join(tmpHome, ".copilot"), { recursive: true });++ const a = await loadAdapter();+ const result = await a.install({ dryRun: false, force: false });+ expect(result.kind).toBe("installed");++ const config = JSON.parse(+ readFileSync(join(tmpHome, ".copilot", "mcp-config.json"), "utf-8"),+ );+ const entry = config.mcpServers.agentmemory;+ expect(entry.env.AGENTMEMORY_URL).toBe(+ "${AGENTMEMORY_URL:-http://localhost:3111}",+ );+ expect(entry.env.AGENTMEMORY_SECRET).toBe("${AGENTMEMORY_SECRET:-}");+ expect(entry.env.AGENTMEMORY_TOOLS).toBe("${AGENTMEMORY_TOOLS:-all}");+ });++ it("install() with --force rewrites even when already wired", async () => {+ require("node:fs").mkdirSync(join(tmpHome, ".copilot"), { recursive: true });+ writeFileSync(+ join(tmpHome, ".copilot", "mcp-config.json"),+ JSON.stringify({+ mcpServers: {+ agentmemory: {+ type: "local",+ ...EXPECTED_COPILOT_MCP_COMMAND,+ env: {+ AGENTMEMORY_URL: "${AGENTMEMORY_URL:-http://localhost:3111}",+ AGENTMEMORY_SECRET: "${AGENTMEMORY_SECRET:-}",+ AGENTMEMORY_TOOLS: "${AGENTMEMORY_TOOLS:-all}",+ },+ tools: ["memory_save"],+ },+ },+ }),+ );++ const a = await loadAdapter();+ const result = await a.install({ dryRun: false, force: true });+ expect(result.kind).toBe("installed");++ const config = JSON.parse(+ readFileSync(join(tmpHome, ".copilot", "mcp-config.json"), "utf-8"),+ );+ expect(config.mcpServers.agentmemory.tools).toEqual(["*"]);+ });++ it("install() with --dry-run does not mutate the file", async () => {+ require("node:fs").mkdirSync(join(tmpHome, ".copilot"), { recursive: true });+ const before = JSON.stringify({ mcpServers: {} });+ writeFileSync(join(tmpHome, ".copilot", "mcp-config.json"), before);++ const a = await loadAdapter();+ const result = await a.install({ dryRun: true, force: false });+ expect(result.kind).toBe("installed");++ const after = readFileSync(+ join(tmpHome, ".copilot", "mcp-config.json"),+ "utf-8",+ );+ expect(after).toBe(before);+ });++ it("install() creates a backup file when config pre-exists", async () => {+ require("node:fs").mkdirSync(join(tmpHome, ".copilot"), { recursive: true });+ writeFileSync(+ join(tmpHome, ".copilot", "mcp-config.json"),+ JSON.stringify({ mcpServers: {} }),+ );++ const a = await loadAdapter();+ const result = await a.install({ dryRun: false, force: false });+ expect(result.kind).toBe("installed");+ if (result.kind === "installed") {+ expect(result.backupPath).toBeDefined();+ expect(existsSync(result.backupPath!)).toBe(true);+ expect(result.backupPath!).toContain(join(".agentmemory", "backups"));}});});diff --git a/test/copilot-plugin.test.ts b/test/copilot-plugin.test.tsnew file mode 100644index 00000000..cd01b2d8--- /dev/null+++ b/test/copilot-plugin.test.ts@@ -0,0 +1,380 @@+import { describe, expect, it } from "vitest";+import { readFileSync, existsSync } from "node:fs";+import { join, resolve } from "node:path";+import { createServer } from "node:http";+import { spawn } from "node:child_process";++const repoRoot = resolve(__dirname, "..");+const pluginRoot = join(repoRoot, "plugin");++function readJson<T = unknown>(path: string): T {+ return JSON.parse(readFileSync(path, "utf-8")) as T;+}++const SUPPORTED_COPILOT_EVENTS = new Set([+ "sessionStart",+ "userPromptSubmitted",+ "preToolUse",+ "postToolUse",+ "postToolUseFailure",+ "preCompact",+ "agentStop",+ "sessionEnd",+ "subagentStart",+ "subagentStop",+ "notification",+]);++const REQUIRED_MINIMUM_EVENTS = [+ "sessionStart",+ "userPromptSubmitted",+ "preToolUse",+ "postToolUse",+ "agentStop",+];++const KNOWN_SKILL_DIRS = [+ "recall",+ "remember",+ "session-history",+ "forget",+ "handoff",+ "recap",+ "commit-context",+ "commit-history",+];++describe("Copilot plugin manifest (plugin/plugin.json)", () => {+ it("manifest exists with kebab-case name, version, and required fields", () => {+ const manifestPath = join(pluginRoot, "plugin.json");+ expect(existsSync(manifestPath)).toBe(true);+ const manifest = readJson<{+ name: string;+ version: string;+ description?: string;+ skills?: string;+ mcpServers?: string;+ hooks?: string;+ }>(manifestPath);+ expect(manifest.name).toBe("agentmemory");+ expect(manifest.name).toMatch(/^[a-z][a-z0-9-]*$/);+ expect(manifest.version).toMatch(/^\d+\.\d+\.\d+/);+ expect(manifest.skills).toBeDefined();+ expect(manifest.mcpServers).toBeDefined();+ expect(manifest.hooks).toBeDefined();+ });++ it("manifest version matches main package.json", () => {+ const pkgVer = readJson<{ version: string }>(join(repoRoot, "package.json")).version;+ const pluginVer = readJson<{ version: string }>(+ join(pluginRoot, "plugin.json"),+ ).version;+ expect(pluginVer).toBe(pkgVer);+ });++ it("all referenced manifest paths resolve to existing files / directories", () => {+ const manifest = readJson<{ skills: string; mcpServers: string; hooks: string }>(+ join(pluginRoot, "plugin.json"),+ );+ const manifestDir = pluginRoot;+ expect(existsSync(resolve(manifestDir, manifest.skills))).toBe(true);+ expect(existsSync(resolve(manifestDir, manifest.mcpServers))).toBe(true);+ expect(existsSync(resolve(manifestDir, manifest.hooks))).toBe(true);+ });++ it("skills path resolves and contains all known skill directories", () => {+ const manifest = readJson<{ skills: string }>(join(pluginRoot, "plugin.json"));+ const manifestDir = pluginRoot;+ const skillsPath = resolve(manifestDir, manifest.skills);+ for (const skill of KNOWN_SKILL_DIRS) {+ expect(+ existsSync(join(skillsPath, skill)),+ `missing skill directory: ${skill}`,+ ).toBe(true);+ }+ });+});++describe("Copilot MCP config (.mcp.copilot.json)", () => {+ it("file exists with expected shape", () => {+ const mcpPath = join(pluginRoot, ".mcp.copilot.json");+ expect(existsSync(mcpPath)).toBe(true);+ const config = readJson<{+ mcpServers: {+ agentmemory: {+ type: string;+ command: string;+ args: string[];+ env: Record<string, string>;+ tools: string[];+ };+ };+ }>(mcpPath);+ const server = config.mcpServers.agentmemory;+ expect(server.type).toBe("local");+ expect(server.command).toBe("npx");+ expect(server.args).toEqual(["-y", "@agentmemory/mcp"]);+ expect(server.env["AGENTMEMORY_URL"]).toBe(+ "${AGENTMEMORY_URL:-http://localhost:3111}",+ );+ expect(server.env["AGENTMEMORY_SECRET"]).toBe("${AGENTMEMORY_SECRET:-}");+ expect(server.env["AGENTMEMORY_TOOLS"]).toBe("${AGENTMEMORY_TOOLS:-all}");+ expect(server.tools).toContain("*");+ });+});++describe("Copilot hooks config (hooks/hooks.copilot.json)", () => {+ type HookEntry = {+ type: string;+ command?: string;+ bash?: string;+ powershell?: string;+ matcher?: string;+ };++ function loadHooks() {+ return readJson<{ version: number; hooks: Record<string, HookEntry[]> }>(+ join(pluginRoot, "hooks/hooks.copilot.json"),+ );+ }++ it("has top-level version === 1 and hooks object", () => {+ const config = loadHooks();+ expect(config.version).toBe(1);+ expect(config.hooks).toBeDefined();+ expect(typeof config.hooks).toBe("object");+ });++ it("contains only supported Copilot event names", () => {+ const config = loadHooks();+ for (const event of Object.keys(config.hooks)) {+ expect(+ SUPPORTED_COPILOT_EVENTS.has(event),+ `unsupported event "${event}" in hooks.copilot.json`,+ ).toBe(true);+ }+ });++ it("contains all required minimum events", () => {+ const config = loadHooks();+ const events = Object.keys(config.hooks);+ for (const event of REQUIRED_MINIMUM_EVENTS) {+ expect(events, `missing required event: ${event}`).toContain(event);+ }+ });++ it("PreToolUse entry has the correct matcher", () => {+ const config = loadHooks();+ const preToolEntries = config.hooks["preToolUse"];+ expect(preToolEntries).toBeDefined();+ const withMatcher = preToolEntries.find(+ (e) => e.matcher === "edit|write|create|read|view|glob|grep",+ );+ expect(+ withMatcher,+ "PreToolUse must have matcher edit|write|create|read|view|glob|grep",+ ).toBeDefined();+ });++ it("every handler has type === 'command' and exactly one of command/bash/powershell", () => {+ const config = loadHooks();+ for (const [event, entries] of Object.entries(config.hooks)) {+ for (const handler of entries) {+ expect(handler.type, `${event} handler type`).toBe("command");+ const commandFields = [handler.command, handler.bash, handler.powershell].filter(+ (v): v is string => typeof v === "string" && v.trim().length > 0,+ );+ expect(+ commandFields.length,+ `${event} handler must have exactly one of command/bash/powershell`,+ ).toBe(1);+ }+ }+ });++ it("every referenced script exists on disk", () => {+ const config = loadHooks();+ const scriptRefs = new Set<string>();+ for (const entries of Object.values(config.hooks)) {+ for (const handler of entries) {+ const cmd = handler.command ?? handler.bash ?? handler.powershell ?? "";+ const match = cmd.match(/\$\{(?:COPILOT_PLUGIN_ROOT|CLAUDE_PLUGIN_ROOT)\}\/(scripts\/[^\s]+)/);+ if (match) scriptRefs.add(match[1]);+ }+ }+ expect(scriptRefs.size).toBeGreaterThan(0);+ for (const rel of scriptRefs) {+ expect(existsSync(join(pluginRoot, rel)), `missing hook script: ${rel}`).toBe(true);+ }+ });+});++describe("Copilot hook scripts", () => {+ type ObservedRequest = { path: string; body: Record<string, unknown> };++ async function runHook(+ script: string,+ payload: Record<string, unknown>,+ env: Record<string, string> = {},+ ): Promise<{ requests: ObservedRequest[]; stdout: string }> {+ const requests: ObservedRequest[] = [];+ const server = createServer((req, res) => {+ let raw = "";+ req.on("data", (chunk) => {+ raw += chunk;+ });+ req.on("end", () => {+ requests.push({+ path: req.url ?? "",+ body: raw ? (JSON.parse(raw) as Record<string, unknown>) : {},+ });+ res.writeHead(200, { "Content-Type": "application/json" });+ res.end(JSON.stringify({ context: "remembered context" }));+ });+ });++ await new Promise<void>((resolveServer) => {+ server.listen(0, "127.0.0.1", resolveServer);+ });++ const address = server.address();+ if (!address || typeof address === "string") {+ server.close();+ throw new Error("test server did not bind to a TCP port");+ }++ try {+ const child = spawn(process.execPath, [join(pluginRoot, script)], {+ env: {+ ...process.env,+ AGENTMEMORY_URL: `http://127.0.0.1:${address.port}`,+ AGENTMEMORY_SECRET: "",+ ...env,+ },+ stdio: ["pipe", "pipe", "pipe"],+ });+ let stdout = "";+ let stderr = "";+ child.stdout.on("data", (chunk) => {+ stdout += chunk;+ });+ child.stderr.on("data", (chunk) => {+ stderr += chunk;+ });+ child.stdin.end(JSON.stringify(payload));++ const exitCode = await new Promise<number | null>((resolveExit, reject) => {+ const timeout = setTimeout(() => {+ child.kill();+ reject(new Error(`hook ${script} timed out`));+ }, 5000);+ child.on("error", reject);+ child.on("close", (code) => {+ clearTimeout(timeout);+ resolveExit(code);+ });+ });++ expect(exitCode, stderr).toBe(0);+ return { requests, stdout };+ } finally {+ await new Promise<void>((resolveClose) => {+ server.close(() => resolveClose());+ });+ }+ }++ it("session-start accepts Copilot camelCase sessionId", async () => {+ const result = await runHook(+ "scripts/session-start.mjs",+ { sessionId: "copilot-session", cwd: "C:\\repo" },+ { AGENTMEMORY_INJECT_CONTEXT: "true" },+ );++ expect(result.stdout).toBe("remembered context");+ expect(result.requests[0]?.path).toBe("/agentmemory/session/start");+ expect(result.requests[0]?.body).toMatchObject({+ sessionId: "copilot-session",+ project: "C:\\repo",+ cwd: "C:\\repo",+ });+ });++ it("pre-tool-use narrows Copilot sessionId to strings", async () => {+ const result = await runHook(+ "scripts/pre-tool-use.mjs",+ {+ sessionId: 123,+ toolName: "read",+ toolArgs: { path: "src/index.ts" },+ },+ { AGENTMEMORY_INJECT_CONTEXT: "true" },+ );++ expect(result.stdout).toBe("remembered context");+ expect(result.requests[0]?.path).toBe("/agentmemory/enrich");+ expect(result.requests[0]?.body).toMatchObject({+ sessionId: "unknown",+ files: ["src/index.ts"],+ terms: [],+ toolName: "read",+ });+ });++ it("prompt-submit accepts Copilot camelCase prompt payload", async () => {+ const result = await runHook("scripts/prompt-submit.mjs", {+ sessionId: "copilot-session",+ cwd: "C:\\repo",+ userPrompt: "remember this prompt",+ });++ expect(result.requests[0]?.path).toBe("/agentmemory/observe");+ expect(result.requests[0]?.body).toMatchObject({+ hookType: "prompt_submit",+ sessionId: "copilot-session",+ data: { prompt: "remember this prompt" },+ });+ });++ it("post-tool-failure accepts Copilot camelCase tool and error payloads", async () => {+ const result = await runHook("scripts/post-tool-failure.mjs", {+ sessionId: "copilot-session",+ cwd: "C:\\repo",+ toolName: "edit",+ toolArgs: { filePath: "src/index.ts" },+ errorMessage: "failed",+ });++ expect(result.requests[0]?.path).toBe("/agentmemory/observe");+ expect(result.requests[0]?.body).toMatchObject({+ hookType: "post_tool_failure",+ sessionId: "copilot-session",+ data: {+ tool_name: "edit",+ tool_input: JSON.stringify({ filePath: "src/index.ts" }),+ error: "failed",+ },+ });+ });++ it("notification accepts Copilot camelCase notificationType", async () => {+ const result = await runHook("scripts/notification.mjs", {+ sessionId: "copilot-session",+ cwd: "C:\\repo",+ notificationType: "permission_prompt",+ title: "Tool approval",+ message: "Approve edit",+ });++ expect(result.requests[0]?.path).toBe("/agentmemory/observe");+ expect(result.requests[0]?.body).toMatchObject({+ hookType: "notification",+ sessionId: "copilot-session",+ data: {+ notification_type: "permission_prompt",+ title: "Tool approval",+ message: "Approve edit",+ },+ });+ });+});diff --git a/test/mcp-transport.test.ts b/test/mcp-transport.test.tsindex bb8627dc..006ecc9e 100644--- a/test/mcp-transport.test.ts+++ b/test/mcp-transport.test.ts@@ -1,5 +1,7 @@import { describe, it, expect, vi } from "vitest";import {+ createMessageParser,+ formatResponse,processLine,type JsonRpcResponse,type RequestHandler,@@ -227,3 +229,47 @@ describe("processLine — id type validation (JSON-RPC §4)", () => {expect(c.out[0].result).toEqual({ method: "ping" });});});++describe("stdio framing", () => {+ it("parses Content-Length framed MCP messages split across chunks", () => {+ const messages: string[] = [];+ const parser = createMessageParser((message) => messages.push(message));+ const body = JSON.stringify({ jsonrpc: "2.0", id: 1, method: "initialize" });+ const framed = `Content-Length: ${Buffer.byteLength(body, "utf8")}\r\n\r\n${body}`;++ parser.push(framed.slice(0, 12));+ parser.push(framed.slice(12));++ expect(messages).toEqual([body]);+ expect(parser.isFramed()).toBe(true);+ });++ it("parses newline-delimited JSON for existing clients", () => {+ const messages: string[] = [];+ const parser = createMessageParser((message) => messages.push(message));+ const first = JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/list" });+ const second = JSON.stringify({ jsonrpc: "2.0", method: "notifications/initialized" });++ parser.push(`${first}\n${second}\n`);++ expect(messages).toEqual([first, second]);+ expect(parser.isFramed()).toBe(false);+ });++ it("formats responses with Content-Length framing when requested", () => {+ const response: JsonRpcResponse = {+ jsonrpc: "2.0",+ id: 1,+ result: { ok: true },+ };+ const formatted = formatResponse(response, true);++ expect(Array.isArray(formatted)).toBe(true);+ if (!Array.isArray(formatted)) throw new Error("expected framed response");+ const header = formatted[0].toString("ascii");+ const body = formatted[1].toString("utf8");++ expect(header).toBe(`Content-Length: ${Buffer.byteLength(body, "utf8")}\r\n\r\n`);+ expect(JSON.parse(body)).toEqual(response);+ });+});diff --git a/test/onboarding.test.ts b/test/onboarding.test.tsnew file mode 100644index 00000000..053085b8--- /dev/null+++ b/test/onboarding.test.ts@@ -0,0 +1,27 @@+import { describe, expect, it } from "vitest";++import { buildAgentOptions, getInitialAgentValues } from "../src/cli/onboarding.js";++describe("first-run onboarding", () => {+ it("offers GitHub Copilot CLI as a native setup target", () => {+ const options = buildAgentOptions();+ expect(options).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ value: "copilot-cli",+ label: expect.stringContaining("GitHub Copilot CLI"),+ hint: "native plugin",+ }),+ ]),+ );+ });++ it("selects GitHub Copilot CLI by default when running inside Copilot CLI", () => {+ expect(getInitialAgentValues({ COPILOT_CLI: "1" })).toEqual(["copilot-cli"]);+ expect(getInitialAgentValues({ COPILOT_AGENT_SESSION_ID: "session" })).toEqual(["copilot-cli"]);+ });++ it("keeps Claude Code as the default outside known agent environments", () => {+ expect(getInitialAgentValues({})).toEqual(["claude-code"]);+ });+});