@tangle-network/agent-runtime 0.104.0 → 0.105.0
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.
- package/README.md +176 -42
- package/dist/agent.js +4 -4
- package/dist/candidate-execution/index.d.ts +2 -2
- package/dist/candidate-execution/index.js +4 -4
- package/dist/{chunk-2QJSNOGK.js → chunk-C5RTIBNZ.js} +2 -2
- package/dist/{chunk-SNSMRT6H.js → chunk-CTRA64LY.js} +3 -3
- package/dist/{chunk-ZXICDSAK.js → chunk-H5QPIZNX.js} +2 -2
- package/dist/{chunk-2X65HYMI.js → chunk-HLKC4UYB.js} +1 -13
- package/dist/chunk-HLKC4UYB.js.map +1 -0
- package/dist/{chunk-3PPVCS75.js → chunk-HNP72PNU.js} +3 -10
- package/dist/chunk-HNP72PNU.js.map +1 -0
- package/dist/chunk-OPVWXJ2H.js +75 -0
- package/dist/chunk-OPVWXJ2H.js.map +1 -0
- package/dist/{chunk-B7K7V22Y.js → chunk-RDOAVVHY.js} +2 -2
- package/dist/{chunk-L5DST3QC.js → chunk-SMQXZGLZ.js} +1 -1
- package/dist/chunk-SMQXZGLZ.js.map +1 -0
- package/dist/{chunk-FJI3EXU3.js → chunk-UHEZW5BU.js} +1104 -588
- package/dist/chunk-UHEZW5BU.js.map +1 -0
- package/dist/{chunk-HAO4CXHP.js → chunk-VISA6CI3.js} +3 -3
- package/dist/{chunk-2UABGGUB.js → chunk-WMTCUOQL.js} +5 -5
- package/dist/{chunk-ATDFUJYI.js → chunk-WRTOVNN4.js} +4 -4
- package/dist/{chunk-ATDFUJYI.js.map → chunk-WRTOVNN4.js.map} +1 -1
- package/dist/{chunk-SBTWKPVR.js → chunk-WSTRQZYQ.js} +1 -1
- package/dist/chunk-WSTRQZYQ.js.map +1 -0
- package/dist/{chunk-5HNDYWUT.js → chunk-XBG2W2VW.js} +13 -3
- package/dist/chunk-XBG2W2VW.js.map +1 -0
- package/dist/{chunk-STJEHM5F.js → chunk-YJZA2BIK.js} +2 -2
- package/dist/{chunk-STJEHM5F.js.map → chunk-YJZA2BIK.js.map} +1 -1
- package/dist/{completion-gate-Bv47cOnn.d.ts → completion-gate-BMy5LGoP.d.ts} +1 -1
- package/dist/{coordination-CxtzMxSM.d.ts → coordination-BZZSVYpZ.d.ts} +2 -2
- package/dist/index.d.ts +101 -177
- package/dist/index.js +373 -235
- package/dist/index.js.map +1 -1
- package/dist/intelligence.d.ts +49 -40
- package/dist/intelligence.js +14 -57
- package/dist/intelligence.js.map +1 -1
- package/dist/knowledge.d.ts +4 -4
- package/dist/knowledge.js +8 -8
- package/dist/{local-harness-CtK9dSny.d.ts → local-harness-BDNcl6jI.d.ts} +1 -1
- package/dist/{loop-runner-bin-DUOGtvOl.d.ts → loop-runner-bin-68aoM9-7.d.ts} +3 -11
- package/dist/loop-runner-bin.d.ts +4 -6
- package/dist/loop-runner-bin.js +5 -5
- package/dist/loops.d.ts +11 -11
- package/dist/loops.js +5 -5
- package/dist/mcp/bin.js +2 -2
- package/dist/mcp/index.d.ts +7 -8
- package/dist/mcp/index.js +6 -6
- package/dist/mcp/memory-bin.js +1 -1
- package/dist/primeintellect/index.d.ts +2 -3
- package/dist/primeintellect/index.js +5 -6
- package/dist/primeintellect/index.js.map +1 -1
- package/dist/{protected-model-port-DzkUY3HQ.d.ts → protected-model-port-B4t-OQjL.d.ts} +1 -1
- package/dist/{improve--2A0gK1-.d.ts → redact-BuFjxBUJ.d.ts} +201 -160
- package/dist/{structural-rollout-C4mabf87.d.ts → structural-rollout-DEh6CEsa.d.ts} +2 -2
- package/dist/{supervise-7q9F5brx.d.ts → supervise-4_48wwvy.d.ts} +2 -2
- package/dist/testing.js +9 -9
- package/dist/testing.js.map +1 -1
- package/dist/{worktree-fanout-WsOzt8qu.d.ts → worktree-fanout-DxhAWr5Z.d.ts} +2 -2
- package/package.json +6 -5
- package/skills/build-with-agent-runtime/SKILL.md +15 -9
- package/skills/loop-writer/SKILL.md +1 -1
- package/dist/chunk-2X65HYMI.js.map +0 -1
- package/dist/chunk-3PPVCS75.js.map +0 -1
- package/dist/chunk-5HNDYWUT.js.map +0 -1
- package/dist/chunk-FJI3EXU3.js.map +0 -1
- package/dist/chunk-L5DST3QC.js.map +0 -1
- package/dist/chunk-SBTWKPVR.js.map +0 -1
- /package/dist/{chunk-2QJSNOGK.js.map → chunk-C5RTIBNZ.js.map} +0 -0
- /package/dist/{chunk-SNSMRT6H.js.map → chunk-CTRA64LY.js.map} +0 -0
- /package/dist/{chunk-ZXICDSAK.js.map → chunk-H5QPIZNX.js.map} +0 -0
- /package/dist/{chunk-B7K7V22Y.js.map → chunk-RDOAVVHY.js.map} +0 -0
- /package/dist/{chunk-HAO4CXHP.js.map → chunk-VISA6CI3.js.map} +0 -0
- /package/dist/{chunk-2UABGGUB.js.map → chunk-WMTCUOQL.js.map} +0 -0
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/mcp/tool-server.ts","../src/mcp/memory-server.ts"],"sourcesContent":["/**\n * `createStdioToolServer` — the generic newline-delimited JSON-RPC 2.0 MCP\n * server core: `initialize` / `notifications/initialized` / `tools/list` /\n * `tools/call` over a stdio-shaped transport, protocol 2024-11-05.\n *\n * Extracted from `createMcpServer` (server.ts) so every in-repo MCP server —\n * the delegation server, the memory server — serves the ONE wire protocol the\n * same-host client (`connectStdioMcp`, runtime/stdio-mcp-client.ts) speaks.\n * A second hand-rolled serve loop could drift from what the client expects;\n * this core makes that impossible by construction.\n *\n * @experimental\n */\n\nimport { createInterface, type Interface as ReadlineInterface } from 'node:readline'\nimport { ValidationError } from '../errors'\n\nconst PROTOCOL_VERSION = '2024-11-05'\n\n/** @experimental */\nexport interface McpToolDescriptor {\n name: string\n description: string\n inputSchema: Record<string, unknown>\n handler: (raw: unknown) => Promise<unknown>\n}\n\n/** @experimental */\nexport interface McpTransport {\n input: NodeJS.ReadableStream\n output: NodeJS.WritableStream\n}\n\n/** @experimental */\nexport interface JsonRpcMessage {\n jsonrpc: '2.0'\n id?: number | string | null\n method: string\n params?: unknown\n}\n\n/** @experimental */\nexport interface JsonRpcResponse {\n jsonrpc: '2.0'\n id: number | string | null\n result?: unknown\n error?: { code: number; message: string; data?: unknown }\n}\n\n/** @experimental */\nexport interface StdioToolServerOptions {\n /** Server display name surfaced via `initialize`. */\n serverName: string\n /** Server version surfaced via `initialize`. */\n serverVersion: string\n /** The tools to serve. Duplicate names throw — a silent shadow would hide a tool. */\n tools: readonly McpToolDescriptor[]\n}\n\n/** @experimental */\nexport interface StdioToolServer {\n /** Tools currently registered, keyed by name. */\n readonly tools: ReadonlyMap<string, McpToolDescriptor>\n /** Handle a single parsed JSON-RPC message. Returns the response object (or `null` for notifications). */\n handle(message: JsonRpcMessage): Promise<JsonRpcResponse | null>\n /** Drive the server on a stdio-shaped transport until `stop()` is called. */\n serve(transport?: McpTransport): Promise<void>\n /** Stop a `serve` call. Subsequent requests are rejected. */\n stop(): void\n}\n\n/** Build the generic stdio JSON-RPC tool server. */\nexport function createStdioToolServer(options: StdioToolServerOptions): StdioToolServer {\n const tools = new Map<string, McpToolDescriptor>()\n for (const tool of options.tools) {\n if (tools.has(tool.name)) {\n throw new ValidationError(`createStdioToolServer: duplicate tool name \"${tool.name}\"`)\n }\n tools.set(tool.name, tool)\n }\n\n let stopped = false\n let activeReadline: ReadlineInterface | undefined\n\n async function handle(message: JsonRpcMessage): Promise<JsonRpcResponse | null> {\n if (stopped) {\n return rpcError(message.id ?? null, -32099, 'server stopped')\n }\n if (message.method === 'initialize') {\n return rpcResult(message.id ?? null, {\n protocolVersion: PROTOCOL_VERSION,\n capabilities: { tools: {} },\n serverInfo: { name: options.serverName, version: options.serverVersion },\n })\n }\n if (message.method === 'notifications/initialized') {\n // MCP clients send this after the handshake; it has no id and expects\n // no response.\n return null\n }\n if (message.method === 'tools/list') {\n return rpcResult(message.id ?? null, {\n tools: [...tools.values()].map((tool) => ({\n name: tool.name,\n description: tool.description,\n inputSchema: tool.inputSchema,\n })),\n })\n }\n if (message.method === 'tools/call') {\n const params = (message.params ?? {}) as { name?: unknown; arguments?: unknown }\n const name = typeof params.name === 'string' ? params.name : ''\n const tool = tools.get(name)\n if (!tool) {\n return rpcError(message.id ?? null, -32601, `unknown tool: ${name}`)\n }\n try {\n const output = await tool.handler(params.arguments ?? {})\n return rpcResult(message.id ?? null, {\n content: [{ type: 'text', text: JSON.stringify(output) }],\n structuredContent: output,\n isError: false,\n })\n } catch (err) {\n const reason = err instanceof Error ? err.message : String(err)\n const code = err instanceof TypeError || err instanceof RangeError ? -32602 : -32000\n return rpcError(message.id ?? null, code, reason)\n }\n }\n if (message.id === undefined || message.id === null) return null\n return rpcError(message.id, -32601, `unknown method: ${message.method}`)\n }\n\n async function serve(transport?: McpTransport): Promise<void> {\n const input = transport?.input ?? process.stdin\n const output = transport?.output ?? process.stdout\n const rl = createInterface({ input, crlfDelay: Number.POSITIVE_INFINITY })\n activeReadline = rl\n return new Promise<void>((resolve, reject) => {\n rl.on('line', (line) => {\n const trimmed = line.trim()\n if (!trimmed) return\n let parsed: JsonRpcMessage | undefined\n try {\n parsed = JSON.parse(trimmed) as JsonRpcMessage\n } catch (err) {\n writeResponse(output, rpcError(null, -32700, `parse error: ${(err as Error).message}`))\n return\n }\n if (!parsed || parsed.jsonrpc !== '2.0' || typeof parsed.method !== 'string') {\n writeResponse(output, rpcError(parsed?.id ?? null, -32600, 'invalid request'))\n return\n }\n void handle(parsed).then((response) => {\n if (response) writeResponse(output, response)\n })\n })\n rl.on('close', () => resolve())\n rl.on('error', (err) => reject(err))\n if (stopped) {\n rl.close()\n resolve()\n }\n })\n }\n\n function stop(): void {\n stopped = true\n activeReadline?.close()\n activeReadline = undefined\n }\n\n return { tools, handle, serve, stop }\n}\n\nfunction rpcResult(id: number | string | null, result: unknown): JsonRpcResponse {\n return { jsonrpc: '2.0', id, result }\n}\n\nfunction rpcError(\n id: number | string | null,\n code: number,\n message: string,\n data?: unknown,\n): JsonRpcResponse {\n return {\n jsonrpc: '2.0',\n id,\n error: data === undefined ? { code, message } : { code, message, data },\n }\n}\n\nfunction writeResponse(output: NodeJS.WritableStream, response: JsonRpcResponse): void {\n output.write(`${JSON.stringify(response)}\\n`)\n}\n","/**\n * Memory MCP server — the LIVE serving half of the `memory` profile surface\n * (Phase 5). A curated memory (lessons distilled from prior runs) is only\n * real if the DRIVEN agent can query it mid-task; this module serves a flat\n * store of `MemoryItem` rows as `memory_search` / `memory_get` tools over the\n * ONE in-repo stdio JSON-RPC core (`createStdioToolServer`), so the exact\n * wire protocol the same-host client (`connectStdioMcp` /\n * `materializeLocalMcp`, runtime/stdio-mcp-client.ts) speaks is guaranteed by\n * construction — serve and consume cannot drift.\n *\n * Retrieval is DETERMINISTIC lexical overlap (no vectors, no LLM): a lift\n * measured with this memory mounted is attributable to the lessons\n * themselves, never to retrieval-model noise — the same discipline as\n * agent-eval's `memoryCurationProposer` (deterministic curation). Every\n * `memory_search` can append one JSONL row to a retrieval log (`logPath`) —\n * the per-query record an off-policy retrieval estimator (agent-knowledge's\n * `RetrievalHoldout`) consumes. agent-knowledge is NOT a dependency of this\n * repo, so the log file is the flagged cross-package seam, not an import.\n *\n * Fail-loud discipline (mirrors `materializeLocalMcp`): an EMPTY memory is\n * never served — a profile without memory simply omits the artifact, and\n * silently serving zero rows would fake the with/without ablation.\n *\n * @experimental\n */\n\nimport { appendFileSync, mkdirSync, readFileSync } from 'node:fs'\nimport { dirname } from 'node:path'\nimport type { AgentProfileMcpServer } from '@tangle-network/agent-interface'\nimport { ValidationError } from '../errors'\nimport { createStdioToolServer, type McpToolDescriptor, type StdioToolServer } from './tool-server'\n\n/** One row of agent memory: a crisp lesson/fact with provenance. */\nexport interface MemoryItem {\n /** Stable id (content-hash by convention; see `memoryArtifactFromLessons`). */\n id: string\n /** The lesson itself — one imperative or observation the agent should recall. */\n text: string\n /** Optional retrieval tags, matched by `memory_search` alongside the text. */\n tags?: string[]\n /** Provenance: the finding / trace / curation pass this row came from. */\n source?: string\n}\n\n/**\n * The `memory` artifact payload — HOW a profile's memory is stored and served:\n *\n * - `store: 'file'` — served by the in-repo memory bin\n * (`agent-runtime-memory-mcp`, src/mcp/memory-bin.ts): rows load from\n * `path` (a JSON array or JSONL file of `MemoryItem`) and/or the inline\n * `items` seed (inline wins on id collision). At least one of\n * `path`/`items` is required.\n * - `store: 'mcp'` — an EXTERNAL, already-runnable MCP server that exposes\n * the memory tools itself; `server` is required and mounts verbatim.\n *\n * `logPath` makes the served memory append one JSONL row per `memory_search`\n * — the retrieval log a holdout estimator reads (see module doc).\n */\nexport interface AgentMemorySpec {\n store: 'file' | 'mcp'\n /** `store:'file'` — host path to the durable row store (JSON array or JSONL). */\n path?: string\n /** Inline seed rows, served alongside (and winning over) `path` rows. */\n items?: MemoryItem[]\n /** `store:'mcp'` — the external server that already serves memory tools. */\n server?: AgentProfileMcpServer\n /** JSONL retrieval log: one row per `memory_search` (ts, query, k, returned). */\n logPath?: string\n}\n\n/** Env var naming the durable row store file the memory bin loads (the\n * `memoryMcpServer` ↔ memory-bin contract). */\nexport const MEMORY_FILE_ENV = 'AGENT_MEMORY_FILE'\n/** Env var carrying inline JSON `MemoryItem` rows (win over file rows on id). */\nexport const MEMORY_ITEMS_ENV = 'AGENT_MEMORY_ITEMS'\n/** Env var naming the JSONL retrieval log (one row per `memory_search`). */\nexport const MEMORY_LOG_ENV = 'AGENT_MEMORY_LOG'\n/** Env var overriding the served display name (default 'agent-memory'). */\nexport const MEMORY_NAME_ENV = 'AGENT_MEMORY_NAME'\n\nexport interface CreateMemoryToolServerOptions {\n /** The rows to serve. MUST be non-empty (an empty memory is never served). */\n items: readonly MemoryItem[]\n /** Server display name surfaced via `initialize`. Default 'agent-memory'. */\n serverName?: string\n /** Server version surfaced via `initialize`. Default '0'. */\n serverVersion?: string\n /** Default result count for `memory_search`. Default 5. */\n defaultK?: number\n /** Append one JSONL row per `memory_search` (the retrieval-holdout seam). */\n logPath?: string\n}\n\n/**\n * Build the memory MCP server: `memory_search` (lexical top-k over the rows)\n * and `memory_get` (one row by id) on the generic stdio JSON-RPC core.\n */\nexport function createMemoryToolServer(opts: CreateMemoryToolServerOptions): StdioToolServer {\n if (opts.items.length === 0) {\n throw new ValidationError(\n 'createMemoryToolServer: refusing to serve an EMPTY memory — a profile without memory omits the artifact; serving zero rows would fake the with/without ablation',\n )\n }\n const byId = new Map<string, MemoryItem>()\n for (const item of opts.items) {\n if (byId.has(item.id)) {\n throw new ValidationError(`createMemoryToolServer: duplicate memory item id '${item.id}'`)\n }\n byId.set(item.id, item)\n }\n const items = [...byId.values()]\n const defaultK = opts.defaultK ?? 5\n const logPath = opts.logPath\n if (logPath) mkdirSync(dirname(logPath), { recursive: true })\n\n const search: McpToolDescriptor = {\n name: 'memory_search',\n description:\n 'Search the agent memory of lessons learned from prior runs. Give what you are about to do or the problem you face; returns the top-k lessons ranked by relevance. Consult it BEFORE repeating work a prior run already learned from.',\n inputSchema: {\n type: 'object',\n properties: {\n query: {\n type: 'string',\n description: 'The task/problem at hand — matched against lesson text and tags.',\n },\n k: { type: 'number', description: `Max results (default ${defaultK}).` },\n tags: {\n type: 'array',\n items: { type: 'string' },\n description: 'Only return items carrying at least one of these tags.',\n },\n },\n required: ['query'],\n },\n handler: async (raw) => {\n const args = (raw ?? {}) as { query?: unknown; k?: unknown; tags?: unknown }\n if (typeof args.query !== 'string' || args.query.trim().length === 0) {\n throw new TypeError('memory_search: query must be a non-empty string')\n }\n const k = args.k === undefined ? defaultK : Math.floor(Number(args.k))\n if (!Number.isFinite(k) || k < 1) {\n throw new TypeError('memory_search: k must be a positive integer')\n }\n let tagFilter: string[] | undefined\n if (args.tags !== undefined) {\n if (!Array.isArray(args.tags) || args.tags.some((t) => typeof t !== 'string')) {\n throw new TypeError('memory_search: tags must be an array of strings')\n }\n tagFilter = args.tags as string[]\n }\n const queryTokens = tokenize(args.query)\n const pool = tagFilter\n ? items.filter((i) => (i.tags ?? []).some((t) => tagFilter.includes(t)))\n : items\n const results = pool\n .map((item) => ({ item, score: scoreItem(queryTokens, item) }))\n .filter((r) => r.score > 0)\n // Highest score first; stable on ties (curation order is the tiebreak).\n .sort((a, b) => b.score - a.score)\n .slice(0, k)\n .map(({ item, score }) => ({\n id: item.id,\n text: item.text,\n score: Number(score.toFixed(4)),\n ...(item.tags ? { tags: item.tags } : {}),\n ...(item.source ? { source: item.source } : {}),\n }))\n if (logPath) {\n // The retrieval log: what was asked, what came back, at what rank —\n // exactly the per-query record an off-policy estimator needs.\n appendFileSync(\n logPath,\n `${JSON.stringify({\n ts: new Date().toISOString(),\n query: args.query,\n k,\n returned: results.map((r) => ({ id: r.id, score: r.score })),\n })}\\n`,\n )\n }\n return { query: args.query, results }\n },\n }\n\n const get: McpToolDescriptor = {\n name: 'memory_get',\n description: 'Fetch one memory item verbatim by its id (ids come from memory_search results).',\n inputSchema: {\n type: 'object',\n properties: { id: { type: 'string', description: 'The memory item id.' } },\n required: ['id'],\n },\n handler: async (raw) => {\n const args = (raw ?? {}) as { id?: unknown }\n if (typeof args.id !== 'string' || args.id.trim().length === 0) {\n throw new TypeError('memory_get: id must be a non-empty string')\n }\n const item = byId.get(args.id)\n if (!item) throw new Error(`memory_get: no memory item with id '${args.id}'`)\n return item\n },\n }\n\n return createStdioToolServer({\n serverName: opts.serverName ?? 'agent-memory',\n serverVersion: opts.serverVersion ?? '0',\n tools: [search, get],\n })\n}\n\n/** Coerce an untrusted JSON array into validated `MemoryItem` rows. */\nexport function parseMemoryItems(value: unknown, source: string): MemoryItem[] {\n if (!Array.isArray(value)) {\n throw new ValidationError(`${source}: expected a JSON array of memory items`)\n }\n return value.map((row, i) => coerceMemoryItem(row, `${source}[${i}]`))\n}\n\n/** Read a memory store file: a JSON array, or JSONL (one `MemoryItem` per line). */\nexport function readMemoryItemsFile(path: string): MemoryItem[] {\n let raw: string\n try {\n raw = readFileSync(path, 'utf8')\n } catch (err) {\n throw new ValidationError(\n `readMemoryItemsFile: cannot read '${path}': ${err instanceof Error ? err.message : String(err)}`,\n )\n }\n const trimmed = raw.trim()\n if (trimmed.length === 0) return []\n if (trimmed.startsWith('[')) {\n let parsed: unknown\n try {\n parsed = JSON.parse(trimmed)\n } catch (err) {\n throw new ValidationError(\n `readMemoryItemsFile: '${path}' is not valid JSON: ${(err as Error).message}`,\n )\n }\n return parseMemoryItems(parsed, path)\n }\n return trimmed\n .split('\\n')\n .map((line) => line.trim())\n .filter((line) => line.length > 0)\n .map((line, i) => {\n let parsed: unknown\n try {\n parsed = JSON.parse(line)\n } catch (err) {\n throw new ValidationError(\n `readMemoryItemsFile: '${path}' line ${i + 1} is not valid JSON: ${(err as Error).message}`,\n )\n }\n return coerceMemoryItem(parsed, `${path}:${i + 1}`)\n })\n}\n\n/** What the memory bin resolved from its environment. */\nexport interface ResolvedMemoryEnv {\n items: MemoryItem[]\n serverName?: string\n logPath?: string\n}\n\n/**\n * Resolve the bin's memory from `AGENT_MEMORY_FILE` (durable store) and/or\n * `AGENT_MEMORY_ITEMS` (inline JSON rows; wins on id collision). Zero rows is\n * a boot FAILURE, matching the fail-closed materialization discipline.\n */\nexport function resolveMemoryFromEnv(env: Record<string, string | undefined>): ResolvedMemoryEnv {\n const filePath = env[MEMORY_FILE_ENV]\n const inlineRaw = env[MEMORY_ITEMS_ENV]\n const fromFile = filePath ? readMemoryItemsFile(filePath) : []\n let inline: MemoryItem[] = []\n if (inlineRaw) {\n let parsed: unknown\n try {\n parsed = JSON.parse(inlineRaw)\n } catch (err) {\n throw new ValidationError(\n `${MEMORY_ITEMS_ENV} is not valid JSON: ${err instanceof Error ? err.message : String(err)}`,\n )\n }\n inline = parseMemoryItems(parsed, MEMORY_ITEMS_ENV)\n }\n const byId = new Map<string, MemoryItem>()\n for (const item of fromFile) byId.set(item.id, item)\n for (const item of inline) byId.set(item.id, item)\n if (byId.size === 0) {\n throw new ValidationError(\n `memory bin: no memory items — set ${MEMORY_FILE_ENV} and/or ${MEMORY_ITEMS_ENV}; an EMPTY memory must never be served (a profile without memory omits the artifact)`,\n )\n }\n const serverName = env[MEMORY_NAME_ENV]\n const logPath = env[MEMORY_LOG_ENV]\n return {\n items: [...byId.values()],\n ...(serverName ? { serverName } : {}),\n ...(logPath ? { logPath } : {}),\n }\n}\n\nfunction coerceMemoryItem(row: unknown, at: string): MemoryItem {\n if (!row || typeof row !== 'object' || Array.isArray(row)) {\n throw new ValidationError(`${at}: memory item must be an object`)\n }\n const r = row as Record<string, unknown>\n if (typeof r.id !== 'string' || r.id.trim().length === 0) {\n throw new ValidationError(`${at}: 'id' must be a non-empty string`)\n }\n if (typeof r.text !== 'string' || r.text.trim().length === 0) {\n throw new ValidationError(`${at}: 'text' must be a non-empty string`)\n }\n let tags: string[] | undefined\n if (r.tags !== undefined) {\n if (!Array.isArray(r.tags) || r.tags.some((t) => typeof t !== 'string')) {\n throw new ValidationError(`${at}: 'tags' must be an array of strings`)\n }\n tags = r.tags as string[]\n }\n if (r.source !== undefined && typeof r.source !== 'string') {\n throw new ValidationError(`${at}: 'source' must be a string`)\n }\n return {\n id: r.id,\n text: r.text,\n ...(tags ? { tags } : {}),\n ...(typeof r.source === 'string' ? { source: r.source } : {}),\n }\n}\n\n/** Unique lowercase alphanumeric tokens of length >= 2. */\nfunction tokenize(text: string): string[] {\n return [\n ...new Set(\n text\n .toLowerCase()\n .split(/[^a-z0-9]+/)\n .filter((t) => t.length >= 2),\n ),\n ]\n}\n\n/** Fraction of query tokens present in the item's text + tags (0..1). */\nfunction scoreItem(queryTokens: readonly string[], item: MemoryItem): number {\n if (queryTokens.length === 0) return 0\n const hay = new Set(tokenize(`${item.text} ${(item.tags ?? []).join(' ')}`))\n let hit = 0\n for (const t of queryTokens) if (hay.has(t)) hit += 1\n return hit / queryTokens.length\n}\n"],"mappings":";;;;;AAcA,SAAS,uBAA4D;AAGrE,IAAM,mBAAmB;AAuDlB,SAAS,sBAAsB,SAAkD;AACtF,QAAM,QAAQ,oBAAI,IAA+B;AACjD,aAAW,QAAQ,QAAQ,OAAO;AAChC,QAAI,MAA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