diff --git a/README.md b/README.md index 8e463090f1..48c6d303f0 100644 --- a/README.md +++ b/README.md @@ -395,7 +395,7 @@ Then add the MCP config for your agent: | **Cursor** | Add to `~/.cursor/mcp.json`: `{"mcpServers": {"agentmemory": {"command": "npx", "args": ["-y", "@agentmemory/mcp"]}}}` | | **OpenClaw** | Add to MCP config: `{"mcpServers": {"agentmemory": {"command": "npx", "args": ["-y", "@agentmemory/mcp"]}}}` or use the [memory plugin](integrations/openclaw/) | | **Gemini CLI** | `gemini mcp add agentmemory npx -y @agentmemory/mcp --scope user` | -| **Codex CLI** | `codex mcp add agentmemory -- npx -y @agentmemory/mcp` or add `[mcp_servers.agentmemory]` to `.codex/config.toml` | +| **Codex CLI / Desktop** | `codex mcp add agentmemory -- npx -y @agentmemory/mcp` or add `[mcp_servers.agentmemory]` to `~/.codex/config.toml`. For Claude Code-style automatic capture, see [`integrations/codex/`](integrations/codex/). | | **pi** | Copy [`integrations/pi`](integrations/pi/) to `~/.pi/agent/extensions/agentmemory` and restart pi | | **OpenCode** | Add to `opencode.json`: `{"mcp": {"agentmemory": {"type": "local", "command": ["npx", "-y", "@agentmemory/mcp"], "enabled": true}}}` | | **Hermes Agent** | Add to `~/.hermes/config.yaml` with `memory.provider: agentmemory` or use the [memory provider plugin](integrations/hermes/) | diff --git a/integrations/codex/README.md b/integrations/codex/README.md new file mode 100644 index 0000000000..602180d6fd --- /dev/null +++ b/integrations/codex/README.md @@ -0,0 +1,252 @@ +# agentmemory for Codex + +Codex supports agentmemory in two layers: + +1. MCP tools for explicit memory actions such as `memory_save`, + `memory_recall`, and `memory_smart_search`. +2. Codex lifecycle hooks for Claude Code-style automatic capture of prompts, + tool calls, tool results, and turn endings. + +Use both layers if you want Codex Desktop or Codex CLI to behave more like the +Claude Code plugin. + +## Prerequisites + +- Codex Desktop or Codex CLI with MCP and hooks support. +- Node.js 20 or newer. +- A running agentmemory server for full capture, viewer, and shared memory: + +```bash +npx -y @agentmemory/agentmemory +``` + +The server exposes: + +- REST API: `http://localhost:3111/agentmemory/*` +- Viewer: `http://localhost:3113` + +On Windows, the full server also needs either Docker Desktop or the prebuilt +`iii.exe` runtime described in the main README. Standalone MCP works without +the full server, but automatic hooks need the REST API. + +> **API stability:** Codex hook event names and payload fields are still evolving. +> This integration was smoke-tested against Codex Desktop `26.429.8261.0` and +> Codex CLI `0.128.0` on Windows. If a newer Codex release changes hook payloads, +> keep the MCP config and update only the hook bridge mapping. + +## 1. Add the MCP server + +Add this to `~/.codex/config.toml`: + +```toml +[mcp_servers.agentmemory] +command = "npx" +args = ["-y", "@agentmemory/mcp"] +env = { AGENTMEMORY_TOOLS = "all" } +startup_timeout_sec = 30 +tool_timeout_sec = 60 +enabled = true +``` + +Restart Codex. You should see the agentmemory MCP tools in Codex. + +## 2. Install the Codex hook bridge + +Copy `agentmemory-codex-hook.mjs` from this directory to a stable local path. + +Examples: + +```bash +mkdir -p ~/.codex/hooks +cp integrations/codex/agentmemory-codex-hook.mjs ~/.codex/hooks/ +``` + +PowerShell: + +```powershell +New-Item -ItemType Directory -Force -Path $env:USERPROFILE\.codex\hooks +Copy-Item integrations\codex\agentmemory-codex-hook.mjs $env:USERPROFILE\.codex\hooks\ +``` + +## 3. Enable Codex hooks + +Add the feature flag to `~/.codex/config.toml`: + +```toml +[features] +codex_hooks = true +``` + +Then add hook registrations. Adjust the `command` path for your machine. + +macOS/Linux: + +```toml +[[hooks.SessionStart]] +matcher = "startup|resume" + +[[hooks.SessionStart.hooks]] +type = "command" +command = 'node "$HOME/.codex/hooks/agentmemory-codex-hook.mjs"' +timeout = 10 +statusMessage = "Loading agentmemory context" + +[[hooks.UserPromptSubmit]] + +[[hooks.UserPromptSubmit.hooks]] +type = "command" +command = 'node "$HOME/.codex/hooks/agentmemory-codex-hook.mjs"' +timeout = 5 +statusMessage = "Capturing prompt to agentmemory" + +[[hooks.PreToolUse]] +matcher = "*" + +[[hooks.PreToolUse.hooks]] +type = "command" +command = 'node "$HOME/.codex/hooks/agentmemory-codex-hook.mjs"' +timeout = 5 +statusMessage = "Capturing tool intent" + +[[hooks.PostToolUse]] +matcher = "*" + +[[hooks.PostToolUse.hooks]] +type = "command" +command = 'node "$HOME/.codex/hooks/agentmemory-codex-hook.mjs"' +timeout = 5 +statusMessage = "Capturing tool result" + +[[hooks.Stop]] + +[[hooks.Stop.hooks]] +type = "command" +command = 'node "$HOME/.codex/hooks/agentmemory-codex-hook.mjs"' +timeout = 8 +statusMessage = "Capturing turn summary" +``` + +Windows: + +```toml +[[hooks.SessionStart]] +matcher = "startup|resume" + +[[hooks.SessionStart.hooks]] +type = "command" +command = 'node "C:\Users\YOUR_USER\.codex\hooks\agentmemory-codex-hook.mjs"' +timeout = 10 +statusMessage = "Loading agentmemory context" + +[[hooks.UserPromptSubmit]] + +[[hooks.UserPromptSubmit.hooks]] +type = "command" +command = 'node "C:\Users\YOUR_USER\.codex\hooks\agentmemory-codex-hook.mjs"' +timeout = 5 +statusMessage = "Capturing prompt to agentmemory" + +[[hooks.PreToolUse]] +matcher = "*" + +[[hooks.PreToolUse.hooks]] +type = "command" +command = 'node "C:\Users\YOUR_USER\.codex\hooks\agentmemory-codex-hook.mjs"' +timeout = 5 +statusMessage = "Capturing tool intent" + +[[hooks.PostToolUse]] +matcher = "*" + +[[hooks.PostToolUse.hooks]] +type = "command" +command = 'node "C:\Users\YOUR_USER\.codex\hooks\agentmemory-codex-hook.mjs"' +timeout = 5 +statusMessage = "Capturing tool result" + +[[hooks.Stop]] + +[[hooks.Stop.hooks]] +type = "command" +command = 'node "C:\Users\YOUR_USER\.codex\hooks\agentmemory-codex-hook.mjs"' +timeout = 8 +statusMessage = "Capturing turn summary" +``` + +Restart Codex after editing the config. + +## What gets captured + +The bridge maps Codex hook events to agentmemory observations: + +| Codex hook | agentmemory hook type | Captures | +| --- | --- | --- | +| `SessionStart` | session start API | Session id, project, cwd, recalled context | +| `UserPromptSubmit` | `prompt_submit` | User prompt, turn id, model | +| `PreToolUse` | `pre_tool_use` | Tool name and input | +| `PostToolUse` | `post_tool_use` | Tool name, input, and output | +| `Stop` | `stop` | Latest assistant message and turn id | + +The bridge truncates large tool outputs before sending them to the REST API. +It never throws or blocks Codex if agentmemory is unavailable. + +## Custom server URL and auth + +The hook bridge reads the same environment variables as the other agentmemory +integrations: + +```bash +AGENTMEMORY_URL=http://localhost:3111 +AGENTMEMORY_SECRET=your-secret +``` + +Set `AGENTMEMORY_URL` when the server is not on `localhost:3111`. Set +`AGENTMEMORY_SECRET` when the agentmemory REST API requires bearer auth; the hook +will send `Authorization: Bearer ` on every request. + +For shared or corporate deployments, set these variables in the shell or launch +environment that starts Codex. The script intentionally writes no debug output +to stdout, because Codex hook stdout may become user-visible context. + +## Context injection + +By default, `SessionStart` writes recalled agentmemory context back to Codex as +additional developer context when the server returns context. Disable this with: + +```bash +AGENTMEMORY_CODEX_INJECT_CONTEXT=false +``` + +You can also tune capture size: + +```bash +AGENTMEMORY_CODEX_MAX_TOOL_OUTPUT=8000 +AGENTMEMORY_CODEX_MAX_ASSISTANT_MESSAGE=12000 +AGENTMEMORY_CODEX_REST_TIMEOUT_MS=4000 +``` + +## Verify + +1. Start agentmemory: + + ```bash + npx -y @agentmemory/agentmemory + ``` + +2. Restart Codex and run a short prompt that uses a tool. +3. Open the viewer at `http://localhost:3113`. +4. Check `Sessions`, `Timeline`, or export: + + ```bash + curl http://localhost:3111/agentmemory/export + ``` + +You should see a Codex session with prompt and tool observations. + +## Notes and limitations + +- Codex hooks are a feature flag and may evolve. +- Codex does not expose every Claude Code lifecycle event, so this is not a + byte-for-byte replacement for the Claude Code plugin. +- The important loop is covered: automatic capture, session registration, + startup context recall, and explicit MCP memory tools. diff --git a/integrations/codex/agentmemory-codex-hook.mjs b/integrations/codex/agentmemory-codex-hook.mjs new file mode 100644 index 0000000000..83084c8925 --- /dev/null +++ b/integrations/codex/agentmemory-codex-hook.mjs @@ -0,0 +1,159 @@ +#!/usr/bin/env node + +/** + * Codex lifecycle hook bridge for agentmemory. + * + * Codex sends one JSON payload on stdin for each configured hook event. + * This script translates those events into agentmemory's REST API shape. + * It is best-effort by design: memory capture should never block Codex. + */ + +const REST_URL = process.env.AGENTMEMORY_URL || "http://localhost:3111"; +const SECRET = process.env.AGENTMEMORY_SECRET || ""; +const INJECT_CONTEXT = process.env.AGENTMEMORY_CODEX_INJECT_CONTEXT !== "false"; +const REST_TIMEOUT_MS = positiveIntEnv( + process.env.AGENTMEMORY_CODEX_REST_TIMEOUT_MS, + 4000, +); +const MAX_TOOL_OUTPUT_CHARS = positiveIntEnv( + process.env.AGENTMEMORY_CODEX_MAX_TOOL_OUTPUT, + 8000, +); +const MAX_ASSISTANT_MESSAGE_CHARS = positiveIntEnv( + process.env.AGENTMEMORY_CODEX_MAX_ASSISTANT_MESSAGE, + 12000, +); + +function positiveIntEnv(value, fallback) { + const parsed = Number.parseInt(value, 10); + return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback; +} + +function authHeaders() { + const headers = { "Content-Type": "application/json" }; + if (SECRET) headers.Authorization = `Bearer ${SECRET}`; + return headers; +} + +async function readJsonFromStdin() { + let input = ""; + for await (const chunk of process.stdin) input += chunk; + if (!input.trim()) return null; + try { + return JSON.parse(input); + } catch { + return null; + } +} + +function projectFrom(data) { + return data.cwd || process.cwd(); +} + +function truncate(value, maxChars) { + if (value === null || value === undefined) return value; + const text = typeof value === "string" ? value : JSON.stringify(value); + if (text.length <= maxChars) return value; + return `${text.slice(0, maxChars)}\n...[truncated ${text.length - maxChars} chars]`; +} + +async function post(path, body, timeoutMs = REST_TIMEOUT_MS) { + const response = await fetch(`${REST_URL}${path}`, { + method: "POST", + headers: authHeaders(), + body: JSON.stringify(body), + signal: AbortSignal.timeout(timeoutMs), + }); + if (!response.ok) return null; + return response.json().catch(() => null); +} + +async function observe(data, sessionId, hookType, observedData) { + return post("/agentmemory/observe", { + hookType, + sessionId, + project: projectFrom(data), + cwd: projectFrom(data), + timestamp: new Date().toISOString(), + data: observedData, + }); +} + +function sessionStartContext(context) { + const text = + typeof context === "string" ? context : JSON.stringify(context, null, 2); + return { + hookSpecificOutput: { + hookEventName: "SessionStart", + additionalContext: text, + }, + }; +} + +async function main() { + const data = await readJsonFromStdin(); + if (!data) return; + + const event = data.hook_event_name; + const sessionId = data.session_id || `codex_${Date.now().toString(36)}`; + const project = projectFrom(data); + + try { + if (event === "SessionStart") { + const result = await post( + "/agentmemory/session/start", + { sessionId, project, cwd: project }, + 5000, + ); + if (INJECT_CONTEXT && result?.context) { + process.stdout.write(JSON.stringify(sessionStartContext(result.context))); + } + return; + } + + if (event === "UserPromptSubmit") { + await observe(data, sessionId, "prompt_submit", { + prompt: data.prompt, + turn_id: data.turn_id, + model: data.model, + }); + return; + } + + if (event === "PreToolUse") { + await observe(data, sessionId, "pre_tool_use", { + tool_name: data.tool_name, + tool_input: data.tool_input, + tool_use_id: data.tool_use_id, + turn_id: data.turn_id, + }); + return; + } + + if (event === "PostToolUse") { + await observe(data, sessionId, "post_tool_use", { + tool_name: data.tool_name, + tool_input: data.tool_input, + tool_output: truncate(data.tool_response, MAX_TOOL_OUTPUT_CHARS), + tool_use_id: data.tool_use_id, + turn_id: data.turn_id, + }); + return; + } + + if (event === "Stop") { + await observe(data, sessionId, "stop", { + last_assistant_message: truncate( + data.last_assistant_message, + MAX_ASSISTANT_MESSAGE_CHARS, + ), + stop_hook_active: data.stop_hook_active, + turn_id: data.turn_id, + }); + } + } catch { + // Best effort only. Do not block Codex when agentmemory is down. + } +} + +main(); diff --git a/test/codex-hook.test.ts b/test/codex-hook.test.ts new file mode 100644 index 0000000000..60ec731ece --- /dev/null +++ b/test/codex-hook.test.ts @@ -0,0 +1,222 @@ +import { afterEach, describe, expect, it } from "vitest"; +import { spawn } from "node:child_process"; +import { createServer, type IncomingMessage, type ServerResponse } from "node:http"; +import { join } from "node:path"; + +const HOOK_PATH = join( + import.meta.dirname, + "..", + "integrations", + "codex", + "agentmemory-codex-hook.mjs", +); +const HOOK_WATCHDOG_MS = 5000; + +type HookResult = { + stdout: string; + stderr: string; + exitCode: number | null; + tookMs: number; +}; + +type CapturedRequest = { + path: string; + method: string; + authorization?: string; + body: unknown; +}; + +let servers: Array> = []; + +afterEach(async () => { + await Promise.all( + servers.map( + (server) => + new Promise((resolve) => { + server.closeAllConnections?.(); + server.close(() => resolve()); + }), + ), + ); + servers = []; +}); + +function readBody(req: IncomingMessage): Promise { + return new Promise((resolve) => { + let body = ""; + req.on("data", (chunk) => { + body += chunk.toString(); + }); + req.on("end", () => resolve(body)); + }); +} + +function runHook( + payload: unknown, + env: Record, +): Promise { + return new Promise((resolve, reject) => { + const start = Date.now(); + const child = spawn(process.execPath, [HOOK_PATH], { + env: { + PATH: process.env["PATH"] ?? "", + ...env, + }, + stdio: ["pipe", "pipe", "pipe"], + }); + const watchdog = setTimeout(() => { + child.kill("SIGKILL"); + reject(new Error(`hook subprocess timed out after ${HOOK_WATCHDOG_MS}ms`)); + }, HOOK_WATCHDOG_MS); + + let stdout = ""; + let stderr = ""; + child.stdout.on("data", (chunk) => { + stdout += chunk.toString(); + }); + child.stderr.on("data", (chunk) => { + stderr += chunk.toString(); + }); + child.on("error", (err) => { + clearTimeout(watchdog); + reject(err); + }); + child.on("close", (exitCode) => { + clearTimeout(watchdog); + resolve({ stdout, stderr, exitCode, tookMs: Date.now() - start }); + }); + + child.stdin.write(JSON.stringify(payload)); + child.stdin.end(); + }); +} + +async function startCaptureServer( + handler: ( + req: IncomingMessage, + res: ServerResponse, + request: CapturedRequest, + ) => void, +): Promise<{ baseUrl: string; requests: CapturedRequest[] }> { + const requests: CapturedRequest[] = []; + const server = createServer(async (req, res) => { + const rawBody = await readBody(req); + const request: CapturedRequest = { + path: req.url || "", + method: req.method || "GET", + authorization: req.headers.authorization, + body: rawBody ? JSON.parse(rawBody) : null, + }; + requests.push(request); + handler(req, res, request); + }); + servers.push(server); + + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const address = server.address(); + if (!address || typeof address === "string") throw new Error("missing server address"); + return { baseUrl: `http://127.0.0.1:${address.port}`, requests }; +} + +describe("Codex hook bridge", () => { + it("uses AGENTMEMORY_URL and AGENTMEMORY_SECRET for SessionStart and emits string context", async () => { + const { baseUrl, requests } = await startCaptureServer((_req, res) => { + res.writeHead(200, { "content-type": "application/json" }); + res.end(JSON.stringify({ context: { project: "codex", fact: "use hooks" } })); + }); + + const result = await runHook( + { + hook_event_name: "SessionStart", + session_id: "ses_codex", + cwd: "/repo", + }, + { + AGENTMEMORY_URL: baseUrl, + AGENTMEMORY_SECRET: "secret-token", + }, + ); + + expect(result.exitCode).toBe(0); + expect(result.stderr).toBe(""); + expect(requests).toHaveLength(1); + expect(requests[0].path).toBe("/agentmemory/session/start"); + expect(requests[0].authorization).toBe("Bearer secret-token"); + expect(requests[0].body).toMatchObject({ + sessionId: "ses_codex", + project: "/repo", + cwd: "/repo", + }); + + const output = JSON.parse(result.stdout); + expect(output.hookSpecificOutput.hookEventName).toBe("SessionStart"); + expect(typeof output.hookSpecificOutput.additionalContext).toBe("string"); + expect(output.hookSpecificOutput.additionalContext).toContain("use hooks"); + }); + + it.each([ + ["UserPromptSubmit", "prompt_submit"], + ["PreToolUse", "pre_tool_use"], + ["PostToolUse", "post_tool_use"], + ["Stop", "stop"], + ])("maps %s to %s observations", async (event, hookType) => { + const { baseUrl, requests } = await startCaptureServer((_req, res) => { + res.writeHead(201, { "content-type": "application/json" }); + res.end(JSON.stringify({ success: true })); + }); + + const result = await runHook( + { + hook_event_name: event, + session_id: "ses_codex", + turn_id: "turn-1", + cwd: "/repo", + prompt: "how does auth work?", + model: "gpt-5.5", + tool_name: "Read", + tool_input: { file_path: "src/auth.ts" }, + tool_response: { output: "contents" }, + last_assistant_message: "done", + }, + { AGENTMEMORY_URL: baseUrl }, + ); + + expect(result.exitCode).toBe(0); + expect(result.stdout).toBe(""); + expect(requests).toHaveLength(1); + expect(requests[0].path).toBe("/agentmemory/observe"); + expect(requests[0].body).toMatchObject({ + hookType, + sessionId: "ses_codex", + project: "/repo", + cwd: "/repo", + }); + }); + + it("does not hang Codex when the REST endpoint stalls", async () => { + const server = createServer(() => { + // Intentionally never respond. The hook must abort its fetch. + }); + servers.push(server); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const address = server.address(); + if (!address || typeof address === "string") throw new Error("missing server address"); + + const result = await runHook( + { + hook_event_name: "UserPromptSubmit", + session_id: "ses_codex", + cwd: "/repo", + prompt: "do not hang", + }, + { + AGENTMEMORY_URL: `http://127.0.0.1:${address.port}`, + AGENTMEMORY_CODEX_REST_TIMEOUT_MS: "100", + }, + ); + + expect(result.exitCode).toBe(0); + expect(result.stdout).toBe(""); + expect(result.tookMs).toBeLessThan(2000); + }); +});