stitchkit 0.68.10 → 0.69.0

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 (124) hide show
  1. package/README.md +30 -1
  2. package/dist/agent-runtime/coding-tool-contract.d.ts +155 -0
  3. package/dist/agent-runtime/coding-tool-contract.d.ts.map +1 -0
  4. package/dist/agent-runtime/coding-tool-files.d.ts +3 -0
  5. package/dist/agent-runtime/coding-tool-files.d.ts.map +1 -0
  6. package/dist/agent-runtime/coding-tool-paths.d.ts +19 -0
  7. package/dist/agent-runtime/coding-tool-paths.d.ts.map +1 -0
  8. package/dist/agent-runtime/coding-tool-search-patch.d.ts +3 -0
  9. package/dist/agent-runtime/coding-tool-search-patch.d.ts.map +1 -0
  10. package/dist/agent-runtime/coding-tool-shell.d.ts +3 -0
  11. package/dist/agent-runtime/coding-tool-shell.d.ts.map +1 -0
  12. package/dist/agent-runtime/coding-tools.d.ts +17 -0
  13. package/dist/agent-runtime/coding-tools.d.ts.map +1 -0
  14. package/dist/agent-runtime/compaction.d.ts +2 -0
  15. package/dist/agent-runtime/compaction.d.ts.map +1 -1
  16. package/dist/agent-runtime/contained-files.d.ts +31 -0
  17. package/dist/agent-runtime/contained-files.d.ts.map +1 -0
  18. package/dist/agent-runtime/control-schema.d.ts +1074 -0
  19. package/dist/agent-runtime/control-schema.d.ts.map +1 -0
  20. package/dist/agent-runtime/conversations.d.ts +128 -0
  21. package/dist/agent-runtime/conversations.d.ts.map +1 -0
  22. package/dist/agent-runtime/event-schema.d.ts +96 -0
  23. package/dist/agent-runtime/event-schema.d.ts.map +1 -1
  24. package/dist/agent-runtime/harness-contract.d.ts +169 -0
  25. package/dist/agent-runtime/harness-contract.d.ts.map +1 -0
  26. package/dist/agent-runtime/harness-control.d.ts +25 -0
  27. package/dist/agent-runtime/harness-control.d.ts.map +1 -0
  28. package/dist/agent-runtime/harness-file-resources.d.ts +33 -0
  29. package/dist/agent-runtime/harness-file-resources.d.ts.map +1 -0
  30. package/dist/agent-runtime/harness-resources.d.ts +5 -0
  31. package/dist/agent-runtime/harness-resources.d.ts.map +1 -0
  32. package/dist/agent-runtime/harness.d.ts +12 -0
  33. package/dist/agent-runtime/harness.d.ts.map +1 -0
  34. package/dist/agent-runtime/history.d.ts +2 -0
  35. package/dist/agent-runtime/history.d.ts.map +1 -1
  36. package/dist/agent-runtime/models.d.ts +199 -0
  37. package/dist/agent-runtime/models.d.ts.map +1 -1
  38. package/dist/agent-runtime/prompt.d.ts +2 -0
  39. package/dist/agent-runtime/prompt.d.ts.map +1 -1
  40. package/dist/agent-runtime/run-execution.d.ts.map +1 -1
  41. package/dist/agent-runtime/runtime.d.ts +11 -3
  42. package/dist/agent-runtime/runtime.d.ts.map +1 -1
  43. package/dist/agent-runtime/schemas.d.ts +49 -0
  44. package/dist/agent-runtime/schemas.d.ts.map +1 -1
  45. package/dist/agent-runtime/sqlite.d.ts +2 -0
  46. package/dist/agent-runtime/sqlite.d.ts.map +1 -1
  47. package/dist/agent-runtime/store-driver.d.ts +61 -212
  48. package/dist/agent-runtime/store-driver.d.ts.map +1 -1
  49. package/dist/agent-runtime/store.d.ts +368 -1
  50. package/dist/agent-runtime/store.d.ts.map +1 -1
  51. package/dist/agent-runtime/terminal-commit.d.ts +12 -1
  52. package/dist/agent-runtime/terminal-commit.d.ts.map +1 -1
  53. package/dist/agent-runtime/terminal-status.d.ts +8 -0
  54. package/dist/agent-runtime/terminal-status.d.ts.map +1 -1
  55. package/dist/agent-runtime-browser.d.ts +1 -0
  56. package/dist/agent-runtime-browser.d.ts.map +1 -1
  57. package/dist/agent-runtime-browser.js +217 -1
  58. package/dist/agent-runtime-coding-tools.d.ts +2 -0
  59. package/dist/agent-runtime-coding-tools.d.ts.map +1 -0
  60. package/dist/agent-runtime-coding-tools.js +706 -0
  61. package/dist/agent-runtime-harness.d.ts +2 -0
  62. package/dist/agent-runtime-harness.d.ts.map +1 -0
  63. package/dist/agent-runtime-harness.js +700 -0
  64. package/dist/agent-runtime-openrouter.d.ts +14 -1
  65. package/dist/agent-runtime-openrouter.d.ts.map +1 -1
  66. package/dist/agent-runtime-openrouter.js +211 -0
  67. package/dist/agent-runtime-sqlite-bun.js +4 -3
  68. package/dist/agent-runtime-sqlite-node.js +4 -3
  69. package/dist/agent-runtime.d.ts +5 -3
  70. package/dist/agent-runtime.d.ts.map +1 -1
  71. package/dist/agent-runtime.js +106 -2580
  72. package/dist/application/diagnostic-journal-contract.d.ts +164 -0
  73. package/dist/application/diagnostic-journal-contract.d.ts.map +1 -0
  74. package/dist/application/diagnostic-journal-manager.d.ts +12 -0
  75. package/dist/application/diagnostic-journal-manager.d.ts.map +1 -0
  76. package/dist/application/diagnostic-journal-storage.d.ts +29 -0
  77. package/dist/application/diagnostic-journal-storage.d.ts.map +1 -0
  78. package/dist/application/diagnostic-journal.d.ts +11 -0
  79. package/dist/application/diagnostic-journal.d.ts.map +1 -0
  80. package/dist/application.d.ts +2 -0
  81. package/dist/application.d.ts.map +1 -1
  82. package/dist/application.js +561 -17
  83. package/dist/browser/socket-io.d.ts +8 -2
  84. package/dist/browser/socket-io.d.ts.map +1 -1
  85. package/dist/cli.js +8 -6
  86. package/dist/{index-8vpzxg55.js → index-10gbbbaa.js} +103 -2
  87. package/dist/index-3eqrkqhg.js +2565 -0
  88. package/dist/{index-hcx9yypn.js → index-444747ww.js} +7 -7
  89. package/dist/{index-557by2db.js → index-7b188kmz.js} +15 -0
  90. package/dist/{index-hxh98zbm.js → index-d1jsvkyk.js} +1 -1
  91. package/dist/index-es0h4w26.js +63 -0
  92. package/dist/{index-grgvpbch.js → index-gqdfpv4n.js} +4 -2
  93. package/dist/{index-bt5179zb.js → index-h7ctj1kp.js} +5 -3
  94. package/dist/{index-y2ctppmg.js → index-h8vn1jcr.js} +7 -73
  95. package/dist/{index-hqza5nde.js → index-hsabxjz0.js} +78 -77
  96. package/dist/index-kg9xx84n.js +73 -0
  97. package/dist/{index-hb0mncmj.js → index-kxxyvkka.js} +2 -2
  98. package/dist/{index-2t6zt5cg.js → index-mbxds404.js} +7 -5
  99. package/dist/{index-f24xg2cw.js → index-p1be103g.js} +1 -1
  100. package/dist/{index-xyvxez9r.js → index-q7gdep2c.js} +5 -5
  101. package/dist/{index-t23p2b68.js → index-t4dpby6e.js} +1 -1
  102. package/dist/index-tg3m2ec5.js +157 -0
  103. package/dist/index-v3dpzpjw.js +92 -0
  104. package/dist/{index-eqqyd9v8.js → index-wwst0td5.js} +2 -46
  105. package/dist/{index-ysphyxax.js → index-x1th9s8c.js} +23 -2
  106. package/dist/index-xxsq3ca1.js +51 -0
  107. package/dist/{index-22tjt2rk.js → index-zh459sfj.js} +1 -1
  108. package/dist/index.js +183 -11
  109. package/dist/internal/ai-sdk-typed.d.ts +14 -0
  110. package/dist/internal/ai-sdk-typed.d.ts.map +1 -0
  111. package/dist/node.js +6 -6
  112. package/dist/observability/index.js +4 -4
  113. package/dist/realtime/index.d.ts +1 -1
  114. package/dist/realtime/index.d.ts.map +1 -1
  115. package/dist/realtime/request.d.ts +30 -0
  116. package/dist/realtime/request.d.ts.map +1 -1
  117. package/dist/remote.js +6 -6
  118. package/dist/server/index.js +10 -10
  119. package/dist/testing.js +6 -6
  120. package/dist/tool-invoker.js +6 -5
  121. package/dist/tools.js +21 -17
  122. package/llms-full.txt +385 -24
  123. package/package.json +10 -2
  124. package/dist/{index-pgsyp3xh.js → index-x18ndp4p.js} +3 -3
@@ -0,0 +1,2565 @@
1
+ import {
2
+ assistantStatus,
3
+ isAssistantHistoryEvidence,
4
+ isCompleteAgentHistoryTurn
5
+ } from "./index-es0h4w26.js";
6
+ import {
7
+ createBoundedSinkManager
8
+ } from "./index-a59da114.js";
9
+ import {
10
+ ToolExecutionControlError,
11
+ isToolExecutionControlError
12
+ } from "./index-h8vn1jcr.js";
13
+ import {
14
+ AgentAssistantPlaceholderSchema,
15
+ AgentJsonObjectSchema,
16
+ AgentMessagePartSchema,
17
+ AgentMessageSchema,
18
+ AgentProvenanceSchema,
19
+ AgentProviderEnvelopeSchema,
20
+ AgentRecordIdSchema,
21
+ AgentRecordVersionSchema,
22
+ AgentRunMetricsSchema,
23
+ AgentRunSchema,
24
+ AgentRunStateSchema,
25
+ AgentSnapshotSchema,
26
+ AgentTerminalReasonSchema,
27
+ AgentTimestampSchema,
28
+ runStateForTerminalReason
29
+ } from "./index-x1th9s8c.js";
30
+ import {
31
+ isRecord,
32
+ transportResult
33
+ } from "./index-qyrqwr4c.js";
34
+
35
+ // src/agent-runtime/context-refusal.ts
36
+ class AgentContextOverflowError extends Error {
37
+ name = "AgentContextOverflowError";
38
+ constructor(message = "Agent context exceeds the configured model budget", options) {
39
+ super(message, options);
40
+ }
41
+ }
42
+
43
+ // src/agent-runtime/coordinator.ts
44
+ function assertCloseBudgets(options) {
45
+ for (const [name, value] of Object.entries(options)) {
46
+ if (value !== undefined && (!Number.isSafeInteger(value) || value < 0)) {
47
+ throw new TypeError(`${name} must be a non-negative safe integer`);
48
+ }
49
+ }
50
+ }
51
+ function createAgentSessionCoordinator() {
52
+ const lanes = new Map;
53
+ let closed = false;
54
+ const waitWithin = async (settled, timeoutMs) => {
55
+ if (timeoutMs === 0)
56
+ return false;
57
+ let timer;
58
+ const timeout = new Promise((resolve) => {
59
+ timer = setTimeout(() => resolve(false), timeoutMs);
60
+ });
61
+ const completed = settled.then(() => true);
62
+ const result = await Promise.race([completed, timeout]);
63
+ if (timer !== undefined)
64
+ clearTimeout(timer);
65
+ return result;
66
+ };
67
+ const laneFor = (key) => {
68
+ const existing = lanes.get(key);
69
+ if (existing)
70
+ return existing;
71
+ const created = { queue: [] };
72
+ lanes.set(key, created);
73
+ return created;
74
+ };
75
+ const startNext = (key, lane) => {
76
+ if (lane.active)
77
+ return;
78
+ const next = lane.queue.shift();
79
+ if (!next) {
80
+ lanes.delete(key);
81
+ return;
82
+ }
83
+ next.start();
84
+ };
85
+ return {
86
+ submit(input) {
87
+ const accepted = Promise.withResolvers();
88
+ const result = Promise.withResolvers();
89
+ if (closed) {
90
+ const error = new Error("Agent session coordinator is closed");
91
+ accepted.reject(error);
92
+ result.reject(error);
93
+ return { accepted: accepted.promise, result: result.promise };
94
+ }
95
+ const lane = laneFor(input.key);
96
+ const pending = {
97
+ priority: input.policy === "interrupt-next",
98
+ reject(reason) {
99
+ accepted.reject(reason);
100
+ result.reject(reason);
101
+ },
102
+ async start() {
103
+ const controller = new AbortController;
104
+ const settlement = Promise.withResolvers();
105
+ lane.active = { controller, settled: settlement.promise };
106
+ try {
107
+ const coordinated = await input.create(controller.signal);
108
+ accepted.resolve();
109
+ result.resolve(await coordinated.execute());
110
+ } catch (error) {
111
+ accepted.reject(error);
112
+ result.reject(error);
113
+ } finally {
114
+ settlement.resolve();
115
+ lane.active = undefined;
116
+ startNext(input.key, lane);
117
+ }
118
+ }
119
+ };
120
+ if (input.policy === "interrupt" || input.policy === "interrupt-next") {
121
+ lane.active?.controller.abort("user-interrupt");
122
+ }
123
+ if (input.policy === "supersede")
124
+ lane.active?.controller.abort("supersede");
125
+ if (pending.priority) {
126
+ const firstOrdinary = lane.queue.findIndex((queued) => !queued.priority);
127
+ if (firstOrdinary === -1)
128
+ lane.queue.push(pending);
129
+ else
130
+ lane.queue.splice(firstOrdinary, 0, pending);
131
+ } else {
132
+ lane.queue.push(pending);
133
+ }
134
+ startNext(input.key, lane);
135
+ return { accepted: accepted.promise, result: result.promise };
136
+ },
137
+ stop(key, reason = "user-interrupt") {
138
+ const lane = lanes.get(key);
139
+ if (!lane?.active)
140
+ return false;
141
+ lane.active.controller.abort(reason);
142
+ return true;
143
+ },
144
+ async close(options = {}) {
145
+ assertCloseBudgets(options);
146
+ closed = true;
147
+ const error = new Error("Agent session coordinator is closed");
148
+ for (const lane of lanes.values()) {
149
+ for (const pending of lane.queue.splice(0))
150
+ pending.reject(error);
151
+ }
152
+ const active = [...lanes.values()].map((lane) => lane.active).filter((run) => run !== undefined);
153
+ const settlements = active.map((run) => run.settled);
154
+ const outstanding = new Set(settlements);
155
+ for (const settled of settlements) {
156
+ settled.then(() => {
157
+ outstanding.delete(settled);
158
+ });
159
+ }
160
+ const drain = Promise.all(settlements).then(() => {
161
+ return;
162
+ });
163
+ const finished = () => ({
164
+ settled: outstanding.size === 0,
165
+ timedOut: outstanding.size > 0,
166
+ remaining: outstanding.size
167
+ });
168
+ if (options.gracePeriodMs !== undefined && await waitWithin(drain, options.gracePeriodMs)) {
169
+ return finished();
170
+ }
171
+ for (const run of active)
172
+ run.controller.abort("shutdown");
173
+ if (options.forceTimeoutMs === undefined) {
174
+ await drain;
175
+ return finished();
176
+ }
177
+ await waitWithin(drain, options.forceTimeoutMs);
178
+ return finished();
179
+ },
180
+ isRunning(key) {
181
+ return lanes.get(key)?.active !== undefined;
182
+ }
183
+ };
184
+ }
185
+
186
+ // src/agent-runtime/event-schema.ts
187
+ import { z } from "zod";
188
+ var AgentAdmissionEventSchema = z.object({
189
+ type: z.literal("admission"),
190
+ eventId: AgentRecordIdSchema,
191
+ conversationId: AgentRecordIdSchema,
192
+ runId: AgentRecordIdSchema,
193
+ snapshotVersion: AgentRecordVersionSchema,
194
+ input: AgentMessageSchema,
195
+ run: AgentRunSchema,
196
+ assistant: z.union([AgentAssistantPlaceholderSchema, AgentMessageSchema]),
197
+ emittedAt: AgentTimestampSchema
198
+ });
199
+ var EventIdentitySchema = z.object({
200
+ conversationId: AgentRecordIdSchema,
201
+ runId: AgentRecordIdSchema,
202
+ emittedAt: AgentTimestampSchema
203
+ });
204
+ var AgentTransientDeltaEventSchema = EventIdentitySchema.extend({
205
+ type: z.literal("assistant-delta"),
206
+ runtimeEpoch: z.string().min(1),
207
+ sequence: z.int().nonnegative(),
208
+ textDelta: z.string()
209
+ });
210
+ var AgentTransientReasoningIdentitySchema = EventIdentitySchema.extend({
211
+ runtimeEpoch: z.string().min(1),
212
+ sequence: z.int().nonnegative(),
213
+ provider: AgentProviderEnvelopeSchema.optional()
214
+ });
215
+ var AgentReasoningStartEventSchema = AgentTransientReasoningIdentitySchema.extend({
216
+ type: z.literal("reasoning-start")
217
+ });
218
+ var AgentReasoningDeltaEventSchema = AgentTransientReasoningIdentitySchema.extend({
219
+ type: z.literal("reasoning-delta"),
220
+ textDelta: z.string()
221
+ });
222
+ var AgentReasoningEndEventSchema = AgentTransientReasoningIdentitySchema.extend({
223
+ type: z.literal("reasoning-end")
224
+ });
225
+ var AgentCheckpointEventSchema = EventIdentitySchema.extend({
226
+ type: z.literal("assistant-checkpoint"),
227
+ eventId: AgentRecordIdSchema,
228
+ snapshotVersion: AgentRecordVersionSchema,
229
+ message: AgentMessageSchema,
230
+ metrics: AgentRunMetricsSchema.optional()
231
+ });
232
+ var AgentRunStateEventSchema = EventIdentitySchema.extend({
233
+ type: z.literal("run-state"),
234
+ eventId: AgentRecordIdSchema,
235
+ snapshotVersion: AgentRecordVersionSchema,
236
+ state: AgentRunStateSchema
237
+ });
238
+ var AgentToolStatusEventSchema = EventIdentitySchema.extend({
239
+ type: z.literal("tool-status"),
240
+ runtimeEpoch: z.string().min(1),
241
+ sequence: z.int().nonnegative(),
242
+ callId: AgentRecordIdSchema,
243
+ toolName: z.string().min(1),
244
+ status: z.enum(["started", "completed", "failed", "interrupted"]),
245
+ input: z.json().optional(),
246
+ output: z.json().optional()
247
+ });
248
+ var AgentTerminalEventSchema = EventIdentitySchema.extend({
249
+ type: z.literal("terminal"),
250
+ eventId: AgentRecordIdSchema,
251
+ snapshotVersion: AgentRecordVersionSchema,
252
+ reason: AgentTerminalReasonSchema,
253
+ policyName: z.string().min(1).optional(),
254
+ message: AgentMessageSchema,
255
+ metrics: AgentRunMetricsSchema.optional()
256
+ });
257
+ var AgentRuntimeEventSchema = z.discriminatedUnion("type", [
258
+ AgentAdmissionEventSchema,
259
+ AgentTransientDeltaEventSchema,
260
+ AgentReasoningStartEventSchema,
261
+ AgentReasoningDeltaEventSchema,
262
+ AgentReasoningEndEventSchema,
263
+ AgentCheckpointEventSchema,
264
+ AgentRunStateEventSchema,
265
+ AgentToolStatusEventSchema,
266
+ AgentTerminalEventSchema
267
+ ]);
268
+ var AgentRuntimeEventCursorSchema = z.object({
269
+ snapshotVersion: AgentRecordVersionSchema.optional(),
270
+ durableEventIds: z.array(AgentRecordIdSchema).optional(),
271
+ runtimeEpoch: z.string().min(1).optional(),
272
+ sequence: z.int().nonnegative().optional()
273
+ });
274
+ function isDurableEvent(event) {
275
+ return event.type === "admission" || event.type === "assistant-checkpoint" || event.type === "run-state" || event.type === "terminal";
276
+ }
277
+ function advanceAgentRuntimeEventCursor(rawCursor, event) {
278
+ const cursor = AgentRuntimeEventCursorSchema.parse(rawCursor);
279
+ if (isDurableEvent(event)) {
280
+ const previous = cursor.snapshotVersion;
281
+ const durableEventIds = previous === event.snapshotVersion ? cursor.durableEventIds ?? [] : [];
282
+ if (previous !== undefined && event.snapshotVersion < previous || durableEventIds.includes(event.eventId)) {
283
+ return { status: "duplicate", cursor };
284
+ }
285
+ return {
286
+ status: "accepted",
287
+ cursor: {
288
+ ...cursor,
289
+ snapshotVersion: event.snapshotVersion,
290
+ durableEventIds: [...durableEventIds, event.eventId]
291
+ }
292
+ };
293
+ }
294
+ const previousSequence = cursor.runtimeEpoch === event.runtimeEpoch ? cursor.sequence : undefined;
295
+ if (previousSequence !== undefined && event.sequence <= previousSequence) {
296
+ return { status: "duplicate", cursor };
297
+ }
298
+ return {
299
+ status: previousSequence !== undefined && event.sequence > previousSequence + 1 ? "gap" : "accepted",
300
+ cursor: { ...cursor, runtimeEpoch: event.runtimeEpoch, sequence: event.sequence }
301
+ };
302
+ }
303
+ function agentDurableEventId(type, runId, snapshotVersion) {
304
+ return `${runId}:${type}:${snapshotVersion}`;
305
+ }
306
+
307
+ // src/agent-runtime/events.ts
308
+ function createAgentRuntimeEventSink(config) {
309
+ const manager = createBoundedSinkManager({
310
+ write: config.write,
311
+ ...config.maxPending !== undefined && { maxPending: config.maxPending },
312
+ ...config.onSinkError && { onSinkError: config.onSinkError },
313
+ ...config.onDrop && { onDrop: config.onDrop }
314
+ });
315
+ return {
316
+ publish(rawEvent) {
317
+ const event = AgentRuntimeEventSchema.parse(rawEvent);
318
+ const projected = config.project?.(event) ?? (config.project ? undefined : event);
319
+ if (projected)
320
+ manager.submit(() => AgentRuntimeEventSchema.parse(projected));
321
+ },
322
+ flush: () => manager.flush(),
323
+ getStatus: () => manager.getStatus(),
324
+ close: () => manager.close()
325
+ };
326
+ }
327
+
328
+ // src/agent-runtime/history.ts
329
+ import { modelMessageSchema as modelMessageSchema2 } from "ai";
330
+
331
+ // src/internal/ai-sdk-typed.ts
332
+ import { modelMessageSchema, streamText } from "ai";
333
+ function streamAgentTextBoundary(options) {
334
+ return streamText(options);
335
+ }
336
+ function modelMessageWithApprovalSignature(input) {
337
+ const parsed = modelMessageSchema.parse(input);
338
+ const rawContent = isRecord(input) ? input.content : undefined;
339
+ if (parsed.role !== "assistant" || typeof parsed.content === "string" || !Array.isArray(rawContent)) {
340
+ return parsed;
341
+ }
342
+ const content = parsed.content.map((part, index) => {
343
+ const raw = rawContent[index];
344
+ if (part.type !== "tool-approval-request" || !isRecord(raw) || typeof raw.signature !== "string") {
345
+ return part;
346
+ }
347
+ return { ...part, signature: raw.signature };
348
+ });
349
+ return transportResult({ ...parsed, content });
350
+ }
351
+
352
+ // src/agent-runtime/history.ts
353
+ function providerOptions(envelope) {
354
+ if (!envelope)
355
+ return;
356
+ return envelope.provider === "ai-sdk" ? envelope.data : { [envelope.provider]: envelope.data };
357
+ }
358
+ function textContent(parts) {
359
+ return parts.filter((part) => part.type === "text").map((part) => part.text).join(`
360
+ `);
361
+ }
362
+ function unrepresented(parts, rendered) {
363
+ const missing = new Set;
364
+ for (const part of parts) {
365
+ if (!rendered.has(part.type))
366
+ missing.add(part.type);
367
+ }
368
+ return [...missing];
369
+ }
370
+ function decide(message, action, reason, rendered) {
371
+ if (action === "omitted" || !rendered)
372
+ return { messageId: message.id, action, reason };
373
+ const omittedParts = unrepresented(message.parts, rendered);
374
+ return {
375
+ messageId: message.id,
376
+ action,
377
+ reason,
378
+ ...omittedParts.length > 0 && { omittedParts }
379
+ };
380
+ }
381
+ var INTERRUPTION_NOTE = "[interrupted: this turn was cut off before it finished]";
382
+ var FAILURE_NOTE = "[failed: partial evidence from a run that did not complete successfully]";
383
+ async function userMessage(message, options) {
384
+ const rendered = new Set;
385
+ const text = textContent(message.parts);
386
+ const content = [];
387
+ if (text) {
388
+ content.push({ type: "text", text });
389
+ rendered.add("text");
390
+ }
391
+ for (const part of message.parts) {
392
+ if (part.type !== "file")
393
+ continue;
394
+ if (options.resolveFile) {
395
+ content.push({
396
+ type: "file",
397
+ data: await options.resolveFile(part, message),
398
+ mediaType: part.mediaType,
399
+ ...part.filename && { filename: part.filename }
400
+ });
401
+ rendered.add("file");
402
+ continue;
403
+ }
404
+ const fallback = options.unresolvedFile ?? "omit";
405
+ if (fallback === "error") {
406
+ throw new Error(`No history file resolver configured for ${part.reference}`);
407
+ }
408
+ if (fallback === "text") {
409
+ const described = part.filename ?? part.mediaType;
410
+ content.push({
411
+ type: "text",
412
+ text: described ? `[attachment: ${described}]` : "[attachment]"
413
+ });
414
+ rendered.add("file");
415
+ }
416
+ }
417
+ if (content.length === 0)
418
+ return { rendered };
419
+ return { message: modelMessageSchema2.parse({ role: "user", content }), rendered };
420
+ }
421
+ function assistantMessages(message, marker) {
422
+ const rendered = new Set;
423
+ const messages = [];
424
+ let role;
425
+ let content = [];
426
+ const flush = () => {
427
+ if (!role || content.length === 0)
428
+ return;
429
+ messages.push(modelMessageWithApprovalSignature({ role, content }));
430
+ content = [];
431
+ };
432
+ const append = (nextRole, part) => {
433
+ if (role !== nextRole) {
434
+ flush();
435
+ role = nextRole;
436
+ }
437
+ content.push(part);
438
+ };
439
+ for (const part of message.parts) {
440
+ if (part.type === "text") {
441
+ append("assistant", { type: "text", text: part.text });
442
+ rendered.add("text");
443
+ }
444
+ if (part.type === "reasoning") {
445
+ append("assistant", {
446
+ type: "reasoning",
447
+ text: part.text,
448
+ ...part.provider && { providerOptions: providerOptions(part.provider) }
449
+ });
450
+ rendered.add("reasoning");
451
+ }
452
+ if (part.type === "tool-call") {
453
+ append("assistant", {
454
+ type: "tool-call",
455
+ toolCallId: part.callId,
456
+ toolName: part.toolName,
457
+ input: part.input,
458
+ ...part.provider && { providerOptions: providerOptions(part.provider) }
459
+ });
460
+ rendered.add("tool-call");
461
+ }
462
+ if (part.type === "tool-result") {
463
+ const output = part.outcome === "success" ? { type: "json", value: part.output ?? null } : { type: "error-json", value: part.output ?? { message: part.outcome } };
464
+ append("tool", {
465
+ type: "tool-result",
466
+ toolCallId: part.callId,
467
+ toolName: part.toolName,
468
+ output
469
+ });
470
+ rendered.add("tool-result");
471
+ }
472
+ if (part.type === "tool-approval-request") {
473
+ append("assistant", {
474
+ type: "tool-approval-request",
475
+ approvalId: part.approvalId,
476
+ toolCallId: part.callId,
477
+ ...part.isAutomatic !== undefined && { isAutomatic: part.isAutomatic },
478
+ ...part.signature && { signature: part.signature }
479
+ });
480
+ rendered.add("tool-approval-request");
481
+ }
482
+ if (part.type === "tool-approval-response") {
483
+ append("tool", {
484
+ type: "tool-approval-response",
485
+ approvalId: part.approvalId,
486
+ approved: part.approved,
487
+ ...part.reason && { reason: part.reason }
488
+ });
489
+ rendered.add("tool-approval-response");
490
+ }
491
+ }
492
+ if (marker && (messages.length > 0 || content.length > 0)) {
493
+ append("assistant", {
494
+ type: "text",
495
+ text: marker === "interrupted" ? INTERRUPTION_NOTE : FAILURE_NOTE
496
+ });
497
+ rendered.add("control");
498
+ }
499
+ flush();
500
+ return { messages, rendered };
501
+ }
502
+ function interruptedSystemNote(message) {
503
+ const rendered = new Set;
504
+ const text = textContent(message.parts);
505
+ if (!text)
506
+ return { rendered };
507
+ rendered.add("text");
508
+ rendered.add("control");
509
+ return { text: `[interrupted] partial response: ${text}`, rendered };
510
+ }
511
+ function completeToolChronology(message) {
512
+ const pending = new Set;
513
+ const completed = new Set;
514
+ let resultsStarted = false;
515
+ for (const part of message.parts) {
516
+ if (part.type === "tool-call") {
517
+ if (resultsStarted && pending.size > 0)
518
+ return false;
519
+ if (pending.size === 0)
520
+ resultsStarted = false;
521
+ if (pending.has(part.callId) || completed.has(part.callId))
522
+ return false;
523
+ pending.add(part.callId);
524
+ }
525
+ if (part.type === "tool-result") {
526
+ if (!pending.delete(part.callId))
527
+ return false;
528
+ completed.add(part.callId);
529
+ resultsStarted = true;
530
+ }
531
+ if (part.type === "tool-approval-request") {
532
+ if (!pending.delete(part.callId))
533
+ return false;
534
+ completed.add(part.callId);
535
+ resultsStarted = true;
536
+ }
537
+ }
538
+ return pending.size === 0;
539
+ }
540
+ async function projectAgentHistoryDetailed(messages, options = {}) {
541
+ const projected = [];
542
+ const system = [];
543
+ const decisions = [];
544
+ const interruptedRule = options.interruptedAssistant ?? "assistant-marked";
545
+ let observedUser = false;
546
+ for (const message of messages) {
547
+ if (message.role === "assistant" && !isAssistantHistoryEvidence(message.status, options.evidencePolicy)) {
548
+ decisions.push(decide(message, "omitted", message.status === "superseded" ? "superseded" : "draft-or-failed"));
549
+ continue;
550
+ }
551
+ if (message.status === "streaming" || message.status === "failed" && options.evidencePolicy?.failedAssistant !== "assistant-marked") {
552
+ decisions.push(decide(message, "omitted", "draft-or-failed"));
553
+ continue;
554
+ }
555
+ if (message.role === "user") {
556
+ const user = await userMessage(message, options);
557
+ observedUser = true;
558
+ if (user.message) {
559
+ projected.push(user.message);
560
+ decisions.push(decide(message, "projected", "projected", user.rendered));
561
+ } else {
562
+ decisions.push(decide(message, "omitted", "empty"));
563
+ }
564
+ continue;
565
+ }
566
+ if (message.role === "system" || message.role === "summary") {
567
+ const content = textContent(message.parts);
568
+ if (content) {
569
+ system.push(content);
570
+ decisions.push(decide(message, "projected", "projected", new Set(["text"])));
571
+ } else {
572
+ decisions.push(decide(message, "omitted", "empty"));
573
+ }
574
+ continue;
575
+ }
576
+ if (!observedUser && options.leadingAssistant !== "allow") {
577
+ if (options.leadingAssistant === "error") {
578
+ throw new Error(`Assistant message ${message.id} precedes the first user message`);
579
+ }
580
+ decisions.push(decide(message, "omitted", "leading-assistant"));
581
+ continue;
582
+ }
583
+ const interrupted = message.status === "interrupted";
584
+ if (interrupted && interruptedRule === "omit") {
585
+ decisions.push(decide(message, "omitted", "interrupted"));
586
+ continue;
587
+ }
588
+ if (interrupted && interruptedRule === "system-note") {
589
+ const note = interruptedSystemNote(message);
590
+ if (note.text) {
591
+ system.push(note.text);
592
+ decisions.push(decide(message, "projected", "projected", note.rendered));
593
+ } else {
594
+ decisions.push(decide(message, "omitted", "empty"));
595
+ }
596
+ continue;
597
+ }
598
+ if (!completeToolChronology(message)) {
599
+ if (options.incompleteToolTurn === "error") {
600
+ throw new Error(`Assistant message ${message.id} has incomplete tool chronology`);
601
+ }
602
+ decisions.push(decide(message, "omitted", "incomplete-tool-turn"));
603
+ continue;
604
+ }
605
+ const assistant = assistantMessages(message, interrupted ? "interrupted" : message.status === "failed" ? "failed" : undefined);
606
+ projected.push(...assistant.messages);
607
+ decisions.push(assistant.messages.length > 0 ? decide(message, "projected", "projected", assistant.rendered) : decide(message, "omitted", "empty"));
608
+ }
609
+ return { messages: projected, decisions, system };
610
+ }
611
+ async function projectAgentHistory(messages, options = {}) {
612
+ return [...(await projectAgentHistoryDetailed(messages, options)).messages];
613
+ }
614
+
615
+ // src/agent-runtime/managed-tools.ts
616
+ async function assertFence(config, input) {
617
+ const rejected = await config.assertCurrent(input);
618
+ if (rejected)
619
+ throw new ToolExecutionControlError(rejected);
620
+ }
621
+ function createAgentToolFenceLifecycle(config) {
622
+ const callContext = (ctx, endpoint) => ({
623
+ runId: config.runId,
624
+ ...config.context?.(ctx, endpoint)
625
+ });
626
+ return {
627
+ async beforeHandle(ctx, endpoint) {
628
+ await assertFence(config, callContext(ctx, endpoint));
629
+ },
630
+ async afterHandle(ctx, result, endpoint) {
631
+ const current = callContext(ctx, endpoint);
632
+ await assertFence(config, current);
633
+ await config.onSettled?.(current);
634
+ return result;
635
+ }
636
+ };
637
+ }
638
+
639
+ // src/agent-runtime/prompt.ts
640
+ import { z as z2 } from "zod";
641
+ var AgentTokenCountSchema = z2.object({
642
+ value: z2.int().nonnegative().optional(),
643
+ provenance: AgentProvenanceSchema.extract([
644
+ "measured",
645
+ "computed",
646
+ "estimated",
647
+ "unavailable"
648
+ ])
649
+ });
650
+ function budgetTurns(messages, evidencePolicy) {
651
+ const turns = [];
652
+ let current = [];
653
+ const flush = () => {
654
+ if (current.length === 0)
655
+ return;
656
+ turns.push({
657
+ messages: current,
658
+ complete: isCompleteAgentHistoryTurn(current, evidencePolicy),
659
+ protectedSystem: false
660
+ });
661
+ current = [];
662
+ };
663
+ for (const message of messages) {
664
+ if (message.role === "system" || message.role === "summary") {
665
+ flush();
666
+ turns.push({ messages: [message], complete: true, protectedSystem: true });
667
+ continue;
668
+ }
669
+ if (message.role === "user")
670
+ flush();
671
+ current.push(message);
672
+ }
673
+ flush();
674
+ return turns;
675
+ }
676
+ async function selectAgentHistory(options) {
677
+ if (!Number.isSafeInteger(options.availableTokens) || options.availableTokens < 0) {
678
+ throw new TypeError("availableTokens must be a non-negative safe integer");
679
+ }
680
+ const keepRecentTurns = options.keepRecentTurns ?? 1;
681
+ if (!Number.isSafeInteger(keepRecentTurns) || keepRecentTurns < 0) {
682
+ throw new TypeError("keepRecentTurns must be a non-negative safe integer");
683
+ }
684
+ const spoken = options.messages.filter((message) => message.role !== "assistant" || isAssistantHistoryEvidence(message.status, options.evidencePolicy));
685
+ const counts = new Map;
686
+ let total = 0;
687
+ let estimated = false;
688
+ for (const message of spoken) {
689
+ const count = AgentTokenCountSchema.parse(await options.estimateMessage(message));
690
+ counts.set(message.id, count);
691
+ const value = knownValue(count);
692
+ if (value === undefined) {
693
+ return {
694
+ messages: [...spoken],
695
+ decisions: options.messages.map((candidate) => ({
696
+ messageId: candidate.id,
697
+ action: candidate.role === "assistant" && !isAssistantHistoryEvidence(candidate.status, options.evidencePolicy) ? "removed" : "kept",
698
+ reason: candidate.role === "assistant" && !isAssistantHistoryEvidence(candidate.status, options.evidencePolicy) ? "unspeakable" : "token-count-unavailable",
699
+ tokens: counts.get(candidate.id) ?? { provenance: "unavailable" }
700
+ })),
701
+ totalTokens: { provenance: "unavailable" },
702
+ outcome: "unavailable"
703
+ };
704
+ }
705
+ total += value;
706
+ if (count.provenance === "estimated")
707
+ estimated = true;
708
+ }
709
+ const turns = budgetTurns(spoken, options.evidencePolicy);
710
+ const completeIndexes = turns.map((turn, index) => ({ turn, index })).filter(({ turn }) => turn.complete && !turn.protectedSystem).map(({ index }) => index);
711
+ const protectedRecent = new Set(completeIndexes.slice(-keepRecentTurns));
712
+ const removed = new Set;
713
+ for (let index = 0;index < turns.length && total > options.availableTokens; index += 1) {
714
+ const turn = turns[index];
715
+ if (!turn || turn.protectedSystem || !turn.complete || protectedRecent.has(index))
716
+ continue;
717
+ for (const message of turn.messages) {
718
+ removed.add(message.id);
719
+ total -= knownValue(counts.get(message.id) ?? { provenance: "unavailable" }) ?? 0;
720
+ }
721
+ }
722
+ const messages = spoken.filter((message) => !removed.has(message.id));
723
+ const decisions = options.messages.map((message) => {
724
+ if (message.role === "assistant" && !isAssistantHistoryEvidence(message.status, options.evidencePolicy)) {
725
+ return {
726
+ messageId: message.id,
727
+ action: "removed",
728
+ reason: "unspeakable",
729
+ tokens: { provenance: "unavailable" }
730
+ };
731
+ }
732
+ const turnIndex = turns.findIndex((turn2) => turn2.messages.some((item) => item.id === message.id));
733
+ const turn = turns[turnIndex];
734
+ let reason = "within-budget";
735
+ if (removed.has(message.id))
736
+ reason = "oldest-eligible-turn";
737
+ else if (turn?.protectedSystem)
738
+ reason = "protected-system";
739
+ else if (turn && !turn.complete)
740
+ reason = "protected-incomplete-turn";
741
+ else if (protectedRecent.has(turnIndex))
742
+ reason = "protected-recent-turn";
743
+ return {
744
+ messageId: message.id,
745
+ action: removed.has(message.id) ? "removed" : "kept",
746
+ reason,
747
+ tokens: counts.get(message.id) ?? { provenance: "unavailable" }
748
+ };
749
+ });
750
+ return {
751
+ messages,
752
+ decisions,
753
+ totalTokens: { value: total, provenance: estimated ? "estimated" : "computed" },
754
+ outcome: total > options.availableTokens ? "oversized" : removed.size > 0 ? "truncated" : "fits"
755
+ };
756
+ }
757
+ function knownValue(value) {
758
+ return value.provenance === "unavailable" ? undefined : value.value;
759
+ }
760
+ function composeAgentPrompt(sections) {
761
+ return async (options) => {
762
+ const rendered = [];
763
+ let total = 0;
764
+ let unavailable = false;
765
+ let estimated = false;
766
+ for (const section of sections) {
767
+ const text = await section.render({ context: options.context, signal: options.signal });
768
+ rendered.push({ name: section.name, stability: section.stability, text });
769
+ let count;
770
+ if (section.estimateTokens) {
771
+ count = AgentTokenCountSchema.parse(await section.estimateTokens(text));
772
+ } else if (options.estimateFallback) {
773
+ count = AgentTokenCountSchema.parse(await options.estimateFallback(text));
774
+ } else
775
+ count = { provenance: "unavailable" };
776
+ const value = knownValue(count);
777
+ if (value === undefined)
778
+ unavailable = true;
779
+ else
780
+ total += value;
781
+ if (count.provenance === "estimated")
782
+ estimated = true;
783
+ }
784
+ const instructionTokens = unavailable ? { provenance: "unavailable" } : { value: total, provenance: estimated ? "estimated" : "computed" };
785
+ let availableHistoryTokens;
786
+ let contextDecision = "unavailable";
787
+ if (options.budget) {
788
+ if (!Number.isSafeInteger(options.budget.contextWindow) || options.budget.contextWindow < 0 || !Number.isSafeInteger(options.budget.reservedOutput) || options.budget.reservedOutput < 0) {
789
+ throw new TypeError("contextWindow and reservedOutput must be non-negative safe integers");
790
+ }
791
+ const reserveValues = [
792
+ options.budget.reservedOutput,
793
+ knownValue(AgentTokenCountSchema.parse(options.budget.toolSchemas)),
794
+ knownValue(AgentTokenCountSchema.parse(options.budget.attachments)),
795
+ knownValue(AgentTokenCountSchema.parse(options.budget.providerOverhead)),
796
+ knownValue(instructionTokens)
797
+ ];
798
+ if (reserveValues.every((value) => value !== undefined)) {
799
+ availableHistoryTokens = options.budget.contextWindow - reserveValues.reduce((sum, value) => sum + (value ?? 0), 0);
800
+ const historyTokens = options.historyTokens ? knownValue(AgentTokenCountSchema.parse(options.historyTokens)) : undefined;
801
+ if (historyTokens !== undefined) {
802
+ if (availableHistoryTokens < 0)
803
+ contextDecision = "oversized";
804
+ else if (historyTokens <= availableHistoryTokens)
805
+ contextDecision = "fits";
806
+ else
807
+ contextDecision = options.oversizePolicy === "compact" ? "requires-compaction" : "oversized";
808
+ }
809
+ }
810
+ }
811
+ const instructionText = rendered.map((section) => section.text).join(`
812
+
813
+ `);
814
+ return {
815
+ instructions: options.adaptInstructions ? await options.adaptInstructions(instructionText) : instructionText,
816
+ sections: rendered,
817
+ instructionTokens,
818
+ contextDecision,
819
+ ...availableHistoryTokens !== undefined && { availableHistoryTokens }
820
+ };
821
+ };
822
+ }
823
+
824
+ // src/agent-runtime/terminal-commit.ts
825
+ class AgentRuntimeConflictError extends Error {
826
+ constructor(operation) {
827
+ super(`Agent runtime store conflict during ${operation}`);
828
+ this.name = "AgentRuntimeConflictError";
829
+ }
830
+ }
831
+ function appliedSnapshot(result, operation) {
832
+ if (result.outcome === "applied" || result.outcome === "duplicate")
833
+ return result.snapshot;
834
+ throw new AgentRuntimeConflictError(operation);
835
+ }
836
+ function viewOfSnapshot(snapshot, runId, retainedAssistant) {
837
+ const run = snapshot.runs.find((candidate) => candidate.id === runId);
838
+ const assistant = snapshot.messages.find((message) => message.id === run?.assistantMessageId) ?? retainedAssistant;
839
+ return {
840
+ snapshotVersion: snapshot.version,
841
+ conversationId: snapshot.conversationId,
842
+ ...run && { run },
843
+ ...assistant && { assistant }
844
+ };
845
+ }
846
+ function viewOfRun(view, conversationId) {
847
+ return {
848
+ snapshotVersion: view.snapshotVersion,
849
+ conversationId,
850
+ run: view.run,
851
+ ...view.assistant && { assistant: view.assistant }
852
+ };
853
+ }
854
+ function canonicalTerminal(view) {
855
+ const { run, assistant } = view;
856
+ if (!run?.terminalReason)
857
+ return;
858
+ if (view.conversationId !== run.conversationId || !assistant || assistant.id !== run.assistantMessageId || assistant.conversationId !== run.conversationId || assistant.runId !== run.id || assistant.role !== "assistant" || assistant.status !== assistantStatus(run.terminalReason)) {
859
+ throw new AgentRuntimeConflictError("terminal result projection");
860
+ }
861
+ return {
862
+ snapshotVersion: view.snapshotVersion,
863
+ run,
864
+ assistant,
865
+ reason: run.terminalReason,
866
+ committedByCaller: false,
867
+ ...run.terminalPolicyName && { policyName: run.terminalPolicyName },
868
+ ...run.usage && { usage: run.usage }
869
+ };
870
+ }
871
+ function interruptedCandidate(candidate, run, now) {
872
+ const reason = candidate.reason === "superseded" ? "superseded" : "interrupted";
873
+ const hasInterruptControl = candidate.assistant.parts.some((part) => part.type === "control" && part.reason === "run-interrupted");
874
+ const parts = hasInterruptControl ? candidate.assistant.parts : [
875
+ ...candidate.assistant.parts,
876
+ AgentMessagePartSchema.parse({ type: "control", reason: "run-interrupted" })
877
+ ];
878
+ return {
879
+ ...candidate.usage && { usage: candidate.usage },
880
+ run,
881
+ assistant: AgentMessageSchema.parse({
882
+ ...candidate.assistant,
883
+ status: assistantStatus(reason),
884
+ parts,
885
+ updatedAt: now().toISOString()
886
+ }),
887
+ reason
888
+ };
889
+ }
890
+ function canRetryTerminal(current, previous, runtimeEpoch) {
891
+ return (current.state === "running" || current.state === "interrupt_requested") && current.ownerId === runtimeEpoch && current.fencingToken === previous.fencingToken;
892
+ }
893
+ var TERMINAL_COMMIT_ATTEMPTS = 32;
894
+ async function commitAgentRunTerminal(input) {
895
+ let candidate = input.candidate;
896
+ for (let attempt = 0;attempt < TERMINAL_COMMIT_ATTEMPTS; attempt += 1) {
897
+ const committed = await input.store.commitRunTerminal({
898
+ conversationId: candidate.run.conversationId,
899
+ runId: candidate.run.id,
900
+ expectedRevision: candidate.run.revision,
901
+ ownerId: input.runtimeEpoch,
902
+ ...candidate.run.fencingToken !== undefined && {
903
+ fencingToken: candidate.run.fencingToken
904
+ },
905
+ assistant: candidate.assistant,
906
+ reason: candidate.reason,
907
+ ...candidate.policyName && { policyName: candidate.policyName },
908
+ ...candidate.usage && { usage: candidate.usage },
909
+ ...candidate.absorb?.length && { absorb: candidate.absorb }
910
+ });
911
+ if (committed.outcome === "applied") {
912
+ const terminal2 = canonicalTerminal(viewOfSnapshot(committed.snapshot, candidate.run.id));
913
+ if (!terminal2)
914
+ throw new AgentRuntimeConflictError("terminal result projection");
915
+ const absorbed = committed.snapshot.runs.filter((run) => run.absorbedIntoRunId === candidate.run.id);
916
+ return {
917
+ ...terminal2,
918
+ committedByCaller: true,
919
+ ...absorbed.length > 0 && { absorbed }
920
+ };
921
+ }
922
+ if (committed.outcome === "duplicate") {
923
+ const terminal2 = canonicalTerminal(viewOfSnapshot(committed.snapshot, candidate.run.id, committed.assistant));
924
+ if (!terminal2)
925
+ throw new AgentRuntimeConflictError("terminal result projection");
926
+ return terminal2;
927
+ }
928
+ if (committed.outcome !== "conflict") {
929
+ throw new AgentRuntimeConflictError("terminal commit");
930
+ }
931
+ const latest = await input.store.loadRun({
932
+ conversationId: candidate.run.conversationId,
933
+ runId: candidate.run.id
934
+ });
935
+ const terminal = latest ? canonicalTerminal(viewOfRun(latest, candidate.run.conversationId)) : undefined;
936
+ if (terminal)
937
+ return terminal;
938
+ const current = latest?.run;
939
+ if (!current || !canRetryTerminal(current, candidate.run, input.runtimeEpoch)) {
940
+ throw new AgentRuntimeConflictError("terminal commit");
941
+ }
942
+ candidate = current.state === "interrupt_requested" ? interruptedCandidate(candidate, current, input.now) : { ...candidate, run: current };
943
+ }
944
+ throw new AgentRuntimeConflictError("terminal commit");
945
+ }
946
+
947
+ // src/agent-runtime/admission-lanes.ts
948
+ function createRuntimeAdmissionLanes() {
949
+ const lanes = new Map;
950
+ const admit = (runId) => {
951
+ const admission = { runId, completion: Promise.withResolvers() };
952
+ admission.completion.promise.catch(() => {
953
+ return;
954
+ });
955
+ return admission;
956
+ };
957
+ return {
958
+ reserve(key, runId) {
959
+ const existing = lanes.get(key);
960
+ const lane = existing ?? { acceptanceTail: Promise.resolve() };
961
+ if (!existing)
962
+ lanes.set(key, lane);
963
+ if (!lane.head) {
964
+ lane.head = admit(runId);
965
+ return { lane, admission: lane.head, shouldSchedule: true };
966
+ }
967
+ if (!lane.pending) {
968
+ lane.pending = admit(runId);
969
+ return { lane, admission: lane.pending, shouldSchedule: true };
970
+ }
971
+ return { lane, admission: lane.pending, shouldSchedule: false };
972
+ },
973
+ settle(key, admission) {
974
+ const lane = lanes.get(key);
975
+ if (!lane)
976
+ return;
977
+ if (lane.head?.runId === admission.runId) {
978
+ lane.head = lane.pending;
979
+ lane.pending = undefined;
980
+ } else if (lane.pending?.runId === admission.runId) {
981
+ lane.pending = undefined;
982
+ }
983
+ if (!lane.head && !lane.pending)
984
+ lanes.delete(key);
985
+ },
986
+ async waitForAcceptances(lane) {
987
+ while (true) {
988
+ const tail = lane.acceptanceTail;
989
+ await tail.catch(() => {
990
+ return;
991
+ });
992
+ if (tail === lane.acceptanceTail)
993
+ return;
994
+ }
995
+ }
996
+ };
997
+ }
998
+
999
+ // src/agent-runtime/injection.ts
1000
+ function createAgentInjectionRegistry() {
1001
+ const offered = new Map;
1002
+ return {
1003
+ offer(key, entry) {
1004
+ const existing = offered.get(key);
1005
+ if (!existing) {
1006
+ offered.set(key, [entry]);
1007
+ return;
1008
+ }
1009
+ if (existing.some((candidate) => candidate.input.id === entry.input.id))
1010
+ return;
1011
+ existing.push(entry);
1012
+ },
1013
+ take(key, excludeRunId) {
1014
+ const existing = offered.get(key);
1015
+ if (!existing)
1016
+ return [];
1017
+ const taken = existing.filter((candidate) => candidate.runId !== excludeRunId);
1018
+ const kept = existing.filter((candidate) => candidate.runId === excludeRunId);
1019
+ if (kept.length === 0)
1020
+ offered.delete(key);
1021
+ else
1022
+ offered.set(key, kept);
1023
+ return taken;
1024
+ },
1025
+ withdraw(key, runId) {
1026
+ const existing = offered.get(key);
1027
+ if (!existing)
1028
+ return;
1029
+ const kept = existing.filter((candidate) => candidate.runId !== runId);
1030
+ if (kept.length === 0)
1031
+ offered.delete(key);
1032
+ else
1033
+ offered.set(key, kept);
1034
+ },
1035
+ clear() {
1036
+ offered.clear();
1037
+ }
1038
+ };
1039
+ }
1040
+
1041
+ // src/agent-runtime/run-execution.ts
1042
+ import {
1043
+ stepCountIs
1044
+ } from "ai";
1045
+
1046
+ // src/agent-runtime/deferred-tools-internal.ts
1047
+ var repairs = new WeakMap;
1048
+ var catalogs = new WeakMap;
1049
+ function registerDeferredToolRepair(prepareStep, repair) {
1050
+ repairs.set(prepareStep, repair);
1051
+ }
1052
+ function deferredToolRepair(prepareStep) {
1053
+ return prepareStep ? repairs.get(prepareStep) : undefined;
1054
+ }
1055
+ function registerDeferredToolCatalog(tools, searchName, names) {
1056
+ const search = tools[searchName];
1057
+ if (search && typeof search === "object")
1058
+ catalogs.set(search, names);
1059
+ }
1060
+ function deferredToolCatalog(tools, searchName) {
1061
+ const search = tools[searchName];
1062
+ return search && typeof search === "object" ? catalogs.get(search) : undefined;
1063
+ }
1064
+ function repairedSearchCall(toolCall, searchName) {
1065
+ return {
1066
+ ...toolCall,
1067
+ toolName: searchName,
1068
+ input: JSON.stringify({ query: toolCall.toolName, reason: "inactive_call" })
1069
+ };
1070
+ }
1071
+
1072
+ // src/agent-runtime/runtime-internals.ts
1073
+ import { z as z3 } from "zod";
1074
+ function findRun(runs, runId) {
1075
+ const run = runs.find((candidate) => candidate.id === runId);
1076
+ if (!run)
1077
+ throw new AgentRuntimeConflictError("run lookup");
1078
+ return run;
1079
+ }
1080
+ function jsonValue(value) {
1081
+ const parsed = z3.json().safeParse(value);
1082
+ return parsed.success ? parsed.data : { message: "Non-JSON tool output omitted" };
1083
+ }
1084
+ function providerEnvelope(value) {
1085
+ const parsed = AgentJsonObjectSchema.safeParse(value);
1086
+ if (!parsed.success)
1087
+ return;
1088
+ return { schemaVersion: 1, provider: "ai-sdk", data: parsed.data };
1089
+ }
1090
+ function appendText(parts, text) {
1091
+ const previous = parts.at(-1);
1092
+ if (previous?.type === "text") {
1093
+ const next = AgentMessagePartSchema.parse({ ...previous, text: previous.text + text });
1094
+ parts.splice(parts.length - 1, 1, next);
1095
+ return;
1096
+ }
1097
+ parts.push(AgentMessagePartSchema.parse({ type: "text", text }));
1098
+ }
1099
+ function abortTerminalReason(signal) {
1100
+ if (signal.reason === "shutdown")
1101
+ return "shutdown";
1102
+ if (signal.reason === "timeout")
1103
+ return "timeout";
1104
+ if (signal.reason === "supersede")
1105
+ return "superseded";
1106
+ return "interrupted";
1107
+ }
1108
+ function addUsage(total, step) {
1109
+ const sum = (left, right) => {
1110
+ if (left?.value === undefined && right?.value === undefined) {
1111
+ return { provenance: "unavailable" };
1112
+ }
1113
+ if (left?.value === undefined)
1114
+ return { ...right, provenance: "computed" };
1115
+ if (right?.value === undefined)
1116
+ return { ...left, provenance: "computed" };
1117
+ return { value: left.value + right.value, provenance: "computed" };
1118
+ };
1119
+ const sumCost = (left, right) => {
1120
+ if (left?.value === undefined || right?.value === undefined) {
1121
+ return { provenance: "unavailable" };
1122
+ }
1123
+ if (left.currency !== right.currency)
1124
+ return { provenance: "unavailable" };
1125
+ return {
1126
+ value: left.value + right.value,
1127
+ ...left.currency && { currency: left.currency },
1128
+ provenance: "computed"
1129
+ };
1130
+ };
1131
+ if (!total)
1132
+ return step;
1133
+ const cost = sumCost(total.cost, step.cost);
1134
+ return {
1135
+ inputTokens: sum(total.inputTokens, step.inputTokens),
1136
+ outputTokens: sum(total.outputTokens, step.outputTokens),
1137
+ reasoningTokens: sum(total.reasoningTokens, step.reasoningTokens),
1138
+ cacheReadTokens: sum(total.cacheReadTokens, step.cacheReadTokens),
1139
+ cacheWriteTokens: sum(total.cacheWriteTokens, step.cacheWriteTokens),
1140
+ ...cost && { cost }
1141
+ };
1142
+ }
1143
+ function mergeModelTotals(sdkTotal, accumulated) {
1144
+ const pick = (total, ours) => total?.value !== undefined ? { value: total.value, provenance: "computed" } : ours ?? { provenance: "unavailable" };
1145
+ return {
1146
+ inputTokens: pick(sdkTotal.inputTokens, accumulated?.inputTokens),
1147
+ outputTokens: pick(sdkTotal.outputTokens, accumulated?.outputTokens),
1148
+ reasoningTokens: pick(sdkTotal.reasoningTokens, accumulated?.reasoningTokens),
1149
+ cacheReadTokens: pick(sdkTotal.cacheReadTokens, accumulated?.cacheReadTokens),
1150
+ cacheWriteTokens: pick(sdkTotal.cacheWriteTokens, accumulated?.cacheWriteTokens),
1151
+ cost: accumulated?.cost ?? { provenance: "unavailable" }
1152
+ };
1153
+ }
1154
+ function statedUsage(usage) {
1155
+ const stated = (value) => value ?? { provenance: "unavailable" };
1156
+ if (!usage)
1157
+ return unknownUsage();
1158
+ return {
1159
+ inputTokens: stated(usage.inputTokens),
1160
+ outputTokens: stated(usage.outputTokens),
1161
+ reasoningTokens: stated(usage.reasoningTokens),
1162
+ cacheReadTokens: stated(usage.cacheReadTokens),
1163
+ cacheWriteTokens: stated(usage.cacheWriteTokens),
1164
+ cost: stated(usage.cost)
1165
+ };
1166
+ }
1167
+ function unknownUsage() {
1168
+ const nothing = { provenance: "unavailable" };
1169
+ return {
1170
+ inputTokens: nothing,
1171
+ outputTokens: nothing,
1172
+ reasoningTokens: nothing,
1173
+ cacheReadTokens: nothing,
1174
+ cacheWriteTokens: nothing,
1175
+ cost: nothing
1176
+ };
1177
+ }
1178
+ function normalizeSdkUsage(value) {
1179
+ const reported = (tokens) => tokens === undefined || !Number.isSafeInteger(tokens) || tokens < 0 ? { provenance: "unavailable" } : { value: tokens, provenance: "provider-reported" };
1180
+ return {
1181
+ inputTokens: reported(value.inputTokens),
1182
+ outputTokens: reported(value.outputTokens),
1183
+ reasoningTokens: reported(value.outputTokenDetails.reasoningTokens),
1184
+ cacheReadTokens: reported(value.inputTokenDetails.cacheReadTokens),
1185
+ cacheWriteTokens: reported(value.inputTokenDetails.cacheWriteTokens)
1186
+ };
1187
+ }
1188
+ function createIdleDeadline(parent, timeoutMs) {
1189
+ if (timeoutMs === undefined) {
1190
+ const noop = () => {
1191
+ return;
1192
+ };
1193
+ return { signal: parent, touch: noop, dispose: noop };
1194
+ }
1195
+ const controller = new AbortController;
1196
+ let timer;
1197
+ const touch = () => {
1198
+ if (timer !== undefined)
1199
+ clearTimeout(timer);
1200
+ timer = setTimeout(() => controller.abort("timeout"), timeoutMs);
1201
+ };
1202
+ touch();
1203
+ return {
1204
+ signal: AbortSignal.any([parent, controller.signal]),
1205
+ touch,
1206
+ dispose() {
1207
+ if (timer !== undefined)
1208
+ clearTimeout(timer);
1209
+ }
1210
+ };
1211
+ }
1212
+
1213
+ // src/agent-runtime/run-execution.ts
1214
+ function snapshotForRunPrompt(snapshot, runId) {
1215
+ const runIndex = snapshot.runs.findIndex((candidate) => candidate.id === runId);
1216
+ if (runIndex < 0)
1217
+ throw new AgentRuntimeConflictError("prompt run lookup");
1218
+ const ownedIds = new Set(snapshot.runs.flatMap((candidate) => [
1219
+ ...candidate.inputMessageIds,
1220
+ candidate.assistantMessageId
1221
+ ]));
1222
+ const eligibleIds = new Set(snapshot.runs.slice(0, runIndex + 1).flatMap((candidate) => [...candidate.inputMessageIds, candidate.assistantMessageId]));
1223
+ return AgentSnapshotSchema.parse({
1224
+ ...snapshot,
1225
+ messages: snapshot.messages.filter((message) => !ownedIds.has(message.id) || eligibleIds.has(message.id))
1226
+ });
1227
+ }
1228
+ function createRunExecutor(dependencies) {
1229
+ const {
1230
+ config,
1231
+ publish,
1232
+ runtimeEpoch,
1233
+ generateId,
1234
+ now,
1235
+ checkpointEveryEvents,
1236
+ maxSteps,
1237
+ idleTimeoutMs,
1238
+ injection
1239
+ } = dependencies;
1240
+ return async function executeRun(input) {
1241
+ injection?.withdraw(input.key, input.acceptedRun.id);
1242
+ const queued = await config.store.loadRun({
1243
+ conversationId: input.acceptedRun.conversationId,
1244
+ runId: input.acceptedRun.id
1245
+ });
1246
+ if (!queued)
1247
+ throw new AgentRuntimeConflictError("run lookup");
1248
+ if (queued.run.terminalReason === "absorbed") {
1249
+ const absorbing = queued.run.absorbedIntoRunId ? await config.store.loadRun({
1250
+ conversationId: queued.run.conversationId,
1251
+ runId: queued.run.absorbedIntoRunId
1252
+ }) : undefined;
1253
+ if (!absorbing?.assistant || !absorbing.run.terminalReason) {
1254
+ throw new AgentRuntimeConflictError("absorbed run resolution");
1255
+ }
1256
+ input.onAcquired?.();
1257
+ return {
1258
+ run: absorbing.run,
1259
+ message: absorbing.assistant,
1260
+ reason: absorbing.run.terminalReason,
1261
+ snapshotVersion: absorbing.snapshotVersion,
1262
+ ...absorbing.run.terminalPolicyName && {
1263
+ policyName: absorbing.run.terminalPolicyName
1264
+ }
1265
+ };
1266
+ }
1267
+ const queuedRun = queued.run;
1268
+ const acquired = appliedSnapshot(await config.store.acquireRun({
1269
+ conversationId: queuedRun.conversationId,
1270
+ runId: queuedRun.id,
1271
+ expectedRevision: queuedRun.revision,
1272
+ ownerId: runtimeEpoch
1273
+ }), "run acquisition");
1274
+ let run = findRun(acquired.runs, input.acceptedRun.id);
1275
+ input.onAcquired?.();
1276
+ await publish({
1277
+ type: "run-state",
1278
+ eventId: agentDurableEventId("run-state", run.id, acquired.version),
1279
+ conversationId: run.conversationId,
1280
+ runId: run.id,
1281
+ snapshotVersion: acquired.version,
1282
+ state: run.state,
1283
+ emittedAt: now().toISOString()
1284
+ });
1285
+ const trace = config.observe?.rootTrace();
1286
+ const runStartedAt = performance.now();
1287
+ config.observe?.emit({
1288
+ schemaVersion: 1,
1289
+ eventId: generateId(),
1290
+ type: "run-started",
1291
+ conversationId: run.conversationId,
1292
+ runId: run.id,
1293
+ traceId: trace?.traceId ?? generateId(),
1294
+ spanId: trace?.spanId ?? generateId(),
1295
+ ...trace?.parentSpanId && { parentSpanId: trace.parentSpanId },
1296
+ state: run.state,
1297
+ queueWaitMs: Math.max(0, now().getTime() - new Date(run.createdAt).getTime()),
1298
+ emittedAt: now().toISOString()
1299
+ });
1300
+ let assistant = AgentMessageSchema.parse({
1301
+ schemaVersion: 1,
1302
+ id: run.assistantMessageId,
1303
+ conversationId: run.conversationId,
1304
+ runId: run.id,
1305
+ role: "assistant",
1306
+ status: "streaming",
1307
+ parts: [],
1308
+ createdAt: now().toISOString(),
1309
+ updatedAt: now().toISOString()
1310
+ });
1311
+ let snapshot = appliedSnapshot(await config.store.checkpointRunAssistant({
1312
+ conversationId: run.conversationId,
1313
+ runId: run.id,
1314
+ expectedRevision: run.revision,
1315
+ ownerId: runtimeEpoch,
1316
+ ...run.fencingToken !== undefined && { fencingToken: run.fencingToken },
1317
+ assistant
1318
+ }), "assistant draft");
1319
+ run = findRun(snapshot.runs, run.id);
1320
+ let observedVersion = snapshot.version;
1321
+ const parts = [];
1322
+ const absorbed = new Map;
1323
+ let eventCount = 0;
1324
+ let sequence = 0;
1325
+ let terminalReason = "success";
1326
+ let nonModelUsage = input.acceptedRun.usage;
1327
+ let modelUsage;
1328
+ let usage = nonModelUsage;
1329
+ let sawProviderFinish = false;
1330
+ let step = 0;
1331
+ let selectedModel;
1332
+ let internalCause;
1333
+ let reasoningPartIndex;
1334
+ let firstOutputAt;
1335
+ let terminalPolicyName;
1336
+ const idleDeadline = createIdleDeadline(input.signal, idleTimeoutMs);
1337
+ const executionSignal = idleDeadline.signal;
1338
+ const updateReasoning = (text, metadata) => {
1339
+ const provider = providerEnvelope(metadata);
1340
+ if (reasoningPartIndex === undefined) {
1341
+ reasoningPartIndex = parts.length;
1342
+ parts.push(AgentMessagePartSchema.parse({
1343
+ type: "reasoning",
1344
+ text,
1345
+ ...provider && { provider }
1346
+ }));
1347
+ return;
1348
+ }
1349
+ const current = parts[reasoningPartIndex];
1350
+ if (current?.type !== "reasoning") {
1351
+ throw new AgentRuntimeConflictError("reasoning accumulator");
1352
+ }
1353
+ parts.splice(reasoningPartIndex, 1, AgentMessagePartSchema.parse({
1354
+ ...current,
1355
+ text: current.text + text,
1356
+ ...provider && { provider }
1357
+ }));
1358
+ };
1359
+ const checkpoint = async () => {
1360
+ assistant = AgentMessageSchema.parse({
1361
+ ...assistant,
1362
+ parts,
1363
+ updatedAt: now().toISOString()
1364
+ });
1365
+ snapshot = appliedSnapshot(await config.store.checkpointRunAssistant({
1366
+ conversationId: run.conversationId,
1367
+ runId: run.id,
1368
+ expectedRevision: run.revision,
1369
+ ownerId: runtimeEpoch,
1370
+ ...run.fencingToken !== undefined && { fencingToken: run.fencingToken },
1371
+ assistant,
1372
+ usage: statedUsage(usage)
1373
+ }), "assistant checkpoint");
1374
+ observedVersion = snapshot.version;
1375
+ run = findRun(snapshot.runs, run.id);
1376
+ const checkpointMetrics = {
1377
+ partial: true,
1378
+ durationMs: performance.now() - runStartedAt,
1379
+ usage: statedUsage(usage),
1380
+ ...firstOutputAt !== undefined && { ttftMs: firstOutputAt - runStartedAt }
1381
+ };
1382
+ await publish({
1383
+ type: "assistant-checkpoint",
1384
+ eventId: agentDurableEventId("assistant-checkpoint", run.id, observedVersion),
1385
+ conversationId: run.conversationId,
1386
+ runId: run.id,
1387
+ snapshotVersion: observedVersion,
1388
+ message: assistant,
1389
+ metrics: checkpointMetrics,
1390
+ emittedAt: now().toISOString()
1391
+ });
1392
+ };
1393
+ try {
1394
+ if (config.history?.compact) {
1395
+ const compacted = await config.history.compact({
1396
+ conversationId: run.conversationId,
1397
+ store: config.store,
1398
+ signal: executionSignal
1399
+ });
1400
+ snapshot = compacted.snapshot;
1401
+ observedVersion = snapshot.version;
1402
+ run = findRun(snapshot.runs, run.id);
1403
+ if (compacted.usage) {
1404
+ nonModelUsage = addUsage(nonModelUsage, compacted.usage);
1405
+ usage = modelUsage ? addUsage(nonModelUsage, modelUsage) : nonModelUsage;
1406
+ }
1407
+ }
1408
+ const assertCurrent = async () => {
1409
+ if (executionSignal.aborted)
1410
+ return "run_interrupted";
1411
+ const current = await config.store.loadRun({
1412
+ conversationId: run.conversationId,
1413
+ runId: run.id
1414
+ });
1415
+ const currentRun = current?.run;
1416
+ if (!currentRun || currentRun.ownerId !== runtimeEpoch)
1417
+ return "stale_run";
1418
+ if (currentRun.fencingToken !== run.fencingToken)
1419
+ return "stale_run";
1420
+ if (currentRun.state === "interrupt_requested")
1421
+ return "run_interrupted";
1422
+ if (currentRun.state !== "running")
1423
+ return "stale_run";
1424
+ return;
1425
+ };
1426
+ const toolFenceLifecycle = createAgentToolFenceLifecycle({
1427
+ runId: run.id,
1428
+ assertCurrent,
1429
+ context: () => ({
1430
+ ...run.fencingToken !== undefined && { fencingToken: run.fencingToken }
1431
+ })
1432
+ });
1433
+ const runtimeContext = {
1434
+ context: input.context,
1435
+ run,
1436
+ signal: executionSignal,
1437
+ toolFenceLifecycle
1438
+ };
1439
+ selectedModel = await config.models.resolve({
1440
+ context: input.context,
1441
+ conversationId: run.conversationId,
1442
+ run,
1443
+ snapshot
1444
+ });
1445
+ const promptSnapshot = snapshotForRunPrompt(snapshot, run.id);
1446
+ const [prompt, tools] = await Promise.all([
1447
+ config.prompt({
1448
+ context: input.context,
1449
+ signal: executionSignal,
1450
+ model: selectedModel,
1451
+ snapshot: promptSnapshot
1452
+ }),
1453
+ config.tools(runtimeContext)
1454
+ ]);
1455
+ if (prompt.contextDecision === "oversized") {
1456
+ throw new AgentContextOverflowError;
1457
+ }
1458
+ if (prompt.contextDecision === "requires-compaction") {
1459
+ throw new AgentContextOverflowError("Agent context still exceeds the model budget after compaction");
1460
+ }
1461
+ let carriedSystem = [];
1462
+ const projectHistory = async (source) => {
1463
+ if (config.history?.project)
1464
+ return config.history.project(source.messages);
1465
+ const detailed = await projectAgentHistoryDetailed(source.messages, {
1466
+ ...config.history?.resolveFile && { resolveFile: config.history.resolveFile },
1467
+ ...config.history?.unresolvedFile && {
1468
+ unresolvedFile: config.history.unresolvedFile
1469
+ },
1470
+ ...config.history?.interruptedAssistant && {
1471
+ interruptedAssistant: config.history.interruptedAssistant
1472
+ },
1473
+ ...config.history?.evidencePolicy && {
1474
+ evidencePolicy: config.history.evidencePolicy
1475
+ }
1476
+ });
1477
+ carriedSystem = detailed.system;
1478
+ return [...detailed.messages];
1479
+ };
1480
+ const projectInputs = async (source) => {
1481
+ if (config.history?.project)
1482
+ return config.history.project(source);
1483
+ const detailed = await projectAgentHistoryDetailed(source, {
1484
+ ...config.history?.resolveFile && { resolveFile: config.history.resolveFile },
1485
+ ...config.history?.unresolvedFile && {
1486
+ unresolvedFile: config.history.unresolvedFile
1487
+ },
1488
+ ...config.history?.interruptedAssistant && {
1489
+ interruptedAssistant: config.history.interruptedAssistant
1490
+ },
1491
+ ...config.history?.evidencePolicy && {
1492
+ evidencePolicy: config.history.evidencePolicy
1493
+ }
1494
+ });
1495
+ return [...detailed.messages];
1496
+ };
1497
+ const history = await projectHistory(promptSnapshot);
1498
+ const withCarriedSystem = (instructions) => {
1499
+ if (carriedSystem.length === 0)
1500
+ return instructions;
1501
+ const composed = typeof instructions === "string" ? [{ role: "system", content: instructions }] : Array.isArray(instructions) ? instructions : [instructions];
1502
+ return [
1503
+ ...composed,
1504
+ ...carriedSystem.map((content) => ({ role: "system", content }))
1505
+ ];
1506
+ };
1507
+ const maxStepCondition = stepCountIs(maxSteps);
1508
+ const stopConditions = [
1509
+ async (options) => {
1510
+ const stopped = await maxStepCondition(options);
1511
+ if (stopped && terminalPolicyName === undefined)
1512
+ terminalPolicyName = "max-steps";
1513
+ return stopped;
1514
+ }
1515
+ ];
1516
+ for (const policy of config.loop?.stopPolicies ?? []) {
1517
+ stopConditions.push(async (options) => {
1518
+ const stopped = await policy.when(options);
1519
+ if (stopped && terminalPolicyName === undefined)
1520
+ terminalPolicyName = policy.name;
1521
+ return stopped;
1522
+ });
1523
+ }
1524
+ const takeInjectedMessages = async () => {
1525
+ const taken = injection?.take(input.key, run.id) ?? [];
1526
+ if (taken.length === 0)
1527
+ return [];
1528
+ const messages = [];
1529
+ for (const entry of taken) {
1530
+ messages.push(...await projectInputs([entry.input]));
1531
+ const ids = absorbed.get(entry.runId) ?? [];
1532
+ ids.push(entry.input.id);
1533
+ absorbed.set(entry.runId, ids);
1534
+ }
1535
+ return messages;
1536
+ };
1537
+ const result = streamAgentTextBoundary({
1538
+ model: selectedModel.model,
1539
+ tools,
1540
+ instructions: withCarriedSystem(prompt.instructions),
1541
+ messages: history,
1542
+ abortSignal: executionSignal,
1543
+ maxRetries: 0,
1544
+ stopWhen: stopConditions,
1545
+ repairToolCall: deferredToolRepair(config.loop?.prepareStep),
1546
+ ...config.loop?.toolApproval && {
1547
+ toolApproval: config.loop.toolApproval,
1548
+ runtimeContext: input.context
1549
+ },
1550
+ ...config.loop?.toolApprovalSecret && {
1551
+ experimental_toolApprovalSecret: config.loop.toolApprovalSecret
1552
+ },
1553
+ ...(config.loop?.prepareStep || injection) && {
1554
+ prepareStep: async (options) => {
1555
+ const prepared = await config.loop?.prepareStep?.({
1556
+ ...options,
1557
+ ...runtimeContext
1558
+ });
1559
+ const injected = await takeInjectedMessages();
1560
+ if (injected.length === 0)
1561
+ return prepared;
1562
+ const base = prepared?.messages ?? options.messages;
1563
+ return { ...prepared, messages: [...base, ...injected] };
1564
+ }
1565
+ }
1566
+ });
1567
+ for await (const part of result.stream) {
1568
+ idleDeadline.touch();
1569
+ eventCount += 1;
1570
+ sequence += 1;
1571
+ if (firstOutputAt === undefined && ["text-delta", "reasoning-delta", "tool-call", "file", "source"].includes(part.type)) {
1572
+ firstOutputAt = performance.now();
1573
+ }
1574
+ if (part.type === "text-delta") {
1575
+ appendText(parts, part.text);
1576
+ await publish({
1577
+ type: "assistant-delta",
1578
+ conversationId: run.conversationId,
1579
+ runId: run.id,
1580
+ runtimeEpoch,
1581
+ sequence,
1582
+ textDelta: part.text,
1583
+ emittedAt: now().toISOString()
1584
+ });
1585
+ } else if (part.type === "reasoning-start") {
1586
+ reasoningPartIndex = undefined;
1587
+ updateReasoning("", part.providerMetadata);
1588
+ const provider = providerEnvelope(part.providerMetadata);
1589
+ await publish({
1590
+ type: "reasoning-start",
1591
+ conversationId: run.conversationId,
1592
+ runId: run.id,
1593
+ runtimeEpoch,
1594
+ sequence,
1595
+ ...provider && { provider },
1596
+ emittedAt: now().toISOString()
1597
+ });
1598
+ } else if (part.type === "reasoning-delta") {
1599
+ updateReasoning(part.text, part.providerMetadata);
1600
+ const provider = providerEnvelope(part.providerMetadata);
1601
+ await publish({
1602
+ type: "reasoning-delta",
1603
+ conversationId: run.conversationId,
1604
+ runId: run.id,
1605
+ runtimeEpoch,
1606
+ sequence,
1607
+ textDelta: part.text,
1608
+ ...provider && { provider },
1609
+ emittedAt: now().toISOString()
1610
+ });
1611
+ } else if (part.type === "reasoning-end") {
1612
+ updateReasoning("", part.providerMetadata);
1613
+ reasoningPartIndex = undefined;
1614
+ const provider = providerEnvelope(part.providerMetadata);
1615
+ await publish({
1616
+ type: "reasoning-end",
1617
+ conversationId: run.conversationId,
1618
+ runId: run.id,
1619
+ runtimeEpoch,
1620
+ sequence,
1621
+ ...provider && { provider },
1622
+ emittedAt: now().toISOString()
1623
+ });
1624
+ } else if (part.type === "tool-call") {
1625
+ const provider = providerEnvelope(part.providerMetadata);
1626
+ parts.push(AgentMessagePartSchema.parse({
1627
+ type: "tool-call",
1628
+ callId: part.toolCallId,
1629
+ toolName: part.toolName,
1630
+ input: jsonValue(part.input),
1631
+ ...provider && { provider }
1632
+ }));
1633
+ await publish({
1634
+ type: "tool-status",
1635
+ conversationId: run.conversationId,
1636
+ runId: run.id,
1637
+ runtimeEpoch,
1638
+ sequence,
1639
+ callId: part.toolCallId,
1640
+ toolName: part.toolName,
1641
+ status: "started",
1642
+ input: jsonValue(part.input),
1643
+ emittedAt: now().toISOString()
1644
+ });
1645
+ } else if (part.type === "tool-result") {
1646
+ parts.push(AgentMessagePartSchema.parse({
1647
+ type: "tool-result",
1648
+ callId: part.toolCallId,
1649
+ toolName: part.toolName,
1650
+ outcome: "success",
1651
+ output: jsonValue(part.output)
1652
+ }));
1653
+ await publish({
1654
+ type: "tool-status",
1655
+ conversationId: run.conversationId,
1656
+ runId: run.id,
1657
+ runtimeEpoch,
1658
+ sequence,
1659
+ callId: part.toolCallId,
1660
+ toolName: part.toolName,
1661
+ status: "completed",
1662
+ output: jsonValue(part.output),
1663
+ emittedAt: now().toISOString()
1664
+ });
1665
+ } else if (part.type === "tool-error") {
1666
+ internalCause = part.error;
1667
+ if (isToolExecutionControlError(part.error)) {
1668
+ await publish({
1669
+ type: "tool-status",
1670
+ conversationId: run.conversationId,
1671
+ runId: run.id,
1672
+ runtimeEpoch,
1673
+ sequence,
1674
+ callId: part.toolCallId,
1675
+ toolName: part.toolName,
1676
+ status: "interrupted",
1677
+ emittedAt: now().toISOString()
1678
+ });
1679
+ throw part.error;
1680
+ }
1681
+ parts.push(AgentMessagePartSchema.parse({
1682
+ type: "tool-result",
1683
+ callId: part.toolCallId,
1684
+ toolName: part.toolName,
1685
+ outcome: "error",
1686
+ output: { message: "Tool execution failed" }
1687
+ }));
1688
+ await publish({
1689
+ type: "tool-status",
1690
+ conversationId: run.conversationId,
1691
+ runId: run.id,
1692
+ runtimeEpoch,
1693
+ sequence,
1694
+ callId: part.toolCallId,
1695
+ toolName: part.toolName,
1696
+ status: "failed",
1697
+ output: { message: "Tool execution failed" },
1698
+ emittedAt: now().toISOString()
1699
+ });
1700
+ } else if (part.type === "tool-output-denied") {
1701
+ parts.push(AgentMessagePartSchema.parse({
1702
+ type: "tool-result",
1703
+ callId: part.toolCallId,
1704
+ toolName: part.toolName,
1705
+ outcome: "error",
1706
+ output: { message: "Tool output denied" }
1707
+ }));
1708
+ await publish({
1709
+ type: "tool-status",
1710
+ conversationId: run.conversationId,
1711
+ runId: run.id,
1712
+ runtimeEpoch,
1713
+ sequence,
1714
+ callId: part.toolCallId,
1715
+ toolName: part.toolName,
1716
+ status: "failed",
1717
+ output: { message: "Tool output denied" },
1718
+ emittedAt: now().toISOString()
1719
+ });
1720
+ } else if (part.type === "source") {
1721
+ parts.push(AgentMessagePartSchema.parse({
1722
+ type: "source",
1723
+ sourceId: part.id,
1724
+ ...part.sourceType === "url" && { url: part.url },
1725
+ ...part.title && { title: part.title }
1726
+ }));
1727
+ } else if (part.type === "file" && config.persistGeneratedFile) {
1728
+ const persisted = await config.persistGeneratedFile(part.file);
1729
+ parts.push(AgentMessagePartSchema.parse({
1730
+ type: "file",
1731
+ mediaType: part.file.mediaType,
1732
+ reference: persisted.reference,
1733
+ ...persisted.filename && { filename: persisted.filename }
1734
+ }));
1735
+ } else if (part.type === "file") {
1736
+ throw new Error("persistGeneratedFile is required for generated file output");
1737
+ } else if (part.type === "reasoning-file" && config.persistGeneratedFile) {
1738
+ const persisted = await config.persistGeneratedFile(part.file);
1739
+ parts.push(AgentMessagePartSchema.parse({
1740
+ type: "file",
1741
+ mediaType: part.file.mediaType,
1742
+ reference: persisted.reference,
1743
+ ...persisted.filename && { filename: persisted.filename }
1744
+ }));
1745
+ } else if (part.type === "reasoning-file") {
1746
+ throw new Error("persistGeneratedFile is required for generated reasoning files");
1747
+ } else if (part.type === "tool-approval-request") {
1748
+ parts.push(AgentMessagePartSchema.parse({
1749
+ type: "tool-approval-request",
1750
+ approvalId: part.approvalId,
1751
+ callId: part.toolCall.toolCallId,
1752
+ ...part.isAutomatic !== undefined && { isAutomatic: part.isAutomatic },
1753
+ ...part.signature && { signature: part.signature }
1754
+ }));
1755
+ } else if (part.type === "tool-approval-response") {
1756
+ parts.push(AgentMessagePartSchema.parse({
1757
+ type: "tool-approval-response",
1758
+ approvalId: part.approvalId,
1759
+ approved: part.approved,
1760
+ ...part.reason && { reason: part.reason }
1761
+ }));
1762
+ } else if (part.type === "custom") {
1763
+ const provider = providerEnvelope(part.providerMetadata);
1764
+ parts.push(AgentMessagePartSchema.parse({
1765
+ type: "provider",
1766
+ envelope: {
1767
+ schemaVersion: 1,
1768
+ provider: "ai-sdk-custom",
1769
+ data: { kind: part.kind, ...provider && { provider: provider.data } }
1770
+ }
1771
+ }));
1772
+ } else if (part.type === "raw") {
1773
+ parts.push(AgentMessagePartSchema.parse({
1774
+ type: "provider",
1775
+ envelope: {
1776
+ schemaVersion: 1,
1777
+ provider: "ai-sdk-raw",
1778
+ data: { value: jsonValue(part.rawValue) }
1779
+ }
1780
+ }));
1781
+ } else if (part.type === "abort") {
1782
+ terminalReason = "interrupted";
1783
+ } else if (part.type === "error") {
1784
+ terminalReason = part.error instanceof AgentContextOverflowError ? "context_overflow" : "provider_failure";
1785
+ internalCause = part.error;
1786
+ } else if (part.type === "finish-step") {
1787
+ const stepTrace = trace ? config.observe?.rootTrace(trace) : undefined;
1788
+ const stepUsage = selectedModel.normalizeUsage?.({
1789
+ usage: part.usage,
1790
+ providerMetadata: part.providerMetadata
1791
+ }) ?? normalizeSdkUsage(part.usage);
1792
+ modelUsage = addUsage(modelUsage, stepUsage);
1793
+ usage = nonModelUsage ? addUsage(nonModelUsage, modelUsage) : modelUsage;
1794
+ config.observe?.emit({
1795
+ schemaVersion: 1,
1796
+ eventId: generateId(),
1797
+ type: "step-finished",
1798
+ conversationId: run.conversationId,
1799
+ runId: run.id,
1800
+ traceId: stepTrace?.traceId ?? trace?.traceId ?? generateId(),
1801
+ spanId: stepTrace?.spanId ?? generateId(),
1802
+ ...stepTrace?.parentSpanId && { parentSpanId: stepTrace.parentSpanId },
1803
+ state: run.state,
1804
+ modelId: selectedModel.descriptor.modelId,
1805
+ step,
1806
+ usage: stepUsage,
1807
+ emittedAt: now().toISOString()
1808
+ });
1809
+ step += 1;
1810
+ } else if (part.type === "finish" && part.finishReason !== "stop") {
1811
+ if (terminalReason === "success") {
1812
+ terminalReason = part.finishReason === "error" ? "provider_failure" : "provider_stop";
1813
+ internalCause ??= { finishReason: part.finishReason };
1814
+ }
1815
+ }
1816
+ if (part.type === "finish") {
1817
+ sawProviderFinish = true;
1818
+ modelUsage = mergeModelTotals(normalizeSdkUsage(part.totalUsage), modelUsage);
1819
+ usage = nonModelUsage ? addUsage(nonModelUsage, modelUsage) : modelUsage;
1820
+ }
1821
+ if (eventCount % checkpointEveryEvents === 0)
1822
+ await checkpoint();
1823
+ }
1824
+ if (terminalPolicyName !== undefined)
1825
+ terminalReason = "policy_stop";
1826
+ if (executionSignal.aborted)
1827
+ terminalReason = abortTerminalReason(executionSignal);
1828
+ const awaitsApproval = parts.some((part) => part.type === "tool-approval-request");
1829
+ if (!awaitsApproval && config.protocol.acceptTerminal && (terminalReason === "success" || terminalReason === "policy_stop" || terminalReason === "provider_stop")) {
1830
+ const candidate = AgentMessageSchema.parse({
1831
+ ...assistant,
1832
+ status: assistantStatus(terminalReason),
1833
+ parts,
1834
+ updatedAt: now().toISOString()
1835
+ });
1836
+ if (!await config.protocol.acceptTerminal({
1837
+ message: candidate,
1838
+ reason: terminalReason,
1839
+ ...terminalPolicyName && { policyName: terminalPolicyName }
1840
+ })) {
1841
+ terminalReason = "provider_failure";
1842
+ internalCause = new Error("Agent terminal output was rejected by the protocol");
1843
+ }
1844
+ }
1845
+ } catch (error) {
1846
+ internalCause = error;
1847
+ const latest = await config.store.loadRun({
1848
+ conversationId: run.conversationId,
1849
+ runId: run.id
1850
+ });
1851
+ const latestRun = latest?.run;
1852
+ const durableInterrupt = latestRun?.ownerId === runtimeEpoch && latestRun.state === "interrupt_requested";
1853
+ if (durableInterrupt && latest && latestRun) {
1854
+ observedVersion = latest.snapshotVersion;
1855
+ run = latestRun;
1856
+ }
1857
+ if (isToolExecutionControlError(error) || executionSignal.aborted || durableInterrupt) {
1858
+ terminalReason = executionSignal.aborted ? abortTerminalReason(executionSignal) : "interrupted";
1859
+ parts.push(AgentMessagePartSchema.parse({
1860
+ type: "control",
1861
+ reason: isToolExecutionControlError(error) && error.reason === "stale_run" ? "stale-run" : "run-interrupted"
1862
+ }));
1863
+ } else {
1864
+ terminalReason = error instanceof AgentContextOverflowError ? "context_overflow" : "provider_failure";
1865
+ }
1866
+ } finally {
1867
+ idleDeadline.dispose();
1868
+ }
1869
+ assistant = AgentMessageSchema.parse({
1870
+ ...assistant,
1871
+ status: assistantStatus(terminalReason),
1872
+ parts,
1873
+ updatedAt: now().toISOString()
1874
+ });
1875
+ const spent = statedUsage(usage);
1876
+ const emitSpend = (report) => {
1877
+ config.observe?.emit({
1878
+ schemaVersion: 1,
1879
+ eventId: report.eventId,
1880
+ type: "run-terminal",
1881
+ conversationId: run.conversationId,
1882
+ runId: run.id,
1883
+ traceId: trace?.traceId ?? generateId(),
1884
+ spanId: trace?.spanId ?? generateId(),
1885
+ ...trace?.parentSpanId && { parentSpanId: trace.parentSpanId },
1886
+ state: report.state,
1887
+ terminalReason: report.reason,
1888
+ ...selectedModel && { modelId: selectedModel.descriptor.modelId },
1889
+ durationMs: performance.now() - runStartedAt,
1890
+ usage: spent,
1891
+ ...internalCause !== undefined && { internalCause },
1892
+ ...firstOutputAt !== undefined && { ttftMs: firstOutputAt - runStartedAt },
1893
+ emittedAt: now().toISOString()
1894
+ });
1895
+ };
1896
+ const unsettledEventId = (version) => agentDurableEventId("terminal", `${run.id}:${runtimeEpoch}`, version);
1897
+ let terminal;
1898
+ try {
1899
+ terminal = await commitAgentRunTerminal({
1900
+ store: config.store,
1901
+ runtimeEpoch,
1902
+ candidate: {
1903
+ run,
1904
+ assistant,
1905
+ reason: terminalReason,
1906
+ ...terminalPolicyName && { policyName: terminalPolicyName },
1907
+ usage: spent,
1908
+ ...absorbed.size > 0 && runStateForTerminalReason(terminalReason) === "completed" && {
1909
+ absorb: [...absorbed].map(([runId, inputMessageIds]) => ({
1910
+ runId,
1911
+ inputMessageIds
1912
+ }))
1913
+ }
1914
+ },
1915
+ now
1916
+ });
1917
+ } catch (error) {
1918
+ emitSpend({
1919
+ eventId: unsettledEventId(observedVersion),
1920
+ state: run.state,
1921
+ reason: terminalReason
1922
+ });
1923
+ throw error;
1924
+ }
1925
+ observedVersion = terminal.snapshotVersion;
1926
+ run = terminal.run;
1927
+ assistant = terminal.assistant;
1928
+ terminalReason = terminal.reason;
1929
+ terminalPolicyName = terminal.policyName;
1930
+ const terminalMetrics = terminal.committedByCaller ? {
1931
+ partial: !sawProviderFinish,
1932
+ durationMs: performance.now() - runStartedAt,
1933
+ usage: spent,
1934
+ ...firstOutputAt !== undefined && { ttftMs: firstOutputAt - runStartedAt }
1935
+ } : undefined;
1936
+ emitSpend({
1937
+ eventId: terminal.committedByCaller ? agentDurableEventId("terminal", run.id, observedVersion) : unsettledEventId(observedVersion),
1938
+ state: run.state,
1939
+ reason: terminalReason
1940
+ });
1941
+ for (const settled of terminal.absorbed ?? []) {
1942
+ await publish({
1943
+ type: "run-state",
1944
+ eventId: agentDurableEventId("run-state", settled.id, observedVersion),
1945
+ conversationId: settled.conversationId,
1946
+ runId: settled.id,
1947
+ snapshotVersion: observedVersion,
1948
+ state: settled.state,
1949
+ emittedAt: now().toISOString()
1950
+ });
1951
+ }
1952
+ if (terminalMetrics) {
1953
+ await publish({
1954
+ type: "terminal",
1955
+ eventId: agentDurableEventId("terminal", run.id, observedVersion),
1956
+ conversationId: run.conversationId,
1957
+ runId: run.id,
1958
+ snapshotVersion: observedVersion,
1959
+ reason: terminalReason,
1960
+ ...terminalPolicyName && { policyName: terminalPolicyName },
1961
+ message: assistant,
1962
+ metrics: terminalMetrics,
1963
+ emittedAt: now().toISOString()
1964
+ });
1965
+ }
1966
+ return {
1967
+ run,
1968
+ message: assistant,
1969
+ reason: terminalReason,
1970
+ snapshotVersion: observedVersion,
1971
+ ...terminalMetrics && { metrics: terminalMetrics },
1972
+ ...terminalPolicyName && { policyName: terminalPolicyName }
1973
+ };
1974
+ };
1975
+ }
1976
+
1977
+ // src/agent-runtime/runtime.ts
1978
+ function createAgentRuntime(config) {
1979
+ const coordinator = createAgentSessionCoordinator();
1980
+ const tickets = new Map;
1981
+ const generateId = config.generateId ?? (() => crypto.randomUUID());
1982
+ const now = config.now ?? (() => new Date);
1983
+ const runtimeEpoch = generateId();
1984
+ const admissionLanes = createRuntimeAdmissionLanes();
1985
+ const injectionPossible = typeof config.runs?.inputPolicy === "function" || config.runs?.inputPolicy === "inject";
1986
+ const injection = injectionPossible ? createAgentInjectionRegistry() : undefined;
1987
+ const reserveAdmission = admissionLanes.reserve;
1988
+ const settleAdmission = admissionLanes.settle;
1989
+ const waitForAdmissionAcceptances = admissionLanes.waitForAcceptances;
1990
+ const checkpointEveryEvents = config.loop?.checkpointEveryEvents ?? 20;
1991
+ const maxSteps = config.loop?.maxSteps ?? 50;
1992
+ const declaredIdleTimeoutMs = config.loop?.idleTimeoutMs;
1993
+ const idleTimeoutMs = declaredIdleTimeoutMs === null ? undefined : declaredIdleTimeoutMs ?? 60000;
1994
+ if (!Number.isSafeInteger(checkpointEveryEvents) || checkpointEveryEvents < 1) {
1995
+ throw new TypeError("checkpointEveryEvents must be a positive safe integer");
1996
+ }
1997
+ if (!Number.isSafeInteger(maxSteps) || maxSteps < 1) {
1998
+ throw new TypeError("maxSteps must be a positive safe integer");
1999
+ }
2000
+ if (idleTimeoutMs !== undefined && (!Number.isSafeInteger(idleTimeoutMs) || idleTimeoutMs < 1)) {
2001
+ throw new TypeError("idleTimeoutMs must be a positive safe integer");
2002
+ }
2003
+ const policyNames = new Set(["max-steps"]);
2004
+ for (const policy of config.loop?.stopPolicies ?? []) {
2005
+ if (!policy.name || policyNames.has(policy.name)) {
2006
+ throw new TypeError("Agent stop policy names must be non-empty and unique");
2007
+ }
2008
+ policyNames.add(policy.name);
2009
+ }
2010
+ const publish = async (event) => {
2011
+ try {
2012
+ await config.publish?.(event);
2013
+ } catch (error) {
2014
+ try {
2015
+ await config.onPublishError?.({ event, error });
2016
+ } catch {}
2017
+ }
2018
+ };
2019
+ const executeRun = createRunExecutor({
2020
+ config,
2021
+ publish,
2022
+ runtimeEpoch,
2023
+ generateId,
2024
+ now,
2025
+ checkpointEveryEvents,
2026
+ maxSteps,
2027
+ ...idleTimeoutMs !== undefined && { idleTimeoutMs },
2028
+ ...injection && { injection }
2029
+ });
2030
+ let admissionClosed = false;
2031
+ const closedError = () => new Error("[stitchkit] agent runtime is closed and admits no further work");
2032
+ const admissionsInFlight = new Set;
2033
+ const beginAdmission = () => {
2034
+ const handoff = Promise.withResolvers();
2035
+ admissionsInFlight.add(handoff);
2036
+ return () => {
2037
+ if (admissionsInFlight.delete(handoff))
2038
+ handoff.resolve();
2039
+ };
2040
+ };
2041
+ const drainAdmissions = async (budgetMs) => {
2042
+ const pending = [...admissionsInFlight].map((handoff) => handoff.promise);
2043
+ if (pending.length === 0)
2044
+ return 0;
2045
+ let stranded = pending.length;
2046
+ const settled = Promise.all(pending.map((promise) => promise.then(() => {
2047
+ stranded -= 1;
2048
+ })));
2049
+ if (budgetMs === undefined) {
2050
+ await settled;
2051
+ return 0;
2052
+ }
2053
+ let timer;
2054
+ await Promise.race([
2055
+ settled,
2056
+ new Promise((resolve) => {
2057
+ timer = setTimeout(resolve, budgetMs);
2058
+ })
2059
+ ]);
2060
+ if (timer !== undefined)
2061
+ clearTimeout(timer);
2062
+ return stranded;
2063
+ };
2064
+ const refuse = () => {
2065
+ const error = closedError();
2066
+ const accepted = Promise.reject(error);
2067
+ const result = Promise.reject(error);
2068
+ accepted.catch(() => {
2069
+ return;
2070
+ });
2071
+ result.catch(() => {
2072
+ return;
2073
+ });
2074
+ return { accepted, result };
2075
+ };
2076
+ const resume = (rawInput) => {
2077
+ if (admissionClosed)
2078
+ return refuse();
2079
+ const context = config.protocol.parseContext(rawInput.context);
2080
+ const accepted = Promise.withResolvers();
2081
+ const result = Promise.withResolvers();
2082
+ let acquisitionSettled = false;
2083
+ const resolveAcquisition = () => {
2084
+ acquisitionSettled = true;
2085
+ accepted.resolve();
2086
+ };
2087
+ const rejectAcquisition = (error) => {
2088
+ if (!acquisitionSettled)
2089
+ accepted.reject(error);
2090
+ };
2091
+ const handedOff = beginAdmission();
2092
+ (async () => {
2093
+ try {
2094
+ const recovered = await config.store.loadRun({
2095
+ conversationId: rawInput.conversationId,
2096
+ runId: rawInput.runId
2097
+ });
2098
+ if (!recovered)
2099
+ throw new AgentRuntimeConflictError("run lookup");
2100
+ const recoveredRun = recovered.run;
2101
+ if (recoveredRun.state !== "queued") {
2102
+ throw new Error("Only a queued recovered agent run can be resumed");
2103
+ }
2104
+ const ticket = coordinator.submit({
2105
+ key: rawInput.conversationKey ?? rawInput.conversationId,
2106
+ policy: "queue",
2107
+ create: (signal) => ({
2108
+ runId: recoveredRun.id,
2109
+ execute: () => executeRun({
2110
+ acceptedRun: recoveredRun,
2111
+ context,
2112
+ signal,
2113
+ key: rawInput.conversationKey ?? rawInput.conversationId,
2114
+ onAcquired: resolveAcquisition
2115
+ })
2116
+ })
2117
+ });
2118
+ ticket.accepted.catch(() => {
2119
+ return;
2120
+ });
2121
+ ticket.result.then(result.resolve, (error) => {
2122
+ rejectAcquisition(error);
2123
+ result.reject(error);
2124
+ });
2125
+ } catch (error) {
2126
+ rejectAcquisition(error);
2127
+ result.reject(error);
2128
+ } finally {
2129
+ handedOff();
2130
+ }
2131
+ })();
2132
+ return { accepted: accepted.promise, result: result.promise };
2133
+ };
2134
+ return {
2135
+ submit(rawInput) {
2136
+ if (admissionClosed) {
2137
+ const refused = refuse();
2138
+ const admission = Promise.reject(closedError());
2139
+ admission.catch(() => {
2140
+ return;
2141
+ });
2142
+ return { ...refused, admission };
2143
+ }
2144
+ const metadata = rawInput.metadata === undefined ? undefined : config.protocol.parseInputMetadata(rawInput.metadata);
2145
+ const input = {
2146
+ conversationId: rawInput.conversationId,
2147
+ idempotencyKey: rawInput.idempotencyKey,
2148
+ context: rawInput.context,
2149
+ parts: rawInput.parts.map((part) => config.protocol.parsePart(part)),
2150
+ role: rawInput.role ?? "user",
2151
+ ...metadata !== undefined && { metadata }
2152
+ };
2153
+ if (input.role === "tool" && (input.parts.length === 0 || input.parts.some((part) => part.type !== "tool-approval-response"))) {
2154
+ throw new TypeError("Tool-role Agent input only accepts approval responses");
2155
+ }
2156
+ const context = config.protocol.parseContext(input.context);
2157
+ const conversationTickets = tickets.get(input.conversationId);
2158
+ const existingTicket = conversationTickets?.get(input.idempotencyKey);
2159
+ if (existingTicket)
2160
+ return existingTicket;
2161
+ const key = config.runs?.key?.(input) ?? input.conversationId;
2162
+ const policy = typeof config.runs?.inputPolicy === "function" ? config.runs.inputPolicy(input) : config.runs?.inputPolicy ?? "queue";
2163
+ const nowIso = now().toISOString();
2164
+ const inputMessageId = rawInput.recordIds?.inputMessageId ?? generateId();
2165
+ const runId = rawInput.recordIds?.runId ?? generateId();
2166
+ const assistantMessageId = rawInput.recordIds?.assistantMessageId ?? generateId();
2167
+ const userMessage2 = AgentMessageSchema.parse({
2168
+ schemaVersion: 1,
2169
+ id: inputMessageId,
2170
+ conversationId: input.conversationId,
2171
+ role: input.role,
2172
+ status: "committed",
2173
+ parts: input.parts,
2174
+ ...input.metadata && { metadata: input.metadata },
2175
+ createdAt: nowIso,
2176
+ updatedAt: nowIso
2177
+ });
2178
+ const queuedRun = AgentRunSchema.parse({
2179
+ schemaVersion: 1,
2180
+ id: runId,
2181
+ conversationId: input.conversationId,
2182
+ inputMessageIds: [inputMessageId],
2183
+ assistantMessageId,
2184
+ state: "queued",
2185
+ revision: 0,
2186
+ ...policy === "interrupt-next" && { queuePriority: "interrupt-next" },
2187
+ createdAt: nowIso,
2188
+ updatedAt: nowIso
2189
+ });
2190
+ const outerAccepted = Promise.withResolvers();
2191
+ const outerAdmission = Promise.withResolvers();
2192
+ outerAdmission.promise.catch(() => {
2193
+ return;
2194
+ });
2195
+ const outerResult = Promise.withResolvers();
2196
+ const reservation = config.runs?.coalescePending && policy !== "interrupt-next" ? reserveAdmission(key, runId) : undefined;
2197
+ const previousAcceptance = reservation?.lane.acceptanceTail ?? Promise.resolve();
2198
+ const acceptanceDone = Promise.withResolvers();
2199
+ if (reservation) {
2200
+ reservation.lane.acceptanceTail = previousAcceptance.catch(() => {
2201
+ return;
2202
+ }).then(() => acceptanceDone.promise);
2203
+ }
2204
+ const publicTicket = {
2205
+ accepted: outerAccepted.promise,
2206
+ admission: outerAdmission.promise,
2207
+ result: outerResult.promise
2208
+ };
2209
+ const currentConversationTickets = conversationTickets ?? new Map;
2210
+ currentConversationTickets.set(input.idempotencyKey, publicTicket);
2211
+ if (!conversationTickets)
2212
+ tickets.set(input.conversationId, currentConversationTickets);
2213
+ let offeredRunId;
2214
+ const forgetTicket = () => {
2215
+ if (offeredRunId !== undefined)
2216
+ injection?.withdraw(key, offeredRunId);
2217
+ if (currentConversationTickets.get(input.idempotencyKey) !== publicTicket)
2218
+ return;
2219
+ currentConversationTickets.delete(input.idempotencyKey);
2220
+ if (currentConversationTickets.size === 0)
2221
+ tickets.delete(input.conversationId);
2222
+ };
2223
+ outerResult.promise.then(forgetTicket, forgetTicket);
2224
+ const handedOff = beginAdmission();
2225
+ (async () => {
2226
+ try {
2227
+ await previousAcceptance.catch(() => {
2228
+ return;
2229
+ });
2230
+ await config.models.preflight?.({
2231
+ context,
2232
+ conversationId: input.conversationId
2233
+ });
2234
+ if (admissionClosed)
2235
+ throw closedError();
2236
+ const acceptance = await config.store.acceptInputAndAssignRun({
2237
+ idempotencyKey: input.idempotencyKey,
2238
+ input: userMessage2,
2239
+ run: queuedRun,
2240
+ ...reservation && !reservation.shouldSchedule && {
2241
+ coalesceIntoRunId: reservation.admission.runId
2242
+ }
2243
+ });
2244
+ const acceptedSnapshot = appliedSnapshot(acceptance, "input acceptance");
2245
+ const assignedRunId = acceptance.outcome === "duplicate" ? acceptance.runId : reservation?.admission.runId ?? runId;
2246
+ const acceptedRun = acceptance.outcome === "duplicate" ? acceptance.run : findRun(acceptedSnapshot.runs, assignedRunId);
2247
+ const actualInputMessageId = acceptance.outcome === "duplicate" ? acceptance.inputMessageId : userMessage2.id;
2248
+ const acceptedInput = acceptance.outcome === "duplicate" ? acceptance.input : acceptedSnapshot.messages.find((candidate) => candidate.id === actualInputMessageId);
2249
+ if (!acceptedInput) {
2250
+ throw new AgentRuntimeConflictError("admission input projection");
2251
+ }
2252
+ const assistantPlaceholder = AgentAssistantPlaceholderSchema.parse({
2253
+ schemaVersion: 1,
2254
+ id: acceptedRun.assistantMessageId,
2255
+ conversationId: acceptedRun.conversationId,
2256
+ runId: acceptedRun.id,
2257
+ status: "pending",
2258
+ createdAt: acceptedRun.createdAt,
2259
+ updatedAt: acceptedRun.updatedAt
2260
+ });
2261
+ const acceptedAssistant = acceptance.outcome === "duplicate" ? acceptance.assistant ?? assistantPlaceholder : assistantPlaceholder;
2262
+ const admission = {
2263
+ inputMessageId: acceptedInput.id,
2264
+ runId: acceptedRun.id,
2265
+ assistantMessageId: assistantPlaceholder.id,
2266
+ input: acceptedInput,
2267
+ run: acceptedRun,
2268
+ assistant: acceptedAssistant,
2269
+ snapshotVersion: acceptedSnapshot.version
2270
+ };
2271
+ outerAdmission.resolve(admission);
2272
+ await publish({
2273
+ type: "admission",
2274
+ eventId: agentDurableEventId("admission", acceptedRun.id, acceptedSnapshot.version),
2275
+ conversationId: acceptedRun.conversationId,
2276
+ runId: acceptedRun.id,
2277
+ snapshotVersion: acceptedSnapshot.version,
2278
+ input: acceptedInput,
2279
+ run: acceptedRun,
2280
+ assistant: acceptedAssistant,
2281
+ emittedAt: now().toISOString()
2282
+ });
2283
+ await publish({
2284
+ type: "run-state",
2285
+ eventId: agentDurableEventId("run-state", acceptedRun.id, acceptedSnapshot.version),
2286
+ conversationId: acceptedRun.conversationId,
2287
+ runId: acceptedRun.id,
2288
+ snapshotVersion: acceptedSnapshot.version,
2289
+ state: acceptedRun.state,
2290
+ emittedAt: now().toISOString()
2291
+ });
2292
+ outerAccepted.resolve();
2293
+ if (acceptance.outcome === "duplicate") {
2294
+ if (!acceptedRun.terminalReason) {
2295
+ const error = new Error("Duplicate input is already owned by another runtime execution");
2296
+ outerResult.reject(error);
2297
+ if (reservation?.shouldSchedule) {
2298
+ reservation.admission.completion.reject(error);
2299
+ settleAdmission(key, reservation.admission);
2300
+ }
2301
+ return;
2302
+ }
2303
+ const message = acceptance.assistant;
2304
+ if (!message) {
2305
+ const error = new Error("Duplicate terminal admission has no retained canonical assistant");
2306
+ outerResult.reject(error);
2307
+ if (reservation?.shouldSchedule) {
2308
+ reservation.admission.completion.reject(error);
2309
+ settleAdmission(key, reservation.admission);
2310
+ }
2311
+ return;
2312
+ }
2313
+ outerResult.resolve({
2314
+ run: acceptedRun,
2315
+ message,
2316
+ reason: acceptedRun.terminalReason,
2317
+ snapshotVersion: acceptedSnapshot.version,
2318
+ ...acceptedRun.terminalPolicyName && {
2319
+ policyName: acceptedRun.terminalPolicyName
2320
+ }
2321
+ });
2322
+ if (reservation?.shouldSchedule) {
2323
+ reservation.admission.completion.reject(new Error("Reserved run resolved to a duplicate durable input"));
2324
+ settleAdmission(key, reservation.admission);
2325
+ }
2326
+ return;
2327
+ }
2328
+ if (policy === "inject") {
2329
+ offeredRunId = acceptedRun.id;
2330
+ injection?.offer(key, { runId: acceptedRun.id, input: acceptedInput });
2331
+ }
2332
+ if (reservation && !reservation.shouldSchedule) {
2333
+ reservation.admission.completion.promise.then(outerResult.resolve, outerResult.reject);
2334
+ return;
2335
+ }
2336
+ const ticket = coordinator.submit({
2337
+ key,
2338
+ policy,
2339
+ create: async (signal) => {
2340
+ if (reservation)
2341
+ await waitForAdmissionAcceptances(reservation.lane);
2342
+ return {
2343
+ runId: acceptedRun.id,
2344
+ execute: () => executeRun({ acceptedRun, context, signal, key })
2345
+ };
2346
+ }
2347
+ });
2348
+ ticket.accepted.catch(() => {
2349
+ return;
2350
+ });
2351
+ if (reservation) {
2352
+ ticket.result.then(reservation.admission.completion.resolve, reservation.admission.completion.reject);
2353
+ reservation.admission.completion.promise.then((value) => {
2354
+ settleAdmission(key, reservation.admission);
2355
+ outerResult.resolve(value);
2356
+ }, (error) => {
2357
+ settleAdmission(key, reservation.admission);
2358
+ outerResult.reject(error);
2359
+ });
2360
+ } else {
2361
+ ticket.result.then(outerResult.resolve, outerResult.reject);
2362
+ }
2363
+ } catch (error) {
2364
+ outerAccepted.reject(error);
2365
+ outerAdmission.reject(error);
2366
+ outerResult.reject(error);
2367
+ if (reservation?.shouldSchedule) {
2368
+ reservation.admission.completion.reject(error);
2369
+ settleAdmission(key, reservation.admission);
2370
+ }
2371
+ } finally {
2372
+ acceptanceDone.resolve();
2373
+ handedOff();
2374
+ }
2375
+ })();
2376
+ return publicTicket;
2377
+ },
2378
+ resume,
2379
+ async interrupt(input) {
2380
+ const view = await config.store.loadRun({
2381
+ conversationId: input.conversationId,
2382
+ runId: input.runId
2383
+ });
2384
+ if (!view)
2385
+ throw new AgentRuntimeConflictError("run lookup");
2386
+ const requested = await config.store.requestRunInterrupt({
2387
+ conversationId: input.conversationId,
2388
+ runId: input.runId,
2389
+ expectedRevision: view.run.revision
2390
+ });
2391
+ if (requested.outcome === "applied") {
2392
+ const interruptedRun = findRun(requested.snapshot.runs, input.runId);
2393
+ await publish({
2394
+ type: "run-state",
2395
+ eventId: agentDurableEventId("run-state", interruptedRun.id, requested.snapshot.version),
2396
+ conversationId: interruptedRun.conversationId,
2397
+ runId: interruptedRun.id,
2398
+ snapshotVersion: requested.snapshot.version,
2399
+ state: interruptedRun.state,
2400
+ emittedAt: now().toISOString()
2401
+ });
2402
+ coordinator.stop(input.conversationKey ?? input.conversationId, "user-interrupt");
2403
+ }
2404
+ return requested;
2405
+ },
2406
+ async recover(options) {
2407
+ if (admissionClosed)
2408
+ throw closedError();
2409
+ const pageSize = options.pageSize ?? 100;
2410
+ const maxRuns = options.maxRuns ?? 1000;
2411
+ if (!Number.isSafeInteger(pageSize) || pageSize < 1 || pageSize > 1000) {
2412
+ throw new TypeError("Recovery pageSize must be an integer between 1 and 1000");
2413
+ }
2414
+ if (!Number.isSafeInteger(maxRuns) || maxRuns < 1) {
2415
+ throw new TypeError("Recovery maxRuns must be a positive safe integer");
2416
+ }
2417
+ const recoverable = [];
2418
+ let cursor;
2419
+ while (recoverable.length < maxRuns && !options.signal?.aborted && !admissionClosed) {
2420
+ const page = await config.store.scanRecoverable({
2421
+ ...cursor && { cursor },
2422
+ limit: Math.min(pageSize, maxRuns - recoverable.length)
2423
+ });
2424
+ recoverable.push(...page.items);
2425
+ cursor = page.nextCursor;
2426
+ if (!cursor || page.items.length === 0)
2427
+ break;
2428
+ }
2429
+ const grouped = new Map;
2430
+ for (const item of recoverable) {
2431
+ const items = grouped.get(item.conversationId) ?? [];
2432
+ items.push(item);
2433
+ grouped.set(item.conversationId, items);
2434
+ }
2435
+ const ordered = [];
2436
+ for (const [conversationId, items] of grouped) {
2437
+ const active = await config.store.listActiveRuns(conversationId);
2438
+ const position = new Map(active.map((run, index) => [run.id, index]));
2439
+ ordered.push(...items.sort((left, right) => {
2440
+ const leftPosition = position.get(left.run.id);
2441
+ const rightPosition = position.get(right.run.id);
2442
+ if (leftPosition === undefined && rightPosition === undefined)
2443
+ return 0;
2444
+ if (leftPosition === undefined)
2445
+ return 1;
2446
+ if (rightPosition === undefined)
2447
+ return -1;
2448
+ return leftPosition - rightPosition;
2449
+ }));
2450
+ }
2451
+ const outcomes = [];
2452
+ const scheduledRuns = new Map;
2453
+ for (const item of ordered) {
2454
+ if (options.signal?.aborted)
2455
+ break;
2456
+ if (admissionClosed)
2457
+ break;
2458
+ const releaseAdmission = beginAdmission();
2459
+ try {
2460
+ const active = await config.store.listActiveRuns(item.conversationId);
2461
+ const position = active.findIndex((run) => run.id === item.run.id);
2462
+ const scheduled = scheduledRuns.get(item.conversationId) ?? new Set;
2463
+ const blockedByUnscheduledPredecessor = position > 0 && active.slice(0, position).some((run) => !scheduled.has(run.id));
2464
+ if (blockedByUnscheduledPredecessor) {
2465
+ outcomes.push({
2466
+ conversationId: item.conversationId,
2467
+ runId: item.run.id,
2468
+ outcome: "skipped"
2469
+ });
2470
+ continue;
2471
+ }
2472
+ const decision = await options.decide?.(item) ?? (item.run.state === "queued" ? { action: "resume" } : { action: "skip" });
2473
+ if (admissionClosed)
2474
+ throw closedError();
2475
+ if (decision.action === "skip") {
2476
+ outcomes.push({
2477
+ conversationId: item.conversationId,
2478
+ runId: item.run.id,
2479
+ outcome: "skipped"
2480
+ });
2481
+ continue;
2482
+ }
2483
+ if (decision.action === "abandon") {
2484
+ const abandoned = await config.store.recoverRun({
2485
+ conversationId: item.conversationId,
2486
+ runId: item.run.id,
2487
+ expectedRevision: item.run.revision,
2488
+ action: "abandon"
2489
+ });
2490
+ if (abandoned.outcome !== "applied") {
2491
+ throw new AgentRuntimeConflictError("recovery abandon");
2492
+ }
2493
+ outcomes.push({
2494
+ conversationId: item.conversationId,
2495
+ runId: item.run.id,
2496
+ outcome: "abandoned"
2497
+ });
2498
+ continue;
2499
+ }
2500
+ if (decision.action === "requeue") {
2501
+ const requeued = await config.store.recoverRun({
2502
+ conversationId: item.conversationId,
2503
+ runId: item.run.id,
2504
+ expectedRevision: item.run.revision,
2505
+ action: "requeue",
2506
+ replaySafe: true
2507
+ });
2508
+ if (requeued.outcome !== "applied") {
2509
+ throw new AgentRuntimeConflictError("recovery requeue");
2510
+ }
2511
+ }
2512
+ const context = await options.resolveContext(item);
2513
+ const resumed = resume({
2514
+ conversationId: item.conversationId,
2515
+ runId: item.run.id,
2516
+ context
2517
+ });
2518
+ resumed.result.catch(() => {
2519
+ return;
2520
+ });
2521
+ await resumed.accepted;
2522
+ scheduled.add(item.run.id);
2523
+ scheduledRuns.set(item.conversationId, scheduled);
2524
+ outcomes.push({
2525
+ conversationId: item.conversationId,
2526
+ runId: item.run.id,
2527
+ outcome: decision.action === "requeue" ? "requeued" : "resumed",
2528
+ result: resumed.result
2529
+ });
2530
+ } catch (error) {
2531
+ outcomes.push({
2532
+ conversationId: item.conversationId,
2533
+ runId: item.run.id,
2534
+ outcome: "failed",
2535
+ error
2536
+ });
2537
+ } finally {
2538
+ releaseAdmission();
2539
+ }
2540
+ }
2541
+ return outcomes;
2542
+ },
2543
+ stop: (conversationKey, reason) => coordinator.stop(conversationKey, reason),
2544
+ close: async (options = {}) => {
2545
+ assertCloseBudgets(options);
2546
+ admissionClosed = true;
2547
+ const startedAt = performance.now();
2548
+ injection?.clear();
2549
+ const stranded = await drainAdmissions(options.forceTimeoutMs);
2550
+ const spent = Math.max(0, Math.round(performance.now() - startedAt));
2551
+ const remainingBudget = (value) => value === undefined ? undefined : Math.max(0, value - spent);
2552
+ const grace = remainingBudget(options.gracePeriodMs);
2553
+ const force = remainingBudget(options.forceTimeoutMs);
2554
+ const result = await coordinator.close({
2555
+ ...grace !== undefined && { gracePeriodMs: grace },
2556
+ ...force !== undefined && { forceTimeoutMs: force }
2557
+ });
2558
+ if (stranded === 0)
2559
+ return result;
2560
+ return { settled: false, timedOut: true, remaining: result.remaining + stranded };
2561
+ }
2562
+ };
2563
+ }
2564
+
2565
+ export { AgentContextOverflowError, createAgentSessionCoordinator, registerDeferredToolRepair, registerDeferredToolCatalog, deferredToolCatalog, repairedSearchCall, AgentAdmissionEventSchema, AgentTransientDeltaEventSchema, AgentReasoningStartEventSchema, AgentReasoningDeltaEventSchema, AgentReasoningEndEventSchema, AgentCheckpointEventSchema, AgentRunStateEventSchema, AgentToolStatusEventSchema, AgentTerminalEventSchema, AgentRuntimeEventSchema, AgentRuntimeEventCursorSchema, advanceAgentRuntimeEventCursor, agentDurableEventId, createAgentRuntimeEventSink, projectAgentHistoryDetailed, projectAgentHistory, createAgentToolFenceLifecycle, AgentTokenCountSchema, selectAgentHistory, composeAgentPrompt, AgentRuntimeConflictError, createAgentRuntime };