@anvia/client 1.5.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,2571 +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_start":
573
- requireEventKeys(event, ["messageId", "role", "metadata"]);
574
- requireStrings(event, ["messageId"], value);
575
- if (event.role !== "assistant") invalid("message_start.role", value);
576
- break;
577
- case "text_start":
578
- requireEventKeys(event, ["messageId", "partId"]);
579
- requireStrings(event, ["messageId", "partId"], value);
580
- break;
581
- case "text_delta":
582
- requireEventKeys(event, ["messageId", "partId", "delta"]);
583
- requireStrings(event, ["messageId", "partId", "delta"], value);
584
- break;
585
- case "reasoning_delta":
586
- requireEventKeys(event, ["messageId", "partId", "delta", "contentType", "signature"]);
587
- requireStrings(event, ["messageId", "partId", "delta"], value);
588
- requireOptionalStrings(event, ["signature"], value);
589
- if (event.contentType !== void 0 && !["text", "summary", "encrypted", "redacted"].includes(event.contentType)) {
590
- invalid("reasoning_delta.contentType", value);
591
- }
592
- break;
593
- case "text_end":
594
- requireEventKeys(event, ["messageId", "partId", "text", "signature"]);
595
- requireStrings(event, ["messageId", "partId"], value);
596
- requireOptionalStrings(event, ["text", "signature"], value);
597
- break;
598
- case "reasoning_start":
599
- requireEventKeys(event, ["messageId", "partId", "reasoningId"]);
600
- requireStrings(event, ["messageId", "partId"], value);
601
- requireOptionalStrings(event, ["reasoningId"], value);
602
- break;
603
- case "reasoning_end":
604
- requireEventKeys(event, ["messageId", "partId", "text", "content"]);
605
- requireStrings(event, ["messageId", "partId"], value);
606
- requireOptionalStrings(event, ["text"], value);
607
- if (event.content !== void 0 && (!Array.isArray(event.content) || !event.content.every(isReasoningContent))) {
608
- invalid("reasoning_end.content", value);
609
- }
610
- break;
611
- case "tool_call_start":
612
- requireEventKeys(event, ["messageId", "partId", "toolCallId", "callId", "toolName"]);
613
- requireStrings(event, ["messageId", "partId", "toolCallId"], value);
614
- requireOptionalStrings(event, ["callId", "toolName"], value);
615
- break;
616
- case "tool_call_delta":
617
- requireEventKeys(event, [
618
- "messageId",
619
- "partId",
620
- "toolCallId",
621
- "callId",
622
- "toolName",
623
- "delta",
624
- "mode",
625
- "signature"
626
- ]);
627
- requireStrings(event, ["messageId", "partId", "toolCallId", "delta"], value);
628
- requireOptionalStrings(event, ["callId", "toolName"], value);
629
- requireOptionalStrings(event, ["signature"], value);
630
- requireOneOf(event.mode, ["append", "replace"], "tool_call_delta.mode", value);
631
- break;
632
- case "tool_call_end":
633
- requireEventKeys(event, [
634
- "messageId",
635
- "partId",
636
- "toolCallId",
637
- "callId",
638
- "toolName",
639
- "input",
640
- "signature"
641
- ]);
642
- requireStrings(event, ["messageId", "partId", "toolCallId", "toolName"], value);
643
- requireOptionalStrings(event, ["callId", "signature"], value);
644
- if (!isJsonValue2(event.input)) invalid("tool_call_end.input", value);
645
- break;
646
- case "tool_result":
647
- requireEventKeys(event, [
648
- "messageId",
649
- "partId",
650
- "toolCallId",
651
- "callId",
652
- "internalCallId",
653
- "toolName",
654
- "input",
655
- "result"
656
- ]);
657
- requireStrings(event, ["messageId", "partId", "toolCallId", "toolName"], value);
658
- requireOptionalStrings(event, ["callId", "internalCallId"], value);
659
- if (!isJsonValue2(event.input)) invalid("tool_result.input", value);
660
- if (!isRecord(event.result)) invalid("tool_result.result", value);
661
- if (event.result.status === "success") {
662
- 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))) {
663
- invalid("tool_result.result", value);
664
- }
665
- } else if (event.result.status === "error") {
666
- if (!hasOnlyKeys(event.result, ["status", "error"]) || !isClientStreamError(event.result.error)) {
667
- invalid("tool_result.result", value);
668
- }
669
- } else {
670
- invalid("tool_result.result.status", value);
671
- }
672
- break;
673
- case "source":
674
- requireEventKeys(event, ["messageId", "partId", "source"]);
675
- requireStrings(event, ["messageId", "partId"], value);
676
- if (!isCompletionSource(event.source)) invalid("source.source", value);
677
- break;
678
- case "attachment":
679
- requireEventKeys(event, ["messageId", "partId", "attachment"]);
680
- requireStrings(event, ["messageId", "partId"], value);
681
- if (!isAttachment(event.attachment)) invalid("attachment.attachment", value);
682
- break;
683
- case "provider_tool_call":
684
- requireEventKeys(event, ["toolCall"]);
685
- if (!isProviderToolCall(event.toolCall)) invalid("provider_tool_call.toolCall", value);
686
- break;
687
- case "interaction":
688
- requireEventKeys(event, ["interaction"]);
689
- try {
690
- parseAgentInteractionRequest(event.interaction);
691
- } catch {
692
- invalid("interaction.interaction", value);
693
- }
694
- break;
695
- case "guardrail_decision":
696
- requireEventKeys(event, ["decision"]);
697
- if (!isGuardrailDecision(event.decision)) invalid("guardrail_decision.decision", value);
698
- break;
699
- case "data":
700
- requireEventKeys(event, ["name", "data", "transient"]);
701
- requireStrings(event, ["name"], value);
702
- if (!isJsonValue2(event.data)) invalid("data.data", value);
703
- if (event.transient !== void 0 && typeof event.transient !== "boolean") {
704
- invalid("data.transient", value);
705
- }
706
- return {
707
- ...event,
708
- data: parseDataEvent(event.name, event.data, options.dataSchemas, value)
709
- };
710
- case "message_end":
711
- requireEventKeys(event, [
712
- "messageId",
713
- "modelMessageId",
714
- "parts",
715
- "usage",
716
- "contextUsage",
717
- "metadata"
718
- ]);
719
- requireStrings(event, ["messageId"], value);
720
- requireOptionalStrings(event, ["modelMessageId"], value);
721
- if (event.parts !== void 0) {
722
- if (!Array.isArray(event.parts)) invalid("message_end.parts", value);
723
- const parts = event.parts.map(
724
- (part) => parseUIMessagePart(part, options.dataSchemas, value)
725
- );
726
- validateUsageAndContext(event, value);
727
- return parseEventMetadata(
728
- { ...event, parts },
729
- options.metadataSchema,
730
- value
731
- );
732
- }
733
- validateUsageAndContext(event, value);
734
- break;
735
- case "turn_end":
736
- requireEventKeys(event, ["usage", "contextUsage", "firstDeltaMs"]);
737
- if (!isPositiveEventId(event.turn)) invalid("turn_end.turn", value);
738
- if (event.firstDeltaMs !== void 0 && !isNonnegativeNumber(event.firstDeltaMs)) {
739
- invalid("turn_end.firstDeltaMs", value);
740
- }
741
- validateUsageAndContext(event, value);
742
- break;
743
- case "memory_compaction":
744
- requireEventKeys(event, [
745
- "originalMessageCount",
746
- "compactedMessageCount",
747
- "retainedMessageCount",
748
- "originalTokenCount",
749
- "compactedTokenCount",
750
- "retainedTokenCount",
751
- "resultTokenCount",
752
- "attempts",
753
- "usage"
754
- ]);
755
- validateMemoryCompactionInfo(event, value);
756
- break;
757
- case "run_end":
758
- requireEventKeys(event, [
759
- "status",
760
- "text",
761
- "output",
762
- "usage",
763
- "contextUsage",
764
- "trace",
765
- "memoryCompaction",
766
- "metadata"
767
- ]);
768
- requireOneOf(
769
- event.status,
770
- ["completed", "blocked", "suspended", "cancelled", "error"],
771
- "run_end.status",
772
- value
773
- );
774
- requireOptionalStrings(event, ["text"], value);
775
- validateUsageAndContext(event, value);
776
- if (event.trace !== void 0 && !isTrace(event.trace)) invalid("run_end.trace", value);
777
- if (event.memoryCompaction !== void 0) {
778
- if (!isRecord(event.memoryCompaction)) invalid("run_end.memoryCompaction", value);
779
- requireOnlyKeys(
780
- event.memoryCompaction,
781
- [
782
- "originalMessageCount",
783
- "compactedMessageCount",
784
- "retainedMessageCount",
785
- "originalTokenCount",
786
- "compactedTokenCount",
787
- "retainedTokenCount",
788
- "resultTokenCount",
789
- "attempts",
790
- "usage"
791
- ],
792
- "run_end.memoryCompaction"
793
- );
794
- validateMemoryCompactionInfo(event.memoryCompaction, value);
795
- }
796
- break;
797
- case "error":
798
- requireEventKeys(event, ["error", "usage"]);
799
- if (!isClientStreamError(event.error)) invalid("error.error", value);
800
- if (event.usage !== void 0 && !isUsage(event.usage)) invalid("error.usage", value);
801
- break;
802
- default:
803
- throw new ClientProtocolError(`Unknown client stream event type "${event.type}".`, value);
804
- }
805
- 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);
806
431
  }
807
432
  function parseClientStreamFrame(value, options = {}) {
808
- const frame = requireRecord(value, "Client stream frame");
809
- if (!isJsonValue2(frame)) {
810
- throw new ClientProtocolError("Client stream frames must be strict JSON values.", value);
811
- }
812
- if (typeof frame.type !== "string") {
813
- throw new ClientProtocolError("Client stream frames require type.", value);
814
- }
815
- if (frame.type === "stream_start") {
816
- requireOnlyKeys(
817
- frame,
818
- ["type", "protocol", "streamId", "eventId", "resumable"],
819
- "stream_start frame"
820
- );
821
- if (frame.protocol === "anvia.client.v1" || frame.protocol === "anvia.client.v2") {
822
- throw new ClientProtocolError(
823
- `Client stream protocol ${frame.protocol.slice(-2)} is not supported.`,
824
- value
825
- );
826
- }
827
- if (frame.protocol !== CLIENT_STREAM_PROTOCOL || typeof frame.streamId !== "string" || frame.eventId !== 0 || typeof frame.resumable !== "boolean") {
828
- throw new ClientProtocolError("Invalid client stream_start frame.", value);
829
- }
830
- return frame;
831
- }
832
- if (frame.type === "stream_event") {
833
- requireOnlyKeys(frame, ["type", "streamId", "eventId", "event"], "stream_event frame");
834
- if (typeof frame.streamId !== "string" || !isPositiveEventId(frame.eventId)) {
835
- throw new ClientProtocolError("Invalid client stream_event frame.", value);
836
- }
837
- const event = parseClientStreamEvent(frame.event, options);
838
- return { ...frame, event };
839
- }
840
- if (frame.type === "stream_end") {
841
- requireOnlyKeys(frame, ["type", "streamId", "eventId", "status"], "stream_end frame");
842
- if (typeof frame.streamId !== "string" || !isEventId(frame.eventId)) {
843
- throw new ClientProtocolError("Invalid client stream_end frame.", value);
844
- }
845
- requireOneOf(frame.status, ["completed", "error", "missing"], "stream_end.status", value);
846
- return frame;
847
- }
848
- 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);
849
478
  }
850
479
  function maskedClientError() {
851
- return { message: "An unexpected error occurred." };
480
+ return { message: "An unexpected error occurred." };
852
481
  }
853
482
  function normalizeClientError(value) {
854
- if (value instanceof Error) return value;
855
- if (isClientStreamError(value)) {
856
- const error = new Error(value.message);
857
- if (value.name !== void 0) error.name = value.name;
858
- return error;
859
- }
860
- 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.");
861
490
  }
862
491
  function parseDataEvent(name, data, schemas, value) {
863
- if (schemas === void 0) return data;
864
- const schema = schemas[name];
865
- if (schema === void 0) {
866
- throw new ClientProtocolError(`Invalid data event "${name}".`, value);
867
- }
868
- const parsed = schema.safeParse(data);
869
- if (parsed.success !== true || !isJsonValue2(parsed.data)) {
870
- throw new ClientProtocolError(`Invalid data event "${name}".`, value);
871
- }
872
- 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;
873
498
  }
874
499
  function parseUIMessagePart(value, schemas, root) {
875
- if (!isUIMessagePart(value)) {
876
- throw new ClientProtocolError("UI message contains an invalid part.", root);
877
- }
878
- if (value.type !== "data") {
879
- return value;
880
- }
881
- return {
882
- ...value,
883
- data: parseDataEvent(value.name, value.data, schemas, root)
884
- };
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
+ };
885
506
  }
886
507
  function parseMetadata(value, schema, root) {
887
- if (schema === void 0) {
888
- if (!isJsonObject(value)) {
889
- throw new ClientProtocolError("Client metadata must be a JSON object.", root);
890
- }
891
- return value;
892
- }
893
- const parsed = schema.safeParse(value);
894
- if (parsed.success !== true || !isJsonObject(parsed.data)) {
895
- throw new ClientProtocolError("Invalid client metadata.", root);
896
- }
897
- 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;
898
515
  }
899
516
  function parseEventMetadata(event, schema, root) {
900
- if (event.metadata === void 0) return event;
901
- 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
+ };
902
522
  }
903
523
  function isUIMessageGeneration(value) {
904
- if (!isRecord(value)) return false;
905
- if (!hasOnlyKeys(value, ["runId", "status", "usage", "contextUsage", "trace", "memoryCompaction"])) {
906
- return false;
907
- }
908
- return (value.runId === void 0 || typeof value.runId === "string") && (value.status === void 0 || ["completed", "blocked", "suspended", "cancelled", "error"].includes(
909
- value.status
910
- )) && (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));
911
540
  }
912
541
  function validateMemoryCompactionForGuard(value) {
913
- try {
914
- requireOnlyKeys(
915
- value,
916
- [
917
- "originalMessageCount",
918
- "compactedMessageCount",
919
- "retainedMessageCount",
920
- "originalTokenCount",
921
- "compactedTokenCount",
922
- "retainedTokenCount",
923
- "resultTokenCount",
924
- "attempts",
925
- "usage"
926
- ],
927
- "memory compaction"
928
- );
929
- validateMemoryCompactionInfo(value, value);
930
- return true;
931
- } catch {
932
- return false;
933
- }
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
+ }
934
559
  }
935
560
  function isJsonObject(value) {
936
- return isRecord(value) && isJsonValue2(value);
561
+ return isRecord$1(value) && isJsonValue$1(value);
937
562
  }
938
563
  function isClientStreamError(value) {
939
- 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));
940
571
  }
941
572
  function isScope(value) {
942
- if (!isRecord(value)) return false;
943
- const keys = [
944
- "agentId",
945
- "agentName",
946
- "parentRunId",
947
- "parentToolName",
948
- "parentToolCallId",
949
- "parentInternalToolCallId"
950
- ];
951
- 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");
952
583
  }
953
584
  function isAttachment(value) {
954
- if (!isRecord(value) || typeof value.id !== "string") return false;
955
- if (value.type !== "image" && value.type !== "document" && value.type !== "file") return false;
956
- return hasOnlyKeys(value, [
957
- "id",
958
- "type",
959
- "name",
960
- "mediaType",
961
- "url",
962
- "data",
963
- "text",
964
- "detail",
965
- "metadata"
966
- ]) && (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));
967
602
  }
968
603
  function isUIMessagePart(value) {
969
- if (!isRecord(value) || typeof value.id !== "string" || typeof value.type !== "string") {
970
- return false;
971
- }
972
- if (value.type === "text") {
973
- return hasOnlyKeys(value, ["id", "type", "text", "signature"]) && typeof value.text === "string" && (value.signature === void 0 || typeof value.signature === "string");
974
- }
975
- if (value.type === "reasoning") {
976
- 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));
977
- }
978
- if (value.type === "source") {
979
- return hasOnlyKeys(value, ["id", "type", "source"]) && isCompletionSource(value.source);
980
- }
981
- if (value.type === "data") {
982
- return hasOnlyKeys(value, ["id", "type", "name", "data"]) && typeof value.name === "string" && isJsonValue2(value.data);
983
- }
984
- if (value.type === "attachment") {
985
- return hasOnlyKeys(value, ["id", "type", "attachment"]) && isAttachment(value.attachment);
986
- }
987
- if (value.type === "error") {
988
- return hasOnlyKeys(value, ["id", "type", "error"]) && isClientStreamError(value.error);
989
- }
990
- if (value.type !== "tool" || !hasOnlyKeys(value, [
991
- "id",
992
- "type",
993
- "toolName",
994
- "toolCallId",
995
- "callId",
996
- "internalCallId",
997
- "turn",
998
- "state",
999
- "input",
1000
- "output",
1001
- "resultContent",
1002
- "signature",
1003
- "error"
1004
- ]) || 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") {
1005
- return false;
1006
- }
1007
- if (value.state === "input-streaming") {
1008
- return typeof value.input === "string" && value.output === void 0 && value.resultContent === void 0 && value.error === void 0;
1009
- }
1010
- if (value.state === "input-available") {
1011
- return isJsonValue2(value.input) && value.output === void 0 && value.resultContent === void 0 && value.error === void 0;
1012
- }
1013
- if (value.state === "output-available") {
1014
- return isJsonValue2(value.input) && isJsonValue2(value.output) && (value.resultContent === void 0 || Array.isArray(value.resultContent) && value.resultContent.every(isToolResultContent)) && value.error === void 0;
1015
- }
1016
- 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);
1017
658
  }
1018
659
  function isReasoningContent(value) {
1019
- if (!isRecord(value) || typeof value.type !== "string") return false;
1020
- if (value.type === "text") {
1021
- return hasOnlyKeys(value, ["type", "text", "signature"]) && typeof value.text === "string" && (value.signature === void 0 || typeof value.signature === "string");
1022
- }
1023
- if (value.type === "summary") {
1024
- return hasOnlyKeys(value, ["type", "text"]) && typeof value.text === "string";
1025
- }
1026
- if (value.type === "encrypted" || value.type === "redacted") {
1027
- return hasOnlyKeys(value, ["type", "data"]) && typeof value.data === "string";
1028
- }
1029
- 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;
1030
669
  }
1031
670
  function isToolResultContent(value) {
1032
- if (!isRecord(value)) return false;
1033
- if (value.type === "text") {
1034
- return hasOnlyKeys(value, ["type", "text", "signature"]) && typeof value.text === "string" && (value.signature === void 0 || typeof value.signature === "string");
1035
- }
1036
- 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");
1037
683
  }
1038
684
  function isFileData(value) {
1039
- if (!isRecord(value)) return false;
1040
- if (value.type === "url") {
1041
- return hasOnlyKeys(value, ["type", "url"]) && typeof value.url === "string";
1042
- }
1043
- if (value.type === "data") {
1044
- return hasOnlyKeys(value, ["type", "data"]) && typeof value.data === "string";
1045
- }
1046
- 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";
1047
689
  }
1048
690
  function isCompletionSource(value) {
1049
- 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));
1050
699
  }
1051
700
  function isProviderToolCall(value) {
1052
- 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));
1053
707
  }
1054
708
  function isGuardrailDecision(value) {
1055
- return isRecord(value) && hasOnlyKeys(value, [
1056
- "policyId",
1057
- "guardrailId",
1058
- "boundary",
1059
- "mode",
1060
- "action",
1061
- "applied",
1062
- "reason",
1063
- "message",
1064
- "metadata",
1065
- "latencyMs"
1066
- ]) && 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);
1067
726
  }
1068
727
  function isUsage(value) {
1069
- if (!isRecord(value) || !hasOnlyKeys(value, [
1070
- "inputTokens",
1071
- "outputTokens",
1072
- "totalTokens",
1073
- "cachedInputTokens",
1074
- "cacheCreationInputTokens",
1075
- "details"
1076
- ]) || ![
1077
- value.inputTokens,
1078
- value.outputTokens,
1079
- value.totalTokens,
1080
- value.cachedInputTokens,
1081
- value.cacheCreationInputTokens
1082
- ].every(isNonnegativeNumber)) {
1083
- return false;
1084
- }
1085
- 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);
1086
743
  }
1087
744
  function isContextUsage(value) {
1088
- if (!isRecord(value) || !isRecord(value.model) || !isRecord(value.model.context)) return false;
1089
- const context = value.model.context;
1090
- return hasOnlyKeys(value, [
1091
- "model",
1092
- "usedTokens",
1093
- "remainingTokens",
1094
- "usedPercent",
1095
- "remainingPercent"
1096
- ]) && 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);
1097
758
  }
1098
759
  function validateUsageAndContext(event, original) {
1099
- if (event.usage !== void 0 && !isUsage(event.usage)) {
1100
- invalid(`${String(event.type)}.usage`, original);
1101
- }
1102
- if (event.contextUsage !== void 0 && !isContextUsage(event.contextUsage)) {
1103
- invalid(`${String(event.type)}.contextUsage`, original);
1104
- }
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);
1105
762
  }
1106
763
  function validateMemoryCompactionInfo(value, original) {
1107
- for (const field of [
1108
- "originalMessageCount",
1109
- "compactedMessageCount",
1110
- "retainedMessageCount",
1111
- "originalTokenCount",
1112
- "compactedTokenCount",
1113
- "retainedTokenCount",
1114
- "resultTokenCount"
1115
- ]) {
1116
- if (!isEventId(value[field])) invalid(`memory_compaction.${field}`, original);
1117
- }
1118
- if (!isPositiveEventId(value.attempts)) invalid("memory_compaction.attempts", original);
1119
- 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);
1120
775
  }
1121
776
  function isTrace(value) {
1122
- 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");
1123
782
  }
1124
783
  function requireRecord(value, label) {
1125
- if (!isRecord(value)) throw new ClientProtocolError(`${label} must be an object.`, value);
1126
- return value;
784
+ if (!isRecord$1(value)) throw new ClientProtocolError(`${label} must be an object.`, value);
785
+ return value;
1127
786
  }
1128
787
  function requireOnlyKeys(value, keys, label) {
1129
- for (const key of Object.keys(value)) {
1130
- if (!keys.includes(key)) throw new ClientProtocolError(`${label} has unknown field "${key}".`);
1131
- }
788
+ for (const key of Object.keys(value)) if (!keys.includes(key)) throw new ClientProtocolError(`${label} has unknown field "${key}".`);
1132
789
  }
1133
790
  function requireEventKeys(value, keys) {
1134
- requireOnlyKeys(
1135
- value,
1136
- ["type", "runId", "turn", "scope", ...keys],
1137
- `${String(value.type)} event`
1138
- );
791
+ requireOnlyKeys(value, [
792
+ "type",
793
+ "runId",
794
+ "turn",
795
+ "scope",
796
+ ...keys
797
+ ], `${String(value.type)} event`);
1139
798
  }
1140
799
  function requireStrings(value, keys, original) {
1141
- for (const key of keys) {
1142
- if (typeof value[key] !== "string") invalid(`${String(value.type)}.${key}`, original);
1143
- }
800
+ for (const key of keys) if (typeof value[key] !== "string") invalid(`${String(value.type)}.${key}`, original);
1144
801
  }
1145
802
  function requireOptionalStrings(value, keys, original) {
1146
- for (const key of keys) {
1147
- if (value[key] !== void 0 && typeof value[key] !== "string") {
1148
- invalid(`${String(value.type)}.${key}`, original);
1149
- }
1150
- }
803
+ for (const key of keys) if (value[key] !== void 0 && typeof value[key] !== "string") invalid(`${String(value.type)}.${key}`, original);
1151
804
  }
1152
805
  function requireOneOf(value, allowed, label, original) {
1153
- if (typeof value !== "string" || !allowed.includes(value)) invalid(label, original);
806
+ if (typeof value !== "string" || !allowed.includes(value)) invalid(label, original);
1154
807
  }
1155
808
  function invalid(label, value) {
1156
- throw new ClientProtocolError(`Invalid ${label}.`, value);
809
+ throw new ClientProtocolError(`Invalid ${label}.`, value);
1157
810
  }
1158
811
  function isEventId(value) {
1159
- return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
812
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
1160
813
  }
1161
814
  function isPositiveEventId(value) {
1162
- return isEventId(value) && value > 0;
815
+ return isEventId(value) && value > 0;
1163
816
  }
1164
817
  function isNonnegativeNumber(value) {
1165
- return typeof value === "number" && Number.isFinite(value) && value >= 0;
818
+ return typeof value === "number" && Number.isFinite(value) && value >= 0;
1166
819
  }
1167
820
  function hasOnlyKeys(value, keys) {
1168
- return Object.keys(value).every((key) => keys.includes(key));
821
+ return Object.keys(value).every((key) => keys.includes(key));
1169
822
  }
1170
- function isRecord(value) {
1171
- return typeof value === "object" && value !== null && !Array.isArray(value);
823
+ function isRecord$1(value) {
824
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1172
825
  }
1173
-
1174
826
  // src/adapters.ts
1175
827
  function completionToClientStream(options) {
1176
- const { events } = options;
1177
- const runId = options.runId ?? createClientId("run");
1178
- return propagateCancellation(events, (source) => ({
1179
- async *[Symbol.asyncIterator]() {
1180
- const state = createMessageState({ runId });
1181
- const runStart = {
1182
- type: "run_start",
1183
- source: "completion"
1184
- };
1185
- if (options.metadata !== void 0) runStart.metadata = options.metadata;
1186
- yield clientEvent(state, runStart);
1187
- if (options.model !== void 0) {
1188
- yield clientEvent(state, { type: "generation_start", model: options.model });
1189
- }
1190
- yield* startMessage(state);
1191
- let terminal = false;
1192
- try {
1193
- for await (const event of source) {
1194
- if (terminal) break;
1195
- switch (event.type) {
1196
- case "text_delta":
1197
- yield* appendText(state, event.delta);
1198
- break;
1199
- case "reasoning_delta":
1200
- yield* appendReasoning(state, event);
1201
- break;
1202
- case "tool_call_delta":
1203
- yield* appendToolCall(state, event);
1204
- break;
1205
- case "tool_call":
1206
- yield* finishToolCall(state, event.toolCall);
1207
- break;
1208
- case "source":
1209
- yield* emitSource(state, event.source);
1210
- break;
1211
- case "provider_tool_call":
1212
- yield* emitProviderToolCall(state, event.toolCall);
1213
- break;
1214
- case "message_id":
1215
- state.modelMessageId = event.id;
1216
- break;
1217
- case "final": {
1218
- const result = event.result;
1219
- if (result.messageId !== void 0) state.modelMessageId = result.messageId;
1220
- const finalMetadata = {
1221
- usage: result.usage
1222
- };
1223
- if (result.contextUsage !== void 0) {
1224
- finalMetadata.contextUsage = result.contextUsage;
1225
- }
1226
- if (result.sources !== void 0) finalMetadata.sources = result.sources;
1227
- if (result.providerToolCalls !== void 0) {
1228
- finalMetadata.providerToolCalls = result.providerToolCalls;
1229
- }
1230
- yield* finishMessage(state, result.content, finalMetadata);
1231
- const output = clientOutput(result.output, options.mapOutput);
1232
- const runEnd = {
1233
- type: "run_end",
1234
- status: "completed",
1235
- text: result.text,
1236
- usage: result.usage
1237
- };
1238
- if (output !== void 0) runEnd.output = output;
1239
- if (result.contextUsage !== void 0) runEnd.contextUsage = result.contextUsage;
1240
- yield clientEvent(state, runEnd);
1241
- terminal = true;
1242
- break;
1243
- }
1244
- case "error":
1245
- yield* finishErroredRun(state, event.error, event.usage, options.mapError);
1246
- terminal = true;
1247
- break;
1248
- }
1249
- }
1250
- if (!terminal) {
1251
- yield* finishErroredRun(
1252
- state,
1253
- new Error("Completion stream ended without a terminal event."),
1254
- void 0,
1255
- options.mapError
1256
- );
1257
- }
1258
- } catch (error) {
1259
- if (!terminal) yield* finishErroredRun(state, error, void 0, options.mapError);
1260
- }
1261
- }
1262
- }));
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
+ } }));
1263
900
  }
1264
901
  function agentToClientStream(options) {
1265
- const { events } = options;
1266
- const runId = options.runId ?? createClientId("run");
1267
- return propagateCancellation(events, (source) => ({
1268
- async *[Symbol.asyncIterator]() {
1269
- const runtime = {
1270
- runId,
1271
- options,
1272
- messages: /* @__PURE__ */ new Map(),
1273
- startedScopes: /* @__PURE__ */ new Set(["root"])
1274
- };
1275
- const runStart = {
1276
- type: "run_start",
1277
- source: "agent"
1278
- };
1279
- if (options.metadata !== void 0) runStart.metadata = options.metadata;
1280
- yield rootEvent(runId, runStart);
1281
- let terminal = false;
1282
- try {
1283
- for await (const event of source) {
1284
- if (terminal) break;
1285
- yield* translateAgentEvent(runtime, event, void 0);
1286
- terminal = isRootTerminalAgentEvent(event);
1287
- }
1288
- if (!terminal) {
1289
- const error = mapClientError(
1290
- new Error("Agent stream ended without a terminal event."),
1291
- options.mapError
1292
- );
1293
- yield rootEvent(runId, { type: "error", error });
1294
- yield rootEvent(runId, { type: "run_end", status: "error" });
1295
- }
1296
- } catch (error) {
1297
- if (!terminal) {
1298
- yield rootEvent(runId, {
1299
- type: "error",
1300
- error: mapClientError(error, options.mapError)
1301
- });
1302
- yield rootEvent(runId, { type: "run_end", status: "error" });
1303
- }
1304
- }
1305
- }
1306
- }));
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
+ } }));
1307
948
  }
1308
949
  function customAgentEventsToClientStream(options) {
1309
- return agentToClientStream(
1310
- options
1311
- );
950
+ return agentToClientStream(options);
1312
951
  }
1313
952
  async function* translateAgentEvent(runtime, event, scope) {
1314
- if (event.type === "agent_tool_event") {
1315
- const childScope = {
1316
- agentId: event.agentId,
1317
- parentRunId: runtime.runId,
1318
- parentToolName: event.toolName,
1319
- parentToolCallId: event.toolCallId ?? event.internalCallId,
1320
- parentInternalToolCallId: event.internalCallId
1321
- };
1322
- if (event.agentName !== void 0) childScope.agentName = event.agentName;
1323
- const key = scopeKey(childScope);
1324
- if (!runtime.startedScopes.has(key)) {
1325
- runtime.startedScopes.add(key);
1326
- yield rootEvent(runtime.runId, { type: "run_start", source: "agent" }, childScope);
1327
- }
1328
- yield* translateAgentEvent(runtime, event.event, childScope);
1329
- return;
1330
- }
1331
- const turn = "turn" in event && typeof event.turn === "number" ? event.turn : void 0;
1332
- switch (event.type) {
1333
- case "memory_compaction":
1334
- yield scopedEvent(runtime.runId, turn, scope, {
1335
- type: "memory_compaction",
1336
- originalMessageCount: event.originalMessageCount,
1337
- compactedMessageCount: event.compactedMessageCount,
1338
- retainedMessageCount: event.retainedMessageCount,
1339
- originalTokenCount: event.originalTokenCount,
1340
- compactedTokenCount: event.compactedTokenCount,
1341
- retainedTokenCount: event.retainedTokenCount,
1342
- resultTokenCount: event.resultTokenCount,
1343
- attempts: event.attempts,
1344
- usage: event.usage
1345
- });
1346
- return;
1347
- case "turn_start":
1348
- yield scopedEvent(runtime.runId, turn, scope, { type: "turn_start" });
1349
- return;
1350
- case "generation_start": {
1351
- const state = getAgentMessage(runtime, event.turn, scope);
1352
- yield scopedEvent(runtime.runId, event.turn, scope, {
1353
- type: "generation_start",
1354
- model: {
1355
- provider: event.modelInfo.provider,
1356
- modelId: event.modelInfo.modelId
1357
- }
1358
- });
1359
- yield* startMessage(state);
1360
- return;
1361
- }
1362
- case "text_delta": {
1363
- const state = getAgentMessage(runtime, event.turn, scope);
1364
- yield* startMessage(state);
1365
- yield* appendText(state, event.delta);
1366
- return;
1367
- }
1368
- case "reasoning_delta": {
1369
- const state = getAgentMessage(runtime, event.turn, scope);
1370
- yield* startMessage(state);
1371
- yield* appendReasoning(state, event);
1372
- return;
1373
- }
1374
- case "tool_call_delta": {
1375
- const state = getAgentMessage(runtime, event.turn, scope);
1376
- yield* startMessage(state);
1377
- yield* appendToolCall(state, event);
1378
- return;
1379
- }
1380
- case "tool_call": {
1381
- const state = getAgentMessage(runtime, event.turn, scope);
1382
- yield* startMessage(state);
1383
- yield* finishToolCall(state, event.toolCall);
1384
- return;
1385
- }
1386
- case "source": {
1387
- const state = getAgentMessage(runtime, event.turn, scope);
1388
- yield* startMessage(state);
1389
- yield* emitSource(state, event.source);
1390
- return;
1391
- }
1392
- case "provider_tool_call": {
1393
- const state = getAgentMessage(runtime, event.turn, scope);
1394
- yield* emitProviderToolCall(state, event.toolCall);
1395
- return;
1396
- }
1397
- case "tool_result": {
1398
- const state = getAgentMessage(runtime, event.turn, scope);
1399
- yield* startMessage(state);
1400
- const tool = getToolResultState(
1401
- state,
1402
- event.toolName,
1403
- event.toolCallId,
1404
- event.callId,
1405
- event.internalCallId
1406
- );
1407
- tool.result = clientToolResult(event.output, event.result);
1408
- const resultEvent = {
1409
- type: "tool_result",
1410
- messageId: state.messageId,
1411
- partId: tool.partId,
1412
- toolCallId: tool.toolCallId,
1413
- internalCallId: event.internalCallId,
1414
- toolName: event.toolName,
1415
- input: parseJsonOrString(event.args),
1416
- result: tool.result
1417
- };
1418
- if (tool.callId !== void 0) resultEvent.callId = tool.callId;
1419
- yield clientEvent(state, resultEvent);
1420
- return;
1421
- }
1422
- case "turn_end": {
1423
- const state = getAgentMessage(runtime, event.turn, scope);
1424
- yield* startMessage(state);
1425
- if (event.response.messageId !== void 0) state.modelMessageId = event.response.messageId;
1426
- const finalMetadata = {
1427
- usage: event.response.usage
1428
- };
1429
- if (event.response.contextUsage !== void 0) {
1430
- finalMetadata.contextUsage = event.response.contextUsage;
1431
- }
1432
- if (event.response.sources !== void 0) finalMetadata.sources = event.response.sources;
1433
- if (event.response.providerToolCalls !== void 0) {
1434
- finalMetadata.providerToolCalls = event.response.providerToolCalls;
1435
- }
1436
- yield* finishMessage(state, event.response.choice, finalMetadata);
1437
- const turnEnd = {
1438
- type: "turn_end",
1439
- usage: event.response.usage
1440
- };
1441
- if (event.response.contextUsage !== void 0) {
1442
- turnEnd.contextUsage = event.response.contextUsage;
1443
- }
1444
- if (event.firstDeltaMs !== void 0) turnEnd.firstDeltaMs = event.firstDeltaMs;
1445
- yield scopedEvent(runtime.runId, event.turn, scope, turnEnd);
1446
- return;
1447
- }
1448
- case "guardrail_decision":
1449
- yield scopedEvent(runtime.runId, event.turn, scope, {
1450
- type: "guardrail_decision",
1451
- decision: event.decision
1452
- });
1453
- return;
1454
- case "response":
1455
- case "interaction":
1456
- case "blocked": {
1457
- const result = event;
1458
- if (result.type === "interaction" && scope === void 0) {
1459
- yield scopedEvent(runtime.runId, turn, scope, {
1460
- type: "interaction",
1461
- interaction: result.interaction
1462
- });
1463
- }
1464
- const output = result.type === "response" ? clientOutput(result.output, runtime.options.mapOutput) : void 0;
1465
- const runEnd = {
1466
- type: "run_end",
1467
- status: agentOutcomeStatus(result.type),
1468
- text: result.text,
1469
- usage: result.usage
1470
- };
1471
- if (output !== void 0) runEnd.output = output;
1472
- if (result.contextUsage !== void 0) runEnd.contextUsage = result.contextUsage;
1473
- if (result.trace !== void 0) runEnd.trace = clientTrace(result.trace);
1474
- if (result.memoryCompaction !== void 0) {
1475
- runEnd.memoryCompaction = result.memoryCompaction;
1476
- }
1477
- if (runtime.options.metadata !== void 0) runEnd.metadata = runtime.options.metadata;
1478
- yield scopedEvent(runtime.runId, turn, scope, runEnd);
1479
- return;
1480
- }
1481
- case "error": {
1482
- const error = mapClientError(event.error, runtime.options.mapError);
1483
- yield scopedEvent(runtime.runId, turn, scope, { type: "error", error, usage: event.usage });
1484
- yield scopedEvent(runtime.runId, turn, scope, {
1485
- type: "run_end",
1486
- status: "error",
1487
- usage: event.usage
1488
- });
1489
- return;
1490
- }
1491
- default: {
1492
- const context = {
1493
- runId: runtime.runId
1494
- };
1495
- if (turn !== void 0) context.turn = turn;
1496
- if (scope !== void 0) context.scope = scope;
1497
- const mapped = runtime.options.mapCustomEvent?.(event, context);
1498
- if (mapped === void 0) return;
1499
- if (Array.isArray(mapped)) {
1500
- yield* mapped;
1501
- } else {
1502
- yield mapped;
1503
- }
1504
- }
1505
- }
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
+ }
1506
1134
  }
1507
1135
  function createMessageState(input) {
1508
- const state = {
1509
- runId: input.runId,
1510
- messageId: createClientId("msg"),
1511
- started: false,
1512
- ended: false,
1513
- textPartId: createClientId("text"),
1514
- text: "",
1515
- textStarted: false,
1516
- textEnded: false,
1517
- reasoning: /* @__PURE__ */ new Map(),
1518
- tools: /* @__PURE__ */ new Map(),
1519
- sourceFingerprints: /* @__PURE__ */ new Set(),
1520
- providerToolCallFingerprints: /* @__PURE__ */ new Set()
1521
- };
1522
- if (input.turn !== void 0) state.turn = input.turn;
1523
- if (input.scope !== void 0) state.scope = input.scope;
1524
- return state;
1525
- }
1526
- function getAgentMessage(runtime, turn, scope) {
1527
- const key = `${scopeKey(scope)}:${turn}`;
1528
- const current = runtime.messages.get(key);
1529
- if (current !== void 0) return current;
1530
- const input = {
1531
- runId: runtime.runId,
1532
- turn
1533
- };
1534
- if (scope !== void 0) input.scope = scope;
1535
- const created = createMessageState(input);
1536
- runtime.messages.set(key, created);
1537
- return created;
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;
1153
+ }
1154
+ function getAgentMessage(runtime, turn, scope, reset = false) {
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;
1538
1170
  }
1539
1171
  async function* startMessage(state) {
1540
- if (state.started) return;
1541
- state.started = true;
1542
- yield clientEvent(state, {
1543
- type: "message_start",
1544
- messageId: state.messageId,
1545
- role: "assistant"
1546
- });
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
+ });
1547
1179
  }
1548
1180
  async function* appendText(state, delta) {
1549
- if (!state.textStarted) {
1550
- state.textStarted = true;
1551
- yield clientEvent(state, {
1552
- type: "text_start",
1553
- messageId: state.messageId,
1554
- partId: state.textPartId
1555
- });
1556
- }
1557
- state.text += delta;
1558
- yield clientEvent(state, {
1559
- type: "text_delta",
1560
- messageId: state.messageId,
1561
- partId: state.textPartId,
1562
- delta
1563
- });
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
+ });
1564
1196
  }
1565
1197
  async function* emitSource(state, source) {
1566
- const fingerprint = valueFingerprint(source);
1567
- if (state.sourceFingerprints.has(fingerprint)) return;
1568
- state.sourceFingerprints.add(fingerprint);
1569
- yield clientEvent(state, {
1570
- type: "source",
1571
- messageId: state.messageId,
1572
- partId: createClientId("source"),
1573
- source
1574
- });
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
+ });
1575
1207
  }
1576
1208
  async function* emitProviderToolCall(state, toolCall) {
1577
- const fingerprint = valueFingerprint(toolCall);
1578
- if (state.providerToolCallFingerprints.has(fingerprint)) return;
1579
- state.providerToolCallFingerprints.add(fingerprint);
1580
- 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
+ });
1581
1216
  }
1582
1217
  async function* appendReasoning(state, event) {
1583
- const key = event.id ?? "default";
1584
- let reasoning = state.reasoning.get(key);
1585
- if (reasoning === void 0) {
1586
- reasoning = {
1587
- partId: createClientId("reasoning"),
1588
- text: "",
1589
- ended: false
1590
- };
1591
- if (event.id !== void 0) reasoning.reasoningId = event.id;
1592
- state.reasoning.set(key, reasoning);
1593
- const reasoningStart = {
1594
- type: "reasoning_start",
1595
- messageId: state.messageId,
1596
- partId: reasoning.partId
1597
- };
1598
- if (event.id !== void 0) reasoningStart.reasoningId = event.id;
1599
- yield clientEvent(state, reasoningStart);
1600
- }
1601
- reasoning.text += event.delta;
1602
- const reasoningDelta = {
1603
- type: "reasoning_delta",
1604
- messageId: state.messageId,
1605
- partId: reasoning.partId,
1606
- delta: event.delta
1607
- };
1608
- if (event.contentType !== void 0) reasoningDelta.contentType = event.contentType;
1609
- if (event.signature !== void 0) reasoningDelta.signature = event.signature;
1610
- 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);
1611
1246
  }
1612
1247
  async function* appendToolCall(state, event) {
1613
- const tool = getToolState(state, event.id, event.name);
1614
- if (!tool.started) {
1615
- tool.started = true;
1616
- const toolCallStart = {
1617
- type: "tool_call_start",
1618
- messageId: state.messageId,
1619
- partId: tool.partId,
1620
- toolCallId: event.id
1621
- };
1622
- if (event.callId !== void 0) toolCallStart.callId = event.callId;
1623
- if (event.name !== void 0) toolCallStart.toolName = event.name;
1624
- yield clientEvent(state, toolCallStart);
1625
- }
1626
- if (event.callId !== void 0) tool.callId = event.callId;
1627
- if (event.name !== void 0) tool.toolName = event.name;
1628
- if (event.signature !== void 0) tool.signature = event.signature;
1629
- if (event.argumentsDelta === void 0) return;
1630
- const mode = event.argumentsMode ?? "append";
1631
- const prior = typeof tool.input === "string" ? tool.input : "";
1632
- tool.input = mode === "replace" ? event.argumentsDelta : `${prior}${event.argumentsDelta}`;
1633
- const toolCallDelta = {
1634
- type: "tool_call_delta",
1635
- messageId: state.messageId,
1636
- partId: tool.partId,
1637
- toolCallId: event.id,
1638
- delta: event.argumentsDelta,
1639
- mode
1640
- };
1641
- if (event.callId !== void 0) toolCallDelta.callId = event.callId;
1642
- if (event.name !== void 0) toolCallDelta.toolName = event.name;
1643
- if (event.signature !== void 0) toolCallDelta.signature = event.signature;
1644
- 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);
1645
1280
  }
1646
1281
  async function* finishToolCall(state, toolCall) {
1647
- const tool = getToolState(state, toolCall.toolCallId, toolCall.toolName);
1648
- const wasEnded = tool.ended;
1649
- if (!tool.started) {
1650
- tool.started = true;
1651
- const toolCallStart = {
1652
- type: "tool_call_start",
1653
- messageId: state.messageId,
1654
- partId: tool.partId,
1655
- toolCallId: toolCall.toolCallId,
1656
- toolName: toolCall.toolName
1657
- };
1658
- if (toolCall.callId !== void 0) toolCallStart.callId = toolCall.callId;
1659
- yield clientEvent(state, toolCallStart);
1660
- }
1661
- if (toolCall.callId === void 0) delete tool.callId;
1662
- else tool.callId = toolCall.callId;
1663
- tool.toolName = toolCall.toolName;
1664
- tool.input = toolCall.input;
1665
- if (toolCall.signature === void 0) delete tool.signature;
1666
- else tool.signature = toolCall.signature;
1667
- if (wasEnded) return;
1668
- tool.ended = true;
1669
- const toolCallEnd = {
1670
- type: "tool_call_end",
1671
- messageId: state.messageId,
1672
- partId: tool.partId,
1673
- toolCallId: toolCall.toolCallId,
1674
- toolName: toolCall.toolName,
1675
- input: toolCall.input
1676
- };
1677
- if (toolCall.callId !== void 0) toolCallEnd.callId = toolCall.callId;
1678
- if (toolCall.signature !== void 0) toolCallEnd.signature = toolCall.signature;
1679
- 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);
1680
1315
  }
1681
1316
  async function* finishMessage(state, content, metadata) {
1682
- if (state.ended) return;
1683
- const textContent2 = content.filter(
1684
- (part) => part.type === "text"
1685
- );
1686
- const text = textContent2.map((part) => part.text).join("");
1687
- if (state.textStarted || text.length > 0) {
1688
- if (!state.textStarted) {
1689
- state.textStarted = true;
1690
- yield clientEvent(state, {
1691
- type: "text_start",
1692
- messageId: state.messageId,
1693
- partId: state.textPartId
1694
- });
1695
- }
1696
- state.text = text;
1697
- state.textEnded = true;
1698
- const textEnd = {
1699
- type: "text_end",
1700
- messageId: state.messageId,
1701
- partId: state.textPartId,
1702
- text
1703
- };
1704
- if (textContent2.length === 1 && textContent2[0]?.signature !== void 0) {
1705
- textEnd.signature = textContent2[0].signature;
1706
- }
1707
- yield clientEvent(state, textEnd);
1708
- }
1709
- const finalReasoning = content.filter(
1710
- (part) => part.type === "reasoning"
1711
- );
1712
- const anonymousReasoning = [...state.reasoning.values()].filter(
1713
- (reasoning) => reasoning.reasoningId === void 0
1714
- );
1715
- let anonymousIndex = 0;
1716
- for (const [index, reasoning] of finalReasoning.entries()) {
1717
- const existing = reasoning.id === void 0 ? anonymousReasoning[anonymousIndex++] : state.reasoning.get(reasoning.id);
1718
- const current = existing ?? createReasoningState(reasoning.id);
1719
- if (existing === void 0) {
1720
- state.reasoning.set(reasoning.id ?? `final:${index}`, current);
1721
- const reasoningStart = {
1722
- type: "reasoning_start",
1723
- messageId: state.messageId,
1724
- partId: current.partId
1725
- };
1726
- if (reasoning.id !== void 0) reasoningStart.reasoningId = reasoning.id;
1727
- yield clientEvent(state, reasoningStart);
1728
- }
1729
- if (!current.ended) {
1730
- current.ended = true;
1731
- current.text = reasoning.text;
1732
- const reasoningEnd = {
1733
- type: "reasoning_end",
1734
- messageId: state.messageId,
1735
- partId: current.partId,
1736
- text: reasoning.text
1737
- };
1738
- if (reasoning.details !== void 0) reasoningEnd.content = reasoning.details;
1739
- yield clientEvent(state, reasoningEnd);
1740
- }
1741
- }
1742
- for (const reasoning of state.reasoning.values()) {
1743
- if (reasoning.ended) continue;
1744
- reasoning.ended = true;
1745
- yield clientEvent(state, {
1746
- type: "reasoning_end",
1747
- messageId: state.messageId,
1748
- partId: reasoning.partId,
1749
- text: reasoning.text
1750
- });
1751
- }
1752
- for (const part of content) {
1753
- if (part.type === "tool-call") yield* finishToolCall(state, part);
1754
- if (part.type === "image" || part.type === "file") {
1755
- const attachment = contentAttachment(part);
1756
- yield clientEvent(state, {
1757
- type: "attachment",
1758
- messageId: state.messageId,
1759
- partId: createClientId("attachment_part"),
1760
- attachment
1761
- });
1762
- }
1763
- }
1764
- for (const source of metadata.sources ?? []) yield* emitSource(state, source);
1765
- for (const toolCall of metadata.providerToolCalls ?? []) {
1766
- yield* emitProviderToolCall(state, toolCall);
1767
- }
1768
- state.ended = true;
1769
- const messageEnd = {
1770
- type: "message_end",
1771
- messageId: state.messageId,
1772
- parts: contentToUIMessageParts(content, state),
1773
- usage: metadata.usage
1774
- };
1775
- if (state.modelMessageId !== void 0) messageEnd.modelMessageId = state.modelMessageId;
1776
- if (metadata.contextUsage !== void 0) messageEnd.contextUsage = metadata.contextUsage;
1777
- 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);
1778
1403
  }
1779
1404
  async function* finishErroredRun(state, error, usage, mapper) {
1780
- const mapped = mapClientError(error, mapper);
1781
- if (state.textStarted && !state.textEnded) {
1782
- state.textEnded = true;
1783
- yield clientEvent(state, {
1784
- type: "text_end",
1785
- messageId: state.messageId,
1786
- partId: state.textPartId,
1787
- text: state.text
1788
- });
1789
- }
1790
- const errorEvent = {
1791
- type: "error",
1792
- error: mapped
1793
- };
1794
- if (usage !== void 0) errorEvent.usage = usage;
1795
- yield clientEvent(state, errorEvent);
1796
- if (!state.ended) {
1797
- state.ended = true;
1798
- const messageEnd = {
1799
- type: "message_end",
1800
- messageId: state.messageId
1801
- };
1802
- if (state.modelMessageId !== void 0) messageEnd.modelMessageId = state.modelMessageId;
1803
- if (usage !== void 0) messageEnd.usage = usage;
1804
- yield clientEvent(state, messageEnd);
1805
- }
1806
- const runEnd = {
1807
- type: "run_end",
1808
- status: "error"
1809
- };
1810
- if (usage !== void 0) runEnd.usage = usage;
1811
- 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);
1812
1437
  }
1813
1438
  function contentToUIMessageParts(content, state) {
1814
- let textIndex = 0;
1815
- let anonymousReasoningIndex = 0;
1816
- const anonymousReasoning = [...state.reasoning.values()].filter(
1817
- (reasoning) => reasoning.reasoningId === void 0
1818
- );
1819
- return content.map((contentPart) => {
1820
- if (contentPart.type === "text") {
1821
- const part = {
1822
- id: textIndex === 0 ? state.textPartId : createClientId("text"),
1823
- type: "text",
1824
- text: contentPart.text
1825
- };
1826
- textIndex += 1;
1827
- if (contentPart.signature !== void 0) part.signature = contentPart.signature;
1828
- return part;
1829
- }
1830
- if (contentPart.type === "reasoning") {
1831
- const current = contentPart.id === void 0 ? anonymousReasoning[anonymousReasoningIndex++] : state.reasoning.get(contentPart.id);
1832
- const part = {
1833
- id: current?.partId ?? createClientId("reasoning"),
1834
- type: "reasoning",
1835
- text: contentPart.text
1836
- };
1837
- if (contentPart.id !== void 0) part.reasoningId = contentPart.id;
1838
- if (contentPart.details !== void 0) part.content = contentPart.details;
1839
- return part;
1840
- }
1841
- if (contentPart.type === "tool-call") {
1842
- const tool = getToolState(state, contentPart.toolCallId, contentPart.toolName);
1843
- const partBase = {
1844
- id: tool.partId,
1845
- type: "tool",
1846
- toolName: contentPart.toolName,
1847
- toolCallId: contentPart.toolCallId
1848
- };
1849
- if (contentPart.callId !== void 0) Object.assign(partBase, { callId: contentPart.callId });
1850
- if (tool.internalCallId !== void 0) {
1851
- Object.assign(partBase, { internalCallId: tool.internalCallId });
1852
- }
1853
- if (state.turn !== void 0) Object.assign(partBase, { turn: state.turn });
1854
- if (contentPart.signature !== void 0) {
1855
- Object.assign(partBase, { signature: contentPart.signature });
1856
- }
1857
- if (tool.result?.status === "success") {
1858
- const part = {
1859
- ...partBase,
1860
- state: "output-available",
1861
- input: contentPart.input,
1862
- output: tool.result.output
1863
- };
1864
- if (tool.result.content !== void 0) part.resultContent = tool.result.content;
1865
- return part;
1866
- }
1867
- if (tool.result?.status === "error") {
1868
- return {
1869
- ...partBase,
1870
- state: "error",
1871
- input: contentPart.input,
1872
- error: tool.result.error
1873
- };
1874
- }
1875
- return {
1876
- ...partBase,
1877
- state: "input-available",
1878
- input: contentPart.input
1879
- };
1880
- }
1881
- const attachment = contentAttachment(contentPart);
1882
- return {
1883
- id: createClientId("attachment_part"),
1884
- type: "attachment",
1885
- attachment
1886
- };
1887
- });
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
+ });
1888
1504
  }
1889
1505
  function getToolState(state, id, name) {
1890
- let tool = state.tools.get(id);
1891
- if (tool === void 0) {
1892
- tool = {
1893
- partId: createClientId("tool"),
1894
- toolCallId: id,
1895
- input: "",
1896
- started: false,
1897
- ended: false
1898
- };
1899
- if (name !== void 0) tool.toolName = name;
1900
- state.tools.set(id, tool);
1901
- } else if (name !== void 0) {
1902
- tool.toolName = name;
1903
- }
1904
- 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;
1905
1519
  }
1906
1520
  function getToolResultState(state, toolName, toolCallId, callId, internalCallId) {
1907
- const matchedByToolCallId = state.tools.get(toolCallId);
1908
- const matchedByCallId = callId === void 0 ? void 0 : [...state.tools.values()].find((tool2) => tool2.callId === callId);
1909
- const tool = matchedByToolCallId ?? matchedByCallId ?? getToolState(state, toolCallId, toolName);
1910
- tool.toolName = toolName;
1911
- if (callId !== void 0) tool.callId = callId;
1912
- tool.internalCallId = internalCallId;
1913
- 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;
1914
1528
  }
1915
1529
  function createReasoningState(id) {
1916
- const state = {
1917
- partId: createClientId("reasoning"),
1918
- text: "",
1919
- ended: false
1920
- };
1921
- if (id !== void 0) state.reasoningId = id;
1922
- 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;
1923
1537
  }
1924
1538
  function contentAttachment(content) {
1925
- const attachment = {
1926
- id: createClientId("attachment"),
1927
- type: content.type === "image" ? "image" : "file"
1928
- };
1929
- if (content.type === "image") {
1930
- if (content.detail !== void 0) attachment.detail = content.detail;
1931
- if (content.mediaType !== void 0) attachment.mediaType = content.mediaType;
1932
- if (content.image.type === "url") attachment.url = content.image.url;
1933
- else attachment.data = content.image.data;
1934
- return attachment;
1935
- }
1936
- attachment.mediaType = content.mediaType;
1937
- if (content.filename !== void 0) attachment.name = content.filename;
1938
- if (content.data.type === "url") {
1939
- attachment.url = content.data.url;
1940
- } else if (content.data.type === "data") {
1941
- attachment.data = content.data.data;
1942
- } else {
1943
- attachment.text = content.data.text;
1944
- }
1945
- 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;
1946
1556
  }
1947
1557
  function clientToolResult(output, result) {
1948
- switch (output.type) {
1949
- case "text":
1950
- return { status: "success", output: output.value };
1951
- case "json":
1952
- return { status: "success", output: output.value };
1953
- case "content":
1954
- return { status: "success", output: result, content: output.value };
1955
- case "execution-denied":
1956
- return {
1957
- status: "error",
1958
- error: {
1959
- message: output.reason ?? "Tool execution was denied.",
1960
- code: "tool_execution_denied"
1961
- }
1962
- };
1963
- case "error-text":
1964
- return {
1965
- status: "error",
1966
- error: { message: output.value, code: "tool_execution_error" }
1967
- };
1968
- case "error-json":
1969
- return {
1970
- status: "error",
1971
- error: {
1972
- message: "Tool execution failed.",
1973
- code: "tool_execution_error",
1974
- details: output.value
1975
- }
1976
- };
1977
- }
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
+ }
1978
1595
  }
1979
1596
  function parseJsonOrString(value) {
1980
- try {
1981
- const parsed = JSON.parse(value);
1982
- return isJsonValue3(parsed) ? parsed : value;
1983
- } catch {
1984
- return value;
1985
- }
1597
+ try {
1598
+ const parsed = JSON.parse(value);
1599
+ return isJsonValue$1(parsed) ? parsed : value;
1600
+ } catch {
1601
+ return value;
1602
+ }
1986
1603
  }
1987
1604
  function clientOutput(output, mapper) {
1988
- const mapped = mapper === void 0 ? isJsonValue3(output) ? output : void 0 : mapper(output);
1989
- if (mapped !== void 0 && !isJsonValue3(mapped)) {
1990
- throw new TypeError("mapOutput must return a strict JSON value or undefined.");
1991
- }
1992
- 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;
1993
1608
  }
1994
1609
  function valueFingerprint(value) {
1995
- if (value === null) return "null";
1996
- if (value === void 0) return "undefined";
1997
- if (Array.isArray(value)) return `[${value.map(valueFingerprint).join(",")}]`;
1998
- if (typeof value === "object") {
1999
- return `{${Object.entries(value).sort(([left], [right]) => left.localeCompare(right)).map(([key, entry]) => `${JSON.stringify(key)}:${valueFingerprint(entry)}`).join(",")}}`;
2000
- }
2001
- 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)}`;
2002
1615
  }
2003
1616
  function clientTrace(trace) {
2004
- const result = {
2005
- observer: trace.observer
2006
- };
2007
- if (trace.traceId !== void 0) result.traceId = trace.traceId;
2008
- if (trace.observationId !== void 0) result.observationId = trace.observationId;
2009
- 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;
2010
1621
  }
2011
1622
  function mapClientError(error, mapper) {
2012
- const mapped = mapper?.(error) ?? maskedClientError();
2013
- if (typeof mapped.message !== "string" || mapped.details !== void 0 && !isJsonValue3(mapped.details)) {
2014
- throw new TypeError("mapError must return a JSON-safe ClientStreamError.");
2015
- }
2016
- 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;
2017
1626
  }
2018
1627
  function clientEvent(state, event) {
2019
- return scopedEvent(state.runId, state.turn, state.scope, event);
1628
+ return scopedEvent(state.runId, state.turn, state.scope, event);
2020
1629
  }
2021
1630
  function rootEvent(runId, event, scope) {
2022
- return scopedEvent(runId, void 0, scope, event);
1631
+ return scopedEvent(runId, void 0, scope, event);
2023
1632
  }
2024
1633
  function scopedEvent(runId, turn, scope, event) {
2025
- let scoped = { runId, ...event };
2026
- if (turn !== void 0) scoped = { ...scoped, turn };
2027
- if (scope !== void 0) scoped = { ...scoped, scope };
2028
- 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;
2029
1647
  }
2030
1648
  function scopeKey(scope) {
2031
- if (scope === void 0) return "root";
2032
- return [
2033
- scope.agentId,
2034
- scope.parentRunId,
2035
- scope.parentToolName,
2036
- scope.parentToolCallId,
2037
- scope.parentInternalToolCallId
2038
- ].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(":");
2039
1657
  }
2040
1658
  function isRootTerminalAgentEvent(event) {
2041
- 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";
2042
1660
  }
2043
1661
  function agentOutcomeStatus(type) {
2044
- if (type === "response") return "completed";
2045
- if (type === "interaction") return "suspended";
2046
- return "blocked";
1662
+ if (type === "response") return "completed";
1663
+ if (type === "interaction") return "suspended";
1664
+ return "blocked";
2047
1665
  }
2048
1666
  function propagateCancellation(source, transform) {
2049
- return {
2050
- [Symbol.asyncIterator]() {
2051
- const sourceIterator = source[Symbol.asyncIterator]();
2052
- const sharedSource = {
2053
- [Symbol.asyncIterator]: () => sourceIterator
2054
- };
2055
- const outputIterator = transform(sharedSource)[Symbol.asyncIterator]();
2056
- let returned = false;
2057
- return {
2058
- next: () => outputIterator.next(),
2059
- async return() {
2060
- if (returned) return { done: true, value: void 0 };
2061
- returned = true;
2062
- const sourceReturn = sourceIterator.return?.();
2063
- const outputReturn = outputIterator.return?.();
2064
- await Promise.all([sourceReturn, outputReturn]);
2065
- return { done: true, value: void 0 };
2066
- }
2067
- };
2068
- }
2069
- };
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
+ } };
2070
1689
  }
2071
-
2072
1690
  // src/client-transport.ts
2073
1691
  function createHttpClientTransport(options) {
2074
- const transport = createFetchEventTransport({
2075
- ...options,
2076
- mapEvent: (event) => parseClientStreamFrame(event, protocolOptions(options)),
2077
- validateResponse(response) {
2078
- if (response.headers.get("x-anvia-stream-protocol") !== CLIENT_STREAM_PROTOCOL) {
2079
- throw new ClientProtocolError(
2080
- `Expected x-anvia-stream-protocol: ${CLIENT_STREAM_PROTOCOL}.`
2081
- );
2082
- }
2083
- }
2084
- });
2085
- return {
2086
- async *send(sendOptions) {
2087
- const resume = sendOptions.resume ?? resumeCursorFromRequest(sendOptions.request);
2088
- yield* validateFrameSequence(transport.send(sendOptions), resume);
2089
- }
2090
- };
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
+ } };
2091
1703
  }
2092
1704
  function createDirectClientTransport(options) {
2093
- return {
2094
- async *send(sendOptions) {
2095
- const resume = sendOptions.resume ?? resumeCursorFromRequest(sendOptions.request);
2096
- if (resume !== void 0) {
2097
- throw new ClientProtocolError("Direct client transports do not support resume cursors.");
2098
- }
2099
- const handlerOptions = {
2100
- request: sendOptions.request
2101
- };
2102
- if (sendOptions.abortSignal !== void 0) {
2103
- handlerOptions.abortSignal = sendOptions.abortSignal;
2104
- }
2105
- if (sendOptions.headers !== void 0) handlerOptions.headers = sendOptions.headers;
2106
- const events = await options.handler(handlerOptions);
2107
- const iterator = events[Symbol.asyncIterator]();
2108
- const streamId = createClientId("stream");
2109
- let eventId = 0;
2110
- yield {
2111
- type: "stream_start",
2112
- protocol: CLIENT_STREAM_PROTOCOL,
2113
- streamId,
2114
- eventId: 0,
2115
- resumable: false
2116
- };
2117
- let status = "completed";
2118
- try {
2119
- let closePromise;
2120
- const close = () => {
2121
- closePromise ??= Promise.resolve(iterator.return?.());
2122
- return closePromise;
2123
- };
2124
- const onAbort = () => {
2125
- void close();
2126
- };
2127
- sendOptions.abortSignal?.addEventListener("abort", onAbort, { once: true });
2128
- try {
2129
- while (!sendOptions.abortSignal?.aborted) {
2130
- const next = await iterator.next();
2131
- if (next.done) break;
2132
- const event = parseClientStreamEvent(
2133
- next.value,
2134
- protocolOptions(options)
2135
- );
2136
- eventId += 1;
2137
- yield { type: "stream_event", streamId, eventId, event };
2138
- }
2139
- } finally {
2140
- sendOptions.abortSignal?.removeEventListener("abort", onAbort);
2141
- await close();
2142
- }
2143
- } catch {
2144
- status = "error";
2145
- }
2146
- yield { type: "stream_end", streamId, eventId, status };
2147
- }
2148
- };
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
+ } };
2149
1758
  }
2150
1759
  async function* validateFrameSequence(frames, resume) {
2151
- let streamId;
2152
- let lastEventId = resume?.after ?? 0;
2153
- let ended = false;
2154
- for await (const frame of frames) {
2155
- if (ended) throw new ClientProtocolError("Received a frame after stream_end.", frame);
2156
- if (streamId === void 0) {
2157
- if (frame.type !== "stream_start") {
2158
- throw new ClientProtocolError("The first client stream frame must be stream_start.", frame);
2159
- }
2160
- streamId = frame.streamId;
2161
- if (resume !== void 0 && frame.streamId !== resume.streamId) {
2162
- throw new ClientProtocolError("Resume response streamId does not match the cursor.", frame);
2163
- }
2164
- if (resume !== void 0 && !frame.resumable) {
2165
- throw new ClientProtocolError("Resume response must identify a resumable stream.", frame);
2166
- }
2167
- } else if (frame.type === "stream_start") {
2168
- throw new ClientProtocolError("Received more than one stream_start frame.", frame);
2169
- } else if (frame.streamId !== streamId) {
2170
- throw new ClientProtocolError("Client streamId changed during the response.", frame);
2171
- }
2172
- if (frame.type === "stream_event") {
2173
- if (frame.eventId !== lastEventId + 1) {
2174
- throw new ClientProtocolError("Client stream event IDs must be contiguous.", frame);
2175
- }
2176
- lastEventId = frame.eventId;
2177
- } else if (frame.type === "stream_end") {
2178
- if (frame.eventId !== lastEventId) {
2179
- throw new ClientProtocolError("stream_end has an invalid eventId.", frame);
2180
- }
2181
- ended = true;
2182
- }
2183
- yield frame;
2184
- }
2185
- if (streamId === void 0 || !ended) {
2186
- throw new ClientProtocolError("Client stream ended without a complete frame sequence.");
2187
- }
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.");
2188
1782
  }
2189
1783
  function protocolOptions(options) {
2190
- const result = {};
2191
- if (options.metadataSchema !== void 0) result.metadataSchema = options.metadataSchema;
2192
- if (options.dataSchemas !== void 0) result.dataSchemas = options.dataSchemas;
2193
- 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;
2194
1788
  }
2195
1789
  function resumeCursorFromRequest(value) {
2196
- if (typeof value !== "object" || value === null || !("resume" in value)) return void 0;
2197
- const resume = value.resume;
2198
- if (typeof resume !== "object" || resume === null) return void 0;
2199
- if (!("streamId" in resume) || !("after" in resume)) return void 0;
2200
- 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;
2201
1798
  }
2202
-
2203
- // src/index.ts
2204
- import { isJsonValue as isJsonValue5 } from "@anvia/core/completion";
2205
-
2206
1799
  // src/reducer.ts
2207
- import { isJsonValue as isJsonValue4 } from "@anvia/core/completion";
2208
1800
  function applyClientStreamEvent(messages, event) {
2209
- if (event.scope?.parentToolCallId !== void 0) {
2210
- return messages;
2211
- }
2212
- switch (event.type) {
2213
- case "message_start": {
2214
- if (messages.some((message2) => message2.id === event.messageId)) return messages;
2215
- let message = {
2216
- id: event.messageId,
2217
- role: event.role,
2218
- parts: []
2219
- };
2220
- if (event.metadata !== void 0) message = { ...message, metadata: event.metadata };
2221
- return [...messages, message];
2222
- }
2223
- case "text_start":
2224
- return upsertPart(messages, event.messageId, {
2225
- id: event.partId,
2226
- type: "text",
2227
- text: ""
2228
- });
2229
- case "text_delta":
2230
- return updatePart(messages, event.messageId, event.partId, (part) => ({
2231
- id: event.partId,
2232
- type: "text",
2233
- text: part?.type === "text" ? `${part.text}${event.delta}` : event.delta
2234
- }));
2235
- case "text_end":
2236
- return updatePart(messages, event.messageId, event.partId, (part) => {
2237
- const next = {
2238
- id: event.partId,
2239
- type: "text",
2240
- text: event.text ?? (part?.type === "text" ? part.text : "")
2241
- };
2242
- if (event.signature !== void 0) next.signature = event.signature;
2243
- return next;
2244
- });
2245
- case "reasoning_start": {
2246
- const reasoning = {
2247
- id: event.partId,
2248
- type: "reasoning",
2249
- text: ""
2250
- };
2251
- if (event.reasoningId !== void 0) reasoning.reasoningId = event.reasoningId;
2252
- return upsertPart(messages, event.messageId, reasoning);
2253
- }
2254
- case "reasoning_delta":
2255
- return updatePart(messages, event.messageId, event.partId, (part) => {
2256
- const reasoning = {
2257
- id: event.partId,
2258
- type: "reasoning",
2259
- text: part?.type === "reasoning" ? `${part.text}${event.delta}` : event.delta
2260
- };
2261
- if (part?.type === "reasoning" && part.reasoningId !== void 0) {
2262
- reasoning.reasoningId = part.reasoningId;
2263
- }
2264
- const content = appendReasoningContent(
2265
- part?.type === "reasoning" ? part.content : void 0,
2266
- event
2267
- );
2268
- if (content !== void 0) reasoning.content = content;
2269
- return reasoning;
2270
- });
2271
- case "reasoning_end":
2272
- return updatePart(messages, event.messageId, event.partId, (part) => {
2273
- const reasoning = {
2274
- id: event.partId,
2275
- type: "reasoning",
2276
- text: event.text ?? (part?.type === "reasoning" ? part.text : "")
2277
- };
2278
- if (part?.type === "reasoning" && part.reasoningId !== void 0) {
2279
- reasoning.reasoningId = part.reasoningId;
2280
- }
2281
- if (event.content !== void 0) {
2282
- reasoning.content = event.content;
2283
- } else if (part?.type === "reasoning" && part.content !== void 0) {
2284
- reasoning.content = part.content;
2285
- }
2286
- return reasoning;
2287
- });
2288
- case "tool_call_start": {
2289
- const part = {
2290
- id: event.partId,
2291
- type: "tool",
2292
- toolName: event.toolName ?? "",
2293
- toolCallId: event.toolCallId,
2294
- state: "input-streaming",
2295
- input: ""
2296
- };
2297
- if (event.callId !== void 0) part.callId = event.callId;
2298
- if (event.turn !== void 0) part.turn = event.turn;
2299
- return upsertPart(messages, event.messageId, part);
2300
- }
2301
- case "tool_call_delta":
2302
- return updatePart(messages, event.messageId, event.partId, (current) => {
2303
- const part = current?.type === "tool" ? toolPartBase(current) : {
2304
- id: event.partId,
2305
- type: "tool",
2306
- toolName: event.toolName ?? "",
2307
- toolCallId: event.toolCallId
2308
- };
2309
- const previous = current?.type === "tool" && typeof current.input === "string" ? current.input : "";
2310
- if (event.toolName !== void 0) part.toolName = event.toolName;
2311
- if (event.callId !== void 0) part.callId = event.callId;
2312
- if (event.signature !== void 0) part.signature = event.signature;
2313
- if (event.turn !== void 0) part.turn = event.turn;
2314
- return {
2315
- ...part,
2316
- state: "input-streaming",
2317
- input: event.mode === "replace" ? event.delta : `${previous}${event.delta}`
2318
- };
2319
- });
2320
- case "tool_call_end": {
2321
- const part = {
2322
- id: event.partId,
2323
- type: "tool",
2324
- toolName: event.toolName,
2325
- toolCallId: event.toolCallId,
2326
- state: "input-available",
2327
- input: event.input
2328
- };
2329
- if (event.callId !== void 0) part.callId = event.callId;
2330
- if (event.turn !== void 0) part.turn = event.turn;
2331
- if (event.signature !== void 0) part.signature = event.signature;
2332
- return upsertPart(messages, event.messageId, part);
2333
- }
2334
- case "tool_result":
2335
- return updatePart(messages, event.messageId, event.partId, (current) => {
2336
- const part = current?.type === "tool" ? toolPartBase(current) : {
2337
- id: event.partId,
2338
- type: "tool",
2339
- toolName: event.toolName,
2340
- toolCallId: event.toolCallId
2341
- };
2342
- if (event.callId !== void 0) part.callId = event.callId;
2343
- if (event.internalCallId !== void 0) part.internalCallId = event.internalCallId;
2344
- if (event.turn !== void 0) part.turn = event.turn;
2345
- if (event.result.status === "error") {
2346
- return {
2347
- ...part,
2348
- state: "error",
2349
- input: event.input,
2350
- error: event.result.error
2351
- };
2352
- }
2353
- const completed = {
2354
- ...part,
2355
- state: "output-available",
2356
- input: event.input,
2357
- output: event.result.output
2358
- };
2359
- if (event.result.content !== void 0) completed.resultContent = event.result.content;
2360
- return completed;
2361
- });
2362
- case "source":
2363
- return upsertPart(messages, event.messageId, {
2364
- id: event.partId,
2365
- type: "source",
2366
- source: event.source
2367
- });
2368
- case "attachment":
2369
- return upsertPart(messages, event.messageId, {
2370
- id: event.partId,
2371
- type: "attachment",
2372
- attachment: event.attachment
2373
- });
2374
- case "data":
2375
- if (event.transient === true) return messages;
2376
- return appendToLastAssistant(messages, {
2377
- id: createClientId("data"),
2378
- type: "data",
2379
- name: event.name,
2380
- data: event.data
2381
- });
2382
- case "message_end":
2383
- return messages.map((message) => {
2384
- if (message.id !== event.messageId) return message;
2385
- const metadata = mergeMetadata(message.metadata, event.metadata);
2386
- const generationUpdate = {
2387
- runId: event.runId
2388
- };
2389
- if (event.usage !== void 0) generationUpdate.usage = event.usage;
2390
- if (event.contextUsage !== void 0) {
2391
- generationUpdate.contextUsage = event.contextUsage;
2392
- }
2393
- const generation = mergeGeneration(message.generation, generationUpdate);
2394
- let updated = {
2395
- ...message,
2396
- generation
2397
- };
2398
- if (event.parts !== void 0) {
2399
- updated = { ...updated, parts: reconcileFinalParts(message.parts, event.parts) };
2400
- }
2401
- if (event.modelMessageId !== void 0) {
2402
- updated = { ...updated, modelMessageId: event.modelMessageId };
2403
- }
2404
- if (metadata !== void 0) updated = { ...updated, metadata };
2405
- return updated;
2406
- });
2407
- case "run_end": {
2408
- const generation = {
2409
- runId: event.runId,
2410
- status: event.status
2411
- };
2412
- if (event.contextUsage !== void 0) generation.contextUsage = event.contextUsage;
2413
- if (event.trace !== void 0) generation.trace = event.trace;
2414
- if (event.memoryCompaction !== void 0) {
2415
- generation.memoryCompaction = event.memoryCompaction;
2416
- }
2417
- return updateLastAssistantGeneration(messages, generation);
2418
- }
2419
- case "error":
2420
- return appendToLastAssistant(messages, {
2421
- id: createClientId("error"),
2422
- type: "error",
2423
- error: event.error
2424
- });
2425
- default:
2426
- return messages;
2427
- }
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
+ }
2428
2001
  }
2429
2002
  function toolPartBase(part) {
2430
- const base = {
2431
- id: part.id,
2432
- type: part.type,
2433
- toolName: part.toolName,
2434
- toolCallId: part.toolCallId
2435
- };
2436
- if (part.callId !== void 0) Object.assign(base, { callId: part.callId });
2437
- if (part.internalCallId !== void 0) {
2438
- Object.assign(base, { internalCallId: part.internalCallId });
2439
- }
2440
- if (part.turn !== void 0) Object.assign(base, { turn: part.turn });
2441
- if (part.signature !== void 0) Object.assign(base, { signature: part.signature });
2442
- 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;
2443
2014
  }
2444
2015
  function reconcileFinalParts(current, final) {
2445
- const clientOnly = current.filter(
2446
- (part) => part.type === "source" || part.type === "data" || part.type === "error"
2447
- );
2448
- return [...final, ...clientOnly];
2016
+ const clientOnly = current.filter((part) => part.type === "source" || part.type === "data" || part.type === "error");
2017
+ return [...final, ...clientOnly];
2449
2018
  }
2450
2019
  function appendReasoningContent(current, event) {
2451
- if (event.contentType === void 0 && event.signature === void 0) return current;
2452
- const type = event.contentType ?? "text";
2453
- const next = [...current ?? []];
2454
- const last = next.at(-1);
2455
- if (type === "text") {
2456
- if (last?.type === "text" && last.signature === event.signature) {
2457
- next[next.length - 1] = { ...last, text: `${last.text}${event.delta}` };
2458
- } else {
2459
- let detail = {
2460
- type,
2461
- text: event.delta
2462
- };
2463
- if (event.signature !== void 0) detail = { ...detail, signature: event.signature };
2464
- next.push(detail);
2465
- }
2466
- return next;
2467
- }
2468
- if (type === "summary") {
2469
- if (last?.type === "summary") {
2470
- next[next.length - 1] = { ...last, text: `${last.text}${event.delta}` };
2471
- } else next.push({ type, text: event.delta });
2472
- return next;
2473
- }
2474
- if (type === "encrypted") {
2475
- if (last?.type === "encrypted") {
2476
- next[next.length - 1] = { ...last, data: `${last.data}${event.delta}` };
2477
- } else next.push({ type, data: event.delta });
2478
- return next;
2479
- }
2480
- if (last?.type === "redacted") {
2481
- next[next.length - 1] = { ...last, data: `${last.data}${event.delta}` };
2482
- } else next.push({ type, data: event.delta });
2483
- 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;
2484
2073
  }
2485
2074
  function messageText(message) {
2486
- return message.parts.flatMap((part) => part.type === "text" ? [part.text] : []).join("");
2075
+ return message.parts.flatMap((part) => part.type === "text" ? [part.text] : []).join("");
2487
2076
  }
2488
2077
  function assistantText(messages) {
2489
- const assistant = [...messages].reverse().find((message) => message.role === "assistant");
2490
- return assistant === void 0 ? "" : messageText(assistant);
2078
+ const assistant = [...messages].reverse().find((message) => message.role === "assistant");
2079
+ return assistant === void 0 ? "" : messageText(assistant);
2491
2080
  }
2492
2081
  function upsertPart(messages, messageId, part) {
2493
- return updatePart(messages, messageId, part.id, () => part);
2082
+ return updatePart(messages, messageId, part.id, () => part);
2494
2083
  }
2495
2084
  function updatePart(messages, messageId, partId, update) {
2496
- const current = ensureAssistant(messages, messageId);
2497
- return current.map((message) => {
2498
- if (message.id !== messageId) return message;
2499
- const index = message.parts.findIndex((part) => part.id === partId);
2500
- if (index === -1) return { ...message, parts: [...message.parts, update(void 0)] };
2501
- const parts = [...message.parts];
2502
- parts[index] = update(parts[index]);
2503
- return { ...message, parts };
2504
- });
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
+ });
2505
2099
  }
2506
2100
  function ensureAssistant(messages, messageId) {
2507
- 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
+ }];
2508
2106
  }
2509
2107
  function appendToLastAssistant(messages, part) {
2510
- const index = findLastIndex(messages, (message2) => message2.role === "assistant");
2511
- if (index === -1) {
2512
- return [...messages, { id: createClientId("msg"), role: "assistant", parts: [part] }];
2513
- }
2514
- const next = [...messages];
2515
- const message = next[index];
2516
- next[index] = { ...message, parts: [...message.parts, part] };
2517
- 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;
2518
2121
  }
2519
2122
  function updateLastAssistantGeneration(messages, value) {
2520
- const index = findLastIndex(messages, (message2) => message2.role === "assistant");
2521
- if (index === -1) return messages;
2522
- const next = [...messages];
2523
- const message = next[index];
2524
- next[index] = { ...message, generation: mergeGeneration(message.generation, value) };
2525
- 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;
2526
2132
  }
2527
2133
  function mergeMetadata(current, provided) {
2528
- if (provided === void 0) return current;
2529
- if (!isRecord2(current) || !isRecord2(provided)) return provided;
2530
- const next = { ...current, ...provided };
2531
- 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;
2532
2141
  }
2533
2142
  function mergeGeneration(current, provided) {
2534
- return {
2535
- ...current,
2536
- ...Object.fromEntries(Object.entries(provided).filter(([, value]) => value !== void 0))
2537
- };
2143
+ return {
2144
+ ...current,
2145
+ ...Object.fromEntries(Object.entries(provided).filter(([, value]) => value !== void 0))
2146
+ };
2538
2147
  }
2539
2148
  function findLastIndex(items, predicate) {
2540
- for (let index = items.length - 1; index >= 0; index -= 1) {
2541
- if (predicate(items[index])) return index;
2542
- }
2543
- return -1;
2544
- }
2545
- function isRecord2(value) {
2546
- return typeof value === "object" && value !== null && !Array.isArray(value);
2547
- }
2548
- export {
2549
- CLIENT_STREAM_PROTOCOL,
2550
- ClientProtocolError,
2551
- agentToClientStream,
2552
- applyClientStreamEvent,
2553
- assistantText,
2554
- completionToClientStream,
2555
- createClientId,
2556
- createDirectClientTransport,
2557
- createHttpClientTransport,
2558
- customAgentEventsToClientStream,
2559
- isJsonValue5 as isJsonValue,
2560
- maskedClientError,
2561
- messageText,
2562
- messagesToUIMessages,
2563
- normalizeClientError,
2564
- parseClientStreamEvent,
2565
- parseClientStreamFrame,
2566
- parseClientStreamRequest,
2567
- parseUIMessage,
2568
- parseUIMessages,
2569
- uiMessagesToMessages
2570
- };
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
+
2571
2157
  //# sourceMappingURL=index.js.map