hiveagents-runtime 0.0.0-stage → 0.1.0-beta.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 (113) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +85 -2
  3. package/dist/adapter-kit.d.ts +37 -0
  4. package/dist/adapter-kit.js +33 -0
  5. package/dist/adapter-kit.js.map +1 -0
  6. package/dist/agent-D0HS38G3.d.ts +169 -0
  7. package/dist/agent-OLSXNGNN.js +23 -0
  8. package/dist/agent-OLSXNGNN.js.map +1 -0
  9. package/dist/agent-readiness-V36OJME4.js +19 -0
  10. package/dist/agent-readiness-V36OJME4.js.map +1 -0
  11. package/dist/capture-runtime-GP6NZ2ee.d.ts +54 -0
  12. package/dist/chunk-2RUEC63U.js +1217 -0
  13. package/dist/chunk-2RUEC63U.js.map +1 -0
  14. package/dist/chunk-3B3JW4U3.js +291 -0
  15. package/dist/chunk-3B3JW4U3.js.map +1 -0
  16. package/dist/chunk-3TIYA3K5.js +55 -0
  17. package/dist/chunk-3TIYA3K5.js.map +1 -0
  18. package/dist/chunk-6XIJW65Q.js +52 -0
  19. package/dist/chunk-6XIJW65Q.js.map +1 -0
  20. package/dist/chunk-7LDQKJKI.js +248 -0
  21. package/dist/chunk-7LDQKJKI.js.map +1 -0
  22. package/dist/chunk-ALLOMOUN.js +810 -0
  23. package/dist/chunk-ALLOMOUN.js.map +1 -0
  24. package/dist/chunk-C2DN6KL4.js +853 -0
  25. package/dist/chunk-C2DN6KL4.js.map +1 -0
  26. package/dist/chunk-COKYQUTK.js +581 -0
  27. package/dist/chunk-COKYQUTK.js.map +1 -0
  28. package/dist/chunk-CPN4DOXH.js +115 -0
  29. package/dist/chunk-CPN4DOXH.js.map +1 -0
  30. package/dist/chunk-DBFXFWQZ.js +385 -0
  31. package/dist/chunk-DBFXFWQZ.js.map +1 -0
  32. package/dist/chunk-DZFFGUIA.js +81 -0
  33. package/dist/chunk-DZFFGUIA.js.map +1 -0
  34. package/dist/chunk-EEUYQFCP.js +106 -0
  35. package/dist/chunk-EEUYQFCP.js.map +1 -0
  36. package/dist/chunk-GFVYNPLS.js +118 -0
  37. package/dist/chunk-GFVYNPLS.js.map +1 -0
  38. package/dist/chunk-GJ4FTDBJ.js +2910 -0
  39. package/dist/chunk-GJ4FTDBJ.js.map +1 -0
  40. package/dist/chunk-GS5U3KUN.js +201 -0
  41. package/dist/chunk-GS5U3KUN.js.map +1 -0
  42. package/dist/chunk-HB7FBSH2.js +960 -0
  43. package/dist/chunk-HB7FBSH2.js.map +1 -0
  44. package/dist/chunk-HZFZX5A3.js +21 -0
  45. package/dist/chunk-HZFZX5A3.js.map +1 -0
  46. package/dist/chunk-J7VAYJKM.js +595 -0
  47. package/dist/chunk-J7VAYJKM.js.map +1 -0
  48. package/dist/chunk-NCNSHOF7.js +52 -0
  49. package/dist/chunk-NCNSHOF7.js.map +1 -0
  50. package/dist/chunk-RXU2Q2HF.js +49 -0
  51. package/dist/chunk-RXU2Q2HF.js.map +1 -0
  52. package/dist/chunk-SRJUZJKV.js +521 -0
  53. package/dist/chunk-SRJUZJKV.js.map +1 -0
  54. package/dist/chunk-TG7NTMTR.js +208 -0
  55. package/dist/chunk-TG7NTMTR.js.map +1 -0
  56. package/dist/chunk-TIZKGD4R.js +202 -0
  57. package/dist/chunk-TIZKGD4R.js.map +1 -0
  58. package/dist/chunk-WMKO5XOE.js +601 -0
  59. package/dist/chunk-WMKO5XOE.js.map +1 -0
  60. package/dist/chunk-WOQBVJH5.js +175 -0
  61. package/dist/chunk-WOQBVJH5.js.map +1 -0
  62. package/dist/cli.d.ts +1 -0
  63. package/dist/cli.js +25 -0
  64. package/dist/cli.js.map +1 -0
  65. package/dist/errors-DgehLwqI.d.ts +98 -0
  66. package/dist/execution-halt-CW0Oi9s9.d.ts +12 -0
  67. package/dist/execution-types-UJ6gAF48.d.ts +239 -0
  68. package/dist/host-ledger-VPRWVVOS.js +25 -0
  69. package/dist/host-ledger-VPRWVVOS.js.map +1 -0
  70. package/dist/hosted-runtime.d.ts +168 -0
  71. package/dist/hosted-runtime.js +857 -0
  72. package/dist/hosted-runtime.js.map +1 -0
  73. package/dist/index-B86C6VAD.d.ts +41 -0
  74. package/dist/index.d.ts +327 -0
  75. package/dist/index.js +8818 -0
  76. package/dist/index.js.map +1 -0
  77. package/dist/memory-items-BSTC0_R0.d.ts +28 -0
  78. package/dist/memory-tools.d.ts +222 -0
  79. package/dist/memory-tools.js +923 -0
  80. package/dist/memory-tools.js.map +1 -0
  81. package/dist/orchestration/dynamic.d.ts +854 -0
  82. package/dist/orchestration/dynamic.js +3150 -0
  83. package/dist/orchestration/dynamic.js.map +1 -0
  84. package/dist/orchestration/graph.d.ts +11 -0
  85. package/dist/orchestration/graph.js +9 -0
  86. package/dist/orchestration/graph.js.map +1 -0
  87. package/dist/orchestration/index.d.ts +2385 -0
  88. package/dist/orchestration/index.js +6403 -0
  89. package/dist/orchestration/index.js.map +1 -0
  90. package/dist/orchestration/log.d.ts +301 -0
  91. package/dist/orchestration/log.js +3058 -0
  92. package/dist/orchestration/log.js.map +1 -0
  93. package/dist/orchestration/memory.d.ts +711 -0
  94. package/dist/orchestration/memory.js +27 -0
  95. package/dist/orchestration/memory.js.map +1 -0
  96. package/dist/provider-XCpWjJ6a.d.ts +151 -0
  97. package/dist/routing/index.d.ts +29 -0
  98. package/dist/routing/index.js +385 -0
  99. package/dist/routing/index.js.map +1 -0
  100. package/dist/routing/learning/index.d.ts +433 -0
  101. package/dist/routing/learning/index.js +2501 -0
  102. package/dist/routing/learning/index.js.map +1 -0
  103. package/dist/runtime-C6Cu2fvw.d.ts +283 -0
  104. package/dist/runtime-Y72XJFFO.js +18 -0
  105. package/dist/runtime-Y72XJFFO.js.map +1 -0
  106. package/dist/store-types-2YdceOMy.d.ts +78 -0
  107. package/dist/types-BB7KqceP.d.ts +52 -0
  108. package/dist/types-BBRKjIc7.d.ts +86 -0
  109. package/dist/types-DTFc1qO6.d.ts +1065 -0
  110. package/dist/types-DYex3p7_.d.ts +88 -0
  111. package/docs/licenses/ruflo-memory-MIT.txt +21 -0
  112. package/docs/releases/0.1.0-beta.1.md +13 -0
  113. package/package.json +114 -4
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/orchestration/memory/ranker.ts","../src/orchestration/memory/gate.ts","../src/orchestration/memory/agent-provider.ts","../src/orchestration/memory/mcp-recipes.ts"],"sourcesContent":["/**\n * BM25/cosine/MMR retrieval adapted from Ruflo's hybrid-retrieval.ts at\n * 0a96fb8857dabd343d71d76c3ca703100a2923bc (MIT, copyright 2024-2026 ruvnet).\n * The upstream notice is in docs/licenses/ruflo-memory-MIT.txt.\n */\n\n/** A caller-owned record. No store is opened, retained, or searched implicitly. */\nexport interface MemoryDocument {\n id: string;\n text: string;\n embedding?: readonly number[];\n}\n\nexport interface MemoryRankingOptions {\n /** Maximum results; a nonnegative safe integer. Default: 5. */\n limit?: number;\n /** Weight in [0, 1]. Default: 1. At least one retrieval weight must be positive. */\n lexicalWeight?: number;\n /** Weight in [0, 1]. Default: 0. A positive value requires queryEmbedding. */\n semanticWeight?: number;\n /** Supplied by the caller, from the same model as document embeddings. */\n queryEmbedding?: readonly number[];\n /**\n * MMR penalty in [0, 1]; 0 disables reranking. Default: 0.\n * Uses cosine between nonzero vectors, otherwise token-set Jaccard similarity.\n * Seeds the most relevant record even when diversity=1.\n */\n diversity?: number;\n}\n\nexport interface MemoryScores {\n /** Unbounded nonnegative BM25 score (k1=1.2, b=0.75). */\n lexical: number;\n /** lexical / (1 + lexical); a zero match stays zero. */\n lexicalNormalized: number;\n /** Cosine similarity clamped to [0, 1]; missing/zero vectors score zero. */\n semantic: number;\n /** Weighted mean of lexicalNormalized and semantic. Not a probability. */\n relevance: number;\n /** Maximum similarity to an earlier MMR selection; 0 when MMR is disabled. */\n redundancy: number;\n /** (1 - diversity) * relevance - diversity * redundancy; may be negative. */\n mmr: number;\n}\n\nexport interface RankedMemory<T extends MemoryDocument> {\n /** The exact input object; all caller payload and provenance remain intact. */\n record: T;\n scores: MemoryScores;\n}\n\nfunction tokenize(text: string): string[] {\n return text.normalize('NFKD').toLowerCase().replace(/\\p{M}/gu, '').match(/[\\p{L}\\p{N}]+/gu) ?? [];\n}\n\nfunction weight(value: number | undefined, fallback: number, name: string): number {\n if (value === undefined) return fallback;\n if (typeof value !== 'number' || !Number.isFinite(value) || value < 0 || value > 1) {\n throw new RangeError(`${name} must be a finite number in [0, 1]`);\n }\n return value;\n}\n\n/** Scaling first avoids overflow/underflow when all components are finite. */\nfunction unitVector(vector: readonly number[], dimension: number | undefined): number[] {\n if (!Array.isArray(vector) || vector.length === 0) {\n throw new TypeError('Embeddings must be nonempty arrays of finite numbers');\n }\n if (dimension !== undefined && vector.length !== dimension) {\n throw new RangeError('All query and document embeddings must have the same dimension');\n }\n let scale = 0;\n for (const value of vector) {\n if (typeof value !== 'number' || !Number.isFinite(value)) {\n throw new TypeError('Embeddings must contain only finite numbers');\n }\n scale = Math.max(scale, Math.abs(value));\n }\n if (scale === 0) return vector.map(() => 0);\n const scaled = vector.map((value) => value / scale);\n const norm = Math.sqrt(scaled.reduce((sum, value) => sum + value * value, 0));\n return scaled.map((value) => value / norm);\n}\n\nfunction cosine(a: readonly number[] | undefined, b: readonly number[] | undefined): number {\n if (!a || !b) return 0;\n let dot = 0;\n for (let i = 0; i < a.length; i++) dot += a[i]! * b[i]!;\n return Math.max(0, Math.min(1, dot));\n}\n\ninterface Candidate<T extends MemoryDocument> extends RankedMemory<T> {\n tokens: ReadonlySet<string>;\n vector: readonly number[] | undefined;\n}\n\nfunction similarity<T extends MemoryDocument>(a: Candidate<T>, b: Candidate<T>): number {\n if (a.vector && b.vector) return cosine(a.vector, b.vector);\n let intersection = 0;\n for (const token of a.tokens) if (b.tokens.has(token)) intersection++;\n const union = a.tokens.size + b.tokens.size - intersection;\n return union > 0 ? intersection / union : 0;\n}\n\nfunction rerank<T extends MemoryDocument>(\n candidates: Candidate<T>[], limit: number, diversity: number,\n): RankedMemory<T>[] {\n if (diversity === 0) {\n return candidates.sort((a, b) => b.scores.relevance - a.scores.relevance)\n .slice(0, limit).map(({ record, scores }) => ({ record, scores }));\n }\n const selected: RankedMemory<T>[] = [];\n while (selected.length < limit && candidates.length > 0) {\n let bestIndex = 0;\n let bestScore = -Infinity;\n for (let i = 0; i < candidates.length; i++) {\n const candidate = candidates[i]!;\n candidate.scores.mmr = (1 - diversity) * candidate.scores.relevance - diversity * candidate.scores.redundancy;\n const score = selected.length === 0 ? candidate.scores.relevance : candidate.scores.mmr;\n // Strict > leaves equal scores in the caller's original input order.\n if (score > bestScore) { bestIndex = i; bestScore = score; }\n }\n const chosen = candidates.splice(bestIndex, 1)[0]!;\n selected.push({ record: chosen.record, scores: chosen.scores });\n for (const candidate of candidates) {\n candidate.scores.redundancy = Math.max(candidate.scores.redundancy, similarity(candidate, chosen));\n }\n }\n return selected;\n}\n\n/**\n * Rank only the supplied records. Pure, synchronous, browser-safe, and stateless:\n * it never fetches embeddings, opens a store, or retains provider memory.\n *\n * The default is lexical BM25 with accent-folded Unicode tokens. There is no\n * stemming, stop-word removal, or synonym expansion. Scores depend on the\n * supplied corpus. Semantic retrieval and diversity are explicit opt-ins.\n * All supplied vectors are validated, including when unused or limit=0.\n * Equal scores retain input order. The caller owns filtering/authorization,\n * forgetting, persistence, and ensuring embeddings share a model/version.\n */\nexport function rankMemories<T extends MemoryDocument>(\n query: string, documents: readonly T[], options: MemoryRankingOptions = {},\n): RankedMemory<T>[] {\n if (typeof query !== 'string' || !Array.isArray(documents)) {\n throw new TypeError('query must be a string and documents must be an array');\n }\n if (!options || typeof options !== 'object' || Array.isArray(options)) {\n throw new TypeError('options must be an object');\n }\n const limit = options.limit === undefined ? 5 : options.limit;\n if (!Number.isSafeInteger(limit) || limit < 0) {\n throw new RangeError('limit must be a nonnegative safe integer');\n }\n const lexicalWeight = weight(options.lexicalWeight, 1, 'lexicalWeight');\n const semanticWeight = weight(options.semanticWeight, 0, 'semanticWeight');\n const diversity = weight(options.diversity, 0, 'diversity');\n const totalWeight = lexicalWeight + semanticWeight;\n if (totalWeight === 0) throw new RangeError('At least one retrieval weight must be positive');\n if (semanticWeight > 0 && options.queryEmbedding === undefined) {\n throw new TypeError('A positive semanticWeight requires queryEmbedding');\n }\n const queryVector = options.queryEmbedding === undefined ? undefined : unitVector(options.queryEmbedding, undefined);\n let dimension = queryVector?.length;\n const vectors = documents.map((record) => {\n if (!record || typeof record.id !== 'string' || record.id.length === 0 || typeof record.text !== 'string') {\n throw new TypeError('Every document must have a nonempty string id and string text');\n }\n if (record.embedding === undefined) return undefined;\n const vector = unitVector(record.embedding, dimension);\n dimension ??= vector.length;\n return vector.some((value) => value !== 0) ? vector : undefined;\n });\n if (limit === 0 || documents.length === 0) return [];\n const queryTokens = new Set(tokenize(query));\n const tokenized = documents.map((record) => tokenize(record.text));\n const frequencies = tokenized.map((tokens) => {\n const counts = new Map<string, number>();\n for (const token of tokens) counts.set(token, (counts.get(token) ?? 0) + 1);\n return counts;\n });\n const documentFrequency = new Map<string, number>();\n for (const counts of frequencies) {\n for (const token of counts.keys()) {\n documentFrequency.set(token, (documentFrequency.get(token) ?? 0) + 1);\n }\n }\n const averageLength = tokenized.reduce((sum, tokens) => sum + tokens.length, 0) / (documents.length || 1);\n const candidates = documents.map((record, index): Candidate<T> => {\n let lexical = 0;\n for (const token of queryTokens) {\n const frequency = frequencies[index]!.get(token) ?? 0;\n if (frequency === 0) continue;\n const df = documentFrequency.get(token)!;\n const idf = Math.log(1 + (documents.length - df + 0.5) / (df + 0.5));\n const norm = tokenized[index]!.length / (averageLength || 1);\n lexical += idf * (frequency * 2.2) / (frequency + 1.2 * (0.25 + 0.75 * norm));\n }\n const lexicalNormalized = lexical / (1 + lexical);\n const semantic = cosine(queryVector, vectors[index]);\n // Normalize weights before multiplying, so tiny positive weights stay useful.\n const relevance = (lexicalWeight / totalWeight) * lexicalNormalized + (semanticWeight / totalWeight) * semantic;\n return { record, tokens: new Set(tokenized[index]), vector: vectors[index], scores: {\n lexical, lexicalNormalized, semantic, relevance,\n redundancy: 0, mmr: relevance,\n } };\n }).filter(({ scores }) => scores.relevance > 0);\n return rerank(candidates, limit, diversity);\n}\n","/**\n * The promotion gate: a measured comparison, supplied by the caller, between the\n * same task set run without memory, with memory, and with the full history.\n *\n * This file is pure (no Node imports) so a renderer can show a gate verdict.\n */\n\n/** How many tasks of the shared task set passed under one condition. */\nexport interface MemoryConditionTally {\n passed: number;\n total: number;\n}\n\n/**\n * What a promotion must carry. Both controls are mandatory: a claim about memory\n * that was not measured against no-memory AND full-history is not evidence.\n */\nexport interface MemoryGateEvidence {\n /** Caller's id for the measurement that produced these numbers. */\n measurementId: string;\n /** SHA-256 of the measurement report, so the numbers can be traced to it. */\n digest: string;\n /**\n * Content digests (`MemoryRecordView.contentDigest`) of the records that were\n * in the memory condition. A digest binds scope, id and content, so evidence\n * for one record cannot promote another one that merely shares its id.\n */\n candidateDigests: readonly string[];\n noMemory: MemoryConditionTally;\n memory: MemoryConditionTally;\n fullHistory: MemoryConditionTally;\n}\n\nexport type MemoryGateRefusal = 'NO_GAIN_OVER_NO_MEMORY' | 'CANDIDATE_NOT_MEASURED';\n\nexport type MemoryGateVerdict =\n | { passed: true }\n | { passed: false; reason: 'NO_GAIN_OVER_NO_MEMORY' };\n\nconst EVIDENCE_KEYS = ['measurementId', 'digest', 'candidateDigests', 'noMemory', 'memory', 'fullHistory'];\nconst SHA256 = /^[a-f0-9]{64}$/;\n/** Control, format and line-separator characters: a label ends up in audit fields and on a console. */\nconst UNPRINTABLE = /[\\p{Cc}\\p{Cf}\\p{Zl}\\p{Zp}]/u;\nconst MAX_CANDIDATES = 64;\n\nfunction plainObject(value: unknown, keys: readonly string[], name: string): Record<string, unknown> {\n if (!value || typeof value !== 'object' || Array.isArray(value)) {\n throw new TypeError(`${name} must be an object`);\n }\n const own = Object.keys(value);\n if (own.length !== keys.length || own.some(key => !keys.includes(key))) {\n throw new TypeError(`${name} must have exactly: ${keys.join(', ')}`);\n }\n return value as Record<string, unknown>;\n}\n\nfunction label(value: unknown, name: string): string {\n if (typeof value !== 'string' || !value.trim() || value.length > 128 || UNPRINTABLE.test(value)) {\n throw new TypeError(`${name} must be a nonempty printable string of at most 128 characters`);\n }\n return value;\n}\n\nfunction tally(value: unknown, name: string): MemoryConditionTally {\n const { passed, total } = plainObject(value, ['passed', 'total'], name);\n if (!Number.isSafeInteger(passed) || !Number.isSafeInteger(total)) {\n throw new TypeError(`${name} must hold integer counts`);\n }\n if ((total as number) < 1 || (passed as number) < 0 || (passed as number) > (total as number)) {\n throw new RangeError(`${name} must satisfy 0 <= passed <= total and total >= 1`);\n }\n return { passed: passed as number, total: total as number };\n}\n\n/** Throws unless the evidence is complete: three tallies over one nonempty task set. */\nexport function assertMemoryGateEvidence(value: unknown): MemoryGateEvidence {\n const evidence = plainObject(value, EVIDENCE_KEYS, 'gate evidence');\n const measurementId = label(evidence.measurementId, 'measurementId');\n if (typeof evidence.digest !== 'string' || !SHA256.test(evidence.digest)) {\n throw new TypeError('digest must be a SHA-256 hex digest');\n }\n const candidates = evidence.candidateDigests;\n if (!Array.isArray(candidates) || candidates.length < 1 || candidates.length > MAX_CANDIDATES\n || new Set(candidates).size !== candidates.length\n || candidates.some(candidate => typeof candidate !== 'string' || !SHA256.test(candidate))) {\n throw new TypeError(`candidateDigests must list 1 to ${MAX_CANDIDATES} distinct record content digests`);\n }\n const candidateDigests = [...candidates] as string[];\n const noMemory = tally(evidence.noMemory, 'noMemory');\n const memory = tally(evidence.memory, 'memory');\n const fullHistory = tally(evidence.fullHistory, 'fullHistory');\n if (noMemory.total !== memory.total || fullHistory.total !== memory.total) {\n throw new RangeError('The three conditions must have run the same task set');\n }\n return { measurementId, digest: evidence.digest, candidateDigests, noMemory, memory, fullHistory };\n}\n\n/**\n * The rule the store applies before a lesson becomes recallable: memory must pass\n * strictly more tasks than the no-memory control. Full history is the ceiling\n * reference; it must have been measured, but memory is not required to beat it,\n * because its point is to get close to that ceiling with far less context.\n *\n * Throws on incomplete evidence; a missing control is never a pass.\n */\nexport function evaluateMemoryGate(evidence: MemoryGateEvidence): MemoryGateVerdict {\n const checked = assertMemoryGateEvidence(evidence);\n if (checked.memory.passed > checked.noMemory.passed) return { passed: true };\n return { passed: false, reason: 'NO_GAIN_OVER_NO_MEMORY' };\n}\n","import type {\n AgentMemoryProvider, AgentMemoryScope, MemoryCaptureRequest, MemoryProfileRequest, MemoryProposeRequest,\n MemoryRecallRequest, RecalledMemory,\n} from '../../public/memory-types.js';\nimport { recallableMemory } from '../../public/memory-items.js';\nimport type {\n EmbeddingIdentity, MemoryEmbedder, MemoryPersistencePort, MemoryQuery, MemoryQueryPort, MemoryScope,\n ScopedMemoryRecord,\n} from './ports.js';\n\n/**\n * Agent memory over the memory ports: the adapter an `Agent`'s `memory` option\n * takes. Pure (no Node imports): digests use Web Crypto, so it bundles for a\n * browser like the rest of this entry.\n *\n * Recall asks the query port for at most `limit` records in the exact scope of\n * the request and hands them to the agent as reference data. Capture is opt-in\n * twice: the application must pass a persistence port here AND set\n * `memory.capture: true` on the agent.\n *\n * Captured turns are episodes, not lessons. With `SqliteSystemMemory`, `query`\n * returns only lessons that passed the promotion gate, so a captured turn is NOT\n * recallable until the application measures it (`measureMemory`, with this\n * episode as the only candidate) and promotes it (`promote`) with that evidence.\n * Capture never promotes anything by itself. A proposal (`propose`, what an agent\n * asks to remember through a memory tool) is stored the same way: an episode.\n *\n * `propose` is offered only where a proposal is sure to stay out of recall until it is\n * promoted: when there is no `recall` port (this provider never reads what it stores), or when\n * `captureGate` is `'store-promotes'`. With `'none-acknowledged'` recall may return what\n * `persistence` stored, unreviewed, on the next turn: acceptable for the application's own\n * captured turns if it says so, but a proposal is model output that the tool tells the agent\n * is \"not recallable until promoted\", so the provider has no `propose` there.\n *\n * A store that returned what it was just given would recall a captured turn on\n * the very next turn: whatever a model was induced to write once would be read\n * back as memory on every later turn. So when both ports are given, the caller\n * must say how recall is gated (`captureGate`); the adapter refuses to guess.\n */\nexport type MemoryCaptureGate =\n /**\n * The recall port returns only records promoted through a measured gate, never a\n * stored episode as it is: `SqliteSystemMemory`, and the vector stores of\n * `hiveagents-runtime-agentdb-memory`.\n */\n | 'store-promotes'\n /**\n * The caller accepts that recall may return what capture stored, on the next\n * turn, unreviewed: for example when `recall` reads a curated store that\n * `persistence` never writes to. Never the right choice for one store that\n * returns everything it holds. Covers captured turns only: the provider then\n * has no `propose`, since a proposal must never be recalled before promotion.\n */\n | 'none-acknowledged';\n\nexport interface MemoryPortsProviderOptions {\n /** Recorded on every turn note. Default: `memory-ports`. */\n id?: string;\n /** Recall source. Without it the provider has no `recall`. */\n recall?: MemoryQueryPort;\n /** Capture target. Without it the provider has no `capture`. */\n persistence?: MemoryPersistencePort;\n /** Embeds the query text and, on capture, the stored text. Without it, recall is lexical only. */\n embedder?: MemoryEmbedder;\n /**\n * Builds the record to store for a completed turn, replacing the default\n * one-episode-per-turn record. Return undefined to store nothing. The record's\n * scope must be the request's scope.\n */\n toRecord?: (request: MemoryCaptureRequest) => ScopedMemoryRecord | undefined | Promise<ScopedMemoryRecord | undefined>;\n /** Clock for `provenance.observedAt`. Default: the system clock. */\n now?: () => Date;\n /**\n * Required when both `recall` and `persistence` are given, refused otherwise:\n * how a captured or proposed episode is kept out of recall until it is measured and promoted.\n */\n captureGate?: MemoryCaptureGate;\n /**\n * The scope's fixed profile, handed through as the provider's `profile` unchanged: the\n * application maintains it, nothing an agent does reaches it. Without it the provider has no\n * `profile`.\n */\n profile?: (request: MemoryProfileRequest) => Promise<string | undefined>;\n}\n\n/** `SqliteSystemMemory` refuses longer query texts. */\nconst MAX_QUERY_TEXT = 4096;\n/**\n * UTF-8 bytes of a default episode as the agent renders it, every line indented by\n * `RENDERED_INDENT` spaces and every whitespace run inside a line datamarked (2 bytes). 6 KiB\n * fits the default recall budget (`MEMORY_DEFAULT_MAX_BYTES`,\n * 8 KiB) with room for the item header, and stays under the 8192 characters a store takes.\n */\nexport const EPISODE_MAX_BYTES = 6 * 1024;\nconst RENDERED_INDENT = 4;\n/** What the agent counts as a line break when it indents recalled text. */\nconst LINE_BREAK = /^[\\n\\r\\u000b\\u000c\\u0085\\u2028\\u2029]$/;\n/** Whitespace; inside a line the agent datamarks each run of it as one U+02C6 (`MARK_BYTES`). */\nconst WHITESPACE = /^\\s$/u, MARK_BYTES = 2;\nconst MAX_NAME = 128;\nconst SOURCE = 'agent-turn';\nconst PROPOSAL_SOURCE = 'agent-proposal';\n/** Control, format and line-separator characters, which a store refuses in names. */\nconst UNPRINTABLE = /[\\p{Cc}\\p{Cf}\\p{Zl}\\p{Zp}]/u;\n\n/**\n * Builds an `AgentMemoryProvider` from memory ports.\n *\n * ```ts\n * const store = new SqliteSystemMemory({ databasePath, systemId: 'acme' });\n * new Agent({ model, memory: {\n * provider: memoryProviderFromPorts({ recall: store, persistence: store, captureGate: 'store-promotes' }),\n * scope: { tenant: 'acme', namespace: 'support', subject: 'customer-42' },\n * } });\n * ```\n *\n * A caller can rely on:\n * - recall never returns more than `limit` items, nor a record of another scope,\n * a revoked one or one whose `validUntil` has passed (by `now`), whatever the\n * port returns; a record the agent would drop (`recallableMemory`) is dropped\n * here and does not count against `limit`;\n * - both ports together are refused unless `captureGate` says how recall is gated;\n * - an embedder whose vectors do not match its identity is refused, never\n * padded or compared;\n * - an aborted `signal` rejects recall and capture with its reason;\n * - the default capture stores one episode per completed turn under an id\n * derived from the session and turn (from the session, the exchange and\n * `completedAt` when the turn has no id), so capturing the same request again\n * is a no-op for an idempotent store, and an exchange repeated later in the\n * session is an episode of its own;\n * - recalled text is returned as data; this adapter adds no instruction to it;\n * - `propose` exists with `persistence` and either no `recall` or `captureGate:\n * 'store-promotes'`; it stores the agent's proposal, whole, as an episode under an id\n * derived from the scope and the digest of the full text, so it is recallable only once\n * promoted; a text that does not fit `EPISODE_MAX_BYTES` as rendered is refused (a\n * TypeError), never cut; proposing the same text again in the scope names the same\n * candidate, when the store can confirm it holds that text (`MemoryPersistencePort.get`);\n * - `profile` is the caller's function, called as given.\n */\nexport function memoryProviderFromPorts(options: MemoryPortsProviderOptions): AgentMemoryProvider {\n const config = captureProviderOptions(options);\n const provider: { -readonly [K in keyof AgentMemoryProvider]: AgentMemoryProvider[K] } = { id: config.id };\n const { recall: port, persistence } = config;\n if (port) provider.recall = request => recallThrough(port, config, request);\n if (persistence) {\n provider.capture = request => captureThrough(persistence, config, request);\n // Only where nothing recalls a proposal before promotion: see `MemoryCaptureGate`.\n if (!port || config.captureGate === 'store-promotes') provider.propose = request => proposeThrough(persistence, config, request);\n }\n const { profile } = config;\n if (profile) provider.profile = request => profile(request);\n return Object.freeze(provider);\n}\n\ninterface CapturedProviderOptions {\n id: string;\n recall?: MemoryQueryPort;\n persistence?: MemoryPersistencePort;\n embedder?: MemoryEmbedder;\n toRecord?: MemoryPortsProviderOptions['toRecord'];\n profile?: MemoryPortsProviderOptions['profile'];\n captureGate?: MemoryCaptureGate;\n now: () => Date;\n}\n\nfunction captureProviderOptions(options: MemoryPortsProviderOptions): CapturedProviderOptions {\n if (!options || typeof options !== 'object') throw new TypeError('memoryProviderFromPorts needs an options object');\n const { id = 'memory-ports', recall, persistence, embedder, toRecord, now, captureGate, profile } = options;\n if (!isName(id)) throw new TypeError('id must be a nonblank printable string of at most 128 characters');\n if (recall === undefined && persistence === undefined) {\n throw new TypeError('memoryProviderFromPorts needs a recall port, a persistence port, or both');\n }\n if (recall !== undefined && persistence !== undefined) {\n if (captureGate !== 'store-promotes' && captureGate !== 'none-acknowledged') {\n throw new TypeError(\n \"With both recall and persistence, captureGate must be 'store-promotes' (recall returns only promoted lessons) \"\n + \"or 'none-acknowledged' (a captured turn may be recalled unreviewed on the next turn)\",\n );\n }\n } else if (captureGate !== undefined) {\n throw new TypeError('captureGate applies only when both recall and persistence are given');\n }\n if (recall !== undefined && typeof recall?.query !== 'function') throw new TypeError('recall must implement query()');\n if (persistence !== undefined && typeof persistence?.put !== 'function') throw new TypeError('persistence must implement put()');\n if (toRecord !== undefined && typeof toRecord !== 'function') throw new TypeError('toRecord must be a function');\n if (now !== undefined && typeof now !== 'function') throw new TypeError('now must be a function');\n if (profile !== undefined && typeof profile !== 'function') throw new TypeError('profile must be a function');\n const config: CapturedProviderOptions = { id, now: now ?? (() => new Date()) };\n if (recall) config.recall = recall;\n if (persistence) config.persistence = persistence;\n if (toRecord) config.toRecord = toRecord;\n if (profile) config.profile = profile;\n if (captureGate) config.captureGate = captureGate;\n if (embedder !== undefined) {\n if (typeof embedder?.embed !== 'function') throw new TypeError('embedder must implement embed()');\n assertIdentity(embedder.identity);\n config.embedder = embedder;\n }\n return config;\n}\n\n/** A plain copy with exactly the four fields a store checks. */\nfunction identityOf({ identity }: MemoryEmbedder): EmbeddingIdentity {\n return { provider: identity.provider, model: identity.model, revision: identity.revision, dimensions: identity.dimensions };\n}\n\nfunction assertIdentity(identity: EmbeddingIdentity): void {\n const { provider, model, revision, dimensions } = identity ?? ({} as EmbeddingIdentity);\n if (![provider, model, revision].every(isName)) {\n throw new TypeError('embedder.identity needs provider, model and revision names');\n }\n if (!Number.isSafeInteger(dimensions) || dimensions < 1) {\n throw new TypeError('embedder.identity.dimensions must be a positive integer');\n }\n}\n\n/** One vector per text, each of the identity's dimensions, finite numbers only. */\nasync function embed(embedder: MemoryEmbedder, text: string, signal?: AbortSignal): Promise<readonly number[]> {\n const vectors = await abortable(embedder.embed([text], signal), signal);\n const { dimensions } = embedder.identity;\n const vector = Array.isArray(vectors) && vectors.length === 1 ? vectors[0] : undefined;\n if (!Array.isArray(vector) || vector.length !== dimensions\n || vector.some(value => typeof value !== 'number' || !Number.isFinite(value))) {\n throw new RangeError(`The embedder must return one vector of ${dimensions} finite numbers per text`);\n }\n return Object.freeze([...vector]);\n}\n\nasync function recallThrough(\n port: MemoryQueryPort, config: CapturedProviderOptions, request: MemoryRecallRequest,\n): Promise<readonly RecalledMemory[]> {\n const { embedder } = config;\n const { signal } = request;\n signal?.throwIfAborted();\n const limit = request.limit;\n if (!Number.isSafeInteger(limit) || limit < 0) throw new RangeError('limit must be a nonnegative integer');\n if (limit === 0) return [];\n const scope = scopeOf(request.scope);\n const text = clip(typeof request.text === 'string' ? request.text : '', MAX_QUERY_TEXT);\n const query: MemoryQuery = { scope, text, limit };\n if (signal) query.signal = signal;\n if (embedder) query.embedding = { identity: identityOf(embedder), values: await embed(embedder, text, signal) };\n const records = await abortable(port.query(query), signal);\n signal?.throwIfAborted();\n if (!Array.isArray(records)) throw new TypeError('The recall port must return an array of records');\n const now = config.now().getTime();\n const recalled: RecalledMemory[] = [];\n const seen = new Set<string>();\n for (const record of records as readonly ScopedMemoryRecord[]) {\n if (recalled.length === limit) break;\n const item = recalledOf(record, scope, now);\n if (!item || seen.has(item.id)) continue;\n seen.add(item.id);\n recalled.push(item);\n }\n return Object.freeze(recalled);\n}\n\n/**\n * Defence in depth: whatever a port returns, only well-formed, live records of the asked scope come back,\n * held to the same rules the agent applies (`recallableMemory`), so an item the agent would drop never\n * takes the place of a usable one within `limit`. An unusable title is left out; the item stays.\n * A record past its `validUntil` at `now` (epoch ms) is dropped, and so is one whose `validUntil`\n * cannot be read: validity that cannot be checked is not assumed.\n */\nfunction recalledOf(record: ScopedMemoryRecord, scope: MemoryScope, now: number): RecalledMemory | undefined {\n if (!record || typeof record !== 'object' || record.revokedAt !== undefined) return undefined;\n if (!sameScope(record.scope, scope) || expired(record.validUntil, now)) return undefined;\n const provenance: Partial<ScopedMemoryRecord['provenance']> = record.provenance ?? {};\n const metadata = record.metadata;\n const title = metadata && typeof metadata === 'object' && !Array.isArray(metadata) ? metadata.title : undefined;\n const base = { id: record.id, text: record.text, source: provenance.source, ...(title === undefined ? {} : { title }) };\n // A store may keep a looser timestamp than the agent carries (no offset, say): leave the time out, keep the item.\n const item = (provenance.observedAt === undefined ? undefined : recallableMemory({ ...base, observedAt: provenance.observedAt }))\n ?? recallableMemory(base);\n return item && Object.freeze(item);\n}\n\nasync function captureThrough(\n persistence: MemoryPersistencePort, config: CapturedProviderOptions, request: MemoryCaptureRequest,\n): Promise<void> {\n const { signal } = request;\n signal?.throwIfAborted();\n const scope = scopeOf(request.scope);\n const record = config.toRecord\n ? await abortable(Promise.resolve(config.toRecord(request)), signal)\n : await defaultRecord(config, request, scope);\n if (record === undefined) return;\n if (!record || typeof record !== 'object' || !sameScope(record.scope, scope)) {\n throw new TypeError('A captured record must belong to the scope of the capture request');\n }\n signal?.throwIfAborted();\n await abortable(persistence.put(record, signal), signal);\n}\n\nfunction expired(validUntil: unknown, now: number): boolean {\n if (validUntil === undefined) return false;\n const until = typeof validUntil === 'string' ? Date.parse(validUntil) : Number.NaN;\n return Number.isNaN(until) || until < now;\n}\n\n/**\n * A proposal is untrusted model output stored as an episode, never a lesson: recall returns\n * it only after the application measures and promotes it. Its text is held to the agent's item\n * rules and to the bound of a captured episode, and stored whole: one that does not fit is\n * refused, since a cut proposal would be reported as stored while losing its end, and two\n * long ones sharing a prefix would collapse into one. Its metadata is only `{ origin, title? }`.\n */\nasync function proposeThrough(\n persistence: MemoryPersistencePort, config: CapturedProviderOptions, request: MemoryProposeRequest,\n): Promise<{ readonly id: string }> {\n const { signal } = request;\n signal?.throwIfAborted();\n const scope = scopeOf(request.scope);\n if (!isName(request.origin)) throw new TypeError('A proposal needs an origin of at most 128 printable characters');\n const text = typeof request.text === 'string' ? request.text : '';\n if (!text.trim() || !recallableMemory({ id: 'proposal', source: PROPOSAL_SOURCE, text })) {\n throw new TypeError('A proposal needs text the agent could recall');\n }\n if (renderedBytes(text) > EPISODE_MAX_BYTES - RENDERED_INDENT) {\n throw new TypeError(`A proposal must fit ${EPISODE_MAX_BYTES} bytes as the agent renders it; it is refused, never cut`);\n }\n const textHash = await sha256(text);\n const id = `${PROPOSAL_SOURCE}-${await sha256(JSON.stringify([scope.tenant, scope.namespace, scope.subject ?? null, textHash]))}`;\n signal?.throwIfAborted();\n const metadata: Record<string, string> = { origin: request.origin };\n if (isName(request.title)) metadata.title = request.title;\n const record: ScopedMemoryRecord = {\n id,\n scope,\n text,\n provenance: { source: PROPOSAL_SOURCE, sourceVersion: request.origin, observedAt: config.now().toISOString(), inputHash: textHash },\n metadata,\n };\n if (config.embedder) record.embedding = { identity: identityOf(config.embedder), values: await embed(config.embedder, text, signal) };\n signal?.throwIfAborted();\n try {\n await abortable(persistence.put(record, signal), signal);\n } catch (error) {\n // The same text proposed again in this scope (at another time, or with another title) lands\n // on this id, and an idempotent store refuses it as CONFLICT. It names the stored candidate\n // only when the store confirms that candidate holds this very text; otherwise the CONFLICT stands.\n if ((error as { code?: unknown } | null)?.code !== 'CONFLICT' || signal?.aborted) throw error;\n if (!await storedText(persistence, scope, id, text, signal)) throw error;\n }\n return Object.freeze({ id });\n}\n\n/** True when the port can read the record back and it is this scope's record with exactly `text`. */\nasync function storedText(\n persistence: MemoryPersistencePort, scope: MemoryScope, id: string, text: string, signal: AbortSignal | undefined,\n): Promise<boolean> {\n if (typeof persistence.get !== 'function') return false;\n const stored = await abortable(persistence.get({ scope, id, ...(signal ? { signal } : {}) }), signal);\n signal?.throwIfAborted();\n return !!stored && typeof stored === 'object' && stored.id === id && sameScope(stored.scope, scope) && stored.text === text;\n}\n\n/** One episode per completed turn: what the user asked and what the agent answered, with its provenance. */\nasync function defaultRecord(\n config: CapturedProviderOptions, request: MemoryCaptureRequest, scope: MemoryScope,\n): Promise<ScopedMemoryRecord | undefined> {\n const { turn, signal } = request;\n if (!turn || turn.status !== 'completed') return undefined;\n const input = typeof request.input === 'string' ? request.input : '';\n const answer = typeof turn.text === 'string' ? turn.text : '';\n if (!input.trim() && !answer.trim()) return undefined;\n const text = episodeText(input, answer);\n const session = turn.session;\n const provider = isName(session?.provider) ? session.provider : 'unknown';\n const model = isName(session?.model) ? session.model : undefined;\n const sessionId = [session?.sessionId, session?.id].find(isName);\n const turnId = isName(turn.id) ? turn.id : undefined;\n const inputHash = await sha256(JSON.stringify([input, answer]));\n signal?.throwIfAborted();\n const observedAt = typeof request.completedAt === 'string' ? request.completedAt : config.now().toISOString();\n // Without a turn id (Claude exec turns have none), the same exchange can repeat in one session:\n // the completion time keeps each repetition its own episode, while a retried capture of the same\n // request, which carries the same `completedAt`, still lands on the same id.\n const key = turnId ? ['turn', sessionId ?? '', turnId] : ['content', sessionId ?? '', inputHash, observedAt];\n const metadata: Record<string, string> = { provider };\n if (isName(session?.transport)) metadata.transport = session.transport;\n if (sessionId) metadata.sessionId = sessionId;\n if (turnId) metadata.turnId = turnId;\n const record: ScopedMemoryRecord = {\n id: `${SOURCE}-${await sha256(JSON.stringify(key))}`,\n scope,\n text,\n provenance: {\n source: SOURCE,\n sourceVersion: model && `${provider}/${model}`.length <= MAX_NAME ? `${provider}/${model}` : provider,\n observedAt,\n inputHash,\n },\n metadata,\n };\n if (config.embedder) record.embedding = { identity: identityOf(config.embedder), values: await embed(config.embedder, text, signal) };\n return record;\n}\n\n/**\n * At most `EPISODE_MAX_BYTES` as rendered. Both sides are kept when the turn is long: the input\n * keeps at least half the budget.\n */\nfunction episodeText(input: string, answer: string): string {\n const head = 'User:\\n';\n const middle = '\\n\\nAssistant:\\n';\n const budget = EPISODE_MAX_BYTES - RENDERED_INDENT - renderedBytes(head) - renderedBytes(middle);\n const inputBudget = Math.max(budget - renderedBytes(answer), Math.floor(budget / 2));\n const asked = clipRendered(input, inputBudget);\n return `${head}${asked}${middle}${clipRendered(answer, budget - renderedBytes(asked))}`;\n}\n\n/** Rendered UTF-8 bytes of one code point: a line break adds the indent; a whitespace run is one 2-byte mark. */\nfunction renderedCost(char: string, afterWhitespace: boolean): number {\n const point = char.codePointAt(0)!;\n const bytes = point < 0x80 ? 1 : point < 0x800 ? 2 : point < 0x10000 ? 3 : 4;\n if (LINE_BREAK.test(char)) return bytes + RENDERED_INDENT;\n if (WHITESPACE.test(char)) return afterWhitespace ? 0 : MARK_BYTES;\n return bytes;\n}\n\n/** Each code point of `text` with its rendered cost; a whitespace run ends at a line break. */\nfunction* renderedCosts(text: string): Generator<[string, number]> {\n let afterWhitespace = false;\n for (const char of text) {\n yield [char, renderedCost(char, afterWhitespace)];\n afterWhitespace = !LINE_BREAK.test(char) && WHITESPACE.test(char);\n }\n}\n\nfunction renderedBytes(text: string): number {\n let total = 0;\n for (const [, cost] of renderedCosts(text)) total += cost;\n return total;\n}\n\n/** The longest prefix whose rendered size is at most `maximum` bytes; never splits a code point. */\nfunction clipRendered(text: string, maximum: number): string {\n let total = 0;\n let end = 0;\n for (const [char, cost] of renderedCosts(text)) {\n total += cost;\n if (total > maximum) break;\n end += char.length;\n }\n return text.slice(0, end);\n}\n\n/** Cuts to at most `maximum` UTF-16 units without leaving half of a surrogate pair. */\nfunction clip(text: string, maximum: number): string {\n if (text.length <= maximum) return text;\n const cut = text.slice(0, maximum);\n const last = cut.charCodeAt(cut.length - 1);\n return last >= 0xd800 && last <= 0xdbff ? cut.slice(0, -1) : cut;\n}\n\nfunction scopeOf(scope: AgentMemoryScope): MemoryScope {\n if (!scope || typeof scope !== 'object') throw new TypeError('A memory request needs a scope');\n const result: MemoryScope = { tenant: scope.tenant, namespace: scope.namespace };\n if (scope.subject !== undefined) result.subject = scope.subject;\n return result;\n}\n\nfunction sameScope(candidate: unknown, scope: MemoryScope): boolean {\n if (!candidate || typeof candidate !== 'object') return false;\n const other = candidate as Partial<MemoryScope>;\n return other.tenant === scope.tenant && other.namespace === scope.namespace && other.subject === scope.subject;\n}\n\nfunction isName(value: unknown): value is string {\n return typeof value === 'string' && value.length <= MAX_NAME && value.trim() === value && value !== ''\n && !UNPRINTABLE.test(value);\n}\n\nasync function sha256(value: string): Promise<string> {\n const bytes = new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(value)));\n return Array.from(bytes, byte => byte.toString(16).padStart(2, '0')).join('');\n}\n\n/** Settles with `work`, or rejects with the signal's reason as soon as it aborts. */\nfunction abortable<T>(work: Promise<T>, signal: AbortSignal | undefined): Promise<T> {\n if (!signal) return work;\n if (signal.aborted) {\n work.catch(() => {});\n return Promise.reject(signal.reason);\n }\n return new Promise<T>((resolve, reject) => {\n const onAbort = () => reject(signal.reason);\n signal.addEventListener('abort', onAbort, { once: true });\n work.then(\n value => { signal.removeEventListener('abort', onAbort); resolve(value); },\n error => { signal.removeEventListener('abort', onAbort); reject(error); },\n );\n });\n}\n","/**\n * MCP server recipes for agent memory tools. Pure (no Node imports): a recipe\n * is data the application hands to a provider, the SDK neither installs nor\n * runs the package, and nothing here reads or writes the memory store.\n *\n * {@link claudeMcpConfig} turns recipes into one inline config for\n * `providerOptions.claude.mcpConfigs` (Claude exec). Codex exec also takes MCP\n * servers, as `mcp_servers.<name>` entries of `providerOptions.codex.config`,\n * but the field layout of those entries is not verified against the Codex CLI\n * in this repository, so no Codex helper is offered. Claude control rejects\n * provider options and Codex control refuses `mcp_servers`, so a recipe reaches\n * neither control transport.\n *\n * Two launch forms:\n * - `executable`: an absolute path to a binary installed beforehand from a\n * lockfile (`npm ci` in a directory the agent cannot write, then\n * `<dir>/node_modules/.bin/agentdb`). The whole dependency tree is the one\n * the lockfile pinned. This is the recommended form.\n * - `version`: `npx -y <package>@<version>`. Only the top-level package is\n * pinned: npm resolves its dependencies from their declared ranges when it\n * installs into its cache, npx runs a package of the same name and version\n * found in the launch directory's own project instead of fetching it, and\n * that project's `.npmrc` can point the registry, scoped registries included,\n * elsewhere. An untrusted workspace can therefore substitute the server. The\n * SDK sets no `npm_config_*` variable: a registry override would outrank only\n * the unscoped registry of a project `.npmrc`, would not stop the local\n * substitution, and would override an owner's mirror.\n *\n * Both packages are published by a single maintainer and move fast, so the npx\n * form pins an exact version: ranges, dist-tags and `latest` are refused.\n * Arguments and environment names below were read from the published\n * `agentdb@3.10.1` and `ruvector@0.3.27` sources; another version may differ.\n */\n\nexport interface McpServerRecipe {\n readonly name: string;\n /** `npx`, or the absolute path given as `executable`. */\n readonly command: string;\n readonly args: readonly string[];\n readonly env: Readonly<Record<string, string>>;\n}\n\n/** Exactly one launch form: an exact npm version (npx) or a pre-installed binary. */\nexport type McpRecipeLaunch =\n | { /** Exact semver, e.g. `3.10.1`; launched with `npx -y`. */ readonly version: string; readonly executable?: undefined }\n | { /** Absolute path of a lockfile-installed bin, e.g. `/opt/oar/node_modules/.bin/agentdb`. */\n readonly executable: string; readonly version?: undefined };\n\n/**\n * `AGENTDB_MCP_PROFILE` values, read-only first. `readonly` and `retrieval`\n * expose the same read tools in 3.10.1; `learning` (the server's default when\n * the variable is unset) adds store, update and feedback tools. `admin`, which\n * unlocks delete and reset tools, is deliberately not offered here.\n */\nexport type AgentDbMcpProfile = 'readonly' | 'retrieval' | 'learning';\n\nexport type AgentDbMcpServerOptions = McpRecipeLaunch & {\n /** Absolute path of this agent's database file (`AGENTDB_PATH`); one file per agent. */\n readonly databasePath: string;\n readonly profile: AgentDbMcpProfile;\n /** MCP server name, default `agentdb`; Claude names its tools `mcp__<name>__<tool>`. */\n readonly name?: string;\n};\n\n/**\n * RuVector policy, read-only first. `readonly` sets `RUVECTOR_MCP_PROFILE=readonly`,\n * the only profile 0.3.27 defines. `unrestricted` sets no policy, which in\n * 0.3.27 exposes every registered tool, memory writes included.\n */\nexport type RuvectorMcpProfile = 'readonly' | 'unrestricted';\n\nexport type RuvectorMcpServerOptions = McpRecipeLaunch & {\n /** MCP server name, default `ruvector`. */\n readonly name?: string;\n} & (\n | { readonly profile: 'readonly'; readonly sharedStoreAcknowledged?: boolean }\n | {\n readonly profile: 'unrestricted';\n /**\n * Required for `unrestricted`: the server's store is shared by every agent\n * launched from the same directory (or home), whatever its memory scope, so\n * a write here is readable by another tenant's agent. The SDK cannot scope it.\n */\n readonly sharedStoreAcknowledged: true;\n }\n);\n\nconst PRERELEASE_ID = '(?:0|[1-9]\\\\d*|\\\\d*[A-Za-z-][0-9A-Za-z-]*)';\nconst EXACT_SEMVER = new RegExp(\n `^(?:0|[1-9]\\\\d*)\\\\.(?:0|[1-9]\\\\d*)\\\\.(?:0|[1-9]\\\\d*)(?:-${PRERELEASE_ID}(?:\\\\.${PRERELEASE_ID})*)?$`,\n);\nconst SERVER_NAME = /^[A-Za-z0-9_-]{1,64}$/;\nconst AGENTDB_PROFILES: readonly string[] = ['readonly', 'retrieval', 'learning'];\nconst RUVECTOR_PROFILES: readonly string[] = ['readonly', 'unrestricted'];\n\nfunction plainOptions(value: unknown, allowed: readonly string[], label: string): Record<string, unknown> {\n if (!value || typeof value !== 'object' || Array.isArray(value)) throw new TypeError(`${label} options must be an object.`);\n const unknown = Object.keys(value).filter((key) => !allowed.includes(key));\n if (unknown.length) throw new TypeError(`${label} options do not accept: ${unknown.join(', ')}.`);\n return value as Record<string, unknown>;\n}\n\nfunction exactVersion(value: unknown, label: string): string {\n if (typeof value !== 'string' || !EXACT_SEMVER.test(value)) {\n throw new TypeError(`${label} version must be an exact semver such as 1.2.3; ranges, tags and latest are refused.`);\n }\n return value;\n}\n\n/** POSIX `/…`, Windows `C:\\…` or `C:/…`, and UNC `\\\\server\\…`. */\nfunction isAbsolutePath(value: unknown): value is string {\n return typeof value === 'string' && !value.includes('\\0') && value.trim() === value\n && (/^\\//.test(value) || /^[A-Za-z]:[\\\\/]/.test(value) || /^\\\\\\\\[^\\\\]/.test(value));\n}\n\nfunction absolutePath(value: unknown, label: string): string {\n if (!isAbsolutePath(value)) throw new TypeError(`${label} must be an absolute path.`);\n return value;\n}\n\nfunction serverName(value: unknown, fallback: string): string {\n const name = value ?? fallback;\n if (typeof name !== 'string' || !SERVER_NAME.test(name)) {\n throw new TypeError('MCP server name must be 1-64 letters, digits, \"_\" or \"-\".');\n }\n return name;\n}\n\nfunction profileOf(value: unknown, profiles: readonly string[], label: string): string {\n if (typeof value !== 'string' || !profiles.includes(value)) {\n throw new TypeError(`${label} profile must be one of: ${profiles.join(', ')}.`);\n }\n return value;\n}\n\nconst LAUNCH_KEYS = ['version', 'executable'];\n\n/** `npx -y <pkg>@<version> …` or `<executable> …`; exactly one of the two. */\nfunction launch(input: Record<string, unknown>, pkg: string, label: string, serverArgs: string[]): [string, string[]] {\n const hasVersion = input.version !== undefined;\n if (hasVersion === (input.executable !== undefined)) {\n throw new TypeError(`${label} needs exactly one of version (npx) or executable (pre-installed binary).`);\n }\n if (hasVersion) return ['npx', ['-y', `${pkg}@${exactVersion(input.version, label)}`, ...serverArgs]];\n return [absolutePath(input.executable, `${label} executable`), serverArgs];\n}\n\nfunction freezeRecipe(name: string, [command, args]: [string, string[]], env: Record<string, string>): McpServerRecipe {\n return Object.freeze({\n name,\n command,\n args: Object.freeze(args),\n env: Object.freeze(env),\n });\n}\n\n/**\n * `agentdb mcp start` (through `npx -y agentdb@<version>` or the given\n * executable) with `AGENTDB_PATH` and an explicit `AGENTDB_MCP_PROFILE`, so the\n * server never falls back to its write-enabled default. The stdio server takes\n * no flags; the database is set only by env.\n */\nexport function agentDbMcpServer(options: AgentDbMcpServerOptions): McpServerRecipe {\n const input = plainOptions(options, [...LAUNCH_KEYS, 'databasePath', 'profile', 'name'], 'AgentDB');\n const command = launch(input, 'agentdb', 'AgentDB', ['mcp', 'start']);\n const databasePath = absolutePath(input.databasePath, 'AgentDB databasePath');\n const profile = profileOf(input.profile, AGENTDB_PROFILES, 'AgentDB');\n return freezeRecipe(serverName(input.name, 'agentdb'), command,\n { AGENTDB_PATH: databasePath, AGENTDB_MCP_PROFILE: profile });\n}\n\n/**\n * `ruvector mcp start` (through `npx -y ruvector@<version>` or the given\n * executable). The 0.3.27 server keeps its memory in\n * `.ruvector/intelligence.json` under the directory it is launched from (or the\n * home directory when that already holds one) and reads no environment variable\n * or flag for it, so this recipe offers no storage path option. That store is\n * shared by every agent launched from the same directory or home and is not\n * scoped by the SDK: `readonly` agents read whatever any writer put there, and\n * `unrestricted` is refused unless `sharedStoreAcknowledged: true` is passed.\n */\nexport function ruvectorMcpServer(options: RuvectorMcpServerOptions): McpServerRecipe {\n const input = plainOptions(options, [...LAUNCH_KEYS, 'profile', 'name', 'sharedStoreAcknowledged'], 'RuVector');\n const command = launch(input, 'ruvector', 'RuVector', ['mcp', 'start']);\n const profile = profileOf(input.profile, RUVECTOR_PROFILES, 'RuVector');\n const acknowledged = input.sharedStoreAcknowledged;\n if (acknowledged !== undefined && typeof acknowledged !== 'boolean') {\n throw new TypeError('RuVector sharedStoreAcknowledged must be true or false.');\n }\n if (profile === 'unrestricted' && acknowledged !== true) {\n throw new TypeError('RuVector unrestricted writes to a store shared per working directory or home, not per agent; '\n + 'pass sharedStoreAcknowledged: true to accept that.');\n }\n return freezeRecipe(serverName(input.name, 'ruvector'), command,\n profile === 'readonly' ? { RUVECTOR_MCP_PROFILE: 'readonly' } : {});\n}\n\n/**\n * One inline config for `providerOptions.claude.mcpConfigs`:\n * `{\"mcpServers\":{\"<name>\":{\"command\",\"args\",\"env\"}}}`. Duplicate names are\n * refused rather than letting the later server silently replace the earlier.\n */\nexport function claudeMcpConfig(recipes: readonly McpServerRecipe[]): string {\n if (!Array.isArray(recipes) || recipes.length === 0) throw new TypeError('claudeMcpConfig needs at least one recipe.');\n const servers: Record<string, { command: string; args: string[]; env: Record<string, string> }> = {};\n for (const recipe of recipes as readonly unknown[]) {\n if (!recipe || typeof recipe !== 'object') throw new TypeError('Each MCP recipe must be an object.');\n const { name, command, args, env } = recipe as Record<string, unknown>;\n const checked = serverName(name, '');\n if (Object.hasOwn(servers, checked)) throw new TypeError(`Duplicate MCP server name: ${checked}.`);\n if (!(command === 'npx' || isAbsolutePath(command)) || !Array.isArray(args) || !args.every((arg) => typeof arg === 'string')\n || !env || typeof env !== 'object' || Array.isArray(env)\n || !Object.values(env).every((value) => typeof value === 'string')) {\n throw new TypeError(`MCP recipe ${checked} is malformed.`);\n }\n servers[checked] = { command, args: [...args] as string[], env: { ...(env as Record<string, string>) } };\n }\n return JSON.stringify({ mcpServers: servers });\n}\n"],"mappings":";;;;;AAmDA,SAAS,SAAS,MAAwB;AACxC,SAAO,KAAK,UAAU,MAAM,EAAE,YAAY,EAAE,QAAQ,WAAC,UAAM,IAAE,GAAE,EAAE,EAAE,MAAM,iBAAiB,KAAK,CAAC;AAClG;AAEA,SAAS,OAAO,OAA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,IAC3D;AACA,YAAQ,OAAO,IAAI,EAAE,SAAS,MAAM,CAAC,GAAG,IAAI,GAAe,KAAK,EAAE,GAAI,IAA+B,EAAE;AAAA,EACzG;AACA,SAAO,KAAK,UAAU,EAAE,YAAY,QAAQ,CAAC;AAC/C;","names":["UNPRINTABLE","label"]}
@@ -0,0 +1,175 @@
1
+ import {
2
+ jsonClone,
3
+ nonempty
4
+ } from "./chunk-CPN4DOXH.js";
5
+ import {
6
+ checksum
7
+ } from "./chunk-EEUYQFCP.js";
8
+ import {
9
+ ExecutionHaltedError,
10
+ isExecutionHalted
11
+ } from "./chunk-NCNSHOF7.js";
12
+
13
+ // src/orchestration/decisions/binding.ts
14
+ var decisionHash = (value) => checksum(JSON.stringify(jsonClone(value)));
15
+ function freeze(value) {
16
+ if (value !== null && typeof value === "object") {
17
+ for (const child of Object.values(value)) freeze(child);
18
+ Object.freeze(value);
19
+ }
20
+ return value;
21
+ }
22
+ function bindDecision(options) {
23
+ nonempty(options.inputVersion, "Input version");
24
+ nonempty(options.authorityVersion, "Authority version");
25
+ const input = jsonClone(options.input);
26
+ return freeze({
27
+ input,
28
+ inputHash: decisionHash(input),
29
+ authorityHash: decisionHash(options.authority),
30
+ inputVersion: options.inputVersion,
31
+ authorityVersion: options.authorityVersion
32
+ });
33
+ }
34
+ function sameDecisionBinding(left, right) {
35
+ return left.inputHash === right.inputHash && left.authorityHash === right.authorityHash && left.inputVersion === right.inputVersion && left.authorityVersion === right.authorityVersion;
36
+ }
37
+ function snapshotBinding(value) {
38
+ nonempty(value.inputVersion, "Input version");
39
+ nonempty(value.authorityVersion, "Authority version");
40
+ if (decisionHash(value.input) !== value.inputHash || !/^[a-f0-9]{64}$/.test(value.authorityHash)) throw new Error("Invalid decision binding");
41
+ return freeze(jsonClone(value));
42
+ }
43
+
44
+ // src/orchestration/decisions/runner.ts
45
+ import { randomUUID } from "node:crypto";
46
+ function authorization(value) {
47
+ const next = jsonClone(value);
48
+ if (!["allow", "wait", "deny"].includes(next.decision) || typeof next.reason !== "string" || !Number.isFinite(next.expiresAt) || next.nextAt !== void 0 && !Number.isFinite(next.nextAt)) throw new Error("Invalid authorization");
49
+ return Object.freeze(next);
50
+ }
51
+ function preserveHalt(primary, secondary) {
52
+ return isExecutionHalted(primary) || isExecutionHalted(secondary) ? new AggregateError([primary, secondary], "Execution halted during decision cleanup", { cause: primary }) : secondary;
53
+ }
54
+ function validateDecisionRecord(value, id) {
55
+ const next = jsonClone(value);
56
+ if (!next || next.format !== 1 || next.id !== id || !["waiting", "denied", "intent", "dispatched", "verified", "needs-owner"].includes(next.status) || !Number.isSafeInteger(next.attempts) || next.attempts < 0 || typeof next.reason !== "string") throw new Error("Invalid decision checkpoint");
57
+ snapshotBinding(next.binding);
58
+ if (next.authorization) authorization(next.authorization);
59
+ if (["intent", "dispatched", "verified"].includes(next.status) && (!next.intentId || !next.authorization || next.authorization.decision !== "allow" || next.attempts < 1)) throw new Error("Invalid decision intent");
60
+ if (["dispatched", "verified"].includes(next.status) && !Object.hasOwn(next, "result")) throw new Error("Missing decision result");
61
+ if (next.status === "verified" && (!next.receipt || next.receipt.intentId !== next.intentId || next.receipt.resultHash !== decisionHash(next.result) || !sameDecisionBinding(next.receipt, next.binding) || !Array.isArray(next.receipt.evidence) || !next.receipt.evidence.length || !next.receipt.evidence.every((e) => typeof e === "string" && e.trim()))) throw new Error("Invalid verification receipt");
62
+ return next;
63
+ }
64
+ var DecisionRunner = class {
65
+ constructor(store) {
66
+ this.store = store;
67
+ }
68
+ store;
69
+ async run(options) {
70
+ nonempty(options.id, "Decision id");
71
+ const binding = snapshotBinding(options.binding), signal = options.signal ?? new AbortController().signal;
72
+ const context = Object.freeze({ id: options.id, binding, signal });
73
+ const now = options.now ?? Date.now;
74
+ let observedClock;
75
+ const clock = () => {
76
+ const value = now();
77
+ if (!Number.isFinite(value)) throw new Error("Invalid decision clock");
78
+ if (observedClock !== void 0 && value < observedClock) throw new ExecutionHaltedError({ sanitizedDiagnostics: { reason: "DECISION_CLOCK_ROLLBACK" } });
79
+ observedClock = value;
80
+ return value;
81
+ };
82
+ signal.throwIfAborted();
83
+ const lease = await this.store.acquire(options.id);
84
+ let failed = false, failure;
85
+ try {
86
+ const loaded = await lease.load();
87
+ let state = loaded === void 0 ? { format: 1, id: options.id, binding, status: "waiting", attempts: 0, reason: "Waiting for condition" } : validateDecisionRecord(loaded, options.id);
88
+ const save = async (next) => {
89
+ await lease.save(jsonClone(next));
90
+ state = next;
91
+ return jsonClone(next);
92
+ };
93
+ if (!sameDecisionBinding(state.binding, binding)) {
94
+ return state.status === "needs-owner" ? jsonClone(state) : await save({ ...state, status: "needs-owner", reason: "Input or authority version changed; owner reconciliation required" });
95
+ }
96
+ if (state.status === "verified" || state.status === "denied" || state.status === "needs-owner") return jsonClone(state);
97
+ if (state.status === "intent") return await save({ ...state, status: "needs-owner", reason: "Interrupted effect is ambiguous; owner reconciliation required" });
98
+ const verify = async () => {
99
+ const effect = Object.freeze({ ...context, intentId: state.intentId, attempt: state.attempts });
100
+ const verdict = await options.verify(jsonClone(state.result), effect);
101
+ signal.throwIfAborted();
102
+ if (!verdict.verified) return jsonClone(state);
103
+ if (!Array.isArray(verdict.evidence) || !verdict.evidence.length || !verdict.evidence.every((e) => typeof e === "string" && e.trim())) throw new Error("Verified result requires evidence");
104
+ const { inputHash, authorityHash, inputVersion, authorityVersion } = binding;
105
+ return save({ ...state, status: "verified", reason: "Result verified", receipt: {
106
+ intentId: state.intentId,
107
+ inputHash,
108
+ authorityHash,
109
+ inputVersion,
110
+ authorityVersion,
111
+ approval: state.authorization,
112
+ resultHash: decisionHash(state.result),
113
+ evidence: [...verdict.evidence],
114
+ verifiedAt: clock()
115
+ } });
116
+ };
117
+ if (state.status === "dispatched") return await verify();
118
+ signal.throwIfAborted();
119
+ clock();
120
+ if (state.authorization?.nextAt !== void 0 && clock() < state.authorization.nextAt) return jsonClone(state);
121
+ if (options.condition && !await options.condition(context)) {
122
+ signal.throwIfAborted();
123
+ return loaded === void 0 ? await save(state) : jsonClone(state);
124
+ }
125
+ signal.throwIfAborted();
126
+ const approval = authorization(await options.authorize(context));
127
+ signal.throwIfAborted();
128
+ if (approval.decision !== "allow" || approval.expiresAt <= clock()) {
129
+ const next = {
130
+ ...state,
131
+ authorization: approval,
132
+ status: approval.decision === "deny" ? "denied" : "waiting",
133
+ reason: approval.expiresAt <= clock() ? "Authorization expired" : approval.reason
134
+ };
135
+ return loaded !== void 0 && JSON.stringify(next) === JSON.stringify(state) ? jsonClone(state) : await save(next);
136
+ }
137
+ await save({ ...state, status: "intent", authorization: approval, attempts: state.attempts + 1, intentId: randomUUID(), reason: approval.reason });
138
+ if (signal.aborted || approval.expiresAt <= clock() || options.isCurrent(context) !== true) {
139
+ return await save({ ...state, status: "needs-owner", reason: "Authorization expired, changed or cancelled before dispatch; owner reconciliation required" });
140
+ }
141
+ try {
142
+ const result = jsonClone(await options.execute(Object.freeze({ ...context, intentId: state.intentId, attempt: state.attempts })));
143
+ await save({ ...state, status: "dispatched", result });
144
+ } catch (error) {
145
+ try {
146
+ await save({ ...state, status: "needs-owner", reason: "Effect failed or persistence is uncertain; owner reconciliation required" });
147
+ } catch (secondary) {
148
+ throw preserveHalt(error, secondary);
149
+ }
150
+ throw error;
151
+ }
152
+ return await verify();
153
+ } catch (error) {
154
+ failed = true;
155
+ failure = error;
156
+ throw error;
157
+ } finally {
158
+ try {
159
+ await lease.release();
160
+ } catch (secondary) {
161
+ throw failed ? preserveHalt(failure, secondary) : secondary;
162
+ }
163
+ }
164
+ }
165
+ };
166
+
167
+ export {
168
+ decisionHash,
169
+ bindDecision,
170
+ sameDecisionBinding,
171
+ snapshotBinding,
172
+ validateDecisionRecord,
173
+ DecisionRunner
174
+ };
175
+ //# sourceMappingURL=chunk-WOQBVJH5.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/orchestration/decisions/binding.ts","../src/orchestration/decisions/runner.ts"],"sourcesContent":["import { checksum, jsonClone, nonempty } from '../workflow/checkpoint.js';\nimport type { JsonValue } from '../workflow/types.js';\nimport type { DecisionBinding } from './types.js';\n\nexport const decisionHash = (value: JsonValue): string => checksum(JSON.stringify(jsonClone(value)));\n\nfunction freeze<T>(value: T): T {\n if (value !== null && typeof value === 'object') {\n for (const child of Object.values(value)) freeze(child);\n Object.freeze(value);\n }\n return value;\n}\n\n/** Snapshot app inputs; authority stays private and only its identity is persisted. */\nexport function bindDecision(options: {\n input: JsonValue; authority: JsonValue; inputVersion: string; authorityVersion: string;\n}): DecisionBinding {\n nonempty(options.inputVersion, 'Input version'); nonempty(options.authorityVersion, 'Authority version');\n const input = jsonClone(options.input);\n return freeze({ input, inputHash: decisionHash(input), authorityHash: decisionHash(options.authority),\n inputVersion: options.inputVersion, authorityVersion: options.authorityVersion });\n}\n\nexport function sameDecisionBinding(left: Omit<DecisionBinding, 'input'>, right: Omit<DecisionBinding, 'input'>): boolean {\n return left.inputHash === right.inputHash && left.authorityHash === right.authorityHash\n && left.inputVersion === right.inputVersion && left.authorityVersion === right.authorityVersion;\n}\n\nexport function snapshotBinding(value: DecisionBinding): DecisionBinding {\n nonempty(value.inputVersion, 'Input version'); nonempty(value.authorityVersion, 'Authority version');\n if (decisionHash(value.input) !== value.inputHash || !/^[a-f0-9]{64}$/.test(value.authorityHash)) throw new Error('Invalid decision binding');\n return freeze(jsonClone(value));\n}\n","import { randomUUID } from 'node:crypto';\nimport { ExecutionHaltedError, isExecutionHalted } from '../../public/execution-halt.js';\nimport { jsonClone, nonempty } from '../workflow/checkpoint.js';\nimport { decisionHash, sameDecisionBinding, snapshotBinding } from './binding.js';\nimport type { DecisionAuthorization, DecisionEffectContext, DecisionRecord, DecisionRunOptions, DecisionStore } from './types.js';\n\nfunction authorization(value: DecisionAuthorization): DecisionAuthorization {\n const next = jsonClone(value);\n if (!['allow', 'wait', 'deny'].includes(next.decision) || typeof next.reason !== 'string'\n || !Number.isFinite(next.expiresAt) || (next.nextAt !== undefined && !Number.isFinite(next.nextAt))) throw new Error('Invalid authorization');\n return Object.freeze(next);\n}\nfunction preserveHalt(primary: unknown, secondary: unknown): unknown {\n return isExecutionHalted(primary) || isExecutionHalted(secondary)\n ? new AggregateError([primary, secondary], 'Execution halted during decision cleanup', { cause: primary }) : secondary;\n}\n\nexport function validateDecisionRecord(value: unknown, id: string): DecisionRecord {\n const next = jsonClone(value) as DecisionRecord;\n if (!next || next.format !== 1 || next.id !== id || !['waiting', 'denied', 'intent', 'dispatched', 'verified', 'needs-owner'].includes(next.status)\n || !Number.isSafeInteger(next.attempts) || next.attempts < 0 || typeof next.reason !== 'string') throw new Error('Invalid decision checkpoint');\n snapshotBinding(next.binding);\n if (next.authorization) authorization(next.authorization);\n if (['intent', 'dispatched', 'verified'].includes(next.status) && (!next.intentId || !next.authorization || next.authorization.decision !== 'allow' || next.attempts < 1)) throw new Error('Invalid decision intent');\n if (['dispatched', 'verified'].includes(next.status) && !Object.hasOwn(next, 'result')) throw new Error('Missing decision result');\n if (next.status === 'verified' && (!next.receipt || next.receipt.intentId !== next.intentId || next.receipt.resultHash !== decisionHash(next.result!)\n || !sameDecisionBinding(next.receipt, next.binding) || !Array.isArray(next.receipt.evidence) || !next.receipt.evidence.length\n || !next.receipt.evidence.every(e => typeof e === 'string' && e.trim()))) throw new Error('Invalid verification receipt');\n return next;\n}\n\n/**\n * A durable wait/decision around one app-owned effect, not a business workflow.\n * Recovered intents require owner reconciliation; this runner never replays an\n * ambiguous effect. Give reconciled replacement work its own id and authority.\n */\nexport class DecisionRunner {\n constructor(private readonly store: DecisionStore) {}\n async run(options: DecisionRunOptions): Promise<DecisionRecord> {\n nonempty(options.id, 'Decision id');\n const binding = snapshotBinding(options.binding), signal = options.signal ?? new AbortController().signal;\n const context = Object.freeze({ id: options.id, binding, signal });\n const now = options.now ?? Date.now;\n let observedClock: number | undefined;\n const clock = () => {\n const value = now(); if (!Number.isFinite(value)) throw new Error('Invalid decision clock');\n if (observedClock !== undefined && value < observedClock) throw new ExecutionHaltedError({ sanitizedDiagnostics: { reason: 'DECISION_CLOCK_ROLLBACK' } });\n observedClock = value; return value;\n };\n signal.throwIfAborted();\n const lease = await this.store.acquire(options.id);\n let failed = false, failure: unknown;\n try {\n const loaded = await lease.load();\n let state: DecisionRecord = loaded === undefined ? { format: 1, id: options.id, binding, status: 'waiting', attempts: 0, reason: 'Waiting for condition' } : validateDecisionRecord(loaded, options.id);\n const save = async (next: DecisionRecord) => {\n await lease.save(jsonClone(next)); state = next; return jsonClone(next);\n };\n if (!sameDecisionBinding(state.binding, binding)) {\n return state.status === 'needs-owner' ? jsonClone(state)\n : await save({ ...state, status: 'needs-owner', reason: 'Input or authority version changed; owner reconciliation required' });\n }\n if (state.status === 'verified' || state.status === 'denied' || state.status === 'needs-owner') return jsonClone(state);\n if (state.status === 'intent') return await save({ ...state, status: 'needs-owner', reason: 'Interrupted effect is ambiguous; owner reconciliation required' });\n const verify = async () => {\n const effect: DecisionEffectContext = Object.freeze({ ...context, intentId: state.intentId!, attempt: state.attempts });\n const verdict = await options.verify(jsonClone(state.result!), effect);\n signal.throwIfAborted();\n if (!verdict.verified) return jsonClone(state);\n if (!Array.isArray(verdict.evidence) || !verdict.evidence.length || !verdict.evidence.every(e => typeof e === 'string' && e.trim())) throw new Error('Verified result requires evidence');\n const { inputHash, authorityHash, inputVersion, authorityVersion } = binding;\n return save({ ...state, status: 'verified', reason: 'Result verified', receipt: {\n intentId: state.intentId!, inputHash, authorityHash, inputVersion, authorityVersion,\n approval: state.authorization!, resultHash: decisionHash(state.result!), evidence: [...verdict.evidence], verifiedAt: clock(),\n } });\n };\n if (state.status === 'dispatched') return await verify();\n signal.throwIfAborted();\n clock(); // Establish a floor before callbacks that may await a changed local clock.\n if (state.authorization?.nextAt !== undefined && clock() < state.authorization.nextAt) return jsonClone(state);\n if (options.condition && !await options.condition(context)) {\n signal.throwIfAborted();\n return loaded === undefined ? await save(state) : jsonClone(state);\n }\n signal.throwIfAborted();\n const approval = authorization(await options.authorize(context));\n signal.throwIfAborted();\n if (approval.decision !== 'allow' || approval.expiresAt <= clock()) {\n const next: DecisionRecord = { ...state, authorization: approval,\n status: approval.decision === 'deny' ? 'denied' : 'waiting',\n reason: approval.expiresAt <= clock() ? 'Authorization expired' : approval.reason };\n return loaded !== undefined && JSON.stringify(next) === JSON.stringify(state) ? jsonClone(state) : await save(next);\n }\n await save({ ...state, status: 'intent', authorization: approval, attempts: state.attempts + 1, intentId: randomUUID(), reason: approval.reason });\n // Persistence may yield long enough to invalidate approval; no effect crosses that gap.\n if (signal.aborted || approval.expiresAt <= clock() || options.isCurrent(context) !== true) {\n return await save({ ...state, status: 'needs-owner', reason: 'Authorization expired, changed or cancelled before dispatch; owner reconciliation required' });\n }\n try {\n const result = jsonClone(await options.execute(Object.freeze({ ...context, intentId: state.intentId!, attempt: state.attempts })));\n await save({ ...state, status: 'dispatched', result });\n } catch (error) {\n try { await save({ ...state, status: 'needs-owner', reason: 'Effect failed or persistence is uncertain; owner reconciliation required' }); }\n catch (secondary) { throw preserveHalt(error, secondary); }\n throw error;\n }\n return await verify();\n } catch (error) { failed = true; failure = error; throw error; }\n finally {\n try { await lease.release(); } catch (secondary) { throw failed ? preserveHalt(failure, secondary) : secondary; }\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;AAIO,IAAM,eAAe,CAAC,UAA6B,SAAS,KAAK,UAAU,UAAU,KAAK,CAAC,CAAC;AAEnG,SAAS,OAAU,OAAa;AAC9B,MAAI,UAAU,QAAQ,OAAO,UAAU,UAAU;AAC/C,eAAW,SAAS,OAAO,OAAO,KAAK,EAAG,QAAO,KAAK;AACtD,WAAO,OAAO,KAAK;AAAA,EACrB;AACA,SAAO;AACT;AAGO,SAAS,aAAa,SAET;AAClB,WAAS,QAAQ,cAAc,eAAe;AAAG,WAAS,QAAQ,kBAAkB,mBAAmB;AACvG,QAAM,QAAQ,UAAU,QAAQ,KAAK;AACrC,SAAO,OAAO;AAAA,IAAE;AAAA,IAAO,WAAW,aAAa,KAAK;AAAA,IAAG,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+ import "./chunk-HZFZX5A3.js";
7
+ import "./chunk-COKYQUTK.js";
8
+ import "./chunk-3TIYA3K5.js";
9
+ import "./chunk-C2DN6KL4.js";
10
+ import "./chunk-J7VAYJKM.js";
11
+ import "./chunk-SRJUZJKV.js";
12
+ import "./chunk-ALLOMOUN.js";
13
+ import "./chunk-6XIJW65Q.js";
14
+ import "./chunk-RXU2Q2HF.js";
15
+ import "./chunk-2RUEC63U.js";
16
+ import "./chunk-GS5U3KUN.js";
17
+ import "./chunk-EEUYQFCP.js";
18
+ import "./chunk-DBFXFWQZ.js";
19
+ import "./chunk-7LDQKJKI.js";
20
+ import "./chunk-NCNSHOF7.js";
21
+ import "./chunk-TG7NTMTR.js";
22
+
23
+ // src/cli/main.ts
24
+ process.exitCode = await runCli(process.argv.slice(2));
25
+ //# sourceMappingURL=cli.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/cli/main.ts"],"sourcesContent":["#!/usr/bin/env node\n\nimport { runCli } from './run-cli.js';\n\nprocess.exitCode = await runCli(process.argv.slice(2));\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAIA,QAAQ,WAAW,MAAM,OAAO,QAAQ,KAAK,MAAM,CAAC,CAAC;","names":[]}
@@ -0,0 +1,98 @@
1
+ import { P as ProviderId, b as TransportKind, S as SessionRef, U as Usage } from './types-DTFc1qO6.js';
2
+
3
+ /** Closed semantic facts, classified before native prose is discarded. No retry/reset authority. */
4
+ interface FailureClassification {
5
+ kind: 'not-authenticated' | 'unknown-model' | 'model-unavailable' | 'usage-limit' | 'untrusted-workspace' | 'session-not-found' | 'provider-unavailable' | 'protocol';
6
+ reason?: 'request-rejected' | 'provider-overloaded' | 'transport' | 'execution-limit' | 'unknown';
7
+ /** Provider-reported reset in epoch milliseconds; only present on a confirmed usage rejection. */
8
+ retryAt?: number;
9
+ }
10
+ interface ErrorContext {
11
+ provider?: ProviderId;
12
+ transport?: TransportKind;
13
+ cliVersion?: string;
14
+ session?: SessionRef;
15
+ retryable: boolean;
16
+ rawCode?: string;
17
+ sanitizedDiagnostics?: unknown;
18
+ /** Provider-reported usage for a failed attempt or local output rejection. Absent when unknown. */
19
+ observedUsage?: Usage;
20
+ failure?: Readonly<FailureClassification>;
21
+ }
22
+ type RuntimeErrorCode = 'EXECUTION_HALTED' | 'ADMISSION_REFUSED' | 'CLI_NOT_INSTALLED' | 'NOT_AUTHENTICATED' | 'UNEXPECTED_AUTH_SOURCE' | 'UNSUPPORTED_CLI_VERSION' | 'UNKNOWN_PROVIDER' | 'UNKNOWN_MODEL' | 'AMBIGUOUS_MODEL' | 'MODEL_PROVIDER_MISMATCH' | 'MODEL_UNAVAILABLE_FOR_AUTH' | 'UNSUPPORTED_CAPABILITY' | 'REQUIRED_TRANSPORT_UNAVAILABLE' | 'SESSION_NOT_FOUND' | 'SESSION_MISMATCH' | 'SESSION_BUSY' | 'SESSION_INTERRUPTED' | 'PROTOCOL_ERROR' | 'STRUCTURED_OUTPUT_ERROR' | 'APPROVAL_REQUIRED' | 'INTERACTION_EXPIRED' | 'TIMEOUT' | 'ABORTED' | 'OUTPUT_LIMIT' | 'USAGE_LIMIT' | 'UNTRUSTED_WORKSPACE' | 'PROVIDER_UNAVAILABLE';
23
+ declare class AgentRuntimeError extends Error {
24
+ readonly code: RuntimeErrorCode;
25
+ readonly context: Readonly<ErrorContext>;
26
+ constructor(code: RuntimeErrorCode, message: string, context: ErrorContext, options?: ErrorOptions);
27
+ }
28
+ type ContextInput = ErrorContext;
29
+ declare class CliNotInstalledError extends AgentRuntimeError {
30
+ constructor(provider: ProviderId, context: ContextInput);
31
+ }
32
+ declare class NotAuthenticatedError extends AgentRuntimeError {
33
+ constructor(provider: ProviderId, context: ContextInput);
34
+ }
35
+ declare class UnexpectedAuthSourceError extends AgentRuntimeError {
36
+ constructor(provider: ProviderId, context: ContextInput);
37
+ }
38
+ declare class UnsupportedCliVersionError extends AgentRuntimeError {
39
+ constructor(provider: ProviderId, version: string, context: ContextInput);
40
+ }
41
+ declare class UnknownModelError extends AgentRuntimeError {
42
+ readonly requested: string;
43
+ readonly suggestions: string[];
44
+ constructor(requested: string, suggestions?: string[], context?: ContextInput);
45
+ }
46
+ declare class AmbiguousModelError extends AgentRuntimeError {
47
+ readonly requested: string;
48
+ readonly providers: ProviderId[];
49
+ constructor(requested: string, providers: ProviderId[]);
50
+ }
51
+ declare class ModelProviderMismatchError extends AgentRuntimeError {
52
+ constructor(requested: string, provider: ProviderId, inferred: ProviderId);
53
+ }
54
+ declare class ModelUnavailableForAuthError extends AgentRuntimeError {
55
+ constructor(provider: ProviderId, model: string, context: ContextInput);
56
+ }
57
+ declare const UnsupportedCapabilityError: new (context: ContextInput, message?: string) => AgentRuntimeError;
58
+ /**
59
+ * The Agent was given pinned constraints, but this turn has no verified channel to deliver them
60
+ * on. Nothing ran. `reason` says why; `allowUnpinned` on the option runs such turns anyway.
61
+ */
62
+ declare class PinnedGuaranteeUnavailableError extends UnsupportedCapabilityError {
63
+ readonly reason: string;
64
+ constructor(context: ContextInput, reason: string);
65
+ }
66
+ declare const RequiredTransportUnavailableError: new (context: ContextInput, message?: string) => AgentRuntimeError;
67
+ declare const SessionNotFoundError: new (context: ContextInput, message?: string) => AgentRuntimeError;
68
+ declare const SessionMismatchError: new (context: ContextInput, message?: string) => AgentRuntimeError;
69
+ declare const SessionBusyError: new (context: ContextInput, message?: string) => AgentRuntimeError;
70
+ declare const SessionInterruptedError: new (context: ContextInput, message?: string) => AgentRuntimeError;
71
+ declare const ProtocolError: new (context: ContextInput, message?: string) => AgentRuntimeError;
72
+ declare const StructuredOutputError: new (context: ContextInput, message?: string) => AgentRuntimeError;
73
+ declare const ApprovalRequiredError: new (context: ContextInput, message?: string) => AgentRuntimeError;
74
+ declare const InteractionExpiredError: new (context: ContextInput, message?: string) => AgentRuntimeError;
75
+ declare const TimeoutError: new (context: ContextInput, message?: string) => AgentRuntimeError;
76
+ declare const AbortError: new (context: ContextInput, message?: string) => AgentRuntimeError;
77
+ declare const OutputLimitError: new (context: ContextInput, message?: string) => AgentRuntimeError;
78
+ declare const UsageLimitError: new (context: ContextInput, message?: string) => AgentRuntimeError;
79
+ /** Reads one nominal provider rejection; no prose, coercion, cause traversal or scheduling. */
80
+ declare function observedUsageLimitReset(error: unknown, provider: string, nowMs?: number): number | undefined;
81
+ declare const UntrustedWorkspaceError: new (context: ContextInput, message?: string) => AgentRuntimeError;
82
+ declare const ProviderUnavailableError: new (context: ContextInput, message?: string) => AgentRuntimeError;
83
+ declare class UnknownProviderError extends AgentRuntimeError {
84
+ constructor(provider: ProviderId);
85
+ }
86
+ type AdmissionRefusalReason = 'concurrency-limit' | 'hourly-limit' | 'daily-limit' | 'quota-cooldown' | 'wait-timeout';
87
+ /** Closed admission classification only. Its fields grant no retry, fallback, lease or release permission. */
88
+ declare class AdmissionRefusedError extends AgentRuntimeError {
89
+ readonly provider: ProviderId;
90
+ readonly reason: AdmissionRefusalReason;
91
+ readonly receiptDigest: string;
92
+ constructor(provider: ProviderId, input: {
93
+ readonly reason: AdmissionRefusalReason;
94
+ readonly receiptDigest: string;
95
+ });
96
+ }
97
+
98
+ export { AgentRuntimeError as A, CliNotInstalledError as C, type ErrorContext as E, type FailureClassification as F, InteractionExpiredError as I, ModelProviderMismatchError as M, NotAuthenticatedError as N, OutputLimitError as O, ProtocolError as P, RequiredTransportUnavailableError as R, SessionBusyError as S, TimeoutError as T, UnexpectedAuthSourceError as U, AbortError as a, type AdmissionRefusalReason as b, AdmissionRefusedError as c, AmbiguousModelError as d, ApprovalRequiredError as e, ModelUnavailableForAuthError as f, PinnedGuaranteeUnavailableError as g, ProviderUnavailableError as h, type RuntimeErrorCode as i, SessionInterruptedError as j, SessionMismatchError as k, SessionNotFoundError as l, StructuredOutputError as m, UnknownModelError as n, UnknownProviderError as o, UnsupportedCapabilityError as p, UnsupportedCliVersionError as q, UntrustedWorkspaceError as r, UsageLimitError as s, observedUsageLimitReset as t };
@@ -0,0 +1,12 @@
1
+ import { A as AgentRuntimeError, E as ErrorContext } from './errors-DgehLwqI.js';
2
+
3
+ /** A failed infrastructure boundary must stop execution, selection and dependent retries. */
4
+ declare class ExecutionHaltedError extends AgentRuntimeError {
5
+ constructor(context?: Omit<ErrorContext, 'retryable'>, options?: ErrorOptions);
6
+ }
7
+ /** Genuine nominal errors only; oversized native error graphs are conservatively halting. */
8
+ declare function isExecutionHalted(error: unknown): boolean;
9
+ /** Preserve the original outer aggregate/cause, without invoking provider getters or proxy traps. */
10
+ declare function rethrowExecutionHalt(error: unknown): void;
11
+
12
+ export { ExecutionHaltedError as E, isExecutionHalted as i, rethrowExecutionHalt as r };