@anvia/client 1.6.0 → 1.7.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.js CHANGED
@@ -1,2587 +1,2157 @@
1
- import {
2
- createFetchEventTransport
3
- } from "./chunk-RK5U6WVJ.js";
4
- import "./chunk-PD72KNCV.js";
5
-
6
- // src/adapters.ts
7
- import {
8
- isJsonValue as isJsonValue3
9
- } from "@anvia/core/completion";
10
-
11
- // src/messages.ts
12
- import { getAssistantGenerationMetadata, isJsonValue } from "@anvia/core/completion";
13
- function uiMessagesToMessages(messages) {
14
- const result = [];
15
- for (const message of messages) {
16
- assertMetadata(message.metadata);
17
- if (message.role === "system") {
18
- assertOnlyParts(message, ["text", "data", "error"]);
19
- result.push({
20
- role: "system",
21
- content: textFromParts(message.parts),
22
- ...metadataField(message.metadata)
23
- });
24
- continue;
25
- }
26
- if (message.role === "user") {
27
- assertOnlyParts(message, ["text", "attachment", "data", "error"]);
28
- const content2 = [];
29
- for (const part of message.parts) {
30
- if (part.type === "text") {
31
- content2.push(textContent(part.text, part.signature));
32
- } else if (part.type === "attachment") {
33
- content2.push(attachmentToUserContent(part.attachment));
34
- }
35
- }
36
- result.push({ role: "user", content: content2, ...metadataField(message.metadata) });
37
- continue;
38
- }
39
- if (message.role === "assistant") {
40
- assertOnlyParts(message, [
41
- "text",
42
- "reasoning",
43
- "tool",
44
- "attachment",
45
- "source",
46
- "data",
47
- "error"
48
- ]);
49
- const content2 = [];
50
- const toolResults = [];
51
- for (const part of message.parts) {
52
- if (part.type === "text") {
53
- content2.push(textContent(part.text, part.signature));
54
- } else if (part.type === "reasoning") {
55
- let reasoning = {
56
- type: "reasoning",
57
- text: part.text
58
- };
59
- if (part.reasoningId !== void 0) reasoning = { ...reasoning, id: part.reasoningId };
60
- if (part.content !== void 0) reasoning = { ...reasoning, details: part.content };
61
- content2.push(reasoning);
62
- } else if (part.type === "tool") {
63
- assertReplayableToolPart(part);
64
- let toolCall = {
65
- type: "tool-call",
66
- toolCallId: part.toolCallId,
67
- toolName: part.toolName,
68
- input: part.input
69
- };
70
- if (part.callId !== void 0) toolCall = { ...toolCall, callId: part.callId };
71
- if (part.signature !== void 0) toolCall = { ...toolCall, signature: part.signature };
72
- content2.push(toolCall);
73
- if (part.state === "output-available" || part.state === "error") {
74
- toolResults.push(toolResultFromPart(part));
75
- }
76
- } else if (part.type === "attachment") {
77
- content2.push(attachmentToAssistantContent(part.attachment));
78
- }
79
- }
80
- let assistant = {
81
- role: "assistant",
82
- content: content2,
83
- ...metadataField(message.metadata)
84
- };
85
- if (message.modelMessageId !== void 0) {
86
- assistant = { ...assistant, id: message.modelMessageId };
87
- }
88
- result.push(assistant);
89
- if (toolResults.length > 0) {
90
- result.push({ role: "tool", content: toolResults });
91
- }
92
- continue;
93
- }
94
- assertOnlyParts(message, ["tool", "data", "error"]);
95
- const content = [];
96
- for (const part of message.parts) {
97
- if (part.type !== "tool") continue;
98
- assertToolResultPart(part);
99
- content.push(toolResultFromPart(part));
100
- }
101
- result.push({ role: "tool", content, ...metadataField(message.metadata) });
102
- }
103
- return result;
104
- }
105
- function messagesToUIMessages(messages) {
106
- const result = [];
107
- const byToolCallId = /* @__PURE__ */ new Map();
108
- const byCallId = /* @__PURE__ */ new Map();
109
- for (const message of messages) {
110
- assertMetadata(message.metadata);
111
- if (message.role === "system") {
112
- result.push({
113
- id: createId("msg"),
114
- role: "system",
115
- parts: [{ id: createId("part"), type: "text", text: message.content }],
116
- ...metadataField(message.metadata)
117
- });
118
- continue;
119
- }
120
- if (message.role === "user") {
121
- const content = typeof message.content === "string" ? [{ type: "text", text: message.content }] : message.content;
122
- const parts = content.map((part) => contentToUIMessagePart(part));
123
- result.push({
124
- id: createId("msg"),
125
- role: "user",
126
- parts,
127
- ...metadataField(message.metadata)
128
- });
129
- continue;
130
- }
131
- if (message.role === "assistant") {
132
- const generationMetadata = getAssistantGenerationMetadata(message);
133
- const content = typeof message.content === "string" ? [{ type: "text", text: message.content }] : message.content;
134
- const parts = content.map(assistantContentToUIMessagePart);
135
- for (const source of generationMetadata?.sources ?? []) {
136
- parts.push({ id: createId("source"), type: "source", source });
137
- }
138
- let uiMessage = {
139
- id: createId("msg"),
140
- role: "assistant",
141
- parts,
142
- ...metadataField(message.metadata)
143
- };
144
- if (generationMetadata !== void 0) {
145
- const generation = { usage: generationMetadata.usage };
146
- if (generationMetadata.contextUsage !== void 0) {
147
- generation.contextUsage = generationMetadata.contextUsage;
148
- }
149
- uiMessage = {
150
- ...uiMessage,
151
- generation
152
- };
153
- }
154
- if (message.id !== void 0) uiMessage = { ...uiMessage, modelMessageId: message.id };
155
- const messageIndex = result.length;
156
- result.push(uiMessage);
157
- for (const [partIndex, part] of parts.entries()) {
158
- if (part.type !== "tool") continue;
159
- const location = { messageIndex, partIndex };
160
- byToolCallId.set(part.toolCallId, location);
161
- if (part.callId !== void 0) byCallId.set(part.callId, location);
162
- }
163
- continue;
164
- }
165
- const unmerged = [];
166
- for (const content of message.content) {
167
- if (content.type !== "tool-result") continue;
168
- const location = (content.callId === void 0 ? void 0 : byCallId.get(content.callId)) ?? byToolCallId.get(content.toolCallId);
169
- const ownerPart = toolPartAt(result, location);
170
- if (ownerPart === void 0 || ownerPart.state === "input-streaming") {
171
- throw new TypeError(
172
- `Tool result "${content.toolCallId}" requires a matching completed tool call.`
173
- );
174
- }
175
- const part = toolResultToUIMessagePart(content, ownerPart.toolName, ownerPart.input);
176
- if (message.metadata === void 0 && location !== void 0) {
177
- const owner = result[location.messageIndex];
178
- const existing = owner?.parts[location.partIndex];
179
- if (owner !== void 0 && existing?.type === "tool") {
180
- const parts = [...owner.parts];
181
- parts[location.partIndex] = { ...existing, ...part, id: existing.id };
182
- result[location.messageIndex] = { ...owner, parts };
183
- continue;
184
- }
185
- }
186
- unmerged.push(part);
187
- }
188
- if (unmerged.length > 0 || message.metadata !== void 0) {
189
- result.push({
190
- id: createId("msg"),
191
- role: "tool",
192
- parts: unmerged,
193
- ...metadataField(message.metadata)
194
- });
195
- }
196
- }
197
- return result;
198
- }
199
- function contentToUIMessagePart(content) {
200
- if (content.type === "text") {
201
- const part = {
202
- id: createId("part"),
203
- type: "text",
204
- text: content.text
205
- };
206
- if (content.signature !== void 0) part.signature = content.signature;
207
- return part;
208
- }
209
- return {
210
- id: createId("part"),
211
- type: "attachment",
212
- attachment: contentToAttachment(content)
213
- };
214
- }
215
- function assistantContentToUIMessagePart(content) {
216
- if (content.type === "text") return contentToUIMessagePart(content);
217
- if (content.type === "reasoning") {
218
- const part = {
219
- id: createId("part"),
220
- type: "reasoning",
221
- text: content.text
222
- };
223
- if (content.id !== void 0) part.reasoningId = content.id;
224
- if (content.details !== void 0) part.content = content.details;
225
- return part;
226
- }
227
- if (content.type === "tool-call") {
228
- const part = {
229
- id: toolPartId(content.toolCallId),
230
- type: "tool",
231
- toolName: content.toolName,
232
- toolCallId: content.toolCallId,
233
- state: "input-available",
234
- input: content.input
235
- };
236
- if (content.callId !== void 0) part.callId = content.callId;
237
- if (content.signature !== void 0) part.signature = content.signature;
238
- return part;
239
- }
240
- return {
241
- id: createId("part"),
242
- type: "attachment",
243
- attachment: contentToAttachment(content)
244
- };
245
- }
246
- function textContent(text, signature) {
247
- return signature === void 0 ? { type: "text", text } : { type: "text", text, signature };
248
- }
249
- function toolResultFromPart(part) {
250
- let result = {
251
- type: "tool-result",
252
- toolCallId: part.toolCallId,
253
- toolName: part.toolName,
254
- output: toolOutputFromPart(part)
255
- };
256
- if (part.callId !== void 0) result = { ...result, callId: part.callId };
257
- return result;
258
- }
259
- function toolOutputFromPart(part) {
260
- if (part.state === "error") {
261
- return { type: "error-text", value: part.error.message };
262
- }
263
- if (part.resultContent !== void 0) {
264
- return { type: "content", value: part.resultContent };
265
- }
266
- const output = part.output;
267
- return typeof output === "string" ? { type: "text", value: output } : { type: "json", value: output };
268
- }
269
- function attachmentToUserContent(attachment) {
270
- if (attachment.type === "image" || attachment.mediaType?.startsWith("image/") === true) {
271
- return attachmentToImageContent(attachment);
272
- }
273
- return attachmentToFileContent(attachment);
274
- }
275
- function attachmentToAssistantContent(attachment) {
276
- return attachment.type === "image" || attachment.mediaType?.startsWith("image/") === true ? attachmentToImageContent(attachment) : attachmentToFileContent(attachment);
277
- }
278
- function attachmentToImageContent(attachment) {
279
- const image = attachment.url !== void 0 ? { type: "url", url: attachment.url } : attachment.data !== void 0 ? { type: "data", data: attachment.data } : (() => {
280
- throw new TypeError("Image attachments require a URL or base64 data.");
281
- })();
282
- let content = {
283
- type: "image",
284
- image
285
- };
286
- if (attachment.mediaType !== void 0) content = { ...content, mediaType: attachment.mediaType };
287
- if (attachment.detail !== void 0) content = { ...content, detail: attachment.detail };
288
- return content;
289
- }
290
- function attachmentToFileContent(attachment) {
291
- const data = attachment.url !== void 0 ? { type: "url", url: attachment.url } : attachment.data !== void 0 ? { type: "data", data: attachment.data } : attachment.text !== void 0 ? { type: "text", text: attachment.text } : (() => {
292
- throw new TypeError("File attachments require a URL, base64 data, or text.");
293
- })();
294
- let content = {
295
- type: "file",
296
- data,
297
- mediaType: attachment.mediaType ?? "application/octet-stream"
298
- };
299
- if (attachment.name !== void 0) content = { ...content, filename: attachment.name };
300
- return content;
301
- }
302
- function contentToAttachment(content) {
303
- const attachment = {
304
- id: createId("attachment"),
305
- type: content.type === "image" ? "image" : "file"
306
- };
307
- if (content.type === "image") {
308
- if (content.detail !== void 0) attachment.detail = content.detail;
309
- if (content.mediaType !== void 0) attachment.mediaType = content.mediaType;
310
- if (content.image.type === "url") attachment.url = content.image.url;
311
- else attachment.data = content.image.data;
312
- return attachment;
313
- }
314
- attachment.mediaType = content.mediaType;
315
- if (content.filename !== void 0) attachment.name = content.filename;
316
- if (content.data.type === "url") attachment.url = content.data.url;
317
- else if (content.data.type === "data") attachment.data = content.data.data;
318
- else attachment.text = content.data.text;
319
- return attachment;
320
- }
321
- function toolResultToUIMessagePart(content, fallbackToolName, input) {
322
- const output = content.output;
323
- const common = {
324
- id: toolPartId(content.toolCallId),
325
- type: "tool",
326
- toolName: content.toolName || fallbackToolName,
327
- toolCallId: content.toolCallId,
328
- input
329
- };
330
- if (content.callId !== void 0) Object.assign(common, { callId: content.callId });
331
- if (output.type === "error-text" || output.type === "error-json") {
332
- return {
333
- ...common,
334
- state: "error",
335
- error: {
336
- message: output.type === "error-text" ? output.value : JSON.stringify(output.value)
337
- }
338
- };
339
- }
340
- if (output.type === "execution-denied") {
341
- return {
342
- ...common,
343
- state: "error",
344
- error: { message: output.reason ?? "Tool execution was denied." }
345
- };
346
- }
347
- const part = {
348
- ...common,
349
- state: "output-available",
350
- output: toolResultOutput(output)
351
- };
352
- if (output.type === "content") part.resultContent = output.value;
353
- return part;
354
- }
355
- function toolResultOutput(output) {
356
- if (output.type === "text" || output.type === "error-text") return output.value;
357
- if (output.type === "json" || output.type === "error-json") return output.value;
358
- if (output.type === "execution-denied") return output.reason ?? "Tool execution was denied.";
359
- return output.value.length === 1 && output.value[0]?.type === "text" ? output.value[0].text : output.value.map(
360
- (part) => part.type === "text" ? { ...part } : { ...part, data: { ...part.data } }
361
- );
362
- }
363
- function toolPartAt(messages, location) {
364
- if (location === void 0) return void 0;
365
- const part = messages[location.messageIndex]?.parts[location.partIndex];
366
- return part?.type === "tool" ? part : void 0;
367
- }
368
- function assertReplayableToolPart(part) {
369
- if (part.state === "input-streaming") {
370
- throw new TypeError(
371
- `Tool call "${part.toolCallId}" is still streaming and cannot be converted to a model message.`
372
- );
373
- }
374
- if (!isJsonValue(part.input)) {
375
- throw new TypeError(`Tool call "${part.toolCallId}" input must be a strict JSON value.`);
376
- }
377
- }
378
- function assertToolResultPart(part) {
379
- assertReplayableToolPart(part);
380
- if (part.state === "input-available") {
381
- throw new TypeError(
382
- `Tool message part "${part.toolCallId}" requires an output or execution error.`
383
- );
384
- }
385
- }
386
- function textFromParts(parts) {
387
- return parts.flatMap((part) => part.type === "text" ? [part.text] : []).join("");
388
- }
389
- function assertOnlyParts(message, allowed) {
390
- for (const part of message.parts) {
391
- if (!allowed.includes(part.type)) {
392
- throw new TypeError(`${message.role} UI messages cannot contain ${part.type} parts.`);
393
- }
394
- }
395
- }
396
- function assertMetadata(metadata) {
397
- if (metadata !== void 0 && (!isJsonValue(metadata) || Array.isArray(metadata))) {
398
- throw new TypeError("Message metadata must be a strict JSON object.");
399
- }
400
- }
401
- function metadataField(metadata) {
402
- return metadata === void 0 ? {} : { metadata };
403
- }
404
- function toolPartId(toolCallId) {
405
- return `tool_${toolCallId}`;
406
- }
407
- var nextId = 0;
408
- function createClientId(prefix) {
409
- const random = globalThis.crypto?.randomUUID?.();
410
- if (random !== void 0) return `${prefix}_${random}`;
411
- nextId += 1;
412
- return `${prefix}_${nextId.toString(36)}`;
413
- }
414
- function createId(prefix) {
415
- return createClientId(prefix);
416
- }
417
-
418
- // src/protocol.ts
419
- import {
420
- parseAgentInteractionRequest,
421
- parseAgentInteractionResponse
422
- } from "@anvia/core/agent/interactions";
423
- import { isJsonValue as isJsonValue2, parseMessages } from "@anvia/core/completion";
424
-
425
- // src/types.ts
426
- var CLIENT_STREAM_PROTOCOL = "anvia.client.v3";
427
-
1
+ import { i as uiMessagesToMessages, n as createClientId, r as messagesToUIMessages, t as CLIENT_STREAM_PROTOCOL } from "./types-CqJxMo_1.js";
2
+ import { n as createFetchEventTransport } from "./event-transport-CcP1zaST.js";
3
+ import { isJsonValue, isJsonValue as isJsonValue$1, parseMessages } from "@anvia/core/completion";
4
+ import { parseAgentInteractionRequest, parseAgentInteractionResponse } from "@anvia/core/agent/interactions";
428
5
  // src/protocol.ts
429
6
  var ClientProtocolError = class extends Error {
430
- constructor(message, value) {
431
- super(message);
432
- this.value = value;
433
- this.name = "ClientProtocolError";
434
- }
435
- value;
7
+ value;
8
+ constructor(message, value) {
9
+ super(message);
10
+ this.value = value;
11
+ this.name = "ClientProtocolError";
12
+ }
436
13
  };
437
14
  function parseUIMessage(value, options = {}) {
438
- const message = requireRecord(value, "UI message");
439
- if (!isJsonValue2(message)) {
440
- throw new ClientProtocolError("UI messages must be strict JSON values.", value);
441
- }
442
- requireOnlyKeys(
443
- message,
444
- ["id", "role", "parts", "modelMessageId", "metadata", "generation"],
445
- "UI message"
446
- );
447
- if (typeof message.id !== "string") invalid("UI message.id", value);
448
- requireOneOf(message.role, ["system", "user", "assistant", "tool"], "UI message.role", value);
449
- if (!Array.isArray(message.parts)) invalid("UI message.parts", value);
450
- const parts = message.parts.map((part) => parseUIMessagePart(part, options.dataSchemas, value));
451
- if (message.modelMessageId !== void 0 && typeof message.modelMessageId !== "string") {
452
- invalid("UI message.modelMessageId", value);
453
- }
454
- const metadata = message.metadata === void 0 ? void 0 : parseMetadata(message.metadata, options.metadataSchema, value);
455
- if (message.generation !== void 0 && !isUIMessageGeneration(message.generation)) {
456
- invalid("UI message.generation", value);
457
- }
458
- let parsed = {
459
- id: message.id,
460
- role: message.role,
461
- parts
462
- };
463
- if (message.modelMessageId !== void 0) {
464
- parsed = { ...parsed, modelMessageId: message.modelMessageId };
465
- }
466
- if (metadata !== void 0) parsed = { ...parsed, metadata };
467
- if (message.generation !== void 0) {
468
- parsed = { ...parsed, generation: message.generation };
469
- }
470
- return parsed;
15
+ const message = requireRecord(value, "UI message");
16
+ if (!isJsonValue$1(message)) throw new ClientProtocolError("UI messages must be strict JSON values.", value);
17
+ requireOnlyKeys(message, [
18
+ "id",
19
+ "role",
20
+ "parts",
21
+ "modelMessageId",
22
+ "metadata",
23
+ "generation"
24
+ ], "UI message");
25
+ if (typeof message.id !== "string") invalid("UI message.id", value);
26
+ requireOneOf(message.role, [
27
+ "system",
28
+ "user",
29
+ "assistant",
30
+ "tool"
31
+ ], "UI message.role", value);
32
+ if (!Array.isArray(message.parts)) invalid("UI message.parts", value);
33
+ const parts = message.parts.map((part) => parseUIMessagePart(part, options.dataSchemas, value));
34
+ if (message.modelMessageId !== void 0 && typeof message.modelMessageId !== "string") invalid("UI message.modelMessageId", value);
35
+ const metadata = message.metadata === void 0 ? void 0 : parseMetadata(message.metadata, options.metadataSchema, value);
36
+ if (message.generation !== void 0 && !isUIMessageGeneration(message.generation)) invalid("UI message.generation", value);
37
+ let parsed = {
38
+ id: message.id,
39
+ role: message.role,
40
+ parts
41
+ };
42
+ if (message.modelMessageId !== void 0) parsed = {
43
+ ...parsed,
44
+ modelMessageId: message.modelMessageId
45
+ };
46
+ if (metadata !== void 0) parsed = {
47
+ ...parsed,
48
+ metadata
49
+ };
50
+ if (message.generation !== void 0) parsed = {
51
+ ...parsed,
52
+ generation: message.generation
53
+ };
54
+ return parsed;
471
55
  }
472
56
  function parseUIMessages(value, options = {}) {
473
- if (!Array.isArray(value)) {
474
- throw new ClientProtocolError("UI messages must be an array.", value);
475
- }
476
- return value.map((message) => parseUIMessage(message, options));
57
+ if (!Array.isArray(value)) throw new ClientProtocolError("UI messages must be an array.", value);
58
+ return value.map((message) => parseUIMessage(message, options));
477
59
  }
478
60
  function parseClientStreamRequest(value) {
479
- const input = requireRecord(value, "Client stream request");
480
- requireOnlyKeys(
481
- input,
482
- ["type", "messages", "interactionId", "response", "metadata", "resume"],
483
- "Client stream request"
484
- );
485
- requireOneOf(
486
- input.type,
487
- ["messages", "interaction_response"],
488
- "Client stream request.type",
489
- value
490
- );
491
- if (input.metadata !== void 0 && !isJsonObject(input.metadata)) {
492
- throw new ClientProtocolError("Client stream request.metadata must be a JSON object.", value);
493
- }
494
- let request;
495
- if (input.type === "messages") {
496
- if (input.interactionId !== void 0 || input.response !== void 0) {
497
- throw new ClientProtocolError(
498
- "Messages requests cannot include interaction response fields.",
499
- value
500
- );
501
- }
502
- let messages;
503
- try {
504
- messages = parseMessages(input.messages);
505
- } catch {
506
- throw new ClientProtocolError("Client stream request.messages must be Message[].", value);
507
- }
508
- request = { type: "messages", messages };
509
- } else {
510
- if (input.messages !== void 0 || typeof input.interactionId !== "string") {
511
- throw new ClientProtocolError(
512
- "Interaction response requests require interactionId and cannot include messages.",
513
- value
514
- );
515
- }
516
- try {
517
- request = {
518
- type: "interaction_response",
519
- interactionId: input.interactionId,
520
- response: parseAgentInteractionResponse(input.response)
521
- };
522
- } catch {
523
- throw new ClientProtocolError("Client interaction response is invalid.", value);
524
- }
525
- }
526
- if (input.metadata !== void 0) request.metadata = input.metadata;
527
- if (input.resume !== void 0) {
528
- const resume = requireRecord(input.resume, "Client stream request.resume");
529
- requireOnlyKeys(resume, ["streamId", "after"], "Client stream request.resume");
530
- if (typeof resume.streamId !== "string" || !isEventId(resume.after)) {
531
- throw new ClientProtocolError(
532
- "Client stream resume cursor requires streamId and a nonnegative safe integer after.",
533
- value
534
- );
535
- }
536
- request.resume = { streamId: resume.streamId, after: resume.after };
537
- }
538
- return request;
61
+ const input = requireRecord(value, "Client stream request");
62
+ requireOnlyKeys(input, [
63
+ "type",
64
+ "messages",
65
+ "interactionId",
66
+ "response",
67
+ "metadata",
68
+ "resume"
69
+ ], "Client stream request");
70
+ requireOneOf(input.type, ["messages", "interaction_response"], "Client stream request.type", value);
71
+ if (input.metadata !== void 0 && !isJsonObject(input.metadata)) throw new ClientProtocolError("Client stream request.metadata must be a JSON object.", value);
72
+ let request;
73
+ if (input.type === "messages") {
74
+ if (input.interactionId !== void 0 || input.response !== void 0) throw new ClientProtocolError("Messages requests cannot include interaction response fields.", value);
75
+ let messages;
76
+ try {
77
+ messages = parseMessages(input.messages);
78
+ } catch {
79
+ throw new ClientProtocolError("Client stream request.messages must be Message[].", value);
80
+ }
81
+ request = {
82
+ type: "messages",
83
+ messages
84
+ };
85
+ } else {
86
+ if (input.messages !== void 0 || typeof input.interactionId !== "string") throw new ClientProtocolError("Interaction response requests require interactionId and cannot include messages.", value);
87
+ try {
88
+ request = {
89
+ type: "interaction_response",
90
+ interactionId: input.interactionId,
91
+ response: parseAgentInteractionResponse(input.response)
92
+ };
93
+ } catch {
94
+ throw new ClientProtocolError("Client interaction response is invalid.", value);
95
+ }
96
+ }
97
+ if (input.metadata !== void 0) request.metadata = input.metadata;
98
+ if (input.resume !== void 0) {
99
+ const resume = requireRecord(input.resume, "Client stream request.resume");
100
+ requireOnlyKeys(resume, ["streamId", "after"], "Client stream request.resume");
101
+ if (typeof resume.streamId !== "string" || !isEventId(resume.after)) throw new ClientProtocolError("Client stream resume cursor requires streamId and a nonnegative safe integer after.", value);
102
+ request.resume = {
103
+ streamId: resume.streamId,
104
+ after: resume.after
105
+ };
106
+ }
107
+ return request;
539
108
  }
540
109
  function parseClientStreamEvent(value, options = {}) {
541
- const event = requireRecord(value, "Client stream event");
542
- if (!isJsonValue2(event)) {
543
- throw new ClientProtocolError("Client stream events must be strict JSON values.", value);
544
- }
545
- if (typeof event.type !== "string" || typeof event.runId !== "string") {
546
- throw new ClientProtocolError("Client stream events require type and runId.", value);
547
- }
548
- if (event.turn !== void 0 && !isPositiveEventId(event.turn)) {
549
- throw new ClientProtocolError(
550
- "Client stream event.turn must be a positive safe integer.",
551
- value
552
- );
553
- }
554
- if (event.scope !== void 0 && !isScope(event.scope)) {
555
- throw new ClientProtocolError("Client stream event.scope is invalid.", value);
556
- }
557
- switch (event.type) {
558
- case "run_start":
559
- requireEventKeys(event, ["source", "metadata"]);
560
- requireOneOf(event.source, ["completion", "agent"], "run_start.source", value);
561
- break;
562
- case "turn_start":
563
- requireEventKeys(event, []);
564
- if (!isPositiveEventId(event.turn)) invalid("turn_start.turn", value);
565
- break;
566
- case "generation_start":
567
- requireEventKeys(event, ["model"]);
568
- if (event.model !== void 0 && (!isRecord(event.model) || !hasOnlyKeys(event.model, ["provider", "modelId"]) || typeof event.model.provider !== "string" || typeof event.model.modelId !== "string")) {
569
- invalid("generation_start.model", value);
570
- }
571
- break;
572
- case "message_reset":
573
- requireEventKeys(event, ["messageId"]);
574
- requireStrings(event, ["messageId"], value);
575
- break;
576
- case "message_start":
577
- requireEventKeys(event, ["messageId", "role", "metadata"]);
578
- requireStrings(event, ["messageId"], value);
579
- if (event.role !== "assistant") invalid("message_start.role", value);
580
- break;
581
- case "text_start":
582
- requireEventKeys(event, ["messageId", "partId"]);
583
- requireStrings(event, ["messageId", "partId"], value);
584
- break;
585
- case "text_delta":
586
- requireEventKeys(event, ["messageId", "partId", "delta"]);
587
- requireStrings(event, ["messageId", "partId", "delta"], value);
588
- break;
589
- case "reasoning_delta":
590
- requireEventKeys(event, ["messageId", "partId", "delta", "contentType", "signature"]);
591
- requireStrings(event, ["messageId", "partId", "delta"], value);
592
- requireOptionalStrings(event, ["signature"], value);
593
- if (event.contentType !== void 0 && !["text", "summary", "encrypted", "redacted"].includes(event.contentType)) {
594
- invalid("reasoning_delta.contentType", value);
595
- }
596
- break;
597
- case "text_end":
598
- requireEventKeys(event, ["messageId", "partId", "text", "signature"]);
599
- requireStrings(event, ["messageId", "partId"], value);
600
- requireOptionalStrings(event, ["text", "signature"], value);
601
- break;
602
- case "reasoning_start":
603
- requireEventKeys(event, ["messageId", "partId", "reasoningId"]);
604
- requireStrings(event, ["messageId", "partId"], value);
605
- requireOptionalStrings(event, ["reasoningId"], value);
606
- break;
607
- case "reasoning_end":
608
- requireEventKeys(event, ["messageId", "partId", "text", "content"]);
609
- requireStrings(event, ["messageId", "partId"], value);
610
- requireOptionalStrings(event, ["text"], value);
611
- if (event.content !== void 0 && (!Array.isArray(event.content) || !event.content.every(isReasoningContent))) {
612
- invalid("reasoning_end.content", value);
613
- }
614
- break;
615
- case "tool_call_start":
616
- requireEventKeys(event, ["messageId", "partId", "toolCallId", "callId", "toolName"]);
617
- requireStrings(event, ["messageId", "partId", "toolCallId"], value);
618
- requireOptionalStrings(event, ["callId", "toolName"], value);
619
- break;
620
- case "tool_call_delta":
621
- requireEventKeys(event, [
622
- "messageId",
623
- "partId",
624
- "toolCallId",
625
- "callId",
626
- "toolName",
627
- "delta",
628
- "mode",
629
- "signature"
630
- ]);
631
- requireStrings(event, ["messageId", "partId", "toolCallId", "delta"], value);
632
- requireOptionalStrings(event, ["callId", "toolName"], value);
633
- requireOptionalStrings(event, ["signature"], value);
634
- requireOneOf(event.mode, ["append", "replace"], "tool_call_delta.mode", value);
635
- break;
636
- case "tool_call_end":
637
- requireEventKeys(event, [
638
- "messageId",
639
- "partId",
640
- "toolCallId",
641
- "callId",
642
- "toolName",
643
- "input",
644
- "signature"
645
- ]);
646
- requireStrings(event, ["messageId", "partId", "toolCallId", "toolName"], value);
647
- requireOptionalStrings(event, ["callId", "signature"], value);
648
- if (!isJsonValue2(event.input)) invalid("tool_call_end.input", value);
649
- break;
650
- case "tool_result":
651
- requireEventKeys(event, [
652
- "messageId",
653
- "partId",
654
- "toolCallId",
655
- "callId",
656
- "internalCallId",
657
- "toolName",
658
- "input",
659
- "result"
660
- ]);
661
- requireStrings(event, ["messageId", "partId", "toolCallId", "toolName"], value);
662
- requireOptionalStrings(event, ["callId", "internalCallId"], value);
663
- if (!isJsonValue2(event.input)) invalid("tool_result.input", value);
664
- if (!isRecord(event.result)) invalid("tool_result.result", value);
665
- if (event.result.status === "success") {
666
- if (!hasOnlyKeys(event.result, ["status", "output", "content"]) || !isJsonValue2(event.result.output) || event.result.content !== void 0 && (!Array.isArray(event.result.content) || !event.result.content.every(isToolResultContent))) {
667
- invalid("tool_result.result", value);
668
- }
669
- } else if (event.result.status === "error") {
670
- if (!hasOnlyKeys(event.result, ["status", "error"]) || !isClientStreamError(event.result.error)) {
671
- invalid("tool_result.result", value);
672
- }
673
- } else {
674
- invalid("tool_result.result.status", value);
675
- }
676
- break;
677
- case "source":
678
- requireEventKeys(event, ["messageId", "partId", "source"]);
679
- requireStrings(event, ["messageId", "partId"], value);
680
- if (!isCompletionSource(event.source)) invalid("source.source", value);
681
- break;
682
- case "attachment":
683
- requireEventKeys(event, ["messageId", "partId", "attachment"]);
684
- requireStrings(event, ["messageId", "partId"], value);
685
- if (!isAttachment(event.attachment)) invalid("attachment.attachment", value);
686
- break;
687
- case "provider_tool_call":
688
- requireEventKeys(event, ["toolCall"]);
689
- if (!isProviderToolCall(event.toolCall)) invalid("provider_tool_call.toolCall", value);
690
- break;
691
- case "interaction":
692
- requireEventKeys(event, ["interaction"]);
693
- try {
694
- parseAgentInteractionRequest(event.interaction);
695
- } catch {
696
- invalid("interaction.interaction", value);
697
- }
698
- break;
699
- case "guardrail_decision":
700
- requireEventKeys(event, ["decision"]);
701
- if (!isGuardrailDecision(event.decision)) invalid("guardrail_decision.decision", value);
702
- break;
703
- case "data":
704
- requireEventKeys(event, ["name", "data", "transient"]);
705
- requireStrings(event, ["name"], value);
706
- if (!isJsonValue2(event.data)) invalid("data.data", value);
707
- if (event.transient !== void 0 && typeof event.transient !== "boolean") {
708
- invalid("data.transient", value);
709
- }
710
- return {
711
- ...event,
712
- data: parseDataEvent(event.name, event.data, options.dataSchemas, value)
713
- };
714
- case "message_end":
715
- requireEventKeys(event, [
716
- "messageId",
717
- "modelMessageId",
718
- "parts",
719
- "usage",
720
- "contextUsage",
721
- "metadata"
722
- ]);
723
- requireStrings(event, ["messageId"], value);
724
- requireOptionalStrings(event, ["modelMessageId"], value);
725
- if (event.parts !== void 0) {
726
- if (!Array.isArray(event.parts)) invalid("message_end.parts", value);
727
- const parts = event.parts.map(
728
- (part) => parseUIMessagePart(part, options.dataSchemas, value)
729
- );
730
- validateUsageAndContext(event, value);
731
- return parseEventMetadata(
732
- { ...event, parts },
733
- options.metadataSchema,
734
- value
735
- );
736
- }
737
- validateUsageAndContext(event, value);
738
- break;
739
- case "turn_end":
740
- requireEventKeys(event, ["usage", "contextUsage", "firstDeltaMs"]);
741
- if (!isPositiveEventId(event.turn)) invalid("turn_end.turn", value);
742
- if (event.firstDeltaMs !== void 0 && !isNonnegativeNumber(event.firstDeltaMs)) {
743
- invalid("turn_end.firstDeltaMs", value);
744
- }
745
- validateUsageAndContext(event, value);
746
- break;
747
- case "memory_compaction":
748
- requireEventKeys(event, [
749
- "originalMessageCount",
750
- "compactedMessageCount",
751
- "retainedMessageCount",
752
- "originalTokenCount",
753
- "compactedTokenCount",
754
- "retainedTokenCount",
755
- "resultTokenCount",
756
- "attempts",
757
- "usage"
758
- ]);
759
- validateMemoryCompactionInfo(event, value);
760
- break;
761
- case "run_end":
762
- requireEventKeys(event, [
763
- "status",
764
- "text",
765
- "output",
766
- "usage",
767
- "contextUsage",
768
- "trace",
769
- "memoryCompaction",
770
- "metadata"
771
- ]);
772
- requireOneOf(
773
- event.status,
774
- ["completed", "blocked", "suspended", "cancelled", "error"],
775
- "run_end.status",
776
- value
777
- );
778
- requireOptionalStrings(event, ["text"], value);
779
- validateUsageAndContext(event, value);
780
- if (event.trace !== void 0 && !isTrace(event.trace)) invalid("run_end.trace", value);
781
- if (event.memoryCompaction !== void 0) {
782
- if (!isRecord(event.memoryCompaction)) invalid("run_end.memoryCompaction", value);
783
- requireOnlyKeys(
784
- event.memoryCompaction,
785
- [
786
- "originalMessageCount",
787
- "compactedMessageCount",
788
- "retainedMessageCount",
789
- "originalTokenCount",
790
- "compactedTokenCount",
791
- "retainedTokenCount",
792
- "resultTokenCount",
793
- "attempts",
794
- "usage"
795
- ],
796
- "run_end.memoryCompaction"
797
- );
798
- validateMemoryCompactionInfo(event.memoryCompaction, value);
799
- }
800
- break;
801
- case "error":
802
- requireEventKeys(event, ["error", "usage"]);
803
- if (!isClientStreamError(event.error)) invalid("error.error", value);
804
- if (event.usage !== void 0 && !isUsage(event.usage)) invalid("error.usage", value);
805
- break;
806
- default:
807
- throw new ClientProtocolError(`Unknown client stream event type "${event.type}".`, value);
808
- }
809
- return parseEventMetadata(event, options.metadataSchema, value);
110
+ const event = requireRecord(value, "Client stream event");
111
+ if (!isJsonValue$1(event)) throw new ClientProtocolError("Client stream events must be strict JSON values.", value);
112
+ if (typeof event.type !== "string" || typeof event.runId !== "string") throw new ClientProtocolError("Client stream events require type and runId.", value);
113
+ if (event.turn !== void 0 && !isPositiveEventId(event.turn)) throw new ClientProtocolError("Client stream event.turn must be a positive safe integer.", value);
114
+ if (event.scope !== void 0 && !isScope(event.scope)) throw new ClientProtocolError("Client stream event.scope is invalid.", value);
115
+ switch (event.type) {
116
+ case "run_start":
117
+ requireEventKeys(event, ["source", "metadata"]);
118
+ requireOneOf(event.source, ["completion", "agent"], "run_start.source", value);
119
+ break;
120
+ case "turn_start":
121
+ requireEventKeys(event, []);
122
+ if (!isPositiveEventId(event.turn)) invalid("turn_start.turn", value);
123
+ break;
124
+ case "generation_start":
125
+ requireEventKeys(event, ["model"]);
126
+ if (event.model !== void 0 && (!isRecord$1(event.model) || !hasOnlyKeys(event.model, ["provider", "modelId"]) || typeof event.model.provider !== "string" || typeof event.model.modelId !== "string")) invalid("generation_start.model", value);
127
+ break;
128
+ case "message_reset":
129
+ requireEventKeys(event, ["messageId"]);
130
+ requireStrings(event, ["messageId"], value);
131
+ break;
132
+ case "message_start":
133
+ requireEventKeys(event, [
134
+ "messageId",
135
+ "role",
136
+ "metadata"
137
+ ]);
138
+ requireStrings(event, ["messageId"], value);
139
+ if (event.role !== "assistant") invalid("message_start.role", value);
140
+ break;
141
+ case "text_start":
142
+ requireEventKeys(event, ["messageId", "partId"]);
143
+ requireStrings(event, ["messageId", "partId"], value);
144
+ break;
145
+ case "text_delta":
146
+ requireEventKeys(event, [
147
+ "messageId",
148
+ "partId",
149
+ "delta"
150
+ ]);
151
+ requireStrings(event, [
152
+ "messageId",
153
+ "partId",
154
+ "delta"
155
+ ], value);
156
+ break;
157
+ case "reasoning_delta":
158
+ requireEventKeys(event, [
159
+ "messageId",
160
+ "partId",
161
+ "delta",
162
+ "contentType",
163
+ "signature"
164
+ ]);
165
+ requireStrings(event, [
166
+ "messageId",
167
+ "partId",
168
+ "delta"
169
+ ], value);
170
+ requireOptionalStrings(event, ["signature"], value);
171
+ if (event.contentType !== void 0 && ![
172
+ "text",
173
+ "summary",
174
+ "encrypted",
175
+ "redacted"
176
+ ].includes(event.contentType)) invalid("reasoning_delta.contentType", value);
177
+ break;
178
+ case "text_end":
179
+ requireEventKeys(event, [
180
+ "messageId",
181
+ "partId",
182
+ "text",
183
+ "signature"
184
+ ]);
185
+ requireStrings(event, ["messageId", "partId"], value);
186
+ requireOptionalStrings(event, ["text", "signature"], value);
187
+ break;
188
+ case "reasoning_start":
189
+ requireEventKeys(event, [
190
+ "messageId",
191
+ "partId",
192
+ "reasoningId"
193
+ ]);
194
+ requireStrings(event, ["messageId", "partId"], value);
195
+ requireOptionalStrings(event, ["reasoningId"], value);
196
+ break;
197
+ case "reasoning_end":
198
+ requireEventKeys(event, [
199
+ "messageId",
200
+ "partId",
201
+ "text",
202
+ "content"
203
+ ]);
204
+ requireStrings(event, ["messageId", "partId"], value);
205
+ requireOptionalStrings(event, ["text"], value);
206
+ if (event.content !== void 0 && (!Array.isArray(event.content) || !event.content.every(isReasoningContent))) invalid("reasoning_end.content", value);
207
+ break;
208
+ case "tool_call_start":
209
+ requireEventKeys(event, [
210
+ "messageId",
211
+ "partId",
212
+ "toolCallId",
213
+ "callId",
214
+ "toolName"
215
+ ]);
216
+ requireStrings(event, [
217
+ "messageId",
218
+ "partId",
219
+ "toolCallId"
220
+ ], value);
221
+ requireOptionalStrings(event, ["callId", "toolName"], value);
222
+ break;
223
+ case "tool_call_delta":
224
+ requireEventKeys(event, [
225
+ "messageId",
226
+ "partId",
227
+ "toolCallId",
228
+ "callId",
229
+ "toolName",
230
+ "delta",
231
+ "mode",
232
+ "signature"
233
+ ]);
234
+ requireStrings(event, [
235
+ "messageId",
236
+ "partId",
237
+ "toolCallId",
238
+ "delta"
239
+ ], value);
240
+ requireOptionalStrings(event, ["callId", "toolName"], value);
241
+ requireOptionalStrings(event, ["signature"], value);
242
+ requireOneOf(event.mode, ["append", "replace"], "tool_call_delta.mode", value);
243
+ break;
244
+ case "tool_call_end":
245
+ requireEventKeys(event, [
246
+ "messageId",
247
+ "partId",
248
+ "toolCallId",
249
+ "callId",
250
+ "toolName",
251
+ "input",
252
+ "signature"
253
+ ]);
254
+ requireStrings(event, [
255
+ "messageId",
256
+ "partId",
257
+ "toolCallId",
258
+ "toolName"
259
+ ], value);
260
+ requireOptionalStrings(event, ["callId", "signature"], value);
261
+ if (!isJsonValue$1(event.input)) invalid("tool_call_end.input", value);
262
+ break;
263
+ case "tool_result":
264
+ requireEventKeys(event, [
265
+ "messageId",
266
+ "partId",
267
+ "toolCallId",
268
+ "callId",
269
+ "internalCallId",
270
+ "toolName",
271
+ "input",
272
+ "result"
273
+ ]);
274
+ requireStrings(event, [
275
+ "messageId",
276
+ "partId",
277
+ "toolCallId",
278
+ "toolName"
279
+ ], value);
280
+ requireOptionalStrings(event, ["callId", "internalCallId"], value);
281
+ if (!isJsonValue$1(event.input)) invalid("tool_result.input", value);
282
+ if (!isRecord$1(event.result)) invalid("tool_result.result", value);
283
+ if (event.result.status === "success") {
284
+ if (!hasOnlyKeys(event.result, [
285
+ "status",
286
+ "output",
287
+ "content"
288
+ ]) || !isJsonValue$1(event.result.output) || event.result.content !== void 0 && (!Array.isArray(event.result.content) || !event.result.content.every(isToolResultContent))) invalid("tool_result.result", value);
289
+ } else if (event.result.status === "error") {
290
+ if (!hasOnlyKeys(event.result, ["status", "error"]) || !isClientStreamError(event.result.error)) invalid("tool_result.result", value);
291
+ } else invalid("tool_result.result.status", value);
292
+ break;
293
+ case "source":
294
+ requireEventKeys(event, [
295
+ "messageId",
296
+ "partId",
297
+ "source"
298
+ ]);
299
+ requireStrings(event, ["messageId", "partId"], value);
300
+ if (!isCompletionSource(event.source)) invalid("source.source", value);
301
+ break;
302
+ case "attachment":
303
+ requireEventKeys(event, [
304
+ "messageId",
305
+ "partId",
306
+ "attachment"
307
+ ]);
308
+ requireStrings(event, ["messageId", "partId"], value);
309
+ if (!isAttachment(event.attachment)) invalid("attachment.attachment", value);
310
+ break;
311
+ case "provider_tool_call":
312
+ requireEventKeys(event, ["toolCall"]);
313
+ if (!isProviderToolCall(event.toolCall)) invalid("provider_tool_call.toolCall", value);
314
+ break;
315
+ case "interaction":
316
+ requireEventKeys(event, ["interaction"]);
317
+ try {
318
+ parseAgentInteractionRequest(event.interaction);
319
+ } catch {
320
+ invalid("interaction.interaction", value);
321
+ }
322
+ break;
323
+ case "guardrail_decision":
324
+ requireEventKeys(event, ["decision"]);
325
+ if (!isGuardrailDecision(event.decision)) invalid("guardrail_decision.decision", value);
326
+ break;
327
+ case "data":
328
+ requireEventKeys(event, [
329
+ "name",
330
+ "data",
331
+ "transient"
332
+ ]);
333
+ requireStrings(event, ["name"], value);
334
+ if (!isJsonValue$1(event.data)) invalid("data.data", value);
335
+ if (event.transient !== void 0 && typeof event.transient !== "boolean") invalid("data.transient", value);
336
+ return {
337
+ ...event,
338
+ data: parseDataEvent(event.name, event.data, options.dataSchemas, value)
339
+ };
340
+ case "message_end":
341
+ requireEventKeys(event, [
342
+ "messageId",
343
+ "modelMessageId",
344
+ "parts",
345
+ "usage",
346
+ "contextUsage",
347
+ "metadata"
348
+ ]);
349
+ requireStrings(event, ["messageId"], value);
350
+ requireOptionalStrings(event, ["modelMessageId"], value);
351
+ if (event.parts !== void 0) {
352
+ if (!Array.isArray(event.parts)) invalid("message_end.parts", value);
353
+ const parts = event.parts.map((part) => parseUIMessagePart(part, options.dataSchemas, value));
354
+ validateUsageAndContext(event, value);
355
+ return parseEventMetadata({
356
+ ...event,
357
+ parts
358
+ }, options.metadataSchema, value);
359
+ }
360
+ validateUsageAndContext(event, value);
361
+ break;
362
+ case "turn_end":
363
+ requireEventKeys(event, [
364
+ "usage",
365
+ "contextUsage",
366
+ "firstDeltaMs"
367
+ ]);
368
+ if (!isPositiveEventId(event.turn)) invalid("turn_end.turn", value);
369
+ if (event.firstDeltaMs !== void 0 && !isNonnegativeNumber(event.firstDeltaMs)) invalid("turn_end.firstDeltaMs", value);
370
+ validateUsageAndContext(event, value);
371
+ break;
372
+ case "memory_compaction":
373
+ requireEventKeys(event, [
374
+ "originalMessageCount",
375
+ "compactedMessageCount",
376
+ "retainedMessageCount",
377
+ "originalTokenCount",
378
+ "compactedTokenCount",
379
+ "retainedTokenCount",
380
+ "resultTokenCount",
381
+ "attempts",
382
+ "usage"
383
+ ]);
384
+ validateMemoryCompactionInfo(event, value);
385
+ break;
386
+ case "run_end":
387
+ requireEventKeys(event, [
388
+ "status",
389
+ "text",
390
+ "output",
391
+ "usage",
392
+ "contextUsage",
393
+ "trace",
394
+ "memoryCompaction",
395
+ "metadata"
396
+ ]);
397
+ requireOneOf(event.status, [
398
+ "completed",
399
+ "blocked",
400
+ "suspended",
401
+ "cancelled",
402
+ "error"
403
+ ], "run_end.status", value);
404
+ requireOptionalStrings(event, ["text"], value);
405
+ validateUsageAndContext(event, value);
406
+ if (event.trace !== void 0 && !isTrace(event.trace)) invalid("run_end.trace", value);
407
+ if (event.memoryCompaction !== void 0) {
408
+ if (!isRecord$1(event.memoryCompaction)) invalid("run_end.memoryCompaction", value);
409
+ requireOnlyKeys(event.memoryCompaction, [
410
+ "originalMessageCount",
411
+ "compactedMessageCount",
412
+ "retainedMessageCount",
413
+ "originalTokenCount",
414
+ "compactedTokenCount",
415
+ "retainedTokenCount",
416
+ "resultTokenCount",
417
+ "attempts",
418
+ "usage"
419
+ ], "run_end.memoryCompaction");
420
+ validateMemoryCompactionInfo(event.memoryCompaction, value);
421
+ }
422
+ break;
423
+ case "error":
424
+ requireEventKeys(event, ["error", "usage"]);
425
+ if (!isClientStreamError(event.error)) invalid("error.error", value);
426
+ if (event.usage !== void 0 && !isUsage(event.usage)) invalid("error.usage", value);
427
+ break;
428
+ default: throw new ClientProtocolError(`Unknown client stream event type "${event.type}".`, value);
429
+ }
430
+ return parseEventMetadata(event, options.metadataSchema, value);
810
431
  }
811
432
  function parseClientStreamFrame(value, options = {}) {
812
- const frame = requireRecord(value, "Client stream frame");
813
- if (!isJsonValue2(frame)) {
814
- throw new ClientProtocolError("Client stream frames must be strict JSON values.", value);
815
- }
816
- if (typeof frame.type !== "string") {
817
- throw new ClientProtocolError("Client stream frames require type.", value);
818
- }
819
- if (frame.type === "stream_start") {
820
- requireOnlyKeys(
821
- frame,
822
- ["type", "protocol", "streamId", "eventId", "resumable"],
823
- "stream_start frame"
824
- );
825
- if (frame.protocol === "anvia.client.v1" || frame.protocol === "anvia.client.v2") {
826
- throw new ClientProtocolError(
827
- `Client stream protocol ${frame.protocol.slice(-2)} is not supported.`,
828
- value
829
- );
830
- }
831
- if (frame.protocol !== CLIENT_STREAM_PROTOCOL || typeof frame.streamId !== "string" || frame.eventId !== 0 || typeof frame.resumable !== "boolean") {
832
- throw new ClientProtocolError("Invalid client stream_start frame.", value);
833
- }
834
- return frame;
835
- }
836
- if (frame.type === "stream_event") {
837
- requireOnlyKeys(frame, ["type", "streamId", "eventId", "event"], "stream_event frame");
838
- if (typeof frame.streamId !== "string" || !isPositiveEventId(frame.eventId)) {
839
- throw new ClientProtocolError("Invalid client stream_event frame.", value);
840
- }
841
- const event = parseClientStreamEvent(frame.event, options);
842
- return { ...frame, event };
843
- }
844
- if (frame.type === "stream_end") {
845
- requireOnlyKeys(frame, ["type", "streamId", "eventId", "status"], "stream_end frame");
846
- if (typeof frame.streamId !== "string" || !isEventId(frame.eventId)) {
847
- throw new ClientProtocolError("Invalid client stream_end frame.", value);
848
- }
849
- requireOneOf(frame.status, ["completed", "error", "missing"], "stream_end.status", value);
850
- return frame;
851
- }
852
- throw new ClientProtocolError(`Unknown client stream frame type "${frame.type}".`, value);
433
+ const frame = requireRecord(value, "Client stream frame");
434
+ if (!isJsonValue$1(frame)) throw new ClientProtocolError("Client stream frames must be strict JSON values.", value);
435
+ if (typeof frame.type !== "string") throw new ClientProtocolError("Client stream frames require type.", value);
436
+ if (frame.type === "stream_start") {
437
+ requireOnlyKeys(frame, [
438
+ "type",
439
+ "protocol",
440
+ "streamId",
441
+ "eventId",
442
+ "resumable"
443
+ ], "stream_start frame");
444
+ if (frame.protocol === "anvia.client.v1" || frame.protocol === "anvia.client.v2") throw new ClientProtocolError(`Client stream protocol ${frame.protocol.slice(-2)} is not supported.`, value);
445
+ if (frame.protocol !== "anvia.client.v3" || typeof frame.streamId !== "string" || frame.eventId !== 0 || typeof frame.resumable !== "boolean") throw new ClientProtocolError("Invalid client stream_start frame.", value);
446
+ return frame;
447
+ }
448
+ if (frame.type === "stream_event") {
449
+ requireOnlyKeys(frame, [
450
+ "type",
451
+ "streamId",
452
+ "eventId",
453
+ "event"
454
+ ], "stream_event frame");
455
+ if (typeof frame.streamId !== "string" || !isPositiveEventId(frame.eventId)) throw new ClientProtocolError("Invalid client stream_event frame.", value);
456
+ const event = parseClientStreamEvent(frame.event, options);
457
+ return {
458
+ ...frame,
459
+ event
460
+ };
461
+ }
462
+ if (frame.type === "stream_end") {
463
+ requireOnlyKeys(frame, [
464
+ "type",
465
+ "streamId",
466
+ "eventId",
467
+ "status"
468
+ ], "stream_end frame");
469
+ if (typeof frame.streamId !== "string" || !isEventId(frame.eventId)) throw new ClientProtocolError("Invalid client stream_end frame.", value);
470
+ requireOneOf(frame.status, [
471
+ "completed",
472
+ "error",
473
+ "missing"
474
+ ], "stream_end.status", value);
475
+ return frame;
476
+ }
477
+ throw new ClientProtocolError(`Unknown client stream frame type "${frame.type}".`, value);
853
478
  }
854
479
  function maskedClientError() {
855
- return { message: "An unexpected error occurred." };
480
+ return { message: "An unexpected error occurred." };
856
481
  }
857
482
  function normalizeClientError(value) {
858
- if (value instanceof Error) return value;
859
- if (isClientStreamError(value)) {
860
- const error = new Error(value.message);
861
- if (value.name !== void 0) error.name = value.name;
862
- return error;
863
- }
864
- return new Error(typeof value === "string" ? value : "An unexpected error occurred.");
483
+ if (value instanceof Error) return value;
484
+ if (isClientStreamError(value)) {
485
+ const error = new Error(value.message);
486
+ if (value.name !== void 0) error.name = value.name;
487
+ return error;
488
+ }
489
+ return new Error(typeof value === "string" ? value : "An unexpected error occurred.");
865
490
  }
866
491
  function parseDataEvent(name, data, schemas, value) {
867
- if (schemas === void 0) return data;
868
- const schema = schemas[name];
869
- if (schema === void 0) {
870
- throw new ClientProtocolError(`Invalid data event "${name}".`, value);
871
- }
872
- const parsed = schema.safeParse(data);
873
- if (parsed.success !== true || !isJsonValue2(parsed.data)) {
874
- throw new ClientProtocolError(`Invalid data event "${name}".`, value);
875
- }
876
- return parsed.data;
492
+ if (schemas === void 0) return data;
493
+ const schema = schemas[name];
494
+ if (schema === void 0) throw new ClientProtocolError(`Invalid data event "${name}".`, value);
495
+ const parsed = schema.safeParse(data);
496
+ if (parsed.success !== true || !isJsonValue$1(parsed.data)) throw new ClientProtocolError(`Invalid data event "${name}".`, value);
497
+ return parsed.data;
877
498
  }
878
499
  function parseUIMessagePart(value, schemas, root) {
879
- if (!isUIMessagePart(value)) {
880
- throw new ClientProtocolError("UI message contains an invalid part.", root);
881
- }
882
- if (value.type !== "data") {
883
- return value;
884
- }
885
- return {
886
- ...value,
887
- data: parseDataEvent(value.name, value.data, schemas, root)
888
- };
500
+ if (!isUIMessagePart(value)) throw new ClientProtocolError("UI message contains an invalid part.", root);
501
+ if (value.type !== "data") return value;
502
+ return {
503
+ ...value,
504
+ data: parseDataEvent(value.name, value.data, schemas, root)
505
+ };
889
506
  }
890
507
  function parseMetadata(value, schema, root) {
891
- if (schema === void 0) {
892
- if (!isJsonObject(value)) {
893
- throw new ClientProtocolError("Client metadata must be a JSON object.", root);
894
- }
895
- return value;
896
- }
897
- const parsed = schema.safeParse(value);
898
- if (parsed.success !== true || !isJsonObject(parsed.data)) {
899
- throw new ClientProtocolError("Invalid client metadata.", root);
900
- }
901
- return parsed.data;
508
+ if (schema === void 0) {
509
+ if (!isJsonObject(value)) throw new ClientProtocolError("Client metadata must be a JSON object.", root);
510
+ return value;
511
+ }
512
+ const parsed = schema.safeParse(value);
513
+ if (parsed.success !== true || !isJsonObject(parsed.data)) throw new ClientProtocolError("Invalid client metadata.", root);
514
+ return parsed.data;
902
515
  }
903
516
  function parseEventMetadata(event, schema, root) {
904
- if (event.metadata === void 0) return event;
905
- return { ...event, metadata: parseMetadata(event.metadata, schema, root) };
517
+ if (event.metadata === void 0) return event;
518
+ return {
519
+ ...event,
520
+ metadata: parseMetadata(event.metadata, schema, root)
521
+ };
906
522
  }
907
523
  function isUIMessageGeneration(value) {
908
- if (!isRecord(value)) return false;
909
- if (!hasOnlyKeys(value, ["runId", "status", "usage", "contextUsage", "trace", "memoryCompaction"])) {
910
- return false;
911
- }
912
- return (value.runId === void 0 || typeof value.runId === "string") && (value.status === void 0 || ["completed", "blocked", "suspended", "cancelled", "error"].includes(
913
- value.status
914
- )) && (value.usage === void 0 || isUsage(value.usage)) && (value.contextUsage === void 0 || isContextUsage(value.contextUsage)) && (value.trace === void 0 || isTrace(value.trace)) && (value.memoryCompaction === void 0 || isRecord(value.memoryCompaction) && validateMemoryCompactionForGuard(value.memoryCompaction));
524
+ if (!isRecord$1(value)) return false;
525
+ if (!hasOnlyKeys(value, [
526
+ "runId",
527
+ "status",
528
+ "usage",
529
+ "contextUsage",
530
+ "trace",
531
+ "memoryCompaction"
532
+ ])) return false;
533
+ return (value.runId === void 0 || typeof value.runId === "string") && (value.status === void 0 || [
534
+ "completed",
535
+ "blocked",
536
+ "suspended",
537
+ "cancelled",
538
+ "error"
539
+ ].includes(value.status)) && (value.usage === void 0 || isUsage(value.usage)) && (value.contextUsage === void 0 || isContextUsage(value.contextUsage)) && (value.trace === void 0 || isTrace(value.trace)) && (value.memoryCompaction === void 0 || isRecord$1(value.memoryCompaction) && validateMemoryCompactionForGuard(value.memoryCompaction));
915
540
  }
916
541
  function validateMemoryCompactionForGuard(value) {
917
- try {
918
- requireOnlyKeys(
919
- value,
920
- [
921
- "originalMessageCount",
922
- "compactedMessageCount",
923
- "retainedMessageCount",
924
- "originalTokenCount",
925
- "compactedTokenCount",
926
- "retainedTokenCount",
927
- "resultTokenCount",
928
- "attempts",
929
- "usage"
930
- ],
931
- "memory compaction"
932
- );
933
- validateMemoryCompactionInfo(value, value);
934
- return true;
935
- } catch {
936
- return false;
937
- }
542
+ try {
543
+ requireOnlyKeys(value, [
544
+ "originalMessageCount",
545
+ "compactedMessageCount",
546
+ "retainedMessageCount",
547
+ "originalTokenCount",
548
+ "compactedTokenCount",
549
+ "retainedTokenCount",
550
+ "resultTokenCount",
551
+ "attempts",
552
+ "usage"
553
+ ], "memory compaction");
554
+ validateMemoryCompactionInfo(value, value);
555
+ return true;
556
+ } catch {
557
+ return false;
558
+ }
938
559
  }
939
560
  function isJsonObject(value) {
940
- return isRecord(value) && isJsonValue2(value);
561
+ return isRecord$1(value) && isJsonValue$1(value);
941
562
  }
942
563
  function isClientStreamError(value) {
943
- return isRecord(value) && hasOnlyKeys(value, ["name", "message", "code", "retryable", "details"]) && typeof value.message === "string" && (value.name === void 0 || typeof value.name === "string") && (value.code === void 0 || typeof value.code === "string") && (value.retryable === void 0 || typeof value.retryable === "boolean") && (value.details === void 0 || isJsonValue2(value.details));
564
+ return isRecord$1(value) && hasOnlyKeys(value, [
565
+ "name",
566
+ "message",
567
+ "code",
568
+ "retryable",
569
+ "details"
570
+ ]) && typeof value.message === "string" && (value.name === void 0 || typeof value.name === "string") && (value.code === void 0 || typeof value.code === "string") && (value.retryable === void 0 || typeof value.retryable === "boolean") && (value.details === void 0 || isJsonValue$1(value.details));
944
571
  }
945
572
  function isScope(value) {
946
- if (!isRecord(value)) return false;
947
- const keys = [
948
- "agentId",
949
- "agentName",
950
- "parentRunId",
951
- "parentToolName",
952
- "parentToolCallId",
953
- "parentInternalToolCallId"
954
- ];
955
- return hasOnlyKeys(value, keys) && keys.every((key) => value[key] === void 0 || typeof value[key] === "string");
573
+ if (!isRecord$1(value)) return false;
574
+ const keys = [
575
+ "agentId",
576
+ "agentName",
577
+ "parentRunId",
578
+ "parentToolName",
579
+ "parentToolCallId",
580
+ "parentInternalToolCallId"
581
+ ];
582
+ return hasOnlyKeys(value, keys) && keys.every((key) => value[key] === void 0 || typeof value[key] === "string");
956
583
  }
957
584
  function isAttachment(value) {
958
- if (!isRecord(value) || typeof value.id !== "string") return false;
959
- if (value.type !== "image" && value.type !== "document" && value.type !== "file") return false;
960
- return hasOnlyKeys(value, [
961
- "id",
962
- "type",
963
- "name",
964
- "mediaType",
965
- "url",
966
- "data",
967
- "text",
968
- "detail",
969
- "metadata"
970
- ]) && (value.name === void 0 || typeof value.name === "string") && (value.mediaType === void 0 || typeof value.mediaType === "string") && (value.url === void 0 || typeof value.url === "string") && (value.data === void 0 || typeof value.data === "string") && (value.text === void 0 || typeof value.text === "string") && (value.detail === void 0 || ["auto", "low", "high"].includes(value.detail)) && (value.metadata === void 0 || isJsonValue2(value.metadata));
585
+ if (!isRecord$1(value) || typeof value.id !== "string") return false;
586
+ if (value.type !== "image" && value.type !== "document" && value.type !== "file") return false;
587
+ return hasOnlyKeys(value, [
588
+ "id",
589
+ "type",
590
+ "name",
591
+ "mediaType",
592
+ "url",
593
+ "data",
594
+ "text",
595
+ "detail",
596
+ "metadata"
597
+ ]) && (value.name === void 0 || typeof value.name === "string") && (value.mediaType === void 0 || typeof value.mediaType === "string") && (value.url === void 0 || typeof value.url === "string") && (value.data === void 0 || typeof value.data === "string") && (value.text === void 0 || typeof value.text === "string") && (value.detail === void 0 || [
598
+ "auto",
599
+ "low",
600
+ "high"
601
+ ].includes(value.detail)) && (value.metadata === void 0 || isJsonValue$1(value.metadata));
971
602
  }
972
603
  function isUIMessagePart(value) {
973
- if (!isRecord(value) || typeof value.id !== "string" || typeof value.type !== "string") {
974
- return false;
975
- }
976
- if (value.type === "text") {
977
- return hasOnlyKeys(value, ["id", "type", "text", "signature"]) && typeof value.text === "string" && (value.signature === void 0 || typeof value.signature === "string");
978
- }
979
- if (value.type === "reasoning") {
980
- return hasOnlyKeys(value, ["id", "type", "text", "reasoningId", "content"]) && typeof value.text === "string" && (value.reasoningId === void 0 || typeof value.reasoningId === "string") && (value.content === void 0 || Array.isArray(value.content) && value.content.every(isReasoningContent));
981
- }
982
- if (value.type === "source") {
983
- return hasOnlyKeys(value, ["id", "type", "source"]) && isCompletionSource(value.source);
984
- }
985
- if (value.type === "data") {
986
- return hasOnlyKeys(value, ["id", "type", "name", "data"]) && typeof value.name === "string" && isJsonValue2(value.data);
987
- }
988
- if (value.type === "attachment") {
989
- return hasOnlyKeys(value, ["id", "type", "attachment"]) && isAttachment(value.attachment);
990
- }
991
- if (value.type === "error") {
992
- return hasOnlyKeys(value, ["id", "type", "error"]) && isClientStreamError(value.error);
993
- }
994
- if (value.type !== "tool" || !hasOnlyKeys(value, [
995
- "id",
996
- "type",
997
- "toolName",
998
- "toolCallId",
999
- "callId",
1000
- "internalCallId",
1001
- "turn",
1002
- "state",
1003
- "input",
1004
- "output",
1005
- "resultContent",
1006
- "signature",
1007
- "error"
1008
- ]) || typeof value.toolName !== "string" || typeof value.toolCallId !== "string" || value.callId !== void 0 && typeof value.callId !== "string" || value.internalCallId !== void 0 && typeof value.internalCallId !== "string" || value.turn !== void 0 && !isPositiveEventId(value.turn) || value.signature !== void 0 && typeof value.signature !== "string") {
1009
- return false;
1010
- }
1011
- if (value.state === "input-streaming") {
1012
- return typeof value.input === "string" && value.output === void 0 && value.resultContent === void 0 && value.error === void 0;
1013
- }
1014
- if (value.state === "input-available") {
1015
- return isJsonValue2(value.input) && value.output === void 0 && value.resultContent === void 0 && value.error === void 0;
1016
- }
1017
- if (value.state === "output-available") {
1018
- return isJsonValue2(value.input) && isJsonValue2(value.output) && (value.resultContent === void 0 || Array.isArray(value.resultContent) && value.resultContent.every(isToolResultContent)) && value.error === void 0;
1019
- }
1020
- return value.state === "error" && isJsonValue2(value.input) && value.output === void 0 && value.resultContent === void 0 && isClientStreamError(value.error);
604
+ if (!isRecord$1(value) || typeof value.id !== "string" || typeof value.type !== "string") return false;
605
+ if (value.type === "text") return hasOnlyKeys(value, [
606
+ "id",
607
+ "type",
608
+ "text",
609
+ "signature"
610
+ ]) && typeof value.text === "string" && (value.signature === void 0 || typeof value.signature === "string");
611
+ if (value.type === "reasoning") return hasOnlyKeys(value, [
612
+ "id",
613
+ "type",
614
+ "text",
615
+ "reasoningId",
616
+ "content"
617
+ ]) && typeof value.text === "string" && (value.reasoningId === void 0 || typeof value.reasoningId === "string") && (value.content === void 0 || Array.isArray(value.content) && value.content.every(isReasoningContent));
618
+ if (value.type === "source") return hasOnlyKeys(value, [
619
+ "id",
620
+ "type",
621
+ "source"
622
+ ]) && isCompletionSource(value.source);
623
+ if (value.type === "data") return hasOnlyKeys(value, [
624
+ "id",
625
+ "type",
626
+ "name",
627
+ "data"
628
+ ]) && typeof value.name === "string" && isJsonValue$1(value.data);
629
+ if (value.type === "attachment") return hasOnlyKeys(value, [
630
+ "id",
631
+ "type",
632
+ "attachment"
633
+ ]) && isAttachment(value.attachment);
634
+ if (value.type === "error") return hasOnlyKeys(value, [
635
+ "id",
636
+ "type",
637
+ "error"
638
+ ]) && isClientStreamError(value.error);
639
+ if (value.type !== "tool" || !hasOnlyKeys(value, [
640
+ "id",
641
+ "type",
642
+ "toolName",
643
+ "toolCallId",
644
+ "callId",
645
+ "internalCallId",
646
+ "turn",
647
+ "state",
648
+ "input",
649
+ "output",
650
+ "resultContent",
651
+ "signature",
652
+ "error"
653
+ ]) || typeof value.toolName !== "string" || typeof value.toolCallId !== "string" || value.callId !== void 0 && typeof value.callId !== "string" || value.internalCallId !== void 0 && typeof value.internalCallId !== "string" || value.turn !== void 0 && !isPositiveEventId(value.turn) || value.signature !== void 0 && typeof value.signature !== "string") return false;
654
+ if (value.state === "input-streaming") return typeof value.input === "string" && value.output === void 0 && value.resultContent === void 0 && value.error === void 0;
655
+ if (value.state === "input-available") return isJsonValue$1(value.input) && value.output === void 0 && value.resultContent === void 0 && value.error === void 0;
656
+ if (value.state === "output-available") return isJsonValue$1(value.input) && isJsonValue$1(value.output) && (value.resultContent === void 0 || Array.isArray(value.resultContent) && value.resultContent.every(isToolResultContent)) && value.error === void 0;
657
+ return value.state === "error" && isJsonValue$1(value.input) && value.output === void 0 && value.resultContent === void 0 && isClientStreamError(value.error);
1021
658
  }
1022
659
  function isReasoningContent(value) {
1023
- if (!isRecord(value) || typeof value.type !== "string") return false;
1024
- if (value.type === "text") {
1025
- return hasOnlyKeys(value, ["type", "text", "signature"]) && typeof value.text === "string" && (value.signature === void 0 || typeof value.signature === "string");
1026
- }
1027
- if (value.type === "summary") {
1028
- return hasOnlyKeys(value, ["type", "text"]) && typeof value.text === "string";
1029
- }
1030
- if (value.type === "encrypted" || value.type === "redacted") {
1031
- return hasOnlyKeys(value, ["type", "data"]) && typeof value.data === "string";
1032
- }
1033
- return false;
660
+ if (!isRecord$1(value) || typeof value.type !== "string") return false;
661
+ if (value.type === "text") return hasOnlyKeys(value, [
662
+ "type",
663
+ "text",
664
+ "signature"
665
+ ]) && typeof value.text === "string" && (value.signature === void 0 || typeof value.signature === "string");
666
+ if (value.type === "summary") return hasOnlyKeys(value, ["type", "text"]) && typeof value.text === "string";
667
+ if (value.type === "encrypted" || value.type === "redacted") return hasOnlyKeys(value, ["type", "data"]) && typeof value.data === "string";
668
+ return false;
1034
669
  }
1035
670
  function isToolResultContent(value) {
1036
- if (!isRecord(value)) return false;
1037
- if (value.type === "text") {
1038
- return hasOnlyKeys(value, ["type", "text", "signature"]) && typeof value.text === "string" && (value.signature === void 0 || typeof value.signature === "string");
1039
- }
1040
- return value.type === "file" && hasOnlyKeys(value, ["type", "data", "mediaType", "filename"]) && isFileData(value.data) && typeof value.mediaType === "string" && (value.filename === void 0 || typeof value.filename === "string");
671
+ if (!isRecord$1(value)) return false;
672
+ if (value.type === "text") return hasOnlyKeys(value, [
673
+ "type",
674
+ "text",
675
+ "signature"
676
+ ]) && typeof value.text === "string" && (value.signature === void 0 || typeof value.signature === "string");
677
+ return value.type === "file" && hasOnlyKeys(value, [
678
+ "type",
679
+ "data",
680
+ "mediaType",
681
+ "filename"
682
+ ]) && isFileData(value.data) && typeof value.mediaType === "string" && (value.filename === void 0 || typeof value.filename === "string");
1041
683
  }
1042
684
  function isFileData(value) {
1043
- if (!isRecord(value)) return false;
1044
- if (value.type === "url") {
1045
- return hasOnlyKeys(value, ["type", "url"]) && typeof value.url === "string";
1046
- }
1047
- if (value.type === "data") {
1048
- return hasOnlyKeys(value, ["type", "data"]) && typeof value.data === "string";
1049
- }
1050
- return value.type === "text" && hasOnlyKeys(value, ["type", "text"]) && typeof value.text === "string";
685
+ if (!isRecord$1(value)) return false;
686
+ if (value.type === "url") return hasOnlyKeys(value, ["type", "url"]) && typeof value.url === "string";
687
+ if (value.type === "data") return hasOnlyKeys(value, ["type", "data"]) && typeof value.data === "string";
688
+ return value.type === "text" && hasOnlyKeys(value, ["type", "text"]) && typeof value.text === "string";
1051
689
  }
1052
690
  function isCompletionSource(value) {
1053
- return isRecord(value) && value.type === "url" && hasOnlyKeys(value, ["type", "url", "title", "id", "startIndex", "endIndex"]) && typeof value.url === "string" && (value.title === void 0 || typeof value.title === "string") && (value.id === void 0 || typeof value.id === "string") && (value.startIndex === void 0 || isNonnegativeNumber(value.startIndex)) && (value.endIndex === void 0 || isNonnegativeNumber(value.endIndex));
691
+ return isRecord$1(value) && value.type === "url" && hasOnlyKeys(value, [
692
+ "type",
693
+ "url",
694
+ "title",
695
+ "id",
696
+ "startIndex",
697
+ "endIndex"
698
+ ]) && typeof value.url === "string" && (value.title === void 0 || typeof value.title === "string") && (value.id === void 0 || typeof value.id === "string") && (value.startIndex === void 0 || isNonnegativeNumber(value.startIndex)) && (value.endIndex === void 0 || isNonnegativeNumber(value.endIndex));
1054
699
  }
1055
700
  function isProviderToolCall(value) {
1056
- return isRecord(value) && hasOnlyKeys(value, ["id", "name", "status", "details"]) && typeof value.id === "string" && typeof value.name === "string" && (value.status === void 0 || typeof value.status === "string") && (value.details === void 0 || isRecord(value.details) && isJsonValue2(value.details));
701
+ return isRecord$1(value) && hasOnlyKeys(value, [
702
+ "id",
703
+ "name",
704
+ "status",
705
+ "details"
706
+ ]) && typeof value.id === "string" && typeof value.name === "string" && (value.status === void 0 || typeof value.status === "string") && (value.details === void 0 || isRecord$1(value.details) && isJsonValue$1(value.details));
1057
707
  }
1058
708
  function isGuardrailDecision(value) {
1059
- return isRecord(value) && hasOnlyKeys(value, [
1060
- "policyId",
1061
- "guardrailId",
1062
- "boundary",
1063
- "mode",
1064
- "action",
1065
- "applied",
1066
- "reason",
1067
- "message",
1068
- "metadata",
1069
- "latencyMs"
1070
- ]) && typeof value.policyId === "string" && typeof value.guardrailId === "string" && (value.boundary === "input" || value.boundary === "output") && (value.mode === "enforce" || value.mode === "observe") && typeof value.action === "string" && ["allow", "block", "rewrite", "error"].includes(value.action) && typeof value.applied === "boolean" && (value.reason === void 0 || typeof value.reason === "string") && (value.message === void 0 || typeof value.message === "string") && (value.metadata === void 0 || isRecord(value.metadata) && isJsonValue2(value.metadata)) && isNonnegativeNumber(value.latencyMs);
709
+ return isRecord$1(value) && hasOnlyKeys(value, [
710
+ "policyId",
711
+ "guardrailId",
712
+ "boundary",
713
+ "mode",
714
+ "action",
715
+ "applied",
716
+ "reason",
717
+ "message",
718
+ "metadata",
719
+ "latencyMs"
720
+ ]) && typeof value.policyId === "string" && typeof value.guardrailId === "string" && (value.boundary === "input" || value.boundary === "output") && (value.mode === "enforce" || value.mode === "observe") && typeof value.action === "string" && [
721
+ "allow",
722
+ "block",
723
+ "rewrite",
724
+ "error"
725
+ ].includes(value.action) && typeof value.applied === "boolean" && (value.reason === void 0 || typeof value.reason === "string") && (value.message === void 0 || typeof value.message === "string") && (value.metadata === void 0 || isRecord$1(value.metadata) && isJsonValue$1(value.metadata)) && isNonnegativeNumber(value.latencyMs);
1071
726
  }
1072
727
  function isUsage(value) {
1073
- if (!isRecord(value) || !hasOnlyKeys(value, [
1074
- "inputTokens",
1075
- "outputTokens",
1076
- "totalTokens",
1077
- "cachedInputTokens",
1078
- "cacheCreationInputTokens",
1079
- "details"
1080
- ]) || ![
1081
- value.inputTokens,
1082
- value.outputTokens,
1083
- value.totalTokens,
1084
- value.cachedInputTokens,
1085
- value.cacheCreationInputTokens
1086
- ].every(isNonnegativeNumber)) {
1087
- return false;
1088
- }
1089
- return value.details === void 0 || isRecord(value.details) && Object.values(value.details).every(isNonnegativeNumber);
728
+ if (!isRecord$1(value) || !hasOnlyKeys(value, [
729
+ "inputTokens",
730
+ "outputTokens",
731
+ "totalTokens",
732
+ "cachedInputTokens",
733
+ "cacheCreationInputTokens",
734
+ "details"
735
+ ]) || ![
736
+ value.inputTokens,
737
+ value.outputTokens,
738
+ value.totalTokens,
739
+ value.cachedInputTokens,
740
+ value.cacheCreationInputTokens
741
+ ].every(isNonnegativeNumber)) return false;
742
+ return value.details === void 0 || isRecord$1(value.details) && Object.values(value.details).every(isNonnegativeNumber);
1090
743
  }
1091
744
  function isContextUsage(value) {
1092
- if (!isRecord(value) || !isRecord(value.model) || !isRecord(value.model.context)) return false;
1093
- const context = value.model.context;
1094
- return hasOnlyKeys(value, [
1095
- "model",
1096
- "usedTokens",
1097
- "remainingTokens",
1098
- "usedPercent",
1099
- "remainingPercent"
1100
- ]) && hasOnlyKeys(value.model, ["modelId", "context"]) && typeof value.model.modelId === "string" && hasOnlyKeys(context, ["contextWindow", "maxInputTokens", "maxOutputTokens"]) && isNonnegativeNumber(context.contextWindow) && (context.maxInputTokens === void 0 || isNonnegativeNumber(context.maxInputTokens)) && (context.maxOutputTokens === void 0 || isNonnegativeNumber(context.maxOutputTokens)) && isNonnegativeNumber(value.usedTokens) && isNonnegativeNumber(value.remainingTokens) && isNonnegativeNumber(value.usedPercent) && isNonnegativeNumber(value.remainingPercent);
745
+ if (!isRecord$1(value) || !isRecord$1(value.model) || !isRecord$1(value.model.context)) return false;
746
+ const context = value.model.context;
747
+ return hasOnlyKeys(value, [
748
+ "model",
749
+ "usedTokens",
750
+ "remainingTokens",
751
+ "usedPercent",
752
+ "remainingPercent"
753
+ ]) && hasOnlyKeys(value.model, ["modelId", "context"]) && typeof value.model.modelId === "string" && hasOnlyKeys(context, [
754
+ "contextWindow",
755
+ "maxInputTokens",
756
+ "maxOutputTokens"
757
+ ]) && isNonnegativeNumber(context.contextWindow) && (context.maxInputTokens === void 0 || isNonnegativeNumber(context.maxInputTokens)) && (context.maxOutputTokens === void 0 || isNonnegativeNumber(context.maxOutputTokens)) && isNonnegativeNumber(value.usedTokens) && isNonnegativeNumber(value.remainingTokens) && isNonnegativeNumber(value.usedPercent) && isNonnegativeNumber(value.remainingPercent);
1101
758
  }
1102
759
  function validateUsageAndContext(event, original) {
1103
- if (event.usage !== void 0 && !isUsage(event.usage)) {
1104
- invalid(`${String(event.type)}.usage`, original);
1105
- }
1106
- if (event.contextUsage !== void 0 && !isContextUsage(event.contextUsage)) {
1107
- invalid(`${String(event.type)}.contextUsage`, original);
1108
- }
760
+ if (event.usage !== void 0 && !isUsage(event.usage)) invalid(`${String(event.type)}.usage`, original);
761
+ if (event.contextUsage !== void 0 && !isContextUsage(event.contextUsage)) invalid(`${String(event.type)}.contextUsage`, original);
1109
762
  }
1110
763
  function validateMemoryCompactionInfo(value, original) {
1111
- for (const field of [
1112
- "originalMessageCount",
1113
- "compactedMessageCount",
1114
- "retainedMessageCount",
1115
- "originalTokenCount",
1116
- "compactedTokenCount",
1117
- "retainedTokenCount",
1118
- "resultTokenCount"
1119
- ]) {
1120
- if (!isEventId(value[field])) invalid(`memory_compaction.${field}`, original);
1121
- }
1122
- if (!isPositiveEventId(value.attempts)) invalid("memory_compaction.attempts", original);
1123
- if (!isUsage(value.usage)) invalid("memory_compaction.usage", original);
764
+ for (const field of [
765
+ "originalMessageCount",
766
+ "compactedMessageCount",
767
+ "retainedMessageCount",
768
+ "originalTokenCount",
769
+ "compactedTokenCount",
770
+ "retainedTokenCount",
771
+ "resultTokenCount"
772
+ ]) if (!isEventId(value[field])) invalid(`memory_compaction.${field}`, original);
773
+ if (!isPositiveEventId(value.attempts)) invalid("memory_compaction.attempts", original);
774
+ if (!isUsage(value.usage)) invalid("memory_compaction.usage", original);
1124
775
  }
1125
776
  function isTrace(value) {
1126
- return isRecord(value) && hasOnlyKeys(value, ["observer", "traceId", "observationId"]) && typeof value.observer === "string" && value.observer.trim().length > 0 && (value.traceId === void 0 || typeof value.traceId === "string") && (value.observationId === void 0 || typeof value.observationId === "string");
777
+ return isRecord$1(value) && hasOnlyKeys(value, [
778
+ "observer",
779
+ "traceId",
780
+ "observationId"
781
+ ]) && typeof value.observer === "string" && value.observer.trim().length > 0 && (value.traceId === void 0 || typeof value.traceId === "string") && (value.observationId === void 0 || typeof value.observationId === "string");
1127
782
  }
1128
783
  function requireRecord(value, label) {
1129
- if (!isRecord(value)) throw new ClientProtocolError(`${label} must be an object.`, value);
1130
- return value;
784
+ if (!isRecord$1(value)) throw new ClientProtocolError(`${label} must be an object.`, value);
785
+ return value;
1131
786
  }
1132
787
  function requireOnlyKeys(value, keys, label) {
1133
- for (const key of Object.keys(value)) {
1134
- if (!keys.includes(key)) throw new ClientProtocolError(`${label} has unknown field "${key}".`);
1135
- }
788
+ for (const key of Object.keys(value)) if (!keys.includes(key)) throw new ClientProtocolError(`${label} has unknown field "${key}".`);
1136
789
  }
1137
790
  function requireEventKeys(value, keys) {
1138
- requireOnlyKeys(
1139
- value,
1140
- ["type", "runId", "turn", "scope", ...keys],
1141
- `${String(value.type)} event`
1142
- );
791
+ requireOnlyKeys(value, [
792
+ "type",
793
+ "runId",
794
+ "turn",
795
+ "scope",
796
+ ...keys
797
+ ], `${String(value.type)} event`);
1143
798
  }
1144
799
  function requireStrings(value, keys, original) {
1145
- for (const key of keys) {
1146
- if (typeof value[key] !== "string") invalid(`${String(value.type)}.${key}`, original);
1147
- }
800
+ for (const key of keys) if (typeof value[key] !== "string") invalid(`${String(value.type)}.${key}`, original);
1148
801
  }
1149
802
  function requireOptionalStrings(value, keys, original) {
1150
- for (const key of keys) {
1151
- if (value[key] !== void 0 && typeof value[key] !== "string") {
1152
- invalid(`${String(value.type)}.${key}`, original);
1153
- }
1154
- }
803
+ for (const key of keys) if (value[key] !== void 0 && typeof value[key] !== "string") invalid(`${String(value.type)}.${key}`, original);
1155
804
  }
1156
805
  function requireOneOf(value, allowed, label, original) {
1157
- if (typeof value !== "string" || !allowed.includes(value)) invalid(label, original);
806
+ if (typeof value !== "string" || !allowed.includes(value)) invalid(label, original);
1158
807
  }
1159
808
  function invalid(label, value) {
1160
- throw new ClientProtocolError(`Invalid ${label}.`, value);
809
+ throw new ClientProtocolError(`Invalid ${label}.`, value);
1161
810
  }
1162
811
  function isEventId(value) {
1163
- return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
812
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
1164
813
  }
1165
814
  function isPositiveEventId(value) {
1166
- return isEventId(value) && value > 0;
815
+ return isEventId(value) && value > 0;
1167
816
  }
1168
817
  function isNonnegativeNumber(value) {
1169
- return typeof value === "number" && Number.isFinite(value) && value >= 0;
818
+ return typeof value === "number" && Number.isFinite(value) && value >= 0;
1170
819
  }
1171
820
  function hasOnlyKeys(value, keys) {
1172
- return Object.keys(value).every((key) => keys.includes(key));
821
+ return Object.keys(value).every((key) => keys.includes(key));
1173
822
  }
1174
- function isRecord(value) {
1175
- return typeof value === "object" && value !== null && !Array.isArray(value);
823
+ function isRecord$1(value) {
824
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1176
825
  }
1177
-
1178
826
  // src/adapters.ts
1179
827
  function completionToClientStream(options) {
1180
- const { events } = options;
1181
- const runId = options.runId ?? createClientId("run");
1182
- return propagateCancellation(events, (source) => ({
1183
- async *[Symbol.asyncIterator]() {
1184
- const state = createMessageState({ runId });
1185
- const runStart = {
1186
- type: "run_start",
1187
- source: "completion"
1188
- };
1189
- if (options.metadata !== void 0) runStart.metadata = options.metadata;
1190
- yield clientEvent(state, runStart);
1191
- if (options.model !== void 0) {
1192
- yield clientEvent(state, { type: "generation_start", model: options.model });
1193
- }
1194
- yield* startMessage(state);
1195
- let terminal = false;
1196
- try {
1197
- for await (const event of source) {
1198
- if (terminal) break;
1199
- switch (event.type) {
1200
- case "text_delta":
1201
- yield* appendText(state, event.delta);
1202
- break;
1203
- case "reasoning_delta":
1204
- yield* appendReasoning(state, event);
1205
- break;
1206
- case "tool_call_delta":
1207
- yield* appendToolCall(state, event);
1208
- break;
1209
- case "tool_call":
1210
- yield* finishToolCall(state, event.toolCall);
1211
- break;
1212
- case "source":
1213
- yield* emitSource(state, event.source);
1214
- break;
1215
- case "provider_tool_call":
1216
- yield* emitProviderToolCall(state, event.toolCall);
1217
- break;
1218
- case "message_id":
1219
- state.modelMessageId = event.id;
1220
- break;
1221
- case "final": {
1222
- const result = event.result;
1223
- if (result.messageId !== void 0) state.modelMessageId = result.messageId;
1224
- const finalMetadata = {
1225
- usage: result.usage
1226
- };
1227
- if (result.contextUsage !== void 0) {
1228
- finalMetadata.contextUsage = result.contextUsage;
1229
- }
1230
- if (result.sources !== void 0) finalMetadata.sources = result.sources;
1231
- if (result.providerToolCalls !== void 0) {
1232
- finalMetadata.providerToolCalls = result.providerToolCalls;
1233
- }
1234
- yield* finishMessage(state, result.content, finalMetadata);
1235
- const output = clientOutput(result.output, options.mapOutput);
1236
- const runEnd = {
1237
- type: "run_end",
1238
- status: "completed",
1239
- text: result.text,
1240
- usage: result.usage
1241
- };
1242
- if (output !== void 0) runEnd.output = output;
1243
- if (result.contextUsage !== void 0) runEnd.contextUsage = result.contextUsage;
1244
- yield clientEvent(state, runEnd);
1245
- terminal = true;
1246
- break;
1247
- }
1248
- case "error":
1249
- yield* finishErroredRun(state, event.error, event.usage, options.mapError);
1250
- terminal = true;
1251
- break;
1252
- }
1253
- }
1254
- if (!terminal) {
1255
- yield* finishErroredRun(
1256
- state,
1257
- new Error("Completion stream ended without a terminal event."),
1258
- void 0,
1259
- options.mapError
1260
- );
1261
- }
1262
- } catch (error) {
1263
- if (!terminal) yield* finishErroredRun(state, error, void 0, options.mapError);
1264
- }
1265
- }
1266
- }));
828
+ const { events } = options;
829
+ const runId = options.runId ?? createClientId("run");
830
+ return propagateCancellation(events, (source) => ({ async *[Symbol.asyncIterator]() {
831
+ const state = createMessageState({ runId });
832
+ const runStart = {
833
+ type: "run_start",
834
+ source: "completion"
835
+ };
836
+ if (options.metadata !== void 0) runStart.metadata = options.metadata;
837
+ yield clientEvent(state, runStart);
838
+ if (options.model !== void 0) yield clientEvent(state, {
839
+ type: "generation_start",
840
+ model: options.model
841
+ });
842
+ yield* startMessage(state);
843
+ let terminal = false;
844
+ try {
845
+ for await (const event of source) {
846
+ if (terminal) break;
847
+ switch (event.type) {
848
+ case "text_delta":
849
+ yield* appendText(state, event.delta);
850
+ break;
851
+ case "reasoning_delta":
852
+ yield* appendReasoning(state, event);
853
+ break;
854
+ case "tool_call_delta":
855
+ yield* appendToolCall(state, event);
856
+ break;
857
+ case "tool_call":
858
+ yield* finishToolCall(state, event.toolCall);
859
+ break;
860
+ case "source":
861
+ yield* emitSource(state, event.source);
862
+ break;
863
+ case "provider_tool_call":
864
+ yield* emitProviderToolCall(state, event.toolCall);
865
+ break;
866
+ case "message_id":
867
+ state.modelMessageId = event.id;
868
+ break;
869
+ case "final": {
870
+ const result = event.result;
871
+ if (result.messageId !== void 0) state.modelMessageId = result.messageId;
872
+ const finalMetadata = { usage: result.usage };
873
+ if (result.contextUsage !== void 0) finalMetadata.contextUsage = result.contextUsage;
874
+ if (result.sources !== void 0) finalMetadata.sources = result.sources;
875
+ if (result.providerToolCalls !== void 0) finalMetadata.providerToolCalls = result.providerToolCalls;
876
+ yield* finishMessage(state, result.content, finalMetadata);
877
+ const output = clientOutput(result.output, options.mapOutput);
878
+ const runEnd = {
879
+ type: "run_end",
880
+ status: "completed",
881
+ text: result.text,
882
+ usage: result.usage
883
+ };
884
+ if (output !== void 0) runEnd.output = output;
885
+ if (result.contextUsage !== void 0) runEnd.contextUsage = result.contextUsage;
886
+ yield clientEvent(state, runEnd);
887
+ terminal = true;
888
+ break;
889
+ }
890
+ case "error":
891
+ yield* finishErroredRun(state, event.error, event.usage, options.mapError);
892
+ terminal = true;
893
+ }
894
+ }
895
+ if (!terminal) yield* finishErroredRun(state, /* @__PURE__ */ new Error("Completion stream ended without a terminal event."), void 0, options.mapError);
896
+ } catch (error) {
897
+ if (!terminal) yield* finishErroredRun(state, error, void 0, options.mapError);
898
+ }
899
+ } }));
1267
900
  }
1268
901
  function agentToClientStream(options) {
1269
- const { events } = options;
1270
- const runId = options.runId ?? createClientId("run");
1271
- return propagateCancellation(events, (source) => ({
1272
- async *[Symbol.asyncIterator]() {
1273
- const runtime = {
1274
- runId,
1275
- options,
1276
- messages: /* @__PURE__ */ new Map(),
1277
- startedScopes: /* @__PURE__ */ new Set(["root"])
1278
- };
1279
- const runStart = {
1280
- type: "run_start",
1281
- source: "agent"
1282
- };
1283
- if (options.metadata !== void 0) runStart.metadata = options.metadata;
1284
- yield rootEvent(runId, runStart);
1285
- let terminal = false;
1286
- try {
1287
- for await (const event of source) {
1288
- if (terminal) break;
1289
- yield* translateAgentEvent(runtime, event, void 0);
1290
- terminal = isRootTerminalAgentEvent(event);
1291
- }
1292
- if (!terminal) {
1293
- const error = mapClientError(
1294
- new Error("Agent stream ended without a terminal event."),
1295
- options.mapError
1296
- );
1297
- yield rootEvent(runId, { type: "error", error });
1298
- yield rootEvent(runId, { type: "run_end", status: "error" });
1299
- }
1300
- } catch (error) {
1301
- if (!terminal) {
1302
- yield rootEvent(runId, {
1303
- type: "error",
1304
- error: mapClientError(error, options.mapError)
1305
- });
1306
- yield rootEvent(runId, { type: "run_end", status: "error" });
1307
- }
1308
- }
1309
- }
1310
- }));
902
+ const { events } = options;
903
+ const runId = options.runId ?? createClientId("run");
904
+ return propagateCancellation(events, (source) => ({ async *[Symbol.asyncIterator]() {
905
+ const runtime = {
906
+ runId,
907
+ options,
908
+ messages: /* @__PURE__ */ new Map(),
909
+ startedScopes: /* @__PURE__ */ new Set(["root"])
910
+ };
911
+ const runStart = {
912
+ type: "run_start",
913
+ source: "agent"
914
+ };
915
+ if (options.metadata !== void 0) runStart.metadata = options.metadata;
916
+ yield rootEvent(runId, runStart);
917
+ let terminal = false;
918
+ try {
919
+ for await (const event of source) {
920
+ if (terminal) break;
921
+ yield* translateAgentEvent(runtime, event, void 0);
922
+ terminal = isRootTerminalAgentEvent(event);
923
+ }
924
+ if (!terminal) {
925
+ const error = mapClientError(/* @__PURE__ */ new Error("Agent stream ended without a terminal event."), options.mapError);
926
+ yield rootEvent(runId, {
927
+ type: "error",
928
+ error
929
+ });
930
+ yield rootEvent(runId, {
931
+ type: "run_end",
932
+ status: "error"
933
+ });
934
+ }
935
+ } catch (error) {
936
+ if (!terminal) {
937
+ yield rootEvent(runId, {
938
+ type: "error",
939
+ error: mapClientError(error, options.mapError)
940
+ });
941
+ yield rootEvent(runId, {
942
+ type: "run_end",
943
+ status: "error"
944
+ });
945
+ }
946
+ }
947
+ } }));
1311
948
  }
1312
949
  function customAgentEventsToClientStream(options) {
1313
- return agentToClientStream(
1314
- options
1315
- );
950
+ return agentToClientStream(options);
1316
951
  }
1317
952
  async function* translateAgentEvent(runtime, event, scope) {
1318
- if (event.type === "agent_tool_event") {
1319
- const childScope = {
1320
- agentId: event.agentId,
1321
- parentRunId: runtime.runId,
1322
- parentToolName: event.toolName,
1323
- parentToolCallId: event.toolCallId ?? event.internalCallId,
1324
- parentInternalToolCallId: event.internalCallId
1325
- };
1326
- if (event.agentName !== void 0) childScope.agentName = event.agentName;
1327
- const key = scopeKey(childScope);
1328
- if (!runtime.startedScopes.has(key)) {
1329
- runtime.startedScopes.add(key);
1330
- yield rootEvent(runtime.runId, { type: "run_start", source: "agent" }, childScope);
1331
- }
1332
- yield* translateAgentEvent(runtime, event.event, childScope);
1333
- return;
1334
- }
1335
- const turn = "turn" in event && typeof event.turn === "number" ? event.turn : void 0;
1336
- switch (event.type) {
1337
- case "memory_compaction":
1338
- yield scopedEvent(runtime.runId, turn, scope, {
1339
- type: "memory_compaction",
1340
- originalMessageCount: event.originalMessageCount,
1341
- compactedMessageCount: event.compactedMessageCount,
1342
- retainedMessageCount: event.retainedMessageCount,
1343
- originalTokenCount: event.originalTokenCount,
1344
- compactedTokenCount: event.compactedTokenCount,
1345
- retainedTokenCount: event.retainedTokenCount,
1346
- resultTokenCount: event.resultTokenCount,
1347
- attempts: event.attempts,
1348
- usage: event.usage
1349
- });
1350
- return;
1351
- case "turn_start":
1352
- yield scopedEvent(runtime.runId, turn, scope, { type: "turn_start" });
1353
- return;
1354
- case "generation_start": {
1355
- let state = getAgentMessage(runtime, event.turn, scope);
1356
- if (state.started && !state.ended) {
1357
- state = getAgentMessage(runtime, event.turn, scope, true);
1358
- yield clientEvent(state, { type: "message_reset", messageId: state.messageId });
1359
- }
1360
- yield scopedEvent(runtime.runId, event.turn, scope, {
1361
- type: "generation_start",
1362
- model: {
1363
- provider: event.modelInfo.provider,
1364
- modelId: event.modelInfo.modelId
1365
- }
1366
- });
1367
- yield* startMessage(state);
1368
- return;
1369
- }
1370
- case "text_delta": {
1371
- const state = getAgentMessage(runtime, event.turn, scope);
1372
- yield* startMessage(state);
1373
- yield* appendText(state, event.delta);
1374
- return;
1375
- }
1376
- case "reasoning_delta": {
1377
- const state = getAgentMessage(runtime, event.turn, scope);
1378
- yield* startMessage(state);
1379
- yield* appendReasoning(state, event);
1380
- return;
1381
- }
1382
- case "tool_call_delta": {
1383
- const state = getAgentMessage(runtime, event.turn, scope);
1384
- yield* startMessage(state);
1385
- yield* appendToolCall(state, event);
1386
- return;
1387
- }
1388
- case "tool_call": {
1389
- const state = getAgentMessage(runtime, event.turn, scope);
1390
- yield* startMessage(state);
1391
- yield* finishToolCall(state, event.toolCall);
1392
- return;
1393
- }
1394
- case "source": {
1395
- const state = getAgentMessage(runtime, event.turn, scope);
1396
- yield* startMessage(state);
1397
- yield* emitSource(state, event.source);
1398
- return;
1399
- }
1400
- case "provider_tool_call": {
1401
- const state = getAgentMessage(runtime, event.turn, scope);
1402
- yield* emitProviderToolCall(state, event.toolCall);
1403
- return;
1404
- }
1405
- case "tool_result": {
1406
- const state = getAgentMessage(runtime, event.turn, scope);
1407
- yield* startMessage(state);
1408
- const tool = getToolResultState(
1409
- state,
1410
- event.toolName,
1411
- event.toolCallId,
1412
- event.callId,
1413
- event.internalCallId
1414
- );
1415
- tool.result = clientToolResult(event.output, event.result);
1416
- const resultEvent = {
1417
- type: "tool_result",
1418
- messageId: state.messageId,
1419
- partId: tool.partId,
1420
- toolCallId: tool.toolCallId,
1421
- internalCallId: event.internalCallId,
1422
- toolName: event.toolName,
1423
- input: parseJsonOrString(event.args),
1424
- result: tool.result
1425
- };
1426
- if (tool.callId !== void 0) resultEvent.callId = tool.callId;
1427
- yield clientEvent(state, resultEvent);
1428
- return;
1429
- }
1430
- case "turn_end": {
1431
- const state = getAgentMessage(runtime, event.turn, scope);
1432
- yield* startMessage(state);
1433
- if (event.response.messageId !== void 0) state.modelMessageId = event.response.messageId;
1434
- const finalMetadata = {
1435
- usage: event.response.usage
1436
- };
1437
- if (event.response.contextUsage !== void 0) {
1438
- finalMetadata.contextUsage = event.response.contextUsage;
1439
- }
1440
- if (event.response.sources !== void 0) finalMetadata.sources = event.response.sources;
1441
- if (event.response.providerToolCalls !== void 0) {
1442
- finalMetadata.providerToolCalls = event.response.providerToolCalls;
1443
- }
1444
- yield* finishMessage(state, event.response.choice, finalMetadata);
1445
- const turnEnd = {
1446
- type: "turn_end",
1447
- usage: event.response.usage
1448
- };
1449
- if (event.response.contextUsage !== void 0) {
1450
- turnEnd.contextUsage = event.response.contextUsage;
1451
- }
1452
- if (event.firstDeltaMs !== void 0) turnEnd.firstDeltaMs = event.firstDeltaMs;
1453
- yield scopedEvent(runtime.runId, event.turn, scope, turnEnd);
1454
- return;
1455
- }
1456
- case "guardrail_decision":
1457
- yield scopedEvent(runtime.runId, event.turn, scope, {
1458
- type: "guardrail_decision",
1459
- decision: event.decision
1460
- });
1461
- return;
1462
- case "response":
1463
- case "interaction":
1464
- case "blocked": {
1465
- const result = event;
1466
- if (result.type === "interaction" && scope === void 0) {
1467
- yield scopedEvent(runtime.runId, turn, scope, {
1468
- type: "interaction",
1469
- interaction: result.interaction
1470
- });
1471
- }
1472
- const output = result.type === "response" ? clientOutput(result.output, runtime.options.mapOutput) : void 0;
1473
- const runEnd = {
1474
- type: "run_end",
1475
- status: agentOutcomeStatus(result.type),
1476
- text: result.text,
1477
- usage: result.usage
1478
- };
1479
- if (output !== void 0) runEnd.output = output;
1480
- if (result.contextUsage !== void 0) runEnd.contextUsage = result.contextUsage;
1481
- if (result.trace !== void 0) runEnd.trace = clientTrace(result.trace);
1482
- if (result.memoryCompaction !== void 0) {
1483
- runEnd.memoryCompaction = result.memoryCompaction;
1484
- }
1485
- if (runtime.options.metadata !== void 0) runEnd.metadata = runtime.options.metadata;
1486
- yield scopedEvent(runtime.runId, turn, scope, runEnd);
1487
- return;
1488
- }
1489
- case "error": {
1490
- const error = mapClientError(event.error, runtime.options.mapError);
1491
- yield scopedEvent(runtime.runId, turn, scope, { type: "error", error, usage: event.usage });
1492
- yield scopedEvent(runtime.runId, turn, scope, {
1493
- type: "run_end",
1494
- status: "error",
1495
- usage: event.usage
1496
- });
1497
- return;
1498
- }
1499
- default: {
1500
- const context = {
1501
- runId: runtime.runId
1502
- };
1503
- if (turn !== void 0) context.turn = turn;
1504
- if (scope !== void 0) context.scope = scope;
1505
- const mapped = runtime.options.mapCustomEvent?.(event, context);
1506
- if (mapped === void 0) return;
1507
- if (Array.isArray(mapped)) {
1508
- yield* mapped;
1509
- } else {
1510
- yield mapped;
1511
- }
1512
- }
1513
- }
953
+ if (event.type === "agent_tool_event") {
954
+ const childScope = {
955
+ agentId: event.agentId,
956
+ parentRunId: runtime.runId,
957
+ parentToolName: event.toolName,
958
+ parentToolCallId: event.toolCallId ?? event.internalCallId,
959
+ parentInternalToolCallId: event.internalCallId
960
+ };
961
+ if (event.agentName !== void 0) childScope.agentName = event.agentName;
962
+ const key = scopeKey(childScope);
963
+ if (!runtime.startedScopes.has(key)) {
964
+ runtime.startedScopes.add(key);
965
+ yield rootEvent(runtime.runId, {
966
+ type: "run_start",
967
+ source: "agent"
968
+ }, childScope);
969
+ }
970
+ yield* translateAgentEvent(runtime, event.event, childScope);
971
+ return;
972
+ }
973
+ const turn = "turn" in event && typeof event.turn === "number" ? event.turn : void 0;
974
+ switch (event.type) {
975
+ case "memory_compaction":
976
+ yield scopedEvent(runtime.runId, turn, scope, {
977
+ type: "memory_compaction",
978
+ originalMessageCount: event.originalMessageCount,
979
+ compactedMessageCount: event.compactedMessageCount,
980
+ retainedMessageCount: event.retainedMessageCount,
981
+ originalTokenCount: event.originalTokenCount,
982
+ compactedTokenCount: event.compactedTokenCount,
983
+ retainedTokenCount: event.retainedTokenCount,
984
+ resultTokenCount: event.resultTokenCount,
985
+ attempts: event.attempts,
986
+ usage: event.usage
987
+ });
988
+ return;
989
+ case "turn_start":
990
+ yield scopedEvent(runtime.runId, turn, scope, { type: "turn_start" });
991
+ return;
992
+ case "generation_start": {
993
+ let state = getAgentMessage(runtime, event.turn, scope);
994
+ if (state.started && !state.ended) {
995
+ state = getAgentMessage(runtime, event.turn, scope, true);
996
+ yield clientEvent(state, {
997
+ type: "message_reset",
998
+ messageId: state.messageId
999
+ });
1000
+ }
1001
+ yield scopedEvent(runtime.runId, event.turn, scope, {
1002
+ type: "generation_start",
1003
+ model: {
1004
+ provider: event.modelInfo.provider,
1005
+ modelId: event.modelInfo.modelId
1006
+ }
1007
+ });
1008
+ yield* startMessage(state);
1009
+ return;
1010
+ }
1011
+ case "text_delta": {
1012
+ const state = getAgentMessage(runtime, event.turn, scope);
1013
+ yield* startMessage(state);
1014
+ yield* appendText(state, event.delta);
1015
+ return;
1016
+ }
1017
+ case "reasoning_delta": {
1018
+ const state = getAgentMessage(runtime, event.turn, scope);
1019
+ yield* startMessage(state);
1020
+ yield* appendReasoning(state, event);
1021
+ return;
1022
+ }
1023
+ case "tool_call_delta": {
1024
+ const state = getAgentMessage(runtime, event.turn, scope);
1025
+ yield* startMessage(state);
1026
+ yield* appendToolCall(state, event);
1027
+ return;
1028
+ }
1029
+ case "tool_call": {
1030
+ const state = getAgentMessage(runtime, event.turn, scope);
1031
+ yield* startMessage(state);
1032
+ yield* finishToolCall(state, event.toolCall);
1033
+ return;
1034
+ }
1035
+ case "source": {
1036
+ const state = getAgentMessage(runtime, event.turn, scope);
1037
+ yield* startMessage(state);
1038
+ yield* emitSource(state, event.source);
1039
+ return;
1040
+ }
1041
+ case "provider_tool_call":
1042
+ yield* emitProviderToolCall(getAgentMessage(runtime, event.turn, scope), event.toolCall);
1043
+ return;
1044
+ case "tool_result": {
1045
+ const state = getAgentMessage(runtime, event.turn, scope);
1046
+ yield* startMessage(state);
1047
+ const tool = getToolResultState(state, event.toolName, event.toolCallId, event.callId, event.internalCallId);
1048
+ tool.result = clientToolResult(event.output, event.result);
1049
+ const resultEvent = {
1050
+ type: "tool_result",
1051
+ messageId: state.messageId,
1052
+ partId: tool.partId,
1053
+ toolCallId: tool.toolCallId,
1054
+ internalCallId: event.internalCallId,
1055
+ toolName: event.toolName,
1056
+ input: parseJsonOrString(event.args),
1057
+ result: tool.result
1058
+ };
1059
+ if (tool.callId !== void 0) resultEvent.callId = tool.callId;
1060
+ yield clientEvent(state, resultEvent);
1061
+ return;
1062
+ }
1063
+ case "turn_end": {
1064
+ const state = getAgentMessage(runtime, event.turn, scope);
1065
+ yield* startMessage(state);
1066
+ if (event.response.messageId !== void 0) state.modelMessageId = event.response.messageId;
1067
+ const finalMetadata = { usage: event.response.usage };
1068
+ if (event.response.contextUsage !== void 0) finalMetadata.contextUsage = event.response.contextUsage;
1069
+ if (event.response.sources !== void 0) finalMetadata.sources = event.response.sources;
1070
+ if (event.response.providerToolCalls !== void 0) finalMetadata.providerToolCalls = event.response.providerToolCalls;
1071
+ yield* finishMessage(state, event.response.choice, finalMetadata);
1072
+ const turnEnd = {
1073
+ type: "turn_end",
1074
+ usage: event.response.usage
1075
+ };
1076
+ if (event.response.contextUsage !== void 0) turnEnd.contextUsage = event.response.contextUsage;
1077
+ if (event.firstDeltaMs !== void 0) turnEnd.firstDeltaMs = event.firstDeltaMs;
1078
+ yield scopedEvent(runtime.runId, event.turn, scope, turnEnd);
1079
+ return;
1080
+ }
1081
+ case "guardrail_decision":
1082
+ yield scopedEvent(runtime.runId, event.turn, scope, {
1083
+ type: "guardrail_decision",
1084
+ decision: event.decision
1085
+ });
1086
+ return;
1087
+ case "response":
1088
+ case "interaction":
1089
+ case "blocked": {
1090
+ const result = event;
1091
+ if (result.type === "interaction" && scope === void 0) yield scopedEvent(runtime.runId, turn, scope, {
1092
+ type: "interaction",
1093
+ interaction: result.interaction
1094
+ });
1095
+ const output = result.type === "response" ? clientOutput(result.output, runtime.options.mapOutput) : void 0;
1096
+ const runEnd = {
1097
+ type: "run_end",
1098
+ status: agentOutcomeStatus(result.type),
1099
+ text: result.text,
1100
+ usage: result.usage
1101
+ };
1102
+ if (output !== void 0) runEnd.output = output;
1103
+ if (result.contextUsage !== void 0) runEnd.contextUsage = result.contextUsage;
1104
+ if (result.trace !== void 0) runEnd.trace = clientTrace(result.trace);
1105
+ if (result.memoryCompaction !== void 0) runEnd.memoryCompaction = result.memoryCompaction;
1106
+ if (runtime.options.metadata !== void 0) runEnd.metadata = runtime.options.metadata;
1107
+ yield scopedEvent(runtime.runId, turn, scope, runEnd);
1108
+ return;
1109
+ }
1110
+ case "error": {
1111
+ const error = mapClientError(event.error, runtime.options.mapError);
1112
+ yield scopedEvent(runtime.runId, turn, scope, {
1113
+ type: "error",
1114
+ error,
1115
+ usage: event.usage
1116
+ });
1117
+ yield scopedEvent(runtime.runId, turn, scope, {
1118
+ type: "run_end",
1119
+ status: "error",
1120
+ usage: event.usage
1121
+ });
1122
+ return;
1123
+ }
1124
+ default: {
1125
+ const context = { runId: runtime.runId };
1126
+ if (turn !== void 0) context.turn = turn;
1127
+ if (scope !== void 0) context.scope = scope;
1128
+ const mapped = runtime.options.mapCustomEvent?.(event, context);
1129
+ if (mapped === void 0) return;
1130
+ if (Array.isArray(mapped)) yield* mapped;
1131
+ else yield mapped;
1132
+ }
1133
+ }
1514
1134
  }
1515
1135
  function createMessageState(input) {
1516
- const state = {
1517
- runId: input.runId,
1518
- messageId: createClientId("msg"),
1519
- started: false,
1520
- ended: false,
1521
- textPartId: createClientId("text"),
1522
- text: "",
1523
- textStarted: false,
1524
- textEnded: false,
1525
- reasoning: /* @__PURE__ */ new Map(),
1526
- tools: /* @__PURE__ */ new Map(),
1527
- sourceFingerprints: /* @__PURE__ */ new Set(),
1528
- providerToolCallFingerprints: /* @__PURE__ */ new Set()
1529
- };
1530
- if (input.turn !== void 0) state.turn = input.turn;
1531
- if (input.scope !== void 0) state.scope = input.scope;
1532
- return state;
1136
+ const state = {
1137
+ runId: input.runId,
1138
+ messageId: createClientId("msg"),
1139
+ started: false,
1140
+ ended: false,
1141
+ textPartId: createClientId("text"),
1142
+ text: "",
1143
+ textStarted: false,
1144
+ textEnded: false,
1145
+ reasoning: /* @__PURE__ */ new Map(),
1146
+ tools: /* @__PURE__ */ new Map(),
1147
+ sourceFingerprints: /* @__PURE__ */ new Set(),
1148
+ providerToolCallFingerprints: /* @__PURE__ */ new Set()
1149
+ };
1150
+ if (input.turn !== void 0) state.turn = input.turn;
1151
+ if (input.scope !== void 0) state.scope = input.scope;
1152
+ return state;
1533
1153
  }
1534
1154
  function getAgentMessage(runtime, turn, scope, reset = false) {
1535
- const key = `${scopeKey(scope)}:${turn}`;
1536
- const current = runtime.messages.get(key);
1537
- if (current !== void 0 && !reset) return current;
1538
- const input = {
1539
- runId: runtime.runId,
1540
- turn
1541
- };
1542
- if (scope !== void 0) input.scope = scope;
1543
- const created = createMessageState(input);
1544
- if (current !== void 0) {
1545
- created.messageId = current.messageId;
1546
- created.started = current.started;
1547
- }
1548
- runtime.messages.set(key, created);
1549
- return created;
1155
+ const key = `${scopeKey(scope)}:${turn}`;
1156
+ const current = runtime.messages.get(key);
1157
+ if (current !== void 0 && !reset) return current;
1158
+ const input = {
1159
+ runId: runtime.runId,
1160
+ turn
1161
+ };
1162
+ if (scope !== void 0) input.scope = scope;
1163
+ const created = createMessageState(input);
1164
+ if (current !== void 0) {
1165
+ created.messageId = current.messageId;
1166
+ created.started = current.started;
1167
+ }
1168
+ runtime.messages.set(key, created);
1169
+ return created;
1550
1170
  }
1551
1171
  async function* startMessage(state) {
1552
- if (state.started) return;
1553
- state.started = true;
1554
- yield clientEvent(state, {
1555
- type: "message_start",
1556
- messageId: state.messageId,
1557
- role: "assistant"
1558
- });
1172
+ if (state.started) return;
1173
+ state.started = true;
1174
+ yield clientEvent(state, {
1175
+ type: "message_start",
1176
+ messageId: state.messageId,
1177
+ role: "assistant"
1178
+ });
1559
1179
  }
1560
1180
  async function* appendText(state, delta) {
1561
- if (!state.textStarted) {
1562
- state.textStarted = true;
1563
- yield clientEvent(state, {
1564
- type: "text_start",
1565
- messageId: state.messageId,
1566
- partId: state.textPartId
1567
- });
1568
- }
1569
- state.text += delta;
1570
- yield clientEvent(state, {
1571
- type: "text_delta",
1572
- messageId: state.messageId,
1573
- partId: state.textPartId,
1574
- delta
1575
- });
1181
+ if (!state.textStarted) {
1182
+ state.textStarted = true;
1183
+ yield clientEvent(state, {
1184
+ type: "text_start",
1185
+ messageId: state.messageId,
1186
+ partId: state.textPartId
1187
+ });
1188
+ }
1189
+ state.text += delta;
1190
+ yield clientEvent(state, {
1191
+ type: "text_delta",
1192
+ messageId: state.messageId,
1193
+ partId: state.textPartId,
1194
+ delta
1195
+ });
1576
1196
  }
1577
1197
  async function* emitSource(state, source) {
1578
- const fingerprint = valueFingerprint(source);
1579
- if (state.sourceFingerprints.has(fingerprint)) return;
1580
- state.sourceFingerprints.add(fingerprint);
1581
- yield clientEvent(state, {
1582
- type: "source",
1583
- messageId: state.messageId,
1584
- partId: createClientId("source"),
1585
- source
1586
- });
1198
+ const fingerprint = valueFingerprint(source);
1199
+ if (state.sourceFingerprints.has(fingerprint)) return;
1200
+ state.sourceFingerprints.add(fingerprint);
1201
+ yield clientEvent(state, {
1202
+ type: "source",
1203
+ messageId: state.messageId,
1204
+ partId: createClientId("source"),
1205
+ source
1206
+ });
1587
1207
  }
1588
1208
  async function* emitProviderToolCall(state, toolCall) {
1589
- const fingerprint = valueFingerprint(toolCall);
1590
- if (state.providerToolCallFingerprints.has(fingerprint)) return;
1591
- state.providerToolCallFingerprints.add(fingerprint);
1592
- yield clientEvent(state, { type: "provider_tool_call", toolCall });
1209
+ const fingerprint = valueFingerprint(toolCall);
1210
+ if (state.providerToolCallFingerprints.has(fingerprint)) return;
1211
+ state.providerToolCallFingerprints.add(fingerprint);
1212
+ yield clientEvent(state, {
1213
+ type: "provider_tool_call",
1214
+ toolCall
1215
+ });
1593
1216
  }
1594
1217
  async function* appendReasoning(state, event) {
1595
- const key = event.id ?? "default";
1596
- let reasoning = state.reasoning.get(key);
1597
- if (reasoning === void 0) {
1598
- reasoning = {
1599
- partId: createClientId("reasoning"),
1600
- text: "",
1601
- ended: false
1602
- };
1603
- if (event.id !== void 0) reasoning.reasoningId = event.id;
1604
- state.reasoning.set(key, reasoning);
1605
- const reasoningStart = {
1606
- type: "reasoning_start",
1607
- messageId: state.messageId,
1608
- partId: reasoning.partId
1609
- };
1610
- if (event.id !== void 0) reasoningStart.reasoningId = event.id;
1611
- yield clientEvent(state, reasoningStart);
1612
- }
1613
- reasoning.text += event.delta;
1614
- const reasoningDelta = {
1615
- type: "reasoning_delta",
1616
- messageId: state.messageId,
1617
- partId: reasoning.partId,
1618
- delta: event.delta
1619
- };
1620
- if (event.contentType !== void 0) reasoningDelta.contentType = event.contentType;
1621
- if (event.signature !== void 0) reasoningDelta.signature = event.signature;
1622
- yield clientEvent(state, reasoningDelta);
1218
+ const key = event.id ?? "default";
1219
+ let reasoning = state.reasoning.get(key);
1220
+ if (reasoning === void 0) {
1221
+ reasoning = {
1222
+ partId: createClientId("reasoning"),
1223
+ text: "",
1224
+ ended: false
1225
+ };
1226
+ if (event.id !== void 0) reasoning.reasoningId = event.id;
1227
+ state.reasoning.set(key, reasoning);
1228
+ const reasoningStart = {
1229
+ type: "reasoning_start",
1230
+ messageId: state.messageId,
1231
+ partId: reasoning.partId
1232
+ };
1233
+ if (event.id !== void 0) reasoningStart.reasoningId = event.id;
1234
+ yield clientEvent(state, reasoningStart);
1235
+ }
1236
+ reasoning.text += event.delta;
1237
+ const reasoningDelta = {
1238
+ type: "reasoning_delta",
1239
+ messageId: state.messageId,
1240
+ partId: reasoning.partId,
1241
+ delta: event.delta
1242
+ };
1243
+ if (event.contentType !== void 0) reasoningDelta.contentType = event.contentType;
1244
+ if (event.signature !== void 0) reasoningDelta.signature = event.signature;
1245
+ yield clientEvent(state, reasoningDelta);
1623
1246
  }
1624
1247
  async function* appendToolCall(state, event) {
1625
- const tool = getToolState(state, event.id, event.name);
1626
- if (!tool.started) {
1627
- tool.started = true;
1628
- const toolCallStart = {
1629
- type: "tool_call_start",
1630
- messageId: state.messageId,
1631
- partId: tool.partId,
1632
- toolCallId: event.id
1633
- };
1634
- if (event.callId !== void 0) toolCallStart.callId = event.callId;
1635
- if (event.name !== void 0) toolCallStart.toolName = event.name;
1636
- yield clientEvent(state, toolCallStart);
1637
- }
1638
- if (event.callId !== void 0) tool.callId = event.callId;
1639
- if (event.name !== void 0) tool.toolName = event.name;
1640
- if (event.signature !== void 0) tool.signature = event.signature;
1641
- if (event.argumentsDelta === void 0) return;
1642
- const mode = event.argumentsMode ?? "append";
1643
- const prior = typeof tool.input === "string" ? tool.input : "";
1644
- tool.input = mode === "replace" ? event.argumentsDelta : `${prior}${event.argumentsDelta}`;
1645
- const toolCallDelta = {
1646
- type: "tool_call_delta",
1647
- messageId: state.messageId,
1648
- partId: tool.partId,
1649
- toolCallId: event.id,
1650
- delta: event.argumentsDelta,
1651
- mode
1652
- };
1653
- if (event.callId !== void 0) toolCallDelta.callId = event.callId;
1654
- if (event.name !== void 0) toolCallDelta.toolName = event.name;
1655
- if (event.signature !== void 0) toolCallDelta.signature = event.signature;
1656
- yield clientEvent(state, toolCallDelta);
1248
+ const tool = getToolState(state, event.id, event.name);
1249
+ if (!tool.started) {
1250
+ tool.started = true;
1251
+ const toolCallStart = {
1252
+ type: "tool_call_start",
1253
+ messageId: state.messageId,
1254
+ partId: tool.partId,
1255
+ toolCallId: event.id
1256
+ };
1257
+ if (event.callId !== void 0) toolCallStart.callId = event.callId;
1258
+ if (event.name !== void 0) toolCallStart.toolName = event.name;
1259
+ yield clientEvent(state, toolCallStart);
1260
+ }
1261
+ if (event.callId !== void 0) tool.callId = event.callId;
1262
+ if (event.name !== void 0) tool.toolName = event.name;
1263
+ if (event.signature !== void 0) tool.signature = event.signature;
1264
+ if (event.argumentsDelta === void 0) return;
1265
+ const mode = event.argumentsMode ?? "append";
1266
+ const prior = typeof tool.input === "string" ? tool.input : "";
1267
+ tool.input = mode === "replace" ? event.argumentsDelta : `${prior}${event.argumentsDelta}`;
1268
+ const toolCallDelta = {
1269
+ type: "tool_call_delta",
1270
+ messageId: state.messageId,
1271
+ partId: tool.partId,
1272
+ toolCallId: event.id,
1273
+ delta: event.argumentsDelta,
1274
+ mode
1275
+ };
1276
+ if (event.callId !== void 0) toolCallDelta.callId = event.callId;
1277
+ if (event.name !== void 0) toolCallDelta.toolName = event.name;
1278
+ if (event.signature !== void 0) toolCallDelta.signature = event.signature;
1279
+ yield clientEvent(state, toolCallDelta);
1657
1280
  }
1658
1281
  async function* finishToolCall(state, toolCall) {
1659
- const tool = getToolState(state, toolCall.toolCallId, toolCall.toolName);
1660
- const wasEnded = tool.ended;
1661
- if (!tool.started) {
1662
- tool.started = true;
1663
- const toolCallStart = {
1664
- type: "tool_call_start",
1665
- messageId: state.messageId,
1666
- partId: tool.partId,
1667
- toolCallId: toolCall.toolCallId,
1668
- toolName: toolCall.toolName
1669
- };
1670
- if (toolCall.callId !== void 0) toolCallStart.callId = toolCall.callId;
1671
- yield clientEvent(state, toolCallStart);
1672
- }
1673
- if (toolCall.callId === void 0) delete tool.callId;
1674
- else tool.callId = toolCall.callId;
1675
- tool.toolName = toolCall.toolName;
1676
- tool.input = toolCall.input;
1677
- if (toolCall.signature === void 0) delete tool.signature;
1678
- else tool.signature = toolCall.signature;
1679
- if (wasEnded) return;
1680
- tool.ended = true;
1681
- const toolCallEnd = {
1682
- type: "tool_call_end",
1683
- messageId: state.messageId,
1684
- partId: tool.partId,
1685
- toolCallId: toolCall.toolCallId,
1686
- toolName: toolCall.toolName,
1687
- input: toolCall.input
1688
- };
1689
- if (toolCall.callId !== void 0) toolCallEnd.callId = toolCall.callId;
1690
- if (toolCall.signature !== void 0) toolCallEnd.signature = toolCall.signature;
1691
- yield clientEvent(state, toolCallEnd);
1282
+ const tool = getToolState(state, toolCall.toolCallId, toolCall.toolName);
1283
+ const wasEnded = tool.ended;
1284
+ if (!tool.started) {
1285
+ tool.started = true;
1286
+ const toolCallStart = {
1287
+ type: "tool_call_start",
1288
+ messageId: state.messageId,
1289
+ partId: tool.partId,
1290
+ toolCallId: toolCall.toolCallId,
1291
+ toolName: toolCall.toolName
1292
+ };
1293
+ if (toolCall.callId !== void 0) toolCallStart.callId = toolCall.callId;
1294
+ yield clientEvent(state, toolCallStart);
1295
+ }
1296
+ if (toolCall.callId === void 0) delete tool.callId;
1297
+ else tool.callId = toolCall.callId;
1298
+ tool.toolName = toolCall.toolName;
1299
+ tool.input = toolCall.input;
1300
+ if (toolCall.signature === void 0) delete tool.signature;
1301
+ else tool.signature = toolCall.signature;
1302
+ if (wasEnded) return;
1303
+ tool.ended = true;
1304
+ const toolCallEnd = {
1305
+ type: "tool_call_end",
1306
+ messageId: state.messageId,
1307
+ partId: tool.partId,
1308
+ toolCallId: toolCall.toolCallId,
1309
+ toolName: toolCall.toolName,
1310
+ input: toolCall.input
1311
+ };
1312
+ if (toolCall.callId !== void 0) toolCallEnd.callId = toolCall.callId;
1313
+ if (toolCall.signature !== void 0) toolCallEnd.signature = toolCall.signature;
1314
+ yield clientEvent(state, toolCallEnd);
1692
1315
  }
1693
1316
  async function* finishMessage(state, content, metadata) {
1694
- if (state.ended) return;
1695
- const textContent2 = content.filter(
1696
- (part) => part.type === "text"
1697
- );
1698
- const text = textContent2.map((part) => part.text).join("");
1699
- if (state.textStarted || text.length > 0) {
1700
- if (!state.textStarted) {
1701
- state.textStarted = true;
1702
- yield clientEvent(state, {
1703
- type: "text_start",
1704
- messageId: state.messageId,
1705
- partId: state.textPartId
1706
- });
1707
- }
1708
- state.text = text;
1709
- state.textEnded = true;
1710
- const textEnd = {
1711
- type: "text_end",
1712
- messageId: state.messageId,
1713
- partId: state.textPartId,
1714
- text
1715
- };
1716
- if (textContent2.length === 1 && textContent2[0]?.signature !== void 0) {
1717
- textEnd.signature = textContent2[0].signature;
1718
- }
1719
- yield clientEvent(state, textEnd);
1720
- }
1721
- const finalReasoning = content.filter(
1722
- (part) => part.type === "reasoning"
1723
- );
1724
- const anonymousReasoning = [...state.reasoning.values()].filter(
1725
- (reasoning) => reasoning.reasoningId === void 0
1726
- );
1727
- let anonymousIndex = 0;
1728
- for (const [index, reasoning] of finalReasoning.entries()) {
1729
- const existing = reasoning.id === void 0 ? anonymousReasoning[anonymousIndex++] : state.reasoning.get(reasoning.id);
1730
- const current = existing ?? createReasoningState(reasoning.id);
1731
- if (existing === void 0) {
1732
- state.reasoning.set(reasoning.id ?? `final:${index}`, current);
1733
- const reasoningStart = {
1734
- type: "reasoning_start",
1735
- messageId: state.messageId,
1736
- partId: current.partId
1737
- };
1738
- if (reasoning.id !== void 0) reasoningStart.reasoningId = reasoning.id;
1739
- yield clientEvent(state, reasoningStart);
1740
- }
1741
- if (!current.ended) {
1742
- current.ended = true;
1743
- current.text = reasoning.text;
1744
- const reasoningEnd = {
1745
- type: "reasoning_end",
1746
- messageId: state.messageId,
1747
- partId: current.partId,
1748
- text: reasoning.text
1749
- };
1750
- if (reasoning.details !== void 0) reasoningEnd.content = reasoning.details;
1751
- yield clientEvent(state, reasoningEnd);
1752
- }
1753
- }
1754
- for (const reasoning of state.reasoning.values()) {
1755
- if (reasoning.ended) continue;
1756
- reasoning.ended = true;
1757
- yield clientEvent(state, {
1758
- type: "reasoning_end",
1759
- messageId: state.messageId,
1760
- partId: reasoning.partId,
1761
- text: reasoning.text
1762
- });
1763
- }
1764
- for (const part of content) {
1765
- if (part.type === "tool-call") yield* finishToolCall(state, part);
1766
- if (part.type === "image" || part.type === "file") {
1767
- const attachment = contentAttachment(part);
1768
- yield clientEvent(state, {
1769
- type: "attachment",
1770
- messageId: state.messageId,
1771
- partId: createClientId("attachment_part"),
1772
- attachment
1773
- });
1774
- }
1775
- }
1776
- for (const source of metadata.sources ?? []) yield* emitSource(state, source);
1777
- for (const toolCall of metadata.providerToolCalls ?? []) {
1778
- yield* emitProviderToolCall(state, toolCall);
1779
- }
1780
- state.ended = true;
1781
- const messageEnd = {
1782
- type: "message_end",
1783
- messageId: state.messageId,
1784
- parts: contentToUIMessageParts(content, state),
1785
- usage: metadata.usage
1786
- };
1787
- if (state.modelMessageId !== void 0) messageEnd.modelMessageId = state.modelMessageId;
1788
- if (metadata.contextUsage !== void 0) messageEnd.contextUsage = metadata.contextUsage;
1789
- yield clientEvent(state, messageEnd);
1317
+ if (state.ended) return;
1318
+ const textContent = content.filter((part) => part.type === "text");
1319
+ const text = textContent.map((part) => part.text).join("");
1320
+ if (state.textStarted || text.length > 0) {
1321
+ if (!state.textStarted) {
1322
+ state.textStarted = true;
1323
+ yield clientEvent(state, {
1324
+ type: "text_start",
1325
+ messageId: state.messageId,
1326
+ partId: state.textPartId
1327
+ });
1328
+ }
1329
+ state.text = text;
1330
+ state.textEnded = true;
1331
+ const textEnd = {
1332
+ type: "text_end",
1333
+ messageId: state.messageId,
1334
+ partId: state.textPartId,
1335
+ text
1336
+ };
1337
+ if (textContent.length === 1 && textContent[0]?.signature !== void 0) textEnd.signature = textContent[0].signature;
1338
+ yield clientEvent(state, textEnd);
1339
+ }
1340
+ const finalReasoning = content.filter((part) => part.type === "reasoning");
1341
+ const anonymousReasoning = [...state.reasoning.values()].filter((reasoning) => reasoning.reasoningId === void 0);
1342
+ let anonymousIndex = 0;
1343
+ for (const [index, reasoning] of finalReasoning.entries()) {
1344
+ const existing = reasoning.id === void 0 ? anonymousReasoning[anonymousIndex++] : state.reasoning.get(reasoning.id);
1345
+ const current = existing ?? createReasoningState(reasoning.id);
1346
+ if (existing === void 0) {
1347
+ state.reasoning.set(reasoning.id ?? `final:${index}`, current);
1348
+ const reasoningStart = {
1349
+ type: "reasoning_start",
1350
+ messageId: state.messageId,
1351
+ partId: current.partId
1352
+ };
1353
+ if (reasoning.id !== void 0) reasoningStart.reasoningId = reasoning.id;
1354
+ yield clientEvent(state, reasoningStart);
1355
+ }
1356
+ if (!current.ended) {
1357
+ current.ended = true;
1358
+ current.text = reasoning.text;
1359
+ const reasoningEnd = {
1360
+ type: "reasoning_end",
1361
+ messageId: state.messageId,
1362
+ partId: current.partId,
1363
+ text: reasoning.text
1364
+ };
1365
+ if (reasoning.details !== void 0) reasoningEnd.content = reasoning.details;
1366
+ yield clientEvent(state, reasoningEnd);
1367
+ }
1368
+ }
1369
+ for (const reasoning of state.reasoning.values()) {
1370
+ if (reasoning.ended) continue;
1371
+ reasoning.ended = true;
1372
+ yield clientEvent(state, {
1373
+ type: "reasoning_end",
1374
+ messageId: state.messageId,
1375
+ partId: reasoning.partId,
1376
+ text: reasoning.text
1377
+ });
1378
+ }
1379
+ for (const part of content) {
1380
+ if (part.type === "tool-call") yield* finishToolCall(state, part);
1381
+ if (part.type === "image" || part.type === "file") {
1382
+ const attachment = contentAttachment(part);
1383
+ yield clientEvent(state, {
1384
+ type: "attachment",
1385
+ messageId: state.messageId,
1386
+ partId: createClientId("attachment_part"),
1387
+ attachment
1388
+ });
1389
+ }
1390
+ }
1391
+ for (const source of metadata.sources ?? []) yield* emitSource(state, source);
1392
+ for (const toolCall of metadata.providerToolCalls ?? []) yield* emitProviderToolCall(state, toolCall);
1393
+ state.ended = true;
1394
+ const messageEnd = {
1395
+ type: "message_end",
1396
+ messageId: state.messageId,
1397
+ parts: contentToUIMessageParts(content, state),
1398
+ usage: metadata.usage
1399
+ };
1400
+ if (state.modelMessageId !== void 0) messageEnd.modelMessageId = state.modelMessageId;
1401
+ if (metadata.contextUsage !== void 0) messageEnd.contextUsage = metadata.contextUsage;
1402
+ yield clientEvent(state, messageEnd);
1790
1403
  }
1791
1404
  async function* finishErroredRun(state, error, usage, mapper) {
1792
- const mapped = mapClientError(error, mapper);
1793
- if (state.textStarted && !state.textEnded) {
1794
- state.textEnded = true;
1795
- yield clientEvent(state, {
1796
- type: "text_end",
1797
- messageId: state.messageId,
1798
- partId: state.textPartId,
1799
- text: state.text
1800
- });
1801
- }
1802
- const errorEvent = {
1803
- type: "error",
1804
- error: mapped
1805
- };
1806
- if (usage !== void 0) errorEvent.usage = usage;
1807
- yield clientEvent(state, errorEvent);
1808
- if (!state.ended) {
1809
- state.ended = true;
1810
- const messageEnd = {
1811
- type: "message_end",
1812
- messageId: state.messageId
1813
- };
1814
- if (state.modelMessageId !== void 0) messageEnd.modelMessageId = state.modelMessageId;
1815
- if (usage !== void 0) messageEnd.usage = usage;
1816
- yield clientEvent(state, messageEnd);
1817
- }
1818
- const runEnd = {
1819
- type: "run_end",
1820
- status: "error"
1821
- };
1822
- if (usage !== void 0) runEnd.usage = usage;
1823
- yield clientEvent(state, runEnd);
1405
+ const mapped = mapClientError(error, mapper);
1406
+ if (state.textStarted && !state.textEnded) {
1407
+ state.textEnded = true;
1408
+ yield clientEvent(state, {
1409
+ type: "text_end",
1410
+ messageId: state.messageId,
1411
+ partId: state.textPartId,
1412
+ text: state.text
1413
+ });
1414
+ }
1415
+ const errorEvent = {
1416
+ type: "error",
1417
+ error: mapped
1418
+ };
1419
+ if (usage !== void 0) errorEvent.usage = usage;
1420
+ yield clientEvent(state, errorEvent);
1421
+ if (!state.ended) {
1422
+ state.ended = true;
1423
+ const messageEnd = {
1424
+ type: "message_end",
1425
+ messageId: state.messageId
1426
+ };
1427
+ if (state.modelMessageId !== void 0) messageEnd.modelMessageId = state.modelMessageId;
1428
+ if (usage !== void 0) messageEnd.usage = usage;
1429
+ yield clientEvent(state, messageEnd);
1430
+ }
1431
+ const runEnd = {
1432
+ type: "run_end",
1433
+ status: "error"
1434
+ };
1435
+ if (usage !== void 0) runEnd.usage = usage;
1436
+ yield clientEvent(state, runEnd);
1824
1437
  }
1825
1438
  function contentToUIMessageParts(content, state) {
1826
- let textIndex = 0;
1827
- let anonymousReasoningIndex = 0;
1828
- const anonymousReasoning = [...state.reasoning.values()].filter(
1829
- (reasoning) => reasoning.reasoningId === void 0
1830
- );
1831
- return content.map((contentPart) => {
1832
- if (contentPart.type === "text") {
1833
- const part = {
1834
- id: textIndex === 0 ? state.textPartId : createClientId("text"),
1835
- type: "text",
1836
- text: contentPart.text
1837
- };
1838
- textIndex += 1;
1839
- if (contentPart.signature !== void 0) part.signature = contentPart.signature;
1840
- return part;
1841
- }
1842
- if (contentPart.type === "reasoning") {
1843
- const current = contentPart.id === void 0 ? anonymousReasoning[anonymousReasoningIndex++] : state.reasoning.get(contentPart.id);
1844
- const part = {
1845
- id: current?.partId ?? createClientId("reasoning"),
1846
- type: "reasoning",
1847
- text: contentPart.text
1848
- };
1849
- if (contentPart.id !== void 0) part.reasoningId = contentPart.id;
1850
- if (contentPart.details !== void 0) part.content = contentPart.details;
1851
- return part;
1852
- }
1853
- if (contentPart.type === "tool-call") {
1854
- const tool = getToolState(state, contentPart.toolCallId, contentPart.toolName);
1855
- const partBase = {
1856
- id: tool.partId,
1857
- type: "tool",
1858
- toolName: contentPart.toolName,
1859
- toolCallId: contentPart.toolCallId
1860
- };
1861
- if (contentPart.callId !== void 0) Object.assign(partBase, { callId: contentPart.callId });
1862
- if (tool.internalCallId !== void 0) {
1863
- Object.assign(partBase, { internalCallId: tool.internalCallId });
1864
- }
1865
- if (state.turn !== void 0) Object.assign(partBase, { turn: state.turn });
1866
- if (contentPart.signature !== void 0) {
1867
- Object.assign(partBase, { signature: contentPart.signature });
1868
- }
1869
- if (tool.result?.status === "success") {
1870
- const part = {
1871
- ...partBase,
1872
- state: "output-available",
1873
- input: contentPart.input,
1874
- output: tool.result.output
1875
- };
1876
- if (tool.result.content !== void 0) part.resultContent = tool.result.content;
1877
- return part;
1878
- }
1879
- if (tool.result?.status === "error") {
1880
- return {
1881
- ...partBase,
1882
- state: "error",
1883
- input: contentPart.input,
1884
- error: tool.result.error
1885
- };
1886
- }
1887
- return {
1888
- ...partBase,
1889
- state: "input-available",
1890
- input: contentPart.input
1891
- };
1892
- }
1893
- const attachment = contentAttachment(contentPart);
1894
- return {
1895
- id: createClientId("attachment_part"),
1896
- type: "attachment",
1897
- attachment
1898
- };
1899
- });
1439
+ let textIndex = 0;
1440
+ let anonymousReasoningIndex = 0;
1441
+ const anonymousReasoning = [...state.reasoning.values()].filter((reasoning) => reasoning.reasoningId === void 0);
1442
+ return content.map((contentPart) => {
1443
+ if (contentPart.type === "text") {
1444
+ const part = {
1445
+ id: textIndex === 0 ? state.textPartId : createClientId("text"),
1446
+ type: "text",
1447
+ text: contentPart.text
1448
+ };
1449
+ textIndex += 1;
1450
+ if (contentPart.signature !== void 0) part.signature = contentPart.signature;
1451
+ return part;
1452
+ }
1453
+ if (contentPart.type === "reasoning") {
1454
+ const part = {
1455
+ id: (contentPart.id === void 0 ? anonymousReasoning[anonymousReasoningIndex++] : state.reasoning.get(contentPart.id))?.partId ?? createClientId("reasoning"),
1456
+ type: "reasoning",
1457
+ text: contentPart.text
1458
+ };
1459
+ if (contentPart.id !== void 0) part.reasoningId = contentPart.id;
1460
+ if (contentPart.details !== void 0) part.content = contentPart.details;
1461
+ return part;
1462
+ }
1463
+ if (contentPart.type === "tool-call") {
1464
+ const tool = getToolState(state, contentPart.toolCallId, contentPart.toolName);
1465
+ const partBase = {
1466
+ id: tool.partId,
1467
+ type: "tool",
1468
+ toolName: contentPart.toolName,
1469
+ toolCallId: contentPart.toolCallId
1470
+ };
1471
+ if (contentPart.callId !== void 0) Object.assign(partBase, { callId: contentPart.callId });
1472
+ if (tool.internalCallId !== void 0) Object.assign(partBase, { internalCallId: tool.internalCallId });
1473
+ if (state.turn !== void 0) Object.assign(partBase, { turn: state.turn });
1474
+ if (contentPart.signature !== void 0) Object.assign(partBase, { signature: contentPart.signature });
1475
+ if (tool.result?.status === "success") {
1476
+ const part = {
1477
+ ...partBase,
1478
+ state: "output-available",
1479
+ input: contentPart.input,
1480
+ output: tool.result.output
1481
+ };
1482
+ if (tool.result.content !== void 0) part.resultContent = tool.result.content;
1483
+ return part;
1484
+ }
1485
+ if (tool.result?.status === "error") return {
1486
+ ...partBase,
1487
+ state: "error",
1488
+ input: contentPart.input,
1489
+ error: tool.result.error
1490
+ };
1491
+ return {
1492
+ ...partBase,
1493
+ state: "input-available",
1494
+ input: contentPart.input
1495
+ };
1496
+ }
1497
+ const attachment = contentAttachment(contentPart);
1498
+ return {
1499
+ id: createClientId("attachment_part"),
1500
+ type: "attachment",
1501
+ attachment
1502
+ };
1503
+ });
1900
1504
  }
1901
1505
  function getToolState(state, id, name) {
1902
- let tool = state.tools.get(id);
1903
- if (tool === void 0) {
1904
- tool = {
1905
- partId: createClientId("tool"),
1906
- toolCallId: id,
1907
- input: "",
1908
- started: false,
1909
- ended: false
1910
- };
1911
- if (name !== void 0) tool.toolName = name;
1912
- state.tools.set(id, tool);
1913
- } else if (name !== void 0) {
1914
- tool.toolName = name;
1915
- }
1916
- return tool;
1506
+ let tool = state.tools.get(id);
1507
+ if (tool === void 0) {
1508
+ tool = {
1509
+ partId: createClientId("tool"),
1510
+ toolCallId: id,
1511
+ input: "",
1512
+ started: false,
1513
+ ended: false
1514
+ };
1515
+ if (name !== void 0) tool.toolName = name;
1516
+ state.tools.set(id, tool);
1517
+ } else if (name !== void 0) tool.toolName = name;
1518
+ return tool;
1917
1519
  }
1918
1520
  function getToolResultState(state, toolName, toolCallId, callId, internalCallId) {
1919
- const matchedByToolCallId = state.tools.get(toolCallId);
1920
- const matchedByCallId = callId === void 0 ? void 0 : [...state.tools.values()].find((tool2) => tool2.callId === callId);
1921
- const tool = matchedByToolCallId ?? matchedByCallId ?? getToolState(state, toolCallId, toolName);
1922
- tool.toolName = toolName;
1923
- if (callId !== void 0) tool.callId = callId;
1924
- tool.internalCallId = internalCallId;
1925
- return tool;
1521
+ const matchedByToolCallId = state.tools.get(toolCallId);
1522
+ const matchedByCallId = callId === void 0 ? void 0 : [...state.tools.values()].find((tool) => tool.callId === callId);
1523
+ const tool = matchedByToolCallId ?? matchedByCallId ?? getToolState(state, toolCallId, toolName);
1524
+ tool.toolName = toolName;
1525
+ if (callId !== void 0) tool.callId = callId;
1526
+ tool.internalCallId = internalCallId;
1527
+ return tool;
1926
1528
  }
1927
1529
  function createReasoningState(id) {
1928
- const state = {
1929
- partId: createClientId("reasoning"),
1930
- text: "",
1931
- ended: false
1932
- };
1933
- if (id !== void 0) state.reasoningId = id;
1934
- return state;
1530
+ const state = {
1531
+ partId: createClientId("reasoning"),
1532
+ text: "",
1533
+ ended: false
1534
+ };
1535
+ if (id !== void 0) state.reasoningId = id;
1536
+ return state;
1935
1537
  }
1936
1538
  function contentAttachment(content) {
1937
- const attachment = {
1938
- id: createClientId("attachment"),
1939
- type: content.type === "image" ? "image" : "file"
1940
- };
1941
- if (content.type === "image") {
1942
- if (content.detail !== void 0) attachment.detail = content.detail;
1943
- if (content.mediaType !== void 0) attachment.mediaType = content.mediaType;
1944
- if (content.image.type === "url") attachment.url = content.image.url;
1945
- else attachment.data = content.image.data;
1946
- return attachment;
1947
- }
1948
- attachment.mediaType = content.mediaType;
1949
- if (content.filename !== void 0) attachment.name = content.filename;
1950
- if (content.data.type === "url") {
1951
- attachment.url = content.data.url;
1952
- } else if (content.data.type === "data") {
1953
- attachment.data = content.data.data;
1954
- } else {
1955
- attachment.text = content.data.text;
1956
- }
1957
- return attachment;
1539
+ const attachment = {
1540
+ id: createClientId("attachment"),
1541
+ type: content.type === "image" ? "image" : "file"
1542
+ };
1543
+ if (content.type === "image") {
1544
+ if (content.detail !== void 0) attachment.detail = content.detail;
1545
+ if (content.mediaType !== void 0) attachment.mediaType = content.mediaType;
1546
+ if (content.image.type === "url") attachment.url = content.image.url;
1547
+ else attachment.data = content.image.data;
1548
+ return attachment;
1549
+ }
1550
+ attachment.mediaType = content.mediaType;
1551
+ if (content.filename !== void 0) attachment.name = content.filename;
1552
+ if (content.data.type === "url") attachment.url = content.data.url;
1553
+ else if (content.data.type === "data") attachment.data = content.data.data;
1554
+ else attachment.text = content.data.text;
1555
+ return attachment;
1958
1556
  }
1959
1557
  function clientToolResult(output, result) {
1960
- switch (output.type) {
1961
- case "text":
1962
- return { status: "success", output: output.value };
1963
- case "json":
1964
- return { status: "success", output: output.value };
1965
- case "content":
1966
- return { status: "success", output: result, content: output.value };
1967
- case "execution-denied":
1968
- return {
1969
- status: "error",
1970
- error: {
1971
- message: output.reason ?? "Tool execution was denied.",
1972
- code: "tool_execution_denied"
1973
- }
1974
- };
1975
- case "error-text":
1976
- return {
1977
- status: "error",
1978
- error: { message: output.value, code: "tool_execution_error" }
1979
- };
1980
- case "error-json":
1981
- return {
1982
- status: "error",
1983
- error: {
1984
- message: "Tool execution failed.",
1985
- code: "tool_execution_error",
1986
- details: output.value
1987
- }
1988
- };
1989
- }
1558
+ switch (output.type) {
1559
+ case "text": return {
1560
+ status: "success",
1561
+ output: output.value
1562
+ };
1563
+ case "json": return {
1564
+ status: "success",
1565
+ output: output.value
1566
+ };
1567
+ case "content": return {
1568
+ status: "success",
1569
+ output: result,
1570
+ content: output.value
1571
+ };
1572
+ case "execution-denied": return {
1573
+ status: "error",
1574
+ error: {
1575
+ message: output.reason ?? "Tool execution was denied.",
1576
+ code: "tool_execution_denied"
1577
+ }
1578
+ };
1579
+ case "error-text": return {
1580
+ status: "error",
1581
+ error: {
1582
+ message: output.value,
1583
+ code: "tool_execution_error"
1584
+ }
1585
+ };
1586
+ case "error-json": return {
1587
+ status: "error",
1588
+ error: {
1589
+ message: "Tool execution failed.",
1590
+ code: "tool_execution_error",
1591
+ details: output.value
1592
+ }
1593
+ };
1594
+ }
1990
1595
  }
1991
1596
  function parseJsonOrString(value) {
1992
- try {
1993
- const parsed = JSON.parse(value);
1994
- return isJsonValue3(parsed) ? parsed : value;
1995
- } catch {
1996
- return value;
1997
- }
1597
+ try {
1598
+ const parsed = JSON.parse(value);
1599
+ return isJsonValue$1(parsed) ? parsed : value;
1600
+ } catch {
1601
+ return value;
1602
+ }
1998
1603
  }
1999
1604
  function clientOutput(output, mapper) {
2000
- const mapped = mapper === void 0 ? isJsonValue3(output) ? output : void 0 : mapper(output);
2001
- if (mapped !== void 0 && !isJsonValue3(mapped)) {
2002
- throw new TypeError("mapOutput must return a strict JSON value or undefined.");
2003
- }
2004
- return mapped;
1605
+ const mapped = mapper === void 0 ? isJsonValue$1(output) ? output : void 0 : mapper(output);
1606
+ if (mapped !== void 0 && !isJsonValue$1(mapped)) throw new TypeError("mapOutput must return a strict JSON value or undefined.");
1607
+ return mapped;
2005
1608
  }
2006
1609
  function valueFingerprint(value) {
2007
- if (value === null) return "null";
2008
- if (value === void 0) return "undefined";
2009
- if (Array.isArray(value)) return `[${value.map(valueFingerprint).join(",")}]`;
2010
- if (typeof value === "object") {
2011
- return `{${Object.entries(value).sort(([left], [right]) => left.localeCompare(right)).map(([key, entry]) => `${JSON.stringify(key)}:${valueFingerprint(entry)}`).join(",")}}`;
2012
- }
2013
- return `${typeof value}:${JSON.stringify(value)}`;
1610
+ if (value === null) return "null";
1611
+ if (value === void 0) return "undefined";
1612
+ if (Array.isArray(value)) return `[${value.map(valueFingerprint).join(",")}]`;
1613
+ if (typeof value === "object") return `{${Object.entries(value).sort(([left], [right]) => left.localeCompare(right)).map(([key, entry]) => `${JSON.stringify(key)}:${valueFingerprint(entry)}`).join(",")}}`;
1614
+ return `${typeof value}:${JSON.stringify(value)}`;
2014
1615
  }
2015
1616
  function clientTrace(trace) {
2016
- const result = {
2017
- observer: trace.observer
2018
- };
2019
- if (trace.traceId !== void 0) result.traceId = trace.traceId;
2020
- if (trace.observationId !== void 0) result.observationId = trace.observationId;
2021
- return result;
1617
+ const result = { observer: trace.observer };
1618
+ if (trace.traceId !== void 0) result.traceId = trace.traceId;
1619
+ if (trace.observationId !== void 0) result.observationId = trace.observationId;
1620
+ return result;
2022
1621
  }
2023
1622
  function mapClientError(error, mapper) {
2024
- const mapped = mapper?.(error) ?? maskedClientError();
2025
- if (typeof mapped.message !== "string" || mapped.details !== void 0 && !isJsonValue3(mapped.details)) {
2026
- throw new TypeError("mapError must return a JSON-safe ClientStreamError.");
2027
- }
2028
- return mapped;
1623
+ const mapped = mapper?.(error) ?? maskedClientError();
1624
+ if (typeof mapped.message !== "string" || mapped.details !== void 0 && !isJsonValue$1(mapped.details)) throw new TypeError("mapError must return a JSON-safe ClientStreamError.");
1625
+ return mapped;
2029
1626
  }
2030
1627
  function clientEvent(state, event) {
2031
- return scopedEvent(state.runId, state.turn, state.scope, event);
1628
+ return scopedEvent(state.runId, state.turn, state.scope, event);
2032
1629
  }
2033
1630
  function rootEvent(runId, event, scope) {
2034
- return scopedEvent(runId, void 0, scope, event);
1631
+ return scopedEvent(runId, void 0, scope, event);
2035
1632
  }
2036
1633
  function scopedEvent(runId, turn, scope, event) {
2037
- let scoped = { runId, ...event };
2038
- if (turn !== void 0) scoped = { ...scoped, turn };
2039
- if (scope !== void 0) scoped = { ...scoped, scope };
2040
- return scoped;
1634
+ let scoped = {
1635
+ runId,
1636
+ ...event
1637
+ };
1638
+ if (turn !== void 0) scoped = {
1639
+ ...scoped,
1640
+ turn
1641
+ };
1642
+ if (scope !== void 0) scoped = {
1643
+ ...scoped,
1644
+ scope
1645
+ };
1646
+ return scoped;
2041
1647
  }
2042
1648
  function scopeKey(scope) {
2043
- if (scope === void 0) return "root";
2044
- return [
2045
- scope.agentId,
2046
- scope.parentRunId,
2047
- scope.parentToolName,
2048
- scope.parentToolCallId,
2049
- scope.parentInternalToolCallId
2050
- ].join(":");
1649
+ if (scope === void 0) return "root";
1650
+ return [
1651
+ scope.agentId,
1652
+ scope.parentRunId,
1653
+ scope.parentToolName,
1654
+ scope.parentToolCallId,
1655
+ scope.parentInternalToolCallId
1656
+ ].join(":");
2051
1657
  }
2052
1658
  function isRootTerminalAgentEvent(event) {
2053
- return event.type === "response" || event.type === "interaction" || event.type === "blocked" || event.type === "error";
1659
+ return event.type === "response" || event.type === "interaction" || event.type === "blocked" || event.type === "error";
2054
1660
  }
2055
1661
  function agentOutcomeStatus(type) {
2056
- if (type === "response") return "completed";
2057
- if (type === "interaction") return "suspended";
2058
- return "blocked";
1662
+ if (type === "response") return "completed";
1663
+ if (type === "interaction") return "suspended";
1664
+ return "blocked";
2059
1665
  }
2060
1666
  function propagateCancellation(source, transform) {
2061
- return {
2062
- [Symbol.asyncIterator]() {
2063
- const sourceIterator = source[Symbol.asyncIterator]();
2064
- const sharedSource = {
2065
- [Symbol.asyncIterator]: () => sourceIterator
2066
- };
2067
- const outputIterator = transform(sharedSource)[Symbol.asyncIterator]();
2068
- let returned = false;
2069
- return {
2070
- next: () => outputIterator.next(),
2071
- async return() {
2072
- if (returned) return { done: true, value: void 0 };
2073
- returned = true;
2074
- const sourceReturn = sourceIterator.return?.();
2075
- const outputReturn = outputIterator.return?.();
2076
- await Promise.all([sourceReturn, outputReturn]);
2077
- return { done: true, value: void 0 };
2078
- }
2079
- };
2080
- }
2081
- };
1667
+ return { [Symbol.asyncIterator]() {
1668
+ const sourceIterator = source[Symbol.asyncIterator]();
1669
+ const outputIterator = transform({ [Symbol.asyncIterator]: () => sourceIterator })[Symbol.asyncIterator]();
1670
+ let returned = false;
1671
+ return {
1672
+ next: () => outputIterator.next(),
1673
+ async return() {
1674
+ if (returned) return {
1675
+ done: true,
1676
+ value: void 0
1677
+ };
1678
+ returned = true;
1679
+ const sourceReturn = sourceIterator.return?.();
1680
+ const outputReturn = outputIterator.return?.();
1681
+ await Promise.all([sourceReturn, outputReturn]);
1682
+ return {
1683
+ done: true,
1684
+ value: void 0
1685
+ };
1686
+ }
1687
+ };
1688
+ } };
2082
1689
  }
2083
-
2084
1690
  // src/client-transport.ts
2085
1691
  function createHttpClientTransport(options) {
2086
- const transport = createFetchEventTransport({
2087
- ...options,
2088
- mapEvent: (event) => parseClientStreamFrame(event, protocolOptions(options)),
2089
- validateResponse(response) {
2090
- if (response.headers.get("x-anvia-stream-protocol") !== CLIENT_STREAM_PROTOCOL) {
2091
- throw new ClientProtocolError(
2092
- `Expected x-anvia-stream-protocol: ${CLIENT_STREAM_PROTOCOL}.`
2093
- );
2094
- }
2095
- }
2096
- });
2097
- return {
2098
- async *send(sendOptions) {
2099
- const resume = sendOptions.resume ?? resumeCursorFromRequest(sendOptions.request);
2100
- yield* validateFrameSequence(transport.send(sendOptions), resume);
2101
- }
2102
- };
1692
+ const transport = createFetchEventTransport({
1693
+ ...options,
1694
+ mapEvent: (event) => parseClientStreamFrame(event, protocolOptions(options)),
1695
+ validateResponse(response) {
1696
+ if (response.headers.get("x-anvia-stream-protocol") !== "anvia.client.v3") throw new ClientProtocolError(`Expected x-anvia-stream-protocol: ${CLIENT_STREAM_PROTOCOL}.`);
1697
+ }
1698
+ });
1699
+ return { async *send(sendOptions) {
1700
+ const resume = sendOptions.resume ?? resumeCursorFromRequest(sendOptions.request);
1701
+ yield* validateFrameSequence(transport.send(sendOptions), resume);
1702
+ } };
2103
1703
  }
2104
1704
  function createDirectClientTransport(options) {
2105
- return {
2106
- async *send(sendOptions) {
2107
- const resume = sendOptions.resume ?? resumeCursorFromRequest(sendOptions.request);
2108
- if (resume !== void 0) {
2109
- throw new ClientProtocolError("Direct client transports do not support resume cursors.");
2110
- }
2111
- const handlerOptions = {
2112
- request: sendOptions.request
2113
- };
2114
- if (sendOptions.abortSignal !== void 0) {
2115
- handlerOptions.abortSignal = sendOptions.abortSignal;
2116
- }
2117
- if (sendOptions.headers !== void 0) handlerOptions.headers = sendOptions.headers;
2118
- const events = await options.handler(handlerOptions);
2119
- const iterator = events[Symbol.asyncIterator]();
2120
- const streamId = createClientId("stream");
2121
- let eventId = 0;
2122
- yield {
2123
- type: "stream_start",
2124
- protocol: CLIENT_STREAM_PROTOCOL,
2125
- streamId,
2126
- eventId: 0,
2127
- resumable: false
2128
- };
2129
- let status = "completed";
2130
- try {
2131
- let closePromise;
2132
- const close = () => {
2133
- closePromise ??= Promise.resolve(iterator.return?.());
2134
- return closePromise;
2135
- };
2136
- const onAbort = () => {
2137
- void close();
2138
- };
2139
- sendOptions.abortSignal?.addEventListener("abort", onAbort, { once: true });
2140
- try {
2141
- while (!sendOptions.abortSignal?.aborted) {
2142
- const next = await iterator.next();
2143
- if (next.done) break;
2144
- const event = parseClientStreamEvent(
2145
- next.value,
2146
- protocolOptions(options)
2147
- );
2148
- eventId += 1;
2149
- yield { type: "stream_event", streamId, eventId, event };
2150
- }
2151
- } finally {
2152
- sendOptions.abortSignal?.removeEventListener("abort", onAbort);
2153
- await close();
2154
- }
2155
- } catch {
2156
- status = "error";
2157
- }
2158
- yield { type: "stream_end", streamId, eventId, status };
2159
- }
2160
- };
1705
+ return { async *send(sendOptions) {
1706
+ if ((sendOptions.resume ?? resumeCursorFromRequest(sendOptions.request)) !== void 0) throw new ClientProtocolError("Direct client transports do not support resume cursors.");
1707
+ const handlerOptions = { request: sendOptions.request };
1708
+ if (sendOptions.abortSignal !== void 0) handlerOptions.abortSignal = sendOptions.abortSignal;
1709
+ if (sendOptions.headers !== void 0) handlerOptions.headers = sendOptions.headers;
1710
+ const iterator = (await options.handler(handlerOptions))[Symbol.asyncIterator]();
1711
+ const streamId = createClientId("stream");
1712
+ let eventId = 0;
1713
+ yield {
1714
+ type: "stream_start",
1715
+ protocol: CLIENT_STREAM_PROTOCOL,
1716
+ streamId,
1717
+ eventId: 0,
1718
+ resumable: false
1719
+ };
1720
+ let status = "completed";
1721
+ try {
1722
+ let closePromise;
1723
+ const close = () => {
1724
+ closePromise ??= Promise.resolve(iterator.return?.());
1725
+ return closePromise;
1726
+ };
1727
+ const onAbort = () => {
1728
+ close();
1729
+ };
1730
+ sendOptions.abortSignal?.addEventListener("abort", onAbort, { once: true });
1731
+ try {
1732
+ while (!sendOptions.abortSignal?.aborted) {
1733
+ const next = await iterator.next();
1734
+ if (next.done) break;
1735
+ const event = parseClientStreamEvent(next.value, protocolOptions(options));
1736
+ eventId += 1;
1737
+ yield {
1738
+ type: "stream_event",
1739
+ streamId,
1740
+ eventId,
1741
+ event
1742
+ };
1743
+ }
1744
+ } finally {
1745
+ sendOptions.abortSignal?.removeEventListener("abort", onAbort);
1746
+ await close();
1747
+ }
1748
+ } catch {
1749
+ status = "error";
1750
+ }
1751
+ yield {
1752
+ type: "stream_end",
1753
+ streamId,
1754
+ eventId,
1755
+ status
1756
+ };
1757
+ } };
2161
1758
  }
2162
1759
  async function* validateFrameSequence(frames, resume) {
2163
- let streamId;
2164
- let lastEventId = resume?.after ?? 0;
2165
- let ended = false;
2166
- for await (const frame of frames) {
2167
- if (ended) throw new ClientProtocolError("Received a frame after stream_end.", frame);
2168
- if (streamId === void 0) {
2169
- if (frame.type !== "stream_start") {
2170
- throw new ClientProtocolError("The first client stream frame must be stream_start.", frame);
2171
- }
2172
- streamId = frame.streamId;
2173
- if (resume !== void 0 && frame.streamId !== resume.streamId) {
2174
- throw new ClientProtocolError("Resume response streamId does not match the cursor.", frame);
2175
- }
2176
- if (resume !== void 0 && !frame.resumable) {
2177
- throw new ClientProtocolError("Resume response must identify a resumable stream.", frame);
2178
- }
2179
- } else if (frame.type === "stream_start") {
2180
- throw new ClientProtocolError("Received more than one stream_start frame.", frame);
2181
- } else if (frame.streamId !== streamId) {
2182
- throw new ClientProtocolError("Client streamId changed during the response.", frame);
2183
- }
2184
- if (frame.type === "stream_event") {
2185
- if (frame.eventId !== lastEventId + 1) {
2186
- throw new ClientProtocolError("Client stream event IDs must be contiguous.", frame);
2187
- }
2188
- lastEventId = frame.eventId;
2189
- } else if (frame.type === "stream_end") {
2190
- if (frame.eventId !== lastEventId) {
2191
- throw new ClientProtocolError("stream_end has an invalid eventId.", frame);
2192
- }
2193
- ended = true;
2194
- }
2195
- yield frame;
2196
- }
2197
- if (streamId === void 0 || !ended) {
2198
- throw new ClientProtocolError("Client stream ended without a complete frame sequence.");
2199
- }
1760
+ let streamId;
1761
+ let lastEventId = resume?.after ?? 0;
1762
+ let ended = false;
1763
+ for await (const frame of frames) {
1764
+ if (ended) throw new ClientProtocolError("Received a frame after stream_end.", frame);
1765
+ if (streamId === void 0) {
1766
+ if (frame.type !== "stream_start") throw new ClientProtocolError("The first client stream frame must be stream_start.", frame);
1767
+ streamId = frame.streamId;
1768
+ if (resume !== void 0 && frame.streamId !== resume.streamId) throw new ClientProtocolError("Resume response streamId does not match the cursor.", frame);
1769
+ if (resume !== void 0 && !frame.resumable) throw new ClientProtocolError("Resume response must identify a resumable stream.", frame);
1770
+ } else if (frame.type === "stream_start") throw new ClientProtocolError("Received more than one stream_start frame.", frame);
1771
+ else if (frame.streamId !== streamId) throw new ClientProtocolError("Client streamId changed during the response.", frame);
1772
+ if (frame.type === "stream_event") {
1773
+ if (frame.eventId !== lastEventId + 1) throw new ClientProtocolError("Client stream event IDs must be contiguous.", frame);
1774
+ lastEventId = frame.eventId;
1775
+ } else if (frame.type === "stream_end") {
1776
+ if (frame.eventId !== lastEventId) throw new ClientProtocolError("stream_end has an invalid eventId.", frame);
1777
+ ended = true;
1778
+ }
1779
+ yield frame;
1780
+ }
1781
+ if (streamId === void 0 || !ended) throw new ClientProtocolError("Client stream ended without a complete frame sequence.");
2200
1782
  }
2201
1783
  function protocolOptions(options) {
2202
- const result = {};
2203
- if (options.metadataSchema !== void 0) result.metadataSchema = options.metadataSchema;
2204
- if (options.dataSchemas !== void 0) result.dataSchemas = options.dataSchemas;
2205
- return result;
1784
+ const result = {};
1785
+ if (options.metadataSchema !== void 0) result.metadataSchema = options.metadataSchema;
1786
+ if (options.dataSchemas !== void 0) result.dataSchemas = options.dataSchemas;
1787
+ return result;
2206
1788
  }
2207
1789
  function resumeCursorFromRequest(value) {
2208
- if (typeof value !== "object" || value === null || !("resume" in value)) return void 0;
2209
- const resume = value.resume;
2210
- if (typeof resume !== "object" || resume === null) return void 0;
2211
- if (!("streamId" in resume) || !("after" in resume)) return void 0;
2212
- return typeof resume.streamId === "string" && typeof resume.after === "number" && Number.isSafeInteger(resume.after) && resume.after >= 0 ? { streamId: resume.streamId, after: resume.after } : void 0;
1790
+ if (typeof value !== "object" || value === null || !("resume" in value)) return void 0;
1791
+ const resume = value.resume;
1792
+ if (typeof resume !== "object" || resume === null) return void 0;
1793
+ if (!("streamId" in resume) || !("after" in resume)) return void 0;
1794
+ return typeof resume.streamId === "string" && typeof resume.after === "number" && Number.isSafeInteger(resume.after) && resume.after >= 0 ? {
1795
+ streamId: resume.streamId,
1796
+ after: resume.after
1797
+ } : void 0;
2213
1798
  }
2214
-
2215
- // src/index.ts
2216
- import { isJsonValue as isJsonValue5 } from "@anvia/core/completion";
2217
-
2218
1799
  // src/reducer.ts
2219
- import { isJsonValue as isJsonValue4 } from "@anvia/core/completion";
2220
1800
  function applyClientStreamEvent(messages, event) {
2221
- if (event.scope?.parentToolCallId !== void 0) {
2222
- return messages;
2223
- }
2224
- switch (event.type) {
2225
- case "message_reset":
2226
- return messages.map(
2227
- (message) => message.id === event.messageId ? { id: message.id, role: message.role, parts: [] } : message
2228
- );
2229
- case "message_start": {
2230
- if (messages.some((message2) => message2.id === event.messageId)) return messages;
2231
- let message = {
2232
- id: event.messageId,
2233
- role: event.role,
2234
- parts: []
2235
- };
2236
- if (event.metadata !== void 0) message = { ...message, metadata: event.metadata };
2237
- return [...messages, message];
2238
- }
2239
- case "text_start":
2240
- return upsertPart(messages, event.messageId, {
2241
- id: event.partId,
2242
- type: "text",
2243
- text: ""
2244
- });
2245
- case "text_delta":
2246
- return updatePart(messages, event.messageId, event.partId, (part) => ({
2247
- id: event.partId,
2248
- type: "text",
2249
- text: part?.type === "text" ? `${part.text}${event.delta}` : event.delta
2250
- }));
2251
- case "text_end":
2252
- return updatePart(messages, event.messageId, event.partId, (part) => {
2253
- const next = {
2254
- id: event.partId,
2255
- type: "text",
2256
- text: event.text ?? (part?.type === "text" ? part.text : "")
2257
- };
2258
- if (event.signature !== void 0) next.signature = event.signature;
2259
- return next;
2260
- });
2261
- case "reasoning_start": {
2262
- const reasoning = {
2263
- id: event.partId,
2264
- type: "reasoning",
2265
- text: ""
2266
- };
2267
- if (event.reasoningId !== void 0) reasoning.reasoningId = event.reasoningId;
2268
- return upsertPart(messages, event.messageId, reasoning);
2269
- }
2270
- case "reasoning_delta":
2271
- return updatePart(messages, event.messageId, event.partId, (part) => {
2272
- const reasoning = {
2273
- id: event.partId,
2274
- type: "reasoning",
2275
- text: part?.type === "reasoning" ? `${part.text}${event.delta}` : event.delta
2276
- };
2277
- if (part?.type === "reasoning" && part.reasoningId !== void 0) {
2278
- reasoning.reasoningId = part.reasoningId;
2279
- }
2280
- const content = appendReasoningContent(
2281
- part?.type === "reasoning" ? part.content : void 0,
2282
- event
2283
- );
2284
- if (content !== void 0) reasoning.content = content;
2285
- return reasoning;
2286
- });
2287
- case "reasoning_end":
2288
- return updatePart(messages, event.messageId, event.partId, (part) => {
2289
- const reasoning = {
2290
- id: event.partId,
2291
- type: "reasoning",
2292
- text: event.text ?? (part?.type === "reasoning" ? part.text : "")
2293
- };
2294
- if (part?.type === "reasoning" && part.reasoningId !== void 0) {
2295
- reasoning.reasoningId = part.reasoningId;
2296
- }
2297
- if (event.content !== void 0) {
2298
- reasoning.content = event.content;
2299
- } else if (part?.type === "reasoning" && part.content !== void 0) {
2300
- reasoning.content = part.content;
2301
- }
2302
- return reasoning;
2303
- });
2304
- case "tool_call_start": {
2305
- const part = {
2306
- id: event.partId,
2307
- type: "tool",
2308
- toolName: event.toolName ?? "",
2309
- toolCallId: event.toolCallId,
2310
- state: "input-streaming",
2311
- input: ""
2312
- };
2313
- if (event.callId !== void 0) part.callId = event.callId;
2314
- if (event.turn !== void 0) part.turn = event.turn;
2315
- return upsertPart(messages, event.messageId, part);
2316
- }
2317
- case "tool_call_delta":
2318
- return updatePart(messages, event.messageId, event.partId, (current) => {
2319
- const part = current?.type === "tool" ? toolPartBase(current) : {
2320
- id: event.partId,
2321
- type: "tool",
2322
- toolName: event.toolName ?? "",
2323
- toolCallId: event.toolCallId
2324
- };
2325
- const previous = current?.type === "tool" && typeof current.input === "string" ? current.input : "";
2326
- if (event.toolName !== void 0) part.toolName = event.toolName;
2327
- if (event.callId !== void 0) part.callId = event.callId;
2328
- if (event.signature !== void 0) part.signature = event.signature;
2329
- if (event.turn !== void 0) part.turn = event.turn;
2330
- return {
2331
- ...part,
2332
- state: "input-streaming",
2333
- input: event.mode === "replace" ? event.delta : `${previous}${event.delta}`
2334
- };
2335
- });
2336
- case "tool_call_end": {
2337
- const part = {
2338
- id: event.partId,
2339
- type: "tool",
2340
- toolName: event.toolName,
2341
- toolCallId: event.toolCallId,
2342
- state: "input-available",
2343
- input: event.input
2344
- };
2345
- if (event.callId !== void 0) part.callId = event.callId;
2346
- if (event.turn !== void 0) part.turn = event.turn;
2347
- if (event.signature !== void 0) part.signature = event.signature;
2348
- return upsertPart(messages, event.messageId, part);
2349
- }
2350
- case "tool_result":
2351
- return updatePart(messages, event.messageId, event.partId, (current) => {
2352
- const part = current?.type === "tool" ? toolPartBase(current) : {
2353
- id: event.partId,
2354
- type: "tool",
2355
- toolName: event.toolName,
2356
- toolCallId: event.toolCallId
2357
- };
2358
- if (event.callId !== void 0) part.callId = event.callId;
2359
- if (event.internalCallId !== void 0) part.internalCallId = event.internalCallId;
2360
- if (event.turn !== void 0) part.turn = event.turn;
2361
- if (event.result.status === "error") {
2362
- return {
2363
- ...part,
2364
- state: "error",
2365
- input: event.input,
2366
- error: event.result.error
2367
- };
2368
- }
2369
- const completed = {
2370
- ...part,
2371
- state: "output-available",
2372
- input: event.input,
2373
- output: event.result.output
2374
- };
2375
- if (event.result.content !== void 0) completed.resultContent = event.result.content;
2376
- return completed;
2377
- });
2378
- case "source":
2379
- return upsertPart(messages, event.messageId, {
2380
- id: event.partId,
2381
- type: "source",
2382
- source: event.source
2383
- });
2384
- case "attachment":
2385
- return upsertPart(messages, event.messageId, {
2386
- id: event.partId,
2387
- type: "attachment",
2388
- attachment: event.attachment
2389
- });
2390
- case "data":
2391
- if (event.transient === true) return messages;
2392
- return appendToLastAssistant(messages, {
2393
- id: createClientId("data"),
2394
- type: "data",
2395
- name: event.name,
2396
- data: event.data
2397
- });
2398
- case "message_end":
2399
- return messages.map((message) => {
2400
- if (message.id !== event.messageId) return message;
2401
- const metadata = mergeMetadata(message.metadata, event.metadata);
2402
- const generationUpdate = {
2403
- runId: event.runId
2404
- };
2405
- if (event.usage !== void 0) generationUpdate.usage = event.usage;
2406
- if (event.contextUsage !== void 0) {
2407
- generationUpdate.contextUsage = event.contextUsage;
2408
- }
2409
- const generation = mergeGeneration(message.generation, generationUpdate);
2410
- let updated = {
2411
- ...message,
2412
- generation
2413
- };
2414
- if (event.parts !== void 0) {
2415
- updated = { ...updated, parts: reconcileFinalParts(message.parts, event.parts) };
2416
- }
2417
- if (event.modelMessageId !== void 0) {
2418
- updated = { ...updated, modelMessageId: event.modelMessageId };
2419
- }
2420
- if (metadata !== void 0) updated = { ...updated, metadata };
2421
- return updated;
2422
- });
2423
- case "run_end": {
2424
- const generation = {
2425
- runId: event.runId,
2426
- status: event.status
2427
- };
2428
- if (event.contextUsage !== void 0) generation.contextUsage = event.contextUsage;
2429
- if (event.trace !== void 0) generation.trace = event.trace;
2430
- if (event.memoryCompaction !== void 0) {
2431
- generation.memoryCompaction = event.memoryCompaction;
2432
- }
2433
- return updateLastAssistantGeneration(messages, generation);
2434
- }
2435
- case "error":
2436
- return appendToLastAssistant(messages, {
2437
- id: createClientId("error"),
2438
- type: "error",
2439
- error: event.error
2440
- });
2441
- default:
2442
- return messages;
2443
- }
1801
+ if (event.scope?.parentToolCallId !== void 0) return messages;
1802
+ switch (event.type) {
1803
+ case "message_reset": return messages.map((message) => message.id === event.messageId ? {
1804
+ id: message.id,
1805
+ role: message.role,
1806
+ parts: []
1807
+ } : message);
1808
+ case "message_start": {
1809
+ if (messages.some((message) => message.id === event.messageId)) return messages;
1810
+ let message = {
1811
+ id: event.messageId,
1812
+ role: event.role,
1813
+ parts: []
1814
+ };
1815
+ if (event.metadata !== void 0) message = {
1816
+ ...message,
1817
+ metadata: event.metadata
1818
+ };
1819
+ return [...messages, message];
1820
+ }
1821
+ case "text_start": return upsertPart(messages, event.messageId, {
1822
+ id: event.partId,
1823
+ type: "text",
1824
+ text: ""
1825
+ });
1826
+ case "text_delta": return updatePart(messages, event.messageId, event.partId, (part) => ({
1827
+ id: event.partId,
1828
+ type: "text",
1829
+ text: part?.type === "text" ? `${part.text}${event.delta}` : event.delta
1830
+ }));
1831
+ case "text_end": return updatePart(messages, event.messageId, event.partId, (part) => {
1832
+ const next = {
1833
+ id: event.partId,
1834
+ type: "text",
1835
+ text: event.text ?? (part?.type === "text" ? part.text : "")
1836
+ };
1837
+ if (event.signature !== void 0) next.signature = event.signature;
1838
+ return next;
1839
+ });
1840
+ case "reasoning_start": {
1841
+ const reasoning = {
1842
+ id: event.partId,
1843
+ type: "reasoning",
1844
+ text: ""
1845
+ };
1846
+ if (event.reasoningId !== void 0) reasoning.reasoningId = event.reasoningId;
1847
+ return upsertPart(messages, event.messageId, reasoning);
1848
+ }
1849
+ case "reasoning_delta": return updatePart(messages, event.messageId, event.partId, (part) => {
1850
+ const reasoning = {
1851
+ id: event.partId,
1852
+ type: "reasoning",
1853
+ text: part?.type === "reasoning" ? `${part.text}${event.delta}` : event.delta
1854
+ };
1855
+ if (part?.type === "reasoning" && part.reasoningId !== void 0) reasoning.reasoningId = part.reasoningId;
1856
+ const content = appendReasoningContent(part?.type === "reasoning" ? part.content : void 0, event);
1857
+ if (content !== void 0) reasoning.content = content;
1858
+ return reasoning;
1859
+ });
1860
+ case "reasoning_end": return updatePart(messages, event.messageId, event.partId, (part) => {
1861
+ const reasoning = {
1862
+ id: event.partId,
1863
+ type: "reasoning",
1864
+ text: event.text ?? (part?.type === "reasoning" ? part.text : "")
1865
+ };
1866
+ if (part?.type === "reasoning" && part.reasoningId !== void 0) reasoning.reasoningId = part.reasoningId;
1867
+ if (event.content !== void 0) reasoning.content = event.content;
1868
+ else if (part?.type === "reasoning" && part.content !== void 0) reasoning.content = part.content;
1869
+ return reasoning;
1870
+ });
1871
+ case "tool_call_start": {
1872
+ const part = {
1873
+ id: event.partId,
1874
+ type: "tool",
1875
+ toolName: event.toolName ?? "",
1876
+ toolCallId: event.toolCallId,
1877
+ state: "input-streaming",
1878
+ input: ""
1879
+ };
1880
+ if (event.callId !== void 0) part.callId = event.callId;
1881
+ if (event.turn !== void 0) part.turn = event.turn;
1882
+ return upsertPart(messages, event.messageId, part);
1883
+ }
1884
+ case "tool_call_delta": return updatePart(messages, event.messageId, event.partId, (current) => {
1885
+ const part = current?.type === "tool" ? toolPartBase(current) : {
1886
+ id: event.partId,
1887
+ type: "tool",
1888
+ toolName: event.toolName ?? "",
1889
+ toolCallId: event.toolCallId
1890
+ };
1891
+ const previous = current?.type === "tool" && typeof current.input === "string" ? current.input : "";
1892
+ if (event.toolName !== void 0) part.toolName = event.toolName;
1893
+ if (event.callId !== void 0) part.callId = event.callId;
1894
+ if (event.signature !== void 0) part.signature = event.signature;
1895
+ if (event.turn !== void 0) part.turn = event.turn;
1896
+ return {
1897
+ ...part,
1898
+ state: "input-streaming",
1899
+ input: event.mode === "replace" ? event.delta : `${previous}${event.delta}`
1900
+ };
1901
+ });
1902
+ case "tool_call_end": {
1903
+ const part = {
1904
+ id: event.partId,
1905
+ type: "tool",
1906
+ toolName: event.toolName,
1907
+ toolCallId: event.toolCallId,
1908
+ state: "input-available",
1909
+ input: event.input
1910
+ };
1911
+ if (event.callId !== void 0) part.callId = event.callId;
1912
+ if (event.turn !== void 0) part.turn = event.turn;
1913
+ if (event.signature !== void 0) part.signature = event.signature;
1914
+ return upsertPart(messages, event.messageId, part);
1915
+ }
1916
+ case "tool_result": return updatePart(messages, event.messageId, event.partId, (current) => {
1917
+ const part = current?.type === "tool" ? toolPartBase(current) : {
1918
+ id: event.partId,
1919
+ type: "tool",
1920
+ toolName: event.toolName,
1921
+ toolCallId: event.toolCallId
1922
+ };
1923
+ if (event.callId !== void 0) part.callId = event.callId;
1924
+ if (event.internalCallId !== void 0) part.internalCallId = event.internalCallId;
1925
+ if (event.turn !== void 0) part.turn = event.turn;
1926
+ if (event.result.status === "error") return {
1927
+ ...part,
1928
+ state: "error",
1929
+ input: event.input,
1930
+ error: event.result.error
1931
+ };
1932
+ const completed = {
1933
+ ...part,
1934
+ state: "output-available",
1935
+ input: event.input,
1936
+ output: event.result.output
1937
+ };
1938
+ if (event.result.content !== void 0) completed.resultContent = event.result.content;
1939
+ return completed;
1940
+ });
1941
+ case "source": return upsertPart(messages, event.messageId, {
1942
+ id: event.partId,
1943
+ type: "source",
1944
+ source: event.source
1945
+ });
1946
+ case "attachment": return upsertPart(messages, event.messageId, {
1947
+ id: event.partId,
1948
+ type: "attachment",
1949
+ attachment: event.attachment
1950
+ });
1951
+ case "data":
1952
+ if (event.transient === true) return messages;
1953
+ return appendToLastAssistant(messages, {
1954
+ id: createClientId("data"),
1955
+ type: "data",
1956
+ name: event.name,
1957
+ data: event.data
1958
+ });
1959
+ case "message_end": return messages.map((message) => {
1960
+ if (message.id !== event.messageId) return message;
1961
+ const metadata = mergeMetadata(message.metadata, event.metadata);
1962
+ const generationUpdate = { runId: event.runId };
1963
+ if (event.usage !== void 0) generationUpdate.usage = event.usage;
1964
+ if (event.contextUsage !== void 0) generationUpdate.contextUsage = event.contextUsage;
1965
+ const generation = mergeGeneration(message.generation, generationUpdate);
1966
+ let updated = {
1967
+ ...message,
1968
+ generation
1969
+ };
1970
+ if (event.parts !== void 0) updated = {
1971
+ ...updated,
1972
+ parts: reconcileFinalParts(message.parts, event.parts)
1973
+ };
1974
+ if (event.modelMessageId !== void 0) updated = {
1975
+ ...updated,
1976
+ modelMessageId: event.modelMessageId
1977
+ };
1978
+ if (metadata !== void 0) updated = {
1979
+ ...updated,
1980
+ metadata
1981
+ };
1982
+ return updated;
1983
+ });
1984
+ case "run_end": {
1985
+ const generation = {
1986
+ runId: event.runId,
1987
+ status: event.status
1988
+ };
1989
+ if (event.contextUsage !== void 0) generation.contextUsage = event.contextUsage;
1990
+ if (event.trace !== void 0) generation.trace = event.trace;
1991
+ if (event.memoryCompaction !== void 0) generation.memoryCompaction = event.memoryCompaction;
1992
+ return updateLastAssistantGeneration(messages, generation);
1993
+ }
1994
+ case "error": return appendToLastAssistant(messages, {
1995
+ id: createClientId("error"),
1996
+ type: "error",
1997
+ error: event.error
1998
+ });
1999
+ default: return messages;
2000
+ }
2444
2001
  }
2445
2002
  function toolPartBase(part) {
2446
- const base = {
2447
- id: part.id,
2448
- type: part.type,
2449
- toolName: part.toolName,
2450
- toolCallId: part.toolCallId
2451
- };
2452
- if (part.callId !== void 0) Object.assign(base, { callId: part.callId });
2453
- if (part.internalCallId !== void 0) {
2454
- Object.assign(base, { internalCallId: part.internalCallId });
2455
- }
2456
- if (part.turn !== void 0) Object.assign(base, { turn: part.turn });
2457
- if (part.signature !== void 0) Object.assign(base, { signature: part.signature });
2458
- return base;
2003
+ const base = {
2004
+ id: part.id,
2005
+ type: part.type,
2006
+ toolName: part.toolName,
2007
+ toolCallId: part.toolCallId
2008
+ };
2009
+ if (part.callId !== void 0) Object.assign(base, { callId: part.callId });
2010
+ if (part.internalCallId !== void 0) Object.assign(base, { internalCallId: part.internalCallId });
2011
+ if (part.turn !== void 0) Object.assign(base, { turn: part.turn });
2012
+ if (part.signature !== void 0) Object.assign(base, { signature: part.signature });
2013
+ return base;
2459
2014
  }
2460
2015
  function reconcileFinalParts(current, final) {
2461
- const clientOnly = current.filter(
2462
- (part) => part.type === "source" || part.type === "data" || part.type === "error"
2463
- );
2464
- return [...final, ...clientOnly];
2016
+ const clientOnly = current.filter((part) => part.type === "source" || part.type === "data" || part.type === "error");
2017
+ return [...final, ...clientOnly];
2465
2018
  }
2466
2019
  function appendReasoningContent(current, event) {
2467
- if (event.contentType === void 0 && event.signature === void 0) return current;
2468
- const type = event.contentType ?? "text";
2469
- const next = [...current ?? []];
2470
- const last = next.at(-1);
2471
- if (type === "text") {
2472
- if (last?.type === "text" && last.signature === event.signature) {
2473
- next[next.length - 1] = { ...last, text: `${last.text}${event.delta}` };
2474
- } else {
2475
- let detail = {
2476
- type,
2477
- text: event.delta
2478
- };
2479
- if (event.signature !== void 0) detail = { ...detail, signature: event.signature };
2480
- next.push(detail);
2481
- }
2482
- return next;
2483
- }
2484
- if (type === "summary") {
2485
- if (last?.type === "summary") {
2486
- next[next.length - 1] = { ...last, text: `${last.text}${event.delta}` };
2487
- } else next.push({ type, text: event.delta });
2488
- return next;
2489
- }
2490
- if (type === "encrypted") {
2491
- if (last?.type === "encrypted") {
2492
- next[next.length - 1] = { ...last, data: `${last.data}${event.delta}` };
2493
- } else next.push({ type, data: event.delta });
2494
- return next;
2495
- }
2496
- if (last?.type === "redacted") {
2497
- next[next.length - 1] = { ...last, data: `${last.data}${event.delta}` };
2498
- } else next.push({ type, data: event.delta });
2499
- return next;
2020
+ if (event.contentType === void 0 && event.signature === void 0) return current;
2021
+ const type = event.contentType ?? "text";
2022
+ const next = [...current ?? []];
2023
+ const last = next.at(-1);
2024
+ if (type === "text") {
2025
+ if (last?.type === "text" && last.signature === event.signature) next[next.length - 1] = {
2026
+ ...last,
2027
+ text: `${last.text}${event.delta}`
2028
+ };
2029
+ else {
2030
+ let detail = {
2031
+ type,
2032
+ text: event.delta
2033
+ };
2034
+ if (event.signature !== void 0) detail = {
2035
+ ...detail,
2036
+ signature: event.signature
2037
+ };
2038
+ next.push(detail);
2039
+ }
2040
+ return next;
2041
+ }
2042
+ if (type === "summary") {
2043
+ if (last?.type === "summary") next[next.length - 1] = {
2044
+ ...last,
2045
+ text: `${last.text}${event.delta}`
2046
+ };
2047
+ else next.push({
2048
+ type,
2049
+ text: event.delta
2050
+ });
2051
+ return next;
2052
+ }
2053
+ if (type === "encrypted") {
2054
+ if (last?.type === "encrypted") next[next.length - 1] = {
2055
+ ...last,
2056
+ data: `${last.data}${event.delta}`
2057
+ };
2058
+ else next.push({
2059
+ type,
2060
+ data: event.delta
2061
+ });
2062
+ return next;
2063
+ }
2064
+ if (last?.type === "redacted") next[next.length - 1] = {
2065
+ ...last,
2066
+ data: `${last.data}${event.delta}`
2067
+ };
2068
+ else next.push({
2069
+ type,
2070
+ data: event.delta
2071
+ });
2072
+ return next;
2500
2073
  }
2501
2074
  function messageText(message) {
2502
- return message.parts.flatMap((part) => part.type === "text" ? [part.text] : []).join("");
2075
+ return message.parts.flatMap((part) => part.type === "text" ? [part.text] : []).join("");
2503
2076
  }
2504
2077
  function assistantText(messages) {
2505
- const assistant = [...messages].reverse().find((message) => message.role === "assistant");
2506
- return assistant === void 0 ? "" : messageText(assistant);
2078
+ const assistant = [...messages].reverse().find((message) => message.role === "assistant");
2079
+ return assistant === void 0 ? "" : messageText(assistant);
2507
2080
  }
2508
2081
  function upsertPart(messages, messageId, part) {
2509
- return updatePart(messages, messageId, part.id, () => part);
2082
+ return updatePart(messages, messageId, part.id, () => part);
2510
2083
  }
2511
2084
  function updatePart(messages, messageId, partId, update) {
2512
- const current = ensureAssistant(messages, messageId);
2513
- return current.map((message) => {
2514
- if (message.id !== messageId) return message;
2515
- const index = message.parts.findIndex((part) => part.id === partId);
2516
- if (index === -1) return { ...message, parts: [...message.parts, update(void 0)] };
2517
- const parts = [...message.parts];
2518
- parts[index] = update(parts[index]);
2519
- return { ...message, parts };
2520
- });
2085
+ return ensureAssistant(messages, messageId).map((message) => {
2086
+ if (message.id !== messageId) return message;
2087
+ const index = message.parts.findIndex((part) => part.id === partId);
2088
+ if (index === -1) return {
2089
+ ...message,
2090
+ parts: [...message.parts, update(void 0)]
2091
+ };
2092
+ const parts = [...message.parts];
2093
+ parts[index] = update(parts[index]);
2094
+ return {
2095
+ ...message,
2096
+ parts
2097
+ };
2098
+ });
2521
2099
  }
2522
2100
  function ensureAssistant(messages, messageId) {
2523
- return messages.some((message) => message.id === messageId) ? messages : [...messages, { id: messageId, role: "assistant", parts: [] }];
2101
+ return messages.some((message) => message.id === messageId) ? messages : [...messages, {
2102
+ id: messageId,
2103
+ role: "assistant",
2104
+ parts: []
2105
+ }];
2524
2106
  }
2525
2107
  function appendToLastAssistant(messages, part) {
2526
- const index = findLastIndex(messages, (message2) => message2.role === "assistant");
2527
- if (index === -1) {
2528
- return [...messages, { id: createClientId("msg"), role: "assistant", parts: [part] }];
2529
- }
2530
- const next = [...messages];
2531
- const message = next[index];
2532
- next[index] = { ...message, parts: [...message.parts, part] };
2533
- return next;
2108
+ const index = findLastIndex(messages, (message) => message.role === "assistant");
2109
+ if (index === -1) return [...messages, {
2110
+ id: createClientId("msg"),
2111
+ role: "assistant",
2112
+ parts: [part]
2113
+ }];
2114
+ const next = [...messages];
2115
+ const message = next[index];
2116
+ next[index] = {
2117
+ ...message,
2118
+ parts: [...message.parts, part]
2119
+ };
2120
+ return next;
2534
2121
  }
2535
2122
  function updateLastAssistantGeneration(messages, value) {
2536
- const index = findLastIndex(messages, (message2) => message2.role === "assistant");
2537
- if (index === -1) return messages;
2538
- const next = [...messages];
2539
- const message = next[index];
2540
- next[index] = { ...message, generation: mergeGeneration(message.generation, value) };
2541
- return next;
2123
+ const index = findLastIndex(messages, (message) => message.role === "assistant");
2124
+ if (index === -1) return messages;
2125
+ const next = [...messages];
2126
+ const message = next[index];
2127
+ next[index] = {
2128
+ ...message,
2129
+ generation: mergeGeneration(message.generation, value)
2130
+ };
2131
+ return next;
2542
2132
  }
2543
2133
  function mergeMetadata(current, provided) {
2544
- if (provided === void 0) return current;
2545
- if (!isRecord2(current) || !isRecord2(provided)) return provided;
2546
- const next = { ...current, ...provided };
2547
- return isJsonValue4(next) ? next : provided;
2134
+ if (provided === void 0) return current;
2135
+ if (!isRecord(current) || !isRecord(provided)) return provided;
2136
+ const next = {
2137
+ ...current,
2138
+ ...provided
2139
+ };
2140
+ return isJsonValue$1(next) ? next : provided;
2548
2141
  }
2549
2142
  function mergeGeneration(current, provided) {
2550
- return {
2551
- ...current,
2552
- ...Object.fromEntries(Object.entries(provided).filter(([, value]) => value !== void 0))
2553
- };
2143
+ return {
2144
+ ...current,
2145
+ ...Object.fromEntries(Object.entries(provided).filter(([, value]) => value !== void 0))
2146
+ };
2554
2147
  }
2555
2148
  function findLastIndex(items, predicate) {
2556
- for (let index = items.length - 1; index >= 0; index -= 1) {
2557
- if (predicate(items[index])) return index;
2558
- }
2559
- return -1;
2560
- }
2561
- function isRecord2(value) {
2562
- return typeof value === "object" && value !== null && !Array.isArray(value);
2563
- }
2564
- export {
2565
- CLIENT_STREAM_PROTOCOL,
2566
- ClientProtocolError,
2567
- agentToClientStream,
2568
- applyClientStreamEvent,
2569
- assistantText,
2570
- completionToClientStream,
2571
- createClientId,
2572
- createDirectClientTransport,
2573
- createHttpClientTransport,
2574
- customAgentEventsToClientStream,
2575
- isJsonValue5 as isJsonValue,
2576
- maskedClientError,
2577
- messageText,
2578
- messagesToUIMessages,
2579
- normalizeClientError,
2580
- parseClientStreamEvent,
2581
- parseClientStreamFrame,
2582
- parseClientStreamRequest,
2583
- parseUIMessage,
2584
- parseUIMessages,
2585
- uiMessagesToMessages
2586
- };
2149
+ for (let index = items.length - 1; index >= 0; index -= 1) if (predicate(items[index])) return index;
2150
+ return -1;
2151
+ }
2152
+ function isRecord(value) {
2153
+ return typeof value === "object" && value !== null && !Array.isArray(value);
2154
+ }
2155
+ export { CLIENT_STREAM_PROTOCOL, ClientProtocolError, agentToClientStream, applyClientStreamEvent, assistantText, completionToClientStream, createClientId, createDirectClientTransport, createHttpClientTransport, customAgentEventsToClientStream, isJsonValue, maskedClientError, messageText, messagesToUIMessages, normalizeClientError, parseClientStreamEvent, parseClientStreamFrame, parseClientStreamRequest, parseUIMessage, parseUIMessages, uiMessagesToMessages };
2156
+
2587
2157
  //# sourceMappingURL=index.js.map