@statelyai/agent 2.0.0-alpha.22 → 2.0.0-alpha.24

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 (48) hide show
  1. package/dist/ai-sdk.cjs +53 -25
  2. package/dist/ai-sdk.d.cts +20 -12
  3. package/dist/ai-sdk.d.mts +20 -12
  4. package/dist/ai-sdk.mjs +53 -25
  5. package/dist/{decision-DxSTqzgZ.mjs → decision-BBZ2jMO1.mjs} +444 -79
  6. package/dist/{decision-1o45_ZrS.cjs → decision-Cv6SfNWl.cjs} +525 -94
  7. package/dist/index.cjs +2224 -1032
  8. package/dist/index.d.cts +413 -275
  9. package/dist/index.d.mts +413 -275
  10. package/dist/index.mjs +2163 -983
  11. package/dist/machines.cjs +30 -2
  12. package/dist/machines.d.cts +1 -1
  13. package/dist/machines.d.mts +1 -1
  14. package/dist/machines.mjs +30 -2
  15. package/dist/openai.cjs +447 -0
  16. package/dist/openai.d.cts +177 -0
  17. package/dist/openai.d.mts +177 -0
  18. package/dist/openai.mjs +437 -0
  19. package/dist/otel.cjs +3 -6
  20. package/dist/otel.d.cts +1 -1
  21. package/dist/otel.d.mts +1 -1
  22. package/dist/otel.mjs +3 -6
  23. package/dist/run-agent-Ck7Sa3Tb.d.mts +968 -0
  24. package/dist/run-agent-DWqA8KiI.d.cts +968 -0
  25. package/dist/setup-agent-CeO2fARv.mjs +639 -0
  26. package/dist/setup-agent-Dl2VELLi.cjs +663 -0
  27. package/dist/{text-logic-BaxPrcLk.d.cts → text-logic-C7bSnH_B.d.cts} +195 -44
  28. package/dist/{text-logic-DhfFWzu9.d.mts → text-logic-DJBK3LbG.d.mts} +195 -44
  29. package/dist/{types-DSdj2tGs.d.cts → types-CjHk5OdH.d.cts} +4 -19
  30. package/dist/{types-CvWRGFxP.d.mts → types-DWA6X9R-.d.mts} +4 -19
  31. package/package.json +17 -21
  32. package/readme.md +32 -17
  33. package/dist/errors-BQRk9eiZ.d.cts +0 -19
  34. package/dist/errors-C9rxnWbX.d.mts +0 -19
  35. package/dist/errors-CeSXQx0v.mjs +0 -23
  36. package/dist/errors-DUBBzRLP.cjs +0 -28
  37. package/dist/event-log-store-Bz7HDBkE.d.cts +0 -145
  38. package/dist/event-log-store-DmIDosD6.mjs +0 -427
  39. package/dist/event-log-store-a_TKy1gk.cjs +0 -468
  40. package/dist/event-log-store-hrA1vqtN.d.mts +0 -145
  41. package/dist/run-agent-0fpEZ1wJ.d.mts +0 -1098
  42. package/dist/run-agent-Zbkx7XP8.d.cts +0 -1098
  43. package/dist/setup-agent-DkCTy5Eu.cjs +0 -1707
  44. package/dist/setup-agent-nSFYrNTP.mjs +0 -1587
  45. package/dist/sqlite.cjs +0 -129
  46. package/dist/sqlite.d.cts +0 -57
  47. package/dist/sqlite.d.mts +0 -57
  48. package/dist/sqlite.mjs +0 -127
@@ -1,468 +0,0 @@
1
- const require_errors = require("./errors-DUBBzRLP.cjs");
2
- //#region src/event-log-store-conformance.ts
3
- /**
4
- * The runner-agnostic conformance suite for {@link AgentEventLogStore}
5
- * implementations. Split out of `event-log-store.ts` so the store contract and
6
- * the reference implementation stay readable; re-exported from there (and from
7
- * the package root) so the public surface is unchanged.
8
- * @module
9
- */
10
- function fail(message) {
11
- throw new Error(`event-log-store conformance: ${message}`);
12
- }
13
- function entry(index, type, metadata) {
14
- return {
15
- schemaVersion: 1,
16
- id: `evt_${index}`,
17
- index,
18
- recordedAt: "2026-01-01T00:00:00.000Z",
19
- machineId: "conformance",
20
- machineVersion: "v1",
21
- event: {
22
- type,
23
- seq: index
24
- },
25
- ...metadata !== void 0 ? { metadata } : {}
26
- };
27
- }
28
- function entriesFrom(start, count) {
29
- return Array.from({ length: count }, (_unused, i) => entry(start + i, `e${start + i}`));
30
- }
31
- function assertJsonEqual(actual, expected, message) {
32
- const a = JSON.stringify(actual);
33
- const b = JSON.stringify(expected);
34
- if (a !== b) fail(`${message} (expected ${b}, got ${a})`);
35
- }
36
- /**
37
- * Validates a store against the reference's semantics: empty read + zero length
38
- * for unknown threads; single and multi-entry append; contiguity misuse guard;
39
- * stale-`expectedIndex` conflict with correct fields; an interleaved concurrent
40
- * append race (exactly one winner); event-id uniqueness; `read({ from })`
41
- * incremental correctness; thread isolation; metadata round-trip; deep-copy
42
- * isolation on append and read; and the full fork contract.
43
- */
44
- async function assertEventLogStoreConformance(create) {
45
- {
46
- const store = await create();
47
- assertJsonEqual(await store.read("missing"), [], "read of an unknown thread must be empty");
48
- if (await store.length("missing") !== 0) fail("length of an unknown thread must be 0");
49
- }
50
- {
51
- const store = await create();
52
- const e = entry(0, "start", { label: "first" });
53
- await store.append({
54
- threadId: "t",
55
- expectedIndex: 0,
56
- entries: [e]
57
- });
58
- assertJsonEqual(await store.read("t"), [e], "read must return the appended entry");
59
- if (await store.length("t") !== 1) fail("length after a single append must be 1");
60
- }
61
- {
62
- const store = await create();
63
- await store.append({
64
- threadId: "t",
65
- expectedIndex: 0,
66
- entries: entriesFrom(0, 3)
67
- });
68
- await store.append({
69
- threadId: "t",
70
- expectedIndex: 3,
71
- entries: entriesFrom(3, 2)
72
- });
73
- if (await store.length("t") !== 5) fail("length after appending 3 then 2 entries must be 5");
74
- assertJsonEqual((await store.read("t")).map((e) => e.index), [
75
- 0,
76
- 1,
77
- 2,
78
- 3,
79
- 4
80
- ], "reads must return entries in contiguous log order");
81
- }
82
- {
83
- const store = await create();
84
- let caught;
85
- try {
86
- await store.append({
87
- threadId: "t",
88
- expectedIndex: 0,
89
- entries: [entry(1, "gap")]
90
- });
91
- } catch (error) {
92
- caught = error;
93
- }
94
- if (!(caught instanceof Error) || caught instanceof AgentEventLogConflictError) fail("a non-contiguous entry.index must throw a plain Error, not a conflict");
95
- }
96
- {
97
- const store = await create();
98
- await store.append({
99
- threadId: "t",
100
- expectedIndex: 0,
101
- entries: [entry(0, "a")]
102
- });
103
- let caught;
104
- try {
105
- await store.append({
106
- threadId: "t",
107
- expectedIndex: 0,
108
- entries: [entry(0, "b")]
109
- });
110
- } catch (error) {
111
- caught = error;
112
- }
113
- if (!(caught instanceof AgentEventLogConflictError)) fail("a stale expectedIndex must throw AgentEventLogConflictError");
114
- if (caught.threadId !== "t" || caught.expectedIndex !== 0 || caught.actualIndex !== 1) fail("conflict error must carry threadId, expectedIndex, and the actual index");
115
- }
116
- {
117
- const store = await create();
118
- await store.append({
119
- threadId: "t",
120
- expectedIndex: 0,
121
- entries: [entry(0, "a")]
122
- });
123
- let caught;
124
- try {
125
- await store.append({
126
- threadId: "t",
127
- expectedIndex: 1,
128
- entries: [{
129
- ...entry(1, "b"),
130
- id: "evt_0"
131
- }]
132
- });
133
- } catch (error) {
134
- caught = error;
135
- }
136
- if (!(caught instanceof Error) || caught instanceof AgentEventLogConflictError) fail("a duplicate event id within a thread must throw a plain Error");
137
- }
138
- {
139
- const store = await create();
140
- await store.append({
141
- threadId: "t",
142
- expectedIndex: 0,
143
- entries: [entry(0, "a")]
144
- });
145
- const results = await Promise.allSettled([store.append({
146
- threadId: "t",
147
- expectedIndex: 1,
148
- entries: [entry(1, "w-a")]
149
- }), store.append({
150
- threadId: "t",
151
- expectedIndex: 1,
152
- entries: [entry(1, "w-b")]
153
- })]);
154
- const winners = results.filter((r) => r.status === "fulfilled");
155
- const conflicts = results.filter((r) => r.status === "rejected" && r.reason instanceof AgentEventLogConflictError);
156
- if (winners.length !== 1) fail(`exactly one racing append must win, got ${winners.length}`);
157
- if (conflicts.length !== 1) fail(`exactly one racing append must reject with a conflict, got ${conflicts.length}`);
158
- if (await store.length("t") !== 2) fail("after the race the log length must be 2");
159
- }
160
- {
161
- const store = await create();
162
- await store.append({
163
- threadId: "t",
164
- expectedIndex: 0,
165
- entries: entriesFrom(0, 5)
166
- });
167
- assertJsonEqual((await store.read("t", { from: 2 })).map((e) => e.index), [
168
- 2,
169
- 3,
170
- 4
171
- ], "read({ from }) must skip entries below `from`");
172
- assertJsonEqual(await store.read("t", { from: 5 }), [], "read({ from }) at the log length must be empty");
173
- }
174
- {
175
- const store = await create();
176
- await store.append({
177
- threadId: "a",
178
- expectedIndex: 0,
179
- entries: [entry(0, "x")]
180
- });
181
- if (await store.length("b") !== 0) fail("an append to one thread must not create another");
182
- await store.append({
183
- threadId: "b",
184
- expectedIndex: 0,
185
- entries: entriesFrom(0, 2)
186
- });
187
- if (await store.length("a") !== 1 || await store.length("b") !== 2) fail("threads must grow independently");
188
- }
189
- {
190
- const store = await create();
191
- const metadata = {
192
- source: "user",
193
- nested: { attempt: 2 },
194
- tags: ["x", "y"]
195
- };
196
- await store.append({
197
- threadId: "t",
198
- expectedIndex: 0,
199
- entries: [entry(0, "e", metadata)]
200
- });
201
- assertJsonEqual((await store.read("t"))[0].metadata, metadata, "metadata must round-trip verbatim");
202
- }
203
- {
204
- const store = await create();
205
- const e = entry(0, "e", { tags: ["a"] });
206
- await store.append({
207
- threadId: "t",
208
- expectedIndex: 0,
209
- entries: [e]
210
- });
211
- e.metadata.tags.push("mutated-after-append");
212
- e.event.seq = 999;
213
- const read = await store.read("t");
214
- read[0].metadata.tags.push("mutated-after-read");
215
- read[0].event.seq = 888;
216
- const reread = await store.read("t");
217
- assertJsonEqual(reread[0].metadata, { tags: ["a"] }, "stored entry must be isolated from post-append and post-read mutation");
218
- assertJsonEqual(reread[0].event, {
219
- type: "e",
220
- seq: 0
221
- }, "stored event must be isolated from mutation of an appended or read copy");
222
- }
223
- {
224
- const store = await create();
225
- await store.append({
226
- threadId: "src",
227
- expectedIndex: 0,
228
- entries: entriesFrom(0, 3)
229
- });
230
- await store.fork({
231
- threadId: "src",
232
- newThreadId: "fork-full"
233
- });
234
- if (await store.length("fork-full") !== 3) fail("fork with the default upToIndex must copy the full log");
235
- await store.fork({
236
- threadId: "src",
237
- newThreadId: "fork-1",
238
- upToIndex: 1
239
- });
240
- assertJsonEqual((await store.read("fork-1")).map((e) => e.index), [0], "fork with upToIndex 1 must copy only entry 0");
241
- await store.fork({
242
- threadId: "src",
243
- newThreadId: "fork-2",
244
- upToIndex: 2
245
- });
246
- assertJsonEqual((await store.read("fork-2")).map((e) => e.id), ["evt_0", "evt_1"], "fork with upToIndex 2 must copy entries 0 and 1 only");
247
- await store.append({
248
- threadId: "fork-1",
249
- expectedIndex: 1,
250
- entries: [entry(1, "branch")]
251
- });
252
- assertJsonEqual((await store.read("fork-1")).map((e) => e.event.type), ["e0", "branch"], "a forked thread must append independently from its copied length");
253
- if (await store.length("src") !== 3) fail("appending to a fork must not touch the source thread");
254
- let caughtExisting;
255
- try {
256
- await store.fork({
257
- threadId: "src",
258
- newThreadId: "fork-full"
259
- });
260
- } catch (error) {
261
- caughtExisting = error;
262
- }
263
- if (!(caughtExisting instanceof Error) || caughtExisting instanceof AgentEventLogConflictError) fail("forking onto a non-empty thread must reject with a plain Error");
264
- let caughtUnknown;
265
- try {
266
- await store.fork({
267
- threadId: "nope",
268
- newThreadId: "fork-nope"
269
- });
270
- } catch (error) {
271
- caughtUnknown = error;
272
- }
273
- if (!(caughtUnknown instanceof Error) || caughtUnknown instanceof AgentEventLogConflictError) fail("forking an unknown source thread must reject with a plain Error");
274
- let caughtRange;
275
- try {
276
- await store.fork({
277
- threadId: "src",
278
- newThreadId: "fork-range",
279
- upToIndex: 99
280
- });
281
- } catch (error) {
282
- caughtRange = error;
283
- }
284
- if (!(caughtRange instanceof Error) || caughtRange instanceof AgentEventLogConflictError) fail("forking past the source length must reject with a plain Error");
285
- }
286
- }
287
- //#endregion
288
- //#region src/event-log-store.ts
289
- /** The durable replay-entry envelope version. */
290
- const AGENT_EVENT_SCHEMA_VERSION = 1;
291
- /** A precise failure when an entry would not survive a JSON round-trip. */
292
- var NonSerializableAgentEventError = class extends require_errors.AgentError {
293
- path;
294
- valueType;
295
- constructor(path, valueType) {
296
- super("non-serializable-event", `Agent event field '${path}' is not JSON-serializable (${valueType}).`);
297
- this.name = "NonSerializableAgentEventError";
298
- this.path = path;
299
- this.valueType = valueType;
300
- }
301
- };
302
- function assertNoHiddenKeys(value, path, isOwnKey) {
303
- const symbols = Object.getOwnPropertySymbols(value);
304
- if (symbols.length > 0) throw new NonSerializableAgentEventError(`${path}.[${String(symbols[0])}]`, "symbol key");
305
- const hiddenKey = Object.getOwnPropertyNames(value).find((key) => !isOwnKey?.(key) && !Object.getOwnPropertyDescriptor(value, key)?.enumerable);
306
- if (hiddenKey !== void 0) throw new NonSerializableAgentEventError(`${path}.${hiddenKey}`, "non-enumerable property");
307
- }
308
- const arrayIndexPattern = /^(?:0|[1-9]\d*)$/;
309
- /**
310
- * Rejects values JSON would drop or coerce. Unlike `JSON.stringify`, this does
311
- * not silently erase `undefined`/functions or turn non-finite numbers into
312
- * `null`; durable entries contain only plain JSON values.
313
- */
314
- function assertJsonSerializable(value, path = "entry", ancestors = /* @__PURE__ */ new WeakSet()) {
315
- if (value === null || typeof value === "string" || typeof value === "boolean") return;
316
- if (typeof value === "number") {
317
- if (!Number.isFinite(value) || Object.is(value, -0)) throw new NonSerializableAgentEventError(path, Object.is(value, -0) ? "-0" : String(value));
318
- return;
319
- }
320
- if (typeof value !== "object") throw new NonSerializableAgentEventError(path, typeof value);
321
- if (ancestors.has(value)) throw new NonSerializableAgentEventError(path, "circular reference");
322
- ancestors.add(value);
323
- try {
324
- if (Array.isArray(value)) {
325
- for (let index = 0; index < value.length; index++) {
326
- if (!Object.hasOwn(value, index)) throw new NonSerializableAgentEventError(`${path}[${index}]`, "array hole");
327
- assertJsonSerializable(value[index], `${path}[${index}]`, ancestors);
328
- }
329
- const extraKey = Object.keys(value).find((key) => !arrayIndexPattern.test(key) || Number(key) >= value.length);
330
- if (extraKey !== void 0) throw new NonSerializableAgentEventError(`${path}.${extraKey}`, "array property");
331
- assertNoHiddenKeys(value, path, (key) => key === "length" || arrayIndexPattern.test(key));
332
- return;
333
- }
334
- const prototype = Object.getPrototypeOf(value);
335
- if (prototype !== Object.prototype && prototype !== null) throw new NonSerializableAgentEventError(path, value.constructor?.name ?? "object");
336
- assertNoHiddenKeys(value, path);
337
- for (const [key, child] of Object.entries(value)) assertJsonSerializable(child, `${path}.${key}`, ancestors);
338
- } finally {
339
- ancestors.delete(value);
340
- }
341
- }
342
- function requireNonEmptyString(value, label, qualifier = "") {
343
- if (typeof value !== "string" || !value) throw new Error(`Agent event ${label} must be a non-empty string${qualifier}.`);
344
- }
345
- /** Validates the complete durable envelope before append/export/replay. */
346
- function assertAgentLogEntry(entry) {
347
- if (entry === null || typeof entry !== "object" || Array.isArray(entry)) throw new Error("Agent event entry must be an object.");
348
- assertJsonSerializable(entry);
349
- const candidate = entry;
350
- if (candidate.schemaVersion !== 1) throw new Error(`Unsupported agent event schema version '${String(candidate.schemaVersion)}'; expected '1'.`);
351
- if (!Number.isInteger(candidate.index) || candidate.index < 0) throw new Error(`Agent event entry.index must be a non-negative integer; got ${String(candidate.index)}.`);
352
- for (const field of [
353
- "id",
354
- "machineId",
355
- "machineVersion"
356
- ]) requireNonEmptyString(candidate[field], `entry.${field}`);
357
- if (typeof candidate.recordedAt !== "string" || !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/.test(candidate.recordedAt) || Number.isNaN(Date.parse(candidate.recordedAt))) throw new Error(`Agent event entry.recordedAt is not RFC 3339: '${String(candidate.recordedAt)}'.`);
358
- if (candidate.event === null || typeof candidate.event !== "object" || Array.isArray(candidate.event) || typeof candidate.event.type !== "string" || !candidate.event.type) throw new Error("Agent event entry.event requires a non-empty string type.");
359
- for (const field of ["causationId", "correlationId"]) if (candidate[field] !== void 0) requireNonEmptyString(candidate[field], `entry.${field}`, " when present");
360
- if (candidate.metadata !== void 0 && (candidate.metadata === null || typeof candidate.metadata !== "object" || Array.isArray(candidate.metadata))) throw new Error("Agent event entry.metadata must be an object when present.");
361
- if (candidate.verification !== void 0 && (candidate.verification === null || typeof candidate.verification !== "object" || typeof candidate.verification.stateHash !== "string" || !candidate.verification.stateHash || typeof candidate.verification.effectsHash !== "string" || !candidate.verification.effectsHash)) throw new Error("Agent event entry.verification requires non-empty stateHash and effectsHash strings.");
362
- }
363
- /**
364
- * Rejection from {@link AgentEventLogStore.append} when the thread's stored
365
- * length is not the `expectedIndex` the writer held — a concurrent writer
366
- * appended first. `actualIndex` is the next index the store would accept.
367
- */
368
- var AgentEventLogConflictError = class extends require_errors.AgentError {
369
- threadId;
370
- expectedIndex;
371
- actualIndex;
372
- constructor(threadId, expectedIndex, actualIndex) {
373
- super("event-log-conflict", `AgentEventLogStore.append: index conflict on thread "${threadId}": expected index ${expectedIndex} but found ${actualIndex} — a concurrent writer won.`);
374
- this.name = "AgentEventLogConflictError";
375
- this.threadId = threadId;
376
- this.expectedIndex = expectedIndex;
377
- this.actualIndex = actualIndex;
378
- }
379
- };
380
- /**
381
- * In-memory reference store, and the baseline the conformance suite runs
382
- * against. Per-thread entries are held in a contiguous, index-ordered list;
383
- * append's check-and-push runs synchronously (no `await` between reading the
384
- * length and writing), so two appends racing on the same `expectedIndex`
385
- * resolve to exactly one winner. Every stored and returned entry is
386
- * `structuredClone`d, so a caller can neither mutate stored state through a
387
- * value it appended nor through a value it read.
388
- */
389
- function createInMemoryEventLogStore() {
390
- const threads = /* @__PURE__ */ new Map();
391
- const clone = (value) => structuredClone(value);
392
- return {
393
- async append({ threadId, expectedIndex, entries }) {
394
- for (const entry of entries) assertAgentLogEntry(entry);
395
- for (let i = 0; i < entries.length; i++) if (entries[i].index !== expectedIndex + i) throw new Error(`AgentEventLogStore.append: entry.index (${entries[i].index}) must be contiguous from expectedIndex (${expectedIndex}); expected ${expectedIndex + i} at position ${i} on thread "${threadId}".`);
396
- const list = threads.get(threadId);
397
- const length = list ? list.length : 0;
398
- if (length !== expectedIndex) throw new AgentEventLogConflictError(threadId, expectedIndex, length);
399
- const ids = new Set((list ?? []).map((entry) => entry.id));
400
- for (const entry of entries) {
401
- if (ids.has(entry.id)) throw new Error(`AgentEventLogStore.append: duplicate event id "${entry.id}" in thread "${threadId}".`);
402
- ids.add(entry.id);
403
- }
404
- const cloned = entries.map((entry) => clone(entry));
405
- if (list) for (const entry of cloned) list.push(entry);
406
- else threads.set(threadId, cloned);
407
- },
408
- async read(threadId, options) {
409
- const list = threads.get(threadId) ?? [];
410
- const from = options?.from ?? 0;
411
- return list.slice(from).map((entry) => clone(entry));
412
- },
413
- async length(threadId) {
414
- return threads.get(threadId)?.length ?? 0;
415
- },
416
- async fork({ threadId, newThreadId, upToIndex }) {
417
- if ((threads.get(newThreadId)?.length ?? 0) > 0) throw new Error(`AgentEventLogStore.fork: newThreadId "${newThreadId}" already has entries.`);
418
- const source = threads.get(threadId);
419
- if (!source) throw new Error(`AgentEventLogStore.fork: unknown source thread "${threadId}".`);
420
- const upTo = upToIndex ?? source.length;
421
- if (upTo < 0 || upTo > source.length) throw new Error(`AgentEventLogStore.fork: thread "${threadId}" (length ${source.length}) has no index ${upTo} to fork up to.`);
422
- threads.set(newThreadId, source.slice(0, upTo).map((entry) => clone(entry)));
423
- }
424
- };
425
- }
426
- //#endregion
427
- Object.defineProperty(exports, "AGENT_EVENT_SCHEMA_VERSION", {
428
- enumerable: true,
429
- get: function() {
430
- return AGENT_EVENT_SCHEMA_VERSION;
431
- }
432
- });
433
- Object.defineProperty(exports, "AgentEventLogConflictError", {
434
- enumerable: true,
435
- get: function() {
436
- return AgentEventLogConflictError;
437
- }
438
- });
439
- Object.defineProperty(exports, "NonSerializableAgentEventError", {
440
- enumerable: true,
441
- get: function() {
442
- return NonSerializableAgentEventError;
443
- }
444
- });
445
- Object.defineProperty(exports, "assertAgentLogEntry", {
446
- enumerable: true,
447
- get: function() {
448
- return assertAgentLogEntry;
449
- }
450
- });
451
- Object.defineProperty(exports, "assertEventLogStoreConformance", {
452
- enumerable: true,
453
- get: function() {
454
- return assertEventLogStoreConformance;
455
- }
456
- });
457
- Object.defineProperty(exports, "assertJsonSerializable", {
458
- enumerable: true,
459
- get: function() {
460
- return assertJsonSerializable;
461
- }
462
- });
463
- Object.defineProperty(exports, "createInMemoryEventLogStore", {
464
- enumerable: true,
465
- get: function() {
466
- return createInMemoryEventLogStore;
467
- }
468
- });
@@ -1,145 +0,0 @@
1
- import { t as AgentError } from "./errors-C9rxnWbX.mjs";
2
- import { EventObject } from "xstate";
3
-
4
- //#region src/event-log-store-conformance.d.ts
5
- /** Produces a fresh, empty store for one assertion. */
6
- type CreateStore = () => Promise<AgentEventLogStore> | AgentEventLogStore;
7
- /**
8
- * Validates a store against the reference's semantics: empty read + zero length
9
- * for unknown threads; single and multi-entry append; contiguity misuse guard;
10
- * stale-`expectedIndex` conflict with correct fields; an interleaved concurrent
11
- * append race (exactly one winner); event-id uniqueness; `read({ from })`
12
- * incremental correctness; thread isolation; metadata round-trip; deep-copy
13
- * isolation on append and read; and the full fork contract.
14
- */
15
- declare function assertEventLogStoreConformance(create: CreateStore): Promise<void>;
16
- //#endregion
17
- //#region src/event-log-store.d.ts
18
- /** The durable replay-entry envelope version. */
19
- declare const AGENT_EVENT_SCHEMA_VERSION: 1;
20
- /** Values that round-trip through JSON without adapters or silent coercion. */
21
- type JsonValue = null | boolean | number | string | JsonValue[] | {
22
- [key: string]: JsonValue;
23
- };
24
- interface AgentLogVerification {
25
- /** Hash of the logical machine projection after this entry is applied. */
26
- stateHash: string;
27
- /** Hash of the serializable effects owed at that frontier. */
28
- effectsHash: string;
29
- }
30
- /**
31
- * One journaled entry: an EXTERNAL input to the machine — an effect completion
32
- * (a `done`/`error` event carrying its output inline), a user-sent event, or a
33
- * timer firing. Never a raised/internal event: deterministic replay re-derives
34
- * those from the machine's own logic, so journaling them would double-apply.
35
- * JSON-safe, stored verbatim.
36
- */
37
- interface AgentLogEntry {
38
- /** Version of this outer envelope, independent of the machine event type. */
39
- schemaVersion: typeof AGENT_EVENT_SCHEMA_VERSION;
40
- /** Stable identity within the thread. Forked prefixes retain their ids. */
41
- id: string;
42
- /** 0-based position in the thread's log. */
43
- index: number;
44
- /** RFC 3339 wall-clock time when the host accepted the entry. Metadata only. */
45
- recordedAt: string;
46
- /** The authored XState machine id. */
47
- machineId: string;
48
- /** Explicit version or structural hash of the machine that accepted the event. */
49
- machineVersion: string;
50
- event: EventObject;
51
- /** Optional causal parent entry id, scoped to the same thread. */
52
- causationId?: string;
53
- /** Optional host-owned correlation id spanning threads/runs. */
54
- correlationId?: string;
55
- /** Recorded projection hashes used by strict replay verification. */
56
- verification?: AgentLogVerification;
57
- /** Host-owned, JSON-safe; stored verbatim, never interpreted. */
58
- metadata?: Record<string, JsonValue>;
59
- }
60
- /** A precise failure when an entry would not survive a JSON round-trip. */
61
- declare class NonSerializableAgentEventError extends AgentError {
62
- readonly path: string;
63
- readonly valueType: string;
64
- constructor(path: string, valueType: string);
65
- }
66
- /**
67
- * Rejects values JSON would drop or coerce. Unlike `JSON.stringify`, this does
68
- * not silently erase `undefined`/functions or turn non-finite numbers into
69
- * `null`; durable entries contain only plain JSON values.
70
- */
71
- declare function assertJsonSerializable(value: unknown, path?: string, ancestors?: WeakSet<object>): asserts value is JsonValue;
72
- /** Validates the complete durable envelope before append/export/replay. */
73
- declare function assertAgentLogEntry(entry: unknown): asserts entry is AgentLogEntry;
74
- /**
75
- * An append-only event log: the authoritative durability artifact of a thread.
76
- * The journal of external inputs IS the source of truth — deterministic machine
77
- * replay derives every snapshot from it, a fork is a copied log prefix, and the
78
- * type-only {@link AgentSnapshotStore} is a mere idle-point compaction cache
79
- * over what the log already implies.
80
- *
81
- * Userland stores (a Postgres table with a `(thread_id, index)` primary key, an
82
- * append-only object in blob storage, …) implement this one shape so they
83
- * interoperate; {@link createInMemoryEventLogStore} is the in-memory reference.
84
- */
85
- interface AgentEventLogStore {
86
- /**
87
- * Append `entries` starting at `expectedIndex` (the current length of the
88
- * thread's log; 0 for a new thread). Atomic — all entries land or none do.
89
- * Rejects with {@link AgentEventLogConflictError} when the thread's length
90
- * differs from `expectedIndex`: a concurrent writer appended first. Each
91
- * entry's `index` must be contiguous from `expectedIndex` (a plain `Error`
92
- * otherwise: that is caller misuse, not a race).
93
- */
94
- append(input: {
95
- threadId: string;
96
- expectedIndex: number;
97
- entries: AgentLogEntry[];
98
- }): Promise<void>;
99
- /**
100
- * Read a thread's entries in log order. `from` (default 0) skips entries
101
- * below that index for incremental catch-up. An unknown thread reads as an
102
- * empty array.
103
- */
104
- read(threadId: string, options?: {
105
- from?: number;
106
- }): Promise<AgentLogEntry[]>;
107
- /** The thread's current log length (0 for an unknown thread) — the next `expectedIndex`. */
108
- length(threadId: string): Promise<number>;
109
- /**
110
- * Copy the prefix `[0, upToIndex)` onto a fresh, empty `newThreadId`.
111
- * Without `upToIndex` the full source is copied. The fork then appends
112
- * independently. Rejects (plain `Error`) if `newThreadId` already has
113
- * entries, the source is unknown, or `upToIndex` is out of range.
114
- * Implementations may copy-on-write or physically copy; observable behavior
115
- * must match a full copy.
116
- */
117
- fork(input: {
118
- threadId: string;
119
- newThreadId: string; /** Exclusive index cutoff. */
120
- upToIndex?: number;
121
- }): Promise<void>;
122
- }
123
- /**
124
- * Rejection from {@link AgentEventLogStore.append} when the thread's stored
125
- * length is not the `expectedIndex` the writer held — a concurrent writer
126
- * appended first. `actualIndex` is the next index the store would accept.
127
- */
128
- declare class AgentEventLogConflictError extends AgentError {
129
- readonly threadId: string;
130
- readonly expectedIndex: number;
131
- readonly actualIndex: number;
132
- constructor(threadId: string, expectedIndex: number, actualIndex: number);
133
- }
134
- /**
135
- * In-memory reference store, and the baseline the conformance suite runs
136
- * against. Per-thread entries are held in a contiguous, index-ordered list;
137
- * append's check-and-push runs synchronously (no `await` between reading the
138
- * length and writing), so two appends racing on the same `expectedIndex`
139
- * resolve to exactly one winner. Every stored and returned entry is
140
- * `structuredClone`d, so a caller can neither mutate stored state through a
141
- * value it appended nor through a value it read.
142
- */
143
- declare function createInMemoryEventLogStore(): AgentEventLogStore;
144
- //#endregion
145
- export { AgentLogVerification as a, assertAgentLogEntry as c, assertEventLogStoreConformance as d, AgentLogEntry as i, assertJsonSerializable as l, AgentEventLogConflictError as n, JsonValue as o, AgentEventLogStore as r, NonSerializableAgentEventError as s, AGENT_EVENT_SCHEMA_VERSION as t, createInMemoryEventLogStore as u };