From a5141eb79f090c1fa75fceee25ce262a51907bd0 Mon Sep 17 00:00:00 2001
From: Ross Story
Date: Mon, 18 May 2026 19:45:00 -0700
Subject: [PATCH 1/8] feat: add Copilot CLI plugin asset slice
- plugin/.plugin/plugin.json: Copilot manifest with name/version/skills/mcpServers/hooks refs
- plugin/.mcp.copilot.json: MCP server config with type:local, npx, env passthrough, tools:[*]
- plugin/hooks/hooks.copilot.json: Copilot hooks (version:1) with 11 supported events and PreToolUse matcher
- test/copilot-plugin.test.ts: 11 tests covering manifest, MCP config, and hooks validation
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
---
plugin/.mcp.copilot.json | 14 +++
plugin/.plugin/plugin.json | 15 +++
plugin/hooks/hooks.copilot.json | 72 ++++++++++++
test/copilot-plugin.test.ts | 200 ++++++++++++++++++++++++++++++++
4 files changed, 301 insertions(+)
create mode 100644 plugin/.mcp.copilot.json
create mode 100644 plugin/.plugin/plugin.json
create mode 100644 plugin/hooks/hooks.copilot.json
create mode 100644 test/copilot-plugin.test.ts
diff --git a/plugin/.mcp.copilot.json b/plugin/.mcp.copilot.json
new file mode 100644
index 0000000000..01d03f7d93
--- /dev/null
+++ b/plugin/.mcp.copilot.json
@@ -0,0 +1,14 @@
+{
+ "mcpServers": {
+ "agentmemory": {
+ "type": "local",
+ "command": "npx",
+ "args": ["-y", "@agentmemory/mcp"],
+ "env": {
+ "AGENTMEMORY_URL": "${AGENTMEMORY_URL}",
+ "AGENTMEMORY_SECRET": "${AGENTMEMORY_SECRET}"
+ },
+ "tools": ["*"]
+ }
+ }
+}
diff --git a/plugin/.plugin/plugin.json b/plugin/.plugin/plugin.json
new file mode 100644
index 0000000000..424b688292
--- /dev/null
+++ b/plugin/.plugin/plugin.json
@@ -0,0 +1,15 @@
+{
+ "name": "agentmemory",
+ "version": "0.9.20",
+ "description": "Persistent memory for AI coding agents -- captures tool usage, compresses via LLM, injects context into future sessions. 12 hooks, 53 MCP tools, 4 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/hooks/hooks.copilot.json b/plugin/hooks/hooks.copilot.json
new file mode 100644
index 0000000000..e3baa79581
--- /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"
+ }
+ ],
+ "UserPromptSubmit": [
+ {
+ "type": "command",
+ "command": "node ${COPILOT_PLUGIN_ROOT}/scripts/prompt-submit.mjs"
+ }
+ ],
+ "PreToolUse": [
+ {
+ "type": "command",
+ "matcher": "Edit|Write|Read|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"
+ }
+ ],
+ "Stop": [
+ {
+ "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/test/copilot-plugin.test.ts b/test/copilot-plugin.test.ts
new file mode 100644
index 0000000000..f1e39c965c
--- /dev/null
+++ b/test/copilot-plugin.test.ts
@@ -0,0 +1,200 @@
+import { describe, expect, it } from "vitest";
+import { readFileSync, existsSync } from "node:fs";
+import { join, resolve } from "node:path";
+
+const repoRoot = resolve(__dirname, "..");
+const pluginRoot = join(repoRoot, "plugin");
+
+function readJson(path: string): T {
+ return JSON.parse(readFileSync(path, "utf-8")) as T;
+}
+
+const SUPPORTED_COPILOT_EVENTS = new Set([
+ "SessionStart",
+ "UserPromptSubmit",
+ "PreToolUse",
+ "PostToolUse",
+ "PostToolUseFailure",
+ "PreCompact",
+ "Stop",
+ "SessionEnd",
+ "SubagentStart",
+ "SubagentStop",
+ "Notification",
+]);
+
+const REQUIRED_MINIMUM_EVENTS = [
+ "SessionStart",
+ "UserPromptSubmit",
+ "PreToolUse",
+ "PostToolUse",
+ "Stop",
+];
+
+const KNOWN_SKILL_DIRS = [
+ "recall",
+ "remember",
+ "session-history",
+ "forget",
+ "handoff",
+ "recap",
+ "commit-context",
+ "commit-history",
+];
+
+describe("Copilot plugin manifest (plugin/.plugin/plugin.json)", () => {
+ it("manifest exists with kebab-case name, version, and required fields", () => {
+ const manifestPath = join(pluginRoot, ".plugin/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/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/plugin.json"),
+ );
+ const manifestDir = join(pluginRoot, ".plugin");
+ 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/plugin.json"));
+ const manifestDir = join(pluginRoot, ".plugin");
+ 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;
+ 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}");
+ expect(server.env["AGENTMEMORY_SECRET"]).toBe("${AGENTMEMORY_SECRET}");
+ 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 }>(
+ 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|Read|Glob|Grep");
+ expect(withMatcher, "PreToolUse must have matcher Edit|Write|Read|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 !== undefined,
+ );
+ 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();
+ 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);
+ }
+ });
+});
From 913fb5119f1daaeac4568a9cf8ca1b2bdf595974 Mon Sep 17 00:00:00 2001
From: Ross Story
Date: Mon, 18 May 2026 19:48:46 -0700
Subject: [PATCH 2/8] Add Copilot CLI connect support
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
---
AGENTS.md | 2 +
README.md | 23 ++++-
src/cli.ts | 5 +-
src/cli/connect/copilot-cli.ts | 91 ++++++++++++++++++
src/cli/connect/index.ts | 2 +
src/cli/connect/util.ts | 11 +++
test/cli-connect.test.ts | 169 ++++++++++++++++++++++++++++++++-
7 files changed, 296 insertions(+), 7 deletions(-)
create mode 100644 src/cli/connect/copilot-cli.ts
diff --git a/AGENTS.md b/AGENTS.md
index ebcf35844b..15ef8ac26d 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -19,6 +19,7 @@ agentmemory is a persistent memory system for AI coding agents, built on iii-eng
5. `test/mcp-standalone.test.ts` — tool count assertion
6. `README.md` — tool counts (search for "MCP tools")
7. `plugin/.claude-plugin/plugin.json` — tool count in description
+8. Copilot plugin manifest/config (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-eng
4. `src/functions/export-import.ts` — supportedVersions set
5. `test/export-import.test.ts` — version assertion
6. `plugin/.claude-plugin/plugin.json` — version field
+7. Copilot plugin manifest/config (when present) — version field
**When adding new KV scopes:**
1. `src/state/schema.ts` — add to the KV object
diff --git a/README.md b/README.md
index abfbb6e012..a06261ba4d 100644
--- a/README.md
+++ b/README.md
@@ -7,7 +7,7 @@
Your coding agent remembers everything. No more re-explaining.
Built on iii engine
- 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.
@@ -75,7 +75,7 @@
npm install -g @agentmemory/agentmemory # once — bare `agentmemory` on PATH
agentmemory # start the memory server on :3111
agentmemory 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):
@@ -107,6 +107,11 @@ agentmemory works with any agent that supports hooks, MCP, or REST API. All agen
native plugin + 6 hooks + MCP
+
+GitHub Copilot CLI
+MCP + plugin hooks/skills
+ |
+

OpenClaw
native plugin + MCP
@@ -418,6 +423,18 @@ The Codex plugin ships from the same `plugin/` directory as the Claude Code plug
Codex's hook engine injects `CLAUDE_PLUGIN_ROOT` into hook subprocesses (per [`codex-rs/hooks/src/engine/discovery.rs`](https://github.com/openai/codex/blob/main/codex-rs/hooks/src/engine/discovery.rs)), so the same hook scripts work across both hosts without duplication. Subagent / SessionEnd / Notification / TaskCompleted / PostToolUseFailure events are Claude-Code-only and are not registered for Codex.
+### 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` and preserves existing servers. 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.
+
OpenClaw (paste this prompt)
@@ -489,6 +506,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 install agentmemory`. Registers MCP + 6 lifecycle hooks (SessionStart, UserPromptSubmit, PreToolUse, PostToolUse, PreCompact, Stop) + 4 skills. |
diff --git a/src/cli.ts b/src/cli.ts
index 5eca18cebf..82535abb95 100644
--- a/src/cli.ts
+++ b/src/cli.ts
@@ -117,8 +117,9 @@ Usage: agentmemory [command] [options]
Commands:
(default) Start agentmemory worker
init 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 health
diff --git a/src/cli/connect/copilot-cli.ts b/src/cli/connect/copilot-cli.ts
new file mode 100644
index 0000000000..245ffc9b4c
--- /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 = join(homedir(), ".copilot");
+const COPILOT_MCP_JSON = join(COPILOT_DIR, "mcp-config.json");
+
+type CopilotMcpEntry = typeof AGENTMEMORY_COPILOT_MCP_BLOCK;
+type CopilotConfig = {
+ mcpServers?: Record;
+ [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 {
+ const existing = readJsonSafe(COPILOT_MCP_JSON);
+ const next: CopilotConfig = existing ? { ...existing } : {};
+ const servers: Record = {
+ ...((next.mcpServers as Record) ?? {}),
+ };
+
+ 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(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.ts
index 17aedf8f6f..1f1e38c9e0 100644
--- a/src/cli/connect/index.ts
+++ b/src/cli/connect/index.ts
@@ -2,6 +2,7 @@ import { platform } from "node:os";
import * as p from "@clack/prompts";
import type { ConnectAdapter, ConnectOptions, ConnectResult } from "./types.js";
import { adapter as claudeCode } from "./claude-code.js";
+import { adapter as copilotCli } from "./copilot-cli.js";
import { adapter as codex } from "./codex.js";
import { adapter as cursor } from "./cursor.js";
import { adapter as geminiCli } from "./gemini-cli.js";
@@ -12,6 +13,7 @@ import { adapter as pi } from "./pi.js";
export const ADAPTERS: readonly ConnectAdapter[] = [
claudeCode,
+ copilotCli,
codex,
cursor,
geminiCli,
diff --git a/src/cli/connect/util.ts b/src/cli/connect/util.ts
index 6d5f61ac98..bff7e1a52f 100644
--- a/src/cli/connect/util.ts
+++ b/src/cli/connect/util.ts
@@ -26,6 +26,17 @@ export const AGENTMEMORY_MCP_BLOCK = {
},
};
+export const AGENTMEMORY_COPILOT_MCP_BLOCK = {
+ type: "local" as const,
+ command: "npx",
+ args: ["-y", "@agentmemory/mcp"],
+ env: {
+ AGENTMEMORY_URL: "${AGENTMEMORY_URL}",
+ AGENTMEMORY_SECRET: "${AGENTMEMORY_SECRET}",
+ },
+ tools: ["*"],
+};
+
export function backupsDir(): string {
return join(homedir(), ".agentmemory", "backups");
}
diff --git a/test/cli-connect.test.ts b/test/cli-connect.test.ts
index 99174dacbc..8443f06fb3 100644
--- a/test/cli-connect.test.ts
+++ b/test/cli-connect.test.ts
@@ -29,10 +29,11 @@ describe("agentmemory connect — dispatcher", () => {
expect(resolveAdapter("")).toBeNull();
});
- it("ships exactly the 8 agents specified by the spec", () => {
+ it("ships exactly the 9 agents specified by the spec", () => {
expect(knownAgents().sort()).toEqual(
[
"claude-code",
+ "copilot-cli",
"codex",
"cursor",
"gemini-cli",
@@ -42,7 +43,7 @@ describe("agentmemory connect — dispatcher", () => {
"pi",
].sort(),
);
- expect(ADAPTERS.length).toBe(8);
+ expect(ADAPTERS.length).toBe(9);
});
it("every adapter exposes detect() and install()", () => {
@@ -175,7 +176,169 @@ 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;
+
+ beforeEach(() => {
+ tmpHome = mkdtempSync(join(tmpdir(), "am-connect-"));
+ originalHome = process.env["HOME"];
+ originalUserprofile = process.env["USERPROFILE"];
+ process.env["HOME"] = tmpHome;
+ process.env["USERPROFILE"] = tmpHome;
+ 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"];
+ rmSync(tmpHome, { recursive: true, force: true });
+ vi.resetModules();
+ });
+
+ async function loadAdapter(): Promise {
+ const mod = await import("../src/cli/connect/copilot-cli.js?t=" + Date.now());
+ 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",
+ command: "npx",
+ args: ["-y", "@agentmemory/mcp"],
+ env: {
+ AGENTMEMORY_URL: "${AGENTMEMORY_URL}",
+ AGENTMEMORY_SECRET: "${AGENTMEMORY_SECRET}",
+ },
+ tools: ["*"],
+ });
+
+ const second = await a.install({ dryRun: false, force: false });
+ expect(second.kind).toBe("already-wired");
+ });
+
+ 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("npx");
+ });
+
+ 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}");
+ expect(entry.env.AGENTMEMORY_SECRET).toBe("${AGENTMEMORY_SECRET}");
+ });
+
+ 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",
+ command: "npx",
+ args: ["-y", "@agentmemory/mcp"],
+ env: {
+ AGENTMEMORY_URL: "${AGENTMEMORY_URL}",
+ AGENTMEMORY_SECRET: "${AGENTMEMORY_SECRET}",
+ },
+ 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"));
}
});
});
From 134f8b199f337d9ed31eb89a63626fd7d462aef8 Mon Sep 17 00:00:00 2001
From: Ross Story
Date: Mon, 18 May 2026 20:32:32 -0700
Subject: [PATCH 3/8] Add GitHub Copilot CLI support
Adds Copilot CLI support through a root plugin manifest, Copilot-specific MCP and hook configuration, and a connect adapter for MCP-only setup.
Includes Windows-safe Copilot MCP command generation, COPILOT_HOME handling, Copilot hook payload normalization, generated hook scripts, and targeted tests for plugin shape, hook execution, and connect behavior.
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
---
AGENTS.md | 4 +-
README.md | 2 +-
plugin/hooks/hooks.copilot.json | 24 ++--
plugin/{.plugin => }/plugin.json | 6 +-
plugin/scripts/notification.mjs | 7 +-
plugin/scripts/post-tool-failure.mjs | 13 +-
plugin/scripts/post-tool-use.mjs | 19 ++-
plugin/scripts/pre-compact.mjs | 2 +-
plugin/scripts/pre-tool-use.mjs | 25 ++--
plugin/scripts/prompt-submit.mjs | 4 +-
plugin/scripts/session-end.mjs | 2 +-
plugin/scripts/session-start.mjs | 2 +-
plugin/scripts/stop.mjs | 2 +-
plugin/scripts/subagent-start.mjs | 8 +-
plugin/scripts/subagent-stop.mjs | 8 +-
src/cli/connect/copilot-cli.ts | 2 +-
src/cli/connect/index.ts | 6 +-
src/cli/connect/util.ts | 14 +-
src/hooks/notification.ts | 7 +-
src/hooks/post-tool-failure.ts | 21 +--
src/hooks/post-tool-use.ts | 20 ++-
src/hooks/pre-compact.ts | 2 +-
src/hooks/pre-tool-use.ts | 18 ++-
src/hooks/prompt-submit.ts | 4 +-
src/hooks/session-end.ts | 4 +-
src/hooks/session-start.ts | 3 +-
src/hooks/stop.ts | 4 +-
src/hooks/subagent-start.ts | 8 +-
src/hooks/subagent-stop.ts | 8 +-
test/cli-connect.test.ts | 47 ++++++-
test/copilot-plugin.test.ts | 203 +++++++++++++++++++++++----
31 files changed, 372 insertions(+), 127 deletions(-)
rename plugin/{.plugin => }/plugin.json (81%)
diff --git a/AGENTS.md b/AGENTS.md
index 15ef8ac26d..24e7424542 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -19,7 +19,7 @@ agentmemory is a persistent memory system for AI coding agents, built on iii-eng
5. `test/mcp-standalone.test.ts` — tool count assertion
6. `README.md` — tool counts (search for "MCP tools")
7. `plugin/.claude-plugin/plugin.json` — tool count in description
-8. Copilot plugin manifest/config (when present) — tool count or MCP exposure
+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
@@ -33,7 +33,7 @@ agentmemory is a persistent memory system for AI coding agents, built on iii-eng
4. `src/functions/export-import.ts` — supportedVersions set
5. `test/export-import.test.ts` — version assertion
6. `plugin/.claude-plugin/plugin.json` — version field
-7. Copilot plugin manifest/config (when present) — version field
+7. `plugin/plugin.json` (when present) — version field
**When adding new KV scopes:**
1. `src/state/schema.ts` — add to the KV object
diff --git a/README.md b/README.md
index a06261ba4d..c462746db9 100644
--- a/README.md
+++ b/README.md
@@ -433,7 +433,7 @@ agentmemory connect copilot-cli
copilot plugin install rohitg00/agentmemory:plugin
```
-`agentmemory connect copilot-cli` merges `mcpServers.agentmemory` into `~/.copilot/mcp-config.json` and preserves existing servers. 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.
+`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.
OpenClaw (paste this prompt)
diff --git a/plugin/hooks/hooks.copilot.json b/plugin/hooks/hooks.copilot.json
index e3baa79581..62bd077a4c 100644
--- a/plugin/hooks/hooks.copilot.json
+++ b/plugin/hooks/hooks.copilot.json
@@ -1,68 +1,68 @@
{
"version": 1,
"hooks": {
- "SessionStart": [
+ "sessionStart": [
{
"type": "command",
"command": "node ${COPILOT_PLUGIN_ROOT}/scripts/session-start.mjs"
}
],
- "UserPromptSubmit": [
+ "userPromptSubmitted": [
{
"type": "command",
"command": "node ${COPILOT_PLUGIN_ROOT}/scripts/prompt-submit.mjs"
}
],
- "PreToolUse": [
+ "preToolUse": [
{
"type": "command",
- "matcher": "Edit|Write|Read|Glob|Grep",
+ "matcher": "edit|create|view|glob|grep",
"command": "node ${COPILOT_PLUGIN_ROOT}/scripts/pre-tool-use.mjs"
}
],
- "PostToolUse": [
+ "postToolUse": [
{
"type": "command",
"command": "node ${COPILOT_PLUGIN_ROOT}/scripts/post-tool-use.mjs"
}
],
- "PostToolUseFailure": [
+ "postToolUseFailure": [
{
"type": "command",
"command": "node ${COPILOT_PLUGIN_ROOT}/scripts/post-tool-failure.mjs"
}
],
- "PreCompact": [
+ "preCompact": [
{
"type": "command",
"command": "node ${COPILOT_PLUGIN_ROOT}/scripts/pre-compact.mjs"
}
],
- "Stop": [
+ "agentStop": [
{
"type": "command",
"command": "node ${COPILOT_PLUGIN_ROOT}/scripts/stop.mjs"
}
],
- "SessionEnd": [
+ "sessionEnd": [
{
"type": "command",
"command": "node ${COPILOT_PLUGIN_ROOT}/scripts/session-end.mjs"
}
],
- "SubagentStart": [
+ "subagentStart": [
{
"type": "command",
"command": "node ${COPILOT_PLUGIN_ROOT}/scripts/subagent-start.mjs"
}
],
- "SubagentStop": [
+ "subagentStop": [
{
"type": "command",
"command": "node ${COPILOT_PLUGIN_ROOT}/scripts/subagent-stop.mjs"
}
],
- "Notification": [
+ "notification": [
{
"type": "command",
"command": "node ${COPILOT_PLUGIN_ROOT}/scripts/notification.mjs"
diff --git a/plugin/.plugin/plugin.json b/plugin/plugin.json
similarity index 81%
rename from plugin/.plugin/plugin.json
rename to plugin/plugin.json
index 424b688292..8de92acda7 100644
--- a/plugin/.plugin/plugin.json
+++ b/plugin/plugin.json
@@ -9,7 +9,7 @@
"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"
+ "skills": "skills/",
+ "mcpServers": ".mcp.copilot.json",
+ "hooks": "hooks/hooks.copilot.json"
}
diff --git a/plugin/scripts/notification.mjs b/plugin/scripts/notification.mjs
index a318848d8e..98049a7ab5 100755
--- a/plugin/scripts/notification.mjs
+++ b/plugin/scripts/notification.mjs
@@ -22,8 +22,9 @@ 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 sessionId = data.session_id || data.sessionId || "unknown";
try {
await fetch(`${REST_URL}/agentmemory/observe`, {
method: "POST",
@@ -35,7 +36,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.mjs
index 3a593f3a6d..902a09306f 100755
--- a/plugin/scripts/post-tool-failure.mjs
+++ b/plugin/scripts/post-tool-failure.mjs
@@ -22,8 +22,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;
try {
await fetch(`${REST_URL}/agentmemory/observe`, {
method: "POST",
@@ -35,9 +38,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.mjs
index 5ebec6450f..b1c30d41aa 100755
--- a/plugin/scripts/post-tool-use.mjs
+++ b/plugin/scripts/post-tool-use.mjs
@@ -22,8 +22,10 @@ async function main() {
return;
}
if (isSdkChildContext(data)) return;
- const sessionId = data.session_id || "unknown";
- const { imageData, cleanOutput } = extractImageData(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));
try {
await fetch(`${REST_URL}/agentmemory/observe`, {
method: "POST",
@@ -35,8 +37,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 } : {}
}
@@ -45,6 +47,15 @@ async function main() {
});
} catch {}
}
+function toolOutput(data) {
+ 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.mjs
index bff9e7fae2..b68bf025ef 100755
--- a/plugin/scripts/pre-compact.mjs
+++ b/plugin/scripts/pre-compact.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";
const project = data.cwd || process.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.mjs
index 561b6b0d54..cab44fb826 100755
--- a/plugin/scripts/pre-tool-use.mjs
+++ b/plugin/scripts/pre-tool-use.mjs
@@ -24,18 +24,21 @@ async function main() {
return;
}
if (isSdkChildContext(data)) return;
- const toolName = data.tool_name;
+ const toolName = typeof data.tool_name === "string" ? data.tool_name : data.toolName;
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 toolInput = data.tool_input || data.toolArgs || {};
const files = [];
- const fileKeys = toolName === "Grep" ? ["path", "file"] : [
+ const fileKeys = normalizedToolName === "grep" ? ["path", "file"] : [
"file_path",
"path",
"file",
@@ -47,11 +50,11 @@ 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 sessionId = data.session_id || data.sessionId || "unknown";
try {
const res = await fetch(`${REST_URL}/agentmemory/enrich`, {
method: "POST",
diff --git a/plugin/scripts/prompt-submit.mjs b/plugin/scripts/prompt-submit.mjs
index 18aa040a3a..a8a61192cc 100755
--- a/plugin/scripts/prompt-submit.mjs
+++ b/plugin/scripts/prompt-submit.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";
try {
await fetch(`${REST_URL}/agentmemory/observe`, {
method: "POST",
@@ -33,7 +33,7 @@ async function main() {
project: data.cwd || process.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)
});
diff --git a/plugin/scripts/session-end.mjs b/plugin/scripts/session-end.mjs
index 8e1de092e8..7707e357dc 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";
try {
await fetch(`${REST_URL}/agentmemory/session/end`, {
method: "POST",
diff --git a/plugin/scripts/session-start.mjs b/plugin/scripts/session-start.mjs
index 9e573e241f..f1ec1be64b 100755
--- a/plugin/scripts/session-start.mjs
+++ b/plugin/scripts/session-start.mjs
@@ -25,7 +25,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 project = data.cwd || process.cwd();
const url = `${REST_URL}/agentmemory/session/start`;
const init = {
diff --git a/plugin/scripts/stop.mjs b/plugin/scripts/stop.mjs
index e0ffa35058..3fe5cb3623 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";
try {
await fetch(`${REST_URL}/agentmemory/summarize`, {
method: "POST",
diff --git a/plugin/scripts/subagent-start.mjs b/plugin/scripts/subagent-start.mjs
index db14345993..b9872d8b2d 100755
--- a/plugin/scripts/subagent-start.mjs
+++ b/plugin/scripts/subagent-start.mjs
@@ -23,7 +23,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(),
@@ -34,8 +36,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.mjs
index 7ec66a7d43..a04b068fc5 100755
--- a/plugin/scripts/subagent-stop.mjs
+++ b/plugin/scripts/subagent-stop.mjs
@@ -22,7 +22,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) : "";
try {
await fetch(`${REST_URL}/agentmemory/observe`, {
@@ -35,8 +37,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/connect/copilot-cli.ts b/src/cli/connect/copilot-cli.ts
index 245ffc9b4c..8cce5a5422 100644
--- a/src/cli/connect/copilot-cli.ts
+++ b/src/cli/connect/copilot-cli.ts
@@ -13,7 +13,7 @@ import {
writeJsonAtomic,
} from "./util.js";
-const COPILOT_DIR = join(homedir(), ".copilot");
+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;
diff --git a/src/cli/connect/index.ts b/src/cli/connect/index.ts
index 1f1e38c9e0..e9db9fc566 100644
--- a/src/cli/connect/index.ts
+++ b/src/cli/connect/index.ts
@@ -76,7 +76,10 @@ export async function runAdapter(
}
export async function runConnect(args: string[]): Promise {
- if (platform() === "win32") {
+ const { dryRun, force, all, 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.",
@@ -85,7 +88,6 @@ export async function runConnect(args: string[]): Promise {
return;
}
- const { dryRun, force, all, positional } = parseFlags(args);
const opts: ConnectOptions = { dryRun, force };
p.intro("agentmemory connect");
diff --git a/src/cli/connect/util.ts b/src/cli/connect/util.ts
index bff7e1a52f..8902e3ef97 100644
--- a/src/cli/connect/util.ts
+++ b/src/cli/connect/util.ts
@@ -26,10 +26,20 @@ 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,
- command: "npx",
- args: ["-y", "@agentmemory/mcp"],
+ ...COPILOT_MCP_COMMAND,
env: {
AGENTMEMORY_URL: "${AGENTMEMORY_URL}",
AGENTMEMORY_SECRET: "${AGENTMEMORY_SECRET}",
diff --git a/src/hooks/notification.ts b/src/hooks/notification.ts
index 6c4b7b81fb..42ef594c5c 100644
--- a/src/hooks/notification.ts
+++ b/src/hooks/notification.ts
@@ -29,9 +29,10 @@ 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 sessionId = ((data.session_id || data.sessionId) as string) || "unknown";
try {
await fetch(`${REST_URL}/agentmemory/observe`, {
@@ -44,7 +45,7 @@ async function main() {
cwd: data.cwd || 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.ts
index 337aebdd1c..7fa71d0524 100644
--- a/src/hooks/post-tool-failure.ts
+++ b/src/hooks/post-tool-failure.ts
@@ -29,9 +29,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;
try {
await fetch(`${REST_URL}/agentmemory/observe`, {
@@ -44,15 +47,15 @@ async function main() {
cwd: data.cwd || 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.ts
index 65afc8b1dc..512ef8441c 100644
--- a/src/hooks/post-tool-use.ts
+++ b/src/hooks/post-tool-use.ts
@@ -30,9 +30,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_output);
+ const { imageData, cleanOutput } = extractImageData(toolOutput(data));
try {
await fetch(`${REST_URL}/agentmemory/observe`, {
@@ -45,8 +47,8 @@ async function main() {
cwd: data.cwd || 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 } : {}),
},
@@ -57,6 +59,16 @@ async function main() {
}
}
+function toolOutput(data: Record): unknown {
+ 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;
+ 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.ts
index ea13ebec29..77fb7a57ed 100644
--- a/src/hooks/pre-compact.ts
+++ b/src/hooks/pre-compact.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";
const project = (data.cwd as string) || process.cwd();
if (process.env["CLAUDE_MEMORY_BRIDGE"] === "true") {
diff --git a/src/hooks/pre-tool-use.ts b/src/hooks/pre-tool-use.ts
index 61f6c443f8..6fbf34b858 100644
--- a/src/hooks/pre-tool-use.ts
+++ b/src/hooks/pre-tool-use.ts
@@ -50,16 +50,20 @@ async function main() {
if (isSdkChildContext(data)) return;
- const toolName = data.tool_name as string;
+ const toolName =
+ typeof data.tool_name === "string"
+ ? data.tool_name
+ : (data.toolName as string);
if (!toolName) return;
- const fileTools = ["Edit", "Write", "Read", "Glob", "Grep"];
- if (!fileTools.includes(toolName)) return;
+ const normalizedToolName = toolName.toLowerCase();
+ const fileTools = ["edit", "write", "create", "read", "view", "glob", "grep"];
+ if (!fileTools.includes(normalizedToolName)) return;
- const toolInput = (data.tool_input || {}) as Record;
+ const toolInput = (data.tool_input || data.toolArgs || {}) as Record;
const files: string[] = [];
const fileKeys =
- toolName === "Grep"
+ normalizedToolName === "grep"
? ["path", "file"]
: ["file_path", "path", "file", "pattern"];
for (const key of fileKeys) {
@@ -69,14 +73,14 @@ 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";
+ const sessionId = ((data.session_id || data.sessionId) as string) || "unknown";
try {
const res = await fetch(`${REST_URL}/agentmemory/enrich`, {
diff --git a/src/hooks/prompt-submit.ts b/src/hooks/prompt-submit.ts
index 971b11be1f..10265a77d6 100644
--- a/src/hooks/prompt-submit.ts
+++ b/src/hooks/prompt-submit.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";
try {
await fetch(`${REST_URL}/agentmemory/observe`, {
@@ -42,7 +42,7 @@ async function main() {
project: data.cwd || process.cwd(),
cwd: data.cwd || process.cwd(),
timestamp: new Date().toISOString(),
- data: { prompt: data.prompt },
+ data: { prompt: data.prompt ?? data.userPrompt },
}),
signal: AbortSignal.timeout(3000),
});
diff --git a/src/hooks/session-end.ts b/src/hooks/session-end.ts
index 31bef22e00..7efa550eb1 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";
try {
await fetch(`${REST_URL}/agentmemory/session/end`, {
@@ -76,4 +76,4 @@ async function main() {
}
}
-main();
\ No newline at end of file
+main();
diff --git a/src/hooks/session-start.ts b/src/hooks/session-start.ts
index a6cefe41a2..444edc32af 100644
--- a/src/hooks/session-start.ts
+++ b/src/hooks/session-start.ts
@@ -49,7 +49,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 project = (data.cwd as string) || process.cwd();
const url = `${REST_URL}/agentmemory/session/start`;
diff --git a/src/hooks/stop.ts b/src/hooks/stop.ts
index 1f2f5b8a69..18ca371dc2 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";
try {
await fetch(`${REST_URL}/agentmemory/summarize`, {
@@ -51,4 +51,4 @@ async function main() {
}
}
-main();
\ No newline at end of file
+main();
diff --git a/src/hooks/subagent-start.ts b/src/hooks/subagent-start.ts
index 3f730adb60..f3f560bcac 100644
--- a/src/hooks/subagent-start.ts
+++ b/src/hooks/subagent-start.ts
@@ -38,7 +38,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",
@@ -50,8 +52,8 @@ async function main() {
cwd: data.cwd || 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.ts
index c555746e7b..1f41e5a45c 100644
--- a/src/hooks/subagent-stop.ts
+++ b/src/hooks/subagent-stop.ts
@@ -30,7 +30,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 || 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/test/cli-connect.test.ts b/test/cli-connect.test.ts
index 8443f06fb3..fbb8c2b55c 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()) {
@@ -185,13 +196,17 @@ 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();
});
@@ -201,12 +216,17 @@ describe("agentmemory connect — copilot-cli adapter (mock filesystem)", () =>
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 {
- const mod = await import("../src/cli/connect/copilot-cli.js?t=" + Date.now());
+ const mod = await import(
+ "../src/cli/connect/copilot-cli.js?t=" + Date.now() + "-" + importCounter++
+ );
return (mod as { adapter: ConnectAdapter }).adapter;
}
@@ -229,8 +249,7 @@ describe("agentmemory connect — copilot-cli adapter (mock filesystem)", () =>
);
expect(config.mcpServers.agentmemory).toEqual({
type: "local",
- command: "npx",
- args: ["-y", "@agentmemory/mcp"],
+ ...EXPECTED_COPILOT_MCP_COMMAND,
env: {
AGENTMEMORY_URL: "${AGENTMEMORY_URL}",
AGENTMEMORY_SECRET: "${AGENTMEMORY_SECRET}",
@@ -242,6 +261,21 @@ describe("agentmemory connect — copilot-cli adapter (mock filesystem)", () =>
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(
@@ -261,7 +295,9 @@ describe("agentmemory connect — copilot-cli adapter (mock filesystem)", () =>
);
expect(config.otherTopLevel).toEqual({ keep: true });
expect(config.mcpServers.other).toEqual({ type: "local", command: "other" });
- expect(config.mcpServers.agentmemory.command).toBe("npx");
+ expect(config.mcpServers.agentmemory.command).toBe(
+ EXPECTED_COPILOT_MCP_COMMAND.command,
+ );
});
it("install() writes env passthrough block for AGENTMEMORY_URL + AGENTMEMORY_SECRET", async () => {
@@ -287,8 +323,7 @@ describe("agentmemory connect — copilot-cli adapter (mock filesystem)", () =>
mcpServers: {
agentmemory: {
type: "local",
- command: "npx",
- args: ["-y", "@agentmemory/mcp"],
+ ...EXPECTED_COPILOT_MCP_COMMAND,
env: {
AGENTMEMORY_URL: "${AGENTMEMORY_URL}",
AGENTMEMORY_SECRET: "${AGENTMEMORY_SECRET}",
diff --git a/test/copilot-plugin.test.ts b/test/copilot-plugin.test.ts
index f1e39c965c..dc734e1eb9 100644
--- a/test/copilot-plugin.test.ts
+++ b/test/copilot-plugin.test.ts
@@ -1,6 +1,8 @@
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");
@@ -10,25 +12,25 @@ function readJson(path: string): T {
}
const SUPPORTED_COPILOT_EVENTS = new Set([
- "SessionStart",
- "UserPromptSubmit",
- "PreToolUse",
- "PostToolUse",
- "PostToolUseFailure",
- "PreCompact",
- "Stop",
- "SessionEnd",
- "SubagentStart",
- "SubagentStop",
- "Notification",
+ "sessionStart",
+ "userPromptSubmitted",
+ "preToolUse",
+ "postToolUse",
+ "postToolUseFailure",
+ "preCompact",
+ "agentStop",
+ "sessionEnd",
+ "subagentStart",
+ "subagentStop",
+ "notification",
]);
const REQUIRED_MINIMUM_EVENTS = [
- "SessionStart",
- "UserPromptSubmit",
- "PreToolUse",
- "PostToolUse",
- "Stop",
+ "sessionStart",
+ "userPromptSubmitted",
+ "preToolUse",
+ "postToolUse",
+ "agentStop",
];
const KNOWN_SKILL_DIRS = [
@@ -42,9 +44,9 @@ const KNOWN_SKILL_DIRS = [
"commit-history",
];
-describe("Copilot plugin manifest (plugin/.plugin/plugin.json)", () => {
+describe("Copilot plugin manifest (plugin/plugin.json)", () => {
it("manifest exists with kebab-case name, version, and required fields", () => {
- const manifestPath = join(pluginRoot, ".plugin/plugin.json");
+ const manifestPath = join(pluginRoot, "plugin.json");
expect(existsSync(manifestPath)).toBe(true);
const manifest = readJson<{
name: string;
@@ -65,24 +67,24 @@ describe("Copilot plugin manifest (plugin/.plugin/plugin.json)", () => {
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/plugin.json"),
+ 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/plugin.json"),
+ join(pluginRoot, "plugin.json"),
);
- const manifestDir = join(pluginRoot, ".plugin");
+ 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/plugin.json"));
- const manifestDir = join(pluginRoot, ".plugin");
+ 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(
@@ -160,10 +162,10 @@ describe("Copilot hooks config (hooks/hooks.copilot.json)", () => {
it("PreToolUse entry has the correct matcher", () => {
const config = loadHooks();
- const preToolEntries = config.hooks["PreToolUse"];
+ const preToolEntries = config.hooks["preToolUse"];
expect(preToolEntries).toBeDefined();
- const withMatcher = preToolEntries.find((e) => e.matcher === "Edit|Write|Read|Glob|Grep");
- expect(withMatcher, "PreToolUse must have matcher Edit|Write|Read|Glob|Grep").toBeDefined();
+ const withMatcher = preToolEntries.find((e) => e.matcher === "edit|create|view|glob|grep");
+ expect(withMatcher, "PreToolUse must have matcher edit|create|view|glob|grep").toBeDefined();
});
it("every handler has type === 'command' and exactly one of command/bash/powershell", () => {
@@ -198,3 +200,152 @@ describe("Copilot hooks config (hooks/hooks.copilot.json)", () => {
}
});
});
+
+describe("Copilot hook scripts", () => {
+ type ObservedRequest = { path: string; body: Record };
+
+ async function runHook(
+ script: string,
+ payload: Record,
+ env: Record = {},
+ ): 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) : {},
+ });
+ res.writeHead(200, { "Content-Type": "application/json" });
+ res.end(JSON.stringify({ context: "remembered context" }));
+ });
+ });
+
+ await new Promise((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((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((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("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",
+ },
+ });
+ });
+});
From 46b0e86f3eebc4c19974840cbba9949d8fa61f0a Mon Sep 17 00:00:00 2001
From: Ross Story
Date: Tue, 19 May 2026 02:04:50 -0700
Subject: [PATCH 4/8] Harden Copilot hook handling
Addresses upstream AI review suggestions by aligning the Copilot preToolUse matcher with the hook allowlist, narrowing hook payload fields at runtime, normalizing subagent fallbacks, and tightening hook config validation.
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
---
plugin/hooks/hooks.copilot.json | 2 +-
plugin/scripts/notification.mjs | 3 ++-
plugin/scripts/pre-tool-use.mjs | 5 +++--
plugin/scripts/subagent-start.mjs | 4 ++--
plugin/scripts/subagent-stop.mjs | 4 ++--
src/hooks/notification.ts | 6 +++++-
src/hooks/pre-tool-use.ts | 12 ++++++++++--
src/hooks/subagent-start.ts | 4 ++--
src/hooks/subagent-stop.ts | 4 ++--
test/copilot-plugin.test.ts | 11 ++++++++---
10 files changed, 37 insertions(+), 18 deletions(-)
diff --git a/plugin/hooks/hooks.copilot.json b/plugin/hooks/hooks.copilot.json
index 62bd077a4c..b7d09f8bcf 100644
--- a/plugin/hooks/hooks.copilot.json
+++ b/plugin/hooks/hooks.copilot.json
@@ -16,7 +16,7 @@
"preToolUse": [
{
"type": "command",
- "matcher": "edit|create|view|glob|grep",
+ "matcher": "edit|write|create|read|view|glob|grep",
"command": "node ${COPILOT_PLUGIN_ROOT}/scripts/pre-tool-use.mjs"
}
],
diff --git a/plugin/scripts/notification.mjs b/plugin/scripts/notification.mjs
index 98049a7ab5..8ba2c9b033 100755
--- a/plugin/scripts/notification.mjs
+++ b/plugin/scripts/notification.mjs
@@ -24,7 +24,8 @@ async function main() {
if (isSdkChildContext(data)) return;
const notificationType = data.notification_type ?? data.notificationType;
if (notificationType !== "permission_prompt") return;
- const sessionId = data.session_id || data.sessionId || "unknown";
+ const rawSessionId = data.session_id ?? data.sessionId;
+ const sessionId = typeof rawSessionId === "string" && rawSessionId.length > 0 ? rawSessionId : "unknown";
try {
await fetch(`${REST_URL}/agentmemory/observe`, {
method: "POST",
diff --git a/plugin/scripts/pre-tool-use.mjs b/plugin/scripts/pre-tool-use.mjs
index cab44fb826..3d9dd98622 100755
--- a/plugin/scripts/pre-tool-use.mjs
+++ b/plugin/scripts/pre-tool-use.mjs
@@ -24,7 +24,7 @@ async function main() {
return;
}
if (isSdkChildContext(data)) return;
- const toolName = typeof data.tool_name === "string" ? data.tool_name : data.toolName;
+ 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 (![
@@ -36,7 +36,8 @@ async function main() {
"glob",
"grep"
].includes(normalizedToolName)) return;
- const toolInput = data.tool_input || data.toolArgs || {};
+ const rawToolInput = data.tool_input ?? data.toolArgs;
+ const toolInput = typeof rawToolInput === "object" && rawToolInput !== null && !Array.isArray(rawToolInput) ? rawToolInput : {};
const files = [];
const fileKeys = normalizedToolName === "grep" ? ["path", "file"] : [
"file_path",
diff --git a/plugin/scripts/subagent-start.mjs b/plugin/scripts/subagent-start.mjs
index b9872d8b2d..c0d0b5ebc9 100755
--- a/plugin/scripts/subagent-start.mjs
+++ b/plugin/scripts/subagent-start.mjs
@@ -24,8 +24,8 @@ async function main() {
}
if (isSdkChildContext(data)) return;
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 agentId = data.agent_id || data.agentName;
+ const agentType = data.agent_type || data.agentDisplayName || data.agentName;
fetch(`${REST_URL}/agentmemory/observe`, {
method: "POST",
headers: authHeaders(),
diff --git a/plugin/scripts/subagent-stop.mjs b/plugin/scripts/subagent-stop.mjs
index a04b068fc5..8765756dea 100755
--- a/plugin/scripts/subagent-stop.mjs
+++ b/plugin/scripts/subagent-stop.mjs
@@ -23,8 +23,8 @@ async function main() {
}
if (isSdkChildContext(data)) return;
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 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) : "";
try {
await fetch(`${REST_URL}/agentmemory/observe`, {
diff --git a/src/hooks/notification.ts b/src/hooks/notification.ts
index 42ef594c5c..51347d50ef 100644
--- a/src/hooks/notification.ts
+++ b/src/hooks/notification.ts
@@ -32,7 +32,11 @@ async function main() {
const notificationType = data.notification_type ?? data.notificationType;
if (notificationType !== "permission_prompt") return;
- const sessionId = ((data.session_id || data.sessionId) as string) || "unknown";
+ const rawSessionId = data.session_id ?? data.sessionId;
+ const sessionId =
+ typeof rawSessionId === "string" && rawSessionId.length > 0
+ ? rawSessionId
+ : "unknown";
try {
await fetch(`${REST_URL}/agentmemory/observe`, {
diff --git a/src/hooks/pre-tool-use.ts b/src/hooks/pre-tool-use.ts
index 6fbf34b858..63061b3df4 100644
--- a/src/hooks/pre-tool-use.ts
+++ b/src/hooks/pre-tool-use.ts
@@ -53,14 +53,22 @@ async function main() {
const toolName =
typeof data.tool_name === "string"
? data.tool_name
- : (data.toolName as string);
+ : typeof data.toolName === "string"
+ ? data.toolName
+ : undefined;
if (!toolName) return;
const normalizedToolName = toolName.toLowerCase();
const fileTools = ["edit", "write", "create", "read", "view", "glob", "grep"];
if (!fileTools.includes(normalizedToolName)) return;
- const toolInput = (data.tool_input || data.toolArgs || {}) as Record;
+ const rawToolInput = data.tool_input ?? data.toolArgs;
+ const toolInput =
+ typeof rawToolInput === "object" &&
+ rawToolInput !== null &&
+ !Array.isArray(rawToolInput)
+ ? (rawToolInput as Record)
+ : {};
const files: string[] = [];
const fileKeys =
normalizedToolName === "grep"
diff --git a/src/hooks/subagent-start.ts b/src/hooks/subagent-start.ts
index f3f560bcac..3463da0bc2 100644
--- a/src/hooks/subagent-start.ts
+++ b/src/hooks/subagent-start.ts
@@ -39,8 +39,8 @@ async function main() {
if (isSdkChildContext(data)) return;
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 agentId = data.agent_id || data.agentName;
+ const agentType = data.agent_type || data.agentDisplayName || data.agentName;
fetch(`${REST_URL}/agentmemory/observe`, {
method: "POST",
diff --git a/src/hooks/subagent-stop.ts b/src/hooks/subagent-stop.ts
index 1f41e5a45c..90b99fd6a9 100644
--- a/src/hooks/subagent-stop.ts
+++ b/src/hooks/subagent-stop.ts
@@ -31,8 +31,8 @@ async function main() {
if (isSdkChildContext(data)) return;
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 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)
diff --git a/test/copilot-plugin.test.ts b/test/copilot-plugin.test.ts
index dc734e1eb9..4956d2ac09 100644
--- a/test/copilot-plugin.test.ts
+++ b/test/copilot-plugin.test.ts
@@ -164,8 +164,13 @@ describe("Copilot hooks config (hooks/hooks.copilot.json)", () => {
const config = loadHooks();
const preToolEntries = config.hooks["preToolUse"];
expect(preToolEntries).toBeDefined();
- const withMatcher = preToolEntries.find((e) => e.matcher === "edit|create|view|glob|grep");
- expect(withMatcher, "PreToolUse must have matcher edit|create|view|glob|grep").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", () => {
@@ -174,7 +179,7 @@ describe("Copilot hooks config (hooks/hooks.copilot.json)", () => {
for (const handler of entries) {
expect(handler.type, `${event} handler type`).toBe("command");
const commandFields = [handler.command, handler.bash, handler.powershell].filter(
- (v) => v !== undefined,
+ (v): v is string => typeof v === "string" && v.trim().length > 0,
);
expect(
commandFields.length,
From 71f4c6b3b3c008be851077cba45f1968b3f9ee4a Mon Sep 17 00:00:00 2001
From: Ross Story
Date: Tue, 19 May 2026 02:25:57 -0700
Subject: [PATCH 5/8] Add Copilot to first-run onboarding
Includes GitHub Copilot CLI in the first-run agent picker and adds a regression test so the Copilot setup path remains discoverable.
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
---
src/cli/onboarding.ts | 5 +++--
test/onboarding.test.ts | 18 ++++++++++++++++++
2 files changed, 21 insertions(+), 2 deletions(-)
create mode 100644 test/onboarding.test.ts
diff --git a/src/cli/onboarding.ts b/src/cli/onboarding.ts
index 92b23d620a..50fe9d4711 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,
@@ -166,7 +167,7 @@ export async function runOnboarding(): Promise {
[
"━ 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/test/onboarding.test.ts b/test/onboarding.test.ts
new file mode 100644
index 0000000000..a706dc0660
--- /dev/null
+++ b/test/onboarding.test.ts
@@ -0,0 +1,18 @@
+import { describe, expect, it } from "vitest";
+
+import { buildAgentOptions } 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",
+ }),
+ ]),
+ );
+ });
+});
From 11a0200334b2a44b135123e31fae8f6880621507 Mon Sep 17 00:00:00 2001
From: Ross Story
Date: Tue, 19 May 2026 02:38:50 -0700
Subject: [PATCH 6/8] Default onboarding to Copilot inside Copilot CLI
Detect Copilot CLI environment markers during first-run setup so pressing Enter wires the current agent instead of the historical Claude Code default.
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
---
src/cli/onboarding.ts | 11 ++++++++++-
test/onboarding.test.ts | 11 ++++++++++-
2 files changed, 20 insertions(+), 2 deletions(-)
diff --git a/src/cli/onboarding.ts b/src/cli/onboarding.ts
index 50fe9d4711..76c446de16 100644
--- a/src/cli/onboarding.ts
+++ b/src/cli/onboarding.ts
@@ -83,6 +83,15 @@ export function buildAgentOptions(): { value: string; label: string; hint?: stri
];
}
+export function getInitialAgentValues(
+ env: Record = 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
@@ -154,7 +163,7 @@ export async function runOnboarding(): Promise {
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");
diff --git a/test/onboarding.test.ts b/test/onboarding.test.ts
index a706dc0660..053085b810 100644
--- a/test/onboarding.test.ts
+++ b/test/onboarding.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
-import { buildAgentOptions } from "../src/cli/onboarding.js";
+import { buildAgentOptions, getInitialAgentValues } from "../src/cli/onboarding.js";
describe("first-run onboarding", () => {
it("offers GitHub Copilot CLI as a native setup target", () => {
@@ -15,4 +15,13 @@ describe("first-run onboarding", () => {
]),
);
});
+
+ 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"]);
+ });
});
From c21bb069ecc46ff372ceb1f523ba5450b28b6f40 Mon Sep 17 00:00:00 2001
From: Ross Story
Date: Tue, 19 May 2026 03:17:32 -0700
Subject: [PATCH 7/8] Support framed stdio MCP transport
Accept Content-Length framed JSON-RPC messages in addition to the existing newline-delimited transport so Copilot CLI can initialize the standalone MCP server.
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
---
src/mcp/transport.ts | 126 ++++++++++++++++++++++++++++++++++---
test/mcp-transport.test.ts | 46 ++++++++++++++
2 files changed, 163 insertions(+), 9 deletions(-)
diff --git a/src/mcp/transport.ts b/src/mcp/transport.ts
index 766e647222..759ed01929 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,
) => Promise;
+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 | 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/mcp-transport.test.ts b/test/mcp-transport.test.ts
index bb8627dcd6..006ecc9eb0 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);
+ });
+});
From 0ba3af4b01da27e1450ddcd4552e0917820ea3f3 Mon Sep 17 00:00:00 2001
From: Ross Story
Date: Wed, 20 May 2026 13:28:57 -0700
Subject: [PATCH 8/8] Narrow Copilot pre-tool session ids
Ensures pre-tool-use only forwards string session IDs and falls back to unknown for invalid Copilot payload values, with regression coverage for the generated plugin script.
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
---
plugin/scripts/pre-tool-use.mjs | 3 ++-
src/hooks/pre-tool-use.ts | 6 +++++-
test/copilot-plugin.test.ts | 21 +++++++++++++++++++++
3 files changed, 28 insertions(+), 2 deletions(-)
diff --git a/plugin/scripts/pre-tool-use.mjs b/plugin/scripts/pre-tool-use.mjs
index 3d9dd98622..16892fcdfb 100755
--- a/plugin/scripts/pre-tool-use.mjs
+++ b/plugin/scripts/pre-tool-use.mjs
@@ -55,7 +55,8 @@ async function main() {
const pattern = toolInput["pattern"];
if (typeof pattern === "string" && pattern.length > 0) terms.push(pattern);
}
- const sessionId = data.session_id || data.sessionId || "unknown";
+ const rawSessionId = data.session_id || data.sessionId;
+ const sessionId = typeof rawSessionId === "string" && rawSessionId.length > 0 ? rawSessionId : "unknown";
try {
const res = await fetch(`${REST_URL}/agentmemory/enrich`, {
method: "POST",
diff --git a/src/hooks/pre-tool-use.ts b/src/hooks/pre-tool-use.ts
index 63061b3df4..eea440c80c 100644
--- a/src/hooks/pre-tool-use.ts
+++ b/src/hooks/pre-tool-use.ts
@@ -88,7 +88,11 @@ async function main() {
}
}
- const sessionId = ((data.session_id || data.sessionId) as string) || "unknown";
+ const rawSessionId = data.session_id || data.sessionId;
+ const sessionId =
+ typeof rawSessionId === "string" && rawSessionId.length > 0
+ ? rawSessionId
+ : "unknown";
try {
const res = await fetch(`${REST_URL}/agentmemory/enrich`, {
diff --git a/test/copilot-plugin.test.ts b/test/copilot-plugin.test.ts
index 4956d2ac09..e412168831 100644
--- a/test/copilot-plugin.test.ts
+++ b/test/copilot-plugin.test.ts
@@ -297,6 +297,27 @@ describe("Copilot hook scripts", () => {
});
});
+ 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",
|