@agentmemory/agentmemory 0.9.18 → 0.9.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"standalone.mjs","names":[],"sources":["../src/mcp/in-memory-kv.ts","../src/mcp/transport.ts","../src/mcp/tools-registry.ts","../src/config.ts","../src/version.ts","../src/state/schema.ts","../src/mcp/rest-proxy.ts","../src/mcp/standalone.ts"],"sourcesContent":["import { existsSync, readFileSync, writeFileSync, mkdirSync } from \"node:fs\";\nimport { dirname } from \"node:path\";\n\nexport class InMemoryKV {\n private store = new Map<string, Map<string, unknown>>();\n\n constructor(private persistPath?: string) {\n if (persistPath && existsSync(persistPath)) {\n try {\n const data = JSON.parse(readFileSync(persistPath, \"utf-8\"));\n for (const [scope, entries] of Object.entries(data)) {\n const map = new Map<string, unknown>();\n for (const [key, value] of Object.entries(\n entries as Record<string, unknown>,\n )) {\n map.set(key, value);\n }\n this.store.set(scope, map);\n }\n } catch {\n // start fresh\n }\n }\n }\n\n async get<T = unknown>(scope: string, key: string): Promise<T | null> {\n return (this.store.get(scope)?.get(key) as T) ?? null;\n }\n\n async set<T = unknown>(scope: string, key: string, data: T): Promise<T> {\n if (!this.store.has(scope)) this.store.set(scope, new Map());\n this.store.get(scope)!.set(key, data);\n return data;\n }\n\n async delete(scope: string, key: string): Promise<void> {\n this.store.get(scope)?.delete(key);\n }\n\n async list<T = unknown>(scope: string): Promise<T[]> {\n const entries = this.store.get(scope);\n return entries ? (Array.from(entries.values()) as T[]) : [];\n }\n\n persist(): void {\n if (!this.persistPath) return;\n try {\n const dir = dirname(this.persistPath);\n if (!existsSync(dir)) mkdirSync(dir, { recursive: true });\n const data: Record<string, Record<string, unknown>> = {};\n for (const [scope, entries] of this.store) {\n data[scope] = Object.fromEntries(entries);\n }\n writeFileSync(this.persistPath, JSON.stringify(data), \"utf-8\");\n } catch (err) {\n process.stderr.write(\n `[@agentmemory/mcp] Persist failed: ${err instanceof Error ? err.message : String(err)}\\n`,\n );\n }\n }\n}\n","import { createInterface } from \"node:readline\";\n\nexport interface JsonRpcRequest {\n jsonrpc: \"2.0\";\n id?: string | number;\n method: string;\n params?: Record<string, unknown>;\n}\n\nexport interface JsonRpcResponse {\n jsonrpc: \"2.0\";\n id: string | number | null;\n result?: unknown;\n error?: { code: number; message: string; data?: unknown };\n}\n\nexport type RequestHandler = (\n method: string,\n params: Record<string, unknown>,\n) => Promise<unknown>;\n\n// JSON-RPC 2.0 notifications are messages without an `id` field. The spec\n// (and the MCP transport contract) requires the server to NOT send a\n// response for notifications. Some clients tolerate spurious responses;\n// stricter clients (e.g. Codex CLI) treat them as protocol violations and\n// close the transport. See agentmemory#129.\nfunction isNotification(req: JsonRpcRequest): boolean {\n return req.id === undefined || req.id === null;\n}\n\n// Per JSON-RPC 2.0 §4, a valid request id must be a String, Number, or Null\n// (Null is technically only allowed in responses; in requests, omitting id\n// is the convention for notifications, which we treat the same as null).\n// Any other runtime type (object, array, boolean) is an Invalid Request.\nfunction isValidId(id: unknown): id is string | number | null | undefined {\n return (\n id === undefined ||\n id === null ||\n typeof id === \"string\" ||\n typeof id === \"number\"\n );\n}\n\n// Exported for unit tests so the line-handling logic is exercised\n// independently of process.stdin / process.stdout.\nexport async function processLine(\n line: string,\n handler: RequestHandler,\n writeOut: (response: JsonRpcResponse) => void,\n writeErr: (msg: string) => void = (msg) => process.stderr.write(msg),\n): Promise<void> {\n const trimmed = line.trim();\n if (!trimmed) return;\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(trimmed);\n } catch {\n writeOut({\n jsonrpc: \"2.0\",\n id: null,\n error: { code: -32700, message: \"Parse error\" },\n });\n return;\n }\n\n const request = parsed as JsonRpcRequest;\n const rawId = (request as { id?: unknown } | null)?.id;\n\n // Invalid request shape (missing/wrong jsonrpc, non-string method).\n if (\n !request ||\n typeof request !== \"object\" ||\n request.jsonrpc !== \"2.0\" ||\n typeof request.method !== \"string\"\n ) {\n // Echo the id back only if it's a valid string/number. Notifications\n // (missing/null id) and malformed ids both drop silently — we don't\n // want to respond to something that could be a notification, and we\n // can't invent an id for a malformed one.\n if (typeof rawId === \"string\" || typeof rawId === \"number\") {\n writeOut({\n jsonrpc: \"2.0\",\n id: rawId,\n error: { code: -32600, message: \"Invalid Request\" },\n });\n }\n return;\n }\n\n // Request shape is valid but id may still be of the wrong type\n // (object, array, boolean). Per the spec, that's an Invalid Request.\n // Respond with id: null because we can't safely echo a non-JSON-RPC id.\n if (!isValidId(rawId)) {\n writeOut({\n jsonrpc: \"2.0\",\n id: null,\n error: { code: -32600, message: \"Invalid Request: id must be string, number, or null\" },\n });\n return;\n }\n\n const notification = isNotification(request);\n\n try {\n const result = await handler(request.method, request.params || {});\n if (notification) return;\n writeOut({\n jsonrpc: \"2.0\",\n id: request.id as string | number,\n result,\n });\n } catch (err) {\n if (notification) {\n writeErr(\n `[mcp-transport] notification handler error for ${request.method}: ${\n err instanceof Error ? err.message : String(err)\n }\\n`,\n );\n return;\n }\n writeOut({\n jsonrpc: \"2.0\",\n id: request.id as string | number,\n error: {\n code: -32603,\n message: err instanceof Error ? err.message : String(err),\n },\n });\n }\n}\n\nexport function createStdioTransport(handler: RequestHandler): {\n start: () => void;\n stop: () => void;\n} {\n let rl: ReturnType<typeof createInterface> | null = null;\n\n const writeResponse = (response: JsonRpcResponse) => {\n process.stdout.write(JSON.stringify(response) + \"\\n\");\n };\n\n const onLine = (line: string) => processLine(line, handler, writeResponse);\n\n return {\n start() {\n rl = createInterface({ input: process.stdin });\n rl.on(\"line\", onLine);\n },\n stop() {\n rl?.close();\n rl = null;\n },\n };\n}\n","export type McpToolDef = {\n name: string;\n description: string;\n inputSchema: {\n type: \"object\";\n properties: Record<string, { type: string; description: string }>;\n required?: string[];\n };\n};\n\nexport const CORE_TOOLS: McpToolDef[] = [\n {\n name: \"memory_recall\",\n description:\n \"Search past session observations for relevant context. Use when you need to recall what happened in previous sessions, find past decisions, or look up how a file was modified before.\",\n inputSchema: {\n type: \"object\",\n properties: {\n query: {\n type: \"string\",\n description: \"Search query (keywords, file names, concepts)\",\n },\n limit: {\n type: \"number\",\n description: \"Max results to return (default 10)\",\n },\n format: {\n type: \"string\",\n description: \"Result format: full, compact, or narrative (default full)\",\n },\n token_budget: {\n type: \"number\",\n description: \"Optional token budget to trim returned results\",\n },\n },\n required: [\"query\"],\n },\n },\n {\n name: \"memory_compress_file\",\n description:\n \"Compress a markdown file to reduce token usage while preserving headings, URLs, and code blocks. Creates a .original.md backup before writing.\",\n inputSchema: {\n type: \"object\",\n properties: {\n filePath: {\n type: \"string\",\n description: \"Path to the markdown file to compress\",\n },\n },\n required: [\"filePath\"],\n },\n },\n {\n name: \"memory_save\",\n description:\n \"Explicitly save an important insight, decision, or pattern to long-term memory.\",\n inputSchema: {\n type: \"object\",\n properties: {\n content: {\n type: \"string\",\n description: \"The insight or decision to remember\",\n },\n type: {\n type: \"string\",\n description:\n \"Memory type: pattern, preference, architecture, bug, workflow, or fact\",\n },\n concepts: {\n type: \"string\",\n description: \"Comma-separated key concepts\",\n },\n files: {\n type: \"string\",\n description: \"Comma-separated relevant file paths\",\n },\n },\n required: [\"content\"],\n },\n },\n {\n name: \"memory_file_history\",\n description: \"Get past observations about specific files.\",\n inputSchema: {\n type: \"object\",\n properties: {\n files: { type: \"string\", description: \"Comma-separated file paths\" },\n sessionId: {\n type: \"string\",\n description: \"Current session ID to exclude\",\n },\n },\n required: [\"files\"],\n },\n },\n {\n name: \"memory_patterns\",\n description: \"Detect recurring patterns across sessions.\",\n inputSchema: {\n type: \"object\",\n properties: {\n project: { type: \"string\", description: \"Project path to analyze\" },\n },\n },\n },\n {\n name: \"memory_sessions\",\n description:\n \"List recent sessions with their status and observation counts.\",\n inputSchema: { type: \"object\", properties: {} },\n },\n {\n name: \"memory_smart_search\",\n description: \"Hybrid semantic+keyword search with progressive disclosure.\",\n inputSchema: {\n type: \"object\",\n properties: {\n query: { type: \"string\", description: \"Search query\" },\n expandIds: {\n type: \"string\",\n description: \"Comma-separated observation IDs to expand\",\n },\n limit: { type: \"number\", description: \"Max results (default 10)\" },\n },\n required: [\"query\"],\n },\n },\n {\n name: \"memory_vision_search\",\n description:\n \"Cross-modal image search via CLIP embeddings. Pass queryText to find screenshots matching a description, or queryImageBase64/queryImageRef to find similar images. Requires AGENTMEMORY_IMAGE_EMBEDDINGS=true.\",\n inputSchema: {\n type: \"object\",\n properties: {\n queryText: { type: \"string\", description: \"Text query (e.g. 'login form with error banner')\" },\n queryImageRef: { type: \"string\", description: \"Absolute path to a stored image to match against\" },\n queryImageBase64: { type: \"string\", description: \"Raw base64 image bytes or data URL\" },\n topK: { type: \"number\", description: \"Max results (default 10, max 50)\" },\n sessionId: { type: \"string\", description: \"Filter to a single session\" },\n },\n },\n },\n {\n name: \"memory_timeline\",\n description: \"Chronological observations around an anchor point.\",\n inputSchema: {\n type: \"object\",\n properties: {\n anchor: {\n type: \"string\",\n description: \"Anchor point: ISO date or keyword\",\n },\n project: { type: \"string\", description: \"Filter by project path\" },\n before: {\n type: \"number\",\n description: \"Observations before anchor (default 5)\",\n },\n after: {\n type: \"number\",\n description: \"Observations after anchor (default 5)\",\n },\n },\n required: [\"anchor\"],\n },\n },\n {\n name: \"memory_profile\",\n description: \"User/project profile with top concepts and file patterns.\",\n inputSchema: {\n type: \"object\",\n properties: {\n project: { type: \"string\", description: \"Project path\" },\n refresh: {\n type: \"string\",\n description: \"Set to 'true' to force rebuild\",\n },\n },\n required: [\"project\"],\n },\n },\n {\n name: \"memory_export\",\n description: \"Export all memory data as JSON.\",\n inputSchema: { type: \"object\", properties: {} },\n },\n {\n name: \"memory_relations\",\n description: \"Query the memory relationship graph.\",\n inputSchema: {\n type: \"object\",\n properties: {\n memoryId: {\n type: \"string\",\n description: \"Memory ID to find relations for\",\n },\n maxHops: {\n type: \"number\",\n description: \"Max traversal depth (default 2)\",\n },\n minConfidence: {\n type: \"number\",\n description: \"Min confidence (0-1, default 0)\",\n },\n },\n required: [\"memoryId\"],\n },\n },\n];\n\nexport const V040_TOOLS: McpToolDef[] = [\n {\n name: \"memory_claude_bridge_sync\",\n description:\n \"Sync memory state to/from Claude Code's native MEMORY.md file.\",\n inputSchema: {\n type: \"object\",\n properties: {\n direction: {\n type: \"string\",\n description:\n \"'read' to import from MEMORY.md, 'write' to export to MEMORY.md\",\n },\n },\n required: [\"direction\"],\n },\n },\n {\n name: \"memory_graph_query\",\n description: \"Query the knowledge graph for entities and relationships.\",\n inputSchema: {\n type: \"object\",\n properties: {\n startNodeId: {\n type: \"string\",\n description: \"Starting node ID for traversal\",\n },\n nodeType: { type: \"string\", description: \"Filter by node type\" },\n maxDepth: {\n type: \"number\",\n description: \"Max BFS depth (default 3, max 5)\",\n },\n query: { type: \"string\", description: \"Search nodes by name\" },\n },\n },\n },\n {\n name: \"memory_consolidate\",\n description:\n \"Run the 4-tier memory consolidation pipeline (working -> episodic -> semantic -> procedural).\",\n inputSchema: {\n type: \"object\",\n properties: {\n tier: {\n type: \"string\",\n description: \"Target tier: episodic, semantic, or procedural\",\n },\n },\n },\n },\n {\n name: \"memory_team_share\",\n description: \"Share a memory or observation with team members.\",\n inputSchema: {\n type: \"object\",\n properties: {\n itemId: {\n type: \"string\",\n description: \"ID of memory or observation to share\",\n },\n itemType: {\n type: \"string\",\n description: \"Type: observation, memory, or pattern\",\n },\n },\n required: [\"itemId\", \"itemType\"],\n },\n },\n {\n name: \"memory_team_feed\",\n description: \"Get recent shared items from all team members.\",\n inputSchema: {\n type: \"object\",\n properties: {\n limit: { type: \"number\", description: \"Max items (default 20)\" },\n },\n },\n },\n {\n name: \"memory_audit\",\n description: \"View the audit trail of memory operations.\",\n inputSchema: {\n type: \"object\",\n properties: {\n operation: { type: \"string\", description: \"Filter by operation type\" },\n limit: { type: \"number\", description: \"Max entries (default 50)\" },\n },\n },\n },\n {\n name: \"memory_governance_delete\",\n description: \"Delete specific memories with audit trail.\",\n inputSchema: {\n type: \"object\",\n properties: {\n memoryIds: {\n type: \"string\",\n description: \"Comma-separated memory IDs to delete\",\n },\n reason: { type: \"string\", description: \"Reason for deletion\" },\n },\n required: [\"memoryIds\"],\n },\n },\n {\n name: \"memory_snapshot_create\",\n description: \"Create a git-versioned snapshot of current memory state.\",\n inputSchema: {\n type: \"object\",\n properties: {\n message: { type: \"string\", description: \"Snapshot description\" },\n },\n },\n },\n];\n\nexport const V050_TOOLS: McpToolDef[] = [\n {\n name: \"memory_action_create\",\n description:\n \"Create an actionable work item with typed dependencies. Actions track what agents need to do and how work items relate to each other.\",\n inputSchema: {\n type: \"object\",\n properties: {\n title: { type: \"string\", description: \"Action title\" },\n description: {\n type: \"string\",\n description: \"Detailed description of the work\",\n },\n priority: {\n type: \"number\",\n description: \"Priority 1-10 (10 highest)\",\n },\n project: { type: \"string\", description: \"Project path\" },\n tags: {\n type: \"string\",\n description: \"Comma-separated tags\",\n },\n parentId: {\n type: \"string\",\n description: \"Parent action ID for hierarchical actions\",\n },\n requires: {\n type: \"string\",\n description:\n \"Comma-separated action IDs that must complete before this\",\n },\n },\n required: [\"title\"],\n },\n },\n {\n name: \"memory_action_update\",\n description:\n \"Update an action's status, priority, or details. Set status to 'done' to complete it and unblock dependent actions.\",\n inputSchema: {\n type: \"object\",\n properties: {\n actionId: { type: \"string\", description: \"Action ID to update\" },\n status: {\n type: \"string\",\n description: \"New status: pending, active, done, blocked, cancelled\",\n },\n result: {\n type: \"string\",\n description: \"Outcome description (when completing)\",\n },\n priority: { type: \"number\", description: \"New priority 1-10\" },\n },\n required: [\"actionId\"],\n },\n },\n {\n name: \"memory_frontier\",\n description:\n \"Get all unblocked actions ranked by priority and urgency. Returns the frontier of actionable work with no unsatisfied dependencies.\",\n inputSchema: {\n type: \"object\",\n properties: {\n project: { type: \"string\", description: \"Filter by project\" },\n agentId: {\n type: \"string\",\n description: \"Agent ID to check lease conflicts\",\n },\n limit: { type: \"number\", description: \"Max results (default 20)\" },\n },\n },\n },\n {\n name: \"memory_next\",\n description:\n \"Get the single most important next action to work on. Combines dependency resolution, priority, and recency into a score.\",\n inputSchema: {\n type: \"object\",\n properties: {\n project: { type: \"string\", description: \"Filter by project\" },\n agentId: { type: \"string\", description: \"Current agent ID\" },\n },\n },\n },\n {\n name: \"memory_lease\",\n description:\n \"Acquire, release, or renew an exclusive lease on an action. Prevents multiple agents from working on the same thing.\",\n inputSchema: {\n type: \"object\",\n properties: {\n actionId: { type: \"string\", description: \"Action ID\" },\n agentId: { type: \"string\", description: \"Agent claiming the action\" },\n operation: {\n type: \"string\",\n description: \"acquire, release, or renew\",\n },\n result: {\n type: \"string\",\n description: \"Result when releasing (marks action done)\",\n },\n ttlMs: {\n type: \"number\",\n description: \"Lease duration in ms (default 10min, max 1hr)\",\n },\n },\n required: [\"actionId\", \"agentId\", \"operation\"],\n },\n },\n {\n name: \"memory_routine_run\",\n description:\n \"Instantiate a frozen workflow routine, creating actions for each step with proper dependencies.\",\n inputSchema: {\n type: \"object\",\n properties: {\n routineId: { type: \"string\", description: \"Routine template ID\" },\n project: { type: \"string\", description: \"Project context\" },\n initiatedBy: { type: \"string\", description: \"Agent starting the run\" },\n },\n required: [\"routineId\"],\n },\n },\n {\n name: \"memory_signal_send\",\n description:\n \"Send a message to another agent or broadcast. Supports threading, typed messages, and TTL expiration.\",\n inputSchema: {\n type: \"object\",\n properties: {\n from: { type: \"string\", description: \"Sender agent ID\" },\n to: {\n type: \"string\",\n description: \"Recipient agent ID (omit for broadcast)\",\n },\n content: { type: \"string\", description: \"Message content\" },\n type: {\n type: \"string\",\n description: \"Message type: info, request, response, alert, handoff\",\n },\n replyTo: {\n type: \"string\",\n description: \"Signal ID to reply to (auto-threads)\",\n },\n },\n required: [\"from\", \"content\"],\n },\n },\n {\n name: \"memory_signal_read\",\n description:\n \"Read messages for an agent. Marks delivered messages as read.\",\n inputSchema: {\n type: \"object\",\n properties: {\n agentId: { type: \"string\", description: \"Agent to read messages for\" },\n unreadOnly: {\n type: \"string\",\n description: \"Set to 'true' for unread only\",\n },\n threadId: {\n type: \"string\",\n description: \"Filter by conversation thread\",\n },\n limit: { type: \"number\", description: \"Max messages (default 50)\" },\n },\n required: [\"agentId\"],\n },\n },\n {\n name: \"memory_checkpoint\",\n description:\n \"Create or resolve an external checkpoint (CI result, approval, deploy status) that gates action progress.\",\n inputSchema: {\n type: \"object\",\n properties: {\n operation: {\n type: \"string\",\n description: \"create, resolve, or list\",\n },\n name: { type: \"string\", description: \"Checkpoint name (for create)\" },\n checkpointId: {\n type: \"string\",\n description: \"Checkpoint ID (for resolve)\",\n },\n status: {\n type: \"string\",\n description: \"passed or failed (for resolve)\",\n },\n type: {\n type: \"string\",\n description: \"Checkpoint type: ci, approval, deploy, external, timer\",\n },\n linkedActionIds: {\n type: \"string\",\n description:\n \"Comma-separated action IDs this checkpoint gates (for create)\",\n },\n },\n required: [\"operation\"],\n },\n },\n {\n name: \"memory_mesh_sync\",\n description:\n \"Sync memories and actions with peer agentmemory instances for multi-agent collaboration.\",\n inputSchema: {\n type: \"object\",\n properties: {\n peerId: {\n type: \"string\",\n description: \"Specific peer ID (omit for all)\",\n },\n direction: {\n type: \"string\",\n description: \"push, pull, or both (default both)\",\n },\n },\n },\n },\n];\n\nexport const V051_TOOLS: McpToolDef[] = [\n {\n name: \"memory_sentinel_create\",\n description:\n \"Create an event-driven sentinel that watches for conditions (webhook, timer, threshold, pattern, approval) and auto-unblocks gated actions when triggered.\",\n inputSchema: {\n type: \"object\",\n properties: {\n name: { type: \"string\", description: \"Sentinel name\" },\n type: {\n type: \"string\",\n description: \"Type: webhook, timer, threshold, pattern, approval, custom\",\n },\n config: {\n type: \"string\",\n description: \"JSON config (timer: {durationMs}, threshold: {metric,operator,value}, pattern: {pattern}, webhook: {path})\",\n },\n linkedActionIds: {\n type: \"string\",\n description: \"Comma-separated action IDs to gate\",\n },\n expiresInMs: { type: \"number\", description: \"Auto-expire after ms\" },\n },\n required: [\"name\", \"type\"],\n },\n },\n {\n name: \"memory_sentinel_trigger\",\n description:\n \"Externally fire a sentinel, providing an optional result payload. Unblocks any gated actions.\",\n inputSchema: {\n type: \"object\",\n properties: {\n sentinelId: { type: \"string\", description: \"Sentinel ID to trigger\" },\n result: { type: \"string\", description: \"JSON result payload\" },\n },\n required: [\"sentinelId\"],\n },\n },\n {\n name: \"memory_sketch_create\",\n description:\n \"Create an ephemeral action graph for exploratory work. Auto-expires after TTL. Can be promoted to permanent actions or discarded.\",\n inputSchema: {\n type: \"object\",\n properties: {\n title: { type: \"string\", description: \"Sketch title\" },\n description: { type: \"string\", description: \"What this sketch explores\" },\n expiresInMs: { type: \"number\", description: \"TTL in ms (default 1 hour)\" },\n project: { type: \"string\", description: \"Project context\" },\n },\n required: [\"title\"],\n },\n },\n {\n name: \"memory_sketch_promote\",\n description:\n \"Promote a sketch's ephemeral actions to permanent actions. Makes the exploratory work official.\",\n inputSchema: {\n type: \"object\",\n properties: {\n sketchId: { type: \"string\", description: \"Sketch ID to promote\" },\n project: { type: \"string\", description: \"Override project for promoted actions\" },\n },\n required: [\"sketchId\"],\n },\n },\n {\n name: \"memory_crystallize\",\n description:\n \"Compress completed action chains into compact crystal digests using LLM summarization. Extracts narrative, key outcomes, files affected, and lessons.\",\n inputSchema: {\n type: \"object\",\n properties: {\n actionIds: {\n type: \"string\",\n description: \"Comma-separated completed action IDs to crystallize\",\n },\n project: { type: \"string\", description: \"Project context\" },\n sessionId: { type: \"string\", description: \"Session context\" },\n },\n required: [\"actionIds\"],\n },\n },\n {\n name: \"memory_diagnose\",\n description:\n \"Run health checks across all subsystems (actions, leases, sentinels, sketches, signals, sessions, memories, mesh). Identifies stuck, orphaned, and inconsistent state.\",\n inputSchema: {\n type: \"object\",\n properties: {\n categories: {\n type: \"string\",\n description: \"Comma-separated categories to check (default all)\",\n },\n },\n },\n },\n {\n name: \"memory_heal\",\n description:\n \"Auto-fix all fixable issues found by diagnostics. Unblocks stuck actions, expires stale leases, cleans up orphaned data.\",\n inputSchema: {\n type: \"object\",\n properties: {\n categories: {\n type: \"string\",\n description: \"Comma-separated categories to heal (default all)\",\n },\n dryRun: {\n type: \"string\",\n description: \"Set to 'true' for dry run (report but don't fix)\",\n },\n },\n },\n },\n {\n name: \"memory_facet_tag\",\n description:\n \"Attach a structured tag (dimension:value) to an action, memory, or observation for multi-dimensional categorization.\",\n inputSchema: {\n type: \"object\",\n properties: {\n targetId: { type: \"string\", description: \"ID of the target to tag\" },\n targetType: {\n type: \"string\",\n description: \"Type: action, memory, or observation\",\n },\n dimension: { type: \"string\", description: \"Tag dimension (e.g., priority, team, status)\" },\n value: { type: \"string\", description: \"Tag value (e.g., urgent, backend, reviewed)\" },\n },\n required: [\"targetId\", \"targetType\", \"dimension\", \"value\"],\n },\n },\n {\n name: \"memory_facet_query\",\n description:\n \"Query targets by facet tags with AND/OR logic. Find all actions tagged priority:urgent AND team:backend.\",\n inputSchema: {\n type: \"object\",\n properties: {\n matchAll: {\n type: \"string\",\n description: \"Comma-separated dimension:value pairs (AND logic)\",\n },\n matchAny: {\n type: \"string\",\n description: \"Comma-separated dimension:value pairs (OR logic)\",\n },\n targetType: {\n type: \"string\",\n description: \"Filter by type: action, memory, or observation\",\n },\n },\n },\n },\n];\n\nexport const V061_TOOLS: McpToolDef[] = [\n {\n name: \"memory_verify\",\n description:\n \"Verify a memory or observation by tracing its citation chain back to source observations and session context. Returns provenance information including confidence scores.\",\n inputSchema: {\n type: \"object\",\n properties: {\n id: {\n type: \"string\",\n description: \"Memory ID or observation ID to verify\",\n },\n },\n required: [\"id\"],\n },\n },\n];\n\nexport const V070_TOOLS: McpToolDef[] = [\n {\n name: \"memory_lesson_save\",\n description:\n \"Save a lesson learned from this session. Lessons have confidence scores that strengthen when reinforced and decay when not used. Duplicate content auto-strengthens the existing lesson.\",\n inputSchema: {\n type: \"object\",\n properties: {\n content: {\n type: \"string\",\n description: \"The lesson learned (what worked, what to avoid, when to use X approach)\",\n },\n context: {\n type: \"string\",\n description: \"When/where this lesson applies\",\n },\n confidence: {\n type: \"number\",\n description: \"Initial confidence 0.0-1.0 (default 0.5)\",\n },\n project: { type: \"string\", description: \"Project this lesson is about\" },\n tags: { type: \"string\", description: \"Comma-separated tags\" },\n },\n required: [\"content\"],\n },\n },\n {\n name: \"memory_lesson_recall\",\n description:\n \"Search lessons by query. Returns lessons sorted by confidence and recency. Use to check what the agent has learned before making decisions.\",\n inputSchema: {\n type: \"object\",\n properties: {\n query: { type: \"string\", description: \"Search query\" },\n project: { type: \"string\", description: \"Filter by project\" },\n minConfidence: {\n type: \"number\",\n description: \"Minimum confidence threshold (default 0.1)\",\n },\n limit: { type: \"number\", description: \"Max results (default 10)\" },\n },\n required: [\"query\"],\n },\n },\n {\n name: \"memory_obsidian_export\",\n description:\n \"Export memories, lessons, and crystals as Obsidian-compatible Markdown files with YAML frontmatter and wikilinks for graph view.\",\n inputSchema: {\n type: \"object\",\n properties: {\n vaultDir: {\n type: \"string\",\n description: \"Output directory (default ~/.agentmemory/vault/)\",\n },\n types: {\n type: \"string\",\n description: \"Comma-separated types to export: memories,lessons,crystals,sessions (default all)\",\n },\n },\n },\n },\n];\n\nexport const V073_TOOLS: McpToolDef[] = [\n {\n name: \"memory_reflect\",\n description:\n \"Traverse the knowledge graph, group related memories by concept clusters, and synthesize higher-order insights via LLM. Returns new and reinforced insights.\",\n inputSchema: {\n type: \"object\",\n properties: {\n project: { type: \"string\", description: \"Filter by project\" },\n maxClusters: {\n type: \"number\",\n description: \"Max concept clusters to process (default 10, max 20)\",\n },\n },\n },\n },\n {\n name: \"memory_insight_list\",\n description:\n \"List synthesized insights — higher-order observations derived from patterns across memories, lessons, and crystals.\",\n inputSchema: {\n type: \"object\",\n properties: {\n project: { type: \"string\", description: \"Filter by project\" },\n minConfidence: {\n type: \"number\",\n description: \"Minimum confidence threshold (default 0)\",\n },\n limit: { type: \"number\", description: \"Max results (default 50)\" },\n },\n },\n },\n];\n\nexport const V010_SLOTS_TOOLS: McpToolDef[] = [\n {\n name: \"memory_slot_list\",\n description:\n \"List all memory slots (pinned + project + global). Slots are editable, size-limited memory units the agent can read and modify across sessions.\",\n inputSchema: { type: \"object\", properties: {} },\n },\n {\n name: \"memory_slot_get\",\n description: \"Read a single slot by label.\",\n inputSchema: {\n type: \"object\",\n properties: {\n label: { type: \"string\", description: \"Slot label (e.g. 'persona', 'pending_items')\" },\n },\n required: [\"label\"],\n },\n },\n {\n name: \"memory_slot_create\",\n description: \"Create a new slot. Reject if a slot with the same label already exists.\",\n inputSchema: {\n type: \"object\",\n properties: {\n label: { type: \"string\", description: \"Slot label — lowercase, starts with letter, [a-z0-9_]\" },\n content: { type: \"string\", description: \"Initial content (default empty)\" },\n sizeLimit: { type: \"number\", description: \"Max chars (default 2000, hard cap 20000)\" },\n description: { type: \"string\", description: \"What this slot is for\" },\n pinned: { type: \"string\", description: \"'false' to exclude from context injection; default true\" },\n scope: { type: \"string\", description: \"'project' (default) or 'global' (shared across projects)\" },\n },\n required: [\"label\"],\n },\n },\n {\n name: \"memory_slot_append\",\n description:\n \"Append text to an existing slot. Fails with 413 if the append would exceed the slot's sizeLimit — agent must compact via memory_slot_replace first.\",\n inputSchema: {\n type: \"object\",\n properties: {\n label: { type: \"string\", description: \"Slot label\" },\n text: { type: \"string\", description: \"Text to append\" },\n },\n required: [\"label\", \"text\"],\n },\n },\n {\n name: \"memory_slot_replace\",\n description: \"Replace slot content in place. Fails if content exceeds sizeLimit.\",\n inputSchema: {\n type: \"object\",\n properties: {\n label: { type: \"string\", description: \"Slot label\" },\n content: { type: \"string\", description: \"New full content\" },\n },\n required: [\"label\", \"content\"],\n },\n },\n {\n name: \"memory_slot_delete\",\n description: \"Delete a slot. Seeded default slots can be deleted unless marked readOnly.\",\n inputSchema: {\n type: \"object\",\n properties: {\n label: { type: \"string\", description: \"Slot label\" },\n },\n required: [\"label\"],\n },\n },\n];\n\nconst ESSENTIAL_TOOLS = new Set([\n \"memory_save\",\n \"memory_recall\",\n \"memory_consolidate\",\n \"memory_smart_search\",\n \"memory_sessions\",\n \"memory_diagnose\",\n \"memory_lesson_save\",\n \"memory_reflect\",\n]);\n\nexport function getAllTools(): McpToolDef[] {\n return [\n ...CORE_TOOLS,\n ...V040_TOOLS,\n ...V050_TOOLS,\n ...V051_TOOLS,\n ...V061_TOOLS,\n ...V070_TOOLS,\n ...V073_TOOLS,\n ...V010_SLOTS_TOOLS,\n ];\n}\n\nexport function getVisibleTools(): McpToolDef[] {\n const mode = process.env[\"AGENTMEMORY_TOOLS\"] || \"core\";\n if (mode === \"all\") return getAllTools();\n return getAllTools().filter((t) => ESSENTIAL_TOOLS.has(t.name));\n}\n","import { existsSync, readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { homedir } from \"node:os\";\nimport type {\n AgentMemoryConfig,\n ProviderConfig,\n EmbeddingConfig,\n FallbackConfig,\n ClaudeBridgeConfig,\n TeamConfig,\n} from \"./types.js\";\n\nfunction safeParseInt(value: string | undefined, fallback: number): number {\n if (!value) return fallback;\n const parsed = parseInt(value, 10);\n return Number.isNaN(parsed) ? fallback : parsed;\n}\n\nconst DATA_DIR = join(homedir(), \".agentmemory\");\nconst ENV_FILE = join(DATA_DIR, \".env\");\n\nfunction loadEnvFile(): Record<string, string> {\n if (!existsSync(ENV_FILE)) return {};\n const content = readFileSync(ENV_FILE, \"utf-8\");\n const vars: Record<string, string> = {};\n for (const line of content.split(\"\\n\")) {\n const trimmed = line.trim();\n if (!trimmed || trimmed.startsWith(\"#\")) continue;\n const eqIdx = trimmed.indexOf(\"=\");\n if (eqIdx === -1) continue;\n const key = trimmed.slice(0, eqIdx).trim();\n let val = trimmed.slice(eqIdx + 1).trim();\n const quoteChar = val[0] === '\"' || val[0] === \"'\" ? val[0] : \"\";\n if (quoteChar) {\n const closeIdx = val.indexOf(quoteChar, 1);\n if (closeIdx !== -1) val = val.slice(1, closeIdx);\n } else {\n const hashIdx = val.indexOf(\" #\");\n if (hashIdx !== -1) val = val.slice(0, hashIdx).trim();\n }\n vars[key] = val;\n }\n return vars;\n}\n\nfunction hasRealValue(v: string | undefined): v is string {\n return typeof v === \"string\" && v.trim().length > 0;\n}\n\nfunction detectProvider(env: Record<string, string>): ProviderConfig {\n const maxTokens = parseInt(env[\"MAX_TOKENS\"] || \"4096\", 10);\n\n // OpenAI-compatible: supports OpenAI, DeepSeek, SiliconFlow, Azure, vLLM, LM Studio\n if (hasRealValue(env[\"OPENAI_API_KEY\"]) && env[\"OPENAI_API_KEY_FOR_LLM\"] !== \"false\") {\n return {\n provider: \"openai\",\n model: env[\"OPENAI_MODEL\"] || \"gpt-4o-mini\",\n maxTokens,\n baseURL: env[\"OPENAI_BASE_URL\"],\n };\n }\n\n // MiniMax: Anthropic-compatible API, requires raw fetch to avoid SDK stainless headers\n if (hasRealValue(env[\"MINIMAX_API_KEY\"])) {\n return {\n provider: \"minimax\",\n model: env[\"MINIMAX_MODEL\"] || \"MiniMax-M2.7\",\n maxTokens,\n };\n }\n\n if (hasRealValue(env[\"ANTHROPIC_API_KEY\"])) {\n return {\n provider: \"anthropic\",\n model: env[\"ANTHROPIC_MODEL\"] || \"claude-sonnet-4-20250514\",\n maxTokens,\n baseURL: env[\"ANTHROPIC_BASE_URL\"],\n };\n }\n if (hasRealValue(env[\"GEMINI_API_KEY\"]) || hasRealValue(env[\"GOOGLE_API_KEY\"])) {\n if (!hasRealValue(env[\"GEMINI_API_KEY\"]) && hasRealValue(env[\"GOOGLE_API_KEY\"])) {\n process.stderr.write(\n \"[agentmemory] GOOGLE_API_KEY detected — treating as GEMINI_API_KEY. \" +\n \"Set GEMINI_API_KEY in ~/.agentmemory/.env to silence this warning.\\n\",\n );\n }\n return {\n provider: \"gemini\",\n model: env[\"GEMINI_MODEL\"] || \"gemini-2.5-flash\",\n maxTokens,\n };\n }\n if (hasRealValue(env[\"OPENROUTER_API_KEY\"])) {\n return {\n provider: \"openrouter\",\n model: env[\"OPENROUTER_MODEL\"] || \"anthropic/claude-sonnet-4-20250514\",\n maxTokens,\n };\n }\n\n const allowAgentSdk = env[\"AGENTMEMORY_ALLOW_AGENT_SDK\"] === \"true\";\n if (!allowAgentSdk) {\n process.stderr.write(\n \"[agentmemory] No LLM provider key found \" +\n \"(ANTHROPIC_API_KEY, GEMINI_API_KEY, OPENROUTER_API_KEY, MINIMAX_API_KEY, OPENAI_API_KEY). \" +\n \"LLM-backed compression and summarization are DISABLED — using no-op provider. \" +\n \"This is the safe default: the agent-sdk fallback used to spawn Claude Agent SDK \" +\n \"child sessions which inherit Claude Code's plugin hooks and cause infinite Stop-hook \" +\n \"recursion (#149 follow-up). To opt in to the agent-sdk fallback anyway, set both \" +\n \"AGENTMEMORY_AUTO_COMPRESS=true AND AGENTMEMORY_ALLOW_AGENT_SDK=true — but be aware \" +\n \"it will burn your Claude Pro allocation and may still recurse if you use it from \" +\n \"inside Claude Code itself.\\n\",\n );\n return {\n provider: \"noop\",\n model: \"noop\",\n maxTokens,\n };\n }\n\n process.stderr.write(\n \"[agentmemory] WARNING: agent-sdk fallback enabled via AGENTMEMORY_ALLOW_AGENT_SDK=true. \" +\n \"This spawns @anthropic-ai/claude-agent-sdk child sessions that can trigger the Stop-hook \" +\n \"recursion loop (#149 follow-up). A SDK-child env marker is set to block re-entry, \" +\n \"but prefer setting a real API key in ~/.agentmemory/.env instead.\\n\",\n );\n return {\n provider: \"agent-sdk\",\n model: \"claude-sonnet-4-20250514\",\n maxTokens,\n };\n}\n\nexport function loadConfig(): AgentMemoryConfig {\n const env = getMergedEnv();\n\n const provider = detectProvider(env);\n\n return {\n engineUrl: env[\"III_ENGINE_URL\"] || \"ws://localhost:49134\",\n restPort: parseInt(env[\"III_REST_PORT\"] || \"3111\", 10) || 3111,\n streamsPort: parseInt(env[\"III_STREAMS_PORT\"] || \"3112\", 10) || 3112,\n provider,\n tokenBudget: safeParseInt(env[\"TOKEN_BUDGET\"], 2000),\n maxObservationsPerSession: safeParseInt(env[\"MAX_OBS_PER_SESSION\"], 500),\n compressionModel: provider.model,\n dataDir: DATA_DIR,\n };\n}\n\nfunction getMergedEnv(\n overrides?: Record<string, string>,\n): Record<string, string> {\n const fileEnv = loadEnvFile();\n return { ...fileEnv, ...process.env, ...overrides } as Record<string, string>;\n}\n\nexport function getEnvVar(key: string): string | undefined {\n return getMergedEnv()[key];\n}\n\nexport function detectLlmProviderKind(): \"llm\" | \"noop\" {\n const env = getMergedEnv();\n if (\n hasRealValue(env[\"ANTHROPIC_API_KEY\"]) ||\n hasRealValue(env[\"GEMINI_API_KEY\"]) ||\n hasRealValue(env[\"GOOGLE_API_KEY\"]) ||\n hasRealValue(env[\"OPENROUTER_API_KEY\"]) ||\n hasRealValue(env[\"MINIMAX_API_KEY\"]) ||\n (hasRealValue(env[\"OPENAI_API_KEY\"]) &&\n env[\"OPENAI_API_KEY_FOR_LLM\"] !== \"false\")\n ) {\n return \"llm\";\n }\n return \"noop\";\n}\n\nexport function loadEmbeddingConfig(): EmbeddingConfig {\n const env = getMergedEnv();\n let bm25Weight = parseFloat(env[\"BM25_WEIGHT\"] || \"0.4\");\n let vectorWeight = parseFloat(env[\"VECTOR_WEIGHT\"] || \"0.6\");\n bm25Weight =\n isNaN(bm25Weight) || bm25Weight < 0 ? 0.4 : Math.min(bm25Weight, 1);\n vectorWeight =\n isNaN(vectorWeight) || vectorWeight < 0 ? 0.6 : Math.min(vectorWeight, 1);\n return {\n provider: env[\"EMBEDDING_PROVIDER\"] || undefined,\n bm25Weight,\n vectorWeight,\n };\n}\n\nexport function detectEmbeddingProvider(\n env?: Record<string, string>,\n): string | null {\n const source = env ?? getMergedEnv();\n const forced = source[\"EMBEDDING_PROVIDER\"];\n if (forced) return forced;\n\n if (source[\"GEMINI_API_KEY\"]) return \"gemini\";\n if (source[\"OPENAI_API_KEY\"]) return \"openai\";\n if (source[\"VOYAGE_API_KEY\"]) return \"voyage\";\n if (source[\"COHERE_API_KEY\"]) return \"cohere\";\n if (source[\"OPENROUTER_API_KEY\"]) return \"openrouter\";\n return null;\n}\n\nexport function loadClaudeBridgeConfig(): ClaudeBridgeConfig {\n const env = getMergedEnv();\n const enabled = env[\"CLAUDE_MEMORY_BRIDGE\"] === \"true\";\n const projectPath = env[\"CLAUDE_PROJECT_PATH\"] || \"\";\n const lineBudget = safeParseInt(env[\"CLAUDE_MEMORY_LINE_BUDGET\"], 200);\n let memoryFilePath = \"\";\n if (enabled && projectPath) {\n const safePath = projectPath.replace(/[/\\\\]/g, \"-\").replace(/^-/, \"\");\n memoryFilePath = join(\n homedir(),\n \".claude\",\n \"projects\",\n safePath,\n \"memory\",\n \"MEMORY.md\",\n );\n }\n return { enabled, projectPath, memoryFilePath, lineBudget };\n}\n\nexport function loadTeamConfig(): TeamConfig | null {\n const env = getMergedEnv();\n const teamId = env[\"TEAM_ID\"];\n const userId = env[\"USER_ID\"];\n if (!teamId || !userId) return null;\n const mode = env[\"TEAM_MODE\"] === \"shared\" ? \"shared\" : \"private\";\n return { teamId, userId, mode };\n}\n\nexport function loadSnapshotConfig(): {\n enabled: boolean;\n interval: number;\n dir: string;\n} {\n const env = getMergedEnv();\n return {\n enabled: env[\"SNAPSHOT_ENABLED\"] === \"true\",\n interval: safeParseInt(env[\"SNAPSHOT_INTERVAL\"], 3600),\n dir: env[\"SNAPSHOT_DIR\"] || join(homedir(), \".agentmemory\", \"snapshots\"),\n };\n}\n\nexport function isGraphExtractionEnabled(): boolean {\n return getMergedEnv()[\"GRAPH_EXTRACTION_ENABLED\"] === \"true\";\n}\n\nexport function getGraphBatchSize(): number {\n return safeParseInt(getMergedEnv()[\"GRAPH_EXTRACTION_BATCH_SIZE\"], 10);\n}\n\nexport function isConsolidationEnabled(): boolean {\n return getMergedEnv()[\"CONSOLIDATION_ENABLED\"] === \"true\";\n}\n\n// Per-observation LLM compression is OFF by default as of 0.8.8 (see #138).\n// When disabled, observations are captured and indexed via a synthetic\n// (zero-LLM) compression path so recall/search still works. Users who want\n// richer LLM-generated summaries can set AGENTMEMORY_AUTO_COMPRESS=true in\n// ~/.agentmemory/.env — but should expect their Claude API token usage to\n// climb proportionally with session tool-use frequency.\nexport function isAutoCompressEnabled(): boolean {\n return getMergedEnv()[\"AGENTMEMORY_AUTO_COMPRESS\"] === \"true\";\n}\n\n// Hook-level context injection into Claude Code's conversation is OFF by\n// default as of 0.8.10 (see #143). When disabled, pre-tool-use and\n// session-start hooks still POST observations for background capture, but\n// never write context to stdout — so Claude Code doesn't inject an extra\n// ~4000-char blob into every tool turn. 0.8.8 stopped the agentmemory-side\n// Claude calls (via ANTHROPIC_API_KEY); this stops the Claude Code-side\n// token burn where every tool call silently grew the model input window.\n// Users who want the in-conversation context injection explicitly opt in\n// with AGENTMEMORY_INJECT_CONTEXT=true and get a loud startup warning.\nexport function isContextInjectionEnabled(): boolean {\n return getMergedEnv()[\"AGENTMEMORY_INJECT_CONTEXT\"] === \"true\";\n}\n\nexport function getConsolidationDecayDays(): number {\n return safeParseInt(getMergedEnv()[\"CONSOLIDATION_DECAY_DAYS\"], 30);\n}\n\nexport function isStandaloneMcp(): boolean {\n return getMergedEnv()[\"STANDALONE_MCP\"] === \"true\";\n}\n\nexport function getStandalonePersistPath(): string {\n const env = getMergedEnv();\n return (\n env[\"STANDALONE_PERSIST_PATH\"] ||\n join(homedir(), \".agentmemory\", \"standalone.json\")\n );\n}\n\nconst VALID_PROVIDERS = new Set([\n \"anthropic\",\n \"gemini\",\n \"openrouter\",\n \"agent-sdk\",\n \"minimax\",\n \"openai\",\n]);\n\nexport function loadFallbackConfig(): FallbackConfig {\n const env = getMergedEnv();\n const raw = env[\"FALLBACK_PROVIDERS\"] || \"\";\n const allowAgentSdk = env[\"AGENTMEMORY_ALLOW_AGENT_SDK\"] === \"true\";\n const providers = raw\n .split(\",\")\n .map((p) => p.trim())\n .filter(\n (p): p is FallbackConfig[\"providers\"][number] =>\n Boolean(p) && VALID_PROVIDERS.has(p),\n )\n .filter((p) => {\n // Honor the same safety gate as detectProvider: agent-sdk is only\n // permitted as a fallback target when the user has explicitly opted\n // in. Without this filter, a user could set FALLBACK_PROVIDERS=agent-sdk\n // and re-introduce the Stop-hook recursion loop even though\n // detectProvider() returned the noop provider.\n if (p === \"agent-sdk\" && !allowAgentSdk) {\n process.stderr.write(\n \"[agentmemory] Ignoring FALLBACK_PROVIDERS entry 'agent-sdk' \" +\n \"(AGENTMEMORY_ALLOW_AGENT_SDK is not 'true'). The agent-sdk \" +\n \"fallback can spawn Claude Agent SDK child sessions that trigger \" +\n \"the Stop-hook recursion loop (#149 follow-up). Opt in explicitly \" +\n \"with AGENTMEMORY_ALLOW_AGENT_SDK=true if this is intentional.\\n\",\n );\n return false;\n }\n return true;\n });\n return { providers };\n}\n","export const VERSION = \"0.9.18\";\n","import { createHash } from \"node:crypto\";\n\nexport const KV = {\n sessions: \"mem:sessions\",\n observations: (sessionId: string) => `mem:obs:${sessionId}`,\n memories: \"mem:memories\",\n summaries: \"mem:summaries\",\n config: \"mem:config\",\n metrics: \"mem:metrics\",\n health: \"mem:health\",\n embeddings: (obsId: string) => `mem:emb:${obsId}`,\n bm25Index: \"mem:index:bm25\",\n relations: \"mem:relations\",\n profiles: \"mem:profiles\",\n claudeBridge: \"mem:claude-bridge\",\n graphNodes: \"mem:graph:nodes\",\n graphEdges: \"mem:graph:edges\",\n semantic: \"mem:semantic\",\n procedural: \"mem:procedural\",\n teamShared: (teamId: string) => `mem:team:${teamId}:shared`,\n teamUsers: (teamId: string, userId: string) =>\n `mem:team:${teamId}:users:${userId}`,\n teamProfile: (teamId: string) => `mem:team:${teamId}:profile`,\n audit: \"mem:audit\",\n actions: \"mem:actions\",\n actionEdges: \"mem:action-edges\",\n leases: \"mem:leases\",\n routines: \"mem:routines\",\n routineRuns: \"mem:routine-runs\",\n signals: \"mem:signals\",\n checkpoints: \"mem:checkpoints\",\n mesh: \"mem:mesh\",\n sketches: \"mem:sketches\",\n facets: \"mem:facets\",\n sentinels: \"mem:sentinels\",\n crystals: \"mem:crystals\",\n lessons: \"mem:lessons\",\n insights: \"mem:insights\",\n graphEdgeHistory: \"mem:graph:edge-history\",\n enrichedChunks: (sessionId: string) => `mem:enriched:${sessionId}`,\n latentEmbeddings: (obsId: string) => `mem:latent:${obsId}`,\n retentionScores: \"mem:retention\",\n accessLog: \"mem:access\",\n imageRefs: \"mem:image-refs\",\n imageEmbeddings: \"mem:image-embeddings\",\n slots: \"mem:slots\",\n globalSlots: \"mem:slots:global\",\n state: \"mem:state\",\n} as const;\n\nexport const STREAM = {\n name: \"mem-live\",\n group: (sessionId: string) => sessionId,\n viewerGroup: \"viewer\",\n} as const;\n\nexport function generateId(prefix: string): string {\n const ts = Date.now().toString(36);\n const rand = crypto.randomUUID().replace(/-/g, \"\").slice(0, 12);\n return `${prefix}_${ts}_${rand}`;\n}\n\nexport function fingerprintId(prefix: string, content: string): string {\n const hash = createHash(\"sha256\").update(content).digest(\"hex\");\n return `${prefix}_${hash.slice(0, 16)}`;\n}\n\nexport function jaccardSimilarity(a: string, b: string): number {\n const setA = new Set(a.split(/\\s+/).filter((t) => t.length > 2));\n const setB = new Set(b.split(/\\s+/).filter((t) => t.length > 2));\n if (setA.size === 0 && setB.size === 0) return 1;\n if (setA.size === 0 || setB.size === 0) return 0;\n let intersection = 0;\n for (const word of setA) {\n if (setB.has(word)) intersection++;\n }\n return intersection / (setA.size + setB.size - intersection);\n}\n","const DEFAULT_URL = \"http://localhost:3111\";\nconst DEFAULT_HEALTH_PROBE_TIMEOUT_MS = 2_000;\nconst CALL_TIMEOUT_MS = 15_000;\nconst LOCAL_MODE_TTL_MS = 30_000;\n\nfunction probeTimeoutMs(): number {\n const raw = process.env[\"AGENTMEMORY_PROBE_TIMEOUT_MS\"];\n if (!raw) return DEFAULT_HEALTH_PROBE_TIMEOUT_MS;\n const n = Number(raw);\n return Number.isFinite(n) && n > 0 ? Math.floor(n) : DEFAULT_HEALTH_PROBE_TIMEOUT_MS;\n}\n\nfunction forceProxy(): boolean {\n const raw = process.env[\"AGENTMEMORY_FORCE_PROXY\"];\n return raw === \"1\" || raw === \"true\";\n}\n\nexport interface ProxyHandle {\n mode: \"proxy\";\n baseUrl: string;\n call: (path: string, init?: RequestInit) => Promise<unknown>;\n}\n\nexport interface LocalHandle {\n mode: \"local\";\n}\n\nexport type Handle = ProxyHandle | LocalHandle;\n\nlet cached: Handle | null = null;\nlet cachedAt = 0;\nlet probeInFlight: Promise<Handle> | null = null;\n\nfunction baseUrl(): string {\n return (process.env[\"AGENTMEMORY_URL\"] || DEFAULT_URL).replace(/\\/+$/, \"\");\n}\n\nfunction authHeader(): Record<string, string> {\n const secret = process.env[\"AGENTMEMORY_SECRET\"];\n return secret ? { authorization: `Bearer ${secret}` } : {};\n}\n\n/**\n * Probes the agentmemory server's livez endpoint. Returns a Response-shaped\n * object whose `ok` flag drives the proxy/local-fallback decision.\n *\n * Tests can swap this via {@link setLivezProbe} to avoid the real 2s\n * AbortController race that destabilises mcp-standalone test runs (#449).\n * Production callers should leave it on the default.\n */\nexport type LivezProbe = (\n url: string,\n timeoutMs: number,\n headers: Record<string, string>,\n) => Promise<{ ok: boolean; status?: number; statusText?: string }>;\n\nconst defaultLivezProbe: LivezProbe = async (url, timeoutMs, headers) => {\n const res = await fetch(`${url}/agentmemory/livez`, {\n method: \"GET\",\n headers,\n signal: AbortSignal.timeout(timeoutMs),\n });\n return { ok: res.ok, status: res.status, statusText: res.statusText };\n};\n\nlet livezProbe: LivezProbe = defaultLivezProbe;\n\n/**\n * Override the livez probe. Intended for tests — production code should rely\n * on the default fetch-based probe. Calling without an argument restores the\n * default. Pair with {@link resetHandleForTests} so the cached handle is\n * dropped before the next call.\n */\nexport function setLivezProbe(fn?: LivezProbe): void {\n livezProbe = fn ?? defaultLivezProbe;\n}\n\nasync function probe(url: string): Promise<boolean> {\n const timeout = probeTimeoutMs();\n try {\n const res = await livezProbe(url, timeout, authHeader());\n if (!res.ok) {\n process.stderr.write(\n `[@agentmemory/mcp] livez probe ${url}/agentmemory/livez -> ${res.status ?? \"?\"} ${res.statusText ?? \"\"}; falling back to local InMemoryKV (set AGENTMEMORY_FORCE_PROXY=1 to skip the probe)\\n`,\n );\n }\n return res.ok;\n } catch (err) {\n process.stderr.write(\n `[@agentmemory/mcp] livez probe ${url}/agentmemory/livez failed in ${timeout}ms: ${err instanceof Error ? err.message : String(err)}; falling back to local InMemoryKV (set AGENTMEMORY_FORCE_PROXY=1 to skip the probe, or raise AGENTMEMORY_PROBE_TIMEOUT_MS)\\n`,\n );\n return false;\n }\n}\n\nexport function invalidateHandle(): void {\n cached = null;\n cachedAt = 0;\n}\n\nexport async function resolveHandle(): Promise<Handle> {\n const now = Date.now();\n if (cached) {\n if (cached.mode === \"local\" && now - cachedAt >= LOCAL_MODE_TTL_MS) {\n cached = null;\n cachedAt = 0;\n } else {\n return cached;\n }\n }\n if (probeInFlight) return probeInFlight;\n const url = baseUrl();\n const skipProbe = forceProxy();\n probeInFlight = (async () => {\n const up = skipProbe ? true : await probe(url);\n if (skipProbe) {\n process.stderr.write(\n `[@agentmemory/mcp] AGENTMEMORY_FORCE_PROXY set; skipping livez probe and trusting ${url}\\n`,\n );\n }\n if (up) {\n const handle: ProxyHandle = {\n mode: \"proxy\",\n baseUrl: url,\n call: async (path, init) => {\n const res = await fetch(`${url}${path}`, {\n ...init,\n headers: {\n \"content-type\": \"application/json\",\n ...authHeader(),\n ...(init?.headers as Record<string, string> | undefined),\n },\n signal: AbortSignal.timeout(CALL_TIMEOUT_MS),\n });\n if (!res.ok) {\n throw new Error(\n `${init?.method || \"GET\"} ${path} -> ${res.status} ${res.statusText}`,\n );\n }\n const text = await res.text();\n return text ? JSON.parse(text) : null;\n },\n };\n cached = handle;\n cachedAt = Date.now();\n return handle;\n }\n const local: LocalHandle = { mode: \"local\" };\n cached = local;\n cachedAt = Date.now();\n return local;\n })();\n try {\n return await probeInFlight;\n } finally {\n probeInFlight = null;\n }\n}\n\nexport function resetHandleForTests(): void {\n cached = null;\n cachedAt = 0;\n probeInFlight = null;\n livezProbe = defaultLivezProbe;\n}\n","#!/usr/bin/env node\n\nimport { InMemoryKV } from \"./in-memory-kv.js\";\nimport { createStdioTransport } from \"./transport.js\";\nimport { getAllTools } from \"./tools-registry.js\";\nimport { getStandalonePersistPath } from \"../config.js\";\nimport { VERSION } from \"../version.js\";\nimport { generateId } from \"../state/schema.js\";\nimport {\n resolveHandle,\n invalidateHandle,\n type Handle,\n type ProxyHandle,\n} from \"./rest-proxy.js\";\n\nconst IMPLEMENTED_TOOLS = new Set([\n \"memory_save\",\n \"memory_recall\",\n \"memory_smart_search\",\n \"memory_sessions\",\n \"memory_export\",\n \"memory_audit\",\n \"memory_governance_delete\",\n]);\n\nconst SERVER_INFO = {\n name: \"agentmemory\",\n version: VERSION,\n protocolVersion: \"2024-11-05\",\n};\n\nconst kv = new InMemoryKV(getStandalonePersistPath());\nlet modeAnnounced = false;\n\nfunction announceMode(handle: Handle): void {\n if (modeAnnounced) return;\n modeAnnounced = true;\n if (handle.mode === \"proxy\") {\n process.stderr.write(\n `[@agentmemory/mcp] proxying to agentmemory server at ${handle.baseUrl}\\n`,\n );\n } else {\n process.stderr.write(\n `[@agentmemory/mcp] no server reachable at ${process.env[\"AGENTMEMORY_URL\"] || \"http://localhost:3111\"}; falling back to local InMemoryKV\\n`,\n );\n }\n}\n\nfunction normalizeList(value: unknown): string[] {\n if (!value) return [];\n if (Array.isArray(value)) {\n return value\n .map((v) => (typeof v === \"string\" ? v.trim() : \"\"))\n .filter((v) => v.length > 0);\n }\n if (typeof value === \"string\") {\n return value\n .split(\",\")\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n }\n return [];\n}\n\nconst DEFAULT_LIMIT = 10;\nconst MAX_LIMIT = 100;\nfunction parseLimit(raw: unknown, fallback = DEFAULT_LIMIT): number {\n if (typeof raw !== \"number\" && typeof raw !== \"string\") return fallback;\n const n = Number(raw);\n if (!Number.isFinite(n) || n <= 0) return fallback;\n return Math.min(Math.floor(n), MAX_LIMIT);\n}\n\nfunction textResponse(payload: unknown, pretty = false): {\n content: Array<{ type: string; text: string }>;\n} {\n return {\n content: [\n { type: \"text\", text: JSON.stringify(payload, null, pretty ? 2 : 0) },\n ],\n };\n}\n\ninterface Validated {\n tool: string;\n content?: string;\n type?: string;\n concepts?: string[];\n files?: string[];\n query?: string;\n limit?: number;\n memoryIds?: string[];\n reason?: string;\n}\n\nfunction validate(toolName: string, args: Record<string, unknown>): Validated {\n if (!IMPLEMENTED_TOOLS.has(toolName)) {\n throw new Error(`Unknown tool: ${toolName}`);\n }\n const v: Validated = { tool: toolName };\n switch (toolName) {\n case \"memory_save\": {\n const content = args[\"content\"];\n if (typeof content !== \"string\" || !content.trim()) {\n throw new Error(\"content is required\");\n }\n v.content = content;\n v.type = (args[\"type\"] as string) || \"fact\";\n v.concepts = normalizeList(args[\"concepts\"]);\n v.files = normalizeList(args[\"files\"]);\n return v;\n }\n case \"memory_recall\":\n case \"memory_smart_search\": {\n const query = args[\"query\"];\n if (typeof query !== \"string\" || !query.trim()) {\n throw new Error(\"query is required\");\n }\n v.query = query.trim();\n v.limit = parseLimit(args[\"limit\"]);\n return v;\n }\n case \"memory_sessions\": {\n v.limit = parseLimit(args[\"limit\"], 20);\n return v;\n }\n case \"memory_governance_delete\": {\n const ids = normalizeList(args[\"memoryIds\"]);\n if (ids.length === 0) throw new Error(\"memoryIds is required\");\n v.memoryIds = ids;\n v.reason = (args[\"reason\"] as string) || \"plugin skill request\";\n return v;\n }\n case \"memory_export\":\n return v;\n case \"memory_audit\": {\n v.limit = parseLimit(args[\"limit\"], 50);\n return v;\n }\n default:\n throw new Error(`Unknown tool: ${toolName}`);\n }\n}\n\nasync function handleProxy(\n v: Validated,\n handle: ProxyHandle,\n): Promise<{ content: Array<{ type: string; text: string }> }> {\n switch (v.tool) {\n case \"memory_save\": {\n const result = await handle.call(\"/agentmemory/remember\", {\n method: \"POST\",\n body: JSON.stringify({\n content: v.content,\n type: v.type,\n concepts: v.concepts,\n files: v.files,\n }),\n });\n return textResponse(result);\n }\n case \"memory_recall\":\n case \"memory_smart_search\": {\n const result = await handle.call(\"/agentmemory/smart-search\", {\n method: \"POST\",\n body: JSON.stringify({ query: v.query, limit: v.limit }),\n });\n return textResponse(result, true);\n }\n case \"memory_sessions\": {\n const result = await handle.call(\n `/agentmemory/sessions?limit=${v.limit}`,\n { method: \"GET\" },\n );\n return textResponse(result, true);\n }\n case \"memory_governance_delete\": {\n const result = await handle.call(\"/agentmemory/governance/memories\", {\n method: \"DELETE\",\n body: JSON.stringify({ memoryIds: v.memoryIds, reason: v.reason }),\n });\n return textResponse(result);\n }\n case \"memory_export\": {\n const result = await handle.call(\"/agentmemory/export\", { method: \"GET\" });\n return textResponse(result, true);\n }\n case \"memory_audit\": {\n const result = await handle.call(\n `/agentmemory/audit?limit=${v.limit}`,\n { method: \"GET\" },\n );\n return textResponse(result, true);\n }\n default:\n throw new Error(`Unknown tool: ${v.tool}`);\n }\n}\n\nasync function handleLocal(\n v: Validated,\n kvInstance: InMemoryKV,\n): Promise<{ content: Array<{ type: string; text: string }> }> {\n switch (v.tool) {\n case \"memory_save\": {\n const id = generateId(\"mem\");\n const isoNow = new Date().toISOString();\n await kvInstance.set(\"mem:memories\", id, {\n id,\n type: v.type,\n title: (v.content || \"\").slice(0, 80),\n content: v.content,\n concepts: v.concepts,\n files: v.files,\n createdAt: isoNow,\n updatedAt: isoNow,\n strength: 7,\n version: 1,\n isLatest: true,\n sessionIds: [],\n });\n kvInstance.persist();\n return textResponse({ saved: id });\n }\n\n case \"memory_recall\":\n case \"memory_smart_search\": {\n const query = (v.query || \"\").toLowerCase();\n const limit = v.limit ?? DEFAULT_LIMIT;\n const all =\n await kvInstance.list<Record<string, unknown>>(\"mem:memories\");\n const results = all\n .filter((m) => {\n const text = [\n typeof m[\"title\"] === \"string\" ? m[\"title\"] : \"\",\n typeof m[\"content\"] === \"string\" ? m[\"content\"] : \"\",\n Array.isArray(m[\"files\"]) ? m[\"files\"].join(\" \") : \"\",\n Array.isArray(m[\"concepts\"]) ? m[\"concepts\"].join(\" \") : \"\",\n Array.isArray(m[\"sessionIds\"]) ? m[\"sessionIds\"].join(\" \") : \"\",\n typeof m[\"id\"] === \"string\" ? m[\"id\"] : \"\",\n ]\n .join(\" \")\n .toLowerCase();\n return query.split(/\\s+/).every((word) => text.includes(word));\n })\n .slice(0, limit);\n return textResponse({ mode: \"compact\", results }, true);\n }\n\n case \"memory_sessions\": {\n const sessions =\n await kvInstance.list<Record<string, unknown>>(\"mem:sessions\");\n const limit = v.limit ?? 20;\n return textResponse({ sessions: sessions.slice(0, limit) }, true);\n }\n\n case \"memory_governance_delete\": {\n let deleted = 0;\n for (const id of v.memoryIds || []) {\n const existing = await kvInstance.get(\"mem:memories\", id);\n if (existing) {\n await kvInstance.delete(\"mem:memories\", id);\n deleted++;\n }\n }\n kvInstance.persist();\n return textResponse({\n deleted,\n requested: (v.memoryIds || []).length,\n reason: v.reason,\n });\n }\n\n case \"memory_export\": {\n const memories = await kvInstance.list(\"mem:memories\");\n const sessions = await kvInstance.list(\"mem:sessions\");\n return textResponse({ version: VERSION, memories, sessions }, true);\n }\n\n case \"memory_audit\": {\n const entries = await kvInstance.list(\"mem:audit\");\n const limit = v.limit ?? 50;\n return textResponse(\n {\n entries: (entries as Array<Record<string, unknown>>).slice(0, limit),\n },\n true,\n );\n }\n\n default:\n throw new Error(`Unknown tool: ${v.tool}`);\n }\n}\n\nasync function handleProxyGeneric(\n toolName: string,\n args: Record<string, unknown>,\n handle: ProxyHandle,\n): Promise<{ content: Array<{ type: string; text: string }> }> {\n // Forward to the server's full MCP surface so non-Claude clients can\n // reach all 51 tools (lessons, sentinels, slots, signals, graph, …)\n // instead of being capped at the 7 IMPLEMENTED_TOOLS set baked into\n // this shim. The server validates arguments per tool.\n const result = (await handle.call(\"/agentmemory/mcp/call\", {\n method: \"POST\",\n body: JSON.stringify({ name: toolName, arguments: args }),\n })) as { content?: Array<{ type: string; text: string }> } | null;\n if (result && Array.isArray(result.content)) {\n return { content: result.content };\n }\n return textResponse(result, true);\n}\n\nexport async function handleToolCall(\n toolName: string,\n args: Record<string, unknown>,\n kvInstance: InMemoryKV = kv,\n): Promise<{ content: Array<{ type: string; text: string }> }> {\n const handle = await resolveHandle();\n announceMode(handle);\n\n // Tools the local InMemoryKV fallback doesn't implement: forward straight\n // to the server. Local validation would otherwise raise \"Unknown tool\"\n // (issue #234).\n if (!IMPLEMENTED_TOOLS.has(toolName)) {\n if (handle.mode === \"proxy\") {\n try {\n return await handleProxyGeneric(toolName, args, handle);\n } catch (err) {\n process.stderr.write(\n `[@agentmemory/mcp] proxy call failed for ${toolName}: ${err instanceof Error ? err.message : String(err)}\\n`,\n );\n invalidateHandle();\n throw err;\n }\n }\n throw new Error(\n `Unknown tool: ${toolName} (local fallback supports only ${[...IMPLEMENTED_TOOLS].join(\", \")}; start an agentmemory server and set AGENTMEMORY_URL to use the full tool set)`,\n );\n }\n\n const validated = validate(toolName, args);\n if (handle.mode === \"proxy\") {\n try {\n return await handleProxy(validated, handle);\n } catch (err) {\n process.stderr.write(\n `[@agentmemory/mcp] proxy call failed for ${toolName}: ${err instanceof Error ? err.message : String(err)}; invalidating handle and falling back to local KV\\n`,\n );\n invalidateHandle();\n }\n }\n return handleLocal(validated, kvInstance);\n}\n\nexport async function handleToolsList(): Promise<{ tools: unknown[] }> {\n const debug = process.env[\"AGENTMEMORY_DEBUG\"] === \"1\" || process.env[\"AGENTMEMORY_DEBUG\"] === \"true\";\n const handle = await resolveHandle();\n announceMode(handle);\n if (debug) {\n process.stderr.write(\n `[@agentmemory/mcp] tools/list: handle.mode=${handle.mode}${handle.mode === \"proxy\" ? ` baseUrl=${handle.baseUrl}` : \"\"}\\n`,\n );\n }\n if (handle.mode === \"proxy\") {\n try {\n const remote = (await handle.call(\"/agentmemory/mcp/tools\", {\n method: \"GET\",\n })) as { tools?: unknown } | null;\n if (debug) {\n const shape = remote === null\n ? \"null\"\n : typeof remote !== \"object\"\n ? typeof remote\n : `keys=${Object.keys(remote as object).join(\",\")} toolsType=${Array.isArray((remote as { tools?: unknown }).tools) ? `array(len=${((remote as { tools: unknown[] }).tools).length})` : typeof (remote as { tools?: unknown }).tools}`;\n process.stderr.write(\n `[@agentmemory/mcp] tools/list: remote response shape: ${shape}\\n`,\n );\n }\n if (remote && Array.isArray(remote.tools)) {\n if (debug) {\n process.stderr.write(\n `[@agentmemory/mcp] tools/list: returning ${remote.tools.length} tools from server\\n`,\n );\n }\n return { tools: remote.tools };\n }\n process.stderr.write(\n `[@agentmemory/mcp] tools/list: server returned unexpected shape (no .tools array); falling back to local IMPLEMENTED_TOOLS list. Set AGENTMEMORY_DEBUG=1 to inspect response.\\n`,\n );\n } catch (err) {\n process.stderr.write(\n `[@agentmemory/mcp] tools/list proxy failed: ${err instanceof Error ? err.message : String(err)}; falling back to local list\\n`,\n );\n invalidateHandle();\n }\n }\n const fallback = getAllTools().filter((t) => IMPLEMENTED_TOOLS.has(t.name));\n if (debug) {\n process.stderr.write(\n `[@agentmemory/mcp] tools/list: returning ${fallback.length} local fallback tools (${fallback.map((t) => t.name).join(\",\")})\\n`,\n );\n }\n return { tools: fallback };\n}\n\nconst transport = createStdioTransport(async (method, params) => {\n switch (method) {\n case \"initialize\":\n return {\n protocolVersion: SERVER_INFO.protocolVersion,\n capabilities: { tools: { listChanged: false } },\n serverInfo: {\n name: SERVER_INFO.name,\n version: SERVER_INFO.version,\n },\n };\n\n case \"notifications/initialized\":\n return {};\n\n case \"tools/list\":\n return handleToolsList();\n\n case \"tools/call\": {\n const toolName = params.name as string;\n const toolArgs = (params.arguments as Record<string, unknown>) || {};\n try {\n return await handleToolCall(toolName, toolArgs);\n } catch (err) {\n return {\n content: [\n {\n type: \"text\",\n text: `Error: ${err instanceof Error ? err.message : String(err)}`,\n },\n ],\n isError: true,\n };\n }\n }\n\n default:\n throw new Error(`Unknown method: ${method}`);\n }\n});\n\nprocess.stderr.write(\n `[@agentmemory/mcp] Standalone MCP server v${SERVER_INFO.version} starting...\\n`,\n);\ntransport.start();\n\nprocess.on(\"SIGINT\", () => {\n kv.persist();\n process.exit(0);\n});\nprocess.on(\"SIGTERM\", () => {\n kv.persist();\n process.exit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,MAAM;KACN,aAAa;KACd;IACF;GACD,UAAU,CAAC,UAAU;GACtB;EACF;CACD;EACE,MAAM;EACN,aAAa;EACb,aAAa;GAAE,MAAM;GAAU,YAAY,EAAE;GAAE;EAChD;CACD;EACE,MAAM;EACN,aAAa;EACb,aAAa;GACX,MAAM;GACN,YAAY;IACV,UAAU;KACR,MAAM;KACN,aAAa;KACd;IACD,SAAS;KACP,MAAM;KACN,aAAa;KACd;IACD,eAAe;KACb,MAAM;KACN,aAAa;KACd;IACF;GACD,UAAU,CAAC,WAAW;GACvB;EACF;CACF;AAED,MAAa,aAA2B;CACtC;EACE,MAAM;EACN,aACE;EACF,aAAa;GACX,MAAM;GACN,YAAY,EACV,WAAW;IACT,MAAM;IACN,aACE;IACH,EACF;GACD,UAAU,CAAC,YAAY;GACxB;EACF;CACD;EACE,MAAM;EACN,aAAa;EACb,aAAa;GACX,MAAM;GACN,YAAY;IACV,aAAa;KACX,MAAM;KACN,aAAa;KACd;IACD,UAAU;KAAE,MAAM;KAAU,aAAa;KAAuB;IAChE,UAAU;KACR,MAAM;KACN,aAAa;KACd;IACD,OAAO;KAAE,MAAM;KAAU,aAAa;KAAwB;IAC/D;GACF;EACF;CACD;EACE,MAAM;EACN,aACE;EACF,aAAa;GACX,MAAM;GACN,YAAY,EACV,MAAM;IACJ,MAAM;IACN,aAAa;IACd,EACF;GACF;EACF;CACD;EACE,MAAM;EACN,aAAa;EACb,aAAa;GACX,MAAM;GACN,YAAY;IACV,QAAQ;KACN,MAAM;KACN,aAAa;KACd;IACD,UAAU;KACR,MAAM;KACN,aAAa;KACd;IACF;GACD,UAAU,CAAC,UAAU,WAAW;GACjC;EACF;CACD;EACE,MAAM;EACN,aAAa;EACb,aAAa;GACX,MAAM;GACN,YAAY,EACV,OAAO;IAAE,MAAM;IAAU,aAAa;IAA0B,EACjE;GACF;EACF;CACD;EACE,MAAM;EACN,aAAa;EACb,aAAa;GACX,MAAM;GACN,YAAY;IACV,WAAW;KAAE,MAAM;K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CACN,aACE;CACF,aAAa;EACX,MAAM;EACN,YAAY,EACV,IAAI;GACF,MAAM;GACN,aAAa;GACd,EACF;EACD,UAAU,CAAC,KAAK;EACjB;CACF,CACF;AAED,MAAa,aAA2B;CACtC;EACE,MAAM;EACN,aACE;EACF,aAAa;GACX,MAAM;GACN,YAAY;IACV,SAAS;KACP,MAAM;KACN,aAAa;KACd;IACD,SAAS;KACP,MAAM;KACN,aAAa;KACd;IACD,YAAY;KACV,MAAM;KACN,aAAa;KACd;IACD,SAAS;KAAE,MAAM;KAAU,aAAa;KAAgC;IACxE,MAAM;KAAE,MAAM;KAAU,aAAa;KAAwB;IAC9D;GACD,UAAU,CAAC,UAAU;GACtB;EACF;CACD;EACE,MAAM;EACN,aACE;EACF,aAAa;GACX,MAAM;GACN,YAAY;IACV,OAAO;KAAE,MAAM;KAAU,aAAa;KAAgB;IACtD,SAAS;KAAE,MAAM;KAAU,aAAa;KAAqB;IAC7D,eAAe;KACb,MAAM;KACN,aAAa;KACd;IACD,OAAO;KAAE,MAAM;KAAU,aAAa;KAA4B;IACnE;GACD,UAAU,CAAC,QAAQ;GACpB;EACF;CACD;EACE,MAAM;EACN,aACE;EACF,aAAa;GACX,MAAM;GACN,YAAY;IACV,UAAU;KACR,MAAM;KACN,aAAa;KACd;IACD,OAAO;KACL,MAAM;KACN,aAAa;KACd;IACF;GACF;EACF;CACF;AAED,MAAa,aAA2B,CACtC;CACE,MAAM;CACN,aACE;CACF,aAAa;EACX,MAAM;EACN,YAAY;GACV,SAAS;IAAE,MAAM;IAAU,aAAa;IAAqB;GAC7D,aAAa;IACX,MAAM;IACN,aAAa;IACd;GACF;EACF;CACF,EACD;CACE,MAAM;CACN,aACE;CACF,aAAa;EACX,MAAM;EACN,YAAY;GACV,SAAS;IAAE,MAAM;IAAU,aAAa;IAAqB;GAC7D,eAAe;IACb,MAAM;IACN,aAAa;IACd;GACD,OAAO;IAAE,MAAM;IAAU,aAAa;IAA4B;GACnE;EACF;CACF,CACF;A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AE;EAEX,KAAK,aACH,QAAO,iBAAiB;EAE1B,KAAK,cAAc;GACjB,MAAM,WAAW,OAAO;GACxB,MAAM,WAAY,OAAO,aAAyC,EAAE;AACpE,OAAI;AACF,WAAO,MAAM,eAAe,UAAU,SAAS;YACxC,KAAK;AACZ,WAAO;KACL,SAAS,CACP;MACE,MAAM;MACN,MAAM,UAAU,eAAe,QAAQ,IAAI,UAAU,OAAO,IAAI;MACjE,CACF;KACD,SAAS;KACV;;;EAIL,QACE,OAAM,IAAI,MAAM,mBAAmB,SAAS;;EAEhD;AAEF,QAAQ,OAAO,MACb,6CAA6C,YAAY,QAAQ,gBAClE;AACD,UAAU,OAAO;AAEjB,QAAQ,GAAG,gBAAgB;AACzB,IAAG,SAAS;AACZ,SAAQ,KAAK,EAAE;EACf;AACF,QAAQ,GAAG,iBAAiB;AAC1B,IAAG,SAAS;AACZ,SAAQ,KAAK,EAAE;EACf"}
1
+ {"version":3,"file":"standalone.mjs","names":[],"sources":["../src/mcp/in-memory-kv.ts","../src/mcp/transport.ts","../src/mcp/tools-registry.ts","../src/config.ts","../src/version.ts","../src/state/schema.ts","../src/mcp/rest-proxy.ts","../src/mcp/standalone.ts"],"sourcesContent":["import { existsSync, readFileSync, writeFileSync, mkdirSync } from \"node:fs\";\nimport { dirname } from \"node:path\";\n\nexport class InMemoryKV {\n private store = new Map<string, Map<string, unknown>>();\n\n constructor(private persistPath?: string) {\n if (persistPath && existsSync(persistPath)) {\n try {\n const data = JSON.parse(readFileSync(persistPath, \"utf-8\"));\n for (const [scope, entries] of Object.entries(data)) {\n const map = new Map<string, unknown>();\n for (const [key, value] of Object.entries(\n entries as Record<string, unknown>,\n )) {\n map.set(key, value);\n }\n this.store.set(scope, map);\n }\n } catch {\n // start fresh\n }\n }\n }\n\n async get<T = unknown>(scope: string, key: string): Promise<T | null> {\n return (this.store.get(scope)?.get(key) as T) ?? null;\n }\n\n async set<T = unknown>(scope: string, key: string, data: T): Promise<T> {\n if (!this.store.has(scope)) this.store.set(scope, new Map());\n this.store.get(scope)!.set(key, data);\n return data;\n }\n\n async delete(scope: string, key: string): Promise<void> {\n this.store.get(scope)?.delete(key);\n }\n\n async list<T = unknown>(scope: string): Promise<T[]> {\n const entries = this.store.get(scope);\n return entries ? (Array.from(entries.values()) as T[]) : [];\n }\n\n persist(): void {\n if (!this.persistPath) return;\n try {\n const dir = dirname(this.persistPath);\n if (!existsSync(dir)) mkdirSync(dir, { recursive: true });\n const data: Record<string, Record<string, unknown>> = {};\n for (const [scope, entries] of this.store) {\n data[scope] = Object.fromEntries(entries);\n }\n writeFileSync(this.persistPath, JSON.stringify(data), \"utf-8\");\n } catch (err) {\n process.stderr.write(\n `[@agentmemory/mcp] Persist failed: ${err instanceof Error ? err.message : String(err)}\\n`,\n );\n }\n }\n}\n","import { createInterface } from \"node:readline\";\n\nexport interface JsonRpcRequest {\n jsonrpc: \"2.0\";\n id?: string | number;\n method: string;\n params?: Record<string, unknown>;\n}\n\nexport interface JsonRpcResponse {\n jsonrpc: \"2.0\";\n id: string | number | null;\n result?: unknown;\n error?: { code: number; message: string; data?: unknown };\n}\n\nexport type RequestHandler = (\n method: string,\n params: Record<string, unknown>,\n) => Promise<unknown>;\n\n// JSON-RPC 2.0 notifications are messages without an `id` field. The spec\n// (and the MCP transport contract) requires the server to NOT send a\n// response for notifications. Some clients tolerate spurious responses;\n// stricter clients (e.g. Codex CLI) treat them as protocol violations and\n// close the transport. See agentmemory#129.\nfunction isNotification(req: JsonRpcRequest): boolean {\n return req.id === undefined || req.id === null;\n}\n\n// Per JSON-RPC 2.0 §4, a valid request id must be a String, Number, or Null\n// (Null is technically only allowed in responses; in requests, omitting id\n// is the convention for notifications, which we treat the same as null).\n// Any other runtime type (object, array, boolean) is an Invalid Request.\nfunction isValidId(id: unknown): id is string | number | null | undefined {\n return (\n id === undefined ||\n id === null ||\n typeof id === \"string\" ||\n typeof id === \"number\"\n );\n}\n\n// Exported for unit tests so the line-handling logic is exercised\n// independently of process.stdin / process.stdout.\nexport async function processLine(\n line: string,\n handler: RequestHandler,\n writeOut: (response: JsonRpcResponse) => void,\n writeErr: (msg: string) => void = (msg) => process.stderr.write(msg),\n): Promise<void> {\n const trimmed = line.trim();\n if (!trimmed) return;\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(trimmed);\n } catch {\n writeOut({\n jsonrpc: \"2.0\",\n id: null,\n error: { code: -32700, message: \"Parse error\" },\n });\n return;\n }\n\n const request = parsed as JsonRpcRequest;\n const rawId = (request as { id?: unknown } | null)?.id;\n\n // Invalid request shape (missing/wrong jsonrpc, non-string method).\n if (\n !request ||\n typeof request !== \"object\" ||\n request.jsonrpc !== \"2.0\" ||\n typeof request.method !== \"string\"\n ) {\n // Echo the id back only if it's a valid string/number. Notifications\n // (missing/null id) and malformed ids both drop silently — we don't\n // want to respond to something that could be a notification, and we\n // can't invent an id for a malformed one.\n if (typeof rawId === \"string\" || typeof rawId === \"number\") {\n writeOut({\n jsonrpc: \"2.0\",\n id: rawId,\n error: { code: -32600, message: \"Invalid Request\" },\n });\n }\n return;\n }\n\n // Request shape is valid but id may still be of the wrong type\n // (object, array, boolean). Per the spec, that's an Invalid Request.\n // Respond with id: null because we can't safely echo a non-JSON-RPC id.\n if (!isValidId(rawId)) {\n writeOut({\n jsonrpc: \"2.0\",\n id: null,\n error: { code: -32600, message: \"Invalid Request: id must be string, number, or null\" },\n });\n return;\n }\n\n const notification = isNotification(request);\n\n try {\n const result = await handler(request.method, request.params || {});\n if (notification) return;\n writeOut({\n jsonrpc: \"2.0\",\n id: request.id as string | number,\n result,\n });\n } catch (err) {\n if (notification) {\n writeErr(\n `[mcp-transport] notification handler error for ${request.method}: ${\n err instanceof Error ? err.message : String(err)\n }\\n`,\n );\n return;\n }\n writeOut({\n jsonrpc: \"2.0\",\n id: request.id as string | number,\n error: {\n code: -32603,\n message: err instanceof Error ? err.message : String(err),\n },\n });\n }\n}\n\nexport function createStdioTransport(handler: RequestHandler): {\n start: () => void;\n stop: () => void;\n} {\n let rl: ReturnType<typeof createInterface> | null = null;\n\n const writeResponse = (response: JsonRpcResponse) => {\n process.stdout.write(JSON.stringify(response) + \"\\n\");\n };\n\n const onLine = (line: string) => processLine(line, handler, writeResponse);\n\n return {\n start() {\n rl = createInterface({ input: process.stdin });\n rl.on(\"line\", onLine);\n },\n stop() {\n rl?.close();\n rl = null;\n },\n };\n}\n","export type McpToolDef = {\n name: string;\n description: string;\n inputSchema: {\n type: \"object\";\n properties: Record<string, { type: string; description: string }>;\n required?: string[];\n };\n};\n\nexport const CORE_TOOLS: McpToolDef[] = [\n {\n name: \"memory_recall\",\n description:\n \"Search past session observations for relevant context. Use when you need to recall what happened in previous sessions, find past decisions, or look up how a file was modified before.\",\n inputSchema: {\n type: \"object\",\n properties: {\n query: {\n type: \"string\",\n description: \"Search query (keywords, file names, concepts)\",\n },\n limit: {\n type: \"number\",\n description: \"Max results to return (default 10)\",\n },\n format: {\n type: \"string\",\n description: \"Result format: full, compact, or narrative (default full)\",\n },\n token_budget: {\n type: \"number\",\n description: \"Optional token budget to trim returned results\",\n },\n },\n required: [\"query\"],\n },\n },\n {\n name: \"memory_compress_file\",\n description:\n \"Compress a markdown file to reduce token usage while preserving headings, URLs, and code blocks. Creates a .original.md backup before writing.\",\n inputSchema: {\n type: \"object\",\n properties: {\n filePath: {\n type: \"string\",\n description: \"Path to the markdown file to compress\",\n },\n },\n required: [\"filePath\"],\n },\n },\n {\n name: \"memory_save\",\n description:\n \"Explicitly save an important insight, decision, or pattern to long-term memory.\",\n inputSchema: {\n type: \"object\",\n properties: {\n content: {\n type: \"string\",\n description: \"The insight or decision to remember\",\n },\n type: {\n type: \"string\",\n description:\n \"Memory type: pattern, preference, architecture, bug, workflow, or fact\",\n },\n concepts: {\n type: \"string\",\n description: \"Comma-separated key concepts\",\n },\n files: {\n type: \"string\",\n description: \"Comma-separated relevant file paths\",\n },\n },\n required: [\"content\"],\n },\n },\n {\n name: \"memory_file_history\",\n description: \"Get past observations about specific files.\",\n inputSchema: {\n type: \"object\",\n properties: {\n files: { type: \"string\", description: \"Comma-separated file paths\" },\n sessionId: {\n type: \"string\",\n description: \"Current session ID to exclude\",\n },\n },\n required: [\"files\"],\n },\n },\n {\n name: \"memory_patterns\",\n description: \"Detect recurring patterns across sessions.\",\n inputSchema: {\n type: \"object\",\n properties: {\n project: { type: \"string\", description: \"Project path to analyze\" },\n },\n },\n },\n {\n name: \"memory_sessions\",\n description:\n \"List recent sessions with their status and observation counts.\",\n inputSchema: { type: \"object\", properties: {} },\n },\n {\n name: \"memory_smart_search\",\n description: \"Hybrid semantic+keyword search with progressive disclosure.\",\n inputSchema: {\n type: \"object\",\n properties: {\n query: { type: \"string\", description: \"Search query\" },\n expandIds: {\n type: \"string\",\n description: \"Comma-separated observation IDs to expand\",\n },\n limit: { type: \"number\", description: \"Max results (default 10)\" },\n },\n required: [\"query\"],\n },\n },\n {\n name: \"memory_vision_search\",\n description:\n \"Cross-modal image search via CLIP embeddings. Pass queryText to find screenshots matching a description, or queryImageBase64/queryImageRef to find similar images. Requires AGENTMEMORY_IMAGE_EMBEDDINGS=true.\",\n inputSchema: {\n type: \"object\",\n properties: {\n queryText: { type: \"string\", description: \"Text query (e.g. 'login form with error banner')\" },\n queryImageRef: { type: \"string\", description: \"Absolute path to a stored image to match against\" },\n queryImageBase64: { type: \"string\", description: \"Raw base64 image bytes or data URL\" },\n topK: { type: \"number\", description: \"Max results (default 10, max 50)\" },\n sessionId: { type: \"string\", description: \"Filter to a single session\" },\n },\n },\n },\n {\n name: \"memory_timeline\",\n description: \"Chronological observations around an anchor point.\",\n inputSchema: {\n type: \"object\",\n properties: {\n anchor: {\n type: \"string\",\n description: \"Anchor point: ISO date or keyword\",\n },\n project: { type: \"string\", description: \"Filter by project path\" },\n before: {\n type: \"number\",\n description: \"Observations before anchor (default 5)\",\n },\n after: {\n type: \"number\",\n description: \"Observations after anchor (default 5)\",\n },\n },\n required: [\"anchor\"],\n },\n },\n {\n name: \"memory_profile\",\n description: \"User/project profile with top concepts and file patterns.\",\n inputSchema: {\n type: \"object\",\n properties: {\n project: { type: \"string\", description: \"Project path\" },\n refresh: {\n type: \"string\",\n description: \"Set to 'true' to force rebuild\",\n },\n },\n required: [\"project\"],\n },\n },\n {\n name: \"memory_export\",\n description: \"Export all memory data as JSON.\",\n inputSchema: { type: \"object\", properties: {} },\n },\n {\n name: \"memory_relations\",\n description: \"Query the memory relationship graph.\",\n inputSchema: {\n type: \"object\",\n properties: {\n memoryId: {\n type: \"string\",\n description: \"Memory ID to find relations for\",\n },\n maxHops: {\n type: \"number\",\n description: \"Max traversal depth (default 2)\",\n },\n minConfidence: {\n type: \"number\",\n description: \"Min confidence (0-1, default 0)\",\n },\n },\n required: [\"memoryId\"],\n },\n },\n {\n name: \"memory_commit_lookup\",\n description:\n \"Look up the agent session(s) that produced a specific git commit, given its SHA. Returns the commit metadata and linked sessions.\",\n inputSchema: {\n type: \"object\",\n properties: {\n sha: { type: \"string\", description: \"Full git commit SHA\" },\n },\n required: [\"sha\"],\n },\n },\n {\n name: \"memory_commits\",\n description:\n \"List recent commits linked to agent sessions, optionally filtered by branch or repo.\",\n inputSchema: {\n type: \"object\",\n properties: {\n branch: { type: \"string\", description: \"Filter by branch name\" },\n repo: { type: \"string\", description: \"Filter by remote URL\" },\n limit: { type: \"number\", description: \"Max results (default 100, max 500)\" },\n },\n },\n },\n];\n\nexport const V040_TOOLS: McpToolDef[] = [\n {\n name: \"memory_claude_bridge_sync\",\n description:\n \"Sync memory state to/from Claude Code's native MEMORY.md file.\",\n inputSchema: {\n type: \"object\",\n properties: {\n direction: {\n type: \"string\",\n description:\n \"'read' to import from MEMORY.md, 'write' to export to MEMORY.md\",\n },\n },\n required: [\"direction\"],\n },\n },\n {\n name: \"memory_graph_query\",\n description: \"Query the knowledge graph for entities and relationships.\",\n inputSchema: {\n type: \"object\",\n properties: {\n startNodeId: {\n type: \"string\",\n description: \"Starting node ID for traversal\",\n },\n nodeType: { type: \"string\", description: \"Filter by node type\" },\n maxDepth: {\n type: \"number\",\n description: \"Max BFS depth (default 3, max 5)\",\n },\n query: { type: \"string\", description: \"Search nodes by name\" },\n },\n },\n },\n {\n name: \"memory_consolidate\",\n description:\n \"Run the 4-tier memory consolidation pipeline (working -> episodic -> semantic -> procedural).\",\n inputSchema: {\n type: \"object\",\n properties: {\n tier: {\n type: \"string\",\n description: \"Target tier: episodic, semantic, or procedural\",\n },\n },\n },\n },\n {\n name: \"memory_team_share\",\n description: \"Share a memory or observation with team members.\",\n inputSchema: {\n type: \"object\",\n properties: {\n itemId: {\n type: \"string\",\n description: \"ID of memory or observation to share\",\n },\n itemType: {\n type: \"string\",\n description: \"Type: observation, memory, or pattern\",\n },\n },\n required: [\"itemId\", \"itemType\"],\n },\n },\n {\n name: \"memory_team_feed\",\n description: \"Get recent shared items from all team members.\",\n inputSchema: {\n type: \"object\",\n properties: {\n limit: { type: \"number\", description: \"Max items (default 20)\" },\n },\n },\n },\n {\n name: \"memory_audit\",\n description: \"View the audit trail of memory operations.\",\n inputSchema: {\n type: \"object\",\n properties: {\n operation: { type: \"string\", description: \"Filter by operation type\" },\n limit: { type: \"number\", description: \"Max entries (default 50)\" },\n },\n },\n },\n {\n name: \"memory_governance_delete\",\n description: \"Delete specific memories with audit trail.\",\n inputSchema: {\n type: \"object\",\n properties: {\n memoryIds: {\n type: \"string\",\n description: \"Comma-separated memory IDs to delete\",\n },\n reason: { type: \"string\", description: \"Reason for deletion\" },\n },\n required: [\"memoryIds\"],\n },\n },\n {\n name: \"memory_snapshot_create\",\n description: \"Create a git-versioned snapshot of current memory state.\",\n inputSchema: {\n type: \"object\",\n properties: {\n message: { type: \"string\", description: \"Snapshot description\" },\n },\n },\n },\n];\n\nexport const V050_TOOLS: McpToolDef[] = [\n {\n name: \"memory_action_create\",\n description:\n \"Create an actionable work item with typed dependencies. Actions track what agents need to do and how work items relate to each other.\",\n inputSchema: {\n type: \"object\",\n properties: {\n title: { type: \"string\", description: \"Action title\" },\n description: {\n type: \"string\",\n description: \"Detailed description of the work\",\n },\n priority: {\n type: \"number\",\n description: \"Priority 1-10 (10 highest)\",\n },\n project: { type: \"string\", description: \"Project path\" },\n tags: {\n type: \"string\",\n description: \"Comma-separated tags\",\n },\n parentId: {\n type: \"string\",\n description: \"Parent action ID for hierarchical actions\",\n },\n requires: {\n type: \"string\",\n description:\n \"Comma-separated action IDs that must complete before this\",\n },\n },\n required: [\"title\"],\n },\n },\n {\n name: \"memory_action_update\",\n description:\n \"Update an action's status, priority, or details. Set status to 'done' to complete it and unblock dependent actions.\",\n inputSchema: {\n type: \"object\",\n properties: {\n actionId: { type: \"string\", description: \"Action ID to update\" },\n status: {\n type: \"string\",\n description: \"New status: pending, active, done, blocked, cancelled\",\n },\n result: {\n type: \"string\",\n description: \"Outcome description (when completing)\",\n },\n priority: { type: \"number\", description: \"New priority 1-10\" },\n },\n required: [\"actionId\"],\n },\n },\n {\n name: \"memory_frontier\",\n description:\n \"Get all unblocked actions ranked by priority and urgency. Returns the frontier of actionable work with no unsatisfied dependencies.\",\n inputSchema: {\n type: \"object\",\n properties: {\n project: { type: \"string\", description: \"Filter by project\" },\n agentId: {\n type: \"string\",\n description: \"Agent ID to check lease conflicts\",\n },\n limit: { type: \"number\", description: \"Max results (default 20)\" },\n },\n },\n },\n {\n name: \"memory_next\",\n description:\n \"Get the single most important next action to work on. Combines dependency resolution, priority, and recency into a score.\",\n inputSchema: {\n type: \"object\",\n properties: {\n project: { type: \"string\", description: \"Filter by project\" },\n agentId: { type: \"string\", description: \"Current agent ID\" },\n },\n },\n },\n {\n name: \"memory_lease\",\n description:\n \"Acquire, release, or renew an exclusive lease on an action. Prevents multiple agents from working on the same thing.\",\n inputSchema: {\n type: \"object\",\n properties: {\n actionId: { type: \"string\", description: \"Action ID\" },\n agentId: { type: \"string\", description: \"Agent claiming the action\" },\n operation: {\n type: \"string\",\n description: \"acquire, release, or renew\",\n },\n result: {\n type: \"string\",\n description: \"Result when releasing (marks action done)\",\n },\n ttlMs: {\n type: \"number\",\n description: \"Lease duration in ms (default 10min, max 1hr)\",\n },\n },\n required: [\"actionId\", \"agentId\", \"operation\"],\n },\n },\n {\n name: \"memory_routine_run\",\n description:\n \"Instantiate a frozen workflow routine, creating actions for each step with proper dependencies.\",\n inputSchema: {\n type: \"object\",\n properties: {\n routineId: { type: \"string\", description: \"Routine template ID\" },\n project: { type: \"string\", description: \"Project context\" },\n initiatedBy: { type: \"string\", description: \"Agent starting the run\" },\n },\n required: [\"routineId\"],\n },\n },\n {\n name: \"memory_signal_send\",\n description:\n \"Send a message to another agent or broadcast. Supports threading, typed messages, and TTL expiration.\",\n inputSchema: {\n type: \"object\",\n properties: {\n from: { type: \"string\", description: \"Sender agent ID\" },\n to: {\n type: \"string\",\n description: \"Recipient agent ID (omit for broadcast)\",\n },\n content: { type: \"string\", description: \"Message content\" },\n type: {\n type: \"string\",\n description: \"Message type: info, request, response, alert, handoff\",\n },\n replyTo: {\n type: \"string\",\n description: \"Signal ID to reply to (auto-threads)\",\n },\n },\n required: [\"from\", \"content\"],\n },\n },\n {\n name: \"memory_signal_read\",\n description:\n \"Read messages for an agent. Marks delivered messages as read.\",\n inputSchema: {\n type: \"object\",\n properties: {\n agentId: { type: \"string\", description: \"Agent to read messages for\" },\n unreadOnly: {\n type: \"string\",\n description: \"Set to 'true' for unread only\",\n },\n threadId: {\n type: \"string\",\n description: \"Filter by conversation thread\",\n },\n limit: { type: \"number\", description: \"Max messages (default 50)\" },\n },\n required: [\"agentId\"],\n },\n },\n {\n name: \"memory_checkpoint\",\n description:\n \"Create or resolve an external checkpoint (CI result, approval, deploy status) that gates action progress.\",\n inputSchema: {\n type: \"object\",\n properties: {\n operation: {\n type: \"string\",\n description: \"create, resolve, or list\",\n },\n name: { type: \"string\", description: \"Checkpoint name (for create)\" },\n checkpointId: {\n type: \"string\",\n description: \"Checkpoint ID (for resolve)\",\n },\n status: {\n type: \"string\",\n description: \"passed or failed (for resolve)\",\n },\n type: {\n type: \"string\",\n description: \"Checkpoint type: ci, approval, deploy, external, timer\",\n },\n linkedActionIds: {\n type: \"string\",\n description:\n \"Comma-separated action IDs this checkpoint gates (for create)\",\n },\n },\n required: [\"operation\"],\n },\n },\n {\n name: \"memory_mesh_sync\",\n description:\n \"Sync memories and actions with peer agentmemory instances for multi-agent collaboration.\",\n inputSchema: {\n type: \"object\",\n properties: {\n peerId: {\n type: \"string\",\n description: \"Specific peer ID (omit for all)\",\n },\n direction: {\n type: \"string\",\n description: \"push, pull, or both (default both)\",\n },\n },\n },\n },\n];\n\nexport const V051_TOOLS: McpToolDef[] = [\n {\n name: \"memory_sentinel_create\",\n description:\n \"Create an event-driven sentinel that watches for conditions (webhook, timer, threshold, pattern, approval) and auto-unblocks gated actions when triggered.\",\n inputSchema: {\n type: \"object\",\n properties: {\n name: { type: \"string\", description: \"Sentinel name\" },\n type: {\n type: \"string\",\n description: \"Type: webhook, timer, threshold, pattern, approval, custom\",\n },\n config: {\n type: \"string\",\n description: \"JSON config (timer: {durationMs}, threshold: {metric,operator,value}, pattern: {pattern}, webhook: {path})\",\n },\n linkedActionIds: {\n type: \"string\",\n description: \"Comma-separated action IDs to gate\",\n },\n expiresInMs: { type: \"number\", description: \"Auto-expire after ms\" },\n },\n required: [\"name\", \"type\"],\n },\n },\n {\n name: \"memory_sentinel_trigger\",\n description:\n \"Externally fire a sentinel, providing an optional result payload. Unblocks any gated actions.\",\n inputSchema: {\n type: \"object\",\n properties: {\n sentinelId: { type: \"string\", description: \"Sentinel ID to trigger\" },\n result: { type: \"string\", description: \"JSON result payload\" },\n },\n required: [\"sentinelId\"],\n },\n },\n {\n name: \"memory_sketch_create\",\n description:\n \"Create an ephemeral action graph for exploratory work. Auto-expires after TTL. Can be promoted to permanent actions or discarded.\",\n inputSchema: {\n type: \"object\",\n properties: {\n title: { type: \"string\", description: \"Sketch title\" },\n description: { type: \"string\", description: \"What this sketch explores\" },\n expiresInMs: { type: \"number\", description: \"TTL in ms (default 1 hour)\" },\n project: { type: \"string\", description: \"Project context\" },\n },\n required: [\"title\"],\n },\n },\n {\n name: \"memory_sketch_promote\",\n description:\n \"Promote a sketch's ephemeral actions to permanent actions. Makes the exploratory work official.\",\n inputSchema: {\n type: \"object\",\n properties: {\n sketchId: { type: \"string\", description: \"Sketch ID to promote\" },\n project: { type: \"string\", description: \"Override project for promoted actions\" },\n },\n required: [\"sketchId\"],\n },\n },\n {\n name: \"memory_crystallize\",\n description:\n \"Compress completed action chains into compact crystal digests using LLM summarization. Extracts narrative, key outcomes, files affected, and lessons.\",\n inputSchema: {\n type: \"object\",\n properties: {\n actionIds: {\n type: \"string\",\n description: \"Comma-separated completed action IDs to crystallize\",\n },\n project: { type: \"string\", description: \"Project context\" },\n sessionId: { type: \"string\", description: \"Session context\" },\n },\n required: [\"actionIds\"],\n },\n },\n {\n name: \"memory_diagnose\",\n description:\n \"Run health checks across all subsystems (actions, leases, sentinels, sketches, signals, sessions, memories, mesh). Identifies stuck, orphaned, and inconsistent state.\",\n inputSchema: {\n type: \"object\",\n properties: {\n categories: {\n type: \"string\",\n description: \"Comma-separated categories to check (default all)\",\n },\n },\n },\n },\n {\n name: \"memory_heal\",\n description:\n \"Auto-fix all fixable issues found by diagnostics. Unblocks stuck actions, expires stale leases, cleans up orphaned data.\",\n inputSchema: {\n type: \"object\",\n properties: {\n categories: {\n type: \"string\",\n description: \"Comma-separated categories to heal (default all)\",\n },\n dryRun: {\n type: \"string\",\n description: \"Set to 'true' for dry run (report but don't fix)\",\n },\n },\n },\n },\n {\n name: \"memory_facet_tag\",\n description:\n \"Attach a structured tag (dimension:value) to an action, memory, or observation for multi-dimensional categorization.\",\n inputSchema: {\n type: \"object\",\n properties: {\n targetId: { type: \"string\", description: \"ID of the target to tag\" },\n targetType: {\n type: \"string\",\n description: \"Type: action, memory, or observation\",\n },\n dimension: { type: \"string\", description: \"Tag dimension (e.g., priority, team, status)\" },\n value: { type: \"string\", description: \"Tag value (e.g., urgent, backend, reviewed)\" },\n },\n required: [\"targetId\", \"targetType\", \"dimension\", \"value\"],\n },\n },\n {\n name: \"memory_facet_query\",\n description:\n \"Query targets by facet tags with AND/OR logic. Find all actions tagged priority:urgent AND team:backend.\",\n inputSchema: {\n type: \"object\",\n properties: {\n matchAll: {\n type: \"string\",\n description: \"Comma-separated dimension:value pairs (AND logic)\",\n },\n matchAny: {\n type: \"string\",\n description: \"Comma-separated dimension:value pairs (OR logic)\",\n },\n targetType: {\n type: \"string\",\n description: \"Filter by type: action, memory, or observation\",\n },\n },\n },\n },\n];\n\nexport const V061_TOOLS: McpToolDef[] = [\n {\n name: \"memory_verify\",\n description:\n \"Verify a memory or observation by tracing its citation chain back to source observations and session context. Returns provenance information including confidence scores.\",\n inputSchema: {\n type: \"object\",\n properties: {\n id: {\n type: \"string\",\n description: \"Memory ID or observation ID to verify\",\n },\n },\n required: [\"id\"],\n },\n },\n];\n\nexport const V070_TOOLS: McpToolDef[] = [\n {\n name: \"memory_lesson_save\",\n description:\n \"Save a lesson learned from this session. Lessons have confidence scores that strengthen when reinforced and decay when not used. Duplicate content auto-strengthens the existing lesson.\",\n inputSchema: {\n type: \"object\",\n properties: {\n content: {\n type: \"string\",\n description: \"The lesson learned (what worked, what to avoid, when to use X approach)\",\n },\n context: {\n type: \"string\",\n description: \"When/where this lesson applies\",\n },\n confidence: {\n type: \"number\",\n description: \"Initial confidence 0.0-1.0 (default 0.5)\",\n },\n project: { type: \"string\", description: \"Project this lesson is about\" },\n tags: { type: \"string\", description: \"Comma-separated tags\" },\n },\n required: [\"content\"],\n },\n },\n {\n name: \"memory_lesson_recall\",\n description:\n \"Search lessons by query. Returns lessons sorted by confidence and recency. Use to check what the agent has learned before making decisions.\",\n inputSchema: {\n type: \"object\",\n properties: {\n query: { type: \"string\", description: \"Search query\" },\n project: { type: \"string\", description: \"Filter by project\" },\n minConfidence: {\n type: \"number\",\n description: \"Minimum confidence threshold (default 0.1)\",\n },\n limit: { type: \"number\", description: \"Max results (default 10)\" },\n },\n required: [\"query\"],\n },\n },\n {\n name: \"memory_obsidian_export\",\n description:\n \"Export memories, lessons, and crystals as Obsidian-compatible Markdown files with YAML frontmatter and wikilinks for graph view.\",\n inputSchema: {\n type: \"object\",\n properties: {\n vaultDir: {\n type: \"string\",\n description: \"Output directory (default ~/.agentmemory/vault/)\",\n },\n types: {\n type: \"string\",\n description: \"Comma-separated types to export: memories,lessons,crystals,sessions (default all)\",\n },\n },\n },\n },\n];\n\nexport const V073_TOOLS: McpToolDef[] = [\n {\n name: \"memory_reflect\",\n description:\n \"Traverse the knowledge graph, group related memories by concept clusters, and synthesize higher-order insights via LLM. Returns new and reinforced insights.\",\n inputSchema: {\n type: \"object\",\n properties: {\n project: { type: \"string\", description: \"Filter by project\" },\n maxClusters: {\n type: \"number\",\n description: \"Max concept clusters to process (default 10, max 20)\",\n },\n },\n },\n },\n {\n name: \"memory_insight_list\",\n description:\n \"List synthesized insights — higher-order observations derived from patterns across memories, lessons, and crystals.\",\n inputSchema: {\n type: \"object\",\n properties: {\n project: { type: \"string\", description: \"Filter by project\" },\n minConfidence: {\n type: \"number\",\n description: \"Minimum confidence threshold (default 0)\",\n },\n limit: { type: \"number\", description: \"Max results (default 50)\" },\n },\n },\n },\n];\n\nexport const V010_SLOTS_TOOLS: McpToolDef[] = [\n {\n name: \"memory_slot_list\",\n description:\n \"List all memory slots (pinned + project + global). Slots are editable, size-limited memory units the agent can read and modify across sessions.\",\n inputSchema: { type: \"object\", properties: {} },\n },\n {\n name: \"memory_slot_get\",\n description: \"Read a single slot by label.\",\n inputSchema: {\n type: \"object\",\n properties: {\n label: { type: \"string\", description: \"Slot label (e.g. 'persona', 'pending_items')\" },\n },\n required: [\"label\"],\n },\n },\n {\n name: \"memory_slot_create\",\n description: \"Create a new slot. Reject if a slot with the same label already exists.\",\n inputSchema: {\n type: \"object\",\n properties: {\n label: { type: \"string\", description: \"Slot label — lowercase, starts with letter, [a-z0-9_]\" },\n content: { type: \"string\", description: \"Initial content (default empty)\" },\n sizeLimit: { type: \"number\", description: \"Max chars (default 2000, hard cap 20000)\" },\n description: { type: \"string\", description: \"What this slot is for\" },\n pinned: { type: \"string\", description: \"'false' to exclude from context injection; default true\" },\n scope: { type: \"string\", description: \"'project' (default) or 'global' (shared across projects)\" },\n },\n required: [\"label\"],\n },\n },\n {\n name: \"memory_slot_append\",\n description:\n \"Append text to an existing slot. Fails with 413 if the append would exceed the slot's sizeLimit — agent must compact via memory_slot_replace first.\",\n inputSchema: {\n type: \"object\",\n properties: {\n label: { type: \"string\", description: \"Slot label\" },\n text: { type: \"string\", description: \"Text to append\" },\n },\n required: [\"label\", \"text\"],\n },\n },\n {\n name: \"memory_slot_replace\",\n description: \"Replace slot content in place. Fails if content exceeds sizeLimit.\",\n inputSchema: {\n type: \"object\",\n properties: {\n label: { type: \"string\", description: \"Slot label\" },\n content: { type: \"string\", description: \"New full content\" },\n },\n required: [\"label\", \"content\"],\n },\n },\n {\n name: \"memory_slot_delete\",\n description: \"Delete a slot. Seeded default slots can be deleted unless marked readOnly.\",\n inputSchema: {\n type: \"object\",\n properties: {\n label: { type: \"string\", description: \"Slot label\" },\n },\n required: [\"label\"],\n },\n },\n];\n\nconst ESSENTIAL_TOOLS = new Set([\n \"memory_save\",\n \"memory_recall\",\n \"memory_consolidate\",\n \"memory_smart_search\",\n \"memory_sessions\",\n \"memory_diagnose\",\n \"memory_lesson_save\",\n \"memory_reflect\",\n]);\n\nexport function getAllTools(): McpToolDef[] {\n return [\n ...CORE_TOOLS,\n ...V040_TOOLS,\n ...V050_TOOLS,\n ...V051_TOOLS,\n ...V061_TOOLS,\n ...V070_TOOLS,\n ...V073_TOOLS,\n ...V010_SLOTS_TOOLS,\n ];\n}\n\nexport function getVisibleTools(): McpToolDef[] {\n const mode = process.env[\"AGENTMEMORY_TOOLS\"] || \"core\";\n if (mode === \"all\") return getAllTools();\n return getAllTools().filter((t) => ESSENTIAL_TOOLS.has(t.name));\n}\n","import { existsSync, readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { homedir } from \"node:os\";\nimport type {\n AgentMemoryConfig,\n ProviderConfig,\n EmbeddingConfig,\n FallbackConfig,\n ClaudeBridgeConfig,\n TeamConfig,\n} from \"./types.js\";\n\nfunction safeParseInt(value: string | undefined, fallback: number): number {\n if (!value) return fallback;\n const parsed = parseInt(value, 10);\n return Number.isNaN(parsed) ? fallback : parsed;\n}\n\nconst DATA_DIR = join(homedir(), \".agentmemory\");\nconst ENV_FILE = join(DATA_DIR, \".env\");\n\nfunction loadEnvFile(): Record<string, string> {\n if (!existsSync(ENV_FILE)) return {};\n const content = readFileSync(ENV_FILE, \"utf-8\");\n const vars: Record<string, string> = {};\n for (const line of content.split(\"\\n\")) {\n const trimmed = line.trim();\n if (!trimmed || trimmed.startsWith(\"#\")) continue;\n const eqIdx = trimmed.indexOf(\"=\");\n if (eqIdx === -1) continue;\n const key = trimmed.slice(0, eqIdx).trim();\n let val = trimmed.slice(eqIdx + 1).trim();\n const quoteChar = val[0] === '\"' || val[0] === \"'\" ? val[0] : \"\";\n if (quoteChar) {\n const closeIdx = val.indexOf(quoteChar, 1);\n if (closeIdx !== -1) val = val.slice(1, closeIdx);\n } else {\n const hashIdx = val.indexOf(\" #\");\n if (hashIdx !== -1) val = val.slice(0, hashIdx).trim();\n }\n vars[key] = val;\n }\n return vars;\n}\n\nfunction hasRealValue(v: string | undefined): v is string {\n return typeof v === \"string\" && v.trim().length > 0;\n}\n\nfunction detectProvider(env: Record<string, string>): ProviderConfig {\n const maxTokens = parseInt(env[\"MAX_TOKENS\"] || \"4096\", 10);\n\n // OpenAI-compatible: supports OpenAI, DeepSeek, SiliconFlow, Azure, vLLM, LM Studio\n if (hasRealValue(env[\"OPENAI_API_KEY\"]) && env[\"OPENAI_API_KEY_FOR_LLM\"] !== \"false\") {\n return {\n provider: \"openai\",\n model: env[\"OPENAI_MODEL\"] || \"gpt-4o-mini\",\n maxTokens,\n baseURL: env[\"OPENAI_BASE_URL\"],\n };\n }\n\n // MiniMax: Anthropic-compatible API, requires raw fetch to avoid SDK stainless headers\n if (hasRealValue(env[\"MINIMAX_API_KEY\"])) {\n return {\n provider: \"minimax\",\n model: env[\"MINIMAX_MODEL\"] || \"MiniMax-M2.7\",\n maxTokens,\n };\n }\n\n if (hasRealValue(env[\"ANTHROPIC_API_KEY\"])) {\n return {\n provider: \"anthropic\",\n model: env[\"ANTHROPIC_MODEL\"] || \"claude-sonnet-4-20250514\",\n maxTokens,\n baseURL: env[\"ANTHROPIC_BASE_URL\"],\n };\n }\n if (hasRealValue(env[\"GEMINI_API_KEY\"]) || hasRealValue(env[\"GOOGLE_API_KEY\"])) {\n if (!hasRealValue(env[\"GEMINI_API_KEY\"]) && hasRealValue(env[\"GOOGLE_API_KEY\"])) {\n process.stderr.write(\n \"[agentmemory] GOOGLE_API_KEY detected — treating as GEMINI_API_KEY. \" +\n \"Set GEMINI_API_KEY in ~/.agentmemory/.env to silence this warning.\\n\",\n );\n }\n return {\n provider: \"gemini\",\n model: env[\"GEMINI_MODEL\"] || \"gemini-2.5-flash\",\n maxTokens,\n };\n }\n if (hasRealValue(env[\"OPENROUTER_API_KEY\"])) {\n return {\n provider: \"openrouter\",\n model: env[\"OPENROUTER_MODEL\"] || \"anthropic/claude-sonnet-4-20250514\",\n maxTokens,\n };\n }\n\n const allowAgentSdk = env[\"AGENTMEMORY_ALLOW_AGENT_SDK\"] === \"true\";\n if (!allowAgentSdk) {\n process.stderr.write(\n \"[agentmemory] No LLM provider key found \" +\n \"(ANTHROPIC_API_KEY, GEMINI_API_KEY, OPENROUTER_API_KEY, MINIMAX_API_KEY, OPENAI_API_KEY). \" +\n \"LLM-backed compression and summarization are DISABLED — using no-op provider. \" +\n \"This is the safe default: the agent-sdk fallback used to spawn Claude Agent SDK \" +\n \"child sessions which inherit Claude Code's plugin hooks and cause infinite Stop-hook \" +\n \"recursion (#149 follow-up). To opt in to the agent-sdk fallback anyway, set both \" +\n \"AGENTMEMORY_AUTO_COMPRESS=true AND AGENTMEMORY_ALLOW_AGENT_SDK=true — but be aware \" +\n \"it will burn your Claude Pro allocation and may still recurse if you use it from \" +\n \"inside Claude Code itself.\\n\",\n );\n return {\n provider: \"noop\",\n model: \"noop\",\n maxTokens,\n };\n }\n\n process.stderr.write(\n \"[agentmemory] WARNING: agent-sdk fallback enabled via AGENTMEMORY_ALLOW_AGENT_SDK=true. \" +\n \"This spawns @anthropic-ai/claude-agent-sdk child sessions that can trigger the Stop-hook \" +\n \"recursion loop (#149 follow-up). A SDK-child env marker is set to block re-entry, \" +\n \"but prefer setting a real API key in ~/.agentmemory/.env instead.\\n\",\n );\n return {\n provider: \"agent-sdk\",\n model: \"claude-sonnet-4-20250514\",\n maxTokens,\n };\n}\n\nexport function loadConfig(): AgentMemoryConfig {\n const env = getMergedEnv();\n\n const provider = detectProvider(env);\n\n return {\n engineUrl: env[\"III_ENGINE_URL\"] || \"ws://localhost:49134\",\n restPort: parseInt(env[\"III_REST_PORT\"] || \"3111\", 10) || 3111,\n streamsPort: parseInt(env[\"III_STREAMS_PORT\"] || \"3112\", 10) || 3112,\n provider,\n tokenBudget: safeParseInt(env[\"TOKEN_BUDGET\"], 2000),\n maxObservationsPerSession: safeParseInt(env[\"MAX_OBS_PER_SESSION\"], 500),\n compressionModel: provider.model,\n dataDir: DATA_DIR,\n };\n}\n\nfunction getMergedEnv(\n overrides?: Record<string, string>,\n): Record<string, string> {\n const fileEnv = loadEnvFile();\n return { ...fileEnv, ...process.env, ...overrides } as Record<string, string>;\n}\n\nexport function getEnvVar(key: string): string | undefined {\n return getMergedEnv()[key];\n}\n\nexport function detectLlmProviderKind(): \"llm\" | \"noop\" {\n const env = getMergedEnv();\n if (\n hasRealValue(env[\"ANTHROPIC_API_KEY\"]) ||\n hasRealValue(env[\"GEMINI_API_KEY\"]) ||\n hasRealValue(env[\"GOOGLE_API_KEY\"]) ||\n hasRealValue(env[\"OPENROUTER_API_KEY\"]) ||\n hasRealValue(env[\"MINIMAX_API_KEY\"]) ||\n (hasRealValue(env[\"OPENAI_API_KEY\"]) &&\n env[\"OPENAI_API_KEY_FOR_LLM\"] !== \"false\")\n ) {\n return \"llm\";\n }\n return \"noop\";\n}\n\nexport function loadEmbeddingConfig(): EmbeddingConfig {\n const env = getMergedEnv();\n let bm25Weight = parseFloat(env[\"BM25_WEIGHT\"] || \"0.4\");\n let vectorWeight = parseFloat(env[\"VECTOR_WEIGHT\"] || \"0.6\");\n bm25Weight =\n isNaN(bm25Weight) || bm25Weight < 0 ? 0.4 : Math.min(bm25Weight, 1);\n vectorWeight =\n isNaN(vectorWeight) || vectorWeight < 0 ? 0.6 : Math.min(vectorWeight, 1);\n return {\n provider: env[\"EMBEDDING_PROVIDER\"] || undefined,\n bm25Weight,\n vectorWeight,\n };\n}\n\nexport function detectEmbeddingProvider(\n env?: Record<string, string>,\n): string | null {\n const source = env ?? getMergedEnv();\n const forced = source[\"EMBEDDING_PROVIDER\"];\n if (forced) return forced;\n\n if (source[\"GEMINI_API_KEY\"]) return \"gemini\";\n if (source[\"OPENAI_API_KEY\"]) return \"openai\";\n if (source[\"VOYAGE_API_KEY\"]) return \"voyage\";\n if (source[\"COHERE_API_KEY\"]) return \"cohere\";\n if (source[\"OPENROUTER_API_KEY\"]) return \"openrouter\";\n return null;\n}\n\nexport function loadClaudeBridgeConfig(): ClaudeBridgeConfig {\n const env = getMergedEnv();\n const enabled = env[\"CLAUDE_MEMORY_BRIDGE\"] === \"true\";\n const projectPath = env[\"CLAUDE_PROJECT_PATH\"] || \"\";\n const lineBudget = safeParseInt(env[\"CLAUDE_MEMORY_LINE_BUDGET\"], 200);\n let memoryFilePath = \"\";\n if (enabled && projectPath) {\n const safePath = projectPath.replace(/[/\\\\]/g, \"-\").replace(/^-/, \"\");\n memoryFilePath = join(\n homedir(),\n \".claude\",\n \"projects\",\n safePath,\n \"memory\",\n \"MEMORY.md\",\n );\n }\n return { enabled, projectPath, memoryFilePath, lineBudget };\n}\n\nexport function loadTeamConfig(): TeamConfig | null {\n const env = getMergedEnv();\n const teamId = env[\"TEAM_ID\"];\n const userId = env[\"USER_ID\"];\n if (!teamId || !userId) return null;\n const mode = env[\"TEAM_MODE\"] === \"shared\" ? \"shared\" : \"private\";\n return { teamId, userId, mode };\n}\n\nexport function loadSnapshotConfig(): {\n enabled: boolean;\n interval: number;\n dir: string;\n} {\n const env = getMergedEnv();\n return {\n enabled: env[\"SNAPSHOT_ENABLED\"] === \"true\",\n interval: safeParseInt(env[\"SNAPSHOT_INTERVAL\"], 3600),\n dir: env[\"SNAPSHOT_DIR\"] || join(homedir(), \".agentmemory\", \"snapshots\"),\n };\n}\n\nexport function isGraphExtractionEnabled(): boolean {\n return getMergedEnv()[\"GRAPH_EXTRACTION_ENABLED\"] === \"true\";\n}\n\nexport function getGraphBatchSize(): number {\n return safeParseInt(getMergedEnv()[\"GRAPH_EXTRACTION_BATCH_SIZE\"], 10);\n}\n\nexport function isConsolidationEnabled(): boolean {\n return getMergedEnv()[\"CONSOLIDATION_ENABLED\"] === \"true\";\n}\n\n// Per-observation LLM compression is OFF by default as of 0.8.8 (see #138).\n// When disabled, observations are captured and indexed via a synthetic\n// (zero-LLM) compression path so recall/search still works. Users who want\n// richer LLM-generated summaries can set AGENTMEMORY_AUTO_COMPRESS=true in\n// ~/.agentmemory/.env — but should expect their Claude API token usage to\n// climb proportionally with session tool-use frequency.\nexport function isAutoCompressEnabled(): boolean {\n return getMergedEnv()[\"AGENTMEMORY_AUTO_COMPRESS\"] === \"true\";\n}\n\n// Hook-level context injection into Claude Code's conversation is OFF by\n// default as of 0.8.10 (see #143). When disabled, pre-tool-use and\n// session-start hooks still POST observations for background capture, but\n// never write context to stdout — so Claude Code doesn't inject an extra\n// ~4000-char blob into every tool turn. 0.8.8 stopped the agentmemory-side\n// Claude calls (via ANTHROPIC_API_KEY); this stops the Claude Code-side\n// token burn where every tool call silently grew the model input window.\n// Users who want the in-conversation context injection explicitly opt in\n// with AGENTMEMORY_INJECT_CONTEXT=true and get a loud startup warning.\nexport function isContextInjectionEnabled(): boolean {\n return getMergedEnv()[\"AGENTMEMORY_INJECT_CONTEXT\"] === \"true\";\n}\n\nexport function getConsolidationDecayDays(): number {\n return safeParseInt(getMergedEnv()[\"CONSOLIDATION_DECAY_DAYS\"], 30);\n}\n\nexport function isStandaloneMcp(): boolean {\n return getMergedEnv()[\"STANDALONE_MCP\"] === \"true\";\n}\n\nexport function getStandalonePersistPath(): string {\n const env = getMergedEnv();\n return (\n env[\"STANDALONE_PERSIST_PATH\"] ||\n join(homedir(), \".agentmemory\", \"standalone.json\")\n );\n}\n\nconst VALID_PROVIDERS = new Set([\n \"anthropic\",\n \"gemini\",\n \"openrouter\",\n \"agent-sdk\",\n \"minimax\",\n \"openai\",\n]);\n\nexport function loadFallbackConfig(): FallbackConfig {\n const env = getMergedEnv();\n const raw = env[\"FALLBACK_PROVIDERS\"] || \"\";\n const allowAgentSdk = env[\"AGENTMEMORY_ALLOW_AGENT_SDK\"] === \"true\";\n const providers = raw\n .split(\",\")\n .map((p) => p.trim())\n .filter(\n (p): p is FallbackConfig[\"providers\"][number] =>\n Boolean(p) && VALID_PROVIDERS.has(p),\n )\n .filter((p) => {\n // Honor the same safety gate as detectProvider: agent-sdk is only\n // permitted as a fallback target when the user has explicitly opted\n // in. Without this filter, a user could set FALLBACK_PROVIDERS=agent-sdk\n // and re-introduce the Stop-hook recursion loop even though\n // detectProvider() returned the noop provider.\n if (p === \"agent-sdk\" && !allowAgentSdk) {\n process.stderr.write(\n \"[agentmemory] Ignoring FALLBACK_PROVIDERS entry 'agent-sdk' \" +\n \"(AGENTMEMORY_ALLOW_AGENT_SDK is not 'true'). The agent-sdk \" +\n \"fallback can spawn Claude Agent SDK child sessions that trigger \" +\n \"the Stop-hook recursion loop (#149 follow-up). Opt in explicitly \" +\n \"with AGENTMEMORY_ALLOW_AGENT_SDK=true if this is intentional.\\n\",\n );\n return false;\n }\n return true;\n });\n return { providers };\n}\n","export const VERSION = \"0.9.20\";\n","import { createHash } from \"node:crypto\";\n\nexport const KV = {\n sessions: \"mem:sessions\",\n observations: (sessionId: string) => `mem:obs:${sessionId}`,\n memories: \"mem:memories\",\n summaries: \"mem:summaries\",\n config: \"mem:config\",\n metrics: \"mem:metrics\",\n health: \"mem:health\",\n embeddings: (obsId: string) => `mem:emb:${obsId}`,\n bm25Index: \"mem:index:bm25\",\n relations: \"mem:relations\",\n profiles: \"mem:profiles\",\n claudeBridge: \"mem:claude-bridge\",\n graphNodes: \"mem:graph:nodes\",\n graphEdges: \"mem:graph:edges\",\n semantic: \"mem:semantic\",\n procedural: \"mem:procedural\",\n teamShared: (teamId: string) => `mem:team:${teamId}:shared`,\n teamUsers: (teamId: string, userId: string) =>\n `mem:team:${teamId}:users:${userId}`,\n teamProfile: (teamId: string) => `mem:team:${teamId}:profile`,\n audit: \"mem:audit\",\n actions: \"mem:actions\",\n actionEdges: \"mem:action-edges\",\n leases: \"mem:leases\",\n routines: \"mem:routines\",\n routineRuns: \"mem:routine-runs\",\n signals: \"mem:signals\",\n checkpoints: \"mem:checkpoints\",\n mesh: \"mem:mesh\",\n sketches: \"mem:sketches\",\n facets: \"mem:facets\",\n sentinels: \"mem:sentinels\",\n crystals: \"mem:crystals\",\n lessons: \"mem:lessons\",\n insights: \"mem:insights\",\n graphEdgeHistory: \"mem:graph:edge-history\",\n enrichedChunks: (sessionId: string) => `mem:enriched:${sessionId}`,\n latentEmbeddings: (obsId: string) => `mem:latent:${obsId}`,\n retentionScores: \"mem:retention\",\n accessLog: \"mem:access\",\n imageRefs: \"mem:image-refs\",\n imageEmbeddings: \"mem:image-embeddings\",\n slots: \"mem:slots\",\n globalSlots: \"mem:slots:global\",\n state: \"mem:state\",\n commits: \"mem:commits\",\n} as const;\n\nexport const STREAM = {\n name: \"mem-live\",\n group: (sessionId: string) => sessionId,\n viewerGroup: \"viewer\",\n} as const;\n\nexport function generateId(prefix: string): string {\n const ts = Date.now().toString(36);\n const rand = crypto.randomUUID().replace(/-/g, \"\").slice(0, 12);\n return `${prefix}_${ts}_${rand}`;\n}\n\nexport function fingerprintId(prefix: string, content: string): string {\n const hash = createHash(\"sha256\").update(content).digest(\"hex\");\n return `${prefix}_${hash.slice(0, 16)}`;\n}\n\nexport function jaccardSimilarity(a: string, b: string): number {\n const setA = new Set(a.split(/\\s+/).filter((t) => t.length > 2));\n const setB = new Set(b.split(/\\s+/).filter((t) => t.length > 2));\n if (setA.size === 0 && setB.size === 0) return 1;\n if (setA.size === 0 || setB.size === 0) return 0;\n let intersection = 0;\n for (const word of setA) {\n if (setB.has(word)) intersection++;\n }\n return intersection / (setA.size + setB.size - intersection);\n}\n","const DEFAULT_URL = \"http://localhost:3111\";\nconst DEFAULT_HEALTH_PROBE_TIMEOUT_MS = 2_000;\nconst CALL_TIMEOUT_MS = 15_000;\nconst LOCAL_MODE_TTL_MS = 30_000;\n\nfunction probeTimeoutMs(): number {\n const raw = process.env[\"AGENTMEMORY_PROBE_TIMEOUT_MS\"];\n if (!raw) return DEFAULT_HEALTH_PROBE_TIMEOUT_MS;\n const n = Number(raw);\n return Number.isFinite(n) && n > 0 ? Math.floor(n) : DEFAULT_HEALTH_PROBE_TIMEOUT_MS;\n}\n\nfunction forceProxy(): boolean {\n const raw = process.env[\"AGENTMEMORY_FORCE_PROXY\"];\n return raw === \"1\" || raw === \"true\";\n}\n\nexport interface ProxyHandle {\n mode: \"proxy\";\n baseUrl: string;\n call: (path: string, init?: RequestInit) => Promise<unknown>;\n}\n\nexport interface LocalHandle {\n mode: \"local\";\n}\n\nexport type Handle = ProxyHandle | LocalHandle;\n\nlet cached: Handle | null = null;\nlet cachedAt = 0;\nlet probeInFlight: Promise<Handle> | null = null;\n\nfunction baseUrl(): string {\n return (process.env[\"AGENTMEMORY_URL\"] || DEFAULT_URL).replace(/\\/+$/, \"\");\n}\n\nfunction authHeader(): Record<string, string> {\n const secret = process.env[\"AGENTMEMORY_SECRET\"];\n return secret ? { authorization: `Bearer ${secret}` } : {};\n}\n\n/**\n * Probes the agentmemory server's livez endpoint. Returns a Response-shaped\n * object whose `ok` flag drives the proxy/local-fallback decision.\n *\n * Tests can swap this via {@link setLivezProbe} to avoid the real 2s\n * AbortController race that destabilises mcp-standalone test runs (#449).\n * Production callers should leave it on the default.\n */\nexport type LivezProbe = (\n url: string,\n timeoutMs: number,\n headers: Record<string, string>,\n) => Promise<{ ok: boolean; status?: number; statusText?: string }>;\n\nconst defaultLivezProbe: LivezProbe = async (url, timeoutMs, headers) => {\n const res = await fetch(`${url}/agentmemory/livez`, {\n method: \"GET\",\n headers,\n signal: AbortSignal.timeout(timeoutMs),\n });\n return { ok: res.ok, status: res.status, statusText: res.statusText };\n};\n\nlet livezProbe: LivezProbe = defaultLivezProbe;\n\n/**\n * Override the livez probe. Intended for tests — production code should rely\n * on the default fetch-based probe. Calling without an argument restores the\n * default. Pair with {@link resetHandleForTests} so the cached handle is\n * dropped before the next call.\n */\nexport function setLivezProbe(fn?: LivezProbe): void {\n livezProbe = fn ?? defaultLivezProbe;\n}\n\nasync function probe(url: string): Promise<boolean> {\n const timeout = probeTimeoutMs();\n try {\n const res = await livezProbe(url, timeout, authHeader());\n if (!res.ok) {\n process.stderr.write(\n `[@agentmemory/mcp] livez probe ${url}/agentmemory/livez -> ${res.status ?? \"?\"} ${res.statusText ?? \"\"}; falling back to local InMemoryKV (set AGENTMEMORY_FORCE_PROXY=1 to skip the probe)\\n`,\n );\n }\n return res.ok;\n } catch (err) {\n process.stderr.write(\n `[@agentmemory/mcp] livez probe ${url}/agentmemory/livez failed in ${timeout}ms: ${err instanceof Error ? err.message : String(err)}; falling back to local InMemoryKV (set AGENTMEMORY_FORCE_PROXY=1 to skip the probe, or raise AGENTMEMORY_PROBE_TIMEOUT_MS)\\n`,\n );\n return false;\n }\n}\n\nexport function invalidateHandle(): void {\n cached = null;\n cachedAt = 0;\n}\n\nexport async function resolveHandle(): Promise<Handle> {\n const now = Date.now();\n if (cached) {\n if (cached.mode === \"local\" && now - cachedAt >= LOCAL_MODE_TTL_MS) {\n cached = null;\n cachedAt = 0;\n } else {\n return cached;\n }\n }\n if (probeInFlight) return probeInFlight;\n const url = baseUrl();\n const skipProbe = forceProxy();\n probeInFlight = (async () => {\n const up = skipProbe ? true : await probe(url);\n if (skipProbe) {\n process.stderr.write(\n `[@agentmemory/mcp] AGENTMEMORY_FORCE_PROXY set; skipping livez probe and trusting ${url}\\n`,\n );\n }\n if (up) {\n const handle: ProxyHandle = {\n mode: \"proxy\",\n baseUrl: url,\n call: async (path, init) => {\n const res = await fetch(`${url}${path}`, {\n ...init,\n headers: {\n \"content-type\": \"application/json\",\n ...authHeader(),\n ...(init?.headers as Record<string, string> | undefined),\n },\n signal: AbortSignal.timeout(CALL_TIMEOUT_MS),\n });\n if (!res.ok) {\n throw new Error(\n `${init?.method || \"GET\"} ${path} -> ${res.status} ${res.statusText}`,\n );\n }\n const text = await res.text();\n return text ? JSON.parse(text) : null;\n },\n };\n cached = handle;\n cachedAt = Date.now();\n return handle;\n }\n const local: LocalHandle = { mode: \"local\" };\n cached = local;\n cachedAt = Date.now();\n return local;\n })();\n try {\n return await probeInFlight;\n } finally {\n probeInFlight = null;\n }\n}\n\nexport function resetHandleForTests(): void {\n cached = null;\n cachedAt = 0;\n probeInFlight = null;\n livezProbe = defaultLivezProbe;\n}\n","#!/usr/bin/env node\n\nimport { InMemoryKV } from \"./in-memory-kv.js\";\nimport { createStdioTransport } from \"./transport.js\";\nimport { getAllTools } from \"./tools-registry.js\";\nimport { getStandalonePersistPath } from \"../config.js\";\nimport { VERSION } from \"../version.js\";\nimport { generateId } from \"../state/schema.js\";\nimport {\n resolveHandle,\n invalidateHandle,\n type Handle,\n type ProxyHandle,\n} from \"./rest-proxy.js\";\n\nconst IMPLEMENTED_TOOLS = new Set([\n \"memory_save\",\n \"memory_recall\",\n \"memory_smart_search\",\n \"memory_sessions\",\n \"memory_export\",\n \"memory_audit\",\n \"memory_governance_delete\",\n]);\n\nconst SERVER_INFO = {\n name: \"agentmemory\",\n version: VERSION,\n protocolVersion: \"2024-11-05\",\n};\n\nconst kv = new InMemoryKV(getStandalonePersistPath());\nlet modeAnnounced = false;\n\nfunction announceMode(handle: Handle): void {\n if (modeAnnounced) return;\n modeAnnounced = true;\n if (handle.mode === \"proxy\") {\n process.stderr.write(\n `[@agentmemory/mcp] proxying to agentmemory server at ${handle.baseUrl}\\n`,\n );\n } else {\n process.stderr.write(\n `[@agentmemory/mcp] no server reachable at ${process.env[\"AGENTMEMORY_URL\"] || \"http://localhost:3111\"}; falling back to local InMemoryKV\\n`,\n );\n }\n}\n\nfunction normalizeList(value: unknown): string[] {\n if (!value) return [];\n if (Array.isArray(value)) {\n return value\n .map((v) => (typeof v === \"string\" ? v.trim() : \"\"))\n .filter((v) => v.length > 0);\n }\n if (typeof value === \"string\") {\n return value\n .split(\",\")\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n }\n return [];\n}\n\nconst DEFAULT_LIMIT = 10;\nconst MAX_LIMIT = 100;\nfunction parseLimit(raw: unknown, fallback = DEFAULT_LIMIT): number {\n if (typeof raw !== \"number\" && typeof raw !== \"string\") return fallback;\n const n = Number(raw);\n if (!Number.isFinite(n) || n <= 0) return fallback;\n return Math.min(Math.floor(n), MAX_LIMIT);\n}\n\nfunction textResponse(payload: unknown, pretty = false): {\n content: Array<{ type: string; text: string }>;\n} {\n return {\n content: [\n { type: \"text\", text: JSON.stringify(payload, null, pretty ? 2 : 0) },\n ],\n };\n}\n\ninterface Validated {\n tool: string;\n content?: string;\n type?: string;\n concepts?: string[];\n files?: string[];\n query?: string;\n limit?: number;\n memoryIds?: string[];\n reason?: string;\n}\n\nfunction validate(toolName: string, args: Record<string, unknown>): Validated {\n if (!IMPLEMENTED_TOOLS.has(toolName)) {\n throw new Error(`Unknown tool: ${toolName}`);\n }\n const v: Validated = { tool: toolName };\n switch (toolName) {\n case \"memory_save\": {\n const content = args[\"content\"];\n if (typeof content !== \"string\" || !content.trim()) {\n throw new Error(\"content is required\");\n }\n v.content = content;\n v.type = (args[\"type\"] as string) || \"fact\";\n v.concepts = normalizeList(args[\"concepts\"]);\n v.files = normalizeList(args[\"files\"]);\n return v;\n }\n case \"memory_recall\":\n case \"memory_smart_search\": {\n const query = args[\"query\"];\n if (typeof query !== \"string\" || !query.trim()) {\n throw new Error(\"query is required\");\n }\n v.query = query.trim();\n v.limit = parseLimit(args[\"limit\"]);\n return v;\n }\n case \"memory_sessions\": {\n v.limit = parseLimit(args[\"limit\"], 20);\n return v;\n }\n case \"memory_governance_delete\": {\n const ids = normalizeList(args[\"memoryIds\"]);\n if (ids.length === 0) throw new Error(\"memoryIds is required\");\n v.memoryIds = ids;\n v.reason = (args[\"reason\"] as string) || \"plugin skill request\";\n return v;\n }\n case \"memory_export\":\n return v;\n case \"memory_audit\": {\n v.limit = parseLimit(args[\"limit\"], 50);\n return v;\n }\n default:\n throw new Error(`Unknown tool: ${toolName}`);\n }\n}\n\nasync function handleProxy(\n v: Validated,\n handle: ProxyHandle,\n): Promise<{ content: Array<{ type: string; text: string }> }> {\n switch (v.tool) {\n case \"memory_save\": {\n const result = await handle.call(\"/agentmemory/remember\", {\n method: \"POST\",\n body: JSON.stringify({\n content: v.content,\n type: v.type,\n concepts: v.concepts,\n files: v.files,\n }),\n });\n return textResponse(result);\n }\n case \"memory_recall\":\n case \"memory_smart_search\": {\n const result = await handle.call(\"/agentmemory/smart-search\", {\n method: \"POST\",\n body: JSON.stringify({ query: v.query, limit: v.limit }),\n });\n return textResponse(result, true);\n }\n case \"memory_sessions\": {\n const result = await handle.call(\n `/agentmemory/sessions?limit=${v.limit}`,\n { method: \"GET\" },\n );\n return textResponse(result, true);\n }\n case \"memory_governance_delete\": {\n const result = await handle.call(\"/agentmemory/governance/memories\", {\n method: \"DELETE\",\n body: JSON.stringify({ memoryIds: v.memoryIds, reason: v.reason }),\n });\n return textResponse(result);\n }\n case \"memory_export\": {\n const result = await handle.call(\"/agentmemory/export\", { method: \"GET\" });\n return textResponse(result, true);\n }\n case \"memory_audit\": {\n const result = await handle.call(\n `/agentmemory/audit?limit=${v.limit}`,\n { method: \"GET\" },\n );\n return textResponse(result, true);\n }\n default:\n throw new Error(`Unknown tool: ${v.tool}`);\n }\n}\n\nasync function handleLocal(\n v: Validated,\n kvInstance: InMemoryKV,\n): Promise<{ content: Array<{ type: string; text: string }> }> {\n switch (v.tool) {\n case \"memory_save\": {\n const id = generateId(\"mem\");\n const isoNow = new Date().toISOString();\n await kvInstance.set(\"mem:memories\", id, {\n id,\n type: v.type,\n title: (v.content || \"\").slice(0, 80),\n content: v.content,\n concepts: v.concepts,\n files: v.files,\n createdAt: isoNow,\n updatedAt: isoNow,\n strength: 7,\n version: 1,\n isLatest: true,\n sessionIds: [],\n });\n kvInstance.persist();\n return textResponse({ saved: id });\n }\n\n case \"memory_recall\":\n case \"memory_smart_search\": {\n const query = (v.query || \"\").toLowerCase();\n const limit = v.limit ?? DEFAULT_LIMIT;\n const all =\n await kvInstance.list<Record<string, unknown>>(\"mem:memories\");\n const results = all\n .filter((m) => {\n const text = [\n typeof m[\"title\"] === \"string\" ? m[\"title\"] : \"\",\n typeof m[\"content\"] === \"string\" ? m[\"content\"] : \"\",\n Array.isArray(m[\"files\"]) ? m[\"files\"].join(\" \") : \"\",\n Array.isArray(m[\"concepts\"]) ? m[\"concepts\"].join(\" \") : \"\",\n Array.isArray(m[\"sessionIds\"]) ? m[\"sessionIds\"].join(\" \") : \"\",\n typeof m[\"id\"] === \"string\" ? m[\"id\"] : \"\",\n ]\n .join(\" \")\n .toLowerCase();\n return query.split(/\\s+/).every((word) => text.includes(word));\n })\n .slice(0, limit);\n return textResponse({ mode: \"compact\", results }, true);\n }\n\n case \"memory_sessions\": {\n const sessions =\n await kvInstance.list<Record<string, unknown>>(\"mem:sessions\");\n const limit = v.limit ?? 20;\n return textResponse({ sessions: sessions.slice(0, limit) }, true);\n }\n\n case \"memory_governance_delete\": {\n let deleted = 0;\n for (const id of v.memoryIds || []) {\n const existing = await kvInstance.get(\"mem:memories\", id);\n if (existing) {\n await kvInstance.delete(\"mem:memories\", id);\n deleted++;\n }\n }\n kvInstance.persist();\n return textResponse({\n deleted,\n requested: (v.memoryIds || []).length,\n reason: v.reason,\n });\n }\n\n case \"memory_export\": {\n const memories = await kvInstance.list(\"mem:memories\");\n const sessions = await kvInstance.list(\"mem:sessions\");\n return textResponse({ version: VERSION, memories, sessions }, true);\n }\n\n case \"memory_audit\": {\n const entries = await kvInstance.list(\"mem:audit\");\n const limit = v.limit ?? 50;\n return textResponse(\n {\n entries: (entries as Array<Record<string, unknown>>).slice(0, limit),\n },\n true,\n );\n }\n\n default:\n throw new Error(`Unknown tool: ${v.tool}`);\n }\n}\n\nasync function handleProxyGeneric(\n toolName: string,\n args: Record<string, unknown>,\n handle: ProxyHandle,\n): Promise<{ content: Array<{ type: string; text: string }> }> {\n // Forward to the server's full MCP surface so non-Claude clients can\n // reach all 51 tools (lessons, sentinels, slots, signals, graph, …)\n // instead of being capped at the 7 IMPLEMENTED_TOOLS set baked into\n // this shim. The server validates arguments per tool.\n const result = (await handle.call(\"/agentmemory/mcp/call\", {\n method: \"POST\",\n body: JSON.stringify({ name: toolName, arguments: args }),\n })) as { content?: Array<{ type: string; text: string }> } | null;\n if (result && Array.isArray(result.content)) {\n return { content: result.content };\n }\n return textResponse(result, true);\n}\n\nexport async function handleToolCall(\n toolName: string,\n args: Record<string, unknown>,\n kvInstance: InMemoryKV = kv,\n): Promise<{ content: Array<{ type: string; text: string }> }> {\n const handle = await resolveHandle();\n announceMode(handle);\n\n // Tools the local InMemoryKV fallback doesn't implement: forward straight\n // to the server. Local validation would otherwise raise \"Unknown tool\"\n // (issue #234).\n if (!IMPLEMENTED_TOOLS.has(toolName)) {\n if (handle.mode === \"proxy\") {\n try {\n return await handleProxyGeneric(toolName, args, handle);\n } catch (err) {\n process.stderr.write(\n `[@agentmemory/mcp] proxy call failed for ${toolName}: ${err instanceof Error ? err.message : String(err)}\\n`,\n );\n invalidateHandle();\n throw err;\n }\n }\n throw new Error(\n `Unknown tool: ${toolName} (local fallback supports only ${[...IMPLEMENTED_TOOLS].join(\", \")}; start an agentmemory server and set AGENTMEMORY_URL to use the full tool set)`,\n );\n }\n\n const validated = validate(toolName, args);\n if (handle.mode === \"proxy\") {\n try {\n return await handleProxy(validated, handle);\n } catch (err) {\n process.stderr.write(\n `[@agentmemory/mcp] proxy call failed for ${toolName}: ${err instanceof Error ? err.message : String(err)}; invalidating handle and falling back to local KV\\n`,\n );\n invalidateHandle();\n }\n }\n return handleLocal(validated, kvInstance);\n}\n\nexport async function handleToolsList(): Promise<{ tools: unknown[] }> {\n const debug = process.env[\"AGENTMEMORY_DEBUG\"] === \"1\" || process.env[\"AGENTMEMORY_DEBUG\"] === \"true\";\n const handle = await resolveHandle();\n announceMode(handle);\n if (debug) {\n process.stderr.write(\n `[@agentmemory/mcp] tools/list: handle.mode=${handle.mode}${handle.mode === \"proxy\" ? ` baseUrl=${handle.baseUrl}` : \"\"}\\n`,\n );\n }\n if (handle.mode === \"proxy\") {\n try {\n const remote = (await handle.call(\"/agentmemory/mcp/tools\", {\n method: \"GET\",\n })) as { tools?: unknown } | null;\n if (debug) {\n const shape = remote === null\n ? \"null\"\n : typeof remote !== \"object\"\n ? typeof remote\n : `keys=${Object.keys(remote as object).join(\",\")} toolsType=${Array.isArray((remote as { tools?: unknown }).tools) ? `array(len=${((remote as { tools: unknown[] }).tools).length})` : typeof (remote as { tools?: unknown }).tools}`;\n process.stderr.write(\n `[@agentmemory/mcp] tools/list: remote response shape: ${shape}\\n`,\n );\n }\n if (remote && Array.isArray(remote.tools)) {\n if (debug) {\n process.stderr.write(\n `[@agentmemory/mcp] tools/list: returning ${remote.tools.length} tools from server\\n`,\n );\n }\n return { tools: remote.tools };\n }\n process.stderr.write(\n `[@agentmemory/mcp] tools/list: server returned unexpected shape (no .tools array); falling back to local IMPLEMENTED_TOOLS list. Set AGENTMEMORY_DEBUG=1 to inspect response.\\n`,\n );\n } catch (err) {\n process.stderr.write(\n `[@agentmemory/mcp] tools/list proxy failed: ${err instanceof Error ? err.message : String(err)}; falling back to local list\\n`,\n );\n invalidateHandle();\n }\n }\n const fallback = getAllTools().filter((t) => IMPLEMENTED_TOOLS.has(t.name));\n if (debug) {\n process.stderr.write(\n `[@agentmemory/mcp] tools/list: returning ${fallback.length} local fallback tools (${fallback.map((t) => t.name).join(\",\")})\\n`,\n );\n }\n return { tools: fallback };\n}\n\nconst transport = createStdioTransport(async (method, params) => {\n switch (method) {\n case \"initialize\":\n return {\n protocolVersion: SERVER_INFO.protocolVersion,\n capabilities: { tools: { listChanged: false } },\n serverInfo: {\n name: SERVER_INFO.name,\n version: SERVER_INFO.version,\n },\n };\n\n case \"notifications/initialized\":\n return {};\n\n case \"tools/list\":\n return handleToolsList();\n\n case \"tools/call\": {\n const toolName = params.name as string;\n const toolArgs = (params.arguments as Record<string, unknown>) || {};\n try {\n return await handleToolCall(toolName, toolArgs);\n } catch (err) {\n return {\n content: [\n {\n type: \"text\",\n text: `Error: ${err instanceof Error ? err.message : String(err)}`,\n },\n ],\n isError: true,\n };\n }\n }\n\n default:\n throw new Error(`Unknown method: ${method}`);\n }\n});\n\nprocess.stderr.write(\n `[@agentmemory/mcp] Standalone MCP server v${SERVER_INFO.version} starting...\\n`,\n);\ntransport.start();\n\nprocess.on(\"SIGINT\", () => {\n kv.persist();\n process.exit(0);\n});\nprocess.on(\"SIGTERM\", () => {\n kv.persist();\n process.exit(0);\n});\n"],"mappings":";;;;;;;AAGA,IAAa,aAAb,MAAwB;CACtB,AAAQ,wBAAQ,IAAI,KAAmC;CAEvD,YAAY,AAAQ,aAAsB;EAAtB;AAClB,MAAI,eAAe,WAAW,YAAY,CACxC,KAAI;GACF,MAAM,OAAO,KAAK,MAAM,aAAa,aAAa,QAAQ,CAAC;AAC3D,QAAK,MAAM,CAAC,OAAO,YAAY,OAAO,QAAQ,KAAK,EAAE;IACnD,MAAM,sBAAM,IAAI,KAAsB;AACtC,SAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAChC,QACD,CACC,KAAI,IAAI,KAAK,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Ac;AAE1E,QAAO;EACL,QAAQ;AACN,QAAK,gBAAgB,EAAE,OAAO,QAAQ,OAAO,CAAC;AAC9C,MAAG,GAAG,QAAQ,OAAO;;EAEvB,OAAO;AACL,OAAI,OAAO;AACX,QAAK;;EAER;;;;;AC/IH,MAAa,aAA2B;CACtC;EACE,MAAM;EACN,aACE;EACF,aAAa;GACX,MAAM;GACN,YAAY;IACV,OAAO;KACL,MAAM;KACN,aAAa;KACd;IACD,OAAO;KACL,MAAM;KACN,aAAa;KACd;IACD,QAAQ;KACN,MAAM;KACN,aAAa;KACd;IACD,cAAc;KACZ,MAAM;KACN,aAAa;KACd;IACF;GACD,UAAU,CAAC,QAAQ;GACpB;EACF;CACD;EACE,MAAM;EACN,aACE;EACF,aAAa;GACX,MAAM;GACN,YAAY,EACV,UAAU;IACR,MAAM;IACN,aAAa;IACd,EACF;GACD,UAAU,CAAC,WAAW;GACvB;EACF;CACD;EACE,MAAM;EACN,aACE;EACF,aAAa;GACX,MAAM;GACN,YAAY;IACV,SAAS;KACP,MAAM;KACN,aAAa;KACd;IACD,MAAM;KACJ,MAAM;KACN,aACE;KACH;IACD,UAAU;KACR,MAAM;KACN,aAAa;KACd;IACD,OAAO;KACL,MAAM;KACN,aAAa;KACd;IACF;GACD,UAAU,CAAC,UAAU;GACtB;EACF;CACD;EACE,MAAM;EACN,aAAa;EACb,aAAa;GACX,MAAM;GACN,YAAY;IACV,OAAO;KAAE,MAAM;KAAU,aAAa;KAA8B;IACpE,WAAW;KACT,MAAM;KACN,aAAa;KACd;IACF;GACD,UAAU,CAAC,QAAQ;GACpB;EACF;CACD;EACE,MAAM;EACN,aAAa;EACb,aAAa;GACX,MAAM;GACN,YAAY,EACV,SAAS;IAAE,MAAM;IAAU,aAAa;IAA2B,EACpE;GACF;EACF;CACD;EACE,MAAM;EACN,aACE;EACF,aAAa;GAAE,MAAM;GAAU,YAAY,EAAE;GAAE;EAChD;CACD;EACE,MAAM;EACN,aAAa;EACb,aAAa;GACX,M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QAAQ;GACpB;EACF;CACD;EACE,MAAM;EACN,aACE;EACF,aAAa;GACX,MAAM;GACN,YAAY;IACV,UAAU;KAAE,MAAM;KAAU,aAAa;KAAwB;IACjE,SAAS;KAAE,MAAM;KAAU,aAAa;KAAyC;IAClF;GACD,UAAU,CAAC,WAAW;GACvB;EACF;CACD;EACE,MAAM;EACN,aACE;EACF,aAAa;GACX,MAAM;GACN,YAAY;IACV,WAAW;KACT,MAAM;KACN,aAAa;KACd;IACD,SAAS;KAAE,MAAM;KAAU,aAAa;KAAmB;IAC3D,WAAW;KAAE,MAAM;KAAU,aAAa;KAAmB;IAC9D;GACD,UAAU,CAAC,YAAY;GACxB;EACF;CACD;EACE,MAAM;EACN,aACE;EACF,aAAa;GACX,MAAM;GACN,YAAY,EACV,YAAY;IACV,MAAM;IACN,aAAa;IACd,EACF;GACF;EACF;CACD;EACE,MAAM;EACN,aACE;EACF,aAAa;GACX,MAAM;GACN,YAAY;IACV,YAAY;KACV,MAAM;KACN,aAAa;KACd;IACD,QAAQ;KACN,MAAM;KACN,aAAa;KACd;IACF;GACF;EACF;CACD;EACE,MAAM;EACN,aACE;EACF,aAAa;GACX,MAAM;GACN,YAAY;IACV,UAAU;KAAE,MAAM;KAAU,aAAa;KAA2B;IACpE,YAAY;KACV,MAAM;KACN,aAAa;KACd;IACD,WAAW;KAAE,MAAM;KAAU,aAAa;KAAgD;IAC1F,OAAO;KAAE,MAAM;KAAU,aAAa;KAA+C;IACtF;GACD,UAAU;IAAC;IAAY;IAAc;IAAa;IAAQ;GAC3D;EACF;CACD;EACE,MAAM;EACN,aACE;EACF,aAAa;GACX,MAAM;GACN,YAAY;IACV,UAAU;KACR,MAAM;KACN,aAAa;KACd;IACD,UAAU;KACR,MAAM;KACN,aAAa;KACd;IACD,YAAY;KACV,MAAM;KACN,aAAa;KACd;IACF;GACF;EACF;CACF;AAED,MAAa,aAA2B,CACtC;CACE,MAAM;CACN,aACE;CACF,aAAa;EACX,MAAM;EACN,YAAY,EACV,IAAI;GACF,MAAM;GACN,aAAa;GACd,EACF;EACD,UAAU,CAAC,KAAK;EACjB;CACF,CACF;AAED,MAAa,aAA2B;CACtC;EACE,MAAM;EACN,aACE;EACF,aAAa;GACX,MAAM;GACN,YAAY;IACV,SAAS;KACP,MAAM;KACN,aAAa;KACd;IACD,SAAS;KACP,MAAM;KACN,aAAa;KACd;IACD,YAAY;KACV,MAAM;KACN,aAAa;KACd;IACD,SAAS;KAAE,MAAM;KAAU,aAAa;KAAgC;IACxE,MAAM;KAAE,MAAM;KAAU,aAAa;KAAwB;IAC9D;GACD,UAAU,CAAC,UAAU;GACtB;EACF;CACD;EACE,MAAM;EACN,aACE;EACF,aAAa;GACX,MAAM;GACN,YAAY;IACV,OAAO;KAAE,MAAM;KAAU,aAAa;KAAgB;IACtD,SAAS;KAAE,MAAM;KAAU,aAAa;KAAqB;IAC7D,eAAe;KACb,MAAM;KACN,aAAa;KACd;IACD,OAAO;KAAE,MAAM;KAAU,aAAa;KAA4B;IACnE;GACD,UAAU,CAAC,QAAQ;GACpB;EACF;CACD;EACE,MAAM;EACN,aACE;EACF,aAAa;GACX,MAAM;GACN,YAAY;IACV,UAAU;KACR,MAAM;KACN,aAAa;KACd;IACD,OAAO;KACL,MAAM;KACN,aAAa;KACd;IACF;GACF;EACF;CACF;AAED,MAAa,aAA2B,CACtC;CACE,MAAM;CACN,aACE;CACF,aAAa;EACX,MAAM;EACN,YAAY;GACV,SAAS;IAAE,MAAM;IAAU,aAAa;IAAqB;GAC7D,aAAa;IACX,MAAM;IACN,aAAa;IACd;GACF;EACF;CACF,EACD;CACE,MAAM;CACN,aACE;CACF,aAAa;EACX,MAAM;EACN,YAAY;GACV,SAAS;IAAE,MAAM;IAAU,aAAa;IAAqB;GAC7D,eAAe;IACb,MAAM;IACN,aAAa;IACd;GACD,OAAO;IAAE,MAAM;IAAU,aAAa;IAA4B;GACnE;EACF;CACF,CACF;AAED,MAAa,mBAAiC;CAC5C;EACE,MAAM;EACN,a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AAK,cAAc;GACjB,MAAM,WAAW,OAAO;GACxB,MAAM,WAAY,OAAO,aAAyC,EAAE;AACpE,OAAI;AACF,WAAO,MAAM,eAAe,UAAU,SAAS;YACxC,KAAK;AACZ,WAAO;KACL,SAAS,CACP;MACE,MAAM;MACN,MAAM,UAAU,eAAe,QAAQ,IAAI,UAAU,OAAO,IAAI;MACjE,CACF;KACD,SAAS;KACV;;;EAIL,QACE,OAAM,IAAI,MAAM,mBAAmB,SAAS;;EAEhD;AAEF,QAAQ,OAAO,MACb,6CAA6C,YAAY,QAAQ,gBAClE;AACD,UAAU,OAAO;AAEjB,QAAQ,GAAG,gBAAgB;AACzB,IAAG,SAAS;AACZ,SAAQ,KAAK,EAAE;EACf;AACF,QAAQ,GAAG,iBAAiB;AAC1B,IAAG,SAAS;AACZ,SAAQ,KAAK,EAAE;EACf"}
@@ -438,6 +438,39 @@ const CORE_TOOLS = [
438
438
  },
439
439
  required: ["memoryId"]
440
440
  }
441
+ },
442
+ {
443
+ name: "memory_commit_lookup",
444
+ description: "Look up the agent session(s) that produced a specific git commit, given its SHA. Returns the commit metadata and linked sessions.",
445
+ inputSchema: {
446
+ type: "object",
447
+ properties: { sha: {
448
+ type: "string",
449
+ description: "Full git commit SHA"
450
+ } },
451
+ required: ["sha"]
452
+ }
453
+ },
454
+ {
455
+ name: "memory_commits",
456
+ description: "List recent commits linked to agent sessions, optionally filtered by branch or repo.",
457
+ inputSchema: {
458
+ type: "object",
459
+ properties: {
460
+ branch: {
461
+ type: "string",
462
+ description: "Filter by branch name"
463
+ },
464
+ repo: {
465
+ type: "string",
466
+ description: "Filter by remote URL"
467
+ },
468
+ limit: {
469
+ type: "number",
470
+ description: "Max results (default 100, max 500)"
471
+ }
472
+ }
473
+ }
441
474
  }
442
475
  ];
443
476
  const V040_TOOLS = [
@@ -1285,4 +1318,4 @@ function getVisibleTools() {
1285
1318
 
1286
1319
  //#endregion
1287
1320
  export { loadTeamConfig as _, getConsolidationDecayDays as a, isAutoCompressEnabled as c, isGraphExtractionEnabled as d, loadClaudeBridgeConfig as f, loadSnapshotConfig as g, loadFallbackConfig as h, detectLlmProviderKind as i, isConsolidationEnabled as l, loadEmbeddingConfig as m, getVisibleTools as n, getEnvVar as o, loadConfig as p, detectEmbeddingProvider as r, getStandalonePersistPath as s, getAllTools as t, isContextInjectionEnabled as u };
1288
- //# sourceMappingURL=tools-registry-BFKFKmYh.mjs.map
1321
+ //# sourceMappingURL=tools-registry-Dz8ssuMf.mjs.map