Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
fix(pi): add generated bridge extension
AkitaOnRails59a1c8bbb497
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex b1cf1053..6b145a25 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -8,15 +8,18 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]### Fixed+- Pi is now supported through a generated `~/.pi/agent/extensions/ai-memory.ts`+ TypeScript extension that combines lifecycle capture with an HTTP MCP bridge;+ `install-hooks --agent pi --apply` writes it, while `install-mcp --client pi`+ prints bridge guidance instead of writing an ignored native `mcp.json`.- Generated OpenCode and OMP TypeScript lifecycle hooks now buffer captureposts through a bounded best-effort queue instead of spawning one unboundedfetch per event, reducing client-side request bursts while preserving directhandoff fetches.- Corrected the Pi vs Oh My Pi / OMP install split: OMP remains supported via`--client omp` / `--agent omp` (or `oh-my-pi`) and writes `.omp` config, while- real `pi` install commands now fail closed with guidance until the Pi bridge- lands. Users who previously used `pi` to mean OMP should switch to `omp` or- `oh-my-pi`.+ real `pi` remains a separate install surface. Users who previously used `pi`+ to mean OMP should switch to `omp` or `oh-my-pi`.## [1.5.0] - 2026-07-01diff --git a/README.md b/README.mdindex 1b7b520d..31db18d7 100644--- a/README.md+++ b/README.md@@ -28,7 +28,7 @@| Cursor | Supported | MCP config + lifecycle hooks. || Gemini CLI | Supported | MCP config + lifecycle hooks. || Oh My Pi / OMP | Supported | Use `--client omp` / `--agent omp` (or `oh-my-pi`) for native `.omp` MCP config + TypeScript extension. |-| Pi | Recognized, pending bridge | `--client pi` / `--agent pi` fail closed with guidance; real Pi MCP/hooks support needs the bridge tracked in #138. |+| Pi | Supported | Generated `~/.pi/agent/extensions/ai-memory.ts` extension provides lifecycle capture and an HTTP MCP bridge; use `install-hooks --agent pi --apply`. || Claude Desktop | MCP-only | Uses `mcp-remote`; no lifecycle hooks. || OpenClaw | Supported | MCP config + native plugin lifecycle hooks. || Antigravity CLI | Supported | MCP config (`serverUrl`) + lifecycle hooks (`agy` alias). |@@ -82,7 +82,7 @@ priors are at the [bottom](#influences-and-prior-art).- **Multi-agent + multi-machine ready.** Supported clients: ClaudeCode, Codex, OpenCode, Cursor, Claude Desktop (via `mcp-remote`),Gemini CLI, Antigravity CLI, Grok Build CLI, OpenClaw, Oh My Pi / OMP- (`omp` / `oh-my-pi`), recognized-but-pending Pi, and VS Code GitHub+ (`omp` / `oh-my-pi`), Pi via generated bridge extension, and VS Code GitHubCopilot agent mode(MCP-only, workspace `.vscode/mcp.json`).Server runs local (loopback) OR on a homelab box (LAN/VPN/cloud)diff --git a/crates/ai-memory-cli/src/commands/install_hooks.rs b/crates/ai-memory-cli/src/commands/install_hooks.rsindex 3cd8785e..006862fb 100644--- a/crates/ai-memory-cli/src/commands/install_hooks.rs+++ b/crates/ai-memory-cli/src/commands/install_hooks.rs@@ -103,6 +103,16 @@ pub(crate) fn omp_extension_path() -> anyhow::Result<std::path::PathBuf> {.join("ai-memory.ts"))}+/// `~/.pi/agent/extensions/ai-memory.ts` — Pi lifecycle + MCP bridge extension.+pub(crate) fn pi_extension_path() -> anyhow::Result<std::path::PathBuf> {+ Ok(home_dir()+ .context("could not locate $HOME for ~/.pi/agent/extensions")?+ .join(".pi")+ .join("agent")+ .join("extensions")+ .join("ai-memory.ts"))+}+/// Run the `install-hooks` subcommand.////// # Errors@@ -135,7 +145,7 @@ pub fn run(config: &Config, args: InstallHooksArgs) -> Result<()> {if args.apply {return match args.agent {AgentChoice::OpenCode => apply_to_opencode_plugin(&server_url, auth, &args),- AgentChoice::Pi => bail_pi_hooks_unsupported(),+ AgentChoice::Pi => apply_to_pi_extension(&server_url, auth, &args),AgentChoice::Omp => apply_to_omp_extension(&server_url, auth, &args),AgentChoice::ClaudeCode => {let hooks_dir = resolve_hooks_dir(args.hooks_dir.as_deref(), args.agent)?;@@ -179,7 +189,7 @@ pub fn run(config: &Config, args: InstallHooksArgs) -> Result<()> {let strategy = args.project_strategy.baked();match args.agent {AgentChoice::OpenCode => render_opencode_plugin(&server_url, auth, strategy),- AgentChoice::Pi => bail_pi_hooks_unsupported(),+ AgentChoice::Pi => render_pi_extension(&server_url, auth, strategy),AgentChoice::Omp => render_omp_extension(&server_url, auth, strategy),AgentChoice::ClaudeCode => {let hooks_dir = resolve_hooks_dir(args.hooks_dir.as_deref(), args.agent)?;@@ -360,12 +370,6 @@ fn mcp_client_for_agent(agent: AgentChoice) -> Option<McpClient> {}}-fn bail_pi_hooks_unsupported<T>() -> Result<T> {- anyhow::bail!(- "Pi hook install is recognized but not supported in ai-memory yet. This command will not write ~/.pi or ~/.omp files. If you meant Oh My Pi / OMP, use `ai-memory install-hooks --agent omp --apply`; real Pi support will arrive with the bridge in issue #138."- )-}-fn infer_json_mcp_config(content: &str,entry_path: &[&str],@@ -1480,6 +1484,171 @@ fn resolve_omp_extension_path(args: &InstallHooksArgs) -> Result<PathBuf> {omp_extension_path()}+fn apply_to_pi_extension(+ server_url: &str,+ auth_token: Option<&str>,+ args: &InstallHooksArgs,+) -> Result<()> {+ let path = resolve_pi_extension_path(args)?;+ let strategy = args.project_strategy.baked();+ let body = build_pi_extension(server_url, auth_token, strategy);++ let outcome = apply_atomic(&path, move |_existing| Ok(body.clone()))?;+ println!(+ "✓ {} {} ({})",+ outcome.verb(),+ path.display(),+ match outcome {+ ApplyOutcome::Created => "new Pi extension file",+ ApplyOutcome::Updated => "backup written next to it",+ ApplyOutcome::NoOp => "already up to date",+ }+ );+ if !matches!(outcome, ApplyOutcome::NoOp) {+ println!();+ println!("Pi loads TypeScript extensions from ~/.pi/agent/extensions/ on next start.");+ println!("Restart Pi for lifecycle capture and MCP tools to take effect.");+ }+ Ok(())+}++fn render_pi_extension(+ server_url: &str,+ auth_token: Option<&str>,+ project_strategy: Option<&str>,+) -> Result<()> {+ println!("// Pi extension — write to ~/.pi/agent/extensions/ai-memory.ts");+ println!("// Or re-run with `--apply` to install it automatically.");+ println!("// Restart Pi after changing extensions; MCP tools are bridged by this file.");+ println!();+ println!(+ "{}",+ build_pi_extension(server_url, auth_token, project_strategy)+ );+ Ok(())+}++fn resolve_pi_extension_path(args: &InstallHooksArgs) -> Result<PathBuf> {+ if let Some(p) = &args.config_file {+ return Ok(p.clone());+ }+ pi_extension_path()+}++fn build_pi_extension(+ server_url: &str,+ auth_token: Option<&str>,+ project_strategy: Option<&str>,+) -> String {+ let lifecycle = build_omp_extension(server_url, auth_token, project_strategy)+ .replace("install-hooks --agent omp --apply", "install-hooks --agent pi --apply")+ .replace("const AGENT = \"omp\";", "const AGENT = \"pi\";")+ .replace(+ r#"+ api.on("session.compacting", (_event: any, ctx: any) => {+ postPreCompact(ctx);+ });+"#,+ "\n",+ )+ .replace(+ "export default function AiMemoryExtension(api: any): void {",+ &format!(+ "{}\nexport default function AiMemoryExtension(pi: any): void {{\n try {{ void bootstrapMcpBridge(pi); }} catch (_e) {{}}",+ pi_mcp_bridge_source()+ ),+ )+ .replace("api.on(\"", "pi.on(\"");+ debug_assert!(!lifecycle.contains(".omp"));+ lifecycle+}++fn pi_mcp_bridge_source() -> &'static str {+ r#"+// ---- MCP bridge ------------------------------------------------------------+const MCP_SERVER = deriveMcpServer(SERVER);+const MCP_REQUEST_TIMEOUT_MS = 10000;+let mcpRequestId = 0;++function deriveMcpServer(server: string): string {+ const trimmed = server.replace(/\/+$/, "");+ return trimmed.endsWith("/mcp") ? trimmed : `${trimmed}/mcp`;+}++function mcpSessionId(ctx: any): string | undefined {+ const id = sessionID(ctx) ?? ctx?.sessionId ?? ctx?.sessionID ?? ctx?.session?.id;+ return typeof id === "string" && id.length > 0 ? id : undefined;+}++function mcpSignal(signal?: AbortSignal): AbortSignal | undefined {+ const timeout = timeoutSignal(MCP_REQUEST_TIMEOUT_MS);+ if (!signal) return timeout;+ if (!timeout) return signal;+ const anyFactory = (AbortSignal as unknown as { any?: (signals: AbortSignal[]) => AbortSignal }).any;+ return anyFactory ? anyFactory([signal, timeout]) : timeout;+}++async function mcpRpc(method: string, params?: unknown, ctx?: any, signal?: AbortSignal): Promise<any> {+ const id = ++mcpRequestId;+ const headers: Record<string, string> = {+ "Content-Type": "application/json",+ "Accept": "application/json, text/event-stream",+ ...authHeaders(),+ };+ const session = mcpSessionId(ctx);+ if (session) {+ headers["X-Memory-Actor-Session-Id"] = session;+ headers["Mcp-Session-Id"] = session;+ }+ const response = await fetch(MCP_SERVER, {+ method: "POST",+ headers,+ body: JSON.stringify({ jsonrpc: "2.0", id, method, params: params ?? {} }),+ signal: mcpSignal(signal),+ });+ if (!response.ok) throw new Error(`ai-memory MCP ${method} failed: HTTP ${response.status}`);+ const payload = await response.json();+ if (payload?.error) throw new Error(`ai-memory MCP ${method} failed: ${payload.error.message ?? JSON.stringify(payload.error)}`);+ if (payload?.result?.isError) throw new Error(`ai-memory MCP ${method} returned isError`);+ return payload?.result;+}++function toolInputSchema(tool: any): any {+ return tool?.inputSchema ?? { type: "object", additionalProperties: true };+}++async function bootstrapMcpBridge(pi: any): Promise<void> {+ try {+ await mcpRpc("initialize", {+ protocolVersion: "2025-03-26",+ capabilities: {},+ clientInfo: { name: "ai-memory-pi-extension", version: "0.0.0" },+ });+ try { await mcpRpc("notifications/initialized"); } catch (_e) {}+ const listed = await mcpRpc("tools/list");+ for (const tool of listed?.tools ?? []) {+ try {+ pi.registerTool({+ name: tool.name,+ label: tool.name,+ description: tool.description,+ parameters: toolInputSchema(tool),+ execute: async (_toolCallId: string, params: unknown, signal?: AbortSignal, _onUpdate?: unknown, ctx?: any) => {+ const result = await mcpRpc("tools/call", { name: tool.name, arguments: params ?? {} }, ctx, signal);+ return { content: result?.content ?? [], details: result };+ },+ });+ } catch (_e) {+ // Duplicate registration or tool-shape mismatch must not break lifecycle capture.+ }+ }+ } catch (_e) {+ // MCP bridge is best-effort; extension load and lifecycle capture must survive.+ }+}+"#+}+fn build_omp_extension(server_url: &str,auth_token: Option<&str>,@@ -1771,6 +1940,10 @@ export default function AiMemoryExtension(api: any): void {{postPreCompact(ctx);}});+ api.on("session_compact", (_event: any, ctx: any) => {{+ postPreCompact(ctx);+ }});+api.on("session.compacting", (_event: any, ctx: any) => {{postPreCompact(ctx);}});@@ -3221,7 +3394,7 @@ model = "gpt-5"}#[test]- fn pi_hook_install_fails_closed_without_writing_even_with_config_override() {+ fn pi_extension_is_directly_discoverable_by_pi() {let tmp = TempDir::new().unwrap();let path = tmp.path().join("extensions").join("ai-memory.ts");let args = InstallHooksArgs {@@ -3235,10 +3408,75 @@ model = "gpt-5"project_strategy: ProjectStrategyArg::Basename,};- let err = run(&Config::default(), args).unwrap_err().to_string();+ let resolved = resolve_pi_extension_path(&args).unwrap();- assert!(err.contains("--agent omp"), "unexpected error: {err}");- assert!(!path.exists(), "Pi hook install must not write files");+ assert_eq!(resolved, path);+ assert_eq!(+ resolved.file_name().and_then(|s| s.to_str()),+ Some("ai-memory.ts")+ );+ assert_eq!(+ resolved+ .parent()+ .and_then(|p| p.file_name())+ .and_then(|s| s.to_str()),+ Some("extensions")+ );+ }++ #[test]+ fn pi_extension_contains_lifecycle_capture_and_mcp_bridge() {+ let extension = build_pi_extension("http://127.0.0.1:49374/base", Some("tok"), None);++ assert!(extension.contains("export default function AiMemoryExtension(pi: any): void"));+ assert!(extension.contains("const AGENT = \"pi\";"));+ assert!(extension.contains("pi.on(\"session_start\""));+ assert!(extension.contains("pi.on(\"before_agent_start\""));+ assert!(extension.contains("pi.on(\"tool_call\""));+ assert!(extension.contains("pi.on(\"tool_result\""));+ assert!(extension.contains("pi.on(\"session_before_compact\""));+ assert!(extension.contains("pi.on(\"session_compact\""));+ assert!(!extension.contains("pi.on(\"session.compacting\""));+ assert!(extension.contains("pi.on(\"agent_end\""));+ assert!(extension.contains("pi.on(\"session_shutdown\""));+ assert!(extension.contains("postHook(\"session-start\""));+ assert!(extension.contains("postHook(\"user-prompt\""));+ assert!(extension.contains("postHook(\"pre-tool-use\""));+ assert!(extension.contains("postHook(\"post-tool-use\""));+ assert!(extension.contains("postHook(\"pre-compact\""));+ assert!(extension.contains("postHook(\"stop\""));+ assert!(extension.contains("postHook(\"session-end\""));+ assert!(extension.contains("fetchHandoff"));+ assert!(extension.contains("customType: \"ai-memory-handoff\""));+ assert!(extension.contains("const MCP_SERVER = deriveMcpServer(SERVER);"));+ assert!(+ extension.contains("return trimmed.endsWith(\"/mcp\") ? trimmed : `${trimmed}/mcp`;")+ );+ assert!(extension.contains("\"Accept\": \"application/json, text/event-stream\""));+ assert!(extension.contains("...authHeaders()"));+ assert!(extension.contains("headers[\"X-Memory-Actor-Session-Id\"] = session;"));+ assert!(extension.contains("headers[\"Mcp-Session-Id\"] = session;"));+ assert!(extension.contains("function mcpSignal(signal?: AbortSignal)"));+ assert!(extension.contains("anyFactory([signal, timeout])"));+ assert!(extension.contains("mcpRpc(\"initialize\""));+ assert!(extension.contains("mcpRpc(\"notifications/initialized\""));+ assert!(extension.contains("mcpRpc(\"tools/list\""));+ assert!(extension.contains("pi.registerTool"));+ assert!(extension.contains("label: tool.name"));+ assert!(extension.contains("parameters: toolInputSchema(tool)"));+ assert!(extension.contains(+ "mcpRpc(\"tools/call\", { name: tool.name, arguments: params ?? {} }, ctx, signal)"+ ));+ assert!(extension.contains("payload?.error"));+ assert!(extension.contains("payload?.result?.isError"));+ assert!(extension.contains("response.ok"));+ assert!(extension.contains("signal: mcpSignal(signal)"));+ assert!(extension.contains("Bearer ${TOKEN}"));+ assert!(extension.contains("tok"));+ assert!(extension.contains("import { execFileSync } from \"node:child_process\";"));+ assert!(!extension.contains(".omp"));+ assert!(!extension.contains("serve --transport stdio"));+ assert!(!extension.contains("serve --stdio"));}// Windows 11 + Git Bash support matters for regulated enterprise setups@@ -3283,8 +3521,9 @@ model = "gpt-5"assert!(stdout.contains("~/.omp/agent/extensions/ai-memory.ts"));}"pi" => {- assert!(stdout.contains("does not install real Pi hooks yet"));- assert!(!stdout.contains("install-hooks --agent omp --apply"));+ assert!(stdout.contains("install-hooks --agent pi --apply"));+ assert!(stdout.contains("~/.pi/agent/extensions/ai-memory.ts"));+ assert!(stdout.contains("MCP tools come through the same generated bridge"));assert!(!stdout.contains("~/.omp/agent/extensions/ai-memory.ts"));}_ => unreachable!(),diff --git a/crates/ai-memory-cli/src/commands/install_mcp.rs b/crates/ai-memory-cli/src/commands/install_mcp.rsindex 1f814f6c..08da1cf3 100644--- a/crates/ai-memory-cli/src/commands/install_mcp.rs+++ b/crates/ai-memory-cli/src/commands/install_mcp.rs@@ -144,7 +144,9 @@ pub(crate) fn mcp_config_path(client: crate::cli::McpClient) -> Result<PathBuf>}McpClient::GeminiCli => home()?.join(".gemini").join("settings.json"),McpClient::Openclaw => home()?.join(".openclaw").join("config.json"),- McpClient::Pi => bail!(pi_mcp_unsupported_message()),+ McpClient::Pi => bail!(+ "Pi has no native mcp.json; use `ai-memory install-hooks --agent pi --apply` to install the generated MCP bridge extension."+ ),McpClient::Omp => home()?.join(".omp").join("agent").join("mcp.json"),McpClient::AntigravityCli => home()?.join(".gemini")@@ -176,7 +178,7 @@ fn resolve_config_file(args: &InstallMcpArgs) -> Result<PathBuf> {/// re-runs that produce the same content are reported as no-op.fn apply_to_config_file(args: &InstallMcpArgs) -> Result<()> {if matches!(args.client, McpClient::Pi) {- bail!(pi_mcp_unsupported_message());+ bail!(pi_mcp_apply_guidance(args));}let path = resolve_config_file(args)?;let outcome = match args.client {@@ -613,12 +615,40 @@ fn render_openclaw(args: &InstallMcpArgs) -> Result<String> {}fn render_pi(args: &InstallMcpArgs) -> Result<String> {- let _ = args;- bail!(pi_mcp_unsupported_message())+ Ok(pi_mcp_render_guidance(args))}-fn pi_mcp_unsupported_message() -> &'static str {- "Pi core has no native MCP config support in ai-memory yet. If you meant Oh My Pi / OMP, use `ai-memory install-mcp --client omp`; real Pi MCP support will be added by the bridge in issue #138."+fn pi_mcp_render_guidance(args: &InstallMcpArgs) -> String {+ format!(+ "# Pi has no native mcp.json. Do not write ~/.pi/agent/mcp.json.\n\+ # Install ai-memory's generated Pi extension instead; it includes\n\+ # lifecycle capture and an HTTP MCP bridge that registers tools in Pi.\n\+ ai-memory install-hooks --agent pi --apply --server-url {}{}\n\+ # Restart Pi after installing ~/.pi/agent/extensions/ai-memory.ts.\n",+ hook_server_url_from_mcp_url(&args.server_url),+ if args.auth_token.is_some() {+ " --auth-token <token>"+ } else {+ ""+ }+ )+}++fn pi_mcp_apply_guidance(args: &InstallMcpArgs) -> String {+ format!(+ "Pi has no native mcp.json; refusing to write MCP config. Install the generated bridge instead: ai-memory install-hooks --agent pi --apply --server-url {}{}",+ hook_server_url_from_mcp_url(&args.server_url),+ if args.auth_token.is_some() {+ " --auth-token <token>"+ } else {+ ""+ }+ )+}++fn hook_server_url_from_mcp_url(url: &str) -> String {+ let trimmed = url.trim().trim_end_matches('/');+ trimmed.strip_suffix("/mcp").unwrap_or(trimmed).to_string()}fn render_omp(args: &InstallMcpArgs) -> Result<String> {@@ -838,12 +868,11 @@ mod tests {assert!(render_for_test(McpClient::Openclaw).contains("\"streamable-http\""));assert!(render_for_test(McpClient::Codex).contains("[mcp_servers.ai-memory]"));assert!(render_for_test(McpClient::Omp).contains("~/.omp/agent/mcp.json"));- assert!(- render_pi(&args_for(McpClient::Pi))- .unwrap_err()- .to_string()- .contains("--client omp")- );+ let pi = render_pi(&args_for(McpClient::Pi)).unwrap();+ assert!(pi.contains("Pi has no native mcp.json"));+ assert!(pi.contains("install-hooks --agent pi --apply"));+ assert!(pi.contains("~/.pi/agent/extensions/ai-memory.ts"));+ assert!(!pi.contains("~/.omp"));assert!(render_for_test(McpClient::AntigravityCli).contains("\"serverUrl\""));// VS Code Copilot must use the `servers` top-level key — the// `mcpServers` form is silently ignored by VS Code's MCP@@ -865,10 +894,29 @@ mod tests {let err = apply_to_config_file(&args).unwrap_err().to_string();- assert!(err.contains("--client omp"), "unexpected error: {err}");+ assert!(+ err.contains("has no native mcp.json"),+ "unexpected error: {err}"+ );+ assert!(+ err.contains("install-hooks --agent pi --apply"),+ "unexpected error: {err}"+ );assert!(!path.exists(), "Pi install must not write ignored config");}+ #[test]+ fn pi_guidance_derives_hook_url_from_mcp_url() {+ let mut args = args_for(McpClient::Pi);+ args.server_url = "http://host:49374/base/mcp".into();+ args.auth_token = Some("tok".into());++ let guidance = render_pi(&args).unwrap();++ assert!(guidance.contains("--server-url http://host:49374/base --auth-token <token>"));+ assert!(!guidance.contains("--server-url http://host:49374/base/mcp"));+ }+/// The Codex apply path must emit block-form `[mcp_servers.<name>]`/// headers, NOT a dotted inline-table on one line. Regression/// guard: M22 originally created `mcp_servers = { ai-memory = {...} }`diff --git a/crates/ai-memory-cli/src/commands/setup_agent.rs b/crates/ai-memory-cli/src/commands/setup_agent.rsindex 89c57360..95b3a1e8 100644--- a/crates/ai-memory-cli/src/commands/setup_agent.rs+++ b/crates/ai-memory-cli/src/commands/setup_agent.rs@@ -59,14 +59,9 @@ pub fn run(config: &Config, args: SetupAgentArgs) -> Result<()> {auth_token: args.auth_token.or_else(|| config.auth.bearer_token.clone()),..args};- if matches!(args.agent, AgentChoice::Pi) {- bail!(- "Pi setup is recognized but not supported in ai-memory yet. This command will not write ~/.pi or ~/.omp files. If you meant Oh My Pi / OMP, use the OMP agent/client names instead; real Pi support will arrive with the bridge in issue #138."- );- }if matches!(args.agent,- AgentChoice::OpenCode | AgentChoice::Omp | AgentChoice::Openclaw+ AgentChoice::OpenCode | AgentChoice::Pi | AgentChoice::Omp | AgentChoice::Openclaw) {emit_extension_setup_hint(&args)?;return Ok(());@@ -174,6 +169,12 @@ fn emit_extension_setup_hint(args: &SetupAgentArgs) -> Result<()> {"Then restart OMP so it loads ~/.omp/agent/extensions/ai-memory.ts.","omp",),+ AgentChoice::Pi => (+ "Pi",+ "pi",+ "Then restart Pi so it loads ~/.pi/agent/extensions/ai-memory.ts.",+ "pi",+ ),AgentChoice::Openclaw => ("OpenClaw","openclaw",@@ -194,7 +195,13 @@ fn emit_extension_setup_hint(args: &SetupAgentArgs) -> Result<()> {}println!();println!("{restart_note}");- println!("Also run `ai-memory install-mcp --client {mcp_client}` to wire MCP separately.");+ if matches!(args.agent, AgentChoice::Pi) {+ println!(+ "MCP tools come through the same generated Pi bridge extension; no native mcp.json is written."+ );+ } else {+ println!("Also run `ai-memory install-mcp --client {mcp_client}` to wire MCP separately.");+ }Ok(())}@@ -408,7 +415,7 @@ mod tests {}#[test]- fn pi_setup_fails_closed_before_copying() {+ fn pi_setup_prints_extension_hint_without_copying() {let tmp = tempfile::TempDir::new().unwrap();let args = SetupAgentArgs {agent: AgentChoice::Pi,@@ -419,9 +426,8 @@ mod tests {source: Some(tmp.path().join("source")),};- let err = run(&Config::default(), args).unwrap_err().to_string();+ run(&Config::default(), args).unwrap();- assert!(err.contains("real Pi support"), "unexpected error: {err}");assert!(!tmp.path().join("hooks").exists());}diff --git a/crates/ai-memory-cli/src/commands/uninstall.rs b/crates/ai-memory-cli/src/commands/uninstall.rsindex c5f04d8c..a9db75e7 100644--- a/crates/ai-memory-cli/src/commands/uninstall.rs+++ b/crates/ai-memory-cli/src/commands/uninstall.rs@@ -41,6 +41,7 @@ enum RewriteOp {#[derive(Debug, Clone, Copy, PartialEq, Eq)]enum DeleteKind {OpenCodePlugin,+ PiExtension,OmpExtension,OpenClawPackageJson,OpenClawManifest,@@ -52,6 +53,7 @@ impl DeleteKind {const fn label(self) -> &'static str {match self {Self::OpenCodePlugin => "OpenCode plugin",+ Self::PiExtension => "Pi extension",Self::OmpExtension => "OMP extension",Self::OpenClawPackageJson => "OpenClaw package manifest",Self::OpenClawManifest => "OpenClaw plugin manifest",@@ -161,6 +163,9 @@ fn build_plan(args: &UninstallArgs) -> anyhow::Result<Vec<PlannedChange>> {let omp = install_hooks::omp_extension_path()?;push_generated_delete(&mut plan, omp, DeleteKind::OmpExtension);+ let pi = install_hooks::pi_extension_path()?;+ push_generated_delete(&mut plan, pi, DeleteKind::PiExtension);+let openclaw_dir = openclaw_plugin::default_plugin_dir()?;push_generated_delete(&mut plan,@@ -613,6 +618,11 @@ fn generated_file_is_ours(path: &Path, kind: DeleteKind) -> bool {content.contains("Auto-generated by `ai-memory install-hooks --agent omp --apply`")&& content.contains("const AGENT = \"omp\";")}+ DeleteKind::PiExtension => {+ content.contains("Auto-generated by `ai-memory install-hooks --agent pi --apply`")+ && content.contains("const AGENT = \"pi\";")+ && content.contains("pi.registerTool")+ }DeleteKind::OpenClawEntrypoint => {content.contains("Auto-generated by `ai-memory install-hooks --agent openclaw --apply`")&& content.contains("definePluginEntry")diff --git a/crates/ai-memory-cli/tests/removal.rs b/crates/ai-memory-cli/tests/removal.rsindex c63239b6..ea3ed4a9 100644--- a/crates/ai-memory-cli/tests/removal.rs+++ b/crates/ai-memory-cli/tests/removal.rs@@ -256,6 +256,40 @@ fn uninstall_omp_extension_deletes_only_generated_file() {assert!(!extension.exists(), "generated extension should be deleted");}+#[test]+fn uninstall_pi_extension_deletes_only_generated_bridge_file() {+ let _guard = cli_test_lock();+ let home = tempfile::tempdir().unwrap();+ let extensions = home.path().join(".pi/agent/extensions");+ std::fs::create_dir_all(&extensions).unwrap();+ let extension = extensions.join("ai-memory.ts");+ let user_content = "// user-owned Pi extension\n";+ std::fs::write(&extension, user_content).unwrap();++ let status = command_with_home(home.path())+ .args(["uninstall", "--apply", "--only", "hooks", "--yes"])+ .status()+ .unwrap();+ assert!(status.success(), "uninstall failed");+ assert_eq!(std::fs::read_to_string(&extension).unwrap(), user_content);++ std::fs::write(+ &extension,+ "// Auto-generated by `ai-memory install-hooks --agent pi --apply`.\nconst AGENT = \"pi\";\npi.registerTool({ name: \"memory_status\" });\n",+ )+ .unwrap();++ let status = command_with_home(home.path())+ .args(["uninstall", "--apply", "--only", "hooks", "--yes"])+ .status()+ .unwrap();+ assert!(status.success(), "uninstall failed");+ assert!(+ !extension.exists(),+ "generated Pi extension should be deleted"+ );+}+#[test]fn uninstall_preserves_user_openclaw_package_at_ai_memory_path() {let _guard = cli_test_lock();diff --git a/crates/ai-memory-core/src/ids.rs b/crates/ai-memory-core/src/ids.rsindex ebb401e9..80db8a6f 100644--- a/crates/ai-memory-core/src/ids.rs+++ b/crates/ai-memory-core/src/ids.rs@@ -191,8 +191,11 @@ pub enum AgentKind {OpenClaw,/// Google Antigravity CLI (`agy`).AntigravityCli,- /// Oh My Pi (`omp`) / Pi-compatible coding agent.+ /// Oh My Pi (`omp`) coding agent.Omp,+ /// Pi coding agent.+ #[serde(rename = "pi")]+ Pi,/// xAI Grok Build CLI (`grok`).Grok,/// Anything else (manual capture, future agents).@@ -213,6 +216,7 @@ impl AgentKind {Self::OpenClaw => "openclaw",Self::AntigravityCli => "antigravity-cli",Self::Omp => "omp",+ Self::Pi => "pi",Self::Grok => "grok",Self::Other => "other",}@@ -232,7 +236,8 @@ impl AgentKind {"claude-desktop" | "claude_desktop" => Self::ClaudeDesktop,"openclaw" | "open-claw" => Self::OpenClaw,"antigravity-cli" | "antigravity" | "agy" => Self::AntigravityCli,- "omp" | "pi" | "oh-my-pi" => Self::Omp,+ "pi" => Self::Pi,+ "omp" | "oh-my-pi" => Self::Omp,"grok" => Self::Grok,_ => Self::Other,}@@ -346,6 +351,17 @@ mod tests {let omp = serde_json::to_string(&AgentKind::Omp).unwrap();assert_eq!(omp, "\"omp\"");+ assert_eq!(AgentKind::from_wire("omp"), AgentKind::Omp);+ assert_eq!(AgentKind::from_wire("oh-my-pi"), AgentKind::Omp);++ let pi = serde_json::to_string(&AgentKind::Pi).unwrap();+ assert_eq!(pi, "\"pi\"");+ assert_eq!(AgentKind::Pi.as_str(), "pi");+ assert_eq!(AgentKind::from_wire("pi"), AgentKind::Pi);+ assert_eq!(+ serde_json::from_str::<AgentKind>(&pi).unwrap(),+ AgentKind::Pi+ );let openclaw = serde_json::to_string(&AgentKind::OpenClaw).unwrap();assert_eq!(openclaw, "\"openclaw\"");diff --git a/crates/ai-memory-hooks/src/payload.rs b/crates/ai-memory-hooks/src/payload.rsindex e4d140f5..51b9f978 100644--- a/crates/ai-memory-hooks/src/payload.rs+++ b/crates/ai-memory-hooks/src/payload.rs@@ -903,7 +903,7 @@ mod tests {assert_eq!(parse_agent("antigravity"), AgentKind::AntigravityCli);assert_eq!(parse_agent("agy"), AgentKind::AntigravityCli);assert_eq!(parse_agent("omp"), AgentKind::Omp);- assert_eq!(parse_agent("pi"), AgentKind::Omp);+ assert_eq!(parse_agent("pi"), AgentKind::Pi);assert_eq!(parse_agent("oh-my-pi"), AgentKind::Omp);// Anything else is `Other`. Critical for the hook router:// a typo in the query string must not crash, it just getsdiff --git a/crates/ai-memory-store/migrations/V25__sessions_pi_agent_kind.sql b/crates/ai-memory-store/migrations/V25__sessions_pi_agent_kind.sqlnew file mode 100644index 00000000..353f3a2a--- /dev/null+++ b/crates/ai-memory-store/migrations/V25__sessions_pi_agent_kind.sql@@ -0,0 +1,59 @@+-- Expand sessions.agent_kind CHECK for Pi coding agent (`pi`).+--+-- V09/V11/V20 intentionally enumerated every supported agent. Adding a+-- concrete AgentKind must update the persisted CHECK too, or Pi hook events+-- fail at begin_session on upgraded databases (the hook router would WARN+-- and drop the session, silently breaking Pi capture server-side).++PRAGMA foreign_keys = OFF;++DROP TRIGGER IF EXISTS auto_improve_scheduler_claims_session_pairing_ai;++CREATE TABLE sessions_new (+ id BLOB PRIMARY KEY NOT NULL,+ workspace_id BLOB NOT NULL REFERENCES workspaces(id) ON DELETE CASCADE,+ project_id BLOB NOT NULL REFERENCES projects(id) ON DELETE CASCADE,+ agent_kind TEXT NOT NULL CHECK (agent_kind IN ('claude-code','codex','open-code','cursor','gemini-cli','claude-desktop','openclaw','antigravity-cli','omp','pi','grok','other')),+ cwd TEXT,+ started_at INTEGER NOT NULL,+ ended_at INTEGER,+ summary_page_id BLOB REFERENCES pages(id) ON DELETE SET NULL+);++INSERT INTO sessions_new SELECT * FROM sessions;++DROP TABLE sessions;++ALTER TABLE sessions_new RENAME TO sessions;++CREATE INDEX idx_sessions_recent ON sessions(workspace_id, project_id, started_at DESC);+CREATE INDEX idx_sessions_project ON sessions(project_id);+CREATE INDEX idx_sessions_started_at ON sessions(started_at DESC);+CREATE INDEX idx_sessions_scope_ended+ ON sessions(workspace_id, project_id, ended_at ASC)+ WHERE ended_at IS NOT NULL;++-- Recreate the V18 pairing-enforcement trigger: dropping the old `sessions`+-- table above also dropped its triggers. Every sessions-table rebuild after+-- V18 must reinstate it or the (workspace_id, project_id) pairing invariant+-- silently stops being enforced on inserts.+CREATE TRIGGER sessions_ws_proj_pairing_ai+BEFORE INSERT ON sessions+FOR EACH ROW+WHEN NEW.workspace_id IS NOT (SELECT workspace_id FROM projects WHERE id = NEW.project_id)+BEGIN+ SELECT RAISE(ABORT, 'sessions.workspace_id does not match the project''s workspace');+END;++-- Recreate the V22 claim/session pairing trigger, which references `sessions`+-- and must be dropped before the table rebuild above.+CREATE TRIGGER auto_improve_scheduler_claims_session_pairing_ai+BEFORE INSERT ON auto_improve_scheduler_claims+FOR EACH ROW+WHEN NEW.workspace_id IS NOT (SELECT workspace_id FROM sessions WHERE id = NEW.session_id)+ OR NEW.project_id IS NOT (SELECT project_id FROM sessions WHERE id = NEW.session_id)+BEGIN+ SELECT RAISE(ABORT, 'auto_improve_scheduler_claims scope does not match the session scope');+END;++PRAGMA foreign_keys = ON;diff --git a/crates/ai-memory-store/src/ops.rs b/crates/ai-memory-store/src/ops.rsindex 307a397e..68061796 100644--- a/crates/ai-memory-store/src/ops.rs+++ b/crates/ai-memory-store/src/ops.rs@@ -1921,6 +1921,7 @@ mod tests {AgentKind::OpenClaw,AgentKind::AntigravityCli,AgentKind::Omp,+ AgentKind::Pi,AgentKind::Grok,AgentKind::Other,] {@@ -2648,6 +2649,123 @@ mod tests {assert_eq!(fk_violations, 0, "V20 must leave foreign keys clean");}+ #[test]+ fn v25_adds_pi_and_preserves_sessions_invariants_on_upgraded_db() {+ use ai_memory_core::{AgentKind, NewSession, SessionId};++ let tmp = TempDir::new().unwrap();+ let db_path = tmp.path().join("test.sqlite");+ let ws;+ let proj;+ let existing_sid = SessionId::new();++ {+ let mut conn = Connection::open(&db_path).unwrap();+ conn.pragma_update(None, "foreign_keys", "OFF").unwrap();+ crate::migrations::run_to(&mut conn, 24).unwrap();+ conn.pragma_update(None, "foreign_keys", "ON").unwrap();+ ws = get_or_create_workspace(&mut conn, "default").unwrap();+ proj = get_or_create_project(&mut conn, &ws, "scratch", None).unwrap();+ begin_session(+ &mut conn,+ &NewSession {+ id: existing_sid,+ workspace_id: ws,+ project_id: proj,+ agent_kind: AgentKind::ClaudeCode,+ cwd: None,+ },+ )+ .unwrap();+ }++ let mut conn = Connection::open(&db_path).unwrap();+ conn.pragma_update(None, "foreign_keys", "OFF").unwrap();+ crate::migrations::run_to(&mut conn, 25).unwrap();+ conn.pragma_update(None, "foreign_keys", "ON").unwrap();++ begin_session(+ &mut conn,+ &NewSession {+ id: SessionId::new(),+ workspace_id: ws,+ project_id: proj,+ agent_kind: AgentKind::Pi,+ cwd: None,+ },+ )+ .unwrap();++ let session_count: i64 = conn+ .query_row("SELECT COUNT(*) FROM sessions", [], |r| r.get(0))+ .unwrap();+ assert_eq!(session_count, 2, "V25 must preserve existing sessions");++ let index_count: i64 = conn+ .query_row(+ "SELECT COUNT(*) FROM sqlite_master \+ WHERE type = 'index' \+ AND name IN ('idx_sessions_recent', 'idx_sessions_project', 'idx_sessions_started_at', 'idx_sessions_scope_ended')",+ [],+ |r| r.get(0),+ )+ .unwrap();+ assert_eq!(index_count, 4, "V25 must recreate sessions indexes");++ let trigger_count: i64 = conn+ .query_row(+ "SELECT COUNT(*) FROM sqlite_master \+ WHERE type = 'trigger' AND name = 'sessions_ws_proj_pairing_ai'",+ [],+ |r| r.get(0),+ )+ .unwrap();+ assert_eq!(+ trigger_count, 1,+ "V25 must recreate the V18 pairing trigger"+ );++ let scheduler_trigger_count: i64 = conn+ .query_row(+ "SELECT COUNT(*) FROM sqlite_master \+ WHERE type = 'trigger' AND name = 'auto_improve_scheduler_claims_session_pairing_ai'",+ [],+ |r| r.get(0),+ )+ .unwrap();+ assert_eq!(+ scheduler_trigger_count, 1,+ "V25 must recreate the V22 scheduler/session pairing trigger"+ );++ let other_ws = get_or_create_workspace(&mut conn, "other").unwrap();+ let other_proj =+ get_or_create_project(&mut conn, &other_ws, "other-project", None).unwrap();+ let err = begin_session(+ &mut conn,+ &NewSession {+ id: SessionId::new(),+ workspace_id: ws,+ project_id: other_proj,+ agent_kind: AgentKind::Pi,+ cwd: None,+ },+ )+ .unwrap_err();+ assert!(+ err.to_string()+ .contains("sessions.workspace_id does not match"),+ "pairing trigger must reject split-brain sessions after V25: {err}"+ );++ let fk_violations: i64 = conn+ .query_row("SELECT COUNT(*) FROM pragma_foreign_key_check", [], |r| {+ r.get(0)+ })+ .unwrap();+ assert_eq!(fk_violations, 0, "V25 must leave foreign keys clean");+ }+/// V19 is idempotent: re-running on a repaired DB is a no-op./// Also asserts the initial run on a clean DB (no orphans, no/// empty fragments) is a no-op.diff --git a/docs/install.md b/docs/install.mdindex 14e01d2a..e15d8501 100644--- a/docs/install.md+++ b/docs/install.md@@ -9,7 +9,7 @@ path (docker + Claude Code). This page covers everything else:- [Arch Linux native packages (AUR)](#arch-linux-native-packages-aur)(systemd system service or user service)- [Configuring other agent CLIs](#configuring-other-agent-clis)- (Codex, OpenCode, OMP, Cursor, Claude Desktop, Gemini CLI, Antigravity CLI, Grok Build CLI, OpenClaw, VS Code Copilot)+ (Codex, OpenCode, OMP, Pi, Cursor, Claude Desktop, Gemini CLI, Antigravity CLI, Grok Build CLI, OpenClaw, VS Code Copilot)- [Installing hooks without docker](#installing-hooks-without-docker)(curl-based installer)- [Running ai-memory without docker](#running-ai-memory-without-docker)@@ -548,9 +548,26 @@ ai-memory install-hooks --agent omp --apply \Restart OMP after installing or changing the extension; extensions areloaded at startup. The ai-memory CLI accepts `--client omp` (or`--client oh-my-pi`) for MCP and `--agent omp` (or `--agent oh-my-pi`)-for hooks; both target OMP's native `.omp` integration surface. Real Pi-is recognized separately, but `--client pi` and `--agent pi` fail closed-until the Pi bridge lands in #138.+for hooks; both target OMP's native `.omp` integration surface.++### Pi++Pi does not read a native `mcp.json`. ai-memory supports Pi through one+generated TypeScript extension at `~/.pi/agent/extensions/ai-memory.ts`; the+same file captures lifecycle events and bridges ai-memory's HTTP MCP tools into+Pi with `pi.registerTool`.++```bash+ai-memory install-hooks --agent pi --apply \+ --server-url "http://homelab:49374" \+ --auth-token "$TOKEN"++# `install-mcp --client pi` prints this guidance instead of writing mcp.json:+ai-memory install-mcp --client pi --server-url "http://homelab:49374/mcp"+```++Restart Pi after installing or changing the extension. OMP / Oh My Pi remains+separate and continues to use `.omp` paths.### Bind mounts vs docker cp@@ -663,10 +680,9 @@ docker run --rm akitaonrails/ai-memory:latest \The curl script installer supports`--agent claude-code|codex|cursor|gemini-cli|antigravity-cli|grok|opencode|openclaw|omp|oh-my-pi|pi`and `--to <dir>`; `--help` prints the full flag list. OpenCode,-OpenClaw, and OMP / Oh My Pi do not need script extraction because+OpenClaw, OMP / Oh My Pi, and Pi do not need script extraction because`install-hooks` generates TypeScript plugin/extension files for them-instead. Real Pi is recognized separately, but the curl installer only-prints fail-closed guidance until the Pi bridge lands.+instead. For Pi, the generated extension also provides the MCP bridge.This path is friction-free when:- You have curl + bash but not dockerdiff --git a/docs/mcp-install.md b/docs/mcp-install.mdindex 0e46d051..dd78667e 100644--- a/docs/mcp-install.md+++ b/docs/mcp-install.md@@ -84,7 +84,7 @@ metadata.> **One-shot tip:** every snippet below is also reachable from the> CLI:> ```bash-> ai-memory install-mcp --client gemini-cli # or cursor / claude-desktop / openclaw / omp / antigravity-cli / vscode-copilot+> ai-memory install-mcp --client gemini-cli # or cursor / claude-desktop / openclaw / omp / pi / antigravity-cli / vscode-copilot> ```---@@ -446,8 +446,7 @@ OpenClaw distinguishes transports explicitly. UseThe current Oh My Pi package exposes the `omp` binary and native`.omp` config directories. Use `omp` (or `oh-my-pi`) for this integration;-real `pi` is recognized separately, but install commands fail closed until-the Pi bridge lands in #138.+real `pi` is recognized separately and uses the generated bridge extension below.```json{@@ -472,16 +471,31 @@ This writes `~/.omp/agent/extensions/ai-memory.ts`, which OMP discoversas a direct TypeScript extension on startup. Restart `omp` afterinstalling or changing the file.-`ai-memory install-mcp --client pi` does not write `~/.pi/agent/mcp.json`:-Pi core has no native MCP config in ai-memory yet. Users who meant OMP should-use `--client omp`; real Pi support will be added by the bridge in #138.-**Gotchas:**- OMP extensions are TypeScript modules, not shell hooks; stdout is notused for context injection.- The extension uses OMP lifecycle events for prompt/tool capture and`before_agent_start` to inject pending ai-memory handoffs.+## Pi++**Status:** ✅ MCP and lifecycle capture supported via generated bridge+extension. Pi has no native `mcp.json`; use `install-hooks --agent pi --apply`+to write `~/.pi/agent/extensions/ai-memory.ts`.++```bash+ai-memory install-hooks --agent pi --apply+```++The generated extension posts lifecycle events to `/hook`, fetches pending+handoffs in `before_agent_start`, initializes ai-memory's HTTP `/mcp` endpoint,+lists tools, and registers each one with `pi.registerTool`. `install-mcp+--client pi` intentionally prints this bridge guidance instead of writing an+ignored `~/.pi/agent/mcp.json`.++OMP / Oh My Pi remains separate: use `--client omp` / `--agent omp` (or+`oh-my-pi`) for `.omp` paths.+---## After registering MCP - verify it worksdiff --git a/docs/windows.md b/docs/windows.mdindex d6bb0111..d050ceb1 100644--- a/docs/windows.md+++ b/docs/windows.md@@ -268,11 +268,11 @@ Windows agent builds.- MCP over HTTP should be less path-sensitive than hooks, but`install-mcp --apply` still writes to a client-specific config file;confirm the agent actually loads it.-- OpenClaw, OpenCode, and OMP / Oh My Pi use generated TypeScript+- OpenClaw, OpenCode, OMP / Oh My Pi, and Pi use generated TypeScriptintegrations rather than the shell hook bundle, so their Windowsbehavior depends on the host runtime loading those files correctly.- Real Pi is recognized separately, but ai-memory does not install real- Pi hooks until the bridge integration lands.+ Pi's generated extension also bridges MCP tools because Pi has no native+ `mcp.json` install surface.## Suggested Test Checklistdiff --git a/scripts/install-hooks.sh b/scripts/install-hooks.shindex 4a8eea7d..7f2a7d3e 100755--- a/scripts/install-hooks.sh+++ b/scripts/install-hooks.sh@@ -74,10 +74,10 @@ if [[ "$AGENT" == "omp" || "$AGENT" == "oh-my-pi" ]]; thenfiif [[ "$AGENT" == "pi" ]]; then- echo "Pi is recognized separately from Oh My Pi / OMP, but ai-memory does not install real Pi hooks yet."- echo "This installer will not write ~/.pi or ~/.omp files."- echo "If you meant Oh My Pi / OMP, rerun with --agent omp or --agent oh-my-pi."- echo "Real Pi support will arrive with the bridge in issue #138."+ echo "Pi uses a generated TypeScript extension, not shell hook scripts."+ echo "Run: ai-memory install-hooks --agent pi --apply"+ echo "Then restart Pi so it loads ~/.pi/agent/extensions/ai-memory.ts."+ echo "MCP tools come through the same generated bridge extension."exit 0fi