stitchkit 0.110.1 → 0.110.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 (86) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/dist/agent-runtime/archive-projection.d.ts +10 -0
  3. package/dist/agent-runtime/archive-projection.d.ts.map +1 -0
  4. package/dist/agent-runtime/archive-spill.d.ts +61 -0
  5. package/dist/agent-runtime/archive-spill.d.ts.map +1 -0
  6. package/dist/agent-runtime/branch-contract.d.ts +102 -0
  7. package/dist/agent-runtime/branch-contract.d.ts.map +1 -0
  8. package/dist/agent-runtime/branch-events.d.ts +18 -0
  9. package/dist/agent-runtime/branch-events.d.ts.map +1 -0
  10. package/dist/agent-runtime/branch-identities.d.ts +20 -0
  11. package/dist/agent-runtime/branch-identities.d.ts.map +1 -0
  12. package/dist/agent-runtime/branch-messages.d.ts +32 -0
  13. package/dist/agent-runtime/branch-messages.d.ts.map +1 -0
  14. package/dist/agent-runtime/branch-observations.d.ts +104 -0
  15. package/dist/agent-runtime/branch-observations.d.ts.map +1 -0
  16. package/dist/agent-runtime/branch-provider.d.ts +130 -0
  17. package/dist/agent-runtime/branch-provider.d.ts.map +1 -0
  18. package/dist/agent-runtime/branch-replay.d.ts +426 -0
  19. package/dist/agent-runtime/branch-replay.d.ts.map +1 -0
  20. package/dist/agent-runtime/branch-source.d.ts +16 -0
  21. package/dist/agent-runtime/branch-source.d.ts.map +1 -0
  22. package/dist/agent-runtime/branch-transitions.d.ts +6 -0
  23. package/dist/agent-runtime/branch-transitions.d.ts.map +1 -0
  24. package/dist/agent-runtime/sqlite-events.d.ts.map +1 -1
  25. package/dist/agent-runtime/sqlite-history.d.ts.map +1 -1
  26. package/dist/agent-runtime/sqlite-purge.d.ts.map +1 -1
  27. package/dist/agent-runtime/store-archive.d.ts +1 -0
  28. package/dist/agent-runtime/store-archive.d.ts.map +1 -1
  29. package/dist/agent-runtime/store-branch.d.ts +5 -0
  30. package/dist/agent-runtime/store-branch.d.ts.map +1 -0
  31. package/dist/agent-runtime/store-conformance-branch.d.ts +4 -0
  32. package/dist/agent-runtime/store-conformance-branch.d.ts.map +1 -0
  33. package/dist/agent-runtime/store-conformance-support.d.ts +5 -5
  34. package/dist/agent-runtime/store-conformance.d.ts.map +1 -1
  35. package/dist/agent-runtime/store-create.d.ts +1 -1
  36. package/dist/agent-runtime/store-create.d.ts.map +1 -1
  37. package/dist/agent-runtime/store-driver-contract.d.ts +6 -0
  38. package/dist/agent-runtime/store-driver-contract.d.ts.map +1 -1
  39. package/dist/agent-runtime/store-events.d.ts +1131 -0
  40. package/dist/agent-runtime/store-events.d.ts.map +1 -1
  41. package/dist/agent-runtime/store-memory-archive.d.ts +8 -0
  42. package/dist/agent-runtime/store-memory-archive.d.ts.map +1 -0
  43. package/dist/agent-runtime/store-memory-events.d.ts +7 -0
  44. package/dist/agent-runtime/store-memory-events.d.ts.map +1 -0
  45. package/dist/agent-runtime/store-memory.d.ts +1 -1
  46. package/dist/agent-runtime/store-memory.d.ts.map +1 -1
  47. package/dist/agent-runtime/store-purge.d.ts +2 -0
  48. package/dist/agent-runtime/store-purge.d.ts.map +1 -1
  49. package/dist/agent-runtime/store-reduce-run.d.ts +2 -2
  50. package/dist/agent-runtime/store-reduce-run.d.ts.map +1 -1
  51. package/dist/agent-runtime/store-reduce-shared.d.ts +1 -0
  52. package/dist/agent-runtime/store-reduce-shared.d.ts.map +1 -1
  53. package/dist/agent-runtime/store-reducer.d.ts +2 -2
  54. package/dist/agent-runtime/store-reducer.d.ts.map +1 -1
  55. package/dist/agent-runtime/store-replay.d.ts +4 -0
  56. package/dist/agent-runtime/store-replay.d.ts.map +1 -0
  57. package/dist/agent-runtime/store.d.ts +3 -0
  58. package/dist/agent-runtime/store.d.ts.map +1 -1
  59. package/dist/durability/events.d.ts +4 -0
  60. package/dist/durability/events.d.ts.map +1 -1
  61. package/dist/entrypoints/agent-runtime/coding-tools.js +1 -2
  62. package/dist/entrypoints/agent-runtime/harness.js +4 -3
  63. package/dist/entrypoints/agent-runtime/sandbox.js +3 -5
  64. package/dist/entrypoints/agent-runtime/sqlite/bun.js +13 -3
  65. package/dist/entrypoints/agent-runtime/sqlite/node.js +13 -3
  66. package/dist/entrypoints/agent-runtime/testing.js +89 -5
  67. package/dist/entrypoints/agent-runtime.d.ts +2 -1
  68. package/dist/entrypoints/agent-runtime.d.ts.map +1 -1
  69. package/dist/entrypoints/agent-runtime.js +27 -15
  70. package/dist/entrypoints/tools.js +5 -3
  71. package/dist/{index-0gs4ymfj.js → index-4fgg1507.js} +31 -2
  72. package/dist/{index-c17xcx4k.js → index-56yx8dxp.js} +19 -96
  73. package/dist/{index-8rstkvcf.js → index-7c046kxr.js} +1 -1
  74. package/dist/{index-tjdsyrys.js → index-bm180f2d.js} +203 -83
  75. package/dist/{index-924500c3.js → index-ddkwkcvn.js} +2 -2
  76. package/dist/{index-c0hffcmj.js → index-dgfah0g8.js} +21 -9
  77. package/dist/index-j1cwtyk1.js +2269 -0
  78. package/dist/index-snef22zr.js +94 -0
  79. package/dist/{index-5p55xreg.js → index-w619fqvv.js} +67 -29
  80. package/llms/agent-runtime.3.txt +4 -0
  81. package/llms/agent-runtime.txt +75 -0
  82. package/llms-full.txt +79 -0
  83. package/llms.txt +1 -1
  84. package/package.json +1 -1
  85. package/dist/index-8ks9b85e.js +0 -129
  86. package/dist/index-d2h99n7d.js +0 -1071
@@ -1,1071 +0,0 @@
1
- import {
2
- AgentRecordIdSchema2,
3
- AgentRecordVersionSchema2,
4
- AgentMessageSchema2,
5
- runStateForTerminalReason2,
6
- AgentRunSchema2,
7
- AgentSnapshotSchema2
8
- } from "./index-8kzct1d6.js";
9
- import {
10
- AppendAgentStoreEventSchema2,
11
- ReadAgentStoreEventsSchema2,
12
- AgentStoreEventPageSchema2,
13
- AgentRunViewSchema2,
14
- AcceptInputAndAssignRunSchema2,
15
- AcquireAgentRunSchema2,
16
- CheckpointRunAssistantSchema2,
17
- RecordRunOperationSchema2,
18
- CommitRunTerminalSchema2,
19
- RequestRunInterruptSchema2,
20
- RecoverAgentRunSchema2,
21
- ReplaceCompactedRangeSchema2,
22
- SeedConversationInputSchema2,
23
- AgentRecoverablePageSchema2,
24
- AgentStoreTransitionSchema2,
25
- agentStoreEventDraft,
26
- canonicalAgentJson2,
27
- encodeAgentConversationArchive2,
28
- decodeAgentConversationArchive2,
29
- assistantStatus
30
- } from "./index-0gs4ymfj.js";
31
-
32
- // src/agent-runtime/purge.ts
33
- import { z } from "zod";
34
- var AgentConversationPurgeInputSchema2 = z.strictObject({
35
- conversationId: AgentRecordIdSchema2,
36
- expectedVersion: AgentRecordVersionSchema2.optional()
37
- });
38
- var AgentConversationPurgeResultSchema2 = z.discriminatedUnion("outcome", [
39
- z.strictObject({ outcome: z.literal("purged") }),
40
- z.strictObject({ outcome: z.literal("already_purged") }),
41
- z.strictObject({ outcome: z.literal("unsupported") }),
42
- z.strictObject({
43
- outcome: z.literal("active"),
44
- runIds: z.array(AgentRecordIdSchema2).min(1)
45
- }),
46
- z.strictObject({ outcome: z.literal("conflict"), actualVersion: AgentRecordVersionSchema2 })
47
- ]);
48
-
49
- class AgentConversationPurgedError2 extends Error {
50
- constructor() {
51
- super("Agent conversation has been purged; use a new conversation ID");
52
- this.name = "AgentConversationPurgedError";
53
- }
54
- }
55
- async function purgeAgentConversation2(store, input) {
56
- const parsed = AgentConversationPurgeInputSchema2.parse(input);
57
- if (!store.purgeConversation)
58
- return { outcome: "unsupported" };
59
- return AgentConversationPurgeResultSchema2.parse(await store.purgeConversation(parsed));
60
- }
61
-
62
- // src/agent-runtime/store-driver-contract.ts
63
- import { z as z2 } from "zod";
64
- var AgentRuntimeHeadSchema2 = z2.object({
65
- schemaVersion: z2.literal(1),
66
- conversationId: AgentRecordIdSchema2,
67
- version: AgentRecordVersionSchema2
68
- });
69
- var AgentStoredRunSchema2 = z2.object({
70
- schemaVersion: z2.literal(1),
71
- run: AgentRunSchema2,
72
- terminalAssistant: AgentMessageSchema2.optional()
73
- });
74
- var AgentAdmissionReceiptSchema2 = z2.object({
75
- schemaVersion: z2.literal(1),
76
- conversationId: AgentRecordIdSchema2,
77
- idempotencyKey: z2.string().min(1),
78
- input: AgentMessageSchema2,
79
- runId: AgentRecordIdSchema2,
80
- assistantMessageId: AgentRecordIdSchema2
81
- });
82
- var AgentSeedReceiptSchema2 = z2.object({
83
- schemaVersion: z2.literal(1),
84
- conversationId: AgentRecordIdSchema2,
85
- seedKey: z2.string().min(1),
86
- messageIds: z2.array(AgentRecordIdSchema2).min(1)
87
- });
88
- var AgentHistoryMutationSchema2 = z2.discriminatedUnion("type", [
89
- z2.object({ type: z2.literal("admit"), input: AgentMessageSchema2 }),
90
- z2.object({
91
- type: z2.literal("upsert-assistant"),
92
- message: AgentMessageSchema2
93
- }),
94
- z2.object({
95
- type: z2.literal("replace-compacted-range"),
96
- replacedMessageIds: z2.array(AgentRecordIdSchema2).min(1),
97
- summary: AgentMessageSchema2
98
- }),
99
- z2.object({
100
- type: z2.literal("seed"),
101
- message: AgentMessageSchema2
102
- })
103
- ]);
104
- var ACTIVE_AGENT_RUN_STATES2 = [
105
- "queued",
106
- "running",
107
- "interrupt_requested"
108
- ];
109
- function isActiveRunState(state) {
110
- return ACTIVE_AGENT_RUN_STATES2.includes(state);
111
- }
112
- function emptyHead(conversationId) {
113
- return AgentRuntimeHeadSchema2.parse({
114
- schemaVersion: 1,
115
- conversationId,
116
- version: 0
117
- });
118
- }
119
-
120
- // src/agent-runtime/store-create.ts
121
- import { z as z5 } from "zod";
122
-
123
- // src/agent-runtime/store-archive.ts
124
- import { z as z3 } from "zod";
125
-
126
- // src/agent-runtime/store-snapshot.ts
127
- function historyPositions(messages) {
128
- const positions = new Map;
129
- messages.forEach((message, index) => {
130
- if (!positions.has(message.id))
131
- positions.set(message.id, index);
132
- });
133
- return (run) => {
134
- let earliest = Number.MAX_SAFE_INTEGER;
135
- for (const id of [...run.inputMessageIds, run.assistantMessageId]) {
136
- const position = positions.get(id);
137
- if (position !== undefined && position < earliest)
138
- earliest = position;
139
- }
140
- return earliest;
141
- };
142
- }
143
- function orderRuns(messages, runs) {
144
- const positionOf = historyPositions(messages);
145
- const fallback = (left, right) => left.createdAt.localeCompare(right.createdAt) || positionOf(left) - positionOf(right) || left.id.localeCompare(right.id);
146
- return [...runs].sort((left, right) => {
147
- if (left.executionSequence !== undefined && right.executionSequence !== undefined && left.executionSequence !== right.executionSequence) {
148
- return left.executionSequence - right.executionSequence;
149
- }
150
- const leftStarted = left.executionSequence !== undefined || left.state !== "queued";
151
- const rightStarted = right.executionSequence !== undefined || right.state !== "queued";
152
- if (leftStarted !== rightStarted)
153
- return leftStarted ? -1 : 1;
154
- if (!leftStarted && !rightStarted) {
155
- const priority = Number(right.queuePriority !== undefined) - Number(left.queuePriority !== undefined);
156
- if (priority !== 0)
157
- return priority;
158
- }
159
- return fallback(left, right);
160
- });
161
- }
162
- function orderRunMessages(messages, runs) {
163
- const byId = new Map(messages.map((message) => [message.id, message]));
164
- const ownedIds = new Set(runs.flatMap((run) => [...run.inputMessageIds, run.assistantMessageId]));
165
- const orderedOwned = runs.flatMap((run) => [...run.inputMessageIds, run.assistantMessageId].flatMap((id) => {
166
- const message = byId.get(id);
167
- return message ? [message] : [];
168
- }));
169
- let ownedIndex = 0;
170
- return messages.map((message) => {
171
- if (!ownedIds.has(message.id))
172
- return message;
173
- const ordered = orderedOwned[ownedIndex];
174
- if (!ordered)
175
- throw new TypeError("Stored agent history lost a run-owned message");
176
- ownedIndex += 1;
177
- return ordered;
178
- });
179
- }
180
- function snapshotOf(head, messages, records) {
181
- validateSnapshot(head, messages, records);
182
- const runs = orderRuns(messages, records.map((record) => record.run));
183
- return AgentSnapshotSchema2.parse({
184
- schemaVersion: 1,
185
- conversationId: head.conversationId,
186
- version: head.version,
187
- messages: orderRunMessages(messages, runs),
188
- runs
189
- });
190
- }
191
- function validateSnapshot(head, messages, records) {
192
- const runIds = new Set;
193
- const assistantIds = new Set;
194
- const messageIds = new Set;
195
- for (const record of records) {
196
- const run = record.run;
197
- if (run.conversationId !== head.conversationId || runIds.has(run.id) || assistantIds.has(run.assistantMessageId)) {
198
- throw new TypeError("Stored agent runs contain inconsistent identities");
199
- }
200
- if (record.terminalAssistant && (record.terminalAssistant.id !== run.assistantMessageId || record.terminalAssistant.conversationId !== run.conversationId || record.terminalAssistant.runId !== run.id || record.terminalAssistant.role !== "assistant" || run.terminalReason === undefined)) {
201
- throw new TypeError("Retained terminal assistant does not match its run");
202
- }
203
- runIds.add(run.id);
204
- assistantIds.add(run.assistantMessageId);
205
- }
206
- for (const message of messages) {
207
- if (message.conversationId !== head.conversationId || messageIds.has(message.id)) {
208
- throw new TypeError("Stored agent history contains inconsistent message identities");
209
- }
210
- messageIds.add(message.id);
211
- if (assistantIds.has(message.id) && message.runId === undefined) {
212
- throw new TypeError("Stored history occupies a reserved assistant identity");
213
- }
214
- if (message.runId !== undefined) {
215
- const run = records.find((candidate) => candidate.run.id === message.runId)?.run;
216
- if (!run || message.role !== "assistant" || run.assistantMessageId !== message.id) {
217
- throw new TypeError("Stored assistant history does not match its reserved run identity");
218
- }
219
- }
220
- }
221
- }
222
- function replaceRun(runs, next) {
223
- return runs.map((run) => run.id === next.id ? next : run);
224
- }
225
- function replaceMessage(messages, next) {
226
- return messages.some((message) => message.id === next.id) ? messages.map((message) => message.id === next.id ? next : message) : [...messages, next];
227
- }
228
- function mergeRunRecords(...groups) {
229
- const records = new Map;
230
- for (const group of groups) {
231
- for (const rawRecord of group) {
232
- const record = AgentStoredRunSchema2.parse(rawRecord);
233
- const previous = records.get(record.run.id);
234
- if (previous && previous.run.assistantMessageId !== record.run.assistantMessageId) {
235
- throw new TypeError("Stored agent run identity changed across normalized records");
236
- }
237
- records.set(record.run.id, record);
238
- }
239
- }
240
- return [...records.values()];
241
- }
242
- function referencedRunIds(messages) {
243
- return [...new Set(messages.flatMap((message) => message.runId ? [message.runId] : []))];
244
- }
245
-
246
- // src/agent-runtime/store-reads.ts
247
- async function snapshotIn(driver, transaction, conversationId) {
248
- const [stored, messages, activeRecords] = await Promise.all([
249
- driver.head.load(transaction, conversationId),
250
- driver.history.load(transaction, conversationId),
251
- driver.runs.listActive(transaction, conversationId)
252
- ]);
253
- const head = AgentRuntimeHeadSchema2.parse(stored ?? emptyHead(conversationId));
254
- const referencedRecords = await driver.runs.loadMany(transaction, {
255
- conversationId,
256
- runIds: referencedRunIds(messages)
257
- });
258
- return snapshotOf(head, messages, mergeRunRecords(activeRecords, referencedRecords));
259
- }
260
- function loadSnapshot(driver, conversationId) {
261
- return driver.transaction((transaction) => snapshotIn(driver, transaction, conversationId), {
262
- access: "read"
263
- });
264
- }
265
- function loadRun(driver, input) {
266
- return driver.transaction(async (transaction) => {
267
- const [stored, record] = await Promise.all([
268
- driver.head.load(transaction, input.conversationId),
269
- driver.runs.load(transaction, input)
270
- ]);
271
- if (!record)
272
- return;
273
- const parsed = AgentStoredRunSchema2.parse(record);
274
- if (parsed.run.conversationId !== input.conversationId || parsed.run.id !== input.runId) {
275
- throw new TypeError("Stored run does not match the identity it was loaded by");
276
- }
277
- const head = AgentRuntimeHeadSchema2.parse(stored ?? emptyHead(input.conversationId));
278
- return AgentRunViewSchema2.parse({
279
- snapshotVersion: head.version,
280
- run: parsed.run,
281
- ...parsed.terminalAssistant && { assistant: parsed.terminalAssistant }
282
- });
283
- }, { access: "read" });
284
- }
285
- function listActiveRuns(driver, conversationId) {
286
- return driver.transaction(async (transaction) => {
287
- const [records, messages] = await Promise.all([
288
- driver.runs.listActive(transaction, conversationId),
289
- driver.history.load(transaction, conversationId)
290
- ]);
291
- const runs = records.map((record) => AgentStoredRunSchema2.parse(record).run);
292
- for (const run of runs) {
293
- if (run.conversationId !== conversationId) {
294
- throw new TypeError("Active run belongs to another conversation");
295
- }
296
- if (!isActiveRunState(run.state)) {
297
- throw new TypeError("Active run listing returned a terminal run");
298
- }
299
- }
300
- return orderRuns(messages, runs);
301
- }, { access: "read" });
302
- }
303
- function appendEvent(driver, input) {
304
- const parsed = AppendAgentStoreEventSchema2.parse(input);
305
- return driver.transaction((transaction) => appendEventIn(driver, transaction, parsed));
306
- }
307
- async function appendEventIn(driver, transaction, parsed) {
308
- if (await driver.conversations?.isPurged(transaction, parsed.conversationId)) {
309
- throw new AgentConversationPurgedError2;
310
- }
311
- return driver.events.append(transaction, agentStoreEventDraft(parsed));
312
- }
313
- function readEvents(driver, input) {
314
- const parsed = ReadAgentStoreEventsSchema2.parse(input);
315
- return driver.transaction(async (transaction) => AgentStoreEventPageSchema2.parse(await driver.events.list(transaction, parsed)), { access: "read" });
316
- }
317
-
318
- // src/agent-runtime/store-archive.ts
319
- function exportConversation(driver, conversationId) {
320
- return driver.transaction(async (transaction) => {
321
- const events = [];
322
- let fromSeq;
323
- do {
324
- const page = AgentStoreEventPageSchema2.parse(await driver.events.list(transaction, ReadAgentStoreEventsSchema2.parse({
325
- conversationId,
326
- ...fromSeq && { fromSeq },
327
- limit: 1e4
328
- })));
329
- events.push(...page.items);
330
- fromSeq = page.nextSeq;
331
- } while (fromSeq !== undefined);
332
- const durable = await driver.archive?.export(transaction, conversationId) ?? {
333
- projections: [],
334
- spills: []
335
- };
336
- const snapshot = await snapshotIn(driver, transaction, conversationId);
337
- return encodeAgentConversationArchive2({
338
- format: "stitchkit.agent-conversation",
339
- formatVersion: 1,
340
- conversationId,
341
- events,
342
- projections: [
343
- { archiveType: "runtime-snapshot", snapshot: z3.json().parse(snapshot) },
344
- ...durable.projections
345
- ],
346
- spills: durable.spills
347
- });
348
- }, { access: "read" });
349
- }
350
- async function importConversation(driver, bytes) {
351
- const archive = decodeAgentConversationArchive2(bytes);
352
- return driver.transaction(async (transaction) => {
353
- const existing = await driver.events.list(transaction, {
354
- conversationId: archive.conversationId,
355
- limit: 1
356
- });
357
- if (existing.items.length > 0) {
358
- throw new TypeError("Conversation event log must be empty before import");
359
- }
360
- for (const event of archive.events) {
361
- const appended = await driver.events.append(transaction, {
362
- schemaVersion: event.schemaVersion,
363
- eventId: event.eventId,
364
- conversationId: event.conversationId,
365
- kind: event.kind,
366
- occurredAt: event.occurredAt,
367
- payload: event.payload,
368
- ...event.ignorable && { ignorable: true }
369
- });
370
- if (appended.seq !== event.seq) {
371
- throw new TypeError("Conversation archive event sequence is not contiguous");
372
- }
373
- }
374
- const snapshotEntry = archive.projections.find((entry) => typeof entry === "object" && entry !== null && !Array.isArray(entry) && entry.archiveType === "runtime-snapshot");
375
- if (snapshotEntry && typeof snapshotEntry === "object" && !Array.isArray(snapshotEntry)) {
376
- const snapshot = AgentSnapshotSchema2.parse(snapshotEntry.snapshot);
377
- if (snapshot.conversationId !== archive.conversationId) {
378
- throw new TypeError("Conversation archive snapshot belongs to another conversation");
379
- }
380
- if (snapshot.version > 0 || snapshot.messages.length > 0 || snapshot.runs.length > 0) {
381
- const outcome = await driver.head.compareAndSwap(transaction, {
382
- conversationId: snapshot.conversationId,
383
- expectedVersion: 0,
384
- next: AgentRuntimeHeadSchema2.parse({
385
- schemaVersion: 1,
386
- conversationId: snapshot.conversationId,
387
- version: snapshot.version
388
- })
389
- });
390
- if (outcome.outcome !== "applied") {
391
- throw new TypeError("Conversation archive snapshot target is not empty");
392
- }
393
- }
394
- for (const run of snapshot.runs) {
395
- const terminalAssistant = snapshot.messages.find((message) => message.id === run.assistantMessageId);
396
- await driver.runs.save(transaction, AgentStoredRunSchema2.parse({
397
- schemaVersion: 1,
398
- run,
399
- ...terminalAssistant && { terminalAssistant }
400
- }));
401
- }
402
- for (const message of snapshot.messages) {
403
- await driver.history.apply(transaction, { type: "admit", input: message });
404
- }
405
- for (const event of archive.events) {
406
- if (event.kind !== "runtime/transition")
407
- continue;
408
- const transition = AgentStoreTransitionSchema2.parse(event.payload);
409
- if (transition.type !== "accept")
410
- continue;
411
- const assigned = snapshot.runs.find((run) => run.inputMessageIds.includes(transition.input.input.id));
412
- if (!assigned) {
413
- throw new TypeError("Conversation archive admission has no assigned run");
414
- }
415
- await driver.admissions.create(transaction, AgentAdmissionReceiptSchema2.parse({
416
- schemaVersion: 1,
417
- conversationId: archive.conversationId,
418
- idempotencyKey: transition.input.idempotencyKey,
419
- input: transition.input.input,
420
- runId: assigned.id,
421
- assistantMessageId: assigned.assistantMessageId
422
- }));
423
- }
424
- }
425
- await driver.archive?.import(transaction, archive);
426
- return { conversationId: archive.conversationId, events: archive.events.length };
427
- });
428
- }
429
-
430
- // src/agent-runtime/store-event-once.ts
431
- import { createHash } from "node:crypto";
432
- function eventOnceId(conversationId, kind, key) {
433
- if (!key)
434
- throw new TypeError("Event admission key must not be empty");
435
- return createHash("sha256").update(JSON.stringify([conversationId, kind, key])).digest("hex");
436
- }
437
- async function findEvent(driver, transaction, conversationId, eventId) {
438
- if (driver.events.find)
439
- return driver.events.find(transaction, { conversationId, eventId });
440
- let fromSeq;
441
- do {
442
- const page = await driver.events.list(transaction, {
443
- conversationId,
444
- fromSeq,
445
- limit: 1e4
446
- });
447
- const found = page.items.find((event) => event.eventId === eventId);
448
- if (found)
449
- return found;
450
- fromSeq = page.nextSeq;
451
- } while (fromSeq !== undefined);
452
- return;
453
- }
454
- function appendEventOnce(driver, input, key) {
455
- const parsed = AppendAgentStoreEventSchema2.parse(input);
456
- const eventId = eventOnceId(parsed.conversationId, parsed.kind, key);
457
- return driver.transaction(async (transaction) => {
458
- if (await driver.conversations?.isPurged(transaction, parsed.conversationId)) {
459
- throw new AgentConversationPurgedError2;
460
- }
461
- const previous = await findEvent(driver, transaction, parsed.conversationId, eventId);
462
- if (previous)
463
- return { outcome: "duplicate", event: previous };
464
- const event = await driver.events.append(transaction, {
465
- ...agentStoreEventDraft(parsed),
466
- eventId
467
- });
468
- return { outcome: "applied", event };
469
- });
470
- }
471
- function findEventOnce(driver, input) {
472
- const eventId = eventOnceId(input.conversationId, input.kind, input.key);
473
- return driver.transaction((transaction) => findEvent(driver, transaction, input.conversationId, eventId), { access: "read" });
474
- }
475
-
476
- // src/agent-runtime/store-mutate.ts
477
- import { z as z4 } from "zod";
478
-
479
- // src/agent-runtime/store-reduce-shared.ts
480
- function conflict(actualVersion) {
481
- return { outcome: "conflict", actualVersion };
482
- }
483
- function applied(current, input, effects) {
484
- const runs = input.runs ?? current.runs;
485
- const messages = input.messages ?? current.messages;
486
- return {
487
- outcome: "applied",
488
- snapshot: AgentSnapshotSchema2.parse({
489
- ...current,
490
- version: current.version + 1,
491
- runs,
492
- messages: orderRunMessages(messages, runs)
493
- }),
494
- ...effects?.runRecords?.length && { runRecords: effects.runRecords },
495
- ...effects?.admissionReceipt && { admissionReceipt: effects.admissionReceipt },
496
- ...effects?.seedReceipt && { seedReceipt: effects.seedReceipt },
497
- ...effects?.historyMutations?.length && { historyMutations: effects.historyMutations }
498
- };
499
- }
500
-
501
- // src/agent-runtime/store-reducer.ts
502
- import { createHash as createHash2 } from "node:crypto";
503
-
504
- // src/agent-runtime/store-reduce-history.ts
505
- function reduceAccept(current, input) {
506
- if (input.expectedVersion !== undefined && input.expectedVersion !== current.version) {
507
- return conflict(current.version);
508
- }
509
- const coalescedRun = input.coalesceIntoRunId ? current.runs.find((candidate) => candidate.id === input.coalesceIntoRunId) : undefined;
510
- if (input.coalesceIntoRunId !== undefined && (!coalescedRun || coalescedRun.conversationId !== input.input.conversationId || coalescedRun.state !== "queued" || coalescedRun.ownerId !== undefined || coalescedRun.terminalReason !== undefined)) {
511
- return coalescedRun ? conflict(coalescedRun.revision) : { outcome: "not_found" };
512
- }
513
- if (input.run.conversationId !== input.input.conversationId || input.run.inputMessageIds.length !== 1 || input.run.inputMessageIds[0] !== input.input.id || input.run.state !== "queued" || input.run.revision !== 0 || input.run.executionSequence !== undefined || input.run.ownerId !== undefined || input.run.terminalReason !== undefined || input.run.terminalPolicyName !== undefined || input.input.role !== "user" && input.input.role !== "tool" || input.input.status !== "committed" || input.input.runId !== undefined || current.messages.some((message) => message.id === input.input.id) || coalescedRun !== undefined && input.input.id === coalescedRun.assistantMessageId || !coalescedRun && (input.run.assistantMessageId === input.input.id || current.runs.some((candidate) => candidate.id === input.run.id) || current.runs.some((candidate) => candidate.assistantMessageId === input.run.assistantMessageId) || current.messages.some((message) => message.id === input.run.assistantMessageId))) {
514
- throw new TypeError("Input and queued run do not form one valid assignment");
515
- }
516
- const assignedRun = coalescedRun ? AgentRunSchema2.parse({
517
- ...coalescedRun,
518
- inputMessageIds: [...coalescedRun.inputMessageIds, input.input.id],
519
- revision: coalescedRun.revision + 1,
520
- updatedAt: new Date().toISOString()
521
- }) : input.run;
522
- const admissionReceipt = AgentAdmissionReceiptSchema2.parse({
523
- schemaVersion: 1,
524
- conversationId: input.input.conversationId,
525
- idempotencyKey: input.idempotencyKey,
526
- input: input.input,
527
- runId: assignedRun.id,
528
- assistantMessageId: assignedRun.assistantMessageId
529
- });
530
- return applied(current, {
531
- messages: [...current.messages, input.input],
532
- runs: coalescedRun ? replaceRun(current.runs, assignedRun) : [...current.runs, assignedRun]
533
- }, {
534
- runRecords: [AgentStoredRunSchema2.parse({ schemaVersion: 1, run: assignedRun })],
535
- admissionReceipt,
536
- historyMutations: [{ type: "admit", input: input.input }]
537
- });
538
- }
539
- function reduceSeed(current, input) {
540
- const conversationId = input.conversationId;
541
- if (current.conversationId !== conversationId)
542
- return { outcome: "not_found" };
543
- for (const message of input.inputs) {
544
- if (message.conversationId !== conversationId || message.role !== "user" || message.status !== "committed" || message.runId !== undefined) {
545
- throw new TypeError("Seeded conversation input must be committed unowned user messages");
546
- }
547
- }
548
- return applied(current, { messages: [...input.inputs, ...current.messages] }, {
549
- seedReceipt: AgentSeedReceiptSchema2.parse({
550
- schemaVersion: 1,
551
- conversationId,
552
- seedKey: input.seedKey,
553
- messageIds: input.inputs.map((message) => message.id)
554
- }),
555
- historyMutations: [...input.inputs].reverse().map((message) => ({
556
- type: "seed",
557
- message
558
- }))
559
- });
560
- }
561
- function reduceCompact(current, input) {
562
- if (current.conversationId !== input.conversationId)
563
- return { outcome: "not_found" };
564
- if (current.version !== input.expectedVersion)
565
- return conflict(current.version);
566
- const replaced = new Set(input.replacedMessageIds);
567
- if (!input.replacedMessageIds.every((id) => current.messages.some((m) => m.id === id))) {
568
- return { outcome: "not_found" };
569
- }
570
- const liveAssistant = current.runs.find((candidate) => isActiveRunState(candidate.state) && replaced.has(candidate.assistantMessageId));
571
- if (liveAssistant) {
572
- throw new TypeError(`Compaction may not replace the assistant message of run ${liveAssistant.id}, which has not finished`);
573
- }
574
- const positions = current.messages.map((message, index) => replaced.has(message.id) ? index : undefined).filter((index) => index !== undefined);
575
- const first = positions[0];
576
- if (first === undefined || positions.some((position, offset) => position !== first + offset) || input.summary.conversationId !== input.conversationId || input.summary.runId !== undefined || input.summary.role !== "summary" || input.summary.status !== "committed" || current.messages.some((message) => message.id === input.summary.id) || current.runs.some((candidate) => candidate.assistantMessageId === input.summary.id)) {
577
- throw new TypeError("Compaction replacement must be one valid contiguous history range");
578
- }
579
- const messages = [
580
- ...current.messages.slice(0, first),
581
- input.summary,
582
- ...current.messages.slice(first + positions.length)
583
- ];
584
- return applied(current, { messages }, {
585
- historyMutations: [
586
- {
587
- type: "replace-compacted-range",
588
- replacedMessageIds: input.replacedMessageIds,
589
- summary: input.summary
590
- }
591
- ]
592
- });
593
- }
594
-
595
- // src/agent-runtime/store-reduce-run.ts
596
- function reduceAcquire(current, run, input) {
597
- const runPosition = current.runs.findIndex((candidate) => candidate.id === run.id);
598
- const acquisitionBlocked = current.runs.some((candidate, index) => candidate.id !== run.id && (candidate.state === "running" || candidate.state === "interrupt_requested" || index < runPosition && candidate.state === "queued"));
599
- if (run.revision !== input.expectedRevision || run.state !== "queued" || acquisitionBlocked) {
600
- return conflict(run.revision);
601
- }
602
- const next = AgentRunSchema2.parse({
603
- ...run,
604
- state: "running",
605
- executionSequence: run.executionSequence ?? current.version + 1,
606
- ownerId: input.ownerId,
607
- fencingToken: (run.fencingToken ?? 0) + 1,
608
- revision: run.revision + 1,
609
- updatedAt: new Date().toISOString()
610
- });
611
- return applied(current, { runs: replaceRun(current.runs, next) }, {
612
- runRecords: [AgentStoredRunSchema2.parse({ schemaVersion: 1, run: next })]
613
- });
614
- }
615
- function reduceCheckpoint(current, run, input) {
616
- if (run.revision !== input.expectedRevision || run.state !== "running" || run.ownerId !== input.ownerId || input.fencingToken !== undefined && run.fencingToken !== input.fencingToken || input.assistant.runId !== run.id || input.assistant.id !== run.assistantMessageId || input.assistant.conversationId !== run.conversationId || input.assistant.role !== "assistant" || input.assistant.status !== "streaming") {
617
- return conflict(run.revision);
618
- }
619
- const next = AgentRunSchema2.parse({
620
- ...run,
621
- ...input.usage && { usage: input.usage },
622
- revision: run.revision + 1,
623
- updatedAt: new Date().toISOString()
624
- });
625
- return applied(current, {
626
- runs: replaceRun(current.runs, next),
627
- messages: replaceMessage(current.messages, input.assistant)
628
- }, {
629
- runRecords: [AgentStoredRunSchema2.parse({ schemaVersion: 1, run: next })],
630
- historyMutations: [{ type: "upsert-assistant", message: input.assistant }]
631
- });
632
- }
633
- function reduceOperation(current, run, input) {
634
- if (run.revision !== input.expectedRevision || run.state !== "running" && run.state !== "interrupt_requested" || run.ownerId !== input.ownerId || input.fencingToken !== undefined && run.fencingToken !== input.fencingToken) {
635
- return conflict(run.revision);
636
- }
637
- const next = AgentRunSchema2.parse({
638
- ...run,
639
- lastOperation: input.operation,
640
- revision: run.revision + 1,
641
- updatedAt: new Date().toISOString()
642
- });
643
- return applied(current, { runs: replaceRun(current.runs, next) }, { runRecords: [AgentStoredRunSchema2.parse({ schemaVersion: 1, run: next })] });
644
- }
645
- function reduceInterrupt(current, run, input) {
646
- if (run.revision !== input.expectedRevision || run.state !== "running") {
647
- return conflict(run.revision);
648
- }
649
- const next = AgentRunSchema2.parse({
650
- ...run,
651
- state: "interrupt_requested",
652
- revision: run.revision + 1,
653
- updatedAt: new Date().toISOString()
654
- });
655
- return applied(current, { runs: replaceRun(current.runs, next) }, {
656
- runRecords: [AgentStoredRunSchema2.parse({ schemaVersion: 1, run: next })]
657
- });
658
- }
659
- function reduceRecover(current, run, input) {
660
- if (run.revision !== input.expectedRevision || !isActiveRunState(run.state)) {
661
- return conflict(run.revision);
662
- }
663
- if (input.action === "requeue" && run.state !== "queued" && input.replaySafe !== true) {
664
- throw new TypeError("Recovering an acquired run requires explicit replaySafe evidence");
665
- }
666
- const { ownerId: _released, ...carried } = run;
667
- const next = AgentRunSchema2.parse({
668
- ...carried,
669
- state: input.action === "requeue" ? "queued" : "abandoned",
670
- revision: run.revision + 1,
671
- ...input.action === "abandon" && { terminalReason: "abandoned" },
672
- updatedAt: new Date().toISOString()
673
- });
674
- if (input.action === "abandon") {
675
- const existingAssistant = current.messages.find((message) => message.id === run.assistantMessageId);
676
- const assistant = AgentMessageSchema2.parse({
677
- ...existingAssistant ?? {
678
- schemaVersion: 1,
679
- id: run.assistantMessageId,
680
- conversationId: run.conversationId,
681
- runId: run.id,
682
- role: "assistant",
683
- parts: [],
684
- createdAt: run.createdAt
685
- },
686
- status: "failed",
687
- updatedAt: new Date().toISOString()
688
- });
689
- return applied(current, {
690
- runs: replaceRun(current.runs, next),
691
- messages: replaceMessage(current.messages, assistant)
692
- }, {
693
- runRecords: [
694
- AgentStoredRunSchema2.parse({
695
- schemaVersion: 1,
696
- run: next,
697
- terminalAssistant: assistant
698
- })
699
- ],
700
- historyMutations: [{ type: "upsert-assistant", message: assistant }]
701
- });
702
- }
703
- return applied(current, { runs: replaceRun(current.runs, next) }, {
704
- runRecords: [AgentStoredRunSchema2.parse({ schemaVersion: 1, run: next })]
705
- });
706
- }
707
-
708
- // src/agent-runtime/store-reduce-terminal.ts
709
- function reduceTerminal(current, run, input) {
710
- if (input.reason === "absorbed") {
711
- throw new TypeError("A run is absorbed by another run, never terminalized as absorbed");
712
- }
713
- if (run.revision !== input.expectedRevision || run.state !== "running" && run.state !== "interrupt_requested" || run.ownerId !== input.ownerId || input.fencingToken !== undefined && run.fencingToken !== input.fencingToken || input.assistant.runId !== run.id || input.assistant.id !== run.assistantMessageId || input.assistant.conversationId !== run.conversationId || input.assistant.role !== "assistant" || input.assistant.status !== assistantStatus(input.reason)) {
714
- return conflict(run.revision);
715
- }
716
- if (input.absorb && runStateForTerminalReason2(input.reason) !== "completed") {
717
- throw new TypeError("Only a completing run may absorb a queued successor");
718
- }
719
- const named = new Set((input.absorb ?? []).map((entry) => entry.runId));
720
- if (named.size !== (input.absorb ?? []).length || named.has(run.id)) {
721
- throw new TypeError("An absorption names each successor once, and never the absorbing run");
722
- }
723
- const absorbable = (input.absorb ?? []).filter((entry) => {
724
- const candidate = current.runs.find((item) => item.id === entry.runId);
725
- return candidate !== undefined && candidate.id !== run.id && candidate.state === "queued" && candidate.conversationId === run.conversationId && candidate.inputMessageIds.length === entry.inputMessageIds.length && candidate.inputMessageIds.every((id, index) => id === entry.inputMessageIds[index]);
726
- });
727
- const absorbedIds = new Set(absorbable.flatMap((entry) => entry.inputMessageIds));
728
- const next = AgentRunSchema2.parse({
729
- ...run,
730
- state: runStateForTerminalReason2(input.reason),
731
- terminalReason: input.reason,
732
- ...input.policyName && { terminalPolicyName: input.policyName },
733
- ...input.usage && { usage: input.usage },
734
- ...absorbedIds.size > 0 && {
735
- inputMessageIds: [
736
- ...run.inputMessageIds,
737
- ...[...absorbedIds].filter((id) => !run.inputMessageIds.includes(id))
738
- ]
739
- },
740
- revision: run.revision + 1,
741
- updatedAt: new Date().toISOString()
742
- });
743
- const absorbedRuns = absorbable.map((entry) => {
744
- const candidate = current.runs.find((item) => item.id === entry.runId);
745
- if (!candidate)
746
- throw new TypeError("Absorbed run disappeared inside the reducer");
747
- return AgentRunSchema2.parse({
748
- ...candidate,
749
- state: runStateForTerminalReason2("absorbed"),
750
- terminalReason: "absorbed",
751
- absorbedIntoRunId: next.id,
752
- revision: candidate.revision + 1,
753
- updatedAt: new Date().toISOString()
754
- });
755
- });
756
- const runs = absorbedRuns.reduce((accumulated, absorbed) => replaceRun(accumulated, absorbed), replaceRun(current.runs, next));
757
- return applied(current, {
758
- runs,
759
- messages: replaceMessage(current.messages, input.assistant)
760
- }, {
761
- runRecords: [
762
- AgentStoredRunSchema2.parse({
763
- schemaVersion: 1,
764
- run: next,
765
- terminalAssistant: input.assistant
766
- }),
767
- ...absorbedRuns.map((absorbed) => AgentStoredRunSchema2.parse({ schemaVersion: 1, run: absorbed }))
768
- ],
769
- historyMutations: [{ type: "upsert-assistant", message: input.assistant }]
770
- });
771
- }
772
-
773
- // src/agent-runtime/store-reducer.ts
774
- function transitionRecord(operation) {
775
- if (operation.type !== "checkpoint")
776
- return operation;
777
- const { assistant, ...rest } = operation.input;
778
- const body = canonicalAgentJson2(assistant);
779
- return {
780
- type: operation.type,
781
- input: {
782
- ...rest,
783
- assistant: {
784
- id: assistant.id,
785
- status: assistant.status,
786
- sha256: createHash2("sha256").update(body).digest("hex"),
787
- parts: assistant.parts.length,
788
- bytes: Buffer.byteLength(body)
789
- }
790
- }
791
- };
792
- }
793
- function reduceStore(current, operation) {
794
- if (operation.type === "accept")
795
- return reduceAccept(current, operation.input);
796
- if (operation.type === "seed")
797
- return reduceSeed(current, operation.input);
798
- if (operation.type === "compact")
799
- return reduceCompact(current, operation.input);
800
- const run = current.runs.find((candidate) => candidate.id === operation.input.runId);
801
- if (!run)
802
- return { outcome: "not_found" };
803
- switch (operation.type) {
804
- case "acquire":
805
- return reduceAcquire(current, run, operation.input);
806
- case "checkpoint":
807
- return reduceCheckpoint(current, run, operation.input);
808
- case "operation":
809
- return reduceOperation(current, run, operation.input);
810
- case "interrupt":
811
- return reduceInterrupt(current, run, operation.input);
812
- case "recover":
813
- return reduceRecover(current, run, operation.input);
814
- case "terminal":
815
- return reduceTerminal(current, run, operation.input);
816
- }
817
- }
818
- function operationConversationId(operation) {
819
- return operation.type === "accept" ? operation.input.input.conversationId : operation.input.conversationId;
820
- }
821
-
822
- // src/agent-runtime/store-mutate.ts
823
- function validateAdmissionReceipt(receipt, record, conversationId) {
824
- const input = receipt.input;
825
- const run = record.run;
826
- if (receipt.conversationId !== conversationId || input.conversationId !== conversationId || input.role !== "user" || input.status !== "committed" || input.runId !== undefined || receipt.runId !== run.id || receipt.assistantMessageId !== run.assistantMessageId || !run.inputMessageIds.includes(input.id)) {
827
- throw new TypeError("Admission receipt does not match its canonical run assignment");
828
- }
829
- }
830
- async function readForMutation(driver, transaction, operation) {
831
- const conversationId = operationConversationId(operation);
832
- if (await driver.conversations?.isPurged(transaction, conversationId)) {
833
- throw new AgentConversationPurgedError2;
834
- }
835
- const operationRunId = operation.type === "accept" ? operation.input.coalesceIntoRunId : operation.type === "compact" || operation.type === "seed" ? undefined : operation.input.runId;
836
- const [stored, messages, activeRecords, operationRecord, duplicateReceipt] = await Promise.all([
837
- driver.head.load(transaction, conversationId),
838
- driver.history.load(transaction, conversationId),
839
- driver.runs.listActive(transaction, conversationId),
840
- operationRunId ? driver.runs.load(transaction, { conversationId, runId: operationRunId }) : undefined,
841
- operation.type === "accept" ? driver.admissions.load(transaction, {
842
- conversationId,
843
- idempotencyKey: operation.input.idempotencyKey
844
- }) : undefined
845
- ]);
846
- const head = AgentRuntimeHeadSchema2.parse(stored ?? emptyHead(conversationId));
847
- const referencedRecords = await driver.runs.loadMany(transaction, {
848
- conversationId,
849
- runIds: referencedRunIds(messages)
850
- });
851
- const records = mergeRunRecords(activeRecords, referencedRecords, operationRecord ? [operationRecord] : []);
852
- const current = snapshotOf(head, messages, records);
853
- return { conversationId, head, messages, records, current, duplicateReceipt };
854
- }
855
- async function settledSeed(driver, transaction, read, input) {
856
- const { conversationId, current } = read;
857
- const existing = await driver.seeds.load(transaction, {
858
- conversationId,
859
- seedKey: input.seedKey
860
- });
861
- if (existing)
862
- return { outcome: "applied", snapshot: current };
863
- let collisions = 0;
864
- for (const message of input.inputs) {
865
- if (current.messages.some((candidate) => candidate.id === message.id) || driver.history.hasMessage && await driver.history.hasMessage(transaction, {
866
- conversationId,
867
- messageId: message.id
868
- }))
869
- collisions++;
870
- }
871
- if (collisions > 0 && collisions < input.inputs.length) {
872
- throw new TypeError("Partial instruction seed collision: restore the complete seed before retrying");
873
- }
874
- if (collisions > 0) {
875
- await driver.seeds.create(transaction, AgentSeedReceiptSchema2.parse({
876
- schemaVersion: 1,
877
- conversationId,
878
- seedKey: input.seedKey,
879
- messageIds: input.inputs.map((message) => message.id)
880
- }));
881
- return { outcome: "applied", snapshot: current };
882
- }
883
- return;
884
- }
885
- async function duplicateAdmission(driver, transaction, read, duplicateReceipt) {
886
- const { conversationId, head, messages, records } = read;
887
- const duplicateRecord = await driver.runs.load(transaction, {
888
- conversationId,
889
- runId: duplicateReceipt.runId
890
- });
891
- if (!duplicateRecord) {
892
- throw new TypeError("Admission receipt points to a missing canonical run");
893
- }
894
- validateAdmissionReceipt(duplicateReceipt, duplicateRecord, conversationId);
895
- const answering = duplicateRecord.run.absorbedIntoRunId ? await driver.runs.load(transaction, {
896
- conversationId,
897
- runId: duplicateRecord.run.absorbedIntoRunId
898
- }) : undefined;
899
- if (duplicateRecord.run.absorbedIntoRunId && !answering) {
900
- throw new TypeError("Absorbed run points to a missing absorbing run");
901
- }
902
- const canonical = answering ?? duplicateRecord;
903
- return {
904
- outcome: "duplicate",
905
- input: duplicateReceipt.input,
906
- inputMessageId: duplicateReceipt.input.id,
907
- runId: canonical.run.id,
908
- assistantMessageId: canonical.run.assistantMessageId,
909
- run: canonical.run,
910
- ...canonical.terminalAssistant && {
911
- assistant: canonical.terminalAssistant
912
- },
913
- snapshot: snapshotOf(head, messages, mergeRunRecords(records, [duplicateRecord], answering ? [answering] : []))
914
- };
915
- }
916
- async function assertAdmissionIdentitiesFree(driver, transaction, conversationId, input) {
917
- const inputCollision = await driver.admissions.loadByInputMessageId(transaction, {
918
- conversationId,
919
- inputMessageId: input.input.id
920
- });
921
- if (inputCollision) {
922
- throw new TypeError("Input message identity is already assigned to an admission");
923
- }
924
- if (!input.coalesceIntoRunId) {
925
- const [runCollision, assistantCollision] = await Promise.all([
926
- driver.runs.load(transaction, {
927
- conversationId,
928
- runId: input.run.id
929
- }),
930
- driver.runs.loadByAssistantMessageId(transaction, {
931
- conversationId,
932
- assistantMessageId: input.run.assistantMessageId
933
- })
934
- ]);
935
- if (runCollision || assistantCollision) {
936
- throw new TypeError("Queued run identities are already reserved");
937
- }
938
- }
939
- }
940
- async function persistApplied(driver, transaction, read, operation, reduced) {
941
- const { conversationId, current } = read;
942
- const nextHead = AgentRuntimeHeadSchema2.parse({
943
- schemaVersion: 1,
944
- conversationId,
945
- version: reduced.snapshot.version
946
- });
947
- const outcome = await driver.head.compareAndSwap(transaction, {
948
- conversationId,
949
- expectedVersion: current.version,
950
- next: nextHead
951
- });
952
- if (outcome.outcome === "conflict")
953
- return conflict(outcome.actualVersion);
954
- for (const record of reduced.runRecords ?? []) {
955
- await driver.runs.save(transaction, record);
956
- }
957
- if (reduced.admissionReceipt) {
958
- await driver.admissions.create(transaction, reduced.admissionReceipt);
959
- }
960
- if (reduced.seedReceipt) {
961
- await driver.seeds.create(transaction, reduced.seedReceipt);
962
- }
963
- for (const mutation of reduced.historyMutations ?? []) {
964
- await driver.history.apply(transaction, mutation);
965
- }
966
- await driver.events.append(transaction, agentStoreEventDraft({
967
- conversationId,
968
- kind: "runtime/transition",
969
- payload: z4.json().parse(transitionRecord(operation))
970
- }));
971
- return { outcome: "applied", snapshot: reduced.snapshot };
972
- }
973
- function mutateStore(driver, operation) {
974
- return driver.transaction(async (transaction) => {
975
- const read = await readForMutation(driver, transaction, operation);
976
- if (operation.type === "seed") {
977
- const settled = await settledSeed(driver, transaction, read, operation.input);
978
- if (settled)
979
- return settled;
980
- }
981
- if (read.duplicateReceipt) {
982
- return duplicateAdmission(driver, transaction, read, read.duplicateReceipt);
983
- }
984
- if (operation.type === "accept") {
985
- await assertAdmissionIdentitiesFree(driver, transaction, read.conversationId, operation.input);
986
- }
987
- const reduced = reduceStore(read.current, operation);
988
- if (reduced.outcome !== "applied")
989
- return reduced;
990
- return persistApplied(driver, transaction, read, operation, reduced);
991
- });
992
- }
993
-
994
- // src/agent-runtime/store-purge.ts
995
- function createStoreConversationPurge(driver, conversations) {
996
- return async (input) => {
997
- const { conversationId, expectedVersion } = AgentConversationPurgeInputSchema2.parse(input);
998
- return driver.transaction(async (transaction) => {
999
- if (await conversations.isPurged(transaction, conversationId)) {
1000
- return { outcome: "already_purged" };
1001
- }
1002
- const head = await driver.head.load(transaction, conversationId);
1003
- const actualVersion = head?.version ?? 0;
1004
- if (expectedVersion !== undefined && expectedVersion !== actualVersion) {
1005
- return { outcome: "conflict", actualVersion };
1006
- }
1007
- const active = await driver.runs.listActive(transaction, conversationId);
1008
- if (active.length > 0) {
1009
- return { outcome: "active", runIds: active.map((record) => record.run.id) };
1010
- }
1011
- await conversations.remove(transaction, conversationId);
1012
- return { outcome: "purged" };
1013
- });
1014
- };
1015
- }
1016
-
1017
- // src/agent-runtime/store-create.ts
1018
- var AgentRecoverableScanInputSchema = z5.object({
1019
- cursor: z5.string().min(1).optional(),
1020
- limit: z5.number().int().min(1).max(1000)
1021
- });
1022
- function createAgentRuntimeStore2(driver) {
1023
- const mutate = (operation) => mutateStore(driver, operation);
1024
- return {
1025
- loadSnapshot: (conversationId) => loadSnapshot(driver, conversationId),
1026
- loadRun: (input) => loadRun(driver, input),
1027
- listActiveRuns: (conversationId) => listActiveRuns(driver, conversationId),
1028
- appendEventOnce: (input, key) => appendEventOnce(driver, input, key),
1029
- findEventOnce: (input) => findEventOnce(driver, input),
1030
- appendEvent: (input) => appendEvent(driver, input),
1031
- readEvents: (input) => readEvents(driver, input),
1032
- exportConversation: (conversationId) => exportConversation(driver, conversationId),
1033
- importConversation: (bytes) => importConversation(driver, bytes),
1034
- ...driver.conversations && {
1035
- purgeConversation: createStoreConversationPurge(driver, driver.conversations)
1036
- },
1037
- acceptInputAndAssignRun: (input) => mutate({
1038
- type: "accept",
1039
- input: AcceptInputAndAssignRunSchema2.parse(input)
1040
- }),
1041
- acquireRun: (input) => mutate({ type: "acquire", input: AcquireAgentRunSchema2.parse(input) }),
1042
- checkpointRunAssistant: (input) => mutate({
1043
- type: "checkpoint",
1044
- input: CheckpointRunAssistantSchema2.parse(input)
1045
- }),
1046
- recordRunOperation: (input) => mutate({
1047
- type: "operation",
1048
- input: RecordRunOperationSchema2.parse(input)
1049
- }),
1050
- requestRunInterrupt: (input) => mutate({
1051
- type: "interrupt",
1052
- input: RequestRunInterruptSchema2.parse(input)
1053
- }),
1054
- recoverRun: (input) => mutate({ type: "recover", input: RecoverAgentRunSchema2.parse(input) }),
1055
- commitRunTerminal: (input) => mutate({ type: "terminal", input: CommitRunTerminalSchema2.parse(input) }),
1056
- replaceCompactedRange: (input) => mutate({
1057
- type: "compact",
1058
- input: ReplaceCompactedRangeSchema2.parse(input)
1059
- }),
1060
- seedConversationInput: (input) => mutate({
1061
- type: "seed",
1062
- input: SeedConversationInputSchema2.parse(input)
1063
- }),
1064
- async scanRecoverable(input) {
1065
- const parsed = AgentRecoverableScanInputSchema.parse(input);
1066
- return AgentRecoverablePageSchema2.parse(await driver.scanRecoverable(parsed));
1067
- }
1068
- };
1069
- }
1070
-
1071
- export { AgentConversationPurgeInputSchema2, AgentConversationPurgeResultSchema2, AgentConversationPurgedError2, purgeAgentConversation2, AgentRuntimeHeadSchema2, AgentStoredRunSchema2, AgentAdmissionReceiptSchema2, AgentSeedReceiptSchema2, AgentHistoryMutationSchema2, ACTIVE_AGENT_RUN_STATES2, isActiveRunState, replaceMessage, appendEventIn, createAgentRuntimeStore2 };