stitchkit 0.78.0 → 0.80.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 (84) hide show
  1. package/dist/agent-runtime-browser.js +53 -581
  2. package/dist/agent-runtime-coding-tools.js +6 -5
  3. package/dist/agent-runtime-harness.js +21 -94
  4. package/dist/agent-runtime-openrouter.js +1 -1
  5. package/dist/agent-runtime.js +68 -64
  6. package/dist/application/kernel.d.ts.map +1 -1
  7. package/dist/application/schemas.d.ts +2 -0
  8. package/dist/application/schemas.d.ts.map +1 -1
  9. package/dist/application/watch-hub.d.ts.map +1 -1
  10. package/dist/application-diagnostic-journal.js +14 -96
  11. package/dist/application-opentelemetry.js +6 -92
  12. package/dist/application-schemas.js +2 -1
  13. package/dist/application.js +158 -1802
  14. package/dist/cli.js +13 -11
  15. package/dist/contract/index.js +7 -4
  16. package/dist/index-2qzskm8h.js +63 -0
  17. package/dist/{index-93xp5tgg.js → index-2rwwmr7v.js} +3 -3
  18. package/dist/{index-kw12fsbc.js → index-3gye9wzb.js} +7 -3
  19. package/dist/{index-1ckavx4h.js → index-3z73fh2c.js} +1 -49
  20. package/dist/index-4fpa9dy2.js +51 -0
  21. package/dist/{index-cwp38wxn.js → index-5mtc969c.js} +2 -2
  22. package/dist/index-5s3zajp8.js +192 -0
  23. package/dist/index-6s7n2v50.js +583 -0
  24. package/dist/{index-qaajjfp6.js → index-758zx2ha.js} +15 -94
  25. package/dist/{index-qyrqwr4c.js → index-77fekveh.js} +4 -1
  26. package/dist/{index-k45qqrdh.js → index-7ag81v2f.js} +13 -166
  27. package/dist/{index-n1g2xm6a.js → index-7gnkny4z.js} +124 -1
  28. package/dist/index-7zbps32p.js +89 -0
  29. package/dist/index-85vfqd7m.js +135 -0
  30. package/dist/{index-4ntp63ps.js → index-9s6z8vgf.js} +18 -142
  31. package/dist/index-a916km3r.js +45 -0
  32. package/dist/index-b9aefrqd.js +20 -0
  33. package/dist/index-dre2ywck.js +48 -0
  34. package/dist/{index-s5tn4kdv.js → index-dwf1f2ap.js} +3 -3
  35. package/dist/{index-wwst0td5.js → index-dx9xehwt.js} +1 -1
  36. package/dist/{index-5r0ak8fr.js → index-dxesg10d.js} +4 -4
  37. package/dist/{index-aczggrty.js → index-dxjjv399.js} +2 -2
  38. package/dist/{index-j6mfaw26.js → index-egaabxkz.js} +3 -3
  39. package/dist/index-evcnmsc3.js +866 -0
  40. package/dist/{index-efm026pw.js → index-fxz0v7vg.js} +86 -86
  41. package/dist/{index-56fm73re.js → index-hb5pf3s4.js} +1 -1
  42. package/dist/{index-n7apa6sy.js → index-k9ay6v6d.js} +24 -275
  43. package/dist/index-kzfs85xp.js +9 -0
  44. package/dist/{index-vbf2p6me.js → index-m9kzax52.js} +91 -89
  45. package/dist/{index-22by16v6.js → index-mgtxfe6b.js} +1 -1
  46. package/dist/index-p7hgdyhb.js +22 -0
  47. package/dist/index-pq95qkbf.js +0 -0
  48. package/dist/index-t0z5p5w6.js +318 -0
  49. package/dist/{index-31k1ns1s.js → index-vwp69871.js} +13 -11
  50. package/dist/index-wc4x00bn.js +103 -0
  51. package/dist/{index-aewy3x5j.js → index-xcetq6j3.js} +10 -8
  52. package/dist/{index-7z69kyrh.js → index-y01f4223.js} +24 -40
  53. package/dist/{index-dmfn9m4x.js → index-ywd0y6m1.js} +20 -341
  54. package/dist/index.js +46 -407
  55. package/dist/live.js +6 -3
  56. package/dist/node.js +17 -14
  57. package/dist/observability/index.js +8 -7
  58. package/dist/primitives.js +4 -2
  59. package/dist/react.js +1 -1
  60. package/dist/remote.js +7 -3
  61. package/dist/server/index.js +32 -45
  62. package/dist/telegram.js +1 -1
  63. package/dist/testing.js +90 -1576
  64. package/dist/tool-invoker.js +11 -9
  65. package/dist/tools/async-operation-contract.d.ts +93 -0
  66. package/dist/tools/async-operation-contract.d.ts.map +1 -0
  67. package/dist/tools/async-operation.d.ts +2 -47
  68. package/dist/tools/async-operation.d.ts.map +1 -1
  69. package/dist/tools/view-file-contract.d.ts +98 -0
  70. package/dist/tools/view-file-contract.d.ts.map +1 -0
  71. package/dist/tools/view-file.d.ts +4 -83
  72. package/dist/tools/view-file.d.ts.map +1 -1
  73. package/dist/tools-contract.d.ts +29 -0
  74. package/dist/tools-contract.d.ts.map +1 -0
  75. package/dist/tools-contract.js +24 -0
  76. package/dist/tools.d.ts +3 -3
  77. package/dist/tools.d.ts.map +1 -1
  78. package/dist/tools.js +61 -140
  79. package/llms-full.txt +86 -3
  80. package/package.json +9 -6
  81. package/dist/index-anyqnqcv.js +0 -79
  82. package/dist/index-ksp6e2ye.js +0 -24
  83. package/dist/index-vj3vvpaa.js +0 -307
  84. package/dist/index-wfq8zerm.js +0 -92
@@ -37,5 +37,8 @@ function mapObject(source, mapper) {
37
37
  }
38
38
  return result;
39
39
  }
40
+ function mapObjectTypeBoundary(source, mapper) {
41
+ return mapObject(source, (key, value) => mapper(key, value));
42
+ }
40
43
 
41
- export { typedEntries, isRecord, callRuntimeHandler, executableAgentRuntimeTools, transportResult, mapObject };
44
+ export { typedEntries, isRecord, callRuntimeHandler, executableAgentRuntimeTools, transportResult, mapObject, mapObjectTypeBoundary };
@@ -1,64 +1,24 @@
1
+ import {
2
+ DEFAULT_STREAM_LINE_BYTES,
3
+ inputIsQuery,
4
+ parseSSE,
5
+ readBoundedUtf8Lines
6
+ } from "./index-hb5pf3s4.js";
7
+ import {
8
+ createTraceContext,
9
+ formatTraceparent
10
+ } from "./index-fxz0v7vg.js";
1
11
  import {
2
12
  ContractStreamFrameSchema,
3
13
  DEFAULT_CONTRACT_STREAM_FRAME_BYTES,
4
14
  parseTrailingWildcard
5
- } from "./index-7z69kyrh.js";
15
+ } from "./index-y01f4223.js";
6
16
  import {
7
17
  isRecord,
8
18
  mapObject,
9
19
  transportResult,
10
20
  typedEntries
11
- } from "./index-ksp6e2ye.js";
12
-
13
- // src/internal/random-hex.ts
14
- function randomHex(bytes) {
15
- const arr = new Uint8Array(bytes);
16
- crypto.getRandomValues(arr);
17
- let hex = "";
18
- for (const byte of arr)
19
- hex += byte.toString(16).padStart(2, "0");
20
- return hex;
21
- }
22
-
23
- // src/observability/trace.ts
24
- var TRACEPARENT_RE = /^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})(.*)$/i;
25
- function createTraceContext() {
26
- return { traceId: randomHex(16), spanId: randomHex(8) };
27
- }
28
- function parseTraceparent(header) {
29
- if (!header)
30
- return null;
31
- const match = TRACEPARENT_RE.exec(header.trim());
32
- if (!match?.[1] || !match[2] || !match[3] || !match[4] || match[5] === undefined)
33
- return null;
34
- const version = match[1].toLowerCase();
35
- if (version === "ff")
36
- return null;
37
- const suffix = match[5];
38
- if (version === "00" ? suffix !== "" : suffix !== "" && !/^(?:-[0-9a-f]{2,})+$/i.test(suffix)) {
39
- return null;
40
- }
41
- const traceId = match[2].toLowerCase();
42
- const parentSpanId = match[3].toLowerCase();
43
- const traceFlags = match[4].toLowerCase();
44
- if (/^0+$/.test(traceId) || /^0+$/.test(parentSpanId))
45
- return null;
46
- return { traceId, spanId: randomHex(8), parentSpanId, traceFlags };
47
- }
48
- function formatTraceparent(ctx) {
49
- return `00-${ctx.traceId}-${ctx.spanId}-${ctx.traceFlags ?? "01"}`;
50
- }
51
- function childSpan(parent) {
52
- return {
53
- traceId: parent.traceId,
54
- spanId: randomHex(8),
55
- parentSpanId: parent.spanId,
56
- ...parent.tracestate !== undefined && { tracestate: parent.tracestate },
57
- ...parent.baggage !== undefined && { baggage: parent.baggage },
58
- ...parent.traceFlags !== undefined && { traceFlags: parent.traceFlags }
59
- };
60
- }
61
- var encoder = new TextEncoder;
21
+ } from "./index-77fekveh.js";
62
22
 
63
23
  // src/browser/http.ts
64
24
  import ky, {
@@ -373,114 +333,6 @@ function createHttpClient(config) {
373
333
  }
374
334
  };
375
335
  }
376
-
377
- // src/internal/errors.ts
378
- import { z } from "zod";
379
- function issuePath(path) {
380
- return path.length > 0 ? path.map(String).join(".") : "(root)";
381
- }
382
- function formatZodError(error) {
383
- const issues = error.issues.slice(0, 5);
384
- const lines = issues.map((issue) => `${issuePath(issue.path)}: ${issue.message}`);
385
- const suffix = error.issues.length > 5 ? `
386
- ...and ${error.issues.length - 5} more issues` : "";
387
- return lines.join(`
388
- `) + suffix;
389
- }
390
- function zodIssues(error) {
391
- return error.issues.map((issue) => ({
392
- path: issuePath(issue.path),
393
- code: issue.code,
394
- message: issue.message
395
- }));
396
- }
397
-
398
- // src/internal/bounded-lines.ts
399
- var DEFAULT_STREAM_LINE_BYTES = 1024 * 1024;
400
- function lineLimit(value) {
401
- const resolved = value ?? DEFAULT_STREAM_LINE_BYTES;
402
- if (!Number.isSafeInteger(resolved) || resolved <= 0) {
403
- throw new TypeError("maxLineBytes must be a positive safe integer");
404
- }
405
- return resolved;
406
- }
407
- function joinBytes(left, right) {
408
- if (left.byteLength === 0)
409
- return right.slice();
410
- const result = new Uint8Array(left.byteLength + right.byteLength);
411
- result.set(left);
412
- result.set(right, left.byteLength);
413
- return result;
414
- }
415
- async function* readBoundedUtf8Lines(response, maxLineBytes, requireFinalNewline = false) {
416
- const reader = response.body?.getReader();
417
- if (!reader)
418
- return;
419
- const limit = lineLimit(maxLineBytes);
420
- const decoder = new TextDecoder("utf-8", { fatal: true });
421
- let pending = new Uint8Array;
422
- try {
423
- for (;; ) {
424
- const chunk = await reader.read();
425
- if (chunk.done)
426
- break;
427
- let start = 0;
428
- for (let index = 0;index < chunk.value.byteLength; index += 1) {
429
- if (chunk.value[index] !== 10)
430
- continue;
431
- const lineBytes = joinBytes(pending, chunk.value.slice(start, index));
432
- if (lineBytes.byteLength > limit) {
433
- throw new RangeError(`Stream line exceeds the ${limit} byte limit`);
434
- }
435
- yield decoder.decode(lineBytes);
436
- pending = new Uint8Array;
437
- start = index + 1;
438
- }
439
- pending = joinBytes(pending, chunk.value.slice(start));
440
- if (pending.byteLength > limit) {
441
- throw new RangeError(`Stream line exceeds the ${limit} byte limit`);
442
- }
443
- }
444
- if (pending.byteLength > 0) {
445
- if (requireFinalNewline) {
446
- throw new SyntaxError("Stream ended with an unterminated final line");
447
- }
448
- yield decoder.decode(pending);
449
- }
450
- } finally {
451
- await reader.cancel().catch(() => {
452
- return;
453
- });
454
- reader.releaseLock();
455
- }
456
- }
457
-
458
- // src/server/stream.ts
459
- async function* parseSSE(response, options) {
460
- try {
461
- for await (const rawLine of readBoundedUtf8Lines(response, options?.maxLineBytes ?? DEFAULT_STREAM_LINE_BYTES)) {
462
- const line = rawLine.endsWith("\r") ? rawLine.slice(0, -1) : rawLine;
463
- if (!line.startsWith("data:"))
464
- continue;
465
- const data = line.slice(5).replace(/^ /, "");
466
- if (data === "[DONE]")
467
- return;
468
- try {
469
- yield JSON.parse(data);
470
- } catch (error) {
471
- const failure = error instanceof Error ? error : new Error(String(error));
472
- if (!options?.onParseError)
473
- throw failure;
474
- options.onParseError(data, failure);
475
- }
476
- }
477
- } catch (error) {
478
- const failure = error instanceof Error ? error : new Error(String(error));
479
- if (!options?.onParseError)
480
- throw failure;
481
- options.onParseError("", failure);
482
- }
483
- }
484
336
  // src/browser/stream.ts
485
337
  function parseFailure(raw, error, onParseError) {
486
338
  const failure = error instanceof Error ? error : new Error(String(error));
@@ -555,11 +407,6 @@ function buildMultipartForm(descriptor, values) {
555
407
  return formData;
556
408
  }
557
409
 
558
- // src/internal/http-input.ts
559
- function inputIsQuery(method) {
560
- return method === "GET" || method === "DELETE";
561
- }
562
-
563
410
  // src/browser/client-url.ts
564
411
  function isParamArray(value) {
565
412
  return Array.isArray(value) && value.every((item) => typeof item === "string" || typeof item === "number");
@@ -1108,4 +955,4 @@ function createScopedUrlBuilders(contracts, source, scopeConfigs) {
1108
955
  return buildScopedRegistry(contracts, scopeConfigs, "URL builder", (contract, config) => createUrlBuilder(contract, source, config));
1109
956
  }
1110
957
 
1111
- export { randomHex, createTraceContext, parseTraceparent, formatTraceparent, childSpan, ApiError, createHttpClient, formatZodError, zodIssues, parseSSE, parseNDJSON, contractEndpointMatchers, createClient, createClients, createScopedClients, createUrlBuilder, createUrlBuilders, createScopedUrlBuilders };
958
+ export { ApiError, createHttpClient, parseNDJSON, contractEndpointMatchers, createClient, createClients, createScopedClients, createUrlBuilder, createUrlBuilders, createScopedUrlBuilders };
@@ -199,5 +199,128 @@ var CreditWindowSnapshotSchema = z.object({
199
199
  replenishedBytes: z.number().int().nonnegative(),
200
200
  waiting: z.number().int().nonnegative()
201
201
  }).strict().readonly();
202
+ function createCreditWindow(config) {
203
+ const capacityBytes = PositiveSafeIntegerSchema.parse(config.capacityBytes);
204
+ let availableBytes = capacityBytes;
205
+ let state = "open";
206
+ let acquired = 0;
207
+ let refused = 0;
208
+ let replenishedBytes = 0;
209
+ const waiters = new Set;
210
+ const snapshot = () => CreditWindowSnapshotSchema.parse({
211
+ state,
212
+ capacityBytes,
213
+ availableBytes,
214
+ leasedBytes: capacityBytes - availableBytes,
215
+ acquired,
216
+ refused,
217
+ replenishedBytes,
218
+ waiting: waiters.size
219
+ });
220
+ const serveWaiters = () => {
221
+ for (const waiter of waiters) {
222
+ if (waiter.bytes > availableBytes)
223
+ return;
224
+ waiter.settle({ outcome: "leased", lease: lease(waiter.bytes) });
225
+ }
226
+ };
227
+ const lease = (requested) => {
228
+ availableBytes -= requested;
229
+ acquired += 1;
230
+ let leaseReleased = false;
231
+ return {
232
+ bytes: requested,
233
+ get released() {
234
+ return leaseReleased;
235
+ },
236
+ release() {
237
+ if (leaseReleased)
238
+ return;
239
+ leaseReleased = true;
240
+ availableBytes += requested;
241
+ replenishedBytes += requested;
242
+ if (availableBytes > capacityBytes) {
243
+ throw new Error("Credit window accounting exceeded its capacity");
244
+ }
245
+ serveWaiters();
246
+ }
247
+ };
248
+ };
249
+ const tryLease = (requested) => {
250
+ if (state === "closed")
251
+ return { outcome: "refused", reason: "closed" };
252
+ if (requested > capacityBytes) {
253
+ return { outcome: "refused", reason: "larger-than-window" };
254
+ }
255
+ if (requested > availableBytes) {
256
+ return { outcome: "refused", reason: "insufficient-credit" };
257
+ }
258
+ return { outcome: "leased", lease: lease(requested) };
259
+ };
260
+ const acquireNow = (requested) => {
261
+ const result = tryLease(requested);
262
+ if (result.outcome === "refused")
263
+ refused += 1;
264
+ return result;
265
+ };
266
+ const acquireWaiting = (requested, options) => {
267
+ const timeoutMs = options.timeoutMs === undefined ? undefined : PositiveSafeIntegerSchema.parse(options.timeoutMs);
268
+ const immediate = tryLease(requested);
269
+ if (immediate.outcome === "leased")
270
+ return Promise.resolve(immediate);
271
+ if (immediate.reason !== "insufficient-credit") {
272
+ refused += 1;
273
+ return Promise.resolve({ outcome: "refused", reason: immediate.reason });
274
+ }
275
+ if (options.signal?.aborted) {
276
+ refused += 1;
277
+ return Promise.resolve({ outcome: "refused", reason: "aborted" });
278
+ }
279
+ return new Promise((resolve) => {
280
+ let settled = false;
281
+ let timer;
282
+ const waiter = {
283
+ bytes: requested,
284
+ settle(result) {
285
+ if (settled)
286
+ return;
287
+ settled = true;
288
+ if (timer !== undefined)
289
+ clearTimeout(timer);
290
+ options.signal?.removeEventListener("abort", onAbort);
291
+ waiters.delete(waiter);
292
+ if (result.outcome === "refused")
293
+ refused += 1;
294
+ resolve(result);
295
+ }
296
+ };
297
+ function onAbort() {
298
+ waiter.settle({ outcome: "refused", reason: "aborted" });
299
+ }
300
+ waiters.add(waiter);
301
+ options.signal?.addEventListener("abort", onAbort, { once: true });
302
+ if (timeoutMs !== undefined) {
303
+ timer = setTimeout(() => {
304
+ waiter.settle({ outcome: "refused", reason: "timed-out" });
305
+ }, timeoutMs);
306
+ }
307
+ });
308
+ };
309
+ function acquire(bytes, options) {
310
+ const requested = PositiveSafeIntegerSchema.parse(bytes);
311
+ return options === undefined ? acquireNow(requested) : acquireWaiting(requested, options);
312
+ }
313
+ return {
314
+ acquire,
315
+ close() {
316
+ state = "closed";
317
+ for (const waiter of [...waiters]) {
318
+ waiter.settle({ outcome: "refused", reason: "closed" });
319
+ }
320
+ return snapshot();
321
+ },
322
+ getSnapshot: snapshot
323
+ };
324
+ }
202
325
 
203
- export { createBoundedChannel };
326
+ export { BoundedChannelPolicySchema, BoundedChannelStateSchema, BoundedChannelSnapshotSchema, BoundedChannelReaderError, createBoundedChannel, CreditWindowSnapshotSchema, createCreditWindow };
@@ -0,0 +1,89 @@
1
+ import {
2
+ safeJsonParse
3
+ } from "./index-kzfs85xp.js";
4
+ import {
5
+ isRecord
6
+ } from "./index-77fekveh.js";
7
+
8
+ // src/tools/coerce.ts
9
+ import { z } from "zod";
10
+ function needsJsonCoercion(schema) {
11
+ if (schema instanceof z.ZodArray || schema instanceof z.ZodObject || schema instanceof z.ZodRecord || schema instanceof z.ZodTuple || schema instanceof z.ZodUnion) {
12
+ return true;
13
+ }
14
+ if (schema instanceof z.ZodOptional || schema instanceof z.ZodNullable || schema instanceof z.ZodDefault) {
15
+ return needsJsonCoercion(schema.unwrap());
16
+ }
17
+ return false;
18
+ }
19
+ function acceptsRawString(schema) {
20
+ const type = schema._zod.def.type;
21
+ if (type === "string" || type === "template_literal")
22
+ return true;
23
+ if (schema instanceof z.ZodLiteral) {
24
+ return schema.def.values.some((value) => typeof value === "string");
25
+ }
26
+ if (schema instanceof z.ZodEnum) {
27
+ return schema.options.some((value) => typeof value === "string");
28
+ }
29
+ if (schema instanceof z.ZodOptional || schema instanceof z.ZodNullable || schema instanceof z.ZodDefault) {
30
+ return acceptsRawString(schema.unwrap());
31
+ }
32
+ if (schema instanceof z.ZodUnion) {
33
+ return schema.def.options.some((option) => acceptsRawString(option));
34
+ }
35
+ return false;
36
+ }
37
+ function matchingVariant(union, value) {
38
+ const disc = union.def.discriminator;
39
+ const tag = value[disc];
40
+ for (const option of union.def.options) {
41
+ if (!(option instanceof z.ZodObject))
42
+ continue;
43
+ const field = option.shape[disc];
44
+ if (field instanceof z.ZodLiteral && field.def.values.some((v) => v === tag))
45
+ return option;
46
+ if (field instanceof z.ZodEnum && field.options.some((v) => v === tag))
47
+ return option;
48
+ }
49
+ return;
50
+ }
51
+ function coerceValue(value, schema) {
52
+ if (!schema)
53
+ return value;
54
+ if (schema instanceof z.ZodOptional || schema instanceof z.ZodNullable || schema instanceof z.ZodDefault) {
55
+ return coerceValue(value, schema.unwrap());
56
+ }
57
+ let current = value;
58
+ if (typeof current === "string" && needsJsonCoercion(schema)) {
59
+ if (acceptsRawString(schema))
60
+ return current;
61
+ try {
62
+ current = safeJsonParse(current);
63
+ } catch {
64
+ return value;
65
+ }
66
+ }
67
+ if (schema instanceof z.ZodObject && isRecord(current)) {
68
+ const shape = schema.shape;
69
+ const out = {};
70
+ for (const [key, item] of Object.entries(current)) {
71
+ out[key] = coerceValue(item, shape[key]);
72
+ }
73
+ return out;
74
+ }
75
+ if (schema instanceof z.ZodArray && Array.isArray(current)) {
76
+ return current.map((item) => coerceValue(item, schema.element));
77
+ }
78
+ if (schema instanceof z.ZodDiscriminatedUnion && isRecord(current)) {
79
+ const variant = matchingVariant(schema, current);
80
+ return variant ? coerceValue(current, variant) : current;
81
+ }
82
+ return current;
83
+ }
84
+ function coerceJsonArgs(args, schema) {
85
+ const coerced = coerceValue(args, schema);
86
+ return isRecord(coerced) ? coerced : args;
87
+ }
88
+
89
+ export { coerceJsonArgs };
@@ -0,0 +1,135 @@
1
+ import {
2
+ AgentAssistantPlaceholderSchema,
3
+ AgentMessageSchema,
4
+ AgentProviderEnvelopeSchema,
5
+ AgentRecordIdSchema,
6
+ AgentRecordVersionSchema,
7
+ AgentRunMetricsSchema,
8
+ AgentRunSchema,
9
+ AgentRunStateSchema,
10
+ AgentTerminalReasonSchema,
11
+ AgentTimestampSchema
12
+ } from "./index-x1th9s8c.js";
13
+
14
+ // src/agent-runtime/event-schema.ts
15
+ import { z } from "zod";
16
+ var AgentAdmissionEventSchema = z.object({
17
+ type: z.literal("admission"),
18
+ eventId: AgentRecordIdSchema,
19
+ conversationId: AgentRecordIdSchema,
20
+ runId: AgentRecordIdSchema,
21
+ snapshotVersion: AgentRecordVersionSchema,
22
+ input: AgentMessageSchema,
23
+ run: AgentRunSchema,
24
+ assistant: z.union([AgentAssistantPlaceholderSchema, AgentMessageSchema]),
25
+ emittedAt: AgentTimestampSchema
26
+ });
27
+ var EventIdentitySchema = z.object({
28
+ conversationId: AgentRecordIdSchema,
29
+ runId: AgentRecordIdSchema,
30
+ emittedAt: AgentTimestampSchema
31
+ });
32
+ var AgentTransientDeltaEventSchema = EventIdentitySchema.extend({
33
+ type: z.literal("assistant-delta"),
34
+ runtimeEpoch: z.string().min(1),
35
+ sequence: z.int().nonnegative(),
36
+ textDelta: z.string()
37
+ });
38
+ var AgentTransientReasoningIdentitySchema = EventIdentitySchema.extend({
39
+ runtimeEpoch: z.string().min(1),
40
+ sequence: z.int().nonnegative(),
41
+ provider: AgentProviderEnvelopeSchema.optional()
42
+ });
43
+ var AgentReasoningStartEventSchema = AgentTransientReasoningIdentitySchema.extend({
44
+ type: z.literal("reasoning-start")
45
+ });
46
+ var AgentReasoningDeltaEventSchema = AgentTransientReasoningIdentitySchema.extend({
47
+ type: z.literal("reasoning-delta"),
48
+ textDelta: z.string()
49
+ });
50
+ var AgentReasoningEndEventSchema = AgentTransientReasoningIdentitySchema.extend({
51
+ type: z.literal("reasoning-end")
52
+ });
53
+ var AgentCheckpointEventSchema = EventIdentitySchema.extend({
54
+ type: z.literal("assistant-checkpoint"),
55
+ eventId: AgentRecordIdSchema,
56
+ snapshotVersion: AgentRecordVersionSchema,
57
+ message: AgentMessageSchema,
58
+ metrics: AgentRunMetricsSchema.optional()
59
+ });
60
+ var AgentRunStateEventSchema = EventIdentitySchema.extend({
61
+ type: z.literal("run-state"),
62
+ eventId: AgentRecordIdSchema,
63
+ snapshotVersion: AgentRecordVersionSchema,
64
+ state: AgentRunStateSchema
65
+ });
66
+ var AgentToolStatusEventSchema = EventIdentitySchema.extend({
67
+ type: z.literal("tool-status"),
68
+ runtimeEpoch: z.string().min(1),
69
+ sequence: z.int().nonnegative(),
70
+ callId: AgentRecordIdSchema,
71
+ toolName: z.string().min(1),
72
+ status: z.enum(["started", "completed", "failed", "interrupted"]),
73
+ input: z.json().optional(),
74
+ output: z.json().optional()
75
+ });
76
+ var AgentTerminalEventSchema = EventIdentitySchema.extend({
77
+ type: z.literal("terminal"),
78
+ eventId: AgentRecordIdSchema,
79
+ snapshotVersion: AgentRecordVersionSchema,
80
+ reason: AgentTerminalReasonSchema,
81
+ policyName: z.string().min(1).optional(),
82
+ message: AgentMessageSchema,
83
+ metrics: AgentRunMetricsSchema.optional()
84
+ });
85
+ var AgentRuntimeEventSchema = z.discriminatedUnion("type", [
86
+ AgentAdmissionEventSchema,
87
+ AgentTransientDeltaEventSchema,
88
+ AgentReasoningStartEventSchema,
89
+ AgentReasoningDeltaEventSchema,
90
+ AgentReasoningEndEventSchema,
91
+ AgentCheckpointEventSchema,
92
+ AgentRunStateEventSchema,
93
+ AgentToolStatusEventSchema,
94
+ AgentTerminalEventSchema
95
+ ]);
96
+ var AgentRuntimeEventCursorSchema = z.object({
97
+ snapshotVersion: AgentRecordVersionSchema.optional(),
98
+ durableEventIds: z.array(AgentRecordIdSchema).optional(),
99
+ runtimeEpoch: z.string().min(1).optional(),
100
+ sequence: z.int().nonnegative().optional()
101
+ });
102
+ function isDurableEvent(event) {
103
+ return event.type === "admission" || event.type === "assistant-checkpoint" || event.type === "run-state" || event.type === "terminal";
104
+ }
105
+ function advanceAgentRuntimeEventCursor(rawCursor, event) {
106
+ const cursor = AgentRuntimeEventCursorSchema.parse(rawCursor);
107
+ if (isDurableEvent(event)) {
108
+ const previous = cursor.snapshotVersion;
109
+ const durableEventIds = previous === event.snapshotVersion ? cursor.durableEventIds ?? [] : [];
110
+ if (previous !== undefined && event.snapshotVersion < previous || durableEventIds.includes(event.eventId)) {
111
+ return { status: "duplicate", cursor };
112
+ }
113
+ return {
114
+ status: "accepted",
115
+ cursor: {
116
+ ...cursor,
117
+ snapshotVersion: event.snapshotVersion,
118
+ durableEventIds: [...durableEventIds, event.eventId]
119
+ }
120
+ };
121
+ }
122
+ const previousSequence = cursor.runtimeEpoch === event.runtimeEpoch ? cursor.sequence : undefined;
123
+ if (previousSequence !== undefined && event.sequence <= previousSequence) {
124
+ return { status: "duplicate", cursor };
125
+ }
126
+ return {
127
+ status: previousSequence !== undefined && event.sequence > previousSequence + 1 ? "gap" : "accepted",
128
+ cursor: { ...cursor, runtimeEpoch: event.runtimeEpoch, sequence: event.sequence }
129
+ };
130
+ }
131
+ function agentDurableEventId(type, runId, snapshotVersion) {
132
+ return `${runId}:${type}:${snapshotVersion}`;
133
+ }
134
+
135
+ export { AgentAdmissionEventSchema, AgentTransientDeltaEventSchema, AgentReasoningStartEventSchema, AgentReasoningDeltaEventSchema, AgentReasoningEndEventSchema, AgentCheckpointEventSchema, AgentRunStateEventSchema, AgentToolStatusEventSchema, AgentTerminalEventSchema, AgentRuntimeEventSchema, AgentRuntimeEventCursorSchema, advanceAgentRuntimeEventCursor, agentDurableEventId };