@ag-ui/core 0.0.59 → 1.0.0-canary.1789569879.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.
package/dist/index.mjs CHANGED
@@ -1,5 +1,786 @@
1
- import { z } from "zod";
1
+ import { n as EventType, t as PROTOCOL_VERSION } from "./version-DQ7V2LqS.mjs";
2
2
 
3
+ //#region src/generated/serialization.ts
4
+ const shapes = {
5
+ TextMessageStartEvent: {
6
+ optional: [
7
+ "timestamp",
8
+ "rawEvent",
9
+ "metadata",
10
+ "subagentRunId",
11
+ "role",
12
+ "name"
13
+ ],
14
+ fields: {}
15
+ },
16
+ TextMessageContentEvent: {
17
+ optional: [
18
+ "timestamp",
19
+ "rawEvent",
20
+ "metadata",
21
+ "subagentRunId"
22
+ ],
23
+ fields: {}
24
+ },
25
+ TextMessageEndEvent: {
26
+ optional: [
27
+ "timestamp",
28
+ "rawEvent",
29
+ "metadata",
30
+ "subagentRunId"
31
+ ],
32
+ fields: {}
33
+ },
34
+ TextMessageChunkEvent: {
35
+ optional: [
36
+ "timestamp",
37
+ "rawEvent",
38
+ "metadata",
39
+ "subagentRunId",
40
+ "messageId",
41
+ "role",
42
+ "delta",
43
+ "name"
44
+ ],
45
+ fields: {}
46
+ },
47
+ ToolCallStartEvent: {
48
+ optional: [
49
+ "timestamp",
50
+ "rawEvent",
51
+ "metadata",
52
+ "subagentRunId",
53
+ "parentMessageId"
54
+ ],
55
+ fields: {}
56
+ },
57
+ ToolCallArgsEvent: {
58
+ optional: [
59
+ "timestamp",
60
+ "rawEvent",
61
+ "metadata",
62
+ "subagentRunId"
63
+ ],
64
+ fields: {}
65
+ },
66
+ ToolCallEndEvent: {
67
+ optional: [
68
+ "timestamp",
69
+ "rawEvent",
70
+ "metadata",
71
+ "subagentRunId"
72
+ ],
73
+ fields: {}
74
+ },
75
+ ToolCallChunkEvent: {
76
+ optional: [
77
+ "timestamp",
78
+ "rawEvent",
79
+ "metadata",
80
+ "subagentRunId",
81
+ "toolCallId",
82
+ "toolCallName",
83
+ "parentMessageId",
84
+ "delta"
85
+ ],
86
+ fields: {}
87
+ },
88
+ TextPart: {
89
+ optional: ["id", "metadata"],
90
+ fields: {}
91
+ },
92
+ DataSource: {
93
+ optional: [],
94
+ fields: {}
95
+ },
96
+ UrlSource: {
97
+ optional: ["mimeType"],
98
+ fields: {}
99
+ },
100
+ FileSource: {
101
+ optional: ["provider", "mimeType"],
102
+ fields: {}
103
+ },
104
+ PartSource: {
105
+ discriminator: "type",
106
+ variants: {
107
+ data: "DataSource",
108
+ url: "UrlSource",
109
+ file: "FileSource"
110
+ }
111
+ },
112
+ ImagePart: {
113
+ optional: ["id", "metadata"],
114
+ fields: { source: "PartSource" }
115
+ },
116
+ AudioPart: {
117
+ optional: ["id", "metadata"],
118
+ fields: { source: "PartSource" }
119
+ },
120
+ VideoPart: {
121
+ optional: ["id", "metadata"],
122
+ fields: { source: "PartSource" }
123
+ },
124
+ DocumentPart: {
125
+ optional: ["id", "metadata"],
126
+ fields: { source: "PartSource" }
127
+ },
128
+ ContentPart: {
129
+ discriminator: "type",
130
+ variants: {
131
+ text: "TextPart",
132
+ image: "ImagePart",
133
+ audio: "AudioPart",
134
+ video: "VideoPart",
135
+ document: "DocumentPart"
136
+ }
137
+ },
138
+ ToolCallResultEvent: {
139
+ optional: [
140
+ "timestamp",
141
+ "rawEvent",
142
+ "metadata",
143
+ "subagentRunId",
144
+ "role"
145
+ ],
146
+ fields: { content: { array: "ContentPart" } }
147
+ },
148
+ StateSnapshotEvent: {
149
+ optional: [
150
+ "timestamp",
151
+ "rawEvent",
152
+ "metadata",
153
+ "subagentRunId"
154
+ ],
155
+ fields: {}
156
+ },
157
+ AddOperation: {
158
+ optional: [],
159
+ fields: {}
160
+ },
161
+ RemoveOperation: {
162
+ optional: [],
163
+ fields: {}
164
+ },
165
+ ReplaceOperation: {
166
+ optional: [],
167
+ fields: {}
168
+ },
169
+ MoveOperation: {
170
+ optional: [],
171
+ fields: {}
172
+ },
173
+ CopyOperation: {
174
+ optional: [],
175
+ fields: {}
176
+ },
177
+ TestOperation: {
178
+ optional: [],
179
+ fields: {}
180
+ },
181
+ JsonPatchOperation: {
182
+ discriminator: "op",
183
+ variants: {
184
+ add: "AddOperation",
185
+ remove: "RemoveOperation",
186
+ replace: "ReplaceOperation",
187
+ move: "MoveOperation",
188
+ copy: "CopyOperation",
189
+ test: "TestOperation"
190
+ }
191
+ },
192
+ StateDeltaEvent: {
193
+ optional: [
194
+ "timestamp",
195
+ "rawEvent",
196
+ "metadata",
197
+ "subagentRunId"
198
+ ],
199
+ fields: { delta: { array: "JsonPatchOperation" } }
200
+ },
201
+ DeveloperMessage: {
202
+ optional: [
203
+ "subagentRunId",
204
+ "name",
205
+ "encryptedValue",
206
+ "metadata"
207
+ ],
208
+ fields: {}
209
+ },
210
+ SystemMessage: {
211
+ optional: [
212
+ "subagentRunId",
213
+ "name",
214
+ "encryptedValue",
215
+ "metadata"
216
+ ],
217
+ fields: {}
218
+ },
219
+ FunctionCall: {
220
+ optional: [],
221
+ fields: {}
222
+ },
223
+ ToolCall: {
224
+ optional: ["encryptedValue", "metadata"],
225
+ fields: { function: "FunctionCall" }
226
+ },
227
+ AssistantMessage: {
228
+ optional: [
229
+ "subagentRunId",
230
+ "name",
231
+ "encryptedValue",
232
+ "metadata",
233
+ "content",
234
+ "toolCalls"
235
+ ],
236
+ fields: { toolCalls: { array: "ToolCall" } }
237
+ },
238
+ UserMessage: {
239
+ optional: [
240
+ "subagentRunId",
241
+ "name",
242
+ "encryptedValue",
243
+ "metadata"
244
+ ],
245
+ fields: { content: { array: "ContentPart" } }
246
+ },
247
+ ToolMessage: {
248
+ optional: [
249
+ "subagentRunId",
250
+ "error",
251
+ "encryptedValue",
252
+ "metadata"
253
+ ],
254
+ fields: { content: { array: "ContentPart" } }
255
+ },
256
+ ActivityMessage: {
257
+ optional: ["subagentRunId", "metadata"],
258
+ fields: {}
259
+ },
260
+ ReasoningMessage: {
261
+ optional: [
262
+ "subagentRunId",
263
+ "encryptedValue",
264
+ "metadata"
265
+ ],
266
+ fields: {}
267
+ },
268
+ Message: {
269
+ discriminator: "role",
270
+ variants: {
271
+ developer: "DeveloperMessage",
272
+ system: "SystemMessage",
273
+ assistant: "AssistantMessage",
274
+ user: "UserMessage",
275
+ tool: "ToolMessage",
276
+ activity: "ActivityMessage",
277
+ reasoning: "ReasoningMessage"
278
+ }
279
+ },
280
+ MessagesSnapshotEvent: {
281
+ optional: [
282
+ "timestamp",
283
+ "rawEvent",
284
+ "metadata"
285
+ ],
286
+ fields: { messages: { array: "Message" } }
287
+ },
288
+ ActivitySnapshotEvent: {
289
+ optional: [
290
+ "timestamp",
291
+ "rawEvent",
292
+ "metadata",
293
+ "subagentRunId",
294
+ "replace"
295
+ ],
296
+ fields: {}
297
+ },
298
+ ActivityDeltaEvent: {
299
+ optional: [
300
+ "timestamp",
301
+ "rawEvent",
302
+ "metadata",
303
+ "subagentRunId"
304
+ ],
305
+ fields: { patch: { array: "JsonPatchOperation" } }
306
+ },
307
+ RawEvent: {
308
+ optional: [
309
+ "timestamp",
310
+ "rawEvent",
311
+ "metadata",
312
+ "subagentRunId",
313
+ "source"
314
+ ],
315
+ fields: {}
316
+ },
317
+ CustomEvent: {
318
+ optional: [
319
+ "timestamp",
320
+ "rawEvent",
321
+ "metadata",
322
+ "subagentRunId"
323
+ ],
324
+ fields: {}
325
+ },
326
+ Tool: {
327
+ optional: ["parameters", "metadata"],
328
+ fields: {}
329
+ },
330
+ Context: {
331
+ optional: [],
332
+ fields: {}
333
+ },
334
+ ResumeEntry: {
335
+ optional: ["payload", "metadata"],
336
+ fields: {}
337
+ },
338
+ RunAgentInput: {
339
+ optional: [
340
+ "protocolVersion",
341
+ "parentRunId",
342
+ "state",
343
+ "tools",
344
+ "context",
345
+ "forwardedProps",
346
+ "resume"
347
+ ],
348
+ fields: {
349
+ messages: { array: "Message" },
350
+ tools: { array: "Tool" },
351
+ context: { array: "Context" },
352
+ resume: { array: "ResumeEntry" }
353
+ }
354
+ },
355
+ RunStartedEvent: {
356
+ optional: [
357
+ "timestamp",
358
+ "rawEvent",
359
+ "metadata",
360
+ "protocolVersion",
361
+ "parentRunId",
362
+ "input"
363
+ ],
364
+ fields: { input: "RunAgentInput" }
365
+ },
366
+ RunFinishedSuccessOutcome: {
367
+ optional: ["pendingToolCallIds"],
368
+ fields: {}
369
+ },
370
+ Interrupt: {
371
+ optional: [
372
+ "subagentRunId",
373
+ "message",
374
+ "toolCallId",
375
+ "responseSchema",
376
+ "expiresAt",
377
+ "metadata"
378
+ ],
379
+ fields: {}
380
+ },
381
+ RunFinishedInterruptOutcome: {
382
+ optional: [],
383
+ fields: { interrupts: { array: "Interrupt" } }
384
+ },
385
+ RunFinishedCancelledOutcome: {
386
+ optional: [],
387
+ fields: {}
388
+ },
389
+ RunFinishedOutcome: {
390
+ discriminator: "type",
391
+ variants: {
392
+ success: "RunFinishedSuccessOutcome",
393
+ interrupt: "RunFinishedInterruptOutcome",
394
+ cancelled: "RunFinishedCancelledOutcome"
395
+ }
396
+ },
397
+ TokenUsage: {
398
+ optional: [
399
+ "provider",
400
+ "model",
401
+ "inputTokens",
402
+ "outputTokens",
403
+ "totalTokens",
404
+ "reasoningTokens",
405
+ "cachedInputTokens",
406
+ "cacheWriteInputTokens"
407
+ ],
408
+ fields: {}
409
+ },
410
+ RunFinishedEvent: {
411
+ optional: [
412
+ "timestamp",
413
+ "rawEvent",
414
+ "metadata",
415
+ "result",
416
+ "outcome",
417
+ "usage"
418
+ ],
419
+ fields: {
420
+ outcome: "RunFinishedOutcome",
421
+ usage: { array: "TokenUsage" }
422
+ }
423
+ },
424
+ RunErrorEvent: {
425
+ optional: [
426
+ "timestamp",
427
+ "rawEvent",
428
+ "metadata",
429
+ "code",
430
+ "usage"
431
+ ],
432
+ fields: { usage: { array: "TokenUsage" } }
433
+ },
434
+ StepStartedEvent: {
435
+ optional: [
436
+ "timestamp",
437
+ "rawEvent",
438
+ "metadata",
439
+ "subagentRunId"
440
+ ],
441
+ fields: {}
442
+ },
443
+ StepFinishedEvent: {
444
+ optional: [
445
+ "timestamp",
446
+ "rawEvent",
447
+ "metadata",
448
+ "subagentRunId"
449
+ ],
450
+ fields: {}
451
+ },
452
+ ReasoningStartEvent: {
453
+ optional: [
454
+ "timestamp",
455
+ "rawEvent",
456
+ "metadata",
457
+ "subagentRunId"
458
+ ],
459
+ fields: {}
460
+ },
461
+ ReasoningMessageStartEvent: {
462
+ optional: [
463
+ "timestamp",
464
+ "rawEvent",
465
+ "metadata",
466
+ "subagentRunId"
467
+ ],
468
+ fields: {}
469
+ },
470
+ ReasoningMessageContentEvent: {
471
+ optional: [
472
+ "timestamp",
473
+ "rawEvent",
474
+ "metadata",
475
+ "subagentRunId"
476
+ ],
477
+ fields: {}
478
+ },
479
+ ReasoningMessageEndEvent: {
480
+ optional: [
481
+ "timestamp",
482
+ "rawEvent",
483
+ "metadata",
484
+ "subagentRunId"
485
+ ],
486
+ fields: {}
487
+ },
488
+ ReasoningMessageChunkEvent: {
489
+ optional: [
490
+ "timestamp",
491
+ "rawEvent",
492
+ "metadata",
493
+ "subagentRunId",
494
+ "messageId",
495
+ "delta"
496
+ ],
497
+ fields: {}
498
+ },
499
+ ReasoningEndEvent: {
500
+ optional: [
501
+ "timestamp",
502
+ "rawEvent",
503
+ "metadata",
504
+ "subagentRunId"
505
+ ],
506
+ fields: {}
507
+ },
508
+ ReasoningEncryptedValueEvent: {
509
+ optional: [
510
+ "timestamp",
511
+ "rawEvent",
512
+ "metadata",
513
+ "subagentRunId"
514
+ ],
515
+ fields: {}
516
+ },
517
+ SubagentStartedEvent: {
518
+ optional: [
519
+ "timestamp",
520
+ "rawEvent",
521
+ "metadata",
522
+ "description",
523
+ "parentSubagentRunId",
524
+ "parentToolCallId",
525
+ "parentMessageId"
526
+ ],
527
+ fields: {}
528
+ },
529
+ SubagentFinishedSuccessOutcome: {
530
+ optional: [],
531
+ fields: {}
532
+ },
533
+ SubagentFinishedSuspendedOutcome: {
534
+ optional: ["interruptIds"],
535
+ fields: {}
536
+ },
537
+ SubagentFinishedOutcome: {
538
+ discriminator: "type",
539
+ variants: {
540
+ success: "SubagentFinishedSuccessOutcome",
541
+ suspended: "SubagentFinishedSuspendedOutcome"
542
+ }
543
+ },
544
+ SubagentFinishedEvent: {
545
+ optional: [
546
+ "timestamp",
547
+ "rawEvent",
548
+ "metadata",
549
+ "result",
550
+ "outcome"
551
+ ],
552
+ fields: { outcome: "SubagentFinishedOutcome" }
553
+ },
554
+ SubagentErrorEvent: {
555
+ optional: [
556
+ "timestamp",
557
+ "rawEvent",
558
+ "metadata",
559
+ "code"
560
+ ],
561
+ fields: {}
562
+ },
563
+ Event: {
564
+ discriminator: "type",
565
+ variants: {
566
+ TEXT_MESSAGE_START: "TextMessageStartEvent",
567
+ TEXT_MESSAGE_CONTENT: "TextMessageContentEvent",
568
+ TEXT_MESSAGE_END: "TextMessageEndEvent",
569
+ TEXT_MESSAGE_CHUNK: "TextMessageChunkEvent",
570
+ TOOL_CALL_START: "ToolCallStartEvent",
571
+ TOOL_CALL_ARGS: "ToolCallArgsEvent",
572
+ TOOL_CALL_END: "ToolCallEndEvent",
573
+ TOOL_CALL_CHUNK: "ToolCallChunkEvent",
574
+ TOOL_CALL_RESULT: "ToolCallResultEvent",
575
+ STATE_SNAPSHOT: "StateSnapshotEvent",
576
+ STATE_DELTA: "StateDeltaEvent",
577
+ MESSAGES_SNAPSHOT: "MessagesSnapshotEvent",
578
+ ACTIVITY_SNAPSHOT: "ActivitySnapshotEvent",
579
+ ACTIVITY_DELTA: "ActivityDeltaEvent",
580
+ RAW: "RawEvent",
581
+ CUSTOM: "CustomEvent",
582
+ RUN_STARTED: "RunStartedEvent",
583
+ RUN_FINISHED: "RunFinishedEvent",
584
+ RUN_ERROR: "RunErrorEvent",
585
+ STEP_STARTED: "StepStartedEvent",
586
+ STEP_FINISHED: "StepFinishedEvent",
587
+ REASONING_START: "ReasoningStartEvent",
588
+ REASONING_MESSAGE_START: "ReasoningMessageStartEvent",
589
+ REASONING_MESSAGE_CONTENT: "ReasoningMessageContentEvent",
590
+ REASONING_MESSAGE_END: "ReasoningMessageEndEvent",
591
+ REASONING_MESSAGE_CHUNK: "ReasoningMessageChunkEvent",
592
+ REASONING_END: "ReasoningEndEvent",
593
+ REASONING_ENCRYPTED_VALUE: "ReasoningEncryptedValueEvent",
594
+ SUBAGENT_STARTED: "SubagentStartedEvent",
595
+ SUBAGENT_FINISHED: "SubagentFinishedEvent",
596
+ SUBAGENT_ERROR: "SubagentErrorEvent"
597
+ }
598
+ },
599
+ SubagentInfo: {
600
+ optional: ["description"],
601
+ fields: {}
602
+ },
603
+ IdentityCapabilities: {
604
+ optional: [
605
+ "name",
606
+ "type",
607
+ "description",
608
+ "version",
609
+ "provider",
610
+ "documentationUrl",
611
+ "metadata"
612
+ ],
613
+ fields: {}
614
+ },
615
+ TransportCapabilities: {
616
+ optional: [
617
+ "streaming",
618
+ "websocket",
619
+ "httpBinary",
620
+ "pushNotifications",
621
+ "resumable"
622
+ ],
623
+ fields: {}
624
+ },
625
+ ToolsCapabilities: {
626
+ optional: [
627
+ "supported",
628
+ "items",
629
+ "parallelCalls",
630
+ "clientProvided"
631
+ ],
632
+ fields: { items: { array: "Tool" } }
633
+ },
634
+ OutputCapabilities: {
635
+ optional: ["structuredOutput", "supportedMimeTypes"],
636
+ fields: {}
637
+ },
638
+ StateCapabilities: {
639
+ optional: [
640
+ "snapshots",
641
+ "deltas",
642
+ "memory",
643
+ "persistentState"
644
+ ],
645
+ fields: {}
646
+ },
647
+ MultiAgentCapabilities: {
648
+ optional: [
649
+ "supported",
650
+ "delegation",
651
+ "handoffs",
652
+ "subagents"
653
+ ],
654
+ fields: { subagents: { array: "SubagentInfo" } }
655
+ },
656
+ ReasoningCapabilities: {
657
+ optional: [
658
+ "supported",
659
+ "streaming",
660
+ "encrypted"
661
+ ],
662
+ fields: {}
663
+ },
664
+ MultimodalInputCapabilities: {
665
+ optional: [
666
+ "image",
667
+ "audio",
668
+ "video",
669
+ "pdf",
670
+ "file"
671
+ ],
672
+ fields: {}
673
+ },
674
+ MultimodalOutputCapabilities: {
675
+ optional: ["image", "audio"],
676
+ fields: {}
677
+ },
678
+ MultimodalCapabilities: {
679
+ optional: ["input", "output"],
680
+ fields: {
681
+ input: "MultimodalInputCapabilities",
682
+ output: "MultimodalOutputCapabilities"
683
+ }
684
+ },
685
+ ExecutionCapabilities: {
686
+ optional: [
687
+ "codeExecution",
688
+ "sandboxed",
689
+ "maxIterations",
690
+ "maxExecutionTime"
691
+ ],
692
+ fields: {}
693
+ },
694
+ HumanInTheLoopCapabilities: {
695
+ optional: [
696
+ "supported",
697
+ "approvals",
698
+ "interventions",
699
+ "feedback",
700
+ "interrupts",
701
+ "approveWithEdits"
702
+ ],
703
+ fields: {}
704
+ },
705
+ AgentCapabilities: {
706
+ optional: [
707
+ "identity",
708
+ "transport",
709
+ "tools",
710
+ "output",
711
+ "state",
712
+ "multiAgent",
713
+ "reasoning",
714
+ "multimodal",
715
+ "execution",
716
+ "humanInTheLoop",
717
+ "custom"
718
+ ],
719
+ fields: {
720
+ identity: "IdentityCapabilities",
721
+ transport: "TransportCapabilities",
722
+ tools: "ToolsCapabilities",
723
+ output: "OutputCapabilities",
724
+ state: "StateCapabilities",
725
+ multiAgent: "MultiAgentCapabilities",
726
+ reasoning: "ReasoningCapabilities",
727
+ multimodal: "MultimodalCapabilities",
728
+ execution: "ExecutionCapabilities",
729
+ humanInTheLoop: "HumanInTheLoopCapabilities"
730
+ }
731
+ }
732
+ };
733
+ function omit(value, shape) {
734
+ if (typeof shape === "string") return omit(value, shapes[shape]);
735
+ if ("array" in shape) {
736
+ if (!Array.isArray(value)) return value;
737
+ const result = value.map((item) => omit(item, shape.array));
738
+ return result.every((item, index) => item === value[index]) ? value : result;
739
+ }
740
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return value;
741
+ const object = value;
742
+ if ("discriminator" in shape) {
743
+ const tag = object[shape.discriminator];
744
+ return typeof tag === "string" && Object.prototype.hasOwnProperty.call(shape.variants, tag) ? omit(value, shape.variants[tag]) : value;
745
+ }
746
+ let result = object;
747
+ for (const key of shape.optional) if (Object.prototype.hasOwnProperty.call(object, key) && object[key] === null) {
748
+ if (result === object) result = { ...object };
749
+ delete result[key];
750
+ }
751
+ for (const [key, child] of Object.entries(shape.fields)) {
752
+ if (!Object.prototype.hasOwnProperty.call(result, key)) continue;
753
+ const next = omit(result[key], child);
754
+ if (next !== result[key]) {
755
+ if (result === object) result = { ...object };
756
+ result[key] = next;
757
+ }
758
+ }
759
+ return result;
760
+ }
761
+ /**
762
+ * Omits whole optional null fields before transmission. Does not validate,
763
+ * mutate the input, or traverse arbitrary application JSON or unknown fields.
764
+ * Required null payloads and null values inside opaque data remain intact.
765
+ */
766
+ function omitOptionalNulls(value, root) {
767
+ return omit(value, root);
768
+ }
769
+
770
+ //#endregion
771
+ //#region src/compat.ts
772
+ var AGUIError = class extends Error {
773
+ constructor(message) {
774
+ super(message);
775
+ }
776
+ };
777
+ var AGUIConnectNotImplementedError = class extends AGUIError {
778
+ constructor() {
779
+ super("Connect not implemented. This method is not supported by the current agent.");
780
+ }
781
+ };
782
+
783
+ //#endregion
3
784
  //#region src/metadata.ts
4
785
  /**
5
786
  * The key reserved for AG-UI's own use inside a metadata object. Every other
@@ -24,32 +805,15 @@ const AGUI_METADATA_KEY = "ag-ui";
24
805
  * every value on every event, on the streaming hot path, to catch a mistake
25
806
  * (a function, a bigint) that already fails loudly at encode time.
26
807
  *
27
- * One consequence worth knowing: `z.record` drops an own `__proto__` key, which
28
- * is its prototype-pollution guard. Preserving it would need null-prototype
29
- * objects throughout parsing and protobuf conversion, handing every consumer
30
- * objects where `hasOwnProperty` throws — a real cost for a key that is
31
- * essentially only ever an attack probe. Python keeps it; TypeScript does not.
808
+ * The schema itself now lives in the generated source (MetadataSchema in
809
+ * src/generated/schemas.ts); this comment survives as the recorded reasoning.
32
810
  */
33
- const MetadataSchema = z.record(z.any());
34
811
  /**
35
- * How metadata is declared on events and messages.
36
- *
37
- * The object itself is absent or an object, never `null` — and parsing
38
- * enforces that invariant rather than coercing a `null` to absent.
39
- *
40
- * This is deliberately NOT the treatment `parentMessageId` and `outcome`
41
- * receive in `events.ts`. Those tolerate `null` because released producers
42
- * emitted it before the producer-side omission fix, and rejecting it would
43
- * break agents already in the wild. Metadata has no such history: it postdates
44
- * the fix that makes every official producer omit fields with no value, and no
45
- * released Python or .NET package has ever emitted `"metadata": null`. Adding
46
- * a tolerance here would grandfather in a fourth exception with nobody to
47
- * protect; enforcing from day one means there is never anything to retire.
48
- *
49
- * A `null` *value under a key* is meaningful data and is preserved. Only a
50
- * `null` in place of the whole object is a contract violation.
812
+ * How metadata is declared on events and messages: the object is absent or an
813
+ * object, never `null`. The validator pinning that invariant is
814
+ * `OptionalMetadataSchema`, which lives in src/schemas.ts along with every
815
+ * other runtime validator this package ships.
51
816
  */
52
- const OptionalMetadataSchema = MetadataSchema.optional();
53
817
  /**
54
818
  * Folds `incoming` metadata into `existing`, key by key, with the last write
55
819
  * winning.
@@ -76,712 +840,31 @@ function mergeMetadata(existing, incoming) {
76
840
  }
77
841
 
78
842
  //#endregion
79
- //#region src/types.ts
80
- const FunctionCallSchema = z.object({
81
- name: z.string(),
82
- arguments: z.string()
83
- });
84
- const ToolCallSchema = z.object({
85
- id: z.string(),
86
- type: z.literal("function"),
87
- function: FunctionCallSchema,
88
- encryptedValue: z.string().optional(),
89
- metadata: OptionalMetadataSchema
90
- });
91
- const BaseMessageSchema = z.object({
92
- id: z.string(),
93
- role: z.string(),
94
- content: z.string().optional(),
95
- name: z.string().optional(),
96
- encryptedValue: z.string().optional(),
97
- subagentRunId: z.string().optional(),
98
- metadata: OptionalMetadataSchema
99
- });
100
- const TextInputContentSchema = z.object({
101
- type: z.literal("text"),
102
- text: z.string()
103
- });
104
- const InputContentDataSourceSchema = z.object({
105
- type: z.literal("data"),
106
- value: z.string(),
107
- mimeType: z.string()
108
- });
109
- const InputContentUrlSourceSchema = z.object({
110
- type: z.literal("url"),
111
- value: z.string(),
112
- mimeType: z.string().optional()
113
- });
114
- const InputContentSourceSchema = z.discriminatedUnion("type", [InputContentDataSourceSchema, InputContentUrlSourceSchema]);
115
- const ImageInputContentSchema = z.object({
116
- type: z.literal("image"),
117
- source: InputContentSourceSchema,
118
- metadata: z.unknown().optional()
119
- });
120
- const AudioInputContentSchema = z.object({
121
- type: z.literal("audio"),
122
- source: InputContentSourceSchema,
123
- metadata: z.unknown().optional()
124
- });
125
- const VideoInputContentSchema = z.object({
126
- type: z.literal("video"),
127
- source: InputContentSourceSchema,
128
- metadata: z.unknown().optional()
129
- });
130
- const DocumentInputContentSchema = z.object({
131
- type: z.literal("document"),
132
- source: InputContentSourceSchema,
133
- metadata: z.unknown().optional()
134
- });
135
- const ImageInputPartSchema = ImageInputContentSchema;
136
- const AudioInputPartSchema = AudioInputContentSchema;
137
- const VideoInputPartSchema = VideoInputContentSchema;
138
- const DocumentInputPartSchema = DocumentInputContentSchema;
139
- const LegacyBinaryInputContentObjectSchema = z.object({
140
- type: z.literal("binary"),
141
- mimeType: z.string(),
142
- id: z.string().optional(),
143
- url: z.string().optional(),
144
- data: z.string().optional(),
145
- filename: z.string().optional()
146
- });
147
- const ensureBinaryPayload = (value, ctx) => {
148
- if (!value.id && !value.url && !value.data) ctx.addIssue({
149
- code: z.ZodIssueCode.custom,
150
- message: "BinaryInputContent requires at least one of id, url, or data.",
151
- path: ["id"]
152
- });
153
- };
154
- const BinaryInputContentSchema = LegacyBinaryInputContentObjectSchema.superRefine((value, ctx) => {
155
- ensureBinaryPayload(value, ctx);
156
- });
157
- const InputContentBaseSchema = z.discriminatedUnion("type", [
158
- TextInputContentSchema,
159
- ImageInputContentSchema,
160
- AudioInputContentSchema,
161
- VideoInputContentSchema,
162
- DocumentInputContentSchema,
163
- LegacyBinaryInputContentObjectSchema
164
- ]);
165
- const InputContentSchema = InputContentBaseSchema.superRefine((value, ctx) => {
166
- if (value.type === "binary") ensureBinaryPayload(value, ctx);
167
- });
168
- const DeveloperMessageSchema = BaseMessageSchema.extend({
169
- role: z.literal("developer"),
170
- content: z.string()
171
- });
172
- const SystemMessageSchema = BaseMessageSchema.extend({
173
- role: z.literal("system"),
174
- content: z.string()
175
- });
176
- const AssistantMessageSchema = BaseMessageSchema.extend({
177
- role: z.literal("assistant"),
178
- content: z.string().optional(),
179
- toolCalls: z.array(ToolCallSchema).optional()
180
- });
181
- const UserMessageSchema = BaseMessageSchema.extend({
182
- role: z.literal("user"),
183
- content: z.union([z.string(), z.array(InputContentSchema)])
184
- });
185
- const ToolMessageSchema = z.object({
186
- id: z.string(),
187
- content: z.string(),
188
- role: z.literal("tool"),
189
- toolCallId: z.string(),
190
- error: z.string().optional(),
191
- encryptedValue: z.string().optional(),
192
- subagentRunId: z.string().optional(),
193
- metadata: OptionalMetadataSchema
194
- });
195
- const ActivityMessageSchema = z.object({
196
- id: z.string(),
197
- role: z.literal("activity"),
198
- activityType: z.string(),
199
- content: z.record(z.any()),
200
- subagentRunId: z.string().optional(),
201
- metadata: OptionalMetadataSchema
202
- });
203
- const ReasoningMessageSchema = z.object({
204
- id: z.string(),
205
- role: z.literal("reasoning"),
206
- content: z.string(),
207
- encryptedValue: z.string().optional(),
208
- subagentRunId: z.string().optional(),
209
- metadata: OptionalMetadataSchema
210
- });
211
- const MessageSchema = z.discriminatedUnion("role", [
212
- DeveloperMessageSchema,
213
- SystemMessageSchema,
214
- AssistantMessageSchema,
215
- UserMessageSchema,
216
- ToolMessageSchema,
217
- ActivityMessageSchema,
218
- ReasoningMessageSchema
219
- ]);
220
- const RoleSchema = z.union([
221
- z.literal("developer"),
222
- z.literal("system"),
223
- z.literal("assistant"),
224
- z.literal("user"),
225
- z.literal("tool"),
226
- z.literal("activity"),
227
- z.literal("reasoning")
228
- ]);
229
- const ContextSchema = z.object({
230
- description: z.string(),
231
- value: z.string()
232
- });
233
- const ToolSchema = z.object({
234
- name: z.string(),
235
- description: z.string(),
236
- parameters: z.any(),
237
- metadata: z.record(z.any()).optional()
238
- });
239
- const InterruptSchema = z.object({
240
- id: z.string(),
241
- reason: z.string(),
242
- message: z.string().optional(),
243
- toolCallId: z.string().optional(),
244
- responseSchema: z.record(z.any()).optional(),
245
- expiresAt: z.string().optional(),
246
- metadata: z.record(z.any()).optional(),
247
- subagentRunId: z.string().optional()
248
- });
249
- const ResumeEntrySchema = z.object({
250
- interruptId: z.string(),
251
- status: z.enum(["resolved", "cancelled"]),
252
- payload: z.any().optional(),
253
- metadata: OptionalMetadataSchema
254
- });
255
- const RunAgentInputSchema = z.object({
256
- threadId: z.string(),
257
- runId: z.string(),
258
- parentRunId: z.string().optional(),
259
- state: z.any().transform((v) => v ?? void 0),
260
- messages: z.array(MessageSchema),
261
- tools: z.array(ToolSchema),
262
- context: z.array(ContextSchema),
263
- forwardedProps: z.any(),
264
- resume: z.array(ResumeEntrySchema).optional()
265
- });
266
- const StateSchema = z.any();
267
- var AGUIError = class extends Error {
268
- constructor(message) {
269
- super(message);
270
- }
271
- };
272
- var AGUIConnectNotImplementedError = class extends AGUIError {
273
- constructor() {
274
- super("Connect not implemented. This method is not supported by the current agent.");
275
- }
276
- };
277
-
278
- //#endregion
279
- //#region src/capabilities.ts
280
- /** Describes a sub-agent that can be invoked by a parent agent. */
281
- const SubAgentInfoSchema = z.object({
282
- name: z.string(),
283
- description: z.string().optional()
284
- });
285
- /**
286
- * Basic metadata about the agent. Useful for discovery UIs, agent marketplaces,
287
- * and debugging. Set these when you want clients to display agent information
288
- * or when multiple agents are available and users need to pick one.
289
- */
290
- const IdentityCapabilitiesSchema = z.object({
291
- name: z.string().optional(),
292
- type: z.string().optional(),
293
- description: z.string().optional(),
294
- version: z.string().optional(),
295
- provider: z.string().optional(),
296
- documentationUrl: z.string().optional(),
297
- metadata: z.record(z.unknown()).optional()
298
- });
299
- /**
300
- * Declares which transport mechanisms the agent supports. Clients use this
301
- * to pick the best connection strategy. Only set flags to `true` for transports
302
- * your agent actually handles — omit or set `false` for unsupported ones.
303
- */
304
- const TransportCapabilitiesSchema = z.object({
305
- streaming: z.boolean().optional(),
306
- websocket: z.boolean().optional(),
307
- httpBinary: z.boolean().optional(),
308
- pushNotifications: z.boolean().optional(),
309
- resumable: z.boolean().optional()
310
- });
311
- /**
312
- * Tool calling capabilities. Distinguishes between tools the agent itself provides
313
- * (listed in `items`) and tools the client passes at runtime via `RunAgentInput.tools`.
314
- * Enable this when your agent can call functions, search the web, execute code, etc.
315
- */
316
- const ToolsCapabilitiesSchema = z.object({
317
- supported: z.boolean().optional(),
318
- items: z.array(ToolSchema).optional(),
319
- parallelCalls: z.boolean().optional(),
320
- clientProvided: z.boolean().optional()
321
- });
322
- /**
323
- * Output format support. Enable `structuredOutput` when your agent can return
324
- * responses conforming to a JSON schema, which is useful for programmatic consumption.
325
- */
326
- const OutputCapabilitiesSchema = z.object({
327
- structuredOutput: z.boolean().optional(),
328
- supportedMimeTypes: z.array(z.string()).optional()
329
- });
330
- /**
331
- * State and memory management capabilities. These tell the client how the agent
332
- * handles shared state and whether conversation context persists across runs.
333
- */
334
- const StateCapabilitiesSchema = z.object({
335
- snapshots: z.boolean().optional(),
336
- deltas: z.boolean().optional(),
337
- memory: z.boolean().optional(),
338
- persistentState: z.boolean().optional()
339
- });
340
- /**
341
- * Multi-agent coordination capabilities. Enable these when your agent can
342
- * orchestrate or hand off work to other agents.
343
- */
344
- const MultiAgentCapabilitiesSchema = z.object({
345
- supported: z.boolean().optional(),
346
- delegation: z.boolean().optional(),
347
- handoffs: z.boolean().optional(),
348
- subAgents: z.array(SubAgentInfoSchema).optional()
349
- });
350
- /**
351
- * Reasoning and thinking capabilities. Enable these when your agent exposes its
352
- * internal thought process (e.g., chain-of-thought, extended thinking).
353
- */
354
- const ReasoningCapabilitiesSchema = z.object({
355
- supported: z.boolean().optional(),
356
- streaming: z.boolean().optional(),
357
- encrypted: z.boolean().optional()
358
- });
359
- /**
360
- * Modalities the agent can accept as input. Clients use this to show/hide
361
- * file upload buttons, audio recorders, image pickers, etc.
362
- */
363
- const MultimodalInputCapabilitiesSchema = z.object({
364
- image: z.boolean().optional(),
365
- audio: z.boolean().optional(),
366
- video: z.boolean().optional(),
367
- pdf: z.boolean().optional(),
368
- file: z.boolean().optional()
369
- });
370
- /**
371
- * Modalities the agent can produce as output. Clients use this to anticipate
372
- * rich content in the agent's response.
373
- */
374
- const MultimodalOutputCapabilitiesSchema = z.object({
375
- image: z.boolean().optional(),
376
- audio: z.boolean().optional()
377
- });
378
- /**
379
- * Multimodal input and output support. Organized into `input` and `output`
380
- * sub-objects so clients can independently query what the agent accepts
381
- * versus what it produces.
382
- */
383
- const MultimodalCapabilitiesSchema = z.object({
384
- input: MultimodalInputCapabilitiesSchema.optional(),
385
- output: MultimodalOutputCapabilitiesSchema.optional()
386
- });
387
- /**
388
- * Execution control and limits. Declare these so clients can set expectations
389
- * about how long or how many steps an agent run might take.
390
- */
391
- const ExecutionCapabilitiesSchema = z.object({
392
- codeExecution: z.boolean().optional(),
393
- sandboxed: z.boolean().optional(),
394
- maxIterations: z.number().optional(),
395
- maxExecutionTime: z.number().optional()
396
- });
397
- /**
398
- * Human-in-the-loop interaction support. Enable these when your agent can pause
399
- * execution to request human input, approval, or feedback before continuing.
400
- */
401
- const HumanInTheLoopCapabilitiesSchema = z.object({
402
- supported: z.boolean().optional(),
403
- approvals: z.boolean().optional(),
404
- interventions: z.boolean().optional(),
405
- feedback: z.boolean().optional(),
406
- interrupts: z.boolean().optional(),
407
- approveWithEdits: z.boolean().optional()
408
- });
409
- /**
410
- * A typed, categorized snapshot of an agent's current capabilities.
411
- * Returned by `getCapabilities()` on `AbstractAgent`.
412
- *
413
- * All fields are optional — agents only declare what they support.
414
- * Omitted fields mean the capability is not declared (unknown), not that
415
- * it's unsupported.
416
- *
417
- * The `custom` field is an escape hatch for integration-specific capabilities
418
- * that don't fit into the standard categories.
419
- */
420
- const AgentCapabilitiesSchema = z.object({
421
- identity: IdentityCapabilitiesSchema.optional(),
422
- transport: TransportCapabilitiesSchema.optional(),
423
- tools: ToolsCapabilitiesSchema.optional(),
424
- output: OutputCapabilitiesSchema.optional(),
425
- state: StateCapabilitiesSchema.optional(),
426
- multiAgent: MultiAgentCapabilitiesSchema.optional(),
427
- reasoning: ReasoningCapabilitiesSchema.optional(),
428
- multimodal: MultimodalCapabilitiesSchema.optional(),
429
- execution: ExecutionCapabilitiesSchema.optional(),
430
- humanInTheLoop: HumanInTheLoopCapabilitiesSchema.optional(),
431
- custom: z.record(z.unknown()).optional()
432
- });
433
-
434
- //#endregion
435
- //#region src/events.ts
436
- const TextMessageRoleSchema = z.union([
437
- z.literal("developer"),
438
- z.literal("system"),
439
- z.literal("assistant"),
440
- z.literal("user")
441
- ]);
442
- let EventType = /* @__PURE__ */ function(EventType) {
443
- EventType["TEXT_MESSAGE_START"] = "TEXT_MESSAGE_START";
444
- EventType["TEXT_MESSAGE_CONTENT"] = "TEXT_MESSAGE_CONTENT";
445
- EventType["TEXT_MESSAGE_END"] = "TEXT_MESSAGE_END";
446
- EventType["TEXT_MESSAGE_CHUNK"] = "TEXT_MESSAGE_CHUNK";
447
- EventType["TOOL_CALL_START"] = "TOOL_CALL_START";
448
- EventType["TOOL_CALL_ARGS"] = "TOOL_CALL_ARGS";
449
- EventType["TOOL_CALL_END"] = "TOOL_CALL_END";
450
- EventType["TOOL_CALL_CHUNK"] = "TOOL_CALL_CHUNK";
451
- EventType["TOOL_CALL_RESULT"] = "TOOL_CALL_RESULT";
452
- /**
453
- * @deprecated Use REASONING_START instead. Will be removed in 1.0.0.
454
- */
455
- EventType["THINKING_START"] = "THINKING_START";
456
- /**
457
- * @deprecated Use REASONING_END instead. Will be removed in 1.0.0.
458
- */
459
- EventType["THINKING_END"] = "THINKING_END";
460
- /**
461
- * @deprecated Use REASONING_MESSAGE_START instead. Will be removed in 1.0.0.
462
- */
463
- EventType["THINKING_TEXT_MESSAGE_START"] = "THINKING_TEXT_MESSAGE_START";
464
- /**
465
- * @deprecated Use REASONING_MESSAGE_CONTENT instead. Will be removed in 1.0.0.
466
- */
467
- EventType["THINKING_TEXT_MESSAGE_CONTENT"] = "THINKING_TEXT_MESSAGE_CONTENT";
468
- /**
469
- * @deprecated Use REASONING_MESSAGE_END instead. Will be removed in 1.0.0.
470
- */
471
- EventType["THINKING_TEXT_MESSAGE_END"] = "THINKING_TEXT_MESSAGE_END";
472
- EventType["STATE_SNAPSHOT"] = "STATE_SNAPSHOT";
473
- EventType["STATE_DELTA"] = "STATE_DELTA";
474
- EventType["MESSAGES_SNAPSHOT"] = "MESSAGES_SNAPSHOT";
475
- EventType["ACTIVITY_SNAPSHOT"] = "ACTIVITY_SNAPSHOT";
476
- EventType["ACTIVITY_DELTA"] = "ACTIVITY_DELTA";
477
- EventType["RAW"] = "RAW";
478
- EventType["CUSTOM"] = "CUSTOM";
479
- EventType["RUN_STARTED"] = "RUN_STARTED";
480
- EventType["RUN_FINISHED"] = "RUN_FINISHED";
481
- EventType["RUN_ERROR"] = "RUN_ERROR";
482
- EventType["STEP_STARTED"] = "STEP_STARTED";
483
- EventType["STEP_FINISHED"] = "STEP_FINISHED";
484
- EventType["REASONING_START"] = "REASONING_START";
485
- EventType["REASONING_MESSAGE_START"] = "REASONING_MESSAGE_START";
486
- EventType["REASONING_MESSAGE_CONTENT"] = "REASONING_MESSAGE_CONTENT";
487
- EventType["REASONING_MESSAGE_END"] = "REASONING_MESSAGE_END";
488
- EventType["REASONING_MESSAGE_CHUNK"] = "REASONING_MESSAGE_CHUNK";
489
- EventType["REASONING_END"] = "REASONING_END";
490
- EventType["REASONING_ENCRYPTED_VALUE"] = "REASONING_ENCRYPTED_VALUE";
491
- EventType["SUBAGENT_STARTED"] = "SUBAGENT_STARTED";
492
- EventType["SUBAGENT_FINISHED"] = "SUBAGENT_FINISHED";
493
- EventType["SUBAGENT_ERROR"] = "SUBAGENT_ERROR";
494
- return EventType;
495
- }({});
496
- const BaseEventSchema = z.object({
497
- type: z.nativeEnum(EventType),
498
- timestamp: z.number().optional(),
499
- rawEvent: z.any().optional(),
500
- metadata: OptionalMetadataSchema
501
- }).passthrough();
502
- const TextMessageStartEventSchema = BaseEventSchema.extend({
503
- type: z.literal(EventType.TEXT_MESSAGE_START),
504
- messageId: z.string(),
505
- role: TextMessageRoleSchema.default("assistant"),
506
- name: z.string().optional(),
507
- subagentRunId: z.string().optional()
508
- });
509
- const TextMessageContentEventSchema = BaseEventSchema.extend({
510
- type: z.literal(EventType.TEXT_MESSAGE_CONTENT),
511
- messageId: z.string(),
512
- delta: z.string(),
513
- subagentRunId: z.string().optional()
514
- });
515
- const TextMessageEndEventSchema = BaseEventSchema.extend({
516
- type: z.literal(EventType.TEXT_MESSAGE_END),
517
- messageId: z.string(),
518
- subagentRunId: z.string().optional()
519
- });
520
- const TextMessageChunkEventSchema = BaseEventSchema.extend({
521
- type: z.literal(EventType.TEXT_MESSAGE_CHUNK),
522
- messageId: z.string().optional(),
523
- role: TextMessageRoleSchema.optional(),
524
- delta: z.string().optional(),
525
- name: z.string().optional(),
526
- subagentRunId: z.string().optional()
527
- });
528
- /**
529
- * @deprecated Use ReasoningMessageStartEventSchema instead. Will be removed in 1.0.0.
530
- */
531
- const ThinkingTextMessageStartEventSchema = BaseEventSchema.extend({ type: z.literal(EventType.THINKING_TEXT_MESSAGE_START) });
532
- /**
533
- * @deprecated Use ReasoningMessageContentEventSchema instead. Will be removed in 1.0.0.
534
- */
535
- const ThinkingTextMessageContentEventSchema = TextMessageContentEventSchema.omit({
536
- messageId: true,
537
- type: true,
538
- subagentRunId: true
539
- }).extend({ type: z.literal(EventType.THINKING_TEXT_MESSAGE_CONTENT) });
540
- /**
541
- * @deprecated Use ReasoningMessageEndEventSchema instead. Will be removed in 1.0.0.
542
- */
543
- const ThinkingTextMessageEndEventSchema = BaseEventSchema.extend({ type: z.literal(EventType.THINKING_TEXT_MESSAGE_END) });
544
- const ToolCallStartEventSchema = BaseEventSchema.extend({
545
- type: z.literal(EventType.TOOL_CALL_START),
546
- toolCallId: z.string(),
547
- toolCallName: z.string(),
548
- parentMessageId: z.string().nullable().optional().transform((v) => v ?? void 0),
549
- subagentRunId: z.string().optional()
550
- });
551
- const ToolCallArgsEventSchema = BaseEventSchema.extend({
552
- type: z.literal(EventType.TOOL_CALL_ARGS),
553
- toolCallId: z.string(),
554
- delta: z.string(),
555
- subagentRunId: z.string().optional()
556
- });
557
- const ToolCallEndEventSchema = BaseEventSchema.extend({
558
- type: z.literal(EventType.TOOL_CALL_END),
559
- toolCallId: z.string(),
560
- subagentRunId: z.string().optional()
561
- });
562
- const ToolCallResultEventSchema = BaseEventSchema.extend({
563
- messageId: z.string(),
564
- type: z.literal(EventType.TOOL_CALL_RESULT),
565
- toolCallId: z.string(),
566
- content: z.string(),
567
- role: z.literal("tool").optional(),
568
- subagentRunId: z.string().optional()
569
- });
570
- const ToolCallChunkEventSchema = BaseEventSchema.extend({
571
- type: z.literal(EventType.TOOL_CALL_CHUNK),
572
- toolCallId: z.string().optional(),
573
- toolCallName: z.string().optional(),
574
- parentMessageId: z.string().nullable().optional().transform((v) => v ?? void 0),
575
- delta: z.string().optional(),
576
- subagentRunId: z.string().optional()
577
- });
578
- /**
579
- * @deprecated Use ReasoningStartEventSchema instead. Will be removed in 1.0.0.
580
- */
581
- const ThinkingStartEventSchema = BaseEventSchema.extend({
582
- type: z.literal(EventType.THINKING_START),
583
- title: z.string().optional()
584
- });
843
+ //#region src/token-usage.ts
844
+ /** The AG-UI names of the six token counts, in the order an entry lists them. */
845
+ const COUNT_KEYS = [
846
+ "inputTokens",
847
+ "outputTokens",
848
+ "totalTokens",
849
+ "reasoningTokens",
850
+ "cachedInputTokens",
851
+ "cacheWriteInputTokens"
852
+ ];
585
853
  /**
586
- * @deprecated Use ReasoningEndEventSchema instead. Will be removed in 1.0.0.
854
+ * The count keys already warned about, so the diagnostic below fires once per
855
+ * process per key rather than once per event. A provider that hands over a
856
+ * string count hands one over on every call, and a per-call warning would bury
857
+ * the stream it is meant to annotate.
587
858
  */
588
- const ThinkingEndEventSchema = BaseEventSchema.extend({ type: z.literal(EventType.THINKING_END) });
589
- const StateSnapshotEventSchema = BaseEventSchema.extend({
590
- type: z.literal(EventType.STATE_SNAPSHOT),
591
- snapshot: StateSchema,
592
- subagentRunId: z.string().optional()
593
- });
594
- const StateDeltaEventSchema = BaseEventSchema.extend({
595
- type: z.literal(EventType.STATE_DELTA),
596
- delta: z.array(z.any()),
597
- subagentRunId: z.string().optional()
598
- });
599
- const MessagesSnapshotEventSchema = BaseEventSchema.extend({
600
- type: z.literal(EventType.MESSAGES_SNAPSHOT),
601
- messages: z.array(MessageSchema)
602
- });
603
- const ActivitySnapshotEventSchema = BaseEventSchema.extend({
604
- type: z.literal(EventType.ACTIVITY_SNAPSHOT),
605
- messageId: z.string(),
606
- activityType: z.string(),
607
- content: z.record(z.any()),
608
- replace: z.boolean().optional().default(true),
609
- subagentRunId: z.string().optional()
610
- });
611
- const ActivityDeltaEventSchema = BaseEventSchema.extend({
612
- type: z.literal(EventType.ACTIVITY_DELTA),
613
- messageId: z.string(),
614
- activityType: z.string(),
615
- patch: z.array(z.any()),
616
- subagentRunId: z.string().optional()
617
- });
618
- const RawEventSchema = BaseEventSchema.extend({
619
- type: z.literal(EventType.RAW),
620
- event: z.any(),
621
- source: z.string().optional(),
622
- subagentRunId: z.string().optional()
623
- });
624
- const CustomEventSchema = BaseEventSchema.extend({
625
- type: z.literal(EventType.CUSTOM),
626
- name: z.string(),
627
- value: z.any(),
628
- subagentRunId: z.string().optional()
629
- });
630
- const RunStartedEventSchema = BaseEventSchema.extend({
631
- type: z.literal(EventType.RUN_STARTED),
632
- threadId: z.string(),
633
- runId: z.string(),
634
- parentRunId: z.string().optional(),
635
- input: RunAgentInputSchema.optional()
636
- });
637
- const RunFinishedSuccessOutcomeSchema = z.object({ type: z.literal("success") }).strict();
638
- const RunFinishedInterruptOutcomeSchema = z.object({
639
- type: z.literal("interrupt"),
640
- interrupts: z.array(InterruptSchema).min(1)
641
- }).strict();
642
- const RunFinishedOutcomeSchema = z.discriminatedUnion("type", [RunFinishedSuccessOutcomeSchema, RunFinishedInterruptOutcomeSchema]);
643
- const TokenUsageSchema = z.object({
644
- provider: z.string().optional(),
645
- model: z.string().optional(),
646
- inputTokens: z.number().int().nonnegative().optional(),
647
- outputTokens: z.number().int().nonnegative().optional(),
648
- totalTokens: z.number().int().nonnegative().optional(),
649
- reasoningTokens: z.number().int().nonnegative().optional(),
650
- cachedInputTokens: z.number().int().nonnegative().optional()
651
- });
652
- const RunFinishedEventSchema = BaseEventSchema.extend({
653
- type: z.literal(EventType.RUN_FINISHED),
654
- threadId: z.string(),
655
- runId: z.string(),
656
- result: z.any().optional(),
657
- outcome: RunFinishedOutcomeSchema.nullable().optional().transform((v) => v ?? void 0),
658
- usage: z.array(TokenUsageSchema).optional()
659
- });
660
- const RunErrorEventSchema = BaseEventSchema.extend({
661
- type: z.literal(EventType.RUN_ERROR),
662
- message: z.string(),
663
- code: z.string().optional(),
664
- usage: z.array(TokenUsageSchema).optional()
665
- });
666
- const StepStartedEventSchema = BaseEventSchema.extend({
667
- type: z.literal(EventType.STEP_STARTED),
668
- stepName: z.string(),
669
- subagentRunId: z.string().optional()
670
- });
671
- const StepFinishedEventSchema = BaseEventSchema.extend({
672
- type: z.literal(EventType.STEP_FINISHED),
673
- stepName: z.string(),
674
- subagentRunId: z.string().optional()
675
- });
676
- const ReasoningEncryptedValueSubtypeSchema = z.union([z.literal("tool-call"), z.literal("message")]);
677
- const ReasoningStartEventSchema = BaseEventSchema.extend({
678
- type: z.literal(EventType.REASONING_START),
679
- messageId: z.string(),
680
- subagentRunId: z.string().optional()
681
- });
682
- const ReasoningMessageStartEventSchema = BaseEventSchema.extend({
683
- type: z.literal(EventType.REASONING_MESSAGE_START),
684
- messageId: z.string(),
685
- role: z.literal("reasoning"),
686
- subagentRunId: z.string().optional()
687
- });
688
- const ReasoningMessageContentEventSchema = BaseEventSchema.extend({
689
- type: z.literal(EventType.REASONING_MESSAGE_CONTENT),
690
- messageId: z.string(),
691
- delta: z.string(),
692
- subagentRunId: z.string().optional()
693
- });
694
- const ReasoningMessageEndEventSchema = BaseEventSchema.extend({
695
- type: z.literal(EventType.REASONING_MESSAGE_END),
696
- messageId: z.string(),
697
- subagentRunId: z.string().optional()
698
- });
699
- const ReasoningMessageChunkEventSchema = BaseEventSchema.extend({
700
- type: z.literal(EventType.REASONING_MESSAGE_CHUNK),
701
- messageId: z.string().optional(),
702
- delta: z.string().optional(),
703
- subagentRunId: z.string().optional()
704
- });
705
- const ReasoningEndEventSchema = BaseEventSchema.extend({
706
- type: z.literal(EventType.REASONING_END),
707
- messageId: z.string(),
708
- subagentRunId: z.string().optional()
709
- });
710
- const ReasoningEncryptedValueEventSchema = BaseEventSchema.extend({
711
- type: z.literal(EventType.REASONING_ENCRYPTED_VALUE),
712
- subtype: ReasoningEncryptedValueSubtypeSchema,
713
- entityId: z.string(),
714
- encryptedValue: z.string(),
715
- subagentRunId: z.string().optional()
716
- });
717
- const SubagentStartedEventSchema = BaseEventSchema.extend({
718
- type: z.literal(EventType.SUBAGENT_STARTED),
719
- subagentRunId: z.string(),
720
- name: z.string(),
721
- description: z.string().optional(),
722
- parentSubagentRunId: z.string().optional(),
723
- parentToolCallId: z.string().optional(),
724
- parentMessageId: z.string().optional()
725
- });
726
- const SubagentFinishedSuccessOutcomeSchema = z.object({ type: z.literal("success") }).strict();
727
- const SubagentFinishedSuspendedOutcomeSchema = z.object({
728
- type: z.literal("suspended"),
729
- interruptIds: z.array(z.string()).optional()
730
- }).strict();
731
- const SubagentFinishedOutcomeSchema = z.discriminatedUnion("type", [SubagentFinishedSuccessOutcomeSchema, SubagentFinishedSuspendedOutcomeSchema]);
732
- const SubagentFinishedEventSchema = BaseEventSchema.extend({
733
- type: z.literal(EventType.SUBAGENT_FINISHED),
734
- subagentRunId: z.string(),
735
- result: z.any().optional(),
736
- outcome: SubagentFinishedOutcomeSchema.optional()
737
- });
738
- const SubagentErrorEventSchema = BaseEventSchema.extend({
739
- type: z.literal(EventType.SUBAGENT_ERROR),
740
- subagentRunId: z.string(),
741
- message: z.string(),
742
- code: z.string().optional()
743
- });
744
- const EventSchemas = z.discriminatedUnion("type", [
745
- TextMessageStartEventSchema,
746
- TextMessageContentEventSchema,
747
- TextMessageEndEventSchema,
748
- TextMessageChunkEventSchema,
749
- ThinkingStartEventSchema,
750
- ThinkingEndEventSchema,
751
- ThinkingTextMessageStartEventSchema,
752
- ThinkingTextMessageContentEventSchema,
753
- ThinkingTextMessageEndEventSchema,
754
- ToolCallStartEventSchema,
755
- ToolCallArgsEventSchema,
756
- ToolCallEndEventSchema,
757
- ToolCallChunkEventSchema,
758
- ToolCallResultEventSchema,
759
- StateSnapshotEventSchema,
760
- StateDeltaEventSchema,
761
- MessagesSnapshotEventSchema,
762
- ActivitySnapshotEventSchema,
763
- ActivityDeltaEventSchema,
764
- RawEventSchema,
765
- CustomEventSchema,
766
- RunStartedEventSchema,
767
- RunFinishedEventSchema,
768
- RunErrorEventSchema,
769
- StepStartedEventSchema,
770
- StepFinishedEventSchema,
771
- ReasoningStartEventSchema,
772
- ReasoningMessageStartEventSchema,
773
- ReasoningMessageContentEventSchema,
774
- ReasoningMessageEndEventSchema,
775
- ReasoningMessageChunkEventSchema,
776
- ReasoningEndEventSchema,
777
- ReasoningEncryptedValueEventSchema,
778
- SubagentStartedEventSchema,
779
- SubagentFinishedEventSchema,
780
- SubagentErrorEventSchema
781
- ]);
782
-
783
- //#endregion
784
- //#region src/token-usage.ts
859
+ const warnedCountKeys = /* @__PURE__ */ new Set();
860
+ /** What the value WAS, said in a way that points at the provider's bug. */
861
+ const describeRejected = (v) => {
862
+ if (v === null) return "null";
863
+ if (typeof v === "string") return `${JSON.stringify(v)} (a string)`;
864
+ if (typeof v === "number") return `${String(v)} (a non-finite number)`;
865
+ if (typeof v === "object") return `an object`;
866
+ return `${String(v)} (a ${typeof v})`;
867
+ };
785
868
  /**
786
869
  * Accept a value only if it is a real, finite number.
787
870
  *
@@ -790,8 +873,28 @@ const EventSchemas = z.discriminatedUnion("type", [
790
873
  * not reach the wire: consumers validate every incoming event and throw on
791
874
  * failure, so one malformed count would fail an otherwise-successful run at its
792
875
  * final event — costing the user the answer, not just the token count.
876
+ *
877
+ * Dropping it is right; dropping it in silence is not. The usage this run
878
+ * reports is then simply wrong, with nothing anywhere saying which count went
879
+ * missing or why, so a present-but-unusable value is named once per key.
880
+ *
881
+ * `undefined` and `NaN` are exempt because they are not defects: they are how a
882
+ * provider spells "did not report this count". `undefined` covers both shapes —
883
+ * an absent key in LangChain's `usage_metadata`, an explicit `undefined` in
884
+ * AI-SDK's `LanguageModelUsage` — and AI-SDK uses `NaN` for the same thing,
885
+ * which is why its mapper's docstring says so. Warning on those would fire on
886
+ * ordinary traffic and train the reader to ignore the message.
887
+ *
888
+ * `key` is the AG-UI count name the value was headed for, not the vendor's
889
+ * spelling of it, so one message reads the same whichever mapper produced it.
793
890
  */
794
- const num = (v) => typeof v === "number" && Number.isFinite(v) ? v : void 0;
891
+ const num = (v, key) => {
892
+ if (typeof v === "number" && Number.isFinite(v)) return v;
893
+ if (!(v === void 0 || typeof v === "number" && Number.isNaN(v)) && !warnedCountKeys.has(key)) {
894
+ warnedCountKeys.add(key);
895
+ console.warn(`[ag-ui] usage.${key} was ${describeRejected(v)}, not a number — omitted from this run's usage. Reported once per key.`);
896
+ }
897
+ };
795
898
  /**
796
899
  * Read a property from a value of unknown shape, yielding `undefined` for
797
900
  * anything that is not an object. Lets the mappers take `unknown` rather than
@@ -799,13 +902,6 @@ const num = (v) => typeof v === "number" && Number.isFinite(v) ? v : void 0;
799
902
  * rather than assumed.
800
903
  */
801
904
  const prop = (v, key) => typeof v === "object" && v !== null ? v[key] : void 0;
802
- const COUNT_KEYS = [
803
- "inputTokens",
804
- "outputTokens",
805
- "totalTokens",
806
- "reasoningTokens",
807
- "cachedInputTokens"
808
- ];
809
905
  /**
810
906
  * Build a {@link TokenUsage} from already-guarded counts, or `undefined` when no
811
907
  * count survived. Returning `undefined` rather than a labels-only entry keeps
@@ -827,43 +923,57 @@ function buildEntry(counts, { provider, model }) {
827
923
  * Map a LangChain-family `usage_metadata` object into an AG-UI {@link TokenUsage}.
828
924
  *
829
925
  * LangChain and LangGraph both attach usage as `{ input_tokens, output_tokens,
830
- * total_tokens, input_token_details: { cache_read }, output_token_details:
831
- * { reasoning } }`. This maps only those numeric counts plus optional
832
- * provider/model labels — never prompt/completion content. Returns `undefined`
833
- * when no usable count is present, so callers can omit usage rather than
834
- * report zeros.
926
+ * total_tokens, input_token_details: { cache_read, cache_creation },
927
+ * output_token_details: { reasoning } }`. LangChain's accounting is the
928
+ * protocol's — `input_tokens` already includes the cache details and
929
+ * `output_tokens` the reasoning detail — so every count passes through as is.
930
+ * This maps only those numeric counts plus optional provider/model labels —
931
+ * never prompt/completion content. A count the provider
932
+ * did not return is simply absent from `usage_metadata` and reads as
933
+ * `undefined` here; that is not a defect and draws no warning. Returns
934
+ * `undefined` when no usable count is present, so callers can omit usage rather
935
+ * than report zeros.
835
936
  */
836
937
  function tokenUsageFromLangChainMetadata(usageMetadata, { provider, model }) {
837
938
  if (!usageMetadata) return void 0;
838
939
  const inputDetails = prop(usageMetadata, "input_token_details");
839
940
  const outputDetails = prop(usageMetadata, "output_token_details");
840
941
  return buildEntry({
841
- inputTokens: num(prop(usageMetadata, "input_tokens")),
842
- outputTokens: num(prop(usageMetadata, "output_tokens")),
843
- totalTokens: num(prop(usageMetadata, "total_tokens")),
844
- reasoningTokens: num(prop(outputDetails, "reasoning")),
845
- cachedInputTokens: num(prop(inputDetails, "cache_read"))
942
+ inputTokens: num(prop(usageMetadata, "input_tokens"), "inputTokens"),
943
+ outputTokens: num(prop(usageMetadata, "output_tokens"), "outputTokens"),
944
+ totalTokens: num(prop(usageMetadata, "total_tokens"), "totalTokens"),
945
+ reasoningTokens: num(prop(outputDetails, "reasoning"), "reasoningTokens"),
946
+ cachedInputTokens: num(prop(inputDetails, "cache_read"), "cachedInputTokens"),
947
+ cacheWriteInputTokens: num(prop(inputDetails, "cache_creation"), "cacheWriteInputTokens")
846
948
  }, {
847
949
  provider,
848
950
  model
849
951
  });
850
952
  }
851
953
  /**
852
- * Map an AI-SDK (v5) `LanguageModelUsage` object into an AG-UI {@link TokenUsage}.
954
+ * Map an AI-SDK `LanguageModelUsage` object into an AG-UI {@link TokenUsage}.
853
955
  *
854
- * AI-SDK's keys already match: `inputTokens`, `outputTokens`, `totalTokens`,
855
- * `reasoningTokens`, `cachedInputTokens`. AI-SDK reports `NaN`/`undefined` for
856
- * counts a provider didn't return, so only finite numbers are copied. Returns
857
- * `undefined` when no finite count is present (so callers omit empty usage).
956
+ * AI-SDK's v5 keys already match — `inputTokens`, `outputTokens`,
957
+ * `totalTokens`, `reasoningTokens`, `cachedInputTokens` — with the totals
958
+ * inclusive the way the protocol counts them. v6 adds `inputTokenDetails:
959
+ * { cacheReadTokens, cacheWriteTokens }` and `outputTokenDetails:
960
+ * { reasoningTokens }`; the cache-write count exists only there, and the two
961
+ * counts present in both forms are read from the top level first. AI-SDK
962
+ * reports `NaN`/`undefined` for counts a provider didn't return, so only finite
963
+ * numbers are copied. Returns `undefined` when no finite count is present (so
964
+ * callers omit empty usage).
858
965
  */
859
966
  function tokenUsageFromAiSdkUsage(usage, { provider, model }) {
860
967
  if (!usage) return void 0;
968
+ const inputDetails = prop(usage, "inputTokenDetails");
969
+ const outputDetails = prop(usage, "outputTokenDetails");
861
970
  return buildEntry({
862
- inputTokens: num(prop(usage, "inputTokens")),
863
- outputTokens: num(prop(usage, "outputTokens")),
864
- totalTokens: num(prop(usage, "totalTokens")),
865
- reasoningTokens: num(prop(usage, "reasoningTokens")),
866
- cachedInputTokens: num(prop(usage, "cachedInputTokens"))
971
+ inputTokens: num(prop(usage, "inputTokens"), "inputTokens"),
972
+ outputTokens: num(prop(usage, "outputTokens"), "outputTokens"),
973
+ totalTokens: num(prop(usage, "totalTokens"), "totalTokens"),
974
+ reasoningTokens: num(prop(usage, "reasoningTokens"), "reasoningTokens") ?? num(prop(outputDetails, "reasoningTokens"), "reasoningTokens"),
975
+ cachedInputTokens: num(prop(usage, "cachedInputTokens"), "cachedInputTokens") ?? num(prop(inputDetails, "cacheReadTokens"), "cachedInputTokens"),
976
+ cacheWriteInputTokens: num(prop(inputDetails, "cacheWriteTokens"), "cacheWriteInputTokens")
867
977
  }, {
868
978
  provider,
869
979
  model
@@ -899,5 +1009,35 @@ function aggregateTokenUsage(entries) {
899
1009
  }
900
1010
 
901
1011
  //#endregion
902
- export { AGUIConnectNotImplementedError, AGUIError, AGUI_METADATA_KEY, ActivityDeltaEventSchema, ActivityMessageSchema, ActivitySnapshotEventSchema, AgentCapabilitiesSchema, AssistantMessageSchema, AudioInputContentSchema, AudioInputPartSchema, BaseEventSchema, BaseMessageSchema, BinaryInputContentSchema, ContextSchema, CustomEventSchema, DeveloperMessageSchema, DocumentInputContentSchema, DocumentInputPartSchema, EventSchemas, EventType, ExecutionCapabilitiesSchema, FunctionCallSchema, HumanInTheLoopCapabilitiesSchema, IdentityCapabilitiesSchema, ImageInputContentSchema, ImageInputPartSchema, InputContentDataSourceSchema, InputContentSchema, InputContentSourceSchema, InputContentUrlSourceSchema, InterruptSchema, MessageSchema, MessagesSnapshotEventSchema, MetadataSchema, MultiAgentCapabilitiesSchema, MultimodalCapabilitiesSchema, MultimodalInputCapabilitiesSchema, MultimodalOutputCapabilitiesSchema, OptionalMetadataSchema, OutputCapabilitiesSchema, RawEventSchema, ReasoningCapabilitiesSchema, ReasoningEncryptedValueEventSchema, ReasoningEncryptedValueSubtypeSchema, ReasoningEndEventSchema, ReasoningMessageChunkEventSchema, ReasoningMessageContentEventSchema, ReasoningMessageEndEventSchema, ReasoningMessageSchema, ReasoningMessageStartEventSchema, ReasoningStartEventSchema, ResumeEntrySchema, RoleSchema, RunAgentInputSchema, RunErrorEventSchema, RunFinishedEventSchema, RunFinishedInterruptOutcomeSchema, RunFinishedOutcomeSchema, RunFinishedSuccessOutcomeSchema, RunStartedEventSchema, StateCapabilitiesSchema, StateDeltaEventSchema, StateSchema, StateSnapshotEventSchema, StepFinishedEventSchema, StepStartedEventSchema, SubAgentInfoSchema, SubagentErrorEventSchema, SubagentFinishedEventSchema, SubagentFinishedOutcomeSchema, SubagentFinishedSuccessOutcomeSchema, SubagentFinishedSuspendedOutcomeSchema, SubagentStartedEventSchema, SystemMessageSchema, TextInputContentSchema, TextMessageChunkEventSchema, TextMessageContentEventSchema, TextMessageEndEventSchema, TextMessageStartEventSchema, ThinkingEndEventSchema, ThinkingStartEventSchema, ThinkingTextMessageContentEventSchema, ThinkingTextMessageEndEventSchema, ThinkingTextMessageStartEventSchema, TokenUsageSchema, ToolCallArgsEventSchema, ToolCallChunkEventSchema, ToolCallEndEventSchema, ToolCallResultEventSchema, ToolCallSchema, ToolCallStartEventSchema, ToolMessageSchema, ToolSchema, ToolsCapabilitiesSchema, TransportCapabilitiesSchema, UserMessageSchema, VideoInputContentSchema, VideoInputPartSchema, aggregateTokenUsage, mergeMetadata, tokenUsageFromAiSdkUsage, tokenUsageFromLangChainMetadata };
1012
+ //#region src/content.ts
1013
+ /**
1014
+ * The text of string-or-parts content, for a consumer that can only hold a
1015
+ * string: the text parts concatenated in order, every other part dropped.
1016
+ *
1017
+ * This is the downgrade the specification permits for a peer that predates
1018
+ * content parts (/spec/draft/basic/versioning): it removes and reshapes, and
1019
+ * it invents nothing — no placeholder stands in for a dropped image, because a
1020
+ * downgrade MUST NOT supply a value the producer never sent. Content that is
1021
+ * entirely media flattens to the empty string, which the same rule allows.
1022
+ *
1023
+ * Losing content is never meant to be silent. This helper only reshapes; a
1024
+ * caller that knows it is talking to an older peer warns as well, the way the
1025
+ * era shims in `@ag-ui/client` do.
1026
+ */
1027
+ function contentToText(content) {
1028
+ if (content === void 0) return "";
1029
+ if (typeof content === "string") return content;
1030
+ return content.filter((part) => part.type === "text").map((part) => part.text).join("");
1031
+ }
1032
+ /**
1033
+ * Whether string-or-parts content carries anything but text — the question a
1034
+ * caller asks before flattening, so it can warn about what the flattening
1035
+ * would drop.
1036
+ */
1037
+ function contentHasMedia(content) {
1038
+ return Array.isArray(content) && content.some((part) => part.type !== "text");
1039
+ }
1040
+
1041
+ //#endregion
1042
+ export { AGUIConnectNotImplementedError, AGUIError, AGUI_METADATA_KEY, EventType, PROTOCOL_VERSION, aggregateTokenUsage, contentHasMedia, contentToText, mergeMetadata, omitOptionalNulls, tokenUsageFromAiSdkUsage, tokenUsageFromLangChainMetadata };
903
1043
  //# sourceMappingURL=index.mjs.map