hiveagents-runtime 0.0.0-stage → 0.1.0-beta.3

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 (115) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +89 -2
  3. package/dist/adapter-kit.d.ts +37 -0
  4. package/dist/adapter-kit.js +34 -0
  5. package/dist/adapter-kit.js.map +1 -0
  6. package/dist/agent-Bj5YPrO7.d.ts +169 -0
  7. package/dist/agent-D6OXR7UF.js +24 -0
  8. package/dist/agent-D6OXR7UF.js.map +1 -0
  9. package/dist/agent-readiness-KSGNKTGK.js +19 -0
  10. package/dist/agent-readiness-KSGNKTGK.js.map +1 -0
  11. package/dist/capture-runtime-GP6NZ2ee.d.ts +54 -0
  12. package/dist/chunk-2RK74GCA.js +2397 -0
  13. package/dist/chunk-2RK74GCA.js.map +1 -0
  14. package/dist/chunk-3TIYA3K5.js +55 -0
  15. package/dist/chunk-3TIYA3K5.js.map +1 -0
  16. package/dist/chunk-6FIXXWNM.js +1 -0
  17. package/dist/chunk-6FIXXWNM.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-CPN4DOXH.js +115 -0
  23. package/dist/chunk-CPN4DOXH.js.map +1 -0
  24. package/dist/chunk-DAXPAV2L.js +810 -0
  25. package/dist/chunk-DAXPAV2L.js.map +1 -0
  26. package/dist/chunk-DQEMIGKC.js +291 -0
  27. package/dist/chunk-DQEMIGKC.js.map +1 -0
  28. package/dist/chunk-DZFFGUIA.js +81 -0
  29. package/dist/chunk-DZFFGUIA.js.map +1 -0
  30. package/dist/chunk-EEUYQFCP.js +106 -0
  31. package/dist/chunk-EEUYQFCP.js.map +1 -0
  32. package/dist/chunk-G6JV7WV6.js +521 -0
  33. package/dist/chunk-G6JV7WV6.js.map +1 -0
  34. package/dist/chunk-GFVYNPLS.js +118 -0
  35. package/dist/chunk-GFVYNPLS.js.map +1 -0
  36. package/dist/chunk-GS5U3KUN.js +201 -0
  37. package/dist/chunk-GS5U3KUN.js.map +1 -0
  38. package/dist/chunk-HB7FBSH2.js +960 -0
  39. package/dist/chunk-HB7FBSH2.js.map +1 -0
  40. package/dist/chunk-HZFZX5A3.js +21 -0
  41. package/dist/chunk-HZFZX5A3.js.map +1 -0
  42. package/dist/chunk-J7VAYJKM.js +595 -0
  43. package/dist/chunk-J7VAYJKM.js.map +1 -0
  44. package/dist/chunk-NCNSHOF7.js +52 -0
  45. package/dist/chunk-NCNSHOF7.js.map +1 -0
  46. package/dist/chunk-RH5A5U7G.js +202 -0
  47. package/dist/chunk-RH5A5U7G.js.map +1 -0
  48. package/dist/chunk-RX3XZENU.js +385 -0
  49. package/dist/chunk-RX3XZENU.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-TG7NTMTR.js +208 -0
  53. package/dist/chunk-TG7NTMTR.js.map +1 -0
  54. package/dist/chunk-TWGEYWMO.js +1217 -0
  55. package/dist/chunk-TWGEYWMO.js.map +1 -0
  56. package/dist/chunk-UZPDDQVJ.js +2910 -0
  57. package/dist/chunk-UZPDDQVJ.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/chunk-WVT5SEKC.js +581 -0
  63. package/dist/chunk-WVT5SEKC.js.map +1 -0
  64. package/dist/cli.d.ts +1 -0
  65. package/dist/cli.js +26 -0
  66. package/dist/cli.js.map +1 -0
  67. package/dist/errors-BNHvvjn9.d.ts +98 -0
  68. package/dist/execution-halt-B8G0fOKS.d.ts +12 -0
  69. package/dist/execution-types-ClYYqPQP.d.ts +239 -0
  70. package/dist/host-ledger-VPRWVVOS.js +25 -0
  71. package/dist/host-ledger-VPRWVVOS.js.map +1 -0
  72. package/dist/hosted-runtime.d.ts +168 -0
  73. package/dist/hosted-runtime.js +858 -0
  74. package/dist/hosted-runtime.js.map +1 -0
  75. package/dist/index-B86C6VAD.d.ts +41 -0
  76. package/dist/index.d.ts +344 -0
  77. package/dist/index.js +8825 -0
  78. package/dist/index.js.map +1 -0
  79. package/dist/memory-items-BSTC0_R0.d.ts +28 -0
  80. package/dist/memory-tools.d.ts +222 -0
  81. package/dist/memory-tools.js +923 -0
  82. package/dist/memory-tools.js.map +1 -0
  83. package/dist/orchestration/dynamic.d.ts +854 -0
  84. package/dist/orchestration/dynamic.js +3150 -0
  85. package/dist/orchestration/dynamic.js.map +1 -0
  86. package/dist/orchestration/graph.d.ts +11 -0
  87. package/dist/orchestration/graph.js +9 -0
  88. package/dist/orchestration/graph.js.map +1 -0
  89. package/dist/orchestration/index.d.ts +2385 -0
  90. package/dist/orchestration/index.js +6409 -0
  91. package/dist/orchestration/index.js.map +1 -0
  92. package/dist/orchestration/log.d.ts +301 -0
  93. package/dist/orchestration/log.js +3058 -0
  94. package/dist/orchestration/log.js.map +1 -0
  95. package/dist/orchestration/memory.d.ts +711 -0
  96. package/dist/orchestration/memory.js +27 -0
  97. package/dist/orchestration/memory.js.map +1 -0
  98. package/dist/provider-DX5Mf0uq.d.ts +151 -0
  99. package/dist/routing/index.d.ts +29 -0
  100. package/dist/routing/index.js +386 -0
  101. package/dist/routing/index.js.map +1 -0
  102. package/dist/routing/learning/index.d.ts +433 -0
  103. package/dist/routing/learning/index.js +2502 -0
  104. package/dist/routing/learning/index.js.map +1 -0
  105. package/dist/runtime-BSjrnxeF.d.ts +283 -0
  106. package/dist/runtime-OISPXS4I.js +19 -0
  107. package/dist/runtime-OISPXS4I.js.map +1 -0
  108. package/dist/store-types-2YdceOMy.d.ts +78 -0
  109. package/dist/types-BB7KqceP.d.ts +52 -0
  110. package/dist/types-CIqkKXix.d.ts +86 -0
  111. package/dist/types-DTFc1qO6.d.ts +1065 -0
  112. package/dist/types-DYex3p7_.d.ts +88 -0
  113. package/docs/licenses/ruflo-memory-MIT.txt +21 -0
  114. package/docs/releases/0.1.0-beta.3.md +13 -0
  115. package/package.json +114 -4
@@ -0,0 +1,595 @@
1
+ import {
2
+ projectAgentEvent,
3
+ validateEvent,
4
+ validateUsage
5
+ } from "./chunk-GS5U3KUN.js";
6
+ import {
7
+ canonical,
8
+ freeze,
9
+ hash,
10
+ identifier,
11
+ jsonClone,
12
+ method,
13
+ object
14
+ } from "./chunk-EEUYQFCP.js";
15
+ import {
16
+ ExecutionHaltedError,
17
+ isExecutionHalted
18
+ } from "./chunk-NCNSHOF7.js";
19
+
20
+ // src/orchestration/log/store-types.ts
21
+ var errors = /* @__PURE__ */ new WeakSet();
22
+ var LogStoreError = class extends Error {
23
+ code;
24
+ constructor(code) {
25
+ const safe = ["INVALID_INPUT", "INTEGRITY", "STORAGE", "CLOSED", "BUSY", "REQUEST_CONFLICT", "PAYLOAD_UNAVAILABLE", "TRANSACTION_REQUIRED", "UNSUPPORTED_RUNTIME"].includes(code) ? code : "INVALID_INPUT";
26
+ super(`Invalid execution log: ${safe}`);
27
+ this.code = safe;
28
+ this.name = "LogStoreError";
29
+ errors.add(this);
30
+ Object.freeze(this);
31
+ }
32
+ };
33
+ function isLogStoreError(value) {
34
+ return !!value && typeof value === "object" && errors.has(value);
35
+ }
36
+ function logError(code) {
37
+ throw new LogStoreError(code);
38
+ }
39
+ function safeFailure(error) {
40
+ if (isLogStoreError(error)) throw error;
41
+ return logError("STORAGE");
42
+ }
43
+
44
+ // src/orchestration/log/capture-codec.ts
45
+ import { types as types2 } from "node:util";
46
+
47
+ // src/orchestration/log/validation.ts
48
+ import { types } from "node:util";
49
+ var LOG_FORMAT_LIMITS = Object.freeze({
50
+ depth: 64,
51
+ nodes: 65536,
52
+ records: 256,
53
+ causal: 64,
54
+ envelopeBytes: 16384,
55
+ inlineBytes: 65536,
56
+ batchInlineBytes: 1048576,
57
+ batchBytes: 6 * 1048576
58
+ });
59
+ function invalid() {
60
+ throw new TypeError("Invalid execution log data");
61
+ }
62
+ var byteLength = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype), "byteLength").get;
63
+ function bounded(input) {
64
+ let nodes = 0, bytes = 0;
65
+ const ancestors = /* @__PURE__ */ new Set();
66
+ function visit(value, depth) {
67
+ if (++nodes > LOG_FORMAT_LIMITS.nodes || depth > LOG_FORMAT_LIMITS.depth) invalid();
68
+ if (typeof value === "string") {
69
+ bytes += Buffer.byteLength(value);
70
+ if (bytes > LOG_FORMAT_LIMITS.batchBytes || Buffer.from(value).toString("utf8") !== value) invalid();
71
+ return;
72
+ }
73
+ if (value === null || typeof value === "boolean" || typeof value === "number" && Number.isFinite(value)) return;
74
+ if (!value || typeof value !== "object" || types.isProxy(value) || ancestors.has(value)) invalid();
75
+ if (Array.isArray(value) && value.length > LOG_FORMAT_LIMITS.nodes) invalid();
76
+ const proto = Object.getPrototypeOf(value);
77
+ if (Array.isArray(value) ? proto !== Array.prototype : proto !== Object.prototype && proto !== null) invalid();
78
+ if (Object.getOwnPropertySymbols(value).length) invalid();
79
+ ancestors.add(value);
80
+ for (const [key, descriptor] of Object.entries(Object.getOwnPropertyDescriptors(value))) {
81
+ if (Array.isArray(value) && key === "length") continue;
82
+ if (!Object.hasOwn(descriptor, "value") || !descriptor.enumerable) invalid();
83
+ bytes += Buffer.byteLength(key);
84
+ if (bytes > LOG_FORMAT_LIMITS.batchBytes || Buffer.from(key).toString("utf8") !== key) invalid();
85
+ visit(descriptor.value, depth + 1);
86
+ }
87
+ ancestors.delete(value);
88
+ }
89
+ visit(input, 0);
90
+ }
91
+ function closed(value, fields) {
92
+ object(value, fields);
93
+ if (fields.some((field2) => !Object.hasOwn(value, field2))) invalid();
94
+ }
95
+ function positive(value, zero = false) {
96
+ if (!Number.isSafeInteger(value) || value < (zero ? 0 : 1)) invalid();
97
+ }
98
+ function captureLogCommit(input) {
99
+ try {
100
+ bounded(input);
101
+ const commit = jsonClone(input);
102
+ closed(commit, ["requestId", "records"]);
103
+ identifier(commit.requestId);
104
+ if (!Array.isArray(commit.records) || !commit.records.length || commit.records.length > LOG_FORMAT_LIMITS.records) invalid();
105
+ let totalInline = 0;
106
+ for (const draft of commit.records) {
107
+ closed(draft, ["identity", "schema", "type", "causal", "payload"]);
108
+ identifier(draft.type);
109
+ closed(draft.identity, ["systemId", "generation", "runId", "agentId", "harness"]);
110
+ for (const key of ["systemId", "runId", "agentId"]) identifier(draft.identity[key]);
111
+ positive(draft.identity.generation);
112
+ closed(draft.identity.harness, ["id", "version", "digest"]);
113
+ identifier(draft.identity.harness.id);
114
+ identifier(draft.identity.harness.version);
115
+ hash(draft.identity.harness.digest);
116
+ closed(draft.schema, ["id", "version"]);
117
+ identifier(draft.schema.id);
118
+ positive(draft.schema.version);
119
+ if (!Array.isArray(draft.causal) || draft.causal.length > LOG_FORMAT_LIMITS.causal) invalid();
120
+ for (const position of draft.causal) {
121
+ closed(position, ["sourceId", "sequence", "digest"]);
122
+ identifier(position.sourceId);
123
+ positive(position.sequence);
124
+ hash(position.digest);
125
+ }
126
+ object(draft.payload, ["inline", "artifact"]);
127
+ if (Object.keys(draft.payload).length !== 1) invalid();
128
+ if (Object.hasOwn(draft.payload, "inline")) {
129
+ const bytes = Buffer.byteLength(canonical(draft.payload.inline));
130
+ totalInline += bytes;
131
+ if (bytes > LOG_FORMAT_LIMITS.inlineBytes || totalInline > LOG_FORMAT_LIMITS.batchInlineBytes) invalid();
132
+ } else {
133
+ const ref = draft.payload.artifact;
134
+ closed(ref, ["sourceId", "systemId", "generation", "digest", "bytes", "mediaType"]);
135
+ identifier(ref.sourceId);
136
+ identifier(ref.systemId);
137
+ positive(ref.generation);
138
+ positive(ref.bytes, true);
139
+ hash(ref.digest);
140
+ if (ref.systemId !== draft.identity.systemId || ref.generation !== draft.identity.generation || ref.mediaType !== "application/json" && ref.mediaType !== "application/octet-stream") invalid();
141
+ }
142
+ const { payload: _, ...envelope } = draft;
143
+ if (Buffer.byteLength(canonical(envelope)) > LOG_FORMAT_LIMITS.envelopeBytes) invalid();
144
+ }
145
+ if (Buffer.byteLength(canonical(commit)) > LOG_FORMAT_LIMITS.batchBytes) invalid();
146
+ return freeze(commit);
147
+ } catch {
148
+ return invalid();
149
+ }
150
+ }
151
+
152
+ // src/orchestration/log/encoding.ts
153
+ import { createHash } from "node:crypto";
154
+ var MAX_EVENT_BYTES = 128 * 1024;
155
+ function digest(text) {
156
+ return createHash("sha256").update(text).digest("hex");
157
+ }
158
+ function genesis(source) {
159
+ return digest(`oar-neutral-log-v1
160
+ ${canonical(source)}`);
161
+ }
162
+ function capture(input, source) {
163
+ try {
164
+ const captured = captureLogCommit(input);
165
+ for (const record of captured.records) if (record.identity.systemId !== source.systemId || "artifact" in record.payload && record.payload.artifact.sourceId !== source.sourceId) logError("INVALID_INPUT");
166
+ return captured;
167
+ } catch {
168
+ return logError("INVALID_INPUT");
169
+ }
170
+ }
171
+ function entryBody(source, sequence, requestId, ordinal, previousDigest, record) {
172
+ return { format: 1, sourceId: source.sourceId, sequence, requestId, ordinal, previousDigest, record };
173
+ }
174
+ function decodeEntry(text, expectedDigest, source) {
175
+ try {
176
+ if (Buffer.byteLength(text) > MAX_EVENT_BYTES || digest(text) !== expectedDigest) logError("INTEGRITY");
177
+ const body = JSON.parse(text);
178
+ object(body, ["format", "sourceId", "sequence", "requestId", "ordinal", "previousDigest", "record"]);
179
+ if (Object.keys(body).length !== 7 || canonical(body) !== text || body.format !== 1 || body.sourceId !== source.sourceId || !Number.isSafeInteger(body.sequence) || Number(body.sequence) < 1 || !Number.isSafeInteger(body.ordinal) || Number(body.ordinal) < 1 || Number(body.ordinal) > 256) logError("INTEGRITY");
180
+ hash(body.previousDigest);
181
+ const checked = capture({ requestId: body.requestId, records: [body.record] }, source);
182
+ return freeze({
183
+ format: 1,
184
+ sourceId: source.sourceId,
185
+ sequence: Number(body.sequence),
186
+ requestId: checked.requestId,
187
+ ordinal: Number(body.ordinal),
188
+ previousDigest: body.previousDigest,
189
+ record: checked.records[0],
190
+ digest: expectedDigest
191
+ });
192
+ } catch {
193
+ return logError("INTEGRITY");
194
+ }
195
+ }
196
+
197
+ // src/orchestration/log/capture-codec.ts
198
+ var AGENT_METADATA_SCHEMA = "oar.sdk.agent-event-metadata";
199
+ var CAPTURE_OPERATION_SCHEMA = "oar.sdk.capture-operation";
200
+ var eventTypes = [
201
+ "session.started",
202
+ "turn.started",
203
+ "message.delta",
204
+ "message.completed",
205
+ "tool.started",
206
+ "tool.updated",
207
+ "tool.completed",
208
+ "subagent.started",
209
+ "subagent.completed",
210
+ "interaction.requested",
211
+ "context.compacted",
212
+ "turn.completed",
213
+ "provider.event"
214
+ ];
215
+ var usageKeys = ["inputTokens", "outputTokens", "cachedInputTokens", "cacheCreationTokens", "reportedCostUsd"];
216
+ var eventKeys = ["type", "sessionId", "turnId", "status", "count", "toolId", "subagentId", "interactionId", "usage"];
217
+ function invalidCapture() {
218
+ throw new TypeError("Invalid required log capture");
219
+ }
220
+ function field(value, key) {
221
+ if (!value || typeof value !== "object" || types2.isProxy(value) || Array.isArray(value) || ![Object.prototype, null].includes(Object.getPrototypeOf(value))) return invalidCapture();
222
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
223
+ if (!descriptor) return void 0;
224
+ if (!Object.hasOwn(descriptor, "value")) return invalidCapture();
225
+ return descriptor.value;
226
+ }
227
+ function boundedInteger(value, min, max) {
228
+ if (!Number.isSafeInteger(value) || Number(value) < min || Number(value) > max) invalidCapture();
229
+ return value;
230
+ }
231
+ function boundedDataArray(input, max) {
232
+ if (types2.isProxy(input) || !Array.isArray(input) || Object.getPrototypeOf(input) !== Array.prototype || input.length > max || Object.getOwnPropertySymbols(input).length) invalidCapture();
233
+ const descriptors = Object.getOwnPropertyDescriptors(input);
234
+ if (Object.keys(descriptors).length !== input.length + 1) invalidCapture();
235
+ for (let i = 0; i < input.length; i++) {
236
+ const d = descriptors[String(i)];
237
+ if (!d || !Object.hasOwn(d, "value") || !d.enumerable) invalidCapture();
238
+ }
239
+ return input;
240
+ }
241
+ function idDigest(value) {
242
+ if (typeof value !== "string" || !value.trim() || value.length > 4096 || Buffer.from(value).toString("utf8") !== value) invalidCapture();
243
+ return digest(value);
244
+ }
245
+ function captureIdentity(input) {
246
+ return captureLogCommit({ requestId: "capture-validation", records: [{ identity: input, schema: { id: CAPTURE_OPERATION_SCHEMA, version: 1 }, type: "capture.started", causal: [], payload: { inline: null } }] }).records[0].identity;
247
+ }
248
+ function captureReceipt(input, sourceId) {
249
+ object(input, ["first", "head", "count"]);
250
+ if (input.count !== 1) invalidCapture();
251
+ for (const value of [input.first, input.head]) {
252
+ object(value, ["sourceId", "sequence", "digest"]);
253
+ if (typeof value.sourceId !== "string" || !value.sourceId || value.sourceId.length > 128 || sourceId !== void 0 && value.sourceId !== sourceId) invalidCapture();
254
+ boundedInteger(value.sequence, 1, Number.MAX_SAFE_INTEGER);
255
+ hash(value.digest);
256
+ }
257
+ if (canonical(input.first) !== canonical(input.head)) invalidCapture();
258
+ return freeze({ first: { ...input.first }, head: { ...input.head }, count: 1 });
259
+ }
260
+ function captureActual(input) {
261
+ object(input, ["provider", "model", "attemptId", "transport", "phase", "sessionId", "transportEpoch"]);
262
+ if (input.transport !== void 0 && !["exec", "control"].includes(input.transport) || input.phase !== void 0 && !["startup", "turn"].includes(input.phase)) invalidCapture();
263
+ return freeze({ providerDigest: idDigest(input.provider), ...input.model === void 0 ? {} : { modelDigest: idDigest(input.model) }, attemptDigest: idDigest(input.attemptId), ...input.transport === void 0 ? {} : { transport: input.transport }, ...input.phase === void 0 ? {} : { phase: input.phase }, ...input.sessionId === void 0 ? {} : { sessionIdDigest: idDigest(input.sessionId) }, ...input.transportEpoch === void 0 ? {} : { transportEpochDigest: idDigest(input.transportEpoch) } });
264
+ }
265
+ function safeUsage(input) {
266
+ object(input, [...usageKeys, "costMeaning", "perModel"]);
267
+ const copy = {};
268
+ for (const key of [...usageKeys, "costMeaning"]) if (Object.hasOwn(input, key)) copy[key] = input[key];
269
+ if (Object.hasOwn(input, "perModel")) {
270
+ object(input.perModel);
271
+ const names = Object.keys(input.perModel);
272
+ if (names.length > 32) invalidCapture();
273
+ const models = /* @__PURE__ */ Object.create(null);
274
+ for (const name of names) {
275
+ object(input.perModel[name], usageKeys);
276
+ models[idDigest(name)] = { ...input.perModel[name] };
277
+ }
278
+ copy.perModel = models;
279
+ }
280
+ return freeze(validateUsage(copy));
281
+ }
282
+ function optionalId(input, key) {
283
+ const value = field(input, key);
284
+ return value === void 0 ? {} : { [key]: idDigest(value) };
285
+ }
286
+ function captureAgentEvent(input) {
287
+ const type = field(input, "type");
288
+ if (typeof type !== "string" || !eventTypes.includes(type)) invalidCapture();
289
+ let safe;
290
+ switch (type) {
291
+ case "session.started":
292
+ safe = { type, session: { id: idDigest(field(field(input, "session"), "id")) } };
293
+ break;
294
+ case "turn.started":
295
+ safe = { type, ...optionalId(input, "turnId") };
296
+ break;
297
+ case "message.delta":
298
+ case "message.completed": {
299
+ const text = field(input, "text");
300
+ if (typeof text !== "string") invalidCapture();
301
+ safe = { type, text };
302
+ break;
303
+ }
304
+ case "tool.started":
305
+ case "tool.updated":
306
+ case "tool.completed":
307
+ case "subagent.started":
308
+ case "subagent.completed":
309
+ safe = { type, id: idDigest(field(input, "id")) };
310
+ break;
311
+ case "interaction.requested": {
312
+ const binding = field(field(input, "request"), "binding");
313
+ safe = { type, request: { binding: { interactionId: idDigest(field(binding, "interactionId")), sessionId: idDigest(field(binding, "sessionId")), ...optionalId(binding, "turnId") } } };
314
+ break;
315
+ }
316
+ case "turn.completed": {
317
+ const turn = field(input, "turn"), usage = field(turn, "usage");
318
+ safe = { type, turn: { ...optionalId(turn, "id"), status: field(turn, "status"), session: { id: idDigest(field(field(turn, "session"), "id")) }, ...usage === void 0 ? {} : { usage: safeUsage(usage) } } };
319
+ break;
320
+ }
321
+ default:
322
+ safe = { type };
323
+ }
324
+ return freeze(projectAgentEvent(safe));
325
+ }
326
+ function captureSessionBinding(event) {
327
+ const type = field(event, "type"), session = type === "session.started" ? field(event, "session") : type === "turn.completed" ? field(field(event, "turn"), "session") : void 0;
328
+ if (session === void 0 || field(session, "schemaVersion") === void 0) return void 0;
329
+ const fields = ["schemaVersion", "id", "provider", "model", "cwd", "transport", "persistence", "transportEpoch", "createdAt"];
330
+ const copy = {};
331
+ for (const key of fields) {
332
+ const value = field(session, key);
333
+ if (key === "model" && value === void 0) continue;
334
+ copy[key] = value;
335
+ }
336
+ if (copy.schemaVersion !== 1 || !["exec", "control"].includes(copy.transport) || !["provider", "process"].includes(copy.persistence)) invalidCapture();
337
+ for (const key of ["id", "provider", "cwd", "transportEpoch", "createdAt"]) idDigest(copy[key]);
338
+ if (copy.model !== void 0) idDigest(copy.model);
339
+ return freeze({ bindingDigest: digest(canonical(copy)), sessionIdDigest: idDigest(copy.id), transportEpochDigest: idDigest(copy.transportEpoch), providerDigest: idDigest(copy.provider), ...copy.model === void 0 ? {} : { modelDigest: idDigest(copy.model) }, transport: copy.transport, persistence: copy.persistence });
340
+ }
341
+ function validateActual(input) {
342
+ object(input, ["providerDigest", "modelDigest", "attemptDigest", "transport", "phase", "sessionIdDigest", "transportEpochDigest"]);
343
+ hash(input.providerDigest);
344
+ hash(input.attemptDigest);
345
+ for (const key of ["modelDigest", "sessionIdDigest", "transportEpochDigest"]) if (input[key] !== void 0) hash(input[key]);
346
+ if (input.transport !== void 0 && !["exec", "control"].includes(input.transport) || input.phase !== void 0 && !["startup", "turn"].includes(input.phase)) invalidCapture();
347
+ return input;
348
+ }
349
+ function decodeCaptureMetadata(schema, type, input) {
350
+ object(input, schema === AGENT_METADATA_SCHEMA ? ["mode", "invocationDigest", "actual", "event", "sessionBinding"] : ["mode", "invocationDigest", "actual", "stage", "outcome", "usage"]);
351
+ if (input.mode !== "metadata-only") invalidCapture();
352
+ hash(input.invocationDigest);
353
+ validateActual(input.actual);
354
+ if (schema === AGENT_METADATA_SCHEMA) {
355
+ object(input.event, eventKeys);
356
+ if (!eventTypes.includes(input.event.type) || input.event.type !== type) invalidCapture();
357
+ for (const key of ["sessionId", "turnId", "toolId", "subagentId", "interactionId"]) if (input.event[key] !== void 0) hash(input.event[key]);
358
+ if (input.event.status !== void 0 && !["completed", "failed", "interrupted", "refused"].includes(input.event.status)) invalidCapture();
359
+ const required = { "session.started": ["sessionId"], "message.delta": ["count"], "message.completed": ["count"], "tool.started": ["toolId"], "tool.updated": ["toolId"], "tool.completed": ["toolId"], "subagent.started": ["subagentId"], "subagent.completed": ["subagentId"], "interaction.requested": ["interactionId", "sessionId"], "turn.completed": ["sessionId", "status"] };
360
+ const allowed = ["type", ...required[type] ?? [], ...type === "turn.started" || type === "turn.completed" || type === "interaction.requested" ? ["turnId"] : [], ...type === "turn.completed" ? ["usage"] : []];
361
+ object(input.event, allowed);
362
+ for (const key of required[type] ?? []) if (!Object.hasOwn(input.event, key)) invalidCapture();
363
+ if (input.event.usage !== void 0) validateEncodedUsage(input.event.usage);
364
+ if (input.sessionBinding !== void 0) {
365
+ const binding = input.sessionBinding;
366
+ object(binding, ["bindingDigest", "sessionIdDigest", "transportEpochDigest", "providerDigest", "modelDigest", "transport", "persistence"]);
367
+ for (const key of ["bindingDigest", "sessionIdDigest", "transportEpochDigest", "providerDigest"]) hash(binding[key]);
368
+ if (binding.modelDigest !== void 0) hash(binding.modelDigest);
369
+ if (!["exec", "control"].includes(binding.transport) || !["provider", "process"].includes(binding.persistence) || binding.sessionIdDigest !== input.event.sessionId) invalidCapture();
370
+ }
371
+ validateEvent(input.event);
372
+ } else {
373
+ if (schema !== CAPTURE_OPERATION_SCHEMA || !["started", "settled", "interrupted"].includes(input.stage) || type !== `capture.${input.stage}`) invalidCapture();
374
+ if (input.stage === "started" ? input.outcome !== void 0 || input.usage !== void 0 : !["returned", "failed", "halted"].includes(input.outcome)) invalidCapture();
375
+ if (input.usage !== void 0) validateEncodedUsage(input.usage);
376
+ }
377
+ if (Buffer.byteLength(canonical(input)) > 16384) invalidCapture();
378
+ return freeze(input);
379
+ }
380
+ function validateEncodedUsage(input) {
381
+ object(input, [...usageKeys, "costMeaning", "perModel"]);
382
+ if (input.perModel !== void 0) {
383
+ object(input.perModel);
384
+ for (const key of Object.keys(input.perModel)) {
385
+ hash(key);
386
+ object(input.perModel[key], usageKeys);
387
+ }
388
+ }
389
+ validateUsage(input);
390
+ }
391
+
392
+ // src/orchestration/log/capture.ts
393
+ import { randomBytes } from "node:crypto";
394
+ import { types as types4 } from "node:util";
395
+
396
+ // src/orchestration/log/capture-writes.ts
397
+ import { types as types3 } from "node:util";
398
+ var aborted = Object.getOwnPropertyDescriptor(AbortSignal.prototype, "aborted").get;
399
+ var reason = Object.getOwnPropertyDescriptor(AbortSignal.prototype, "reason").get;
400
+ function captureWriteOptions(input) {
401
+ const maxWriteMs = boundedInteger(input.maxWriteMs ?? 5e3, 1, 3e4), signal = input.signal;
402
+ if (signal !== void 0) {
403
+ if (types3.isProxy(signal)) invalidCapture();
404
+ try {
405
+ Reflect.apply(aborted, signal, []);
406
+ } catch {
407
+ invalidCapture();
408
+ }
409
+ }
410
+ return { maxWriteMs, signal };
411
+ }
412
+ function awaitCaptureWrite(work, maxWriteMs, signal, halt) {
413
+ return new Promise((resolve, reject) => {
414
+ let settled = false, timer;
415
+ const clean = () => {
416
+ if (timer) clearTimeout(timer);
417
+ if (signal) EventTarget.prototype.removeEventListener.call(signal, "abort", cancel);
418
+ };
419
+ const complete = (callback) => {
420
+ if (settled) return;
421
+ settled = true;
422
+ clean();
423
+ callback();
424
+ };
425
+ const cancel = () => complete(() => reject(halt(signal ? Reflect.apply(reason, signal, []) : Error("CAPTURE_WRITE_INTERRUPTED"))));
426
+ work.then((value) => complete(() => resolve(value)), (error) => complete(() => reject(error)));
427
+ if (signal && Reflect.apply(aborted, signal, [])) {
428
+ cancel();
429
+ return;
430
+ }
431
+ if (signal) EventTarget.prototype.addEventListener.call(signal, "abort", cancel, { once: true });
432
+ timer = setTimeout(() => complete(() => reject(halt(Error("CAPTURE_WRITE_TIMEOUT")))), maxWriteMs);
433
+ });
434
+ }
435
+
436
+ // src/orchestration/log/capture.ts
437
+ function createRequiredLogCapture(options) {
438
+ object(options, ["store", "identity", "actual", "maxPending", "maxWriteMs", "signal"]);
439
+ const { maxWriteMs, signal } = captureWriteOptions(options);
440
+ const identity = captureIdentity(options.identity), actual = captureActual(options.actual), maxPending = boundedInteger(options.maxPending ?? 2, 1, 64);
441
+ const append = method(options.store, "append");
442
+ const invocationDigest = randomBytes(32).toString("hex"), controller = new AbortController();
443
+ const pending = /* @__PURE__ */ new Set();
444
+ let state = "idle";
445
+ let failure, usage, sourceId, interrupted = false;
446
+ function halt(cause) {
447
+ if (!failure) {
448
+ failure = new ExecutionHaltedError({ ...usage ? { observedUsage: usage } : {} }, { cause });
449
+ state = "halted";
450
+ controller.abort(failure);
451
+ }
452
+ return failure;
453
+ }
454
+ function write(schema, type, metadata) {
455
+ if (failure) return observedRejection(failure);
456
+ if (pending.size >= maxPending) return observedRejection(halt(Error("CAPTURE_CAPACITY")));
457
+ let operation;
458
+ try {
459
+ decodeCaptureMetadata(schema, type, metadata);
460
+ const commit = captureLogCommit({ requestId: randomBytes(24).toString("hex"), records: [{ identity, schema: { id: schema, version: 1 }, type, causal: [], payload: { inline: metadata } }] });
461
+ operation = Promise.resolve(append(commit));
462
+ } catch (error) {
463
+ return observedRejection(halt(error));
464
+ }
465
+ const tracked = operation.then((value) => {
466
+ const receipt = captureReceipt(value, sourceId);
467
+ sourceId = receipt.head.sourceId;
468
+ return receipt;
469
+ }).catch((error) => {
470
+ throw halt(error);
471
+ });
472
+ pending.add(tracked);
473
+ void tracked.then(() => pending.delete(tracked), () => pending.delete(tracked));
474
+ return awaitCaptureWrite(tracked, maxWriteMs, state === "draining" ? void 0 : signal, halt);
475
+ }
476
+ function observedRejection(error) {
477
+ const promise = Promise.reject(error);
478
+ void promise.catch(() => {
479
+ });
480
+ return promise;
481
+ }
482
+ async function drain() {
483
+ if (failure) throw failure;
484
+ while (pending.size) await awaitCaptureWrite(Promise.allSettled([...pending]), maxWriteMs, void 0, halt);
485
+ if (failure) throw failure;
486
+ }
487
+ function observe(event) {
488
+ if (state !== "running" || failure) return observedRejection(failure ?? halt(Error("CAPTURE_NOT_RUNNING")));
489
+ try {
490
+ const projected = captureAgentEvent(event);
491
+ if (projected.usage) usage = projected.usage;
492
+ const sessionBinding = captureSessionBinding(event);
493
+ return write(AGENT_METADATA_SCHEMA, projected.type, freeze({ mode: "metadata-only", invocationDigest, actual, event: projected, ...sessionBinding ? { sessionBinding } : {} }));
494
+ } catch (error) {
495
+ return observedRejection(halt(error));
496
+ }
497
+ }
498
+ async function run(work) {
499
+ if (state !== "idle" || typeof work !== "function" || types4.isProxy(work)) throw failure ?? halt(Error("CAPTURE_ALREADY_USED"));
500
+ state = "starting";
501
+ await write(CAPTURE_OPERATION_SCHEMA, "capture.started", freeze({ mode: "metadata-only", invocationDigest, actual, stage: "started" }));
502
+ if (failure) throw failure;
503
+ state = "running";
504
+ let result, original, failed = false;
505
+ try {
506
+ result = await work();
507
+ } catch (error) {
508
+ original = error;
509
+ failed = true;
510
+ const observed = errorUsage(error);
511
+ if (observed) usage = observed;
512
+ }
513
+ if (!failure) state = "draining";
514
+ let secondary;
515
+ try {
516
+ await drain();
517
+ const stage = interrupted ? "interrupted" : "settled";
518
+ await write(CAPTURE_OPERATION_SCHEMA, `capture.${stage}`, freeze({ mode: "metadata-only", invocationDigest, actual, stage, outcome: failed ? isExecutionHalted(original) ? "halted" : "failed" : "returned", ...usage ? { usage } : {} }));
519
+ } catch (error) {
520
+ secondary = error;
521
+ }
522
+ if (!secondary) state = "settled";
523
+ if (failed) {
524
+ if (secondary && !isExecutionHalted(original)) throw new ExecutionHaltedError({ ...usage ? { observedUsage: usage } : {} }, { cause: original });
525
+ throw original;
526
+ }
527
+ if (secondary) throw secondary;
528
+ state = "settled";
529
+ return result;
530
+ }
531
+ return Object.freeze({
532
+ run,
533
+ observe,
534
+ drain,
535
+ recordUsage: (input) => {
536
+ usage = safeUsage(input);
537
+ },
538
+ markInterrupted: () => {
539
+ interrupted = true;
540
+ },
541
+ signal: controller.signal,
542
+ snapshot: () => freeze({ state, pending: pending.size, maxPending, mode: "metadata-only", textReconstruction: "unavailable" })
543
+ });
544
+ }
545
+ function errorUsage(error) {
546
+ const pending = [{ value: error, depth: 0 }], seen = /* @__PURE__ */ new Set();
547
+ while (pending.length && seen.size < 64) {
548
+ const { value, depth } = pending.shift();
549
+ if (!value || typeof value !== "object" || types4.isProxy(value) || !types4.isNativeError(value) || seen.has(value) || depth >= 16) continue;
550
+ seen.add(value);
551
+ const context = Object.getOwnPropertyDescriptor(value, "context");
552
+ if (context && Object.hasOwn(context, "value") && context.value && typeof context.value === "object" && !types4.isProxy(context.value)) {
553
+ const observed = Object.getOwnPropertyDescriptor(context.value, "observedUsage");
554
+ if (observed && Object.hasOwn(observed, "value")) try {
555
+ return safeUsage(observed.value);
556
+ } catch {
557
+ }
558
+ }
559
+ const cause = Object.getOwnPropertyDescriptor(value, "cause");
560
+ if (cause && Object.hasOwn(cause, "value")) pending.push({ value: cause.value, depth: depth + 1 });
561
+ const errors2 = Object.getOwnPropertyDescriptor(value, "errors");
562
+ if (errors2 && Object.hasOwn(errors2, "value") && !types4.isProxy(errors2.value) && Array.isArray(errors2.value) && errors2.value.length <= 64 - pending.length) {
563
+ for (let i = 0; i < errors2.value.length; i++) {
564
+ const item = Object.getOwnPropertyDescriptor(errors2.value, String(i));
565
+ if (item && Object.hasOwn(item, "value")) pending.push({ value: item.value, depth: depth + 1 });
566
+ }
567
+ }
568
+ }
569
+ return void 0;
570
+ }
571
+
572
+ export {
573
+ captureLogCommit,
574
+ LogStoreError,
575
+ isLogStoreError,
576
+ logError,
577
+ safeFailure,
578
+ MAX_EVENT_BYTES,
579
+ digest,
580
+ genesis,
581
+ capture,
582
+ entryBody,
583
+ decodeEntry,
584
+ AGENT_METADATA_SCHEMA,
585
+ CAPTURE_OPERATION_SCHEMA,
586
+ invalidCapture,
587
+ field,
588
+ boundedInteger,
589
+ boundedDataArray,
590
+ captureIdentity,
591
+ safeUsage,
592
+ decodeCaptureMetadata,
593
+ createRequiredLogCapture
594
+ };
595
+ //# sourceMappingURL=chunk-J7VAYJKM.js.map