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.
- package/LICENSE +202 -0
- package/README.md +85 -2
- package/dist/adapter-kit.d.ts +37 -0
- package/dist/adapter-kit.js +33 -0
- package/dist/adapter-kit.js.map +1 -0
- package/dist/agent-D0HS38G3.d.ts +169 -0
- package/dist/agent-OLSXNGNN.js +23 -0
- package/dist/agent-OLSXNGNN.js.map +1 -0
- package/dist/agent-readiness-V36OJME4.js +19 -0
- package/dist/agent-readiness-V36OJME4.js.map +1 -0
- package/dist/capture-runtime-GP6NZ2ee.d.ts +54 -0
- package/dist/chunk-2RUEC63U.js +1217 -0
- package/dist/chunk-2RUEC63U.js.map +1 -0
- package/dist/chunk-3B3JW4U3.js +291 -0
- package/dist/chunk-3B3JW4U3.js.map +1 -0
- package/dist/chunk-3TIYA3K5.js +55 -0
- package/dist/chunk-3TIYA3K5.js.map +1 -0
- package/dist/chunk-6XIJW65Q.js +52 -0
- package/dist/chunk-6XIJW65Q.js.map +1 -0
- package/dist/chunk-7LDQKJKI.js +248 -0
- package/dist/chunk-7LDQKJKI.js.map +1 -0
- package/dist/chunk-ALLOMOUN.js +810 -0
- package/dist/chunk-ALLOMOUN.js.map +1 -0
- package/dist/chunk-C2DN6KL4.js +853 -0
- package/dist/chunk-C2DN6KL4.js.map +1 -0
- package/dist/chunk-COKYQUTK.js +581 -0
- package/dist/chunk-COKYQUTK.js.map +1 -0
- package/dist/chunk-CPN4DOXH.js +115 -0
- package/dist/chunk-CPN4DOXH.js.map +1 -0
- package/dist/chunk-DBFXFWQZ.js +385 -0
- package/dist/chunk-DBFXFWQZ.js.map +1 -0
- package/dist/chunk-DZFFGUIA.js +81 -0
- package/dist/chunk-DZFFGUIA.js.map +1 -0
- package/dist/chunk-EEUYQFCP.js +106 -0
- package/dist/chunk-EEUYQFCP.js.map +1 -0
- package/dist/chunk-GFVYNPLS.js +118 -0
- package/dist/chunk-GFVYNPLS.js.map +1 -0
- package/dist/chunk-GJ4FTDBJ.js +2910 -0
- package/dist/chunk-GJ4FTDBJ.js.map +1 -0
- package/dist/chunk-GS5U3KUN.js +201 -0
- package/dist/chunk-GS5U3KUN.js.map +1 -0
- package/dist/chunk-HB7FBSH2.js +960 -0
- package/dist/chunk-HB7FBSH2.js.map +1 -0
- package/dist/chunk-HZFZX5A3.js +21 -0
- package/dist/chunk-HZFZX5A3.js.map +1 -0
- package/dist/chunk-J7VAYJKM.js +595 -0
- package/dist/chunk-J7VAYJKM.js.map +1 -0
- package/dist/chunk-NCNSHOF7.js +52 -0
- package/dist/chunk-NCNSHOF7.js.map +1 -0
- package/dist/chunk-RXU2Q2HF.js +49 -0
- package/dist/chunk-RXU2Q2HF.js.map +1 -0
- package/dist/chunk-SRJUZJKV.js +521 -0
- package/dist/chunk-SRJUZJKV.js.map +1 -0
- package/dist/chunk-TG7NTMTR.js +208 -0
- package/dist/chunk-TG7NTMTR.js.map +1 -0
- package/dist/chunk-TIZKGD4R.js +202 -0
- package/dist/chunk-TIZKGD4R.js.map +1 -0
- package/dist/chunk-WMKO5XOE.js +601 -0
- package/dist/chunk-WMKO5XOE.js.map +1 -0
- package/dist/chunk-WOQBVJH5.js +175 -0
- package/dist/chunk-WOQBVJH5.js.map +1 -0
- package/dist/cli.d.ts +1 -0
- package/dist/cli.js +25 -0
- package/dist/cli.js.map +1 -0
- package/dist/errors-DgehLwqI.d.ts +98 -0
- package/dist/execution-halt-CW0Oi9s9.d.ts +12 -0
- package/dist/execution-types-UJ6gAF48.d.ts +239 -0
- package/dist/host-ledger-VPRWVVOS.js +25 -0
- package/dist/host-ledger-VPRWVVOS.js.map +1 -0
- package/dist/hosted-runtime.d.ts +168 -0
- package/dist/hosted-runtime.js +857 -0
- package/dist/hosted-runtime.js.map +1 -0
- package/dist/index-B86C6VAD.d.ts +41 -0
- package/dist/index.d.ts +327 -0
- package/dist/index.js +8818 -0
- package/dist/index.js.map +1 -0
- package/dist/memory-items-BSTC0_R0.d.ts +28 -0
- package/dist/memory-tools.d.ts +222 -0
- package/dist/memory-tools.js +923 -0
- package/dist/memory-tools.js.map +1 -0
- package/dist/orchestration/dynamic.d.ts +854 -0
- package/dist/orchestration/dynamic.js +3150 -0
- package/dist/orchestration/dynamic.js.map +1 -0
- package/dist/orchestration/graph.d.ts +11 -0
- package/dist/orchestration/graph.js +9 -0
- package/dist/orchestration/graph.js.map +1 -0
- package/dist/orchestration/index.d.ts +2385 -0
- package/dist/orchestration/index.js +6403 -0
- package/dist/orchestration/index.js.map +1 -0
- package/dist/orchestration/log.d.ts +301 -0
- package/dist/orchestration/log.js +3058 -0
- package/dist/orchestration/log.js.map +1 -0
- package/dist/orchestration/memory.d.ts +711 -0
- package/dist/orchestration/memory.js +27 -0
- package/dist/orchestration/memory.js.map +1 -0
- package/dist/provider-XCpWjJ6a.d.ts +151 -0
- package/dist/routing/index.d.ts +29 -0
- package/dist/routing/index.js +385 -0
- package/dist/routing/index.js.map +1 -0
- package/dist/routing/learning/index.d.ts +433 -0
- package/dist/routing/learning/index.js +2501 -0
- package/dist/routing/learning/index.js.map +1 -0
- package/dist/runtime-C6Cu2fvw.d.ts +283 -0
- package/dist/runtime-Y72XJFFO.js +18 -0
- package/dist/runtime-Y72XJFFO.js.map +1 -0
- package/dist/store-types-2YdceOMy.d.ts +78 -0
- package/dist/types-BB7KqceP.d.ts +52 -0
- package/dist/types-BBRKjIc7.d.ts +86 -0
- package/dist/types-DTFc1qO6.d.ts +1065 -0
- package/dist/types-DYex3p7_.d.ts +88 -0
- package/docs/licenses/ruflo-memory-MIT.txt +21 -0
- package/docs/releases/0.1.0-beta.1.md +13 -0
- package/package.json +114 -4
|
@@ -0,0 +1,601 @@
|
|
|
1
|
+
import {
|
|
2
|
+
recallableMemory
|
|
3
|
+
} from "./chunk-6XIJW65Q.js";
|
|
4
|
+
|
|
5
|
+
// src/orchestration/memory/ranker.ts
|
|
6
|
+
function tokenize(text) {
|
|
7
|
+
return text.normalize("NFKD").toLowerCase().replace(new RegExp("\\p{M}", "gu"), "").match(/[\p{L}\p{N}]+/gu) ?? [];
|
|
8
|
+
}
|
|
9
|
+
function weight(value, fallback, name) {
|
|
10
|
+
if (value === void 0) return fallback;
|
|
11
|
+
if (typeof value !== "number" || !Number.isFinite(value) || value < 0 || value > 1) {
|
|
12
|
+
throw new RangeError(`${name} must be a finite number in [0, 1]`);
|
|
13
|
+
}
|
|
14
|
+
return value;
|
|
15
|
+
}
|
|
16
|
+
function unitVector(vector, dimension) {
|
|
17
|
+
if (!Array.isArray(vector) || vector.length === 0) {
|
|
18
|
+
throw new TypeError("Embeddings must be nonempty arrays of finite numbers");
|
|
19
|
+
}
|
|
20
|
+
if (dimension !== void 0 && vector.length !== dimension) {
|
|
21
|
+
throw new RangeError("All query and document embeddings must have the same dimension");
|
|
22
|
+
}
|
|
23
|
+
let scale = 0;
|
|
24
|
+
for (const value of vector) {
|
|
25
|
+
if (typeof value !== "number" || !Number.isFinite(value)) {
|
|
26
|
+
throw new TypeError("Embeddings must contain only finite numbers");
|
|
27
|
+
}
|
|
28
|
+
scale = Math.max(scale, Math.abs(value));
|
|
29
|
+
}
|
|
30
|
+
if (scale === 0) return vector.map(() => 0);
|
|
31
|
+
const scaled = vector.map((value) => value / scale);
|
|
32
|
+
const norm = Math.sqrt(scaled.reduce((sum, value) => sum + value * value, 0));
|
|
33
|
+
return scaled.map((value) => value / norm);
|
|
34
|
+
}
|
|
35
|
+
function cosine(a, b) {
|
|
36
|
+
if (!a || !b) return 0;
|
|
37
|
+
let dot = 0;
|
|
38
|
+
for (let i = 0; i < a.length; i++) dot += a[i] * b[i];
|
|
39
|
+
return Math.max(0, Math.min(1, dot));
|
|
40
|
+
}
|
|
41
|
+
function similarity(a, b) {
|
|
42
|
+
if (a.vector && b.vector) return cosine(a.vector, b.vector);
|
|
43
|
+
let intersection = 0;
|
|
44
|
+
for (const token of a.tokens) if (b.tokens.has(token)) intersection++;
|
|
45
|
+
const union = a.tokens.size + b.tokens.size - intersection;
|
|
46
|
+
return union > 0 ? intersection / union : 0;
|
|
47
|
+
}
|
|
48
|
+
function rerank(candidates, limit, diversity) {
|
|
49
|
+
if (diversity === 0) {
|
|
50
|
+
return candidates.sort((a, b) => b.scores.relevance - a.scores.relevance).slice(0, limit).map(({ record, scores }) => ({ record, scores }));
|
|
51
|
+
}
|
|
52
|
+
const selected = [];
|
|
53
|
+
while (selected.length < limit && candidates.length > 0) {
|
|
54
|
+
let bestIndex = 0;
|
|
55
|
+
let bestScore = -Infinity;
|
|
56
|
+
for (let i = 0; i < candidates.length; i++) {
|
|
57
|
+
const candidate = candidates[i];
|
|
58
|
+
candidate.scores.mmr = (1 - diversity) * candidate.scores.relevance - diversity * candidate.scores.redundancy;
|
|
59
|
+
const score = selected.length === 0 ? candidate.scores.relevance : candidate.scores.mmr;
|
|
60
|
+
if (score > bestScore) {
|
|
61
|
+
bestIndex = i;
|
|
62
|
+
bestScore = score;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
const chosen = candidates.splice(bestIndex, 1)[0];
|
|
66
|
+
selected.push({ record: chosen.record, scores: chosen.scores });
|
|
67
|
+
for (const candidate of candidates) {
|
|
68
|
+
candidate.scores.redundancy = Math.max(candidate.scores.redundancy, similarity(candidate, chosen));
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
return selected;
|
|
72
|
+
}
|
|
73
|
+
function rankMemories(query, documents, options = {}) {
|
|
74
|
+
if (typeof query !== "string" || !Array.isArray(documents)) {
|
|
75
|
+
throw new TypeError("query must be a string and documents must be an array");
|
|
76
|
+
}
|
|
77
|
+
if (!options || typeof options !== "object" || Array.isArray(options)) {
|
|
78
|
+
throw new TypeError("options must be an object");
|
|
79
|
+
}
|
|
80
|
+
const limit = options.limit === void 0 ? 5 : options.limit;
|
|
81
|
+
if (!Number.isSafeInteger(limit) || limit < 0) {
|
|
82
|
+
throw new RangeError("limit must be a nonnegative safe integer");
|
|
83
|
+
}
|
|
84
|
+
const lexicalWeight = weight(options.lexicalWeight, 1, "lexicalWeight");
|
|
85
|
+
const semanticWeight = weight(options.semanticWeight, 0, "semanticWeight");
|
|
86
|
+
const diversity = weight(options.diversity, 0, "diversity");
|
|
87
|
+
const totalWeight = lexicalWeight + semanticWeight;
|
|
88
|
+
if (totalWeight === 0) throw new RangeError("At least one retrieval weight must be positive");
|
|
89
|
+
if (semanticWeight > 0 && options.queryEmbedding === void 0) {
|
|
90
|
+
throw new TypeError("A positive semanticWeight requires queryEmbedding");
|
|
91
|
+
}
|
|
92
|
+
const queryVector = options.queryEmbedding === void 0 ? void 0 : unitVector(options.queryEmbedding, void 0);
|
|
93
|
+
let dimension = queryVector?.length;
|
|
94
|
+
const vectors = documents.map((record) => {
|
|
95
|
+
if (!record || typeof record.id !== "string" || record.id.length === 0 || typeof record.text !== "string") {
|
|
96
|
+
throw new TypeError("Every document must have a nonempty string id and string text");
|
|
97
|
+
}
|
|
98
|
+
if (record.embedding === void 0) return void 0;
|
|
99
|
+
const vector = unitVector(record.embedding, dimension);
|
|
100
|
+
dimension ??= vector.length;
|
|
101
|
+
return vector.some((value) => value !== 0) ? vector : void 0;
|
|
102
|
+
});
|
|
103
|
+
if (limit === 0 || documents.length === 0) return [];
|
|
104
|
+
const queryTokens = new Set(tokenize(query));
|
|
105
|
+
const tokenized = documents.map((record) => tokenize(record.text));
|
|
106
|
+
const frequencies = tokenized.map((tokens) => {
|
|
107
|
+
const counts = /* @__PURE__ */ new Map();
|
|
108
|
+
for (const token of tokens) counts.set(token, (counts.get(token) ?? 0) + 1);
|
|
109
|
+
return counts;
|
|
110
|
+
});
|
|
111
|
+
const documentFrequency = /* @__PURE__ */ new Map();
|
|
112
|
+
for (const counts of frequencies) {
|
|
113
|
+
for (const token of counts.keys()) {
|
|
114
|
+
documentFrequency.set(token, (documentFrequency.get(token) ?? 0) + 1);
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
const averageLength = tokenized.reduce((sum, tokens) => sum + tokens.length, 0) / (documents.length || 1);
|
|
118
|
+
const candidates = documents.map((record, index) => {
|
|
119
|
+
let lexical = 0;
|
|
120
|
+
for (const token of queryTokens) {
|
|
121
|
+
const frequency = frequencies[index].get(token) ?? 0;
|
|
122
|
+
if (frequency === 0) continue;
|
|
123
|
+
const df = documentFrequency.get(token);
|
|
124
|
+
const idf = Math.log(1 + (documents.length - df + 0.5) / (df + 0.5));
|
|
125
|
+
const norm = tokenized[index].length / (averageLength || 1);
|
|
126
|
+
lexical += idf * (frequency * 2.2) / (frequency + 1.2 * (0.25 + 0.75 * norm));
|
|
127
|
+
}
|
|
128
|
+
const lexicalNormalized = lexical / (1 + lexical);
|
|
129
|
+
const semantic = cosine(queryVector, vectors[index]);
|
|
130
|
+
const relevance = lexicalWeight / totalWeight * lexicalNormalized + semanticWeight / totalWeight * semantic;
|
|
131
|
+
return { record, tokens: new Set(tokenized[index]), vector: vectors[index], scores: {
|
|
132
|
+
lexical,
|
|
133
|
+
lexicalNormalized,
|
|
134
|
+
semantic,
|
|
135
|
+
relevance,
|
|
136
|
+
redundancy: 0,
|
|
137
|
+
mmr: relevance
|
|
138
|
+
} };
|
|
139
|
+
}).filter(({ scores }) => scores.relevance > 0);
|
|
140
|
+
return rerank(candidates, limit, diversity);
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
// src/orchestration/memory/gate.ts
|
|
144
|
+
var EVIDENCE_KEYS = ["measurementId", "digest", "candidateDigests", "noMemory", "memory", "fullHistory"];
|
|
145
|
+
var SHA256 = /^[a-f0-9]{64}$/;
|
|
146
|
+
var UNPRINTABLE = /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u;
|
|
147
|
+
var MAX_CANDIDATES = 64;
|
|
148
|
+
function plainObject(value, keys, name) {
|
|
149
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
150
|
+
throw new TypeError(`${name} must be an object`);
|
|
151
|
+
}
|
|
152
|
+
const own = Object.keys(value);
|
|
153
|
+
if (own.length !== keys.length || own.some((key) => !keys.includes(key))) {
|
|
154
|
+
throw new TypeError(`${name} must have exactly: ${keys.join(", ")}`);
|
|
155
|
+
}
|
|
156
|
+
return value;
|
|
157
|
+
}
|
|
158
|
+
function label(value, name) {
|
|
159
|
+
if (typeof value !== "string" || !value.trim() || value.length > 128 || UNPRINTABLE.test(value)) {
|
|
160
|
+
throw new TypeError(`${name} must be a nonempty printable string of at most 128 characters`);
|
|
161
|
+
}
|
|
162
|
+
return value;
|
|
163
|
+
}
|
|
164
|
+
function tally(value, name) {
|
|
165
|
+
const { passed, total } = plainObject(value, ["passed", "total"], name);
|
|
166
|
+
if (!Number.isSafeInteger(passed) || !Number.isSafeInteger(total)) {
|
|
167
|
+
throw new TypeError(`${name} must hold integer counts`);
|
|
168
|
+
}
|
|
169
|
+
if (total < 1 || passed < 0 || passed > total) {
|
|
170
|
+
throw new RangeError(`${name} must satisfy 0 <= passed <= total and total >= 1`);
|
|
171
|
+
}
|
|
172
|
+
return { passed, total };
|
|
173
|
+
}
|
|
174
|
+
function assertMemoryGateEvidence(value) {
|
|
175
|
+
const evidence = plainObject(value, EVIDENCE_KEYS, "gate evidence");
|
|
176
|
+
const measurementId = label(evidence.measurementId, "measurementId");
|
|
177
|
+
if (typeof evidence.digest !== "string" || !SHA256.test(evidence.digest)) {
|
|
178
|
+
throw new TypeError("digest must be a SHA-256 hex digest");
|
|
179
|
+
}
|
|
180
|
+
const candidates = evidence.candidateDigests;
|
|
181
|
+
if (!Array.isArray(candidates) || candidates.length < 1 || candidates.length > MAX_CANDIDATES || new Set(candidates).size !== candidates.length || candidates.some((candidate) => typeof candidate !== "string" || !SHA256.test(candidate))) {
|
|
182
|
+
throw new TypeError(`candidateDigests must list 1 to ${MAX_CANDIDATES} distinct record content digests`);
|
|
183
|
+
}
|
|
184
|
+
const candidateDigests = [...candidates];
|
|
185
|
+
const noMemory = tally(evidence.noMemory, "noMemory");
|
|
186
|
+
const memory = tally(evidence.memory, "memory");
|
|
187
|
+
const fullHistory = tally(evidence.fullHistory, "fullHistory");
|
|
188
|
+
if (noMemory.total !== memory.total || fullHistory.total !== memory.total) {
|
|
189
|
+
throw new RangeError("The three conditions must have run the same task set");
|
|
190
|
+
}
|
|
191
|
+
return { measurementId, digest: evidence.digest, candidateDigests, noMemory, memory, fullHistory };
|
|
192
|
+
}
|
|
193
|
+
function evaluateMemoryGate(evidence) {
|
|
194
|
+
const checked = assertMemoryGateEvidence(evidence);
|
|
195
|
+
if (checked.memory.passed > checked.noMemory.passed) return { passed: true };
|
|
196
|
+
return { passed: false, reason: "NO_GAIN_OVER_NO_MEMORY" };
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
// src/orchestration/memory/agent-provider.ts
|
|
200
|
+
var MAX_QUERY_TEXT = 4096;
|
|
201
|
+
var EPISODE_MAX_BYTES = 6 * 1024;
|
|
202
|
+
var RENDERED_INDENT = 4;
|
|
203
|
+
var LINE_BREAK = /^[\n\r\u000b\u000c\u0085\u2028\u2029]$/;
|
|
204
|
+
var WHITESPACE = /^\s$/u;
|
|
205
|
+
var MARK_BYTES = 2;
|
|
206
|
+
var MAX_NAME = 128;
|
|
207
|
+
var SOURCE = "agent-turn";
|
|
208
|
+
var PROPOSAL_SOURCE = "agent-proposal";
|
|
209
|
+
var UNPRINTABLE2 = /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u;
|
|
210
|
+
function memoryProviderFromPorts(options) {
|
|
211
|
+
const config = captureProviderOptions(options);
|
|
212
|
+
const provider = { id: config.id };
|
|
213
|
+
const { recall: port, persistence } = config;
|
|
214
|
+
if (port) provider.recall = (request) => recallThrough(port, config, request);
|
|
215
|
+
if (persistence) {
|
|
216
|
+
provider.capture = (request) => captureThrough(persistence, config, request);
|
|
217
|
+
if (!port || config.captureGate === "store-promotes") provider.propose = (request) => proposeThrough(persistence, config, request);
|
|
218
|
+
}
|
|
219
|
+
const { profile } = config;
|
|
220
|
+
if (profile) provider.profile = (request) => profile(request);
|
|
221
|
+
return Object.freeze(provider);
|
|
222
|
+
}
|
|
223
|
+
function captureProviderOptions(options) {
|
|
224
|
+
if (!options || typeof options !== "object") throw new TypeError("memoryProviderFromPorts needs an options object");
|
|
225
|
+
const { id = "memory-ports", recall, persistence, embedder, toRecord, now, captureGate, profile } = options;
|
|
226
|
+
if (!isName(id)) throw new TypeError("id must be a nonblank printable string of at most 128 characters");
|
|
227
|
+
if (recall === void 0 && persistence === void 0) {
|
|
228
|
+
throw new TypeError("memoryProviderFromPorts needs a recall port, a persistence port, or both");
|
|
229
|
+
}
|
|
230
|
+
if (recall !== void 0 && persistence !== void 0) {
|
|
231
|
+
if (captureGate !== "store-promotes" && captureGate !== "none-acknowledged") {
|
|
232
|
+
throw new TypeError(
|
|
233
|
+
"With both recall and persistence, captureGate must be 'store-promotes' (recall returns only promoted lessons) or 'none-acknowledged' (a captured turn may be recalled unreviewed on the next turn)"
|
|
234
|
+
);
|
|
235
|
+
}
|
|
236
|
+
} else if (captureGate !== void 0) {
|
|
237
|
+
throw new TypeError("captureGate applies only when both recall and persistence are given");
|
|
238
|
+
}
|
|
239
|
+
if (recall !== void 0 && typeof recall?.query !== "function") throw new TypeError("recall must implement query()");
|
|
240
|
+
if (persistence !== void 0 && typeof persistence?.put !== "function") throw new TypeError("persistence must implement put()");
|
|
241
|
+
if (toRecord !== void 0 && typeof toRecord !== "function") throw new TypeError("toRecord must be a function");
|
|
242
|
+
if (now !== void 0 && typeof now !== "function") throw new TypeError("now must be a function");
|
|
243
|
+
if (profile !== void 0 && typeof profile !== "function") throw new TypeError("profile must be a function");
|
|
244
|
+
const config = { id, now: now ?? (() => /* @__PURE__ */ new Date()) };
|
|
245
|
+
if (recall) config.recall = recall;
|
|
246
|
+
if (persistence) config.persistence = persistence;
|
|
247
|
+
if (toRecord) config.toRecord = toRecord;
|
|
248
|
+
if (profile) config.profile = profile;
|
|
249
|
+
if (captureGate) config.captureGate = captureGate;
|
|
250
|
+
if (embedder !== void 0) {
|
|
251
|
+
if (typeof embedder?.embed !== "function") throw new TypeError("embedder must implement embed()");
|
|
252
|
+
assertIdentity(embedder.identity);
|
|
253
|
+
config.embedder = embedder;
|
|
254
|
+
}
|
|
255
|
+
return config;
|
|
256
|
+
}
|
|
257
|
+
function identityOf({ identity }) {
|
|
258
|
+
return { provider: identity.provider, model: identity.model, revision: identity.revision, dimensions: identity.dimensions };
|
|
259
|
+
}
|
|
260
|
+
function assertIdentity(identity) {
|
|
261
|
+
const { provider, model, revision, dimensions } = identity ?? {};
|
|
262
|
+
if (![provider, model, revision].every(isName)) {
|
|
263
|
+
throw new TypeError("embedder.identity needs provider, model and revision names");
|
|
264
|
+
}
|
|
265
|
+
if (!Number.isSafeInteger(dimensions) || dimensions < 1) {
|
|
266
|
+
throw new TypeError("embedder.identity.dimensions must be a positive integer");
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
async function embed(embedder, text, signal) {
|
|
270
|
+
const vectors = await abortable(embedder.embed([text], signal), signal);
|
|
271
|
+
const { dimensions } = embedder.identity;
|
|
272
|
+
const vector = Array.isArray(vectors) && vectors.length === 1 ? vectors[0] : void 0;
|
|
273
|
+
if (!Array.isArray(vector) || vector.length !== dimensions || vector.some((value) => typeof value !== "number" || !Number.isFinite(value))) {
|
|
274
|
+
throw new RangeError(`The embedder must return one vector of ${dimensions} finite numbers per text`);
|
|
275
|
+
}
|
|
276
|
+
return Object.freeze([...vector]);
|
|
277
|
+
}
|
|
278
|
+
async function recallThrough(port, config, request) {
|
|
279
|
+
const { embedder } = config;
|
|
280
|
+
const { signal } = request;
|
|
281
|
+
signal?.throwIfAborted();
|
|
282
|
+
const limit = request.limit;
|
|
283
|
+
if (!Number.isSafeInteger(limit) || limit < 0) throw new RangeError("limit must be a nonnegative integer");
|
|
284
|
+
if (limit === 0) return [];
|
|
285
|
+
const scope = scopeOf(request.scope);
|
|
286
|
+
const text = clip(typeof request.text === "string" ? request.text : "", MAX_QUERY_TEXT);
|
|
287
|
+
const query = { scope, text, limit };
|
|
288
|
+
if (signal) query.signal = signal;
|
|
289
|
+
if (embedder) query.embedding = { identity: identityOf(embedder), values: await embed(embedder, text, signal) };
|
|
290
|
+
const records = await abortable(port.query(query), signal);
|
|
291
|
+
signal?.throwIfAborted();
|
|
292
|
+
if (!Array.isArray(records)) throw new TypeError("The recall port must return an array of records");
|
|
293
|
+
const now = config.now().getTime();
|
|
294
|
+
const recalled = [];
|
|
295
|
+
const seen = /* @__PURE__ */ new Set();
|
|
296
|
+
for (const record of records) {
|
|
297
|
+
if (recalled.length === limit) break;
|
|
298
|
+
const item = recalledOf(record, scope, now);
|
|
299
|
+
if (!item || seen.has(item.id)) continue;
|
|
300
|
+
seen.add(item.id);
|
|
301
|
+
recalled.push(item);
|
|
302
|
+
}
|
|
303
|
+
return Object.freeze(recalled);
|
|
304
|
+
}
|
|
305
|
+
function recalledOf(record, scope, now) {
|
|
306
|
+
if (!record || typeof record !== "object" || record.revokedAt !== void 0) return void 0;
|
|
307
|
+
if (!sameScope(record.scope, scope) || expired(record.validUntil, now)) return void 0;
|
|
308
|
+
const provenance = record.provenance ?? {};
|
|
309
|
+
const metadata = record.metadata;
|
|
310
|
+
const title = metadata && typeof metadata === "object" && !Array.isArray(metadata) ? metadata.title : void 0;
|
|
311
|
+
const base = { id: record.id, text: record.text, source: provenance.source, ...title === void 0 ? {} : { title } };
|
|
312
|
+
const item = (provenance.observedAt === void 0 ? void 0 : recallableMemory({ ...base, observedAt: provenance.observedAt })) ?? recallableMemory(base);
|
|
313
|
+
return item && Object.freeze(item);
|
|
314
|
+
}
|
|
315
|
+
async function captureThrough(persistence, config, request) {
|
|
316
|
+
const { signal } = request;
|
|
317
|
+
signal?.throwIfAborted();
|
|
318
|
+
const scope = scopeOf(request.scope);
|
|
319
|
+
const record = config.toRecord ? await abortable(Promise.resolve(config.toRecord(request)), signal) : await defaultRecord(config, request, scope);
|
|
320
|
+
if (record === void 0) return;
|
|
321
|
+
if (!record || typeof record !== "object" || !sameScope(record.scope, scope)) {
|
|
322
|
+
throw new TypeError("A captured record must belong to the scope of the capture request");
|
|
323
|
+
}
|
|
324
|
+
signal?.throwIfAborted();
|
|
325
|
+
await abortable(persistence.put(record, signal), signal);
|
|
326
|
+
}
|
|
327
|
+
function expired(validUntil, now) {
|
|
328
|
+
if (validUntil === void 0) return false;
|
|
329
|
+
const until = typeof validUntil === "string" ? Date.parse(validUntil) : Number.NaN;
|
|
330
|
+
return Number.isNaN(until) || until < now;
|
|
331
|
+
}
|
|
332
|
+
async function proposeThrough(persistence, config, request) {
|
|
333
|
+
const { signal } = request;
|
|
334
|
+
signal?.throwIfAborted();
|
|
335
|
+
const scope = scopeOf(request.scope);
|
|
336
|
+
if (!isName(request.origin)) throw new TypeError("A proposal needs an origin of at most 128 printable characters");
|
|
337
|
+
const text = typeof request.text === "string" ? request.text : "";
|
|
338
|
+
if (!text.trim() || !recallableMemory({ id: "proposal", source: PROPOSAL_SOURCE, text })) {
|
|
339
|
+
throw new TypeError("A proposal needs text the agent could recall");
|
|
340
|
+
}
|
|
341
|
+
if (renderedBytes(text) > EPISODE_MAX_BYTES - RENDERED_INDENT) {
|
|
342
|
+
throw new TypeError(`A proposal must fit ${EPISODE_MAX_BYTES} bytes as the agent renders it; it is refused, never cut`);
|
|
343
|
+
}
|
|
344
|
+
const textHash = await sha256(text);
|
|
345
|
+
const id = `${PROPOSAL_SOURCE}-${await sha256(JSON.stringify([scope.tenant, scope.namespace, scope.subject ?? null, textHash]))}`;
|
|
346
|
+
signal?.throwIfAborted();
|
|
347
|
+
const metadata = { origin: request.origin };
|
|
348
|
+
if (isName(request.title)) metadata.title = request.title;
|
|
349
|
+
const record = {
|
|
350
|
+
id,
|
|
351
|
+
scope,
|
|
352
|
+
text,
|
|
353
|
+
provenance: { source: PROPOSAL_SOURCE, sourceVersion: request.origin, observedAt: config.now().toISOString(), inputHash: textHash },
|
|
354
|
+
metadata
|
|
355
|
+
};
|
|
356
|
+
if (config.embedder) record.embedding = { identity: identityOf(config.embedder), values: await embed(config.embedder, text, signal) };
|
|
357
|
+
signal?.throwIfAborted();
|
|
358
|
+
try {
|
|
359
|
+
await abortable(persistence.put(record, signal), signal);
|
|
360
|
+
} catch (error) {
|
|
361
|
+
if (error?.code !== "CONFLICT" || signal?.aborted) throw error;
|
|
362
|
+
if (!await storedText(persistence, scope, id, text, signal)) throw error;
|
|
363
|
+
}
|
|
364
|
+
return Object.freeze({ id });
|
|
365
|
+
}
|
|
366
|
+
async function storedText(persistence, scope, id, text, signal) {
|
|
367
|
+
if (typeof persistence.get !== "function") return false;
|
|
368
|
+
const stored = await abortable(persistence.get({ scope, id, ...signal ? { signal } : {} }), signal);
|
|
369
|
+
signal?.throwIfAborted();
|
|
370
|
+
return !!stored && typeof stored === "object" && stored.id === id && sameScope(stored.scope, scope) && stored.text === text;
|
|
371
|
+
}
|
|
372
|
+
async function defaultRecord(config, request, scope) {
|
|
373
|
+
const { turn, signal } = request;
|
|
374
|
+
if (!turn || turn.status !== "completed") return void 0;
|
|
375
|
+
const input = typeof request.input === "string" ? request.input : "";
|
|
376
|
+
const answer = typeof turn.text === "string" ? turn.text : "";
|
|
377
|
+
if (!input.trim() && !answer.trim()) return void 0;
|
|
378
|
+
const text = episodeText(input, answer);
|
|
379
|
+
const session = turn.session;
|
|
380
|
+
const provider = isName(session?.provider) ? session.provider : "unknown";
|
|
381
|
+
const model = isName(session?.model) ? session.model : void 0;
|
|
382
|
+
const sessionId = [session?.sessionId, session?.id].find(isName);
|
|
383
|
+
const turnId = isName(turn.id) ? turn.id : void 0;
|
|
384
|
+
const inputHash = await sha256(JSON.stringify([input, answer]));
|
|
385
|
+
signal?.throwIfAborted();
|
|
386
|
+
const observedAt = typeof request.completedAt === "string" ? request.completedAt : config.now().toISOString();
|
|
387
|
+
const key = turnId ? ["turn", sessionId ?? "", turnId] : ["content", sessionId ?? "", inputHash, observedAt];
|
|
388
|
+
const metadata = { provider };
|
|
389
|
+
if (isName(session?.transport)) metadata.transport = session.transport;
|
|
390
|
+
if (sessionId) metadata.sessionId = sessionId;
|
|
391
|
+
if (turnId) metadata.turnId = turnId;
|
|
392
|
+
const record = {
|
|
393
|
+
id: `${SOURCE}-${await sha256(JSON.stringify(key))}`,
|
|
394
|
+
scope,
|
|
395
|
+
text,
|
|
396
|
+
provenance: {
|
|
397
|
+
source: SOURCE,
|
|
398
|
+
sourceVersion: model && `${provider}/${model}`.length <= MAX_NAME ? `${provider}/${model}` : provider,
|
|
399
|
+
observedAt,
|
|
400
|
+
inputHash
|
|
401
|
+
},
|
|
402
|
+
metadata
|
|
403
|
+
};
|
|
404
|
+
if (config.embedder) record.embedding = { identity: identityOf(config.embedder), values: await embed(config.embedder, text, signal) };
|
|
405
|
+
return record;
|
|
406
|
+
}
|
|
407
|
+
function episodeText(input, answer) {
|
|
408
|
+
const head = "User:\n";
|
|
409
|
+
const middle = "\n\nAssistant:\n";
|
|
410
|
+
const budget = EPISODE_MAX_BYTES - RENDERED_INDENT - renderedBytes(head) - renderedBytes(middle);
|
|
411
|
+
const inputBudget = Math.max(budget - renderedBytes(answer), Math.floor(budget / 2));
|
|
412
|
+
const asked = clipRendered(input, inputBudget);
|
|
413
|
+
return `${head}${asked}${middle}${clipRendered(answer, budget - renderedBytes(asked))}`;
|
|
414
|
+
}
|
|
415
|
+
function renderedCost(char, afterWhitespace) {
|
|
416
|
+
const point = char.codePointAt(0);
|
|
417
|
+
const bytes = point < 128 ? 1 : point < 2048 ? 2 : point < 65536 ? 3 : 4;
|
|
418
|
+
if (LINE_BREAK.test(char)) return bytes + RENDERED_INDENT;
|
|
419
|
+
if (WHITESPACE.test(char)) return afterWhitespace ? 0 : MARK_BYTES;
|
|
420
|
+
return bytes;
|
|
421
|
+
}
|
|
422
|
+
function* renderedCosts(text) {
|
|
423
|
+
let afterWhitespace = false;
|
|
424
|
+
for (const char of text) {
|
|
425
|
+
yield [char, renderedCost(char, afterWhitespace)];
|
|
426
|
+
afterWhitespace = !LINE_BREAK.test(char) && WHITESPACE.test(char);
|
|
427
|
+
}
|
|
428
|
+
}
|
|
429
|
+
function renderedBytes(text) {
|
|
430
|
+
let total = 0;
|
|
431
|
+
for (const [, cost] of renderedCosts(text)) total += cost;
|
|
432
|
+
return total;
|
|
433
|
+
}
|
|
434
|
+
function clipRendered(text, maximum) {
|
|
435
|
+
let total = 0;
|
|
436
|
+
let end = 0;
|
|
437
|
+
for (const [char, cost] of renderedCosts(text)) {
|
|
438
|
+
total += cost;
|
|
439
|
+
if (total > maximum) break;
|
|
440
|
+
end += char.length;
|
|
441
|
+
}
|
|
442
|
+
return text.slice(0, end);
|
|
443
|
+
}
|
|
444
|
+
function clip(text, maximum) {
|
|
445
|
+
if (text.length <= maximum) return text;
|
|
446
|
+
const cut = text.slice(0, maximum);
|
|
447
|
+
const last = cut.charCodeAt(cut.length - 1);
|
|
448
|
+
return last >= 55296 && last <= 56319 ? cut.slice(0, -1) : cut;
|
|
449
|
+
}
|
|
450
|
+
function scopeOf(scope) {
|
|
451
|
+
if (!scope || typeof scope !== "object") throw new TypeError("A memory request needs a scope");
|
|
452
|
+
const result = { tenant: scope.tenant, namespace: scope.namespace };
|
|
453
|
+
if (scope.subject !== void 0) result.subject = scope.subject;
|
|
454
|
+
return result;
|
|
455
|
+
}
|
|
456
|
+
function sameScope(candidate, scope) {
|
|
457
|
+
if (!candidate || typeof candidate !== "object") return false;
|
|
458
|
+
const other = candidate;
|
|
459
|
+
return other.tenant === scope.tenant && other.namespace === scope.namespace && other.subject === scope.subject;
|
|
460
|
+
}
|
|
461
|
+
function isName(value) {
|
|
462
|
+
return typeof value === "string" && value.length <= MAX_NAME && value.trim() === value && value !== "" && !UNPRINTABLE2.test(value);
|
|
463
|
+
}
|
|
464
|
+
async function sha256(value) {
|
|
465
|
+
const bytes = new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(value)));
|
|
466
|
+
return Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
467
|
+
}
|
|
468
|
+
function abortable(work, signal) {
|
|
469
|
+
if (!signal) return work;
|
|
470
|
+
if (signal.aborted) {
|
|
471
|
+
work.catch(() => {
|
|
472
|
+
});
|
|
473
|
+
return Promise.reject(signal.reason);
|
|
474
|
+
}
|
|
475
|
+
return new Promise((resolve, reject) => {
|
|
476
|
+
const onAbort = () => reject(signal.reason);
|
|
477
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
478
|
+
work.then(
|
|
479
|
+
(value) => {
|
|
480
|
+
signal.removeEventListener("abort", onAbort);
|
|
481
|
+
resolve(value);
|
|
482
|
+
},
|
|
483
|
+
(error) => {
|
|
484
|
+
signal.removeEventListener("abort", onAbort);
|
|
485
|
+
reject(error);
|
|
486
|
+
}
|
|
487
|
+
);
|
|
488
|
+
});
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
// src/orchestration/memory/mcp-recipes.ts
|
|
492
|
+
var PRERELEASE_ID = "(?:0|[1-9]\\d*|\\d*[A-Za-z-][0-9A-Za-z-]*)";
|
|
493
|
+
var EXACT_SEMVER = new RegExp(
|
|
494
|
+
`^(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)(?:-${PRERELEASE_ID}(?:\\.${PRERELEASE_ID})*)?$`
|
|
495
|
+
);
|
|
496
|
+
var SERVER_NAME = /^[A-Za-z0-9_-]{1,64}$/;
|
|
497
|
+
var AGENTDB_PROFILES = ["readonly", "retrieval", "learning"];
|
|
498
|
+
var RUVECTOR_PROFILES = ["readonly", "unrestricted"];
|
|
499
|
+
function plainOptions(value, allowed, label2) {
|
|
500
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) throw new TypeError(`${label2} options must be an object.`);
|
|
501
|
+
const unknown = Object.keys(value).filter((key) => !allowed.includes(key));
|
|
502
|
+
if (unknown.length) throw new TypeError(`${label2} options do not accept: ${unknown.join(", ")}.`);
|
|
503
|
+
return value;
|
|
504
|
+
}
|
|
505
|
+
function exactVersion(value, label2) {
|
|
506
|
+
if (typeof value !== "string" || !EXACT_SEMVER.test(value)) {
|
|
507
|
+
throw new TypeError(`${label2} version must be an exact semver such as 1.2.3; ranges, tags and latest are refused.`);
|
|
508
|
+
}
|
|
509
|
+
return value;
|
|
510
|
+
}
|
|
511
|
+
function isAbsolutePath(value) {
|
|
512
|
+
return typeof value === "string" && !value.includes("\0") && value.trim() === value && (/^\//.test(value) || /^[A-Za-z]:[\\/]/.test(value) || /^\\\\[^\\]/.test(value));
|
|
513
|
+
}
|
|
514
|
+
function absolutePath(value, label2) {
|
|
515
|
+
if (!isAbsolutePath(value)) throw new TypeError(`${label2} must be an absolute path.`);
|
|
516
|
+
return value;
|
|
517
|
+
}
|
|
518
|
+
function serverName(value, fallback) {
|
|
519
|
+
const name = value ?? fallback;
|
|
520
|
+
if (typeof name !== "string" || !SERVER_NAME.test(name)) {
|
|
521
|
+
throw new TypeError('MCP server name must be 1-64 letters, digits, "_" or "-".');
|
|
522
|
+
}
|
|
523
|
+
return name;
|
|
524
|
+
}
|
|
525
|
+
function profileOf(value, profiles, label2) {
|
|
526
|
+
if (typeof value !== "string" || !profiles.includes(value)) {
|
|
527
|
+
throw new TypeError(`${label2} profile must be one of: ${profiles.join(", ")}.`);
|
|
528
|
+
}
|
|
529
|
+
return value;
|
|
530
|
+
}
|
|
531
|
+
var LAUNCH_KEYS = ["version", "executable"];
|
|
532
|
+
function launch(input, pkg, label2, serverArgs) {
|
|
533
|
+
const hasVersion = input.version !== void 0;
|
|
534
|
+
if (hasVersion === (input.executable !== void 0)) {
|
|
535
|
+
throw new TypeError(`${label2} needs exactly one of version (npx) or executable (pre-installed binary).`);
|
|
536
|
+
}
|
|
537
|
+
if (hasVersion) return ["npx", ["-y", `${pkg}@${exactVersion(input.version, label2)}`, ...serverArgs]];
|
|
538
|
+
return [absolutePath(input.executable, `${label2} executable`), serverArgs];
|
|
539
|
+
}
|
|
540
|
+
function freezeRecipe(name, [command, args], env) {
|
|
541
|
+
return Object.freeze({
|
|
542
|
+
name,
|
|
543
|
+
command,
|
|
544
|
+
args: Object.freeze(args),
|
|
545
|
+
env: Object.freeze(env)
|
|
546
|
+
});
|
|
547
|
+
}
|
|
548
|
+
function agentDbMcpServer(options) {
|
|
549
|
+
const input = plainOptions(options, [...LAUNCH_KEYS, "databasePath", "profile", "name"], "AgentDB");
|
|
550
|
+
const command = launch(input, "agentdb", "AgentDB", ["mcp", "start"]);
|
|
551
|
+
const databasePath = absolutePath(input.databasePath, "AgentDB databasePath");
|
|
552
|
+
const profile = profileOf(input.profile, AGENTDB_PROFILES, "AgentDB");
|
|
553
|
+
return freezeRecipe(
|
|
554
|
+
serverName(input.name, "agentdb"),
|
|
555
|
+
command,
|
|
556
|
+
{ AGENTDB_PATH: databasePath, AGENTDB_MCP_PROFILE: profile }
|
|
557
|
+
);
|
|
558
|
+
}
|
|
559
|
+
function ruvectorMcpServer(options) {
|
|
560
|
+
const input = plainOptions(options, [...LAUNCH_KEYS, "profile", "name", "sharedStoreAcknowledged"], "RuVector");
|
|
561
|
+
const command = launch(input, "ruvector", "RuVector", ["mcp", "start"]);
|
|
562
|
+
const profile = profileOf(input.profile, RUVECTOR_PROFILES, "RuVector");
|
|
563
|
+
const acknowledged = input.sharedStoreAcknowledged;
|
|
564
|
+
if (acknowledged !== void 0 && typeof acknowledged !== "boolean") {
|
|
565
|
+
throw new TypeError("RuVector sharedStoreAcknowledged must be true or false.");
|
|
566
|
+
}
|
|
567
|
+
if (profile === "unrestricted" && acknowledged !== true) {
|
|
568
|
+
throw new TypeError("RuVector unrestricted writes to a store shared per working directory or home, not per agent; pass sharedStoreAcknowledged: true to accept that.");
|
|
569
|
+
}
|
|
570
|
+
return freezeRecipe(
|
|
571
|
+
serverName(input.name, "ruvector"),
|
|
572
|
+
command,
|
|
573
|
+
profile === "readonly" ? { RUVECTOR_MCP_PROFILE: "readonly" } : {}
|
|
574
|
+
);
|
|
575
|
+
}
|
|
576
|
+
function claudeMcpConfig(recipes) {
|
|
577
|
+
if (!Array.isArray(recipes) || recipes.length === 0) throw new TypeError("claudeMcpConfig needs at least one recipe.");
|
|
578
|
+
const servers = {};
|
|
579
|
+
for (const recipe of recipes) {
|
|
580
|
+
if (!recipe || typeof recipe !== "object") throw new TypeError("Each MCP recipe must be an object.");
|
|
581
|
+
const { name, command, args, env } = recipe;
|
|
582
|
+
const checked = serverName(name, "");
|
|
583
|
+
if (Object.hasOwn(servers, checked)) throw new TypeError(`Duplicate MCP server name: ${checked}.`);
|
|
584
|
+
if (!(command === "npx" || isAbsolutePath(command)) || !Array.isArray(args) || !args.every((arg) => typeof arg === "string") || !env || typeof env !== "object" || Array.isArray(env) || !Object.values(env).every((value) => typeof value === "string")) {
|
|
585
|
+
throw new TypeError(`MCP recipe ${checked} is malformed.`);
|
|
586
|
+
}
|
|
587
|
+
servers[checked] = { command, args: [...args], env: { ...env } };
|
|
588
|
+
}
|
|
589
|
+
return JSON.stringify({ mcpServers: servers });
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
export {
|
|
593
|
+
rankMemories,
|
|
594
|
+
assertMemoryGateEvidence,
|
|
595
|
+
evaluateMemoryGate,
|
|
596
|
+
memoryProviderFromPorts,
|
|
597
|
+
agentDbMcpServer,
|
|
598
|
+
ruvectorMcpServer,
|
|
599
|
+
claudeMcpConfig
|
|
600
|
+
};
|
|
601
|
+
//# sourceMappingURL=chunk-WMKO5XOE.js.map
|