diff --git a/INSTALL_FOR_AGENTS.md b/INSTALL_FOR_AGENTS.md index 68d2071067..4464c49ad3 100644 --- a/INSTALL_FOR_AGENTS.md +++ b/INSTALL_FOR_AGENTS.md @@ -14,7 +14,7 @@ Default keyless mode needs no API key or cloud account and disables vector embed - Node.js >= 20 with npm and npx. Check with `node -v`, `npm -v`, and `npx -v`. - macOS/Linux automatic iii installation also requires `curl`, a POSIX `sh`, and `tar`. Check with `command -v curl sh tar`. Minimal images such as `node:20-slim` may not include them. -- Windows: WSL2 follows the Linux path. Native Windows installs the pinned iii-engine v0.25.1 ZIP automatically. Native automated `connect` supports only `copilot-cli`; configure other Windows agents manually. WSL `connect` applies only to agents installed in that same WSL environment. +- Windows: WSL2 follows the Linux path. Native Windows installs the pinned iii-engine v0.25.1 ZIP automatically. Native `connect` works for every adapter. WSL `connect` applies only to agents installed in that same WSL environment. - Default ports 3111 (REST), 3113 (viewer), and 49134 (engine) must be free. Viewer events are carried over REST. ## Running non-interactively @@ -100,7 +100,7 @@ The first embedding request downloads `Xenova/all-MiniLM-L6-v2`; wait for that d ## 5. Wire MCP into the calling agent -Detect which agent is running this runbook, then wire its MCP config. On native Windows, run this automated step only for `copilot-cli`: +Detect which agent is running this runbook, then wire its MCP config: ```bash npx -y @agentmemory/agentmemory@latest connect @@ -110,7 +110,7 @@ Supported agent names: `claude-code`, `copilot-cli`, `codex`, `cursor`, `gemini-cli`, `opencode`, `cline`, `continue`, `droid`, `hermes`, `openclaw`, `openhuman`, `pi`, `omp`, `qwen`, `warp`, `zed`, `antigravity`, `kiro`. -If you cannot tell which agent you are, default to `claude-code` on macOS/Linux. On native Windows, `copilot-cli` is the only automated adapter; configure all other agents with the manual MCP block in the README. Run `connect` inside WSL only when the target agent is installed inside the same WSL environment. After wiring, restart the agent or run its MCP reload command (for example `/mcp` in Claude Code) so it picks up the server. +If you cannot tell which agent you are, default to `claude-code` on macOS/Linux. Run `connect` inside WSL only when the target agent is installed inside the same WSL environment. After wiring, restart the agent or run its MCP reload command (for example `/mcp` in Claude Code) so it picks up the server. Expect: the agent now lists agentmemory's tools. With the server running you should see the full set of 54 tools (for example `memory_save`, `memory_smart_search`, `memory_sessions`). If you see only 7 tools, the MCP shim could not reach the server; see Troubleshooting. @@ -216,7 +216,7 @@ The MCP server exposes 54 tools by default (`--tools all`). Use `--tools core` ( - `The engine process started but the REST API never responded.`: inspect the REST, viewer, and engine ports, confirm the pinned iii process stayed alive, and use `--verbose` for captured engine stderr. - Engine version conflict / another iii engine already running: if an unmanaged engine is already listening on the engine port, agentmemory will not adopt it. Stop that engine or choose another `--instance` or `--port`. The CLI keeps its private pinned binary separate from a user-managed `iii` on `PATH`. - Only 7 tools visible in the agent: the MCP shim is in local fallback because it could not reach a server. Start `npx -y @agentmemory/agentmemory@latest`, ensure `AGENTMEMORY_URL` points at it (default `http://localhost:3111`), then reload MCP. -- Native Windows: if the automatic engine install fails, install the pinned v0.25.1 `iii.exe` manually or use WSL2. Automated `connect` supports only `copilot-cli`; configure other native agents manually. +- Native Windows: if the automatic engine install fails, install the pinned v0.25.1 `iii.exe` manually or use WSL2. - Semantic demo query returns zero hits: this is expected with vectors disabled in default keyless mode. Set `EMBEDDING_PROVIDER=local`, restart, allow the first model download to complete, and rerun the demo. ## Report success diff --git a/README.md b/README.md index cd40701a05..147677d666 100644 --- a/README.md +++ b/README.md @@ -533,7 +533,7 @@ agentmemory connect copilot-cli 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. On native Windows this is the only automated `connect` adapter; configure every other native Windows agent manually. WSL `connect` is supported only when the target agent is installed in that same WSL environment. 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. WSL `connect` is supported only when the target agent is installed in that same WSL environment. 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. ### Cursor @@ -690,7 +690,7 @@ npm install && npm run build && npm start agentmemory runs on Windows 10/11. WSL2 follows the Linux path and can install the pinned engine automatically. Native Windows also installs the pinned iii-engine v0.25.1 automatically: the CLI downloads the Windows ZIP, verifies its SHA-256 and extracts `iii.exe` into `%USERPROFILE%\.agentmemory\bin`. If that fails, download the matching archive from the [iii v0.25.1 release page](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.25.1), verify its checksum, and extract `iii.exe` into the same directory. -Native Windows automated MCP wiring supports only `agentmemory connect copilot-cli`. For other native Windows agents, use the manual MCP block from [Other agents](#other-agents). Run `connect` inside WSL only when the target agent is installed in that same WSL environment. +`agentmemory connect ` works on native Windows. It writes the MCP server as `cmd /c npx -y @agentmemory/mcp`, because Windows cannot start `npx` without a shell, and it writes hook script paths as absolute paths with forward slashes, either quoted or passed as a separate argument, so a home folder with spaces is safe. Antigravity hooks cannot use quoted paths. When the install path has spaces, `connect antigravity --with-hooks` uses the Windows short (8.3) path. If the short path is not available, it prints the hook JSON to paste by hand, and the MCP wiring still applies. Run `connect` inside WSL only when the target agent is installed in that same WSL environment. **Standalone MCP only (no engine).** If you only need MCP tools and do not need the REST API, viewer, or runtime services: diff --git a/src/cli/connect/antigravity-cli.ts b/src/cli/connect/antigravity-cli.ts index 05cc5b72fe..36ade28b3e 100644 --- a/src/cli/connect/antigravity-cli.ts +++ b/src/cli/connect/antigravity-cli.ts @@ -1,3 +1,4 @@ +import { execFileSync } from "node:child_process"; import { existsSync, mkdirSync } from "node:fs"; import { homedir } from "node:os"; import { join } from "node:path"; @@ -44,7 +45,59 @@ export const adapter = createJsonMcpAdapter({ * Merge the bundled `plugin/hooks/hooks.antigravity.json` into * `~/.gemini/config/hooks.json`, replacing only the bundle agentmemory owns. */ -export function installAntigravityCliHooks(opts: ConnectOptions): ConnectResult { +export function windowsShortPath(path: string): string | null { + try { + const out = execFileSync( + "powershell.exe", + [ + "-NoProfile", + "-NonInteractive", + "-Command", + "(New-Object -ComObject Scripting.FileSystemObject).GetFolder($env:AGENTMEMORY_LONG_PATH__).ShortPath", + ], + { + env: { ...process.env, AGENTMEMORY_LONG_PATH__: path }, + encoding: "utf-8", + stdio: ["ignore", "pipe", "ignore"], + timeout: 15_000, + windowsHide: true, + }, + ).trim(); + return out || null; + } catch { + return null; + } +} + +export function resolveHookCommandRoot( + pluginRoot: string, + shortPath: (path: string) => string | null = windowsShortPath, +): string | null { + if (!containsSpaces(pluginRoot)) return pluginRoot; + if (process.platform !== "win32") return null; + const short = shortPath(pluginRoot); + return short && !containsSpaces(short) ? short : null; +} + +function printManualHooks(pluginRoot: string): void { + const target = + process.platform === "win32" ? "C:/agentmemory/plugin" : "/opt/agentmemory/plugin"; + const manual = buildMergedAntigravityHooks(null, pluginRoot, undefined, target); + p.log.message( + [ + "Manual hook setup for Antigravity:", + ` 1. Copy ${pluginRoot} to ${target} (any path without spaces works).`, + ` 2. Merge this into ${ANTIGRAVITY_CLI_HOOKS}:`, + "", + JSON.stringify(manual, null, 2), + ].join("\n"), + ); +} + +export function installAntigravityCliHooks( + opts: ConnectOptions, + shortPath: (path: string) => string | null = windowsShortPath, +): ConnectResult { let pluginRoot: string; try { pluginRoot = findPluginRoot(); @@ -55,17 +108,17 @@ export function installAntigravityCliHooks(opts: ConnectOptions): ConnectResult }; } - // agy honours no quoting, so a space in the path yields hooks that load - // but never run. Refuse rather than install something that can only fail. - if (containsSpaces(pluginRoot)) { + const commandRoot = resolveHookCommandRoot(pluginRoot, shortPath); + if (commandRoot === null) { + printManualHooks(pluginRoot); return { kind: "skipped", - reason: `Antigravity CLI cannot run hook commands whose path contains spaces, and agentmemory is installed at ${pluginRoot}. Reinstall it under a space-free path to use --with-hooks; MCP works either way.`, + reason: `Antigravity cannot run hook commands whose path contains spaces, and agentmemory is installed at ${pluginRoot}. Follow the manual hook steps above; MCP works either way`, }; } const existing = readJsonSafe(ANTIGRAVITY_CLI_HOOKS); - const merged = buildMergedAntigravityHooks(existing, pluginRoot); + const merged = buildMergedAntigravityHooks(existing, pluginRoot, undefined, commandRoot); if (opts.dryRun) { p.log.info( diff --git a/src/cli/connect/antigravity-hooks.ts b/src/cli/connect/antigravity-hooks.ts index b3b11297dc..426c27a952 100644 --- a/src/cli/connect/antigravity-hooks.ts +++ b/src/cli/connect/antigravity-hooks.ts @@ -1,5 +1,6 @@ import { readFileSync } from "node:fs"; import { join } from "node:path"; +import { toCommandPath } from "./util.js"; /** * Merge engine for Antigravity CLI's `hooks.json`. @@ -62,11 +63,12 @@ export function buildMergedAntigravityHooks( existing: AntigravityHookManifest | null, pluginRoot: string, manifestFile = "hooks.antigravity.json", + commandRoot = pluginRoot, ): AntigravityHookManifest { const ours = JSON.parse( readFileSync(join(pluginRoot, "hooks", manifestFile), "utf-8"), ) as AntigravityHookManifest; - const scriptsDir = join(pluginRoot, "scripts"); + const scriptsDir = join(commandRoot, "scripts"); const out: AntigravityHookManifest = {}; @@ -76,7 +78,7 @@ export function buildMergedAntigravityHooks( } for (const [name, bundle] of Object.entries(ours)) { - out[name] = resolveBundle(bundle, pluginRoot); + out[name] = resolveBundle(bundle, toCommandPath(commandRoot)); } return out; diff --git a/src/cli/connect/antigravity.ts b/src/cli/connect/antigravity.ts index a434d07182..db732198e3 100644 --- a/src/cli/connect/antigravity.ts +++ b/src/cli/connect/antigravity.ts @@ -4,10 +4,17 @@ import { join } from "node:path"; import { createJsonMcpAdapter } from "./json-mcp-adapter.js"; import { installAntigravityCliHooks } from "./antigravity-cli.js"; -const LEGACY_USER_DIR = - platform() === "darwin" - ? join(homedir(), "Library", "Application Support", "Antigravity", "User") - : join(homedir(), ".config", "Antigravity", "User"); +function legacyUserDir(): string { + if (platform() === "darwin") { + return join(homedir(), "Library", "Application Support", "Antigravity", "User"); + } + if (platform() === "win32") { + return join(process.env["APPDATA"] || join(homedir(), "AppData", "Roaming"), "Antigravity", "User"); + } + return join(homedir(), ".config", "Antigravity", "User"); +} + +const LEGACY_USER_DIR = legacyUserDir(); const CUSTOMIZATION_DIR = join(homedir(), ".gemini", "config"); const mcpAdapter = createJsonMcpAdapter({ diff --git a/src/cli/connect/claude-code.ts b/src/cli/connect/claude-code.ts index 271468bf2e..1f1557c30b 100644 --- a/src/cli/connect/claude-code.ts +++ b/src/cli/connect/claude-code.ts @@ -7,6 +7,7 @@ import type { ConnectAdapter, ConnectOptions, ConnectResult } from "./types.js"; import { AGENTMEMORY_MCP_BLOCK, backupFile, + isAgentmemoryMcpEntry, logAlreadyWired, logBackup, logInstalled, @@ -38,13 +39,7 @@ type ClaudeConfig = { [key: string]: unknown; }; -function entryMatches(entry: unknown): boolean { - if (!entry || typeof entry !== "object") return false; - const e = entry as Record; - if (e["command"] !== "npx") return false; - const args = Array.isArray(e["args"]) ? (e["args"] as string[]) : []; - return args.includes("@agentmemory/mcp"); -} +const entryMatches = isAgentmemoryMcpEntry; export const adapter: ConnectAdapter = { name: "claude-code", diff --git a/src/cli/connect/codex-hooks.ts b/src/cli/connect/codex-hooks.ts index 0b239b3fc3..205cc0f963 100644 --- a/src/cli/connect/codex-hooks.ts +++ b/src/cli/connect/codex-hooks.ts @@ -1,6 +1,7 @@ import { existsSync, readFileSync } from "node:fs"; import { dirname, join, resolve } from "node:path"; import { fileURLToPath } from "node:url"; +import { toCommandPath } from "./util.js"; type HookHandler = { type: string; command?: string; args?: string[]; [key: string]: unknown }; type HookEntry = { matcher?: string; hooks: HookHandler[] }; @@ -86,7 +87,7 @@ export function buildMergedHooks( } function withPluginRoot(value: string | undefined, pluginRoot: string): string | undefined { - return value?.replace(/\$\{CLAUDE_PLUGIN_ROOT\}/g, () => pluginRoot); + return value?.replace(/\$\{CLAUDE_PLUGIN_ROOT\}/g, () => toCommandPath(pluginRoot)); } function isAgentmemoryHandler(handler: HookHandler, scriptsDir: string): boolean { diff --git a/src/cli/connect/codex.ts b/src/cli/connect/codex.ts index b31b35d119..a3dbf84dc0 100644 --- a/src/cli/connect/codex.ts +++ b/src/cli/connect/codex.ts @@ -4,7 +4,9 @@ import { join, dirname } from "node:path"; import * as p from "@clack/prompts"; import type { ConnectAdapter, ConnectOptions, ConnectResult } from "./types.js"; import { + AGENTMEMORY_MCP_BLOCK, backupFile, + isLegacyMcpCommand, logAlreadyWired, logBackup, logInstalled, @@ -22,8 +24,8 @@ const CODEX_TOML = join(CODEX_DIR, "config.toml"); const CODEX_HOOKS = join(CODEX_DIR, "hooks.json"); const TOML_BLOCK = `[mcp_servers.agentmemory] -command = "npx" -args = ["-y", "@agentmemory/mcp"] +command = ${JSON.stringify(AGENTMEMORY_MCP_BLOCK.command)} +args = [${AGENTMEMORY_MCP_BLOCK.args.map((arg) => JSON.stringify(arg)).join(", ")}] [mcp_servers.agentmemory.env] AGENTMEMORY_URL = "http://localhost:3111" @@ -35,6 +37,90 @@ function isWiredText(toml: string): boolean { return toml.includes(SECTION_HEADER); } +const COMMAND_LINE = /^([ \t]*command[ \t]*=[ \t]*)(["'])(.*?)\2(?=[ \t]*(?:#.*)?$)/m; +const ARGS_KEY = /^[ \t]*args[ \t]*=[ \t]*(?=\[)/m; + +function sectionBounds(toml: string): { start: number; end: number } | null { + const header = toml.indexOf(SECTION_HEADER); + if (header < 0) return null; + const start = header + SECTION_HEADER.length; + const end = toml.slice(start).search(/^\s*\[/m); + return { start, end: end < 0 ? toml.length : start + end }; +} + +function decodeBasicString(literal: string): string { + try { + return JSON.parse(literal) as string; + } catch { + return literal.slice(1, -1); + } +} + +function findArgs(section: string): { open: number; end: number; items: string[] } | null { + const key = section.match(ARGS_KEY); + if (!key || key.index === undefined) return null; + const open = key.index + key[0].length; + const items: string[] = []; + let depth = 0; + for (let i = open; i < section.length; i++) { + const ch = section[i]; + if (ch === "#") { + const newline = section.indexOf("\n", i); + if (newline < 0) return null; + i = newline; + } else if (ch === '"' || ch === "'") { + let j = i + 1; + while (j < section.length && section[j] !== ch && section[j] !== "\n") { + j += ch === '"' && section[j] === "\\" ? 2 : 1; + } + if (section[j] !== ch) return null; + const literal = section.slice(i, j + 1); + if (depth === 1) items.push(ch === '"' ? decodeBasicString(literal) : literal.slice(1, -1)); + i = j; + } else if (ch === "[") { + depth++; + } else if (ch === "]" && --depth === 0) { + return { open, end: i + 1, items }; + } + } + return null; +} + +function agentmemorySection(toml: string): string | null { + const bounds = sectionBounds(toml); + return bounds ? toml.slice(bounds.start, bounds.end) : null; +} + +function hasLegacyCommand(toml: string): boolean { + const section = agentmemorySection(toml); + if (section === null) return false; + return isLegacyMcpCommand(section.match(COMMAND_LINE)?.[3], findArgs(section)?.items); +} + +function hasCurrentCommand(toml: string): boolean { + const section = agentmemorySection(toml); + if (section === null) return false; + const args = findArgs(section)?.items; + return ( + section.match(COMMAND_LINE)?.[3] === AGENTMEMORY_MCP_BLOCK.command && + JSON.stringify(args) === JSON.stringify(AGENTMEMORY_MCP_BLOCK.args) + ); +} + +function migrateLegacyCommand(toml: string): string | null { + const bounds = sectionBounds(toml)!; + const section = toml.slice(bounds.start, bounds.end); + const args = findArgs(section); + if (!args) return null; + const nextArgs = `[${AGENTMEMORY_MCP_BLOCK.args.map((arg) => JSON.stringify(arg)).join(", ")}]`; + const migrated = (section.slice(0, args.open) + nextArgs + section.slice(args.end)).replace( + COMMAND_LINE, + (_, prefix: string) => `${prefix}${JSON.stringify(AGENTMEMORY_MCP_BLOCK.command)}`, + ); + const next = toml.slice(0, bounds.start) + migrated + toml.slice(bounds.end); + return hasCurrentCommand(next) ? next : null; +} + function stripExistingBlock(toml: string): string { const lines = toml.split(/\r?\n/); const out: string[] = []; @@ -76,8 +162,9 @@ export const adapter: ConnectAdapter = { const exists = existsSync(CODEX_TOML); const current = exists ? readFileSync(CODEX_TOML, "utf-8") : ""; const wired = isWiredText(current); + const legacy = wired && hasLegacyCommand(current); - if (wired && !opts.force) { + if (wired && !legacy && !opts.force) { logAlreadyWired("Codex CLI", CODEX_TOML); return { kind: "already-wired", mutatedPath: CODEX_TOML }; } @@ -98,10 +185,20 @@ export const adapter: ConnectAdapter = { mkdirSync(dirname(CODEX_TOML), { recursive: true }); } - const cleaned = wired ? stripExistingBlock(current) : current; - const joiner = cleaned.length === 0 || cleaned.endsWith("\n") ? "" : "\n"; - const next = `${cleaned}${joiner}${cleaned.length > 0 ? "\n" : ""}${TOML_BLOCK}`; - writeFileSync(CODEX_TOML, next, "utf-8"); + if (legacy && !opts.force) { + const migrated = migrateLegacyCommand(current); + if (migrated === null) { + p.log.error( + `Could not migrate the agentmemory launcher in ${CODEX_TOML}. Run again with --force to rewrite the block.`, + ); + return { kind: "skipped", reason: "verification-failed" }; + } + writeFileSync(CODEX_TOML, migrated, "utf-8"); + } else { + const cleaned = wired ? stripExistingBlock(current) : current; + const joiner = cleaned.length === 0 || cleaned.endsWith("\n") ? "" : "\n"; + writeFileSync(CODEX_TOML, `${cleaned}${joiner}${cleaned.length > 0 ? "\n" : ""}${TOML_BLOCK}`, "utf-8"); + } const verify = readFileSync(CODEX_TOML, "utf-8"); if (!isWiredText(verify)) { diff --git a/src/cli/connect/continue.ts b/src/cli/connect/continue.ts index c09107c09e..aaeeead536 100644 --- a/src/cli/connect/continue.ts +++ b/src/cli/connect/continue.ts @@ -6,6 +6,7 @@ import type { ConnectAdapter, ConnectOptions, ConnectResult } from "./types.js"; import { AGENTMEMORY_MCP_BLOCK, backupFile, + isLegacyMcpCommand, logAlreadyWired, logBackup, logInstalled, @@ -110,7 +111,8 @@ export const adapter: ConnectAdapter = { const idx = servers.findIndex((s) => s?.name === "agentmemory"); const alreadyHas = idx >= 0 && entryIsAgentmemory(servers[idx]); - if (alreadyHas && !opts.force) { + const legacy = idx >= 0 && isLegacyMcpCommand(servers[idx]?.command, servers[idx]?.args); + if (alreadyHas && !legacy && !opts.force) { logAlreadyWired("Continue", JSON_PATH); return { kind: "already-wired", mutatedPath: JSON_PATH }; } @@ -125,7 +127,11 @@ export const adapter: ConnectAdapter = { const backupPath = backupFile(JSON_PATH, "continue"); logBackup(backupPath); - const entry = buildEntry(); + const fresh = buildEntry(); + const entry = + legacy && !opts.force + ? { ...servers[idx], command: fresh.command, args: fresh.args } + : fresh; if (idx >= 0) servers[idx] = entry; else servers.push(entry); next.mcpServers = servers; diff --git a/src/cli/connect/dsh.ts b/src/cli/connect/dsh.ts index f18c93b7e9..4de9b21258 100644 --- a/src/cli/connect/dsh.ts +++ b/src/cli/connect/dsh.ts @@ -4,7 +4,9 @@ import * as p from "@clack/prompts"; import { isMap, isSeq, parseDocument, type YAMLMap } from "yaml"; import type { ConnectAdapter, ConnectOptions, ConnectResult } from "./types.js"; import { + AGENTMEMORY_MCP_BLOCK, backupFile, + isLegacyMcpCommand, resolveDshHome, logAlreadyWired, logBackup, @@ -20,8 +22,8 @@ const MCP_BLOCK = `- insert: config: transport: stdio serverName: agentmemory - command: npx - args: ['-y', '@agentmemory/mcp'] + command: ${AGENTMEMORY_MCP_BLOCK.command} + args: [${AGENTMEMORY_MCP_BLOCK.args.map((arg) => `'${arg}'`).join(", ")}] env: AGENTMEMORY_URL: !!js process.env.AGENTMEMORY_URL || 'http://localhost:3111' AGENTMEMORY_SECRET: !!js process.env.AGENTMEMORY_SECRET || '' @@ -61,6 +63,38 @@ function managedEntries(content: string, marker: string): YAMLMap[] { }); } +function isLegacyEntry(entry: YAMLMap): boolean { + const args = entry.getIn(["config", "args"]); + return isLegacyMcpCommand(entry.getIn(["config", "command"]), isSeq(args) ? args.toJSON() : args); +} + +function migrateLegacyCommand(content: string): string { + const { doc, operations } = parsePatch(content); + let kept = false; + for (let i = 0; i < operations.items.length; i++) { + const operation = operations.items[i]; + const entries = isMap(operation) ? operation.get("insert", true) : null; + if (!isSeq(entries)) continue; + let removed = false; + for (let j = 0; j < entries.items.length; j++) { + const entry = entries.items[j]; + if (!isManaged(entry, MCP_MARKER) || !isLegacyEntry(entry)) continue; + if (kept) { + entries.delete(j--); + removed = true; + continue; + } + kept = true; + const args = doc.createNode([...AGENTMEMORY_MCP_BLOCK.args]); + args.flow = true; + entry.setIn(["config", "command"], AGENTMEMORY_MCP_BLOCK.command); + entry.setIn(["config", "args"], args); + } + if (removed && entries.items.length === 0) operations.delete(i--); + } + return doc.toString(); +} + function hasBlock(content: string, marker: string): boolean { return managedEntries(content, marker).length > 0; } @@ -111,7 +145,9 @@ export const adapter: ConnectAdapter = { : ""; const wantHooks = opts.withHooks === true; - const hasMcp = hasBlock(existing, MCP_MARKER); + const mcpEntries = managedEntries(existing, MCP_MARKER); + const legacyMcp = mcpEntries.some(isLegacyEntry); + const hasMcp = mcpEntries.length > 0 && !legacyMcp; const hooks = managedEntries(existing, HOOKS_MARKER); const pluginPath = wantHooks ? join(dirname(findPluginRoot()), "dist", "integrations", "dsh.mjs") : ""; const hooksReady = hooks.length === 1 && hooks[0].get("name") === pluginPath && existsSync(pluginPath); @@ -144,7 +180,9 @@ export const adapter: ConnectAdapter = { mkdirSync(dirname(configPath), { recursive: true }); } - let next = hasMcp && !opts.force ? existing : upsertBlock(existing, MCP_MARKER, MCP_BLOCK); + let next = existing; + if (opts.force || mcpEntries.length === 0) next = upsertBlock(existing, MCP_MARKER, MCP_BLOCK); + else if (legacyMcp) next = migrateLegacyCommand(existing); if (wantHooks && (!hooksReady || opts.force)) { next = upsertBlock(next, HOOKS_MARKER, hooksBlock(pluginPath)); diff --git a/src/cli/connect/guidelines.ts b/src/cli/connect/guidelines.ts index 58d1cf786f..39c46a9175 100644 --- a/src/cli/connect/guidelines.ts +++ b/src/cli/connect/guidelines.ts @@ -1,7 +1,7 @@ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"; import { homedir } from "node:os"; import { dirname, join } from "node:path"; -import { resolveDshHome } from "./util.js"; +import { resolveDshHome, resolveZedConfigDir } from "./util.js"; // Activating memory for agents that have no auto-capture hooks: write a short // "use the memory tools" guideline into each agent's native rules mechanism so @@ -65,7 +65,7 @@ export function guidelineTargets( source: "https://docs.continue.dev/customize/deep-dives/rules", }, zed: { - globalPath: join(home, ".config", "zed", "AGENTS.md"), + globalPath: join(resolveZedConfigDir(home), "AGENTS.md"), projectPath: "AGENTS.md", format: "block", scope: "global", diff --git a/src/cli/connect/index.ts b/src/cli/connect/index.ts index 055cb547d3..8a7e0e9b2e 100644 --- a/src/cli/connect/index.ts +++ b/src/cli/connect/index.ts @@ -1,4 +1,3 @@ -import { platform } from "node:os"; import * as p from "@clack/prompts"; import pc from "picocolors"; import type { ConnectAdapter, ConnectOptions, ConnectResult } from "./types.js"; @@ -141,17 +140,6 @@ export async function runAdapter( export async function runConnect(args: string[]): Promise { const { dryRun, force, all, withHooks, withMcp, guidelines, 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.", - ); - p.outro("Windows: manual install required — see docs"); - return; - } - const opts: ConnectOptions = { dryRun, force, withHooks, withMcp, guidelines }; p.intro("agentmemory connect"); diff --git a/src/cli/connect/json-mcp-adapter.ts b/src/cli/connect/json-mcp-adapter.ts index 0b76aa754f..a1fbac63d9 100644 --- a/src/cli/connect/json-mcp-adapter.ts +++ b/src/cli/connect/json-mcp-adapter.ts @@ -5,6 +5,7 @@ import type { ConnectAdapter, ConnectOptions, ConnectResult } from "./types.js"; import { AGENTMEMORY_MCP_BLOCK, backupFile, + isAgentmemoryMcpEntry, logAlreadyWired, logBackup, logInstalled, @@ -35,13 +36,7 @@ export type JsonMcpAdapterConfig = { type McpEntry = typeof AGENTMEMORY_MCP_BLOCK; type McpConfig = Record; -function entryMatches(entry: unknown): boolean { - if (!entry || typeof entry !== "object") return false; - const e = entry as Record; - if (e["command"] !== "npx") return false; - const args = Array.isArray(e["args"]) ? (e["args"] as string[]) : []; - return args.includes("@agentmemory/mcp"); -} +const entryMatches = isAgentmemoryMcpEntry; export function createJsonMcpAdapter( config: JsonMcpAdapterConfig, diff --git a/src/cli/connect/opencode.ts b/src/cli/connect/opencode.ts index 76ddbf63d1..b51829cca1 100644 --- a/src/cli/connect/opencode.ts +++ b/src/cli/connect/opencode.ts @@ -4,7 +4,9 @@ import { dirname, join } from "node:path"; import * as p from "@clack/prompts"; import type { ConnectAdapter, ConnectOptions, ConnectResult } from "./types.js"; import { + AGENTMEMORY_MCP_BLOCK, backupFile, + isLegacyMcpCommand, logAlreadyWired, logBackup, logInstalled, @@ -28,7 +30,7 @@ const DETECT_DIR = join(homedir(), ".config", "opencode"); // shim defaults unset vars (URL -> localhost:3111, no secret, all tools). const OPENCODE_ENTRY = { type: "local", - command: ["npx", "-y", "@agentmemory/mcp"], + command: [AGENTMEMORY_MCP_BLOCK.command, ...AGENTMEMORY_MCP_BLOCK.args], enabled: true, }; @@ -65,7 +67,9 @@ export const adapter: ConnectAdapter = { : {}; const alreadyHas = entryMatches(mcp["agentmemory"]); - if (alreadyHas && !opts.force) { + const command = mcp["agentmemory"]?.["command"]; + const legacy = Array.isArray(command) && isLegacyMcpCommand(command[0], command.slice(1)); + if (alreadyHas && !legacy && !opts.force) { logAlreadyWired(this.displayName, CONFIG_PATH); return { kind: "already-wired", mutatedPath: CONFIG_PATH }; } @@ -85,7 +89,10 @@ export const adapter: ConnectAdapter = { mkdirSync(dirname(CONFIG_PATH), { recursive: true }); } - mcp["agentmemory"] = { ...OPENCODE_ENTRY }; + mcp["agentmemory"] = + legacy && !opts.force + ? { ...mcp["agentmemory"], command: [...OPENCODE_ENTRY.command] } + : { ...OPENCODE_ENTRY }; next["mcp"] = mcp; writeJsonAtomic(CONFIG_PATH, next); diff --git a/src/cli/connect/util.ts b/src/cli/connect/util.ts index cc2d64484f..ce29f1d1c3 100644 --- a/src/cli/connect/util.ts +++ b/src/cli/connect/util.ts @@ -10,9 +10,13 @@ import { dirname, join, resolve } from "node:path"; import { homedir } from "node:os"; import * as p from "@clack/prompts"; +const MCP_COMMAND = + process.platform === "win32" + ? { command: "cmd", args: ["/c", "npx", "-y", "@agentmemory/mcp"] } + : { command: "npx", args: ["-y", "@agentmemory/mcp"] }; + export const AGENTMEMORY_MCP_BLOCK = { - command: "npx", - args: ["-y", "@agentmemory/mcp"], + ...MCP_COMMAND, env: { AGENTMEMORY_URL: "${AGENTMEMORY_URL:-http://localhost:3111}", AGENTMEMORY_SECRET: "${AGENTMEMORY_SECRET:-}", @@ -42,6 +46,32 @@ export const AGENTMEMORY_COPILOT_MCP_BLOCK = { tools: ["*"], }; +export function isAgentmemoryMcpEntry(entry: unknown): boolean { + if (!entry || typeof entry !== "object") return false; + const e = entry as Record; + if (e["command"] !== AGENTMEMORY_MCP_BLOCK.command) return false; + const args = Array.isArray(e["args"]) ? (e["args"] as string[]) : []; + return args.includes("@agentmemory/mcp"); +} + +export function isLegacyMcpCommand(command: unknown, args: unknown): boolean { + return ( + AGENTMEMORY_MCP_BLOCK.command !== "npx" && + command === "npx" && + Array.isArray(args) && + args.includes("@agentmemory/mcp") + ); +} + +export function toCommandPath(path: string): string { + return process.platform === "win32" ? path.replace(/\\/g, "/") : path; +} + +export function resolveZedConfigDir(home: string = homedir()): string { + if (process.platform !== "win32") return join(home, ".config", "zed"); + return join(process.env["APPDATA"] || join(home, "AppData", "Roaming"), "Zed"); +} + export function resolveDshHome(home: string = homedir()): string { const override = process.env["DSH_HOME"]; const value = override?.trim() ? override : join(home, ".dsh"); diff --git a/src/cli/connect/zed.ts b/src/cli/connect/zed.ts index bad7730d85..a092c38710 100644 --- a/src/cli/connect/zed.ts +++ b/src/cli/connect/zed.ts @@ -1,6 +1,6 @@ -import { homedir } from "node:os"; import { join } from "node:path"; import { createJsonMcpAdapter } from "./json-mcp-adapter.js"; +import { resolveZedConfigDir } from "./util.js"; // Zed stores its settings (including MCP servers) under "context_servers" // in settings.json — NOT "mcpServers". User config lives at @@ -8,7 +8,7 @@ import { createJsonMcpAdapter } from "./json-mcp-adapter.js"; // even on macOS; ~/Library/Application Support/Zed/ holds runtime data // like the database + cached language servers, not the config). // Source: zed.dev/docs/ai/mcp + zed.dev/docs/configuring-zed -const zedConfigDir = join(homedir(), ".config", "zed"); +const zedConfigDir = resolveZedConfigDir(); export const adapter = createJsonMcpAdapter({ name: "zed", diff --git a/test/connect-dsh.test.ts b/test/connect-dsh.test.ts index e222b64d6c..d12049f22e 100644 --- a/test/connect-dsh.test.ts +++ b/test/connect-dsh.test.ts @@ -68,7 +68,11 @@ describe("connect: DeepSeek Harness", () => { expect(patch).toContain("name: '@deepseek-ai/dsh-mcp-client'"); expect(patch).toContain("serverName: agentmemory"); expect(patch).toContain("transport: stdio"); - expect(parseDocument(patch).toJS()[0].insert[0].config.args).toEqual(["-y", "@agentmemory/mcp"]); + expect(parseDocument(patch).toJS()[0].insert[0].config.args).toEqual( + process.platform === "win32" + ? ["/c", "npx", "-y", "@agentmemory/mcp"] + : ["-y", "@agentmemory/mcp"], + ); expect(patch).toContain("AGENTMEMORY_URL:"); }); diff --git a/test/connect-windows.test.ts b/test/connect-windows.test.ts new file mode 100644 index 0000000000..dc5211343a --- /dev/null +++ b/test/connect-windows.test.ts @@ -0,0 +1,443 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join, resolve } from "node:path"; + +const { log, pluginRootOverride } = vi.hoisted(() => ({ + log: { + info: vi.fn(), + warn: vi.fn(), + error: vi.fn(), + success: vi.fn(), + message: vi.fn(), + step: vi.fn(), + }, + pluginRootOverride: { value: null as string | null }, +})); +vi.mock("@clack/prompts", () => ({ + log, + intro: vi.fn(), + outro: vi.fn(), + note: vi.fn(), + cancel: vi.fn(), + isCancel: () => false, + multiselect: vi.fn(), +})); + +const REPO_PLUGIN = resolve(__dirname, "..", "plugin"); +const WINDOWS_MCP = { command: "cmd", args: ["/c", "npx", "-y", "@agentmemory/mcp"] }; +const QUOTED_NODE_COMMAND = /^node "(\/|[A-Za-z]:\/)[^"\\]+\.mjs"$/; + +vi.mock("../src/cli/connect/codex-hooks.js", async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + findPluginRoot: (...args: Parameters) => + pluginRootOverride.value ?? actual.findPluginRoot(...args), + }; +}); + +type Handler = { command?: string; args?: string[] }; + +function hookHandlers(hooks: Record): Handler[] { + return Object.values(hooks).flatMap((entries) => entries.flatMap((entry) => entry.hooks)); +} + +function hookCommands(hooks: Record): string[] { + return hookHandlers(hooks).map((h) => h.command ?? ""); +} + +function spacedPluginRoot(home: string): string { + const root = join(home, "AppData", "Local", "npm-cache", "_npx", "abc 123", "node_modules", "@agentmemory", "agentmemory", "plugin"); + mkdirSync(join(root, "hooks"), { recursive: true }); + mkdirSync(join(root, "scripts"), { recursive: true }); + for (const file of readdirSync(join(REPO_PLUGIN, "hooks"))) { + copyFileSync(join(REPO_PLUGIN, "hooks", file), join(root, "hooks", file)); + } + return root; +} + +describe("connect on Windows with a home directory that contains spaces", () => { + let home: string; + const originalPlatform = process.platform; + + beforeEach(() => { + home = mkdtempSync(join(tmpdir(), "am win home ")); + vi.resetModules(); + vi.stubEnv("HOME", home); + vi.stubEnv("USERPROFILE", home); + vi.stubEnv("APPDATA", join(home, "AppData", "Roaming")); + vi.stubEnv("CLAUDE_CONFIG_DIR", ""); + vi.stubEnv("COPILOT_HOME", ""); + Object.defineProperty(process, "platform", { value: "win32" }); + pluginRootOverride.value = null; + for (const fn of Object.values(log)) fn.mockClear(); + }); + + afterEach(() => { + Object.defineProperty(process, "platform", { value: originalPlatform }); + vi.unstubAllEnvs(); + pluginRootOverride.value = null; + rmSync(home, { recursive: true, force: true }); + }); + + it("runConnect wires an agent instead of refusing on win32", async () => { + mkdirSync(join(home, ".gemini"), { recursive: true }); + const { runConnect } = await import("../src/cli/connect/index.js"); + await runConnect(["gemini-cli", "--no-guidelines"]); + const cfg = JSON.parse(readFileSync(join(home, ".gemini", "settings.json"), "utf-8")); + expect(cfg.mcpServers.agentmemory).toMatchObject(WINDOWS_MCP); + }); + + it("writes a cmd-wrapped MCP server for JSON adapters and stays idempotent", async () => { + mkdirSync(join(home, ".cursor"), { recursive: true }); + const { adapter } = await import("../src/cli/connect/cursor.js"); + expect((await adapter.install({ dryRun: false, force: false })).kind).toBe("installed"); + const cfg = JSON.parse(readFileSync(join(home, ".cursor", "mcp.json"), "utf-8")); + expect(cfg.mcpServers.agentmemory).toMatchObject(WINDOWS_MCP); + expect((await adapter.install({ dryRun: false, force: false })).kind).toBe("already-wired"); + }); + + it("replaces a bare npx entry that Windows cannot spawn", async () => { + mkdirSync(join(home, ".kiro", "settings"), { recursive: true }); + const { writeFileSync } = await import("node:fs"); + writeFileSync( + join(home, ".kiro", "settings", "mcp.json"), + JSON.stringify({ mcpServers: { agentmemory: { command: "npx", args: ["-y", "@agentmemory/mcp"] } } }), + ); + const { adapter } = await import("../src/cli/connect/kiro.js"); + expect((await adapter.install({ dryRun: false, force: false })).kind).toBe("installed"); + const cfg = JSON.parse(readFileSync(join(home, ".kiro", "settings", "mcp.json"), "utf-8")); + expect(cfg.mcpServers.agentmemory).toMatchObject(WINDOWS_MCP); + }); + + it("claude-code writes a cmd-wrapped MCP server and quoted absolute hook commands", async () => { + mkdirSync(join(home, ".claude"), { recursive: true }); + const root = spacedPluginRoot(home); + pluginRootOverride.value = root; + const { adapter } = await import("../src/cli/connect/claude-code.js"); + expect((await adapter.install({ dryRun: false, force: false, withHooks: true })).kind).toBe("installed"); + + const mcp = JSON.parse(readFileSync(join(home, ".claude.json"), "utf-8")); + expect(mcp.mcpServers.agentmemory).toMatchObject(WINDOWS_MCP); + + const settings = JSON.parse(readFileSync(join(home, ".claude", "settings.json"), "utf-8")); + const handlers = hookHandlers(settings.hooks); + expect(handlers.length).toBeGreaterThan(0); + for (const handler of handlers) { + expect(handler.command).toBe("node"); + expect(handler.args).toHaveLength(1); + expect(handler.args![0].startsWith(`${root.replace(/\\/g, "/")}/scripts/`)).toBe(true); + expect(handler.args![0]).toMatch(/\.mjs$/); + } + }); + + it("codex writes a cmd-wrapped TOML block and quoted hook commands", async () => { + mkdirSync(join(home, ".codex"), { recursive: true }); + const root = spacedPluginRoot(home); + pluginRootOverride.value = root; + const { adapter } = await import("../src/cli/connect/codex.js"); + expect((await adapter.install({ dryRun: false, force: false, withHooks: true })).kind).toBe("installed"); + + const toml = readFileSync(join(home, ".codex", "config.toml"), "utf-8"); + expect(toml).toContain('command = "cmd"'); + expect(toml).toContain('args = ["/c", "npx", "-y", "@agentmemory/mcp"]'); + + const hooks = JSON.parse(readFileSync(join(home, ".codex", "hooks.json"), "utf-8")); + for (const command of hookCommands(hooks.hooks)) { + expect(command).toMatch(QUOTED_NODE_COMMAND); + expect(command).toContain(root.replace(/\\/g, "/")); + } + }); + + it("codex replaces a bare npx block without --force", async () => { + mkdirSync(join(home, ".codex"), { recursive: true }); + writeFileSync( + join(home, ".codex", "config.toml"), + '[mcp_servers.agentmemory]\ncommand = "npx"\nargs = ["-y", "@agentmemory/mcp"]\n', + ); + const { adapter } = await import("../src/cli/connect/codex.js"); + expect((await adapter.install({ dryRun: false, force: false })).kind).toBe("installed"); + const toml = readFileSync(join(home, ".codex", "config.toml"), "utf-8"); + expect(toml).toContain('command = "cmd"'); + expect(toml).not.toContain('command = "npx"'); + expect((await adapter.install({ dryRun: false, force: false })).kind).toBe("already-wired"); + }); + + it("opencode replaces a bare npx command array without --force", async () => { + mkdirSync(join(home, ".config", "opencode"), { recursive: true }); + writeFileSync( + join(home, ".config", "opencode", "opencode.json"), + JSON.stringify({ theme: "dark", mcp: { agentmemory: { type: "local", command: ["npx", "-y", "@agentmemory/mcp"], enabled: true } } }), + ); + const { adapter } = await import("../src/cli/connect/opencode.js"); + expect((await adapter.install({ dryRun: false, force: false })).kind).toBe("installed"); + const cfg = JSON.parse(readFileSync(join(home, ".config", "opencode", "opencode.json"), "utf-8")); + expect(cfg.theme).toBe("dark"); + expect(cfg.mcp.agentmemory.command).toEqual(["cmd", ...WINDOWS_MCP.args]); + expect((await adapter.install({ dryRun: false, force: false })).kind).toBe("already-wired"); + }); + + it("continue replaces a bare npx entry in config.json without --force", async () => { + mkdirSync(join(home, ".continue"), { recursive: true }); + writeFileSync( + join(home, ".continue", "config.json"), + JSON.stringify({ mcpServers: [{ name: "agentmemory", command: "npx", args: ["-y", "@agentmemory/mcp"] }] }), + ); + const { adapter } = await import("../src/cli/connect/continue.js"); + expect((await adapter.install({ dryRun: false, force: false })).kind).toBe("installed"); + const cfg = JSON.parse(readFileSync(join(home, ".continue", "config.json"), "utf-8")); + expect(cfg.mcpServers).toHaveLength(1); + expect(cfg.mcpServers[0]).toMatchObject(WINDOWS_MCP); + expect((await adapter.install({ dryRun: false, force: false })).kind).toBe("already-wired"); + }); + + it("dsh replaces a bare npx mcp-client row without --force", async () => { + mkdirSync(join(home, ".dsh"), { recursive: true }); + writeFileSync( + join(home, ".dsh", "cordis.patch.yml"), + "- insert:\n - id: agentmemory\n name: '@deepseek-ai/dsh-mcp-client'\n config:\n transport: stdio\n serverName: agentmemory\n command: npx\n args: ['-y', '@agentmemory/mcp']\n", + ); + const { adapter } = await import("../src/cli/connect/dsh.js"); + expect((await adapter.install({ dryRun: false, force: false })).kind).toBe("installed"); + const patch = readFileSync(join(home, ".dsh", "cordis.patch.yml"), "utf-8"); + expect(patch).toContain("command: cmd"); + expect(patch).not.toContain("command: npx"); + expect((await adapter.install({ dryRun: false, force: false })).kind).toBe("already-wired"); + }); + + it("only treats a bare npx launcher of @agentmemory/mcp as legacy", async () => { + const { isLegacyMcpCommand } = await import("../src/cli/connect/util.js"); + expect(isLegacyMcpCommand("npx", ["-y", "@agentmemory/mcp"])).toBe(true); + expect(isLegacyMcpCommand("npx", ["-y", "@team/custom-mcp"])).toBe(false); + expect(isLegacyMcpCommand("npx", undefined)).toBe(false); + expect(isLegacyMcpCommand("cmd", WINDOWS_MCP.args)).toBe(false); + }); + + it("codex migrates a bare npx command that has a trailing TOML comment", async () => { + mkdirSync(join(home, ".codex"), { recursive: true }); + writeFileSync( + join(home, ".codex", "config.toml"), + '[mcp_servers.agentmemory]\ncommand = "npx" # launcher\nargs = ["-y", "@agentmemory/mcp"] # pkg\n', + ); + const { adapter } = await import("../src/cli/connect/codex.js"); + expect((await adapter.install({ dryRun: false, force: false })).kind).toBe("installed"); + const toml = readFileSync(join(home, ".codex", "config.toml"), "utf-8"); + expect(toml).toContain('command = "cmd" # launcher'); + expect(toml).toContain('args = ["/c", "npx", "-y", "@agentmemory/mcp"] # pkg'); + }); + + it("codex migrates a multiline args array with brackets in strings and comments", async () => { + mkdirSync(join(home, ".codex"), { recursive: true }); + writeFileSync( + join(home, ".codex", "config.toml"), + '[mcp_servers.agentmemory]\ncommand = "npx"\nargs = [\n "-y",\n "@agentmemory/mcp", # [required]\n "--filter=[foo]",\n]\n\n[mcp_servers.agentmemory.env]\nAGENTMEMORY_URL = "https://memory.example.com"\n', + ); + const { adapter } = await import("../src/cli/connect/codex.js"); + expect((await adapter.install({ dryRun: false, force: false })).kind).toBe("installed"); + const toml = readFileSync(join(home, ".codex", "config.toml"), "utf-8"); + expect(toml).toBe( + '[mcp_servers.agentmemory]\ncommand = "cmd"\nargs = ["/c", "npx", "-y", "@agentmemory/mcp"]\n\n[mcp_servers.agentmemory.env]\nAGENTMEMORY_URL = "https://memory.example.com"\n', + ); + expect((await adapter.install({ dryRun: false, force: false })).kind).toBe("already-wired"); + }); + + it("codex does not treat an unterminated args array as legacy", async () => { + mkdirSync(join(home, ".codex"), { recursive: true }); + const original = '[mcp_servers.agentmemory]\ncommand = "npx"\nargs = ["-y", "@agentmemory/mcp"\n'; + writeFileSync(join(home, ".codex", "config.toml"), original); + const { adapter } = await import("../src/cli/connect/codex.js"); + expect((await adapter.install({ dryRun: false, force: false })).kind).toBe("already-wired"); + expect(readFileSync(join(home, ".codex", "config.toml"), "utf-8")).toBe(original); + }); + + it("codex leaves a custom npx package untouched without --force", async () => { + mkdirSync(join(home, ".codex"), { recursive: true }); + const original = '[mcp_servers.agentmemory]\ncommand = "npx"\nargs = ["-y", "@team/custom-mcp"]\n'; + writeFileSync(join(home, ".codex", "config.toml"), original); + const { adapter } = await import("../src/cli/connect/codex.js"); + expect((await adapter.install({ dryRun: false, force: false })).kind).toBe("already-wired"); + expect(readFileSync(join(home, ".codex", "config.toml"), "utf-8")).toBe(original); + }); + + it("codex keeps existing env and options when it migrates the launcher", async () => { + mkdirSync(join(home, ".codex"), { recursive: true }); + writeFileSync( + join(home, ".codex", "config.toml"), + '[mcp_servers.agentmemory]\ncommand = "npx"\nargs = ["-y", "@agentmemory/mcp"]\nstartup_timeout_sec = 30\n\n[mcp_servers.agentmemory.env]\nAGENTMEMORY_URL = "https://memory.example.com"\nAGENTMEMORY_SECRET = "s3cret"\n\n[other]\nkey = 1\n', + ); + const { adapter } = await import("../src/cli/connect/codex.js"); + expect((await adapter.install({ dryRun: false, force: false })).kind).toBe("installed"); + const toml = readFileSync(join(home, ".codex", "config.toml"), "utf-8"); + expect(toml).toContain('command = "cmd"'); + expect(toml).toContain("startup_timeout_sec = 30"); + expect(toml).toContain('AGENTMEMORY_URL = "https://memory.example.com"'); + expect(toml).toContain('AGENTMEMORY_SECRET = "s3cret"'); + expect(toml).not.toContain("localhost:3111"); + expect(toml).toContain("[other]\nkey = 1"); + }); + + it("continue keeps existing env when it migrates the launcher", async () => { + mkdirSync(join(home, ".continue"), { recursive: true }); + const env = { AGENTMEMORY_URL: "https://memory.example.com", AGENTMEMORY_SECRET: "s3cret" }; + writeFileSync( + join(home, ".continue", "config.json"), + JSON.stringify({ mcpServers: [{ name: "agentmemory", command: "npx", args: ["-y", "@agentmemory/mcp"], env }] }), + ); + const { adapter } = await import("../src/cli/connect/continue.js"); + expect((await adapter.install({ dryRun: false, force: false })).kind).toBe("installed"); + const cfg = JSON.parse(readFileSync(join(home, ".continue", "config.json"), "utf-8")); + expect(cfg.mcpServers[0]).toMatchObject({ ...WINDOWS_MCP, env }); + }); + + it("opencode keeps existing environment and options when it migrates the launcher", async () => { + mkdirSync(join(home, ".config", "opencode"), { recursive: true }); + const environment = { AGENTMEMORY_URL: "https://memory.example.com", AGENTMEMORY_SECRET: "s3cret" }; + writeFileSync( + join(home, ".config", "opencode", "opencode.json"), + JSON.stringify({ mcp: { agentmemory: { type: "local", command: ["npx", "-y", "@agentmemory/mcp"], enabled: false, environment } } }), + ); + const { adapter } = await import("../src/cli/connect/opencode.js"); + expect((await adapter.install({ dryRun: false, force: false })).kind).toBe("installed"); + const cfg = JSON.parse(readFileSync(join(home, ".config", "opencode", "opencode.json"), "utf-8")); + expect(cfg.mcp.agentmemory).toEqual({ type: "local", command: ["cmd", ...WINDOWS_MCP.args], enabled: false, environment }); + }); + + it("dsh keeps existing env when it migrates the launcher", async () => { + mkdirSync(join(home, ".dsh"), { recursive: true }); + writeFileSync( + join(home, ".dsh", "cordis.patch.yml"), + "- insert:\n - id: agentmemory\n name: '@deepseek-ai/dsh-mcp-client'\n config:\n transport: stdio\n serverName: agentmemory\n command: npx\n args: ['-y', '@agentmemory/mcp']\n env:\n AGENTMEMORY_URL: https://memory.example.com\n AGENTMEMORY_SECRET: s3cret\n", + ); + const { adapter } = await import("../src/cli/connect/dsh.js"); + expect((await adapter.install({ dryRun: false, force: false })).kind).toBe("installed"); + const { parseDocument } = await import("yaml"); + const config = parseDocument(readFileSync(join(home, ".dsh", "cordis.patch.yml"), "utf-8")).toJS()[0].insert[0].config; + expect(config.command).toBe("cmd"); + expect(config.args).toEqual(WINDOWS_MCP.args); + expect(config.env).toEqual({ AGENTMEMORY_URL: "https://memory.example.com", AGENTMEMORY_SECRET: "s3cret" }); + }); + + it("dsh collapses duplicate agentmemory rows when it migrates the launcher", async () => { + mkdirSync(join(home, ".dsh"), { recursive: true }); + const row = (url: string) => + `- insert:\n - id: agentmemory\n name: '@deepseek-ai/dsh-mcp-client'\n config:\n transport: stdio\n serverName: agentmemory\n command: npx\n args: ['-y', '@agentmemory/mcp']\n env:\n AGENTMEMORY_URL: ${url}\n`; + const other = "- insert:\n - id: other\n name: other-plugin\n"; + writeFileSync(join(home, ".dsh", "cordis.patch.yml"), row("https://first.example.com") + other + row("https://second.example.com")); + const { adapter } = await import("../src/cli/connect/dsh.js"); + expect((await adapter.install({ dryRun: false, force: false })).kind).toBe("installed"); + const { parseDocument } = await import("yaml"); + const ops = parseDocument(readFileSync(join(home, ".dsh", "cordis.patch.yml"), "utf-8")).toJS(); + expect(ops).toHaveLength(2); + expect(ops[0].insert[0].config).toMatchObject({ command: "cmd", args: WINDOWS_MCP.args, env: { AGENTMEMORY_URL: "https://first.example.com" } }); + expect(ops[1].insert[0].id).toBe("other"); + }); + + it.each([true, false])("dsh migrates the legacy row and keeps a custom row, custom first: %s", async (customFirst) => { + mkdirSync(join(home, ".dsh"), { recursive: true }); + const row = (id: string, command: string, args: string, extra = "") => + `- insert:\n - id: ${id}\n name: '@deepseek-ai/dsh-mcp-client'\n${extra} config:\n transport: stdio\n serverName: agentmemory\n command: ${command}\n args: ${args}\n`; + const custom = row("agentmemory-custom", "custom-mcp", "['--port', '1']"); + const legacy = row("agentmemory", "npx", "['-y', '@agentmemory/mcp']", " disabled: true\n"); + writeFileSync(join(home, ".dsh", "cordis.patch.yml"), customFirst ? custom + legacy : legacy + custom); + const { adapter } = await import("../src/cli/connect/dsh.js"); + expect((await adapter.install({ dryRun: false, force: false })).kind).toBe("installed"); + const { parseDocument } = await import("yaml"); + const rows = parseDocument(readFileSync(join(home, ".dsh", "cordis.patch.yml"), "utf-8")) + .toJS() + .map((op: { insert: { id: string; disabled?: boolean; config: { command: string; args: string[] } }[] }) => op.insert[0]); + expect(rows).toHaveLength(2); + expect(rows.find((r: { id: string }) => r.id === "agentmemory-custom").config).toMatchObject({ command: "custom-mcp", args: ["--port", "1"] }); + expect(rows.find((r: { id: string }) => r.id === "agentmemory")).toMatchObject({ disabled: true, config: { command: "cmd", args: WINDOWS_MCP.args } }); + }); + + it("dsh leaves a custom npx package untouched without --force", async () => { + mkdirSync(join(home, ".dsh"), { recursive: true }); + const original = + "- insert:\n - id: agentmemory\n name: '@deepseek-ai/dsh-mcp-client'\n config:\n transport: stdio\n serverName: agentmemory\n command: npx\n args: ['-y', '@team/custom-mcp']\n"; + writeFileSync(join(home, ".dsh", "cordis.patch.yml"), original); + const { adapter } = await import("../src/cli/connect/dsh.js"); + expect((await adapter.install({ dryRun: false, force: false })).kind).toBe("already-wired"); + expect(readFileSync(join(home, ".dsh", "cordis.patch.yml"), "utf-8")).toBe(original); + }); + + it("droid hooks quote a plugin path with spaces", async () => { + mkdirSync(join(home, ".factory"), { recursive: true }); + const root = spacedPluginRoot(home); + pluginRootOverride.value = root; + const { adapter } = await import("../src/cli/connect/droid.js"); + expect((await adapter.install({ dryRun: false, force: false, withHooks: true })).kind).toBe("installed"); + const mcp = JSON.parse(readFileSync(join(home, ".factory", "mcp.json"), "utf-8")); + expect(mcp.mcpServers.agentmemory).toMatchObject({ ...WINDOWS_MCP, type: "stdio" }); + const hooks = JSON.parse(readFileSync(join(home, ".factory", "hooks.json"), "utf-8")); + for (const command of hookCommands(hooks.hooks)) { + expect(command).toMatch(QUOTED_NODE_COMMAND); + } + }); + + it("opencode writes a cmd-wrapped command array", async () => { + mkdirSync(join(home, ".config", "opencode"), { recursive: true }); + const { adapter } = await import("../src/cli/connect/opencode.js"); + expect((await adapter.install({ dryRun: false, force: false })).kind).toBe("installed"); + const cfg = JSON.parse(readFileSync(join(home, ".config", "opencode", "opencode.json"), "utf-8")); + expect(cfg.mcp.agentmemory.command).toEqual(["cmd", ...WINDOWS_MCP.args]); + }); + + it("zed reads its settings from %APPDATA%\\Zed", async () => { + const zedDir = join(home, "AppData", "Roaming", "Zed"); + mkdirSync(zedDir, { recursive: true }); + const { adapter } = await import("../src/cli/connect/zed.js"); + expect(adapter.detect()).toBe(true); + await adapter.install({ dryRun: false, force: false }); + const cfg = JSON.parse(readFileSync(join(zedDir, "settings.json"), "utf-8")); + expect(cfg.context_servers.agentmemory).toMatchObject(WINDOWS_MCP); + }); + + it("zed guideline lands beside the %APPDATA%\\Zed settings", async () => { + const { guidelineTargets } = await import("../src/cli/connect/guidelines.js"); + expect(guidelineTargets(home).zed.globalPath).toBe(join(home, "AppData", "Roaming", "Zed", "AGENTS.md")); + }); + + it("converts Windows separators in hook command paths", async () => { + const { toCommandPath } = await import("../src/cli/connect/util.js"); + expect(toCommandPath("C:\\Users\\Jane Doe\\plugin")).toBe("C:/Users/Jane Doe/plugin"); + }); + + it("antigravity hooks use the Windows short path when the install path has spaces", async () => { + mkdirSync(join(home, ".gemini", "antigravity-cli"), { recursive: true }); + const root = spacedPluginRoot(home); + pluginRootOverride.value = root; + const short = "C:/Users/JANEDO~1/AppData/Local/npm-cache/_npx/ABC123~1/plugin"; + const { installAntigravityCliHooks } = await import("../src/cli/connect/antigravity-cli.js"); + const shortPath = vi.fn(() => short); + + const result = installAntigravityCliHooks({ dryRun: false, force: false }, shortPath); + + expect(result.kind).toBe("installed"); + expect(shortPath).toHaveBeenCalledWith(root); + const hooks = JSON.parse(readFileSync(join(home, ".gemini", "config", "hooks.json"), "utf-8")); + const stop = hooks.agentmemory.Stop[0].command as string; + expect(stop).toBe(`node ${short}/scripts/antigravity-bridge.mjs Stop`); + expect(JSON.stringify(hooks)).not.toContain(" 123"); + }); + + it("antigravity refuses only the hooks and prints manual steps when no short path exists", async () => { + mkdirSync(join(home, ".gemini", "antigravity-cli"), { recursive: true }); + const root = spacedPluginRoot(home); + pluginRootOverride.value = root; + const { adapter, installAntigravityCliHooks } = await import("../src/cli/connect/antigravity-cli.js"); + + const result = installAntigravityCliHooks({ dryRun: false, force: false }, () => null); + + expect(result.kind).toBe("skipped"); + expect(existsSync(join(home, ".gemini", "config", "hooks.json"))).toBe(false); + const printed = log.message.mock.calls.map((call) => String(call[0])).join("\n"); + expect(printed).toContain(root); + expect(printed).toContain("node C:/agentmemory/plugin/scripts/antigravity-bridge.mjs Stop"); + + const mcpResult = await adapter.install({ dryRun: false, force: false }); + expect(mcpResult.kind).toBe("installed"); + const mcp = JSON.parse(readFileSync(join(home, ".gemini", "config", "mcp_config.json"), "utf-8")); + expect(mcp.mcpServers.agentmemory).toMatchObject(WINDOWS_MCP); + }); +});