@tangle-network/agent-runtime 0.133.8 → 0.134.1

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.
Files changed (99) hide show
  1. package/dist/{activation-CbgOt7bK.js → activation-BaxUkhEf.js} +3 -3
  2. package/dist/{activation-CbgOt7bK.js.map → activation-BaxUkhEf.js.map} +1 -1
  3. package/dist/agent.d.ts +1 -1
  4. package/dist/agent.js +2 -2
  5. package/dist/{analyst-loop-C189F6v8.js → analyst-loop-BKWqQhVI.js} +2 -2
  6. package/dist/{analyst-loop-C189F6v8.js.map → analyst-loop-BKWqQhVI.js.map} +1 -1
  7. package/dist/analyst-loop.js +1 -1
  8. package/dist/{authoring-DI2ZcORJ.js → authoring-BlbRLEOS.js} +2 -2
  9. package/dist/{authoring-DI2ZcORJ.js.map → authoring-BlbRLEOS.js.map} +1 -1
  10. package/dist/candidate-execution/index.js +4 -4
  11. package/dist/{candidate-execution-_u2HIWeX.js → candidate-execution-CJRP9CcZ.js} +4 -4
  12. package/dist/{candidate-execution-_u2HIWeX.js.map → candidate-execution-CJRP9CcZ.js.map} +1 -1
  13. package/dist/{conversation-kPowfA_A.js → conversation-CrWcNPQg.js} +4 -4
  14. package/dist/{conversation-kPowfA_A.js.map → conversation-CrWcNPQg.js.map} +1 -1
  15. package/dist/conversation.d.ts +1 -1
  16. package/dist/conversation.js +1 -1
  17. package/dist/{environment-provider-DTJA4ZiM.js → environment-provider-CwvY-Zeq.js} +2 -2
  18. package/dist/{environment-provider-DTJA4ZiM.js.map → environment-provider-CwvY-Zeq.js.map} +1 -1
  19. package/dist/{environment-provider-B-w9VYcF.d.ts → environment-provider-qDOhdE9M.d.ts} +2 -2
  20. package/dist/environment-provider.d.ts +1 -1
  21. package/dist/environment-provider.js +1 -1
  22. package/dist/{errors-DRoXIc7E.js → errors-CVIDr7GQ.js} +9 -1
  23. package/dist/errors-CVIDr7GQ.js.map +1 -0
  24. package/dist/{graph-CnLcp2Tl.js → graph-CKNenH2a.js} +4 -4
  25. package/dist/{graph-CnLcp2Tl.js.map → graph-CKNenH2a.js.map} +1 -1
  26. package/dist/{improvement-cycle-ekj_ODWY.js → improvement-cycle-CSBantKB.js} +9 -9
  27. package/dist/{improvement-cycle-ekj_ODWY.js.map → improvement-cycle-CSBantKB.js.map} +1 -1
  28. package/dist/{index-DqJa9jGF.d.ts → index-CgBJtAzI.d.ts} +2 -2
  29. package/dist/{index-CP8LBWD1.d.ts → index-Cz4qKBxm.d.ts} +4 -4
  30. package/dist/{index-Cgo-tyB8.d.ts → index-De10l_EU.d.ts} +27 -6
  31. package/dist/index.d.ts +7 -7
  32. package/dist/index.js +14 -14
  33. package/dist/intelligence.d.ts +4 -4
  34. package/dist/intelligence.js +6 -6
  35. package/dist/kernel.d.ts +6 -6
  36. package/dist/kernel.js +10 -10
  37. package/dist/{knowledge-BdJoVN9q.js → knowledge-B2C9t1Z4.js} +7 -7
  38. package/dist/{knowledge-BdJoVN9q.js.map → knowledge-B2C9t1Z4.js.map} +1 -1
  39. package/dist/knowledge.d.ts +1 -1
  40. package/dist/knowledge.js +1 -1
  41. package/dist/{loop-runner-bin-C1uQcY_O.js → loop-runner-bin-C0ymKYU7.js} +5 -5
  42. package/dist/{loop-runner-bin-C1uQcY_O.js.map → loop-runner-bin-C0ymKYU7.js.map} +1 -1
  43. package/dist/{loop-runner-bin-BX_266wJ.d.ts → loop-runner-bin-D-tgbSPx.d.ts} +3 -3
  44. package/dist/loop-runner-bin.d.ts +1 -1
  45. package/dist/loop-runner-bin.js +1 -1
  46. package/dist/{materialization-D2bdTfkK.js → materialization-BP5zspr2.js} +25 -10
  47. package/dist/materialization-BP5zspr2.js.map +1 -0
  48. package/dist/mcp/bin.js +4 -4
  49. package/dist/mcp/index.d.ts +3 -3
  50. package/dist/mcp/index.js +9 -9
  51. package/dist/mcp/memory-bin.js +1 -1
  52. package/dist/{memory-server-CblxrUKT.js → memory-server-Cdpy7Uu8.js} +3 -3
  53. package/dist/{memory-server-CblxrUKT.js.map → memory-server-Cdpy7Uu8.js.map} +1 -1
  54. package/dist/{model-policy-Bv1DU2fw.js → model-policy-UTTc9Z-A.js} +2 -2
  55. package/dist/{model-policy-Bv1DU2fw.js.map → model-policy-UTTc9Z-A.js.map} +1 -1
  56. package/dist/{openai-tools-BTznyT19.js → openai-tools-ClOkPIi0.js} +2 -2
  57. package/dist/{openai-tools-BTznyT19.js.map → openai-tools-ClOkPIi0.js.map} +1 -1
  58. package/dist/{prepare-DUbH3GD5.js → prepare-BXEtLOj9.js} +2 -2
  59. package/dist/{prepare-DUbH3GD5.js.map → prepare-BXEtLOj9.js.map} +1 -1
  60. package/dist/primeintellect/index.d.ts +1 -1
  61. package/dist/profiles.js +1 -1
  62. package/dist/{protected-model-port-DP7MS63a.js → protected-model-port-B7PAmTGi.js} +2 -2
  63. package/dist/{protected-model-port-DP7MS63a.js.map → protected-model-port-B7PAmTGi.js.map} +1 -1
  64. package/dist/{redact-BSD-nvTf.d.ts → redact-6UE6pdNi.d.ts} +3 -3
  65. package/dist/{researcher-BiWSFLi6.js → researcher-DBfKdnAz.js} +3 -3
  66. package/dist/{researcher-BiWSFLi6.js.map → researcher-DBfKdnAz.js.map} +1 -1
  67. package/dist/{runtime-Br49sl8u.js → runtime-Bisfbn3_.js} +29 -14
  68. package/dist/runtime-Bisfbn3_.js.map +1 -0
  69. package/dist/{runtime-D-26vxJt.d.ts → runtime-DlxoqEj2.d.ts} +27 -6
  70. package/dist/{snapshot-DY6VGliG.js → snapshot-BOIprwBk.js} +2 -2
  71. package/dist/{snapshot-DY6VGliG.js.map → snapshot-BOIprwBk.js.map} +1 -1
  72. package/dist/{spawn-journal-BX3-4WDm.js → spawn-journal-B856eA8e.js} +27 -11
  73. package/dist/spawn-journal-B856eA8e.js.map +1 -0
  74. package/dist/{stream-agent-turn-NFWCv1X1.d.ts → stream-agent-turn-CJog3ebs.d.ts} +2 -2
  75. package/dist/{stream-agent-turn-D8YHY0oO.js → stream-agent-turn-CdIcf-bn.js} +4 -4
  76. package/dist/{stream-agent-turn-D8YHY0oO.js.map → stream-agent-turn-CdIcf-bn.js.map} +1 -1
  77. package/dist/{structural-rollout-C4_mifPH.js → structural-rollout-DKEP5i__.js} +6 -6
  78. package/dist/{structural-rollout-C4_mifPH.js.map → structural-rollout-DKEP5i__.js.map} +1 -1
  79. package/dist/{supervise-BTwl4Cdi.js → supervise-DhghNvl6.js} +55 -37
  80. package/dist/supervise-DhghNvl6.js.map +1 -0
  81. package/dist/{supervisor-BA87pb7g.js → supervisor-CMlIOkJP.js} +65 -21
  82. package/dist/supervisor-CMlIOkJP.js.map +1 -0
  83. package/dist/testing.d.ts +2 -2
  84. package/dist/testing.js +12 -12
  85. package/dist/{tool-server-VvSK1K3X.js → tool-server-Dh-NcbHr.js} +2 -2
  86. package/dist/{tool-server-VvSK1K3X.js.map → tool-server-Dh-NcbHr.js.map} +1 -1
  87. package/dist/{types-DJ7k6vHE.d.ts → types-D4BfurNs.d.ts} +9 -2
  88. package/dist/{util-Dr--8wAL.js → util-DD8bRWPL.js} +21 -2
  89. package/dist/util-DD8bRWPL.js.map +1 -0
  90. package/dist/{workspace-archive-WEbaLREb.js → workspace-archive-B5oJu5mZ.js} +2 -2
  91. package/dist/{workspace-archive-WEbaLREb.js.map → workspace-archive-B5oJu5mZ.js.map} +1 -1
  92. package/package.json +1 -1
  93. package/dist/errors-DRoXIc7E.js.map +0 -1
  94. package/dist/materialization-D2bdTfkK.js.map +0 -1
  95. package/dist/runtime-Br49sl8u.js.map +0 -1
  96. package/dist/spawn-journal-BX3-4WDm.js.map +0 -1
  97. package/dist/supervise-BTwl4Cdi.js.map +0 -1
  98. package/dist/supervisor-BA87pb7g.js.map +0 -1
  99. package/dist/util-Dr--8wAL.js.map +0 -1
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { a as createMemoryToolServer, c as resolveMemoryFromEnv } from "../memory-server-CblxrUKT.js";
2
+ import { a as createMemoryToolServer, c as resolveMemoryFromEnv } from "../memory-server-Cdpy7Uu8.js";
3
3
  //#region src/mcp/memory-bin.ts
4
4
  /**
5
5
  * `agent-runtime-memory-mcp` — stdio memory MCP server entry point.
@@ -1,5 +1,5 @@
1
- import { f as ValidationError } from "./errors-DRoXIc7E.js";
2
- import { t as createStdioToolServer } from "./tool-server-VvSK1K3X.js";
1
+ import { f as ValidationError } from "./errors-CVIDr7GQ.js";
2
+ import { t as createStdioToolServer } from "./tool-server-Dh-NcbHr.js";
3
3
  import { dirname } from "node:path";
4
4
  import { appendFileSync, mkdirSync, readFileSync } from "node:fs";
5
5
  //#region src/mcp/memory-server.ts
@@ -231,4 +231,4 @@ function scoreItem(queryTokens, item) {
231
231
  //#endregion
232
232
  export { createMemoryToolServer as a, resolveMemoryFromEnv as c, MEMORY_NAME_ENV as i, MEMORY_ITEMS_ENV as n, parseMemoryItems as o, MEMORY_LOG_ENV as r, readMemoryItemsFile as s, MEMORY_FILE_ENV as t };
233
233
 
234
- //# sourceMappingURL=memory-server-CblxrUKT.js.map
234
+ //# sourceMappingURL=memory-server-Cdpy7Uu8.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"memory-server-CblxrUKT.js","names":[],"sources":["../src/mcp/memory-server.ts"],"sourcesContent":["/**\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. 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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuEA,MAAa,kBAAkB;;AAE/B,MAAa,mBAAmB;;AAEhC,MAAa,iBAAiB;;AAE9B,MAAa,kBAAkB;;;;;AAmB/B,SAAgB,uBAAuB,MAAsD;CAC3F,IAAI,KAAK,MAAM,WAAW,GACxB,MAAM,IAAI,gBACR,iKACF;CAEF,MAAM,uBAAO,IAAI,IAAwB;CACzC,KAAK,MAAM,QAAQ,KAAK,OAAO;EAC7B,IAAI,KAAK,IAAI,KAAK,EAAE,GAClB,MAAM,IAAI,gBAAgB,qDAAqD,KAAK,GAAG,EAAE;EAE3F,KAAK,IAAI,KAAK,IAAI,IAAI;CACxB;CACA,MAAM,QAAQ,CAAC,GAAG,KAAK,OAAO,CAAC;CAC/B,MAAM,WAAW,KAAK,YAAY;CAClC,MAAM,UAAU,KAAK;CACrB,IAAI,SAAS,UAAU,QAAQ,OAAO,GAAG,EAAE,WAAW,KAAK,CAAC;CAE5D,MAAM,SAA4B;EAChC,MAAM;EACN,aACE;EACF,aAAa;GACX,MAAM;GACN,YAAY;IACV,OAAO;KACL,MAAM;KACN,aAAa;IACf;IACA,GAAG;KAAE,MAAM;KAAU,aAAa,wBAAwB,SAAS;IAAI;IACvE,MAAM;KACJ,MAAM;KACN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CACnB,QAAQ,MAAM,EAAE,UAAU,CAAC,CAChC,CACF;AACF;;AAGA,SAAS,UAAU,aAAgC,MAA0B;CAC3E,IAAI,YAAY,WAAW,GAAG,OAAO;CACrC,MAAM,MAAM,IAAI,IAAI,SAAS,GAAG,KAAK,KAAK,IAAI,KAAK,QAAQ,CAAC,EAAA,CAAG,KAAK,GAAG,GAAG,CAAC;CAC3E,IAAI,MAAM;CACV,KAAK,MAAM,KAAK,aAAa,IAAI,IAAI,IAAI,CAAC,GAAG,OAAO;CACpD,OAAO,MAAM,YAAY;AAC3B"}
1
+ {"version":3,"file":"memory-server-Cdpy7Uu8.js","names":[],"sources":["../src/mcp/memory-server.ts"],"sourcesContent":["/**\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. 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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuEA,MAAa,kBAAkB;;AAE/B,MAAa,mBAAmB;;AAEhC,MAAa,iBAAiB;;AAE9B,MAAa,kBAAkB;;;;;AAmB/B,SAAgB,uBAAuB,MAAsD;CAC3F,IAAI,KAAK,MAAM,WAAW,GACxB,MAAM,IAAI,gBACR,iKACF;CAEF,MAAM,uBAAO,IAAI,IAAwB;CACzC,KAAK,MAAM,QAAQ,KAAK,OAAO;EAC7B,IAAI,KAAK,IAAI,KAAK,EAAE,GAClB,MAAM,IAAI,gBAAgB,qDAAqD,KAAK,GAAG,EAAE;EAE3F,KAAK,IAAI,KAAK,IAAI,IAAI;CACxB;CACA,MAAM,QAAQ,CAAC,GAAG,KAAK,OAAO,CAAC;CAC/B,MAAM,WAAW,KAAK,YAAY;CAClC,MAAM,UAAU,KAAK;CACrB,IAAI,SAAS,UAAU,QAAQ,OAAO,GAAG,EAAE,WAAW,KAAK,CAAC;CAE5D,MAAM,SAA4B;EAChC,MAAM;EACN,aACE;EACF,aAAa;GACX,MAAM;GACN,YAAY;IACV,OAAO;KACL,MAAM;KACN,aAAa;IACf;IACA,GAAG;KAAE,MAAM;KAAU,aAAa,wBAAwB,SAAS;IAAI;IACvE,MAAM;KACJ,MAAM;KACN,OAAO,EAAE,MAAM,SAAS;KACxB,aAAa;IACf;GACF;GACA,UAAU,CAAC,OAAO;EACpB;EACA,SAAS,OAAO,QAAQ;GACtB,MAAM,OAAQ,OAAO,CAAC;GACtB,IAAI,OAAO,KAAK,UAAU,YAAY,KAAK,MAAM,KAAK,CAAC,CAAC,WAAW,GACjE,MAAM,IAAI,UAAU,iDAAiD;GAEvE,MAAM,IAAI,KAAK,MAAM,KAAA,IAAY,WAAW,KAAK,MAAM,OAAO,KAAK,CAAC,CAAC;GACrE,IAAI,CAA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AAM,YAAY;AAC3B"}
@@ -1,4 +1,4 @@
1
- import { f as ValidationError, i as ConfigError } from "./errors-DRoXIc7E.js";
1
+ import { f as ValidationError, i as ConfigError } from "./errors-CVIDr7GQ.js";
2
2
  import { HARNESS_NATIVE_MODEL } from "@tangle-network/agent-eval";
3
3
  //#region src/runtime/harness-role.ts
4
4
  /**
@@ -230,4 +230,4 @@ function assertProfileModelsAllowed(profile, allowed) {
230
230
  //#endregion
231
231
  export { concreteProfileModel as a, profileProviderModel as c, harnessRunsAgent as d, concreteModelId as i, resolveRouterRetryPolicy as l, assertModelAllowed as n, profileBridgeWireModel as o, assertProfileModelsAllowed as r, profileModelExecutionSettings as s, assertExecutableAgentProfile as t, agentHarness as u };
232
232
 
233
- //# sourceMappingURL=model-policy-Bv1DU2fw.js.map
233
+ //# sourceMappingURL=model-policy-UTTc9Z-A.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"model-policy-Bv1DU2fw.js","names":["positiveInteger"],"sources":["../src/runtime/harness-role.ts","../src/runtime/router-retry-policy.ts","../src/runtime/supervise/model-policy.ts"],"sourcesContent":["/**\n * Which `HarnessType` values name a real coding-agent runtime, and which name a MODE that has no\n * agent behind it.\n *\n * `cli-base` is the router-backed mode — a plain multi-turn router call with no coding-agent\n * harness (`@tangle-network/agent-interface`'s `HarnessType` doc, and the same table's\n * `harnessReasoningCeiling['cli-base'] = 'none'` commented \"cli-base has no agent\"). The\n * distinction is REAL; what was accidental is that three call sites each spelled the test\n * themselves, so a second no-agent mode would have to be remembered in three places.\n *\n * SHOULD UPSTREAM: this belongs next to `harnessHonorsEffort` in agent-interface's\n * `harness-capabilities.ts`, which already encodes the fact but exports no predicate for it.\n * Until it does, this is the one local copy — extend the set here, never re-test the name.\n */\n\nimport type { HarnessType } from '@tangle-network/agent-interface'\n\n/**\n * Harness ids that select a router/no-agent mode rather than a coding-agent runtime.\n *\n * `nanoclaw` is deliberately ABSENT: the shared capability table clamps its reasoning ceiling the\n * same way it clamps `cli-base`, but nanoclaw does run an agent (a socket-bridge runner to the\n * NanoClaw daemon) and every caller here treats it as a full harness. Add a row only with the\n * behavior change stated, never to make the two clamps look symmetric.\n */\nconst NO_AGENT_HARNESSES: ReadonlySet<string> = new Set<string>(['cli-base' satisfies HarnessType])\n\n/** Whether this profile harness selects a real coding-agent runtime (vs. the router/no-agent mode\n * or no preference at all). Accepts the looser `string` some local profile shapes declare, and\n * preserves the caller's own harness type when it is narrower. */\nexport function harnessRunsAgent<T extends string>(harness: T | null | undefined): harness is T {\n return harness != null && !NO_AGENT_HARNESSES.has(harness)\n}\n\n/** The coding-agent harness this profile selects, or `undefined` when it selects none — the shape\n * callers want when a no-agent mode must fall through to the router arm. */\nexport function agentHarness<T extends string>(harness: T | null | undefined): T | undefined {\n return harnessRunsAgent(harness) ? harness : undefined\n}\n","import { ValidationError } from '../errors'\n\n/** Exact retry controls accepted at `AgentProfile.model.metadata.retry`. */\nexport interface RouterRetryPolicy {\n /** Total attempts, including the first request. */\n readonly maxAttempts?: number\n /** Delay before the second attempt. Later delays grow exponentially. */\n readonly initialBackoffMs?: number\n /** Maximum delay between attempts. */\n readonly maxBackoffMs?: number\n /** Symmetric random variation around each delay, from 0 through 1. */\n readonly jitter?: number\n /** HTTP statuses that may be retried. */\n readonly retryStatuses?: ReadonlyArray<number>\n /** Deadline for receiving one attempt's response headers. Zero disables it. */\n readonly requestTimeoutMs?: number\n}\n\nexport interface ResolvedRouterRetryPolicy {\n readonly maxAttempts: number\n readonly initialBackoffMs: number\n readonly maxBackoffMs: number\n readonly jitter: number\n readonly retryStatuses: ReadonlyArray<number>\n readonly requestTimeoutMs: number\n}\n\nconst maximumTimerMs = 2_147_483_647\nconst defaultRetryStatuses = Object.freeze([408, 425, 429, 500, 502, 503, 504, 520, 522, 524])\nconst retryPolicyKeys = new Set([\n 'initialBackoffMs',\n 'jitter',\n 'maxAttempts',\n 'maxBackoffMs',\n 'requestTimeoutMs',\n 'retryStatuses',\n])\n\n/** Parse untrusted profile/config data once and return an immutable complete policy. */\nexport function resolveRouterRetryPolicy(\n input: unknown,\n context: string,\n): ResolvedRouterRetryPolicy {\n if (\n input !== undefined &&\n (typeof input !== 'object' || input === null || Array.isArray(input))\n ) {\n throw new ValidationError(`${context} must be an object`)\n }\n const policy = input === undefined ? {} : Object.fromEntries(Object.entries(input))\n const unknown = Object.keys(policy).filter((key) => !retryPolicyKeys.has(key))\n if (unknown.length > 0) {\n throw new ValidationError(`${context} has unsupported fields: ${unknown.join(', ')}`)\n }\n const maxAttempts = positiveInteger(policy.maxAttempts, 5, `${context}.maxAttempts`)\n const initialBackoffMs = timerInteger(\n policy.initialBackoffMs,\n 1_000,\n `${context}.initialBackoffMs`,\n )\n const maxBackoffMs = timerInteger(policy.maxBackoffMs, 30_000, `${context}.maxBackoffMs`)\n const requestTimeoutMs = timerInteger(policy.requestTimeoutMs, 0, `${context}.requestTimeoutMs`)\n const jitter = policy.jitter ?? 0.25\n if (typeof jitter !== 'number' || !Number.isFinite(jitter) || jitter < 0 || jitter > 1) {\n throw new ValidationError(`${context}.jitter must be a finite number from 0 through 1`)\n }\n const retryStatuses = parseRetryStatuses(policy.retryStatuses, context)\n return Object.freeze({\n maxAttempts,\n initialBackoffMs,\n maxBackoffMs,\n jitter,\n retryStatuses,\n requestTimeoutMs,\n })\n}\n\nfunction parseRetryStatuses(value: unknown, context: string): ReadonlyArray<number> {\n if (value === undefined) return defaultRetryStatuses\n if (!Array.isArray(value)) {\n throw new ValidationError(`${context}.retryStatuses must be an array of HTTP statuses`)\n }\n const statuses: number[] = []\n const seen = new Set<number>()\n for (const status of value) {\n if (!Number.isSafeInteger(status) || status < 100 || status > 599) {\n throw new ValidationError(\n `${context}.retryStatuses must contain integer HTTP statuses from 100 through 599`,\n )\n }\n if (seen.has(status)) {\n throw new ValidationError(`${context}.retryStatuses must not contain duplicates`)\n }\n seen.add(status)\n statuses.push(status)\n }\n return Object.freeze(statuses)\n}\n\nfunction positiveInteger(value: unknown, fallback: number, context: string): number {\n const parsed = value ?? fallback\n if (typeof parsed !== 'number' || !Number.isSafeInteger(parsed) || parsed < 1) {\n throw new ValidationError(`${context} must be a positive safe integer`)\n }\n return parsed\n}\n\nfunction timerInteger(value: unknown, fallback: number, context: string): number {\n const parsed = value ?? fallback\n if (\n typeof parsed !== 'number' ||\n !Number.isSafeInteger(parsed) ||\n parsed < 0 ||\n parsed > maximumTimerMs\n ) {\n throw new ValidationError(\n `${context} must be a nonnegative safe integer no greater than ${maximumTimerMs}`,\n )\n }\n return parsed\n}\n","/**\n * `assertModelAllowed` — a fail-loud guard that restricts a run to a chosen subset of\n * models. The two front doors (`supervise()` / `improve()`) call it once per configured\n * model at resolve time, so a run that names a model outside the allowed set throws before\n * any compute is spent — never silently swapped or silently allowed.\n */\nimport { HARNESS_NATIVE_MODEL } from '@tangle-network/agent-eval'\nimport type { AgentProfile } from '@tangle-network/agent-interface'\nimport { ConfigError } from '../../errors'\nimport { agentHarness } from '../harness-role'\nimport { type ResolvedRouterRetryPolicy, resolveRouterRetryPolicy } from '../router-retry-policy'\n\n/**\n * Return the model id an executor may send to a provider.\n *\n * Eval stamps {@link HARNESS_NATIVE_MODEL} into a profile when model selection is deliberately\n * delegated to the configured runtime. That marker belongs in experiment identity and cost\n * admission; it is not a provider model id.\n */\nexport function concreteModelId(model: string | undefined): string | undefined {\n if (model === undefined) return undefined\n const id = model.trim()\n return id.length > 0 && !isHarnessNativeModel(id) ? id : undefined\n}\n\n/** Whether a model value delegates selection to the chosen execution system. */\nexport function isHarnessNativeModel(model: string | undefined): boolean {\n return model?.trim() === HARNESS_NATIVE_MODEL\n}\n\n/** Return a profile's explicitly selected provider model, if it has one. */\nexport function concreteProfileModel(profile: Pick<AgentProfile, 'model'>): string | undefined {\n return concreteModelId(profile.model?.default)\n}\n\n/** The provider-facing model id declared by a profile. Direct Router execution uses this form:\n * the endpoint already selects the provider, so the model id itself is not harness-prefixed. */\nexport function profileProviderModel(profile: Pick<AgentProfile, 'model'>): string | undefined {\n return concreteProfileModel(profile)\n}\n\n/** The full cli-bridge wire id declared by a profile: harness/provider/model. */\nexport function profileBridgeWireModel(\n profile: Pick<AgentProfile, 'harness' | 'model'>,\n): string | undefined {\n const model = concreteProfileModel(profile)\n const provider = profile.model?.provider\n const harness = agentHarness(profile.harness)\n const modelWithoutHarness =\n model && harness && model.startsWith(`${harness}/`) ? model.slice(harness.length + 1) : model\n const providerModel = modelWithoutHarness\n ? provider && !modelWithoutHarness.startsWith(`${provider}/`)\n ? `${provider}/${modelWithoutHarness}`\n : modelWithoutHarness\n : undefined\n if (!harness) return providerModel\n if (!providerModel) return harness\n return providerModel.startsWith(`${harness}/`) ? providerModel : `${harness}/${providerModel}`\n}\n\n/**\n * Refuse an incomplete execution identity before any backend may fill it from ambient config.\n * `AgentProfile` is the sole behavioral authority: harness, provider, and concrete model all\n * participate in its digest. Eval's runtime-selected marker is a matrix-planning value, never an\n * executable model.\n */\nexport function assertExecutableAgentProfile(profile: AgentProfile, context: string): void {\n if (profile.harness === undefined) {\n throw new ConfigError(`${context}: AgentProfile.harness must be explicit before execution`)\n }\n const declared = profile.model?.default\n const model = concreteModelId(declared)\n if (!model) {\n const reason = isHarnessNativeModel(declared) ? 'runtime-selected' : 'missing'\n throw new ConfigError(\n `${context}: AgentProfile.model.default is ${reason}; execution requires a concrete model`,\n )\n }\n if (!profile.model?.provider?.trim()) {\n throw new ConfigError(\n `${context}: AgentProfile.model.provider must be explicit before execution`,\n )\n }\n}\n\n/** Generation and loop controls that may affect one model execution. */\nexport interface ProfileModelExecutionSettings {\n readonly temperature?: number\n readonly maxTokens?: number\n readonly retry?: ResolvedRouterRetryPolicy\n readonly seed?: number\n readonly toolChoice?: 'auto' | 'required' | 'none'\n readonly extraBody?: Readonly<Record<string, unknown>>\n /** Zero means no turn-count cap; conserved budgets and deadlines still apply. */\n readonly maxTurns?: number\n readonly stream?: boolean\n}\n\nconst PROFILE_MODEL_METADATA_KEYS = new Set([\n 'extraBody',\n 'maxTokens',\n 'maxTurns',\n 'retry',\n 'seed',\n 'stream',\n 'temperature',\n 'toolChoice',\n])\n\n/**\n * Read every Router-affecting control from the exact profile and reject unknown controls.\n * Backends receive endpoint/auth and executable ports only; they cannot silently alter behavior.\n */\nexport function profileModelExecutionSettings(\n profile: Pick<AgentProfile, 'model'>,\n context: string,\n): ProfileModelExecutionSettings {\n const metadata = profile.model?.metadata ?? {}\n const unknown = Object.keys(metadata).filter((key) => !PROFILE_MODEL_METADATA_KEYS.has(key))\n if (unknown.length > 0) {\n throw new ConfigError(\n `${context}: unsupported AgentProfile.model.metadata fields: ${unknown.join(', ')}`,\n )\n }\n const temperature = finiteNumber(metadata.temperature, `${context}: temperature`)\n const maxTokens = positiveInteger(metadata.maxTokens, `${context}: maxTokens`)\n const retryInput = metadata.retry\n const retry =\n retryInput === undefined\n ? undefined\n : resolveRouterRetryPolicy(retryInput, `${context}: AgentProfile.model.metadata.retry`)\n const seed = safeInteger(metadata.seed, `${context}: seed`)\n const maxTurns = nonnegativeInteger(metadata.maxTurns, `${context}: maxTurns`)\n const stream = optionalBoolean(metadata.stream, `${context}: stream`)\n const toolChoice = metadata.toolChoice\n if (\n toolChoice !== undefined &&\n toolChoice !== 'auto' &&\n toolChoice !== 'required' &&\n toolChoice !== 'none'\n ) {\n throw new ConfigError(`${context}: toolChoice must be auto, required, or none`)\n }\n const extraBody = metadata.extraBody\n if (\n extraBody !== undefined &&\n (typeof extraBody !== 'object' || extraBody === null || Array.isArray(extraBody))\n ) {\n throw new ConfigError(`${context}: extraBody must be an object`)\n }\n return {\n ...(temperature !== undefined ? { temperature } : {}),\n ...(maxTokens !== undefined ? { maxTokens } : {}),\n ...(retry !== undefined ? { retry } : {}),\n ...(seed !== undefined ? { seed } : {}),\n ...(toolChoice !== undefined ? { toolChoice } : {}),\n ...(extraBody !== undefined\n ? { extraBody: Object.freeze({ ...(extraBody as Record<string, unknown>) }) }\n : {}),\n ...(maxTurns !== undefined ? { maxTurns } : {}),\n ...(stream !== undefined ? { stream } : {}),\n }\n}\n\nfunction finiteNumber(value: unknown, context: string): number | undefined {\n if (value === undefined) return undefined\n if (typeof value !== 'number' || !Number.isFinite(value)) {\n throw new ConfigError(`${context} must be a finite number`)\n }\n return value\n}\n\nfunction safeInteger(value: unknown, context: string): number | undefined {\n if (value === undefined) return undefined\n if (!Number.isSafeInteger(value)) throw new ConfigError(`${context} must be a safe integer`)\n return value as number\n}\n\nfunction positiveInteger(value: unknown, context: string): number | undefined {\n const parsed = safeInteger(value, context)\n if (parsed !== undefined && parsed < 1) {\n throw new ConfigError(`${context} must be positive`)\n }\n return parsed\n}\n\nfunction nonnegativeInteger(value: unknown, context: string): number | undefined {\n const parsed = safeInteger(value, context)\n if (parsed !== undefined && parsed < 0) {\n throw new ConfigError(`${context} must be nonnegative`)\n }\n return parsed\n}\n\nfunction optionalBoolean(value: unknown, context: string): boolean | undefined {\n if (value === undefined) return undefined\n if (typeof value !== 'boolean') throw new ConfigError(`${context} must be boolean`)\n return value\n}\n\n/**\n * Throw a `ConfigError` when `allowed` is set, `model` is defined, and `model` is not a\n * member of `allowed`. No-op when `allowed` is unset (the unrestricted default) or when\n * `model` is undefined (nothing was configured to check).\n */\nexport function assertModelAllowed(\n model: string | undefined,\n allowed: readonly string[] | undefined,\n): void {\n if (!allowed || model === undefined) return\n if (!allowed.includes(model)) {\n throw new ConfigError(\n `model ${JSON.stringify(model)} is not in the allowed set ${JSON.stringify([...allowed])}`,\n )\n }\n}\n\n/** Check every canonical model-bearing field in a complete profile, including the models a\n * backend may select for cheap work, named subagents, or modes. */\nexport function assertProfileModelsAllowed(\n profile: AgentProfile,\n allowed: readonly string[] | undefined,\n): void {\n assertModelAllowed(profile.model?.default, allowed)\n assertModelAllowed(profile.model?.small, allowed)\n for (const subagent of Object.values(profile.subagents ?? {})) {\n assertModelAllowed(subagent.model, allowed)\n }\n for (const mode of Object.values(profile.modes ?? {})) {\n assertModelAllowed(mode.model, allowed)\n }\n}\n"],"mappings":";;;;;;;;;;;AA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AAK,UAAU,KAAK,EAAE,6BAA6B,KAAK,UAAU,CAAC,GAAG,OAAO,CAAC,GACzF;AAEJ;;;AAIA,SAAgB,2BACd,SACA,SACM;CACN,mBAAmB,QAAQ,OAAO,SAAS,OAAO;CAClD,mBAAmB,QAAQ,OAAO,OAAO,OAAO;CAChD,KAAK,MAAM,YAAY,OAAO,OAAO,QAAQ,aAAa,CAAC,CAAC,GAC1D,mBAAmB,SAAS,OAAO,OAAO;CAE5C,KAAK,MAAM,QAAQ,OAAO,OAAO,QAAQ,SAAS,CAAC,CAAC,GAClD,mBAAmB,KAAK,OAAO,OAAO;AAE1C"}
1
+ {"version":3,"file":"model-policy-UTTc9Z-A.js","names":["positiveInteger"],"sources":["../src/runtime/harness-role.ts","../src/runtime/router-retry-policy.ts","../src/runtime/supervise/model-policy.ts"],"sourcesContent":["/**\n * Which `HarnessType` values name a real coding-agent runtime, and which name a MODE that has no\n * agent behind it.\n *\n * `cli-base` is the router-backed mode — a plain multi-turn router call with no coding-agent\n * harness (`@tangle-network/agent-interface`'s `HarnessType` doc, and the same table's\n * `harnessReasoningCeiling['cli-base'] = 'none'` commented \"cli-base has no agent\"). The\n * distinction is REAL; what was accidental is that three call sites each spelled the test\n * themselves, so a second no-agent mode would have to be remembered in three places.\n *\n * SHOULD UPSTREAM: this belongs next to `harnessHonorsEffort` in agent-interface's\n * `harness-capabilities.ts`, which already encodes the fact but exports no predicate for it.\n * Until it does, this is the one local copy — extend the set here, never re-test the name.\n */\n\nimport type { HarnessType } from '@tangle-network/agent-interface'\n\n/**\n * Harness ids that select a router/no-agent mode rather than a coding-agent runtime.\n *\n * `nanoclaw` is deliberately ABSENT: the shared capability table clamps its reasoning ceiling the\n * same way it clamps `cli-base`, but nanoclaw does run an agent (a socket-bridge runner to the\n * NanoClaw daemon) and every caller here treats it as a full harness. Add a row only with the\n * behavior change stated, never to make the two clamps look symmetric.\n */\nconst NO_AGENT_HARNESSES: ReadonlySet<string> = new Set<string>(['cli-base' satisfies HarnessType])\n\n/** Whether this profile harness selects a real coding-agent runtime (vs. the router/no-agent mode\n * or no preference at all). Accepts the looser `string` some local profile shapes declare, and\n * preserves the caller's own harness type when it is narrower. */\nexport function harnessRunsAgent<T extends string>(harness: T | null | undefined): harness is T {\n return harness != null && !NO_AGENT_HARNESSES.has(harness)\n}\n\n/** The coding-agent harness this profile selects, or `undefined` when it selects none — the shape\n * callers want when a no-agent mode must fall through to the router arm. */\nexport function agentHarness<T extends string>(harness: T | null | undefined): T | undefined {\n return harnessRunsAgent(harness) ? harness : undefined\n}\n","import { ValidationError } from '../errors'\n\n/** Exact retry controls accepted at `AgentProfile.model.metadata.retry`. */\nexport interface RouterRetryPolicy {\n /** Total attempts, including the first request. */\n readonly maxAttempts?: number\n /** Delay before the second attempt. Later delays grow exponentially. */\n readonly initialBackoffMs?: number\n /** Maximum delay between attempts. */\n readonly maxBackoffMs?: number\n /** Symmetric random variation around each delay, from 0 through 1. */\n readonly jitter?: number\n /** HTTP statuses that may be retried. */\n readonly retryStatuses?: ReadonlyArray<number>\n /** Deadline for receiving one attempt's response headers. Zero disables it. */\n readonly requestTimeoutMs?: number\n}\n\nexport interface ResolvedRouterRetryPolicy {\n readonly maxAttempts: number\n readonly initialBackoffMs: number\n readonly maxBackoffMs: number\n readonly jitter: number\n readonly retryStatuses: ReadonlyArray<number>\n readonly requestTimeoutMs: number\n}\n\nconst maximumTimerMs = 2_147_483_647\nconst defaultRetryStatuses = Object.freeze([408, 425, 429, 500, 502, 503, 504, 520, 522, 524])\nconst retryPolicyKeys = new Set([\n 'initialBackoffMs',\n 'jitter',\n 'maxAttempts',\n 'maxBackoffMs',\n 'requestTimeoutMs',\n 'retryStatuses',\n])\n\n/** Parse untrusted profile/config data once and return an immutable complete policy. */\nexport function resolveRouterRetryPolicy(\n input: unknown,\n context: string,\n): ResolvedRouterRetryPolicy {\n if (\n input !== undefined &&\n (typeof input !== 'object' || input === null || Array.isArray(input))\n ) {\n throw new ValidationError(`${context} must be an object`)\n }\n const policy = input === undefined ? {} : Object.fromEntries(Object.entries(input))\n const unknown = Object.keys(policy).filter((key) => !retryPolicyKeys.has(key))\n if (unknown.length > 0) {\n throw new ValidationError(`${context} has unsupported fields: ${unknown.join(', ')}`)\n }\n const maxAttempts = positiveInteger(policy.maxAttempts, 5, `${context}.maxAttempts`)\n const initialBackoffMs = timerInteger(\n policy.initialBackoffMs,\n 1_000,\n `${context}.initialBackoffMs`,\n )\n const maxBackoffMs = timerInteger(policy.maxBackoffMs, 30_000, `${context}.maxBackoffMs`)\n const requestTimeoutMs = timerInteger(policy.requestTimeoutMs, 0, `${context}.requestTimeoutMs`)\n const jitter = policy.jitter ?? 0.25\n if (typeof jitter !== 'number' || !Number.isFinite(jitter) || jitter < 0 || jitter > 1) {\n throw new ValidationError(`${context}.jitter must be a finite number from 0 through 1`)\n }\n const retryStatuses = parseRetryStatuses(policy.retryStatuses, context)\n return Object.freeze({\n maxAttempts,\n initialBackoffMs,\n maxBackoffMs,\n jitter,\n retryStatuses,\n requestTimeoutMs,\n })\n}\n\nfunction parseRetryStatuses(value: unknown, context: string): ReadonlyArray<number> {\n if (value === undefined) return defaultRetryStatuses\n if (!Array.isArray(value)) {\n throw new ValidationError(`${context}.retryStatuses must be an array of HTTP statuses`)\n }\n const statuses: number[] = []\n const seen = new Set<number>()\n for (const status of value) {\n if (!Number.isSafeInteger(status) || status < 100 || status > 599) {\n throw new ValidationError(\n `${context}.retryStatuses must contain integer HTTP statuses from 100 through 599`,\n )\n }\n if (seen.has(status)) {\n throw new ValidationError(`${context}.retryStatuses must not contain duplicates`)\n }\n seen.add(status)\n statuses.push(status)\n }\n return Object.freeze(statuses)\n}\n\nfunction positiveInteger(value: unknown, fallback: number, context: string): number {\n const parsed = value ?? fallback\n if (typeof parsed !== 'number' || !Number.isSafeInteger(parsed) || parsed < 1) {\n throw new ValidationError(`${context} must be a positive safe integer`)\n }\n return parsed\n}\n\nfunction timerInteger(value: unknown, fallback: number, context: string): number {\n const parsed = value ?? fallback\n if (\n typeof parsed !== 'number' ||\n !Number.isSafeInteger(parsed) ||\n parsed < 0 ||\n parsed > maximumTimerMs\n ) {\n throw new ValidationError(\n `${context} must be a nonnegative safe integer no greater than ${maximumTimerMs}`,\n )\n }\n return parsed\n}\n","/**\n * `assertModelAllowed` — a fail-loud guard that restricts a run to a chosen subset of\n * models. The two front doors (`supervise()` / `improve()`) call it once per configured\n * model at resolve time, so a run that names a model outside the allowed set throws before\n * any compute is spent — never silently swapped or silently allowed.\n */\nimport { HARNESS_NATIVE_MODEL } from '@tangle-network/agent-eval'\nimport type { AgentProfile } from '@tangle-network/agent-interface'\nimport { ConfigError } from '../../errors'\nimport { agentHarness } from '../harness-role'\nimport { type ResolvedRouterRetryPolicy, resolveRouterRetryPolicy } from '../router-retry-policy'\n\n/**\n * Return the model id an executor may send to a provider.\n *\n * Eval stamps {@link HARNESS_NATIVE_MODEL} into a profile when model selection is deliberately\n * delegated to the configured runtime. That marker belongs in experiment identity and cost\n * admission; it is not a provider model id.\n */\nexport function concreteModelId(model: string | undefined): string | undefined {\n if (model === undefined) return undefined\n const id = model.trim()\n return id.length > 0 && !isHarnessNativeModel(id) ? id : undefined\n}\n\n/** Whether a model value delegates selection to the chosen execution system. */\nexport function isHarnessNativeModel(model: string | undefined): boolean {\n return model?.trim() === HARNESS_NATIVE_MODEL\n}\n\n/** Return a profile's explicitly selected provider model, if it has one. */\nexport function concreteProfileModel(profile: Pick<AgentProfile, 'model'>): string | undefined {\n return concreteModelId(profile.model?.default)\n}\n\n/** The provider-facing model id declared by a profile. Direct Router execution uses this form:\n * the endpoint already selects the provider, so the model id itself is not harness-prefixed. */\nexport function profileProviderModel(profile: Pick<AgentProfile, 'model'>): string | undefined {\n return concreteProfileModel(profile)\n}\n\n/** The full cli-bridge wire id declared by a profile: harness/provider/model. */\nexport function profileBridgeWireModel(\n profile: Pick<AgentProfile, 'harness' | 'model'>,\n): string | undefined {\n const model = concreteProfileModel(profile)\n const provider = profile.model?.provider\n const harness = agentHarness(profile.harness)\n const modelWithoutHarness =\n model && harness && model.startsWith(`${harness}/`) ? model.slice(harness.length + 1) : model\n const providerModel = modelWithoutHarness\n ? provider && !modelWithoutHarness.startsWith(`${provider}/`)\n ? `${provider}/${modelWithoutHarness}`\n : modelWithoutHarness\n : undefined\n if (!harness) return providerModel\n if (!providerModel) return harness\n return providerModel.startsWith(`${harness}/`) ? providerModel : `${harness}/${providerModel}`\n}\n\n/**\n * Refuse an incomplete execution identity before any backend may fill it from ambient config.\n * `AgentProfile` is the sole behavioral authority: harness, provider, and concrete model all\n * participate in its digest. Eval's runtime-selected marker is a matrix-planning value, never an\n * executable model.\n */\nexport function assertExecutableAgentProfile(profile: AgentProfile, context: string): void {\n if (profile.harness === undefined) {\n throw new ConfigError(`${context}: AgentProfile.harness must be explicit before execution`)\n }\n const declared = profile.model?.default\n const model = concreteModelId(declared)\n if (!model) {\n const reason = isHarnessNativeModel(declared) ? 'runtime-selected' : 'missing'\n throw new ConfigError(\n `${context}: AgentProfile.model.default is ${reason}; execution requires a concrete model`,\n )\n }\n if (!profile.model?.provider?.trim()) {\n throw new ConfigError(\n `${context}: AgentProfile.model.provider must be explicit before execution`,\n )\n }\n}\n\n/** Generation and loop controls that may affect one model execution. */\nexport interface ProfileModelExecutionSettings {\n readonly temperature?: number\n readonly maxTokens?: number\n readonly retry?: ResolvedRouterRetryPolicy\n readonly seed?: number\n readonly toolChoice?: 'auto' | 'required' | 'none'\n readonly extraBody?: Readonly<Record<string, unknown>>\n /** Zero means no turn-count cap; conserved budgets and deadlines still apply. */\n readonly maxTurns?: number\n readonly stream?: boolean\n}\n\nconst PROFILE_MODEL_METADATA_KEYS = new Set([\n 'extraBody',\n 'maxTokens',\n 'maxTurns',\n 'retry',\n 'seed',\n 'stream',\n 'temperature',\n 'toolChoice',\n])\n\n/**\n * Read every Router-affecting control from the exact profile and reject unknown controls.\n * Backends receive endpoint/auth and executable ports only; they cannot silently alter behavior.\n */\nexport function profileModelExecutionSettings(\n profile: Pick<AgentProfile, 'model'>,\n context: string,\n): ProfileModelExecutionSettings {\n const metadata = profile.model?.metadata ?? {}\n const unknown = Object.keys(metadata).filter((key) => !PROFILE_MODEL_METADATA_KEYS.has(key))\n if (unknown.length > 0) {\n throw new ConfigError(\n `${context}: unsupported AgentProfile.model.metadata fields: ${unknown.join(', ')}`,\n )\n }\n const temperature = finiteNumber(metadata.temperature, `${context}: temperature`)\n const maxTokens = positiveInteger(metadata.maxTokens, `${context}: maxTokens`)\n const retryInput = metadata.retry\n const retry =\n retryInput === undefined\n ? undefined\n : resolveRouterRetryPolicy(retryInput, `${context}: AgentProfile.model.metadata.retry`)\n const seed = safeInteger(metadata.seed, `${context}: seed`)\n const maxTurns = nonnegativeInteger(metadata.maxTurns, `${context}: maxTurns`)\n const stream = optionalBoolean(metadata.stream, `${context}: stream`)\n const toolChoice = metadata.toolChoice\n if (\n toolChoice !== undefined &&\n toolChoice !== 'auto' &&\n toolChoice !== 'required' &&\n toolChoice !== 'none'\n ) {\n throw new ConfigError(`${context}: toolChoice must be auto, required, or none`)\n }\n const extraBody = metadata.extraBody\n if (\n extraBody !== undefined &&\n (typeof extraBody !== 'object' || extraBody === null || Array.isArray(extraBody))\n ) {\n throw new ConfigError(`${context}: extraBody must be an object`)\n }\n return {\n ...(temperature !== undefined ? { temperature } : {}),\n ...(maxTokens !== undefined ? { maxTokens } : {}),\n ...(retry !== undefined ? { retry } : {}),\n ...(seed !== undefined ? { seed } : {}),\n ...(toolChoice !== undefined ? { toolChoice } : {}),\n ...(extraBody !== undefined\n ? { extraBody: Object.freeze({ ...(extraBody as Record<string, unknown>) }) }\n : {}),\n ...(maxTurns !== undefined ? { maxTurns } : {}),\n ...(stream !== undefined ? { stream } : {}),\n }\n}\n\nfunction finiteNumber(value: unknown, context: string): number | undefined {\n if (value === undefined) return undefined\n if (typeof value !== 'number' || !Number.isFinite(value)) {\n throw new ConfigError(`${context} must be a finite number`)\n }\n return value\n}\n\nfunction safeInteger(value: unknown, context: string): number | undefined {\n if (value === undefined) return undefined\n if (!Number.isSafeInteger(value)) throw new ConfigError(`${context} must be a safe integer`)\n return value as number\n}\n\nfunction positiveInteger(value: unknown, context: string): number | undefined {\n const parsed = safeInteger(value, context)\n if (parsed !== undefined && parsed < 1) {\n throw new ConfigError(`${context} must be positive`)\n }\n return parsed\n}\n\nfunction nonnegativeInteger(value: unknown, context: string): number | undefined {\n const parsed = safeInteger(value, context)\n if (parsed !== undefined && parsed < 0) {\n throw new ConfigError(`${context} must be nonnegative`)\n }\n return parsed\n}\n\nfunction optionalBoolean(value: unknown, context: string): boolean | undefined {\n if (value === undefined) return undefined\n if (typeof value !== 'boolean') throw new ConfigError(`${context} must be boolean`)\n return value\n}\n\n/**\n * Throw a `ConfigError` when `allowed` is set, `model` is defined, and `model` is not a\n * member of `allowed`. No-op when `allowed` is unset (the unrestricted default) or when\n * `model` is undefined (nothing was configured to check).\n */\nexport function assertModelAllowed(\n model: string | undefined,\n allowed: readonly string[] | undefined,\n): void {\n if (!allowed || model === undefined) return\n if (!allowed.includes(model)) {\n throw new ConfigError(\n `model ${JSON.stringify(model)} is not in the allowed set ${JSON.stringify([...allowed])}`,\n )\n }\n}\n\n/** Check every canonical model-bearing field in a complete profile, including the models a\n * backend may select for cheap work, named subagents, or modes. */\nexport function assertProfileModelsAllowed(\n profile: AgentProfile,\n allowed: readonly string[] | undefined,\n): void {\n assertModelAllowed(profile.model?.default, allowed)\n assertModelAllowed(profile.model?.small, allowed)\n for (const subagent of Object.values(profile.subagents ?? {})) {\n assertModelAllowed(subagent.model, allowed)\n }\n for (const mode of Object.values(profile.modes ?? {})) {\n assertModelAllowed(mode.model, allowed)\n }\n}\n"],"mappings":";;;;;;;;;;;AAyBA,MAAM,qCAA0C,IAAI,IAAY,CAAC,UAAgC,CAAC;;;;AAKlG,SAAgB,iBAAmC,SAA6C;CAC9F,OAAO,WAAW,QAAQ,CAAC,mBAAmB,IAAI,OAAO;AAC3D;;;AAIA,SAAgB,a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mB,QAAQ,OAAO,OAAO,OAAO;CAChD,KAAK,MAAM,YAAY,OAAO,OAAO,QAAQ,aAAa,CAAC,CAAC,GAC1D,mBAAmB,SAAS,OAAO,OAAO;CAE5C,KAAK,MAAM,QAAQ,OAAO,OAAO,QAAQ,SAAS,CAAC,CAAC,GAClD,mBAAmB,KAAK,OAAO,OAAO;AAE1C"}
@@ -1,4 +1,4 @@
1
- import { A as DELEGATION_HISTORY_INPUT_SCHEMA, B as DELEGATE_FEEDBACK_INPUT_SCHEMA, E as DELEGATION_STATUS_TOOL_NAME, T as DELEGATION_STATUS_INPUT_SCHEMA, V as DELEGATE_FEEDBACK_TOOL_NAME, j as DELEGATION_HISTORY_TOOL_NAME, k as DELEGATION_HISTORY_DESCRIPTION, w as DELEGATION_STATUS_DESCRIPTION, z as DELEGATE_FEEDBACK_DESCRIPTION } from "./supervise-BTwl4Cdi.js";
1
+ import { A as DELEGATION_HISTORY_INPUT_SCHEMA, B as DELEGATE_FEEDBACK_INPUT_SCHEMA, E as DELEGATION_STATUS_TOOL_NAME, T as DELEGATION_STATUS_INPUT_SCHEMA, V as DELEGATE_FEEDBACK_TOOL_NAME, j as DELEGATION_HISTORY_TOOL_NAME, k as DELEGATION_HISTORY_DESCRIPTION, w as DELEGATION_STATUS_DESCRIPTION, z as DELEGATE_FEEDBACK_DESCRIPTION } from "./supervise-DhghNvl6.js";
2
2
  //#region src/mcp/openai-tools.ts
3
3
  function buildTool(name, description, parameters) {
4
4
  return {
@@ -41,4 +41,4 @@ function mcpToolsForRuntimeMcpSubset(names) {
41
41
  //#endregion
42
42
  export { mcpToolsForRuntimeMcpSubset as n, mcpToolsForRuntimeMcp as t };
43
43
 
44
- //# sourceMappingURL=openai-tools-BTznyT19.js.map
44
+ //# sourceMappingURL=openai-tools-ClOkPIi0.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"openai-tools-BTznyT19.js","names":[],"sources":["../src/mcp/openai-tools.ts"],"sourcesContent":["/**\n *\n * OpenAI Chat Completions `tools[]` projection of the queue-bound agent-runtime\n * MCP delegation tools.\n *\n * Use when a caller-owned OpenAI-compatible transport needs the model to call\n * `delegate_feedback`, `delegation_status`, and `delegation_history`. Execution\n * is the caller's responsibility (typically the parent sandbox runtime's MCP\n * mount); Runtime's profile-bound model path materializes profile tools through\n * its executor instead.\n *\n * Sandbox-SDK callers do NOT need this helper: the sandbox runtime mounts\n * MCP servers natively and the in-sandbox harness discovers tools via the\n * runtime, not via an OpenAI tools array.\n *\n * Tool name + description + JSON-schema are pulled from the canonical\n * `DELEGATE_*` constants exported by `./tools/*` so the projection cannot\n * drift from the server's own validators.\n *\n * @experimental\n */\n\nimport type { OpenAIChatTool } from '../types'\nimport {\n DELEGATE_FEEDBACK_DESCRIPTION,\n DELEGATE_FEEDBACK_INPUT_SCHEMA,\n DELEGATE_FEEDBACK_TOOL_NAME,\n} from './tools/delegate-feedback'\nimport {\n DELEGATION_HISTORY_DESCRIPTION,\n DELEGATION_HISTORY_INPUT_SCHEMA,\n DELEGATION_HISTORY_TOOL_NAME,\n} from './tools/delegation-history'\nimport {\n DELEGATION_STATUS_DESCRIPTION,\n DELEGATION_STATUS_INPUT_SCHEMA,\n DELEGATION_STATUS_TOOL_NAME,\n} from './tools/delegation-status'\n\nfunction buildTool(\n name: string,\n description: string,\n parameters: Readonly<Record<string, unknown>>,\n): OpenAIChatTool {\n // `parameters` arrives as a deeply-readonly `as const` literal. The\n // OpenAI-compatible transports JSON-serialize the body, so a shallow copy\n // into a plain object is sufficient and shields callers that mutate\n // the returned descriptor from corrupting the source constant.\n return {\n type: 'function',\n function: { name, description, parameters: { ...parameters } },\n }\n}\n\n/**\n *\n * Returns the queue-bound delegation tools projected into OpenAI Chat\n * Completions `tools[]` shape. The order is stable: `delegate_feedback`,\n * `delegation_status`, `delegation_history`.\n *\n * @experimental\n */\nexport function mcpToolsForRuntimeMcp(): OpenAIChatTool[] {\n return [\n buildTool(\n DELEGATE_FEEDBACK_TOOL_NAME,\n DELEGATE_FEEDBACK_DESCRIPTION,\n DELEGATE_FEEDBACK_INPUT_SCHEMA as Readonly<Record<string, unknown>>,\n ),\n buildTool(\n DELEGATION_STATUS_TOOL_NAME,\n DELEGATION_STATUS_DESCRIPTION,\n DELEGATION_STATUS_INPUT_SCHEMA as Readonly<Record<string, unknown>>,\n ),\n buildTool(\n DELEGATION_HISTORY_TOOL_NAME,\n DELEGATION_HISTORY_DESCRIPTION,\n DELEGATION_HISTORY_INPUT_SCHEMA as Readonly<Record<string, unknown>>,\n ),\n ]\n}\n\n/**\n *\n * Subset filter — return only the projected tools whose `function.name`\n * appears in `names`. Useful for curated mounts (e.g. only the queue-bound\n * delegation tools, omitting `delegate_feedback`). Unknown names are\n * silently ignored; pass an empty array to get an empty result.\n *\n * @experimental\n */\nexport function mcpToolsForRuntimeMcpSubset(names: ReadonlyArray<string>): OpenAIChatTool[] {\n const allowed = new Set(names)\n return mcpToolsForRuntimeMcp().filter((tool) => allowed.has(tool.function.name))\n}\n"],"mappings":";;AAuCA,SAAS,UACP,MACA,aACA,YACgB;CAKhB,OAAO;EACL,MAAM;EACN,UAAU;GAAE;GAAM;GAAa,YAAY,EAAE,GAAG,WAAW;EAAE;CAC/D;AACF;;;;;;;;;AAUA,SAAgB,wBAA0C;CACxD,OAAO;EACL,UACE,6BACA,+BACA,8BACF;EACA,UACE,6BACA,+BACA,8BACF;EACA,UACE,8BACA,gCACA,+BACF;CACF;AACF;;;;;;;;;;AAWA,SAAgB,4BAA4B,OAAgD;CAC1F,MAAM,UAAU,IAAI,IAAI,KAAK;CAC7B,OAAO,sBAAsB,CAAC,CAAC,QAAQ,SAAS,QAAQ,IAAI,KAAK,SAAS,IAAI,CAAC;AACjF"}
1
+ {"version":3,"file":"openai-tools-ClOkPIi0.js","names":[],"sources":["../src/mcp/openai-tools.ts"],"sourcesContent":["/**\n *\n * OpenAI Chat Completions `tools[]` projection of the queue-bound agent-runtime\n * MCP delegation tools.\n *\n * Use when a caller-owned OpenAI-compatible transport needs the model to call\n * `delegate_feedback`, `delegation_status`, and `delegation_history`. Execution\n * is the caller's responsibility (typically the parent sandbox runtime's MCP\n * mount); Runtime's profile-bound model path materializes profile tools through\n * its executor instead.\n *\n * Sandbox-SDK callers do NOT need this helper: the sandbox runtime mounts\n * MCP servers natively and the in-sandbox harness discovers tools via the\n * runtime, not via an OpenAI tools array.\n *\n * Tool name + description + JSON-schema are pulled from the canonical\n * `DELEGATE_*` constants exported by `./tools/*` so the projection cannot\n * drift from the server's own validators.\n *\n * @experimental\n */\n\nimport type { OpenAIChatTool } from '../types'\nimport {\n DELEGATE_FEEDBACK_DESCRIPTION,\n DELEGATE_FEEDBACK_INPUT_SCHEMA,\n DELEGATE_FEEDBACK_TOOL_NAME,\n} from './tools/delegate-feedback'\nimport {\n DELEGATION_HISTORY_DESCRIPTION,\n DELEGATION_HISTORY_INPUT_SCHEMA,\n DELEGATION_HISTORY_TOOL_NAME,\n} from './tools/delegation-history'\nimport {\n DELEGATION_STATUS_DESCRIPTION,\n DELEGATION_STATUS_INPUT_SCHEMA,\n DELEGATION_STATUS_TOOL_NAME,\n} from './tools/delegation-status'\n\nfunction buildTool(\n name: string,\n description: string,\n parameters: Readonly<Record<string, unknown>>,\n): OpenAIChatTool {\n // `parameters` arrives as a deeply-readonly `as const` literal. The\n // OpenAI-compatible transports JSON-serialize the body, so a shallow copy\n // into a plain object is sufficient and shields callers that mutate\n // the returned descriptor from corrupting the source constant.\n return {\n type: 'function',\n function: { name, description, parameters: { ...parameters } },\n }\n}\n\n/**\n *\n * Returns the queue-bound delegation tools projected into OpenAI Chat\n * Completions `tools[]` shape. The order is stable: `delegate_feedback`,\n * `delegation_status`, `delegation_history`.\n *\n * @experimental\n */\nexport function mcpToolsForRuntimeMcp(): OpenAIChatTool[] {\n return [\n buildTool(\n DELEGATE_FEEDBACK_TOOL_NAME,\n DELEGATE_FEEDBACK_DESCRIPTION,\n DELEGATE_FEEDBACK_INPUT_SCHEMA as Readonly<Record<string, unknown>>,\n ),\n buildTool(\n DELEGATION_STATUS_TOOL_NAME,\n DELEGATION_STATUS_DESCRIPTION,\n DELEGATION_STATUS_INPUT_SCHEMA as Readonly<Record<string, unknown>>,\n ),\n buildTool(\n DELEGATION_HISTORY_TOOL_NAME,\n DELEGATION_HISTORY_DESCRIPTION,\n DELEGATION_HISTORY_INPUT_SCHEMA as Readonly<Record<string, unknown>>,\n ),\n ]\n}\n\n/**\n *\n * Subset filter — return only the projected tools whose `function.name`\n * appears in `names`. Useful for curated mounts (e.g. only the queue-bound\n * delegation tools, omitting `delegate_feedback`). Unknown names are\n * silently ignored; pass an empty array to get an empty result.\n *\n * @experimental\n */\nexport function mcpToolsForRuntimeMcpSubset(names: ReadonlyArray<string>): OpenAIChatTool[] {\n const allowed = new Set(names)\n return mcpToolsForRuntimeMcp().filter((tool) => allowed.has(tool.function.name))\n}\n"],"mappings":";;AAuCA,SAAS,UACP,MACA,aACA,YACgB;CAKhB,OAAO;EACL,MAAM;EACN,UAAU;GAAE;GAAM;GAAa,YAAY,EAAE,GAAG,WAAW;EAAE;CAC/D;AACF;;;;;;;;;AAUA,SAAgB,wBAA0C;CACxD,OAAO;EACL,UACE,6BACA,+BACA,8BACF;EACA,UACE,6BACA,+BACA,8BACF;EACA,UACE,8BACA,gCACA,+BACF;CACF;AACF;;;;;;;;;;AAWA,SAAgB,4BAA4B,OAAgD;CAC1F,MAAM,UAAU,IAAI,IAAI,KAAK;CAC7B,OAAO,sBAAsB,CAAC,CAAC,QAAQ,SAAS,QAAQ,IAAI,KAAK,SAAS,IAAI,CAAC;AACjF"}
@@ -1,4 +1,4 @@
1
- import { S as contentAddress } from "./spawn-journal-BX3-4WDm.js";
1
+ import { S as contentAddress } from "./spawn-journal-B856eA8e.js";
2
2
  import { i as redactProtectedValue, n as createProtectedRecordRedactor, r as redactProtectedReason, t as assertNoProtectedBytes } from "./protected-redaction--F3v1oo8.js";
3
3
  import { REDACTION_VERSION, canonicalJson, isLlmSpan } from "@tangle-network/agent-eval";
4
4
  import { agentCandidateArtifactRefSchema, agentCandidateBenchmarkResultEvidenceSchema, agentCandidateBenchmarkSuiteSchema, agentCandidateBenchmarkTaskSchema, agentCandidateBundleSchema, agentCandidateContainerSchema, agentCandidateExecutionLimitsSchema, agentCandidateExecutionPlanEvidenceSchema, agentCandidateExecutionPlanMaterialSchema, agentCandidateMaterializationReceiptSchema, agentCandidateModelAccessNetworkSchema, agentCandidateModelSettlementEvidenceSchema, agentCandidateProfileActivationSchema, agentCandidateProfilePlanEvidenceSchema, agentCandidateProfileSchema, agentCandidateResolvedModelSchema, agentCandidateRunCellSchema, agentCandidateRunReceiptSchema, agentCandidateTaskOutcomeEvidenceSchema, agentCandidateTaskOutcomeSpecSchema, agentCandidateTerminationSchema, agentCandidateWorkspaceManifestMaterialSchema, agentCandidateWorkspaceSnapshotEvidenceSchema, agentProfileDiffSchema, agentProfileSchema, applyAgentProfileDiff, sha256DigestSchema } from "@tangle-network/agent-interface";
@@ -4477,4 +4477,4 @@ function errorMessage(error) {
4477
4477
  //#endregion
4478
4478
  export { parseExactAgentProfile as $, verifyMaterializedWorkspace as A, rejectedStage as B, assertNoGitIndirection as C, captureMaterializedWorkspace as D, candidateWorkspaceManifest as E, assertTerminalAllowedInPhase as F, agentCandidateProfileAsAgentProfile as G, sealTerminalDigest as H, assertTerminalMatchesClaim as I, createAgentCandidateProfileActivation as J, applyExactAgentProfileDiff as K, assertTerminalMatchesStaged as L, candidateCleanupTimeout as M, withinCandidateCleanupDeadline as N, readVerifiedArtifact as O, assertRecoveryMatchesStaged as P, parseAgentCandidateProfileActivation as Q, recoveredTerminalRecord as R, CANDIDATE_TRACE_TAGS as S, runCandidateGit as T, terminalRecord as U, requireStagedTerminal as V, assertExactObjectKeys as W, materializeAgentCandidateProfilePlan as X, freezeGenericAgentCandidateProfile as Y, omitUndefinedObjectFields as Z, candidateExecutionClaim as _, persistCandidateOutputArtifact as a, deepFreezeCandidate as at, consumePreparedCandidateExecution as b, CANDIDATE_KNOWLEDGE_ROOT_ENV as c, omitTopLevelDigest as ct, verifiedResourceTextByDigest as d, parseExactAgentProfileDiff as et, verifyAgentCandidateBundle as f, candidateClaimFileInternals as g, InMemoryAgentCandidateExecutionClaimStore as h, persistCandidateModelSettlementEvidence as i, canonicalCandidateDocument as it, candidateCleanupDeadline as j, verifyBytes as k, candidateKnowledgeExecutionPaths as l, sha256Bytes as lt, usdToNanos as m, executePreparedAgentCandidate as n, canonicalCandidateBytes as nt, sealAgentCandidateExecutorStopAcknowledgement as o, embeddedCandidateArtifact as ot, sealAgentCandidateModelSettlement as p, assertCandidateProfileBinding as q, RecoveryAgentCandidateTraceStore as r, canonicalCandidateDigest$1 as rt, CANDIDATE_KNOWLEDGE_RETRIEVAL_CONFIG_ENV as s, immutableCandidateValue as st, prepareAgentCandidateExecution as t, parseExactCandidateProfile as tt, AGENT_CANDIDATE_EXECUTION_SUPPORT as u, verifyCanonicalCandidateDocument as ut, assertPreparedCandidateIntegrity as v, readCandidateGitTreeFiles as w, CANDIDATE_TRACE_ENV as x, beginPreparedCandidateDisposal as y, rejectedFinish as z };
4479
4479
 
4480
- //# sourceMappingURL=prepare-DUbH3GD5.js.map
4480
+ //# sourceMappingURL=prepare-BXEtLOj9.js.map