@assistant-ui/react-ag-ui 0.0.58 → 0.0.60
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/agUiExtras.d.ts +1 -2
- package/dist/agUiExtras.d.ts.map +1 -1
- package/dist/hooks.d.ts +6 -7
- package/dist/hooks.d.ts.map +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/runtime/AgUiThreadRuntimeCore.d.ts +17 -6
- package/dist/runtime/AgUiThreadRuntimeCore.d.ts.map +1 -1
- package/dist/runtime/AgUiThreadRuntimeCore.js +95 -47
- package/dist/runtime/AgUiThreadRuntimeCore.js.map +1 -1
- package/dist/runtime/adapter/conversions.d.ts +11 -11
- package/dist/runtime/adapter/conversions.d.ts.map +1 -1
- package/dist/runtime/adapter/conversions.js +114 -17
- package/dist/runtime/adapter/conversions.js.map +1 -1
- package/dist/runtime/adapter/run-aggregator.d.ts +9 -10
- package/dist/runtime/adapter/run-aggregator.d.ts.map +1 -1
- package/dist/runtime/adapter/run-aggregator.js +59 -0
- package/dist/runtime/adapter/run-aggregator.js.map +1 -1
- package/dist/runtime/adapter/subscriber.d.ts +2 -3
- package/dist/runtime/adapter/subscriber.d.ts.map +1 -1
- package/dist/runtime/adapter/tool-approval.d.ts +4 -5
- package/dist/runtime/adapter/tool-approval.d.ts.map +1 -1
- package/dist/runtime/event-parser.d.ts +2 -3
- package/dist/runtime/event-parser.d.ts.map +1 -1
- package/dist/runtime/interrupt-internals.d.ts +3 -4
- package/dist/runtime/interrupt-internals.d.ts.map +1 -1
- package/dist/runtime/logger.d.ts +2 -3
- package/dist/runtime/logger.d.ts.map +1 -1
- package/dist/runtime/mcp-tool-result.d.ts +3 -4
- package/dist/runtime/mcp-tool-result.d.ts.map +1 -1
- package/dist/runtime/types.d.ts +35 -11
- package/dist/runtime/types.d.ts.map +1 -1
- package/dist/useAgUiRuntime.d.ts +2 -3
- package/dist/useAgUiRuntime.d.ts.map +1 -1
- package/dist/useAgUiRuntime.js +14 -5
- package/dist/useAgUiRuntime.js.map +1 -1
- package/package.json +12 -11
- package/src/index.ts +1 -0
- package/src/runtime/AgUiThreadRuntimeCore.test.ts +18 -0
- package/src/runtime/AgUiThreadRuntimeCore.ts +176 -63
- package/src/runtime/adapter/conversions.ts +200 -26
- package/src/runtime/adapter/run-aggregator.ts +85 -0
- package/src/runtime/types.ts +26 -0
- package/src/useAgUiRuntime.queue.test.tsx +54 -0
- package/src/useAgUiRuntime.thread-switch.test.tsx +199 -0
- package/src/useAgUiRuntime.ts +14 -3
|
@@ -433,17 +433,92 @@ function attachA2uiSurfaces(message, state) {
|
|
|
433
433
|
content: [...preserved, ...a2uiParts]
|
|
434
434
|
};
|
|
435
435
|
}
|
|
436
|
+
function isSyntheticToolCallContainer(message) {
|
|
437
|
+
if (message.role !== "assistant" || !Array.isArray(message.content)) return false;
|
|
438
|
+
let carriesOwnId = false;
|
|
439
|
+
for (const part of message.content) {
|
|
440
|
+
if (!isObject(part)) continue;
|
|
441
|
+
if (part.type === "text") return false;
|
|
442
|
+
if (part.type === "tool-call" && getString(part, "toolCallId") === message.id) carriesOwnId = true;
|
|
443
|
+
}
|
|
444
|
+
return carriesOwnId;
|
|
445
|
+
}
|
|
446
|
+
function carriesText(message) {
|
|
447
|
+
return Array.isArray(message.content) && message.content.some((part) => isObject(part) && part.type === "text");
|
|
448
|
+
}
|
|
449
|
+
function foldsOntoToolCallContainer(message) {
|
|
450
|
+
if (message.role !== "assistant" || !Array.isArray(message.content)) return false;
|
|
451
|
+
if (message.content.length === 0) return false;
|
|
452
|
+
return isSyntheticToolCallContainer(message) || !message.content.some((part) => isObject(part) && part.type === "tool-call");
|
|
453
|
+
}
|
|
454
|
+
function readCustomMetadata(metadata) {
|
|
455
|
+
if (!isObject(metadata) || !isObject(metadata.custom)) return {};
|
|
456
|
+
return metadata.custom;
|
|
457
|
+
}
|
|
458
|
+
function readNamespacedMetadata(metadata) {
|
|
459
|
+
const namespaced = readCustomMetadata(metadata)[AG_UI_METADATA_NAMESPACE];
|
|
460
|
+
return isObject(namespaced) ? namespaced : {};
|
|
461
|
+
}
|
|
462
|
+
function foldOntoToolCallContainer(container, message) {
|
|
463
|
+
const interrupts = [...readPersistedInterrupts(container.metadata) ?? [], ...readPersistedInterrupts(message.metadata) ?? []];
|
|
464
|
+
const opaqueReasoning = [...readOpaqueReasoning(container.metadata), ...readOpaqueReasoning(message.metadata).map((entry) => ({
|
|
465
|
+
...entry,
|
|
466
|
+
after: true
|
|
467
|
+
}))];
|
|
468
|
+
const namespaced = {
|
|
469
|
+
...readNamespacedMetadata(container.metadata),
|
|
470
|
+
...readNamespacedMetadata(message.metadata),
|
|
471
|
+
...interrupts.length > 0 ? { interrupts } : {},
|
|
472
|
+
...opaqueReasoning.length > 0 ? { opaqueReasoning } : {}
|
|
473
|
+
};
|
|
474
|
+
const custom = {
|
|
475
|
+
...readCustomMetadata(container.metadata),
|
|
476
|
+
...readCustomMetadata(message.metadata),
|
|
477
|
+
...Object.keys(namespaced).length > 0 ? { [AG_UI_METADATA_NAMESPACE]: namespaced } : {}
|
|
478
|
+
};
|
|
479
|
+
const metadata = {
|
|
480
|
+
...isObject(container.metadata) ? container.metadata : {},
|
|
481
|
+
...isObject(message.metadata) ? message.metadata : {},
|
|
482
|
+
...Object.keys(custom).length > 0 ? { custom } : {}
|
|
483
|
+
};
|
|
484
|
+
return {
|
|
485
|
+
...container,
|
|
486
|
+
...message,
|
|
487
|
+
id: carriesText(message) ? message.id : container.id,
|
|
488
|
+
content: [...Array.isArray(container.content) ? container.content : [], ...Array.isArray(message.content) ? message.content : []],
|
|
489
|
+
...Object.keys(metadata).length > 0 ? { metadata } : {}
|
|
490
|
+
};
|
|
491
|
+
}
|
|
436
492
|
function fromAgUiMessages(messages, options) {
|
|
437
493
|
const showThinking = options?.showThinking ?? true;
|
|
438
494
|
const converted = [];
|
|
439
495
|
const a2uiBuckets = /* @__PURE__ */ new Map();
|
|
440
496
|
const a2uiBucketOwnerIndices = /* @__PURE__ */ new Map();
|
|
441
497
|
const opaqueReasoning = [];
|
|
498
|
+
const pendingReasoning = [];
|
|
499
|
+
const flushPendingReasoning = () => {
|
|
500
|
+
for (const { id, part } of pendingReasoning) converted.push({
|
|
501
|
+
id: id ?? generateId(),
|
|
502
|
+
role: "assistant",
|
|
503
|
+
content: [part]
|
|
504
|
+
});
|
|
505
|
+
pendingReasoning.length = 0;
|
|
506
|
+
};
|
|
507
|
+
const withPendingReasoning = (message) => {
|
|
508
|
+
if (pendingReasoning.length === 0) return message;
|
|
509
|
+
const parts = pendingReasoning.map(({ part }) => part);
|
|
510
|
+
pendingReasoning.length = 0;
|
|
511
|
+
return {
|
|
512
|
+
...message,
|
|
513
|
+
content: [...parts, ...Array.isArray(message.content) ? message.content : []]
|
|
514
|
+
};
|
|
515
|
+
};
|
|
442
516
|
for (const rawMessage of messages) {
|
|
443
517
|
if (!isObject(rawMessage)) continue;
|
|
444
518
|
const role = getString(rawMessage, "role");
|
|
445
519
|
if (!role) continue;
|
|
446
520
|
if (role === "tool") {
|
|
521
|
+
flushPendingReasoning();
|
|
447
522
|
const toolCallId = getToolCallId(rawMessage) ?? `tool-${generateId()}`;
|
|
448
523
|
const toolMessageId = getString(rawMessage, "id");
|
|
449
524
|
const modelContent = extractText(rawMessage.content);
|
|
@@ -506,6 +581,7 @@ function fromAgUiMessages(messages, options) {
|
|
|
506
581
|
if (getString(rawMessage, "activityType") !== "a2ui-surface") continue;
|
|
507
582
|
const operations = (isObject(rawMessage.content) ? rawMessage.content : null)?.["a2ui_operations"];
|
|
508
583
|
if (!Array.isArray(operations)) continue;
|
|
584
|
+
flushPendingReasoning();
|
|
509
585
|
let ownerIndex = -1;
|
|
510
586
|
for (let i = converted.length - 1; i >= 0; i--) {
|
|
511
587
|
const candidate = converted[i];
|
|
@@ -531,7 +607,7 @@ function fromAgUiMessages(messages, options) {
|
|
|
531
607
|
continue;
|
|
532
608
|
}
|
|
533
609
|
if (role === "assistant") {
|
|
534
|
-
converted.push(toAssistantSnapshotMessage(rawMessage));
|
|
610
|
+
converted.push(withPendingReasoning(toAssistantSnapshotMessage(rawMessage)));
|
|
535
611
|
continue;
|
|
536
612
|
}
|
|
537
613
|
if (role === "reasoning") {
|
|
@@ -539,11 +615,14 @@ function fromAgUiMessages(messages, options) {
|
|
|
539
615
|
const encryptedValue = getString(rawMessage, "encryptedValue");
|
|
540
616
|
if (text.trim().length === 0) {
|
|
541
617
|
const opaqueId = getString(rawMessage, "id");
|
|
542
|
-
if (opaqueId?.trim() && encryptedValue?.trim())
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
618
|
+
if (opaqueId?.trim() && encryptedValue?.trim()) {
|
|
619
|
+
flushPendingReasoning();
|
|
620
|
+
opaqueReasoning.push({
|
|
621
|
+
id: opaqueId,
|
|
622
|
+
encryptedValue,
|
|
623
|
+
anchor: converted.length
|
|
624
|
+
});
|
|
625
|
+
}
|
|
547
626
|
continue;
|
|
548
627
|
}
|
|
549
628
|
if (!showThinking) {
|
|
@@ -555,19 +634,28 @@ function fromAgUiMessages(messages, options) {
|
|
|
555
634
|
});
|
|
556
635
|
continue;
|
|
557
636
|
}
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
637
|
+
const rawReasoningId = getString(rawMessage, "id");
|
|
638
|
+
const reasoningId = rawReasoningId?.trim() ? rawReasoningId : void 0;
|
|
639
|
+
const meta = {
|
|
640
|
+
...reasoningId !== void 0 ? { reasoningId } : {},
|
|
641
|
+
...encryptedValue !== void 0 ? { encryptedValue } : {}
|
|
642
|
+
};
|
|
643
|
+
pendingReasoning.push({
|
|
644
|
+
id: reasoningId,
|
|
645
|
+
part: {
|
|
562
646
|
type: "reasoning",
|
|
563
647
|
text,
|
|
564
|
-
...
|
|
565
|
-
}
|
|
648
|
+
...Object.keys(meta).length > 0 ? { providerMetadata: { [AG_UI_METADATA_NAMESPACE]: meta } } : {}
|
|
649
|
+
}
|
|
566
650
|
});
|
|
567
651
|
continue;
|
|
568
652
|
}
|
|
569
|
-
if (role === "user" || role === "system" || role === "developer")
|
|
653
|
+
if (role === "user" || role === "system" || role === "developer") {
|
|
654
|
+
flushPendingReasoning();
|
|
655
|
+
converted.push(toUserOrSystemSnapshotMessage(role, rawMessage));
|
|
656
|
+
}
|
|
570
657
|
}
|
|
658
|
+
flushPendingReasoning();
|
|
571
659
|
for (const { anchor, ...entry } of opaqueReasoning) {
|
|
572
660
|
const trailing = anchor >= converted.length;
|
|
573
661
|
const index = trailing ? converted.length - 1 : anchor;
|
|
@@ -578,17 +666,26 @@ function fromAgUiMessages(messages, options) {
|
|
|
578
666
|
after: true
|
|
579
667
|
}] : [entry]]);
|
|
580
668
|
}
|
|
581
|
-
|
|
582
|
-
|
|
669
|
+
const folded = [];
|
|
670
|
+
for (const message of converted) {
|
|
671
|
+
const previous = folded[folded.length - 1];
|
|
672
|
+
if (previous !== void 0 && isSyntheticToolCallContainer(previous) && foldsOntoToolCallContainer(message)) {
|
|
673
|
+
folded[folded.length - 1] = foldOntoToolCallContainer(previous, message);
|
|
674
|
+
continue;
|
|
675
|
+
}
|
|
676
|
+
folded.push(message);
|
|
677
|
+
}
|
|
678
|
+
for (let i = 0; i < folded.length; i++) {
|
|
679
|
+
const message = folded[i];
|
|
583
680
|
if (message.role !== "assistant") continue;
|
|
584
681
|
const hasInterrupt = readPersistedInterrupts(message.metadata) !== void 0;
|
|
585
682
|
const hasPendingToolCall = Array.isArray(message.content) && message.content.some((part) => isObject(part) && part.type === "tool-call" && part.result === void 0);
|
|
586
|
-
if (hasInterrupt || hasPendingToolCall)
|
|
683
|
+
if (hasInterrupt || hasPendingToolCall) folded[i] = {
|
|
587
684
|
...message,
|
|
588
685
|
status: getAutoStatus(false, false, hasInterrupt, hasPendingToolCall, void 0)
|
|
589
686
|
};
|
|
590
687
|
}
|
|
591
|
-
return
|
|
688
|
+
return folded;
|
|
592
689
|
}
|
|
593
690
|
function convertAssistantMessage(message, converted) {
|
|
594
691
|
const content = extractText(message.content);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"conversions.js","names":[],"sources":["../../../src/runtime/adapter/conversions.ts"],"sourcesContent":["\"use client\";\n\nimport type { InputContent, RunAgentParameters } from \"@ag-ui/client\";\nimport { generateId } from \"@assistant-ui/core\";\nimport type {\n ThreadMessageLike as CoreThreadMessageLike,\n PartProviderMetadata,\n ThreadMessage,\n ToolCallMessagePartMcpMetadata,\n ToolModelContentPart,\n} from \"@assistant-ui/core\";\nimport {\n getAutoStatus,\n parseDataUrl,\n resolveFilePartSource,\n} from \"@assistant-ui/core/internal\";\nimport { type Tool, toToolsJSONSchema } from \"assistant-stream\";\nimport type { ReadonlyJSONObject } from \"assistant-stream/utils\";\nimport {\n AG_UI_METADATA_NAMESPACE,\n A2UI_SURFACE_ACTIVITY_TYPE,\n type AgUiCustomMetadata,\n type AgUiOpaqueReasoning,\n} from \"./run-aggregator\";\nimport {\n applyA2uiOperations,\n convertSurfaceToUISpec,\n type A2uiState,\n type A2uiSurfaceState,\n} from \"@assistant-ui/react-generative-ui/a2ui\";\nimport type { AgUiInterrupt } from \"../types\";\nimport { projectAgUiToolApprovals } from \"./tool-approval\";\nimport {\n parseMcpToolCallResult,\n readMcpAppResourceUri,\n} from \"../mcp-tool-result\";\n\nexport type { InputContent };\n\ntype AttachmentLike = {\n name?: string | undefined;\n contentType?: string | undefined;\n content?: readonly unknown[] | undefined;\n};\n\ntype ThreadMessageLike = {\n id?: string;\n role: string;\n content: unknown;\n metadata?: unknown;\n name?: string;\n toolCallId?: string;\n error?: string;\n attachments?: readonly AttachmentLike[];\n};\n\ntype NormalizedThreadMessageLike = ThreadMessageLike & { id: string };\n\ntype AgUiToolCall = {\n id: string;\n type: \"function\";\n function: { name: string; arguments: string };\n};\n\nexport type AgUiMessage =\n | {\n id: string;\n role: \"user\";\n content: string | InputContent[];\n name?: string;\n }\n | {\n id: string;\n role: \"assistant\";\n content: string;\n name?: string;\n toolCalls?: AgUiToolCall[];\n }\n | {\n id: string;\n role: \"system\" | \"developer\";\n content: string;\n name?: string;\n }\n | {\n id: string;\n role: \"reasoning\";\n content: string;\n encryptedValue?: string;\n }\n | {\n id: string;\n role: \"tool\";\n content: string;\n toolCallId: string;\n error?: string;\n };\n\ntype ToolCallPart = {\n type: \"tool-call\";\n toolCallId?: string;\n toolName: string;\n argsText?: string;\n args?: ReadonlyJSONObject;\n result?: unknown;\n isError?: boolean;\n modelContent?: readonly ToolModelContentPart[];\n unstable_toolMessageId?: string;\n mcp?: ToolCallMessagePartMcpMetadata;\n messages?: readonly ThreadMessage[];\n approval?: CoreToolCallPartApproval;\n};\n\ntype CoreToolCallPartApproval = NonNullable<\n Extract<\n Exclude<CoreThreadMessageLike[\"content\"], string>[number],\n { type: \"tool-call\" }\n >[\"approval\"]\n>;\n\nconst isObject = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null;\n\nconst getString = (record: Record<string, unknown>, key: string) => {\n const value = record[key];\n return typeof value === \"string\" ? value : undefined;\n};\n\nconst getToolCallId = (record: Record<string, unknown>) =>\n getString(record, \"toolCallId\") ?? getString(record, \"tool_call_id\");\n\nconst readAgUiNamespace = (providerMetadata: unknown) => {\n if (!isObject(providerMetadata)) return undefined;\n const namespaced = providerMetadata[AG_UI_METADATA_NAMESPACE];\n return isObject(namespaced) ? namespaced : undefined;\n};\n\nconst readAgUiReasoningMeta = (providerMetadata: unknown) => {\n const namespaced = readAgUiNamespace(providerMetadata);\n if (!namespaced) return {};\n return {\n encryptedValue: getString(namespaced, \"encryptedValue\"),\n reasoningId: getString(namespaced, \"reasoningId\"),\n };\n};\n\n// AG-UI carries per-item extras in `metadata`; anything else on the item is\n// stripped by its schema. The part's own `filename` wins over a key of the\n// same name in the bag.\nconst buildInputMetadata = (\n part: Record<string, unknown>,\n filename?: string | undefined,\n) => {\n const metadata = {\n ...readAgUiNamespace(part.providerMetadata),\n ...(filename !== undefined && { filename }),\n };\n return Object.keys(metadata).length > 0 ? metadata : undefined;\n};\n\n// The inverse: `filename` lands on the part's own field, everything else the\n// item carried goes back into the namespace it came from, so a snapshot echo\n// resends what the host attached.\nconst readInputMetadata = (\n metadata: unknown,\n): {\n filename?: string | undefined;\n providerMetadata?: PartProviderMetadata | undefined;\n} => {\n if (!isObject(metadata)) return {};\n const { filename: _filename, ...rest } = metadata;\n return {\n filename: getString(metadata, \"filename\"),\n ...(Object.keys(rest).length > 0 && {\n providerMetadata: {\n [AG_UI_METADATA_NAMESPACE]: rest as PartProviderMetadata[string],\n },\n }),\n };\n};\n\nfunction parseJSONText(value: string): unknown {\n if (!value) return value;\n try {\n return JSON.parse(value);\n } catch {\n return value;\n }\n}\n\nfunction normalizeToolCall(part: ToolCallPart): {\n id: string;\n call: AgUiToolCall;\n} {\n const id = part.toolCallId ?? generateId();\n const argsText =\n typeof part.argsText === \"string\"\n ? part.argsText\n : JSON.stringify(part.args ?? {});\n\n return {\n id,\n call: {\n id,\n type: \"function\",\n function: {\n name: part.toolName ?? \"tool\",\n arguments: argsText,\n },\n },\n };\n}\n\nfunction extractText(content: unknown): string {\n if (typeof content === \"string\") return content;\n if (!Array.isArray(content)) return \"\";\n\n return content\n .filter(\n (part): part is { type: \"text\"; text: string } =>\n part?.type === \"text\" && typeof part?.text === \"string\",\n )\n .map((part) => part.text)\n .join(\"\\n\");\n}\n\ntype InputContentSource =\n | { type: \"data\"; value: string; mimeType: string }\n | { type: \"url\"; value: string; mimeType?: string };\n\ntype MediaInputType = \"image\" | \"audio\" | \"video\" | \"document\";\n\nfunction mediaTypeForMime(mimeType: string | undefined): MediaInputType {\n if (mimeType?.startsWith(\"image/\")) return \"image\";\n if (mimeType?.startsWith(\"audio/\")) return \"audio\";\n if (mimeType?.startsWith(\"video/\")) return \"video\";\n return \"document\";\n}\n\n// Build an AG-UI multimodal source from a data URL, raw base64 payload, or an\n// http(s) URL. A `url` source may omit the mime type; a `data` source always\n// resolves one (falling back to application/octet-stream). An explicit\n// `sourceType: \"url\"` on the part forces the url leg for non-http references.\nfunction buildInputSource(\n value: string,\n declaredMimeType: string | undefined,\n sourceType?: string,\n): InputContentSource {\n const source = resolveFilePartSource({\n data: value,\n mimeType: declaredMimeType ?? \"application/octet-stream\",\n sourceType,\n });\n if (source.kind === \"url\") {\n return declaredMimeType !== undefined\n ? { type: \"url\", value: source.url, mimeType: declaredMimeType }\n : { type: \"url\", value: source.url };\n }\n return {\n type: \"data\",\n value: source.data,\n mimeType: source.mimeType,\n };\n}\n\nfunction toInputContent(\n part: unknown,\n fallbackMimeType: string | undefined,\n): InputContent | null {\n if (!isObject(part)) return null;\n const type = getString(part, \"type\");\n\n if (type === \"text\") {\n const text = getString(part, \"text\");\n if (text === undefined) return null;\n return { type: \"text\", text };\n }\n\n if (type === \"image\") {\n const image = getString(part, \"image\");\n if (image === undefined) return null;\n const metadata = buildInputMetadata(part, getString(part, \"filename\"));\n return {\n type: \"image\",\n source: buildInputSource(image, fallbackMimeType),\n ...(metadata && { metadata }),\n };\n }\n\n if (type === \"file\") {\n const data = getString(part, \"data\");\n if (data === undefined) return null;\n const declaredMimeType = getString(part, \"mimeType\") || fallbackMimeType;\n const filename = getString(part, \"filename\");\n const source = buildInputSource(\n data,\n declaredMimeType,\n getString(part, \"sourceType\"),\n );\n const metadata = buildInputMetadata(part, filename);\n switch (mediaTypeForMime(source.mimeType)) {\n case \"image\":\n return { type: \"image\", source, ...(metadata && { metadata }) };\n case \"audio\":\n return { type: \"audio\", source, ...(metadata && { metadata }) };\n case \"video\":\n return { type: \"video\", source, ...(metadata && { metadata }) };\n default:\n return { type: \"document\", source, ...(metadata && { metadata }) };\n }\n }\n\n if (type === \"audio\") {\n const audio = part.audio;\n if (!isObject(audio)) return null;\n const data = getString(audio, \"data\");\n const format = getString(audio, \"format\");\n if (data === undefined || format === undefined) return null;\n return {\n type: \"audio\",\n source: buildInputSource(\n parseDataUrl(data)?.data ?? data,\n `audio/${format}`,\n ),\n };\n }\n\n return null;\n}\n\ntype SnapshotAttachment = NonNullable<\n CoreThreadMessageLike[\"attachments\"]\n>[number];\n\nconst mediaInputTypes = new Set([\"image\", \"audio\", \"video\", \"document\"]);\n\n// Inverse of buildInputSource.\nfunction inputSourceToString(\n value: unknown,\n): { value: string; mimeType?: string; isUrl?: boolean } | null {\n if (!isObject(value)) return null;\n const sourceValue = getString(value, \"value\");\n if (sourceValue === undefined) return null;\n const mimeType = getString(value, \"mimeType\");\n const type = getString(value, \"type\");\n if (type === \"url\") {\n return {\n value: sourceValue,\n isUrl: true,\n ...(mimeType !== undefined && { mimeType }),\n };\n }\n if (type === \"data\") {\n const resolvedMimeType = mimeType ?? \"application/octet-stream\";\n return {\n value: `data:${resolvedMimeType};base64,${sourceValue}`,\n mimeType: resolvedMimeType,\n };\n }\n return null;\n}\n\n// Mirrors @ag-ui/client's BackwardCompatibility_0_0_47 middleware.\nfunction upgradeBinaryInputPart(\n part: Record<string, unknown>,\n): Record<string, unknown> | null {\n const mimeType = getString(part, \"mimeType\");\n if (mimeType === undefined) return null;\n const data = getString(part, \"data\");\n const url = getString(part, \"url\");\n const source = data\n ? { type: \"data\", value: data, mimeType }\n : url\n ? { type: \"url\", value: url, mimeType }\n : null;\n if (!source) return null;\n const filename = getString(part, \"filename\");\n return {\n type: mediaTypeForMime(mimeType),\n source,\n ...(filename && { metadata: { filename } }),\n };\n}\n\nfunction toSnapshotAttachments(content: unknown): SnapshotAttachment[] {\n if (!Array.isArray(content)) return [];\n\n const attachments: SnapshotAttachment[] = [];\n for (const rawPart of content) {\n if (!isObject(rawPart)) continue;\n const part =\n getString(rawPart, \"type\") === \"binary\"\n ? upgradeBinaryInputPart(rawPart)\n : rawPart;\n if (!part) continue;\n const type = getString(part, \"type\");\n if (type === undefined || !mediaInputTypes.has(type)) continue;\n const source = inputSourceToString(part.source);\n if (!source) continue;\n\n const { filename, providerMetadata } = readInputMetadata(part.metadata);\n const id = attachments.length.toString();\n\n if (type === \"image\") {\n attachments.push({\n id,\n type: \"image\",\n name: filename ?? \"image\",\n ...(source.mimeType !== undefined && { contentType: source.mimeType }),\n status: { type: \"complete\" },\n content: [\n {\n type: \"image\",\n image: source.value,\n ...(filename !== undefined && { filename }),\n ...(providerMetadata && { providerMetadata }),\n },\n ],\n });\n continue;\n }\n\n const mimeType = source.mimeType ?? \"application/octet-stream\";\n attachments.push({\n id,\n type: type === \"document\" ? \"document\" : \"file\",\n name: filename ?? \"file\",\n contentType: mimeType,\n status: { type: \"complete\" },\n content: [\n {\n type: \"file\",\n data: source.value,\n mimeType,\n ...(source.isUrl && { sourceType: \"url\" as const }),\n ...(filename !== undefined && { filename }),\n ...(providerMetadata && { providerMetadata }),\n },\n ],\n });\n }\n return attachments;\n}\n\nfunction buildUserContent(message: ThreadMessageLike): string | InputContent[] {\n const contentParts = Array.isArray(message.content) ? message.content : [];\n\n const attachments = message.attachments ?? [];\n\n const converted: InputContent[] = [];\n\n // Promote string-form content to a leading text part so it survives when\n // non-text attachments are present (fromAgUiMessages emits string content).\n if (typeof message.content === \"string\" && message.content.length > 0) {\n converted.push({ type: \"text\", text: message.content });\n }\n\n for (const part of contentParts) {\n const input = toInputContent(part, undefined);\n if (input) converted.push(input);\n }\n for (const attachment of attachments) {\n if (!isObject(attachment)) continue;\n const attachmentContent = attachment.content;\n if (!Array.isArray(attachmentContent)) continue;\n const fallbackMime = getString(attachment, \"contentType\");\n for (const part of attachmentContent) {\n const input = toInputContent(part, fallbackMime);\n if (input) converted.push(input);\n }\n }\n\n const hasNonText = converted.some((part) => part.type !== \"text\");\n if (hasNonText) return converted;\n\n // All-text path: collapse to plain string. Join text parts collected from\n // both content and attachments so attachment-sourced text is not dropped.\n if (converted.length === 0) return extractText(message.content);\n return converted\n .filter(\n (part): part is { type: \"text\"; text: string } => part.type === \"text\",\n )\n .map((part) => part.text)\n .join(\"\\n\");\n}\n\nfunction toToolCallPart(value: unknown): ToolCallPart | null {\n if (!isObject(value)) return null;\n const rawFunction = isObject(value.function) ? value.function : null;\n const toolCallId = getString(value, \"toolCallId\") ?? getString(value, \"id\");\n const toolName =\n getString(value, \"toolName\") ??\n getString(value, \"name\") ??\n (rawFunction ? getString(rawFunction, \"name\") : undefined) ??\n \"tool\";\n const argsText =\n getString(value, \"argsText\") ??\n getString(value, \"arguments\") ??\n (rawFunction ? getString(rawFunction, \"arguments\") : undefined);\n\n const parsedArgs =\n typeof argsText === \"string\" ? parseJSONText(argsText) : undefined;\n const args =\n isObject(parsedArgs) && !Array.isArray(parsedArgs)\n ? (parsedArgs as ReadonlyJSONObject)\n : isObject(value.args) && !Array.isArray(value.args)\n ? (value.args as ReadonlyJSONObject)\n : undefined;\n\n const part: ToolCallPart = {\n type: \"tool-call\",\n ...(toolCallId !== undefined ? { toolCallId } : {}),\n toolName,\n argsText: argsText ?? JSON.stringify(args ?? {}),\n ...(args !== undefined ? { args } : {}),\n };\n\n if (value.type === \"tool-call\") {\n const result = value.result;\n const isError = value.isError;\n if (result !== undefined) part.result = result;\n if (typeof isError === \"boolean\") part.isError = isError;\n }\n\n return part;\n}\n\nfunction extractAssistantToolCalls(\n message: Record<string, unknown>,\n): ToolCallPart[] {\n const parts: ToolCallPart[] = [];\n const seenToolCallIds = new Set<string>();\n const pushPart = (part: ToolCallPart | null) => {\n if (!part) return;\n const id = part.toolCallId ?? generateId();\n if (seenToolCallIds.has(id)) return;\n seenToolCallIds.add(id);\n parts.push({\n ...part,\n toolCallId: id,\n });\n };\n\n const content = message.content;\n if (Array.isArray(content)) {\n for (const part of content) {\n if (isObject(part) && part.type === \"tool-call\") {\n pushPart(toToolCallPart(part));\n }\n }\n }\n\n const toolCalls = Array.isArray(message.toolCalls)\n ? message.toolCalls\n : Array.isArray(message.tool_calls)\n ? message.tool_calls\n : [];\n for (const call of toolCalls) {\n pushPart(toToolCallPart(call));\n }\n\n return parts;\n}\n\nfunction validateInterrupts(value: unknown): AgUiInterrupt[] | undefined {\n if (!Array.isArray(value)) return undefined;\n const valid = value.filter(\n (entry): entry is AgUiInterrupt =>\n isObject(entry) &&\n typeof entry.id === \"string\" &&\n typeof entry.reason === \"string\",\n );\n return valid.length > 0 ? valid : undefined;\n}\n\nfunction readPersistedInterrupts(\n metadata: unknown,\n): AgUiInterrupt[] | undefined {\n if (!isObject(metadata)) return undefined;\n const custom = metadata.custom;\n if (!isObject(custom)) return undefined;\n const namespaced = custom[AG_UI_METADATA_NAMESPACE];\n if (!isObject(namespaced)) return undefined;\n return validateInterrupts(namespaced.interrupts);\n}\n\nfunction readOpaqueReasoning(metadata: unknown): AgUiOpaqueReasoning[] {\n if (!isObject(metadata)) return [];\n const custom = metadata.custom;\n if (!isObject(custom)) return [];\n const namespaced = custom[AG_UI_METADATA_NAMESPACE];\n if (!isObject(namespaced)) return [];\n const entries = namespaced.opaqueReasoning;\n if (!Array.isArray(entries)) return [];\n return entries.flatMap((entry) => {\n if (!isObject(entry)) return [];\n const id = getString(entry, \"id\");\n const encryptedValue = getString(entry, \"encryptedValue\");\n if (!id?.trim() || !encryptedValue?.trim()) return [];\n return [\n { id, encryptedValue, ...(entry.after === true ? { after: true } : {}) },\n ];\n });\n}\n\nfunction withOpaqueReasoning(\n message: CoreThreadMessageLike,\n opaqueReasoning: AgUiOpaqueReasoning[],\n): CoreThreadMessageLike {\n const metadata = isObject(message.metadata) ? message.metadata : {};\n const custom = isObject(metadata.custom) ? metadata.custom : {};\n const namespaced = isObject(custom[AG_UI_METADATA_NAMESPACE])\n ? (custom[AG_UI_METADATA_NAMESPACE] as Record<string, unknown>)\n : {};\n return {\n ...message,\n metadata: {\n ...metadata,\n custom: {\n ...custom,\n [AG_UI_METADATA_NAMESPACE]: { ...namespaced, opaqueReasoning },\n },\n },\n } as CoreThreadMessageLike;\n}\n\nfunction toAssistantSnapshotMessage(\n rawMessage: Record<string, unknown>,\n): CoreThreadMessageLike {\n const text = extractText(rawMessage.content);\n const interrupts = readPersistedInterrupts(rawMessage.metadata);\n const restoredToolCalls = extractAssistantToolCalls(rawMessage);\n const approvals = projectAgUiToolApprovals(\n interrupts,\n new Set(\n restoredToolCalls\n .map((part) => part.toolCallId)\n .filter((id): id is string => !!id),\n ),\n );\n const toolCallParts = restoredToolCalls.map((part) => {\n const approval = part.toolCallId\n ? approvals.get(part.toolCallId)\n : undefined;\n return approval ? { ...part, approval } : part;\n });\n const assistantContent = [\n ...(text.length > 0 ? [{ type: \"text\" as const, text }] : []),\n ...toolCallParts,\n ];\n const messageName = getString(rawMessage, \"name\");\n return {\n id: getString(rawMessage, \"id\") ?? generateId(),\n role: \"assistant\",\n content: assistantContent.length > 0 ? assistantContent : \"\",\n ...(messageName !== undefined ? { name: messageName } : {}),\n ...(interrupts\n ? {\n metadata: {\n custom: {\n [AG_UI_METADATA_NAMESPACE]: {\n interrupts,\n } satisfies AgUiCustomMetadata,\n },\n },\n }\n : {}),\n };\n}\n\nfunction toUserOrSystemSnapshotMessage(\n role: \"user\" | \"system\" | \"developer\",\n rawMessage: Record<string, unknown>,\n): CoreThreadMessageLike {\n const messageName = getString(rawMessage, \"name\");\n const attachments =\n role === \"user\" ? toSnapshotAttachments(rawMessage.content) : [];\n return {\n id: getString(rawMessage, \"id\") ?? generateId(),\n // The internal message model has no developer role; it rides as a system\n // message with its wire role kept in metadata so the export restores it.\n role: role === \"developer\" ? \"system\" : role,\n content: extractText(rawMessage.content),\n ...(messageName !== undefined ? { name: messageName } : {}),\n ...(attachments.length > 0 ? { attachments } : {}),\n ...(role === \"developer\"\n ? {\n metadata: {\n custom: {\n [AG_UI_METADATA_NAMESPACE]: {\n role: \"developer\",\n } satisfies AgUiCustomMetadata,\n },\n },\n }\n : {}),\n };\n}\n\n// Rebuilds the a2ui:<surfaceId> \"present\" tool-call parts for one owning\n// assistant message from a bucket of rebuilt surface state, mirroring the\n// live RunAggregator.synthesizeA2uiToolCalls shape. Non-a2ui parts (text,\n// other tool calls) are preserved; existing a2ui parts are replaced wholesale\n// so create/update/delete within the bucket all converge on the rebuilt set.\nfunction attachA2uiSurfaces(\n message: CoreThreadMessageLike,\n state: A2uiState,\n): CoreThreadMessageLike {\n const a2uiParts: ToolCallPart[] = [];\n for (const [surfaceId, surface] of state) {\n const { spec } = convertSurfaceToUISpec(surface);\n if (!spec) continue;\n a2uiParts.push({\n type: \"tool-call\",\n toolCallId: `a2ui:${surfaceId}`,\n toolName: \"present\",\n args: spec as unknown as ReadonlyJSONObject,\n argsText: JSON.stringify(spec),\n result: {},\n });\n }\n\n const content = Array.isArray(message.content) ? message.content : [];\n const preserved = content.filter(\n (part) =>\n !(\n isObject(part) &&\n part.type === \"tool-call\" &&\n typeof part.toolCallId === \"string\" &&\n part.toolCallId.startsWith(\"a2ui:\")\n ),\n );\n return { ...message, content: [...preserved, ...a2uiParts] };\n}\n\nexport type FromAgUiMessagesOptions = {\n /**\n * Whether to convert `reasoning` messages into visible reasoning parts.\n * Matches the `showThinking` option of `useAgUiRuntime`. Defaults to `true`.\n */\n showThinking?: boolean;\n};\n\nexport function fromAgUiMessages(\n messages: readonly unknown[],\n options?: FromAgUiMessagesOptions,\n): CoreThreadMessageLike[] {\n const showThinking = options?.showThinking ?? true;\n const converted: CoreThreadMessageLike[] = [];\n const a2uiBuckets = new Map<string, A2uiState>();\n const a2uiBucketOwnerIndices = new Map<string, number>();\n // A zero-data-retention run carries its payload in encryptedValue with no\n // readable content, so the record has no part to become and rides on the\n // neighbouring message instead of being dropped. The anchor is the index the\n // next pushed message will occupy, which is where it sat on the wire.\n const opaqueReasoning: (AgUiOpaqueReasoning & { anchor: number })[] = [];\n\n for (const rawMessage of messages) {\n if (!isObject(rawMessage)) continue;\n const role = getString(rawMessage, \"role\");\n if (!role) continue;\n\n if (role === \"tool\") {\n const toolCallId = getToolCallId(rawMessage) ?? `tool-${generateId()}`;\n const toolMessageId = getString(rawMessage, \"id\");\n const modelContent = extractText(rawMessage.content);\n const mcpResult = parseMcpToolCallResult(rawMessage, modelContent);\n const mcpModelContent = mcpResult\n ? [{ type: \"text\" as const, text: modelContent }]\n : undefined;\n const result =\n mcpResult ??\n (rawMessage.result !== undefined\n ? rawMessage.result\n : typeof rawMessage.content === \"string\"\n ? parseJSONText(rawMessage.content)\n : rawMessage.content);\n const isError =\n typeof rawMessage.error === \"string\" ||\n rawMessage.isError === true ||\n rawMessage.status === \"error\"\n ? true\n : rawMessage.isError === false\n ? false\n : undefined;\n const mcpAppUri = readMcpAppResourceUri(mcpResult?._meta);\n const mcpApp =\n mcpAppUri !== undefined ? { resourceUri: mcpAppUri } : undefined;\n\n let updated = false;\n for (\n let messageIndex = converted.length - 1;\n messageIndex >= 0 && !updated;\n messageIndex--\n ) {\n const message = converted[messageIndex];\n if (\n !message ||\n message.role !== \"assistant\" ||\n !Array.isArray(message.content)\n )\n continue;\n\n for (\n let partIndex = message.content.length - 1;\n partIndex >= 0;\n partIndex--\n ) {\n const part = message.content[partIndex];\n if (!isObject(part) || part.type !== \"tool-call\") continue;\n if (getString(part, \"toolCallId\") !== toolCallId) continue;\n\n const updatedPart: ToolCallPart = {\n ...(part as ToolCallPart),\n result,\n ...(mcpModelContent ? { modelContent: mcpModelContent } : {}),\n ...(isError !== undefined ? { isError } : {}),\n ...(toolMessageId !== undefined\n ? { unstable_toolMessageId: toolMessageId }\n : {}),\n ...(mcpApp ? { mcp: { app: mcpApp } } : {}),\n };\n const updatedContent = message.content.map((contentPart, index) =>\n index === partIndex ? updatedPart : contentPart,\n );\n converted[messageIndex] = { ...message, content: updatedContent };\n updated = true;\n break;\n }\n }\n\n if (updated) {\n continue;\n }\n\n const id = toolMessageId ?? toolCallId;\n const toolName =\n getString(rawMessage, \"name\") ??\n getString(rawMessage, \"toolName\") ??\n \"tool\";\n converted.push({\n id: `${id}:assistant`,\n role: \"assistant\",\n content: [\n {\n type: \"tool-call\",\n toolCallId,\n toolName,\n args: {},\n argsText: \"{}\",\n result,\n ...(mcpModelContent ? { modelContent: mcpModelContent } : {}),\n ...(isError !== undefined ? { isError } : {}),\n ...(toolMessageId !== undefined\n ? { unstable_toolMessageId: toolMessageId }\n : {}),\n ...(mcpApp ? { mcp: { app: mcpApp } } : {}),\n },\n ],\n });\n continue;\n }\n\n if (role === \"activity\") {\n // Only a2ui-surface activity messages have an assistant-part equivalent\n // to rehydrate; other activity types still have no surface to repaint.\n const activityType = getString(rawMessage, \"activityType\");\n if (activityType !== A2UI_SURFACE_ACTIVITY_TYPE) continue;\n const activityContent = isObject(rawMessage.content)\n ? (rawMessage.content as Record<string, unknown>)\n : null;\n const operations = activityContent?.[\"a2ui_operations\"];\n if (!Array.isArray(operations)) continue;\n\n let ownerIndex = -1;\n for (let i = converted.length - 1; i >= 0; i--) {\n const candidate = converted[i];\n if (candidate && candidate.role === \"assistant\") {\n ownerIndex = i;\n break;\n }\n }\n if (ownerIndex === -1) continue;\n\n const owner = converted[ownerIndex]!;\n const bucketKey = getString(rawMessage, \"id\") ?? \"a2ui:anonymous\";\n const { state } = applyA2uiOperations(new Map(), operations);\n a2uiBuckets.delete(bucketKey);\n a2uiBucketOwnerIndices.delete(bucketKey);\n a2uiBuckets.set(bucketKey, state);\n a2uiBucketOwnerIndices.set(bucketKey, ownerIndex);\n\n const ownerState = new Map<string, A2uiSurfaceState>();\n for (const [candidateBucketKey, candidateState] of a2uiBuckets) {\n if (a2uiBucketOwnerIndices.get(candidateBucketKey) !== ownerIndex)\n continue;\n for (const [surfaceId, surface] of candidateState) {\n ownerState.set(surfaceId, surface);\n }\n }\n converted[ownerIndex] = attachA2uiSurfaces(owner, ownerState);\n continue;\n }\n\n if (role === \"assistant\") {\n converted.push(toAssistantSnapshotMessage(rawMessage));\n continue;\n }\n\n if (role === \"reasoning\") {\n const text = extractText(rawMessage.content);\n const encryptedValue = getString(rawMessage, \"encryptedValue\");\n if (text.trim().length === 0) {\n // showThinking hides reasoning; this record is never rendered anyway,\n // and dropping it would deny the provider the payload it needs to\n // accept the next run.\n const opaqueId = getString(rawMessage, \"id\");\n if (opaqueId?.trim() && encryptedValue?.trim()) {\n opaqueReasoning.push({\n id: opaqueId,\n encryptedValue,\n anchor: converted.length,\n });\n }\n continue;\n }\n // Gate visible reasoning on showThinking so a cold reload matches the\n // live run: the aggregator never stores reasoning parts when it is off.\n // A signature on a hidden record is still transport state, so it is kept\n // opaque rather than discarded with the text.\n if (!showThinking) {\n const hiddenId = getString(rawMessage, \"id\");\n if (hiddenId?.trim() && encryptedValue?.trim()) {\n opaqueReasoning.push({\n id: hiddenId,\n encryptedValue,\n anchor: converted.length,\n });\n }\n continue;\n }\n converted.push({\n id: getString(rawMessage, \"id\") ?? generateId(),\n role: \"assistant\",\n content: [\n {\n type: \"reasoning\",\n text,\n ...(encryptedValue !== undefined\n ? {\n providerMetadata: {\n [AG_UI_METADATA_NAMESPACE]: { encryptedValue },\n },\n }\n : {}),\n },\n ],\n });\n continue;\n }\n\n if (role === \"user\" || role === \"system\" || role === \"developer\") {\n converted.push(toUserOrSystemSnapshotMessage(role, rawMessage));\n }\n }\n\n for (const { anchor, ...entry } of opaqueReasoning) {\n // Nothing followed it on the wire, so it trails the last message instead.\n const trailing = anchor >= converted.length;\n const index = trailing ? converted.length - 1 : anchor;\n const target = converted[index];\n if (!target) continue;\n converted[index] = withOpaqueReasoning(target, [\n ...readOpaqueReasoning(target.metadata),\n ...(trailing ? [{ ...entry, after: true }] : [entry]),\n ]);\n }\n\n for (let i = 0; i < converted.length; i++) {\n const message = converted[i]!;\n if (message.role !== \"assistant\") continue;\n\n const hasInterrupt =\n readPersistedInterrupts(message.metadata) !== undefined;\n const hasPendingToolCall =\n Array.isArray(message.content) &&\n message.content.some(\n (part) =>\n isObject(part) &&\n part.type === \"tool-call\" &&\n part.result === undefined,\n );\n\n if (hasInterrupt || hasPendingToolCall) {\n converted[i] = {\n ...message,\n status: getAutoStatus(\n false,\n false,\n hasInterrupt,\n hasPendingToolCall,\n undefined,\n ),\n };\n }\n }\n\n return converted;\n}\n\nfunction convertAssistantMessage(\n message: NormalizedThreadMessageLike,\n converted: AgUiMessage[],\n): void {\n const content = extractText(message.content);\n const contentArray = Array.isArray(message.content) ? message.content : [];\n\n const toolCallParts = contentArray.filter(\n (part): part is ToolCallPart =>\n part?.type === \"tool-call\" &&\n !(\n typeof part.toolCallId === \"string\" &&\n part.toolCallId.startsWith(\"a2ui:\")\n ),\n );\n\n const toolCalls = toolCallParts.map((part) => ({\n ...normalizeToolCall(part),\n part,\n }));\n\n // An AG-UI assistant record has no reasoning field, so reasoning leaves as\n // the standalone record it arrived as, ahead of the assistant it belongs to.\n const shellIsDropped = content.length === 0 && toolCalls.length === 0;\n let reasoningIndex = 0;\n for (const part of contentArray) {\n if (!isObject(part) || part.type !== \"reasoning\") continue;\n const text = getString(part, \"text\") ?? \"\";\n if (text.trim().length === 0) continue;\n const { encryptedValue, reasoningId } = readAgUiReasoningMeta(\n part.providerMetadata,\n );\n converted.push({\n // The wire id is what a signature was issued against, so it wins over a\n // synthesized one whenever the run carried it.\n id: reasoningId?.trim()\n ? reasoningId\n : shellIsDropped && reasoningIndex === 0\n ? message.id\n : `${message.id}:reasoning-${reasoningIndex}`,\n role: \"reasoning\",\n content: text,\n ...(encryptedValue !== undefined ? { encryptedValue } : {}),\n });\n reasoningIndex++;\n }\n\n // Drop assistant messages with no text or tool calls (e.g. an imported\n // reasoning-only entry) so they are not re-sent as a blank assistant turn.\n if (shellIsDropped) {\n return;\n }\n\n // A subagent's tool calls live on nested assistant messages. Before\n // subagent attribution they flattened to root and went out with this\n // assistant record as their antecedent, so the resume payload restores\n // exactly that shape: the calls join this record's toolCalls and their\n // results follow as tool records — never a tool record without its call.\n // The nested assistant content itself is backend-owned state and is not\n // re-sent.\n const nestedToolCalls: {\n id: string;\n call: AgUiToolCall;\n part: ToolCallPart;\n }[] = [];\n for (const { part } of toolCalls) {\n collectNestedToolCalls(part, nestedToolCalls);\n }\n\n converted.push({\n id: message.id,\n role: \"assistant\",\n content,\n ...(message.name ? { name: message.name } : {}),\n ...(toolCalls.length + nestedToolCalls.length > 0\n ? {\n toolCalls: [...toolCalls, ...nestedToolCalls].map(\n (entry) => entry.call,\n ),\n }\n : {}),\n });\n\n for (const { id: toolCallId, part } of toolCalls) {\n emitToolResult(toolCallId, part, converted);\n }\n for (const { id: toolCallId, part } of nestedToolCalls) {\n // A result recorded while the call's approval gate is still open must not\n // reach the backend as if the gate had been decided.\n const gateOpen =\n part.approval != null &&\n part.approval.approved === undefined &&\n part.approval.resolution === undefined;\n if (gateOpen) continue;\n emitToolResult(toolCallId, part, converted);\n }\n}\n\nfunction collectNestedToolCalls(\n part: ToolCallPart,\n out: { id: string; call: AgUiToolCall; part: ToolCallPart }[],\n): void {\n for (const nested of part.messages ?? []) {\n if (!isObject(nested) || nested.role !== \"assistant\") continue;\n const nestedContent = Array.isArray(nested.content) ? nested.content : [];\n for (const nestedPart of nestedContent) {\n if (!isObject(nestedPart) || nestedPart.type !== \"tool-call\") continue;\n const nestedToolCall = nestedPart as ToolCallPart;\n if (\n typeof nestedToolCall.toolCallId !== \"string\" ||\n nestedToolCall.toolCallId.startsWith(\"a2ui:\")\n ) {\n continue;\n }\n out.push({ ...normalizeToolCall(nestedToolCall), part: nestedToolCall });\n collectNestedToolCalls(nestedToolCall, out);\n }\n }\n}\n\nfunction emitToolResult(\n toolCallId: string,\n part: ToolCallPart,\n converted: AgUiMessage[],\n): void {\n if (part.result === undefined) return;\n\n const resultContent =\n part.modelContent !== undefined\n ? extractText(part.modelContent)\n : typeof part.result === \"string\"\n ? part.result\n : JSON.stringify(part.result);\n\n converted.push({\n id: part.unstable_toolMessageId ?? `${toolCallId}:tool`,\n role: \"tool\",\n content: resultContent,\n toolCallId,\n ...(part.isError ? { error: resultContent } : {}),\n });\n}\n\nfunction convertToolMessage(\n message: NormalizedThreadMessageLike,\n converted: AgUiMessage[],\n): void {\n const content = extractText(message.content);\n const toolCallId = message.toolCallId ?? generateId();\n\n converted.push({\n id: message.id,\n role: \"tool\",\n content,\n toolCallId,\n ...(typeof message.error === \"string\" ? { error: message.error } : {}),\n });\n}\n\nexport function toAgUiMessages(\n messages: readonly ThreadMessageLike[],\n): AgUiMessage[] {\n const converted: AgUiMessage[] = [];\n\n for (const rawMessage of messages) {\n const message: NormalizedThreadMessageLike = {\n ...rawMessage,\n id: rawMessage.id ?? generateId(),\n };\n const opaqueReasoning = readOpaqueReasoning(message.metadata);\n const toOpaqueRecord = (entry: AgUiOpaqueReasoning): AgUiMessage => ({\n id: entry.id,\n role: \"reasoning\",\n content: \"\",\n encryptedValue: entry.encryptedValue,\n });\n for (const entry of opaqueReasoning) {\n if (entry.after !== true) converted.push(toOpaqueRecord(entry));\n }\n const flushTrailingOpaqueReasoning = () => {\n for (const entry of opaqueReasoning) {\n if (entry.after === true) converted.push(toOpaqueRecord(entry));\n }\n };\n\n if (message.role === \"assistant\") {\n convertAssistantMessage(message, converted);\n flushTrailingOpaqueReasoning();\n continue;\n }\n\n if (message.role === \"tool\") {\n convertToolMessage(message, converted);\n flushTrailingOpaqueReasoning();\n continue;\n }\n\n if (message.role === \"user\") {\n converted.push({\n id: message.id,\n role: \"user\",\n content: buildUserContent(message),\n ...(message.name ? { name: message.name } : {}),\n });\n flushTrailingOpaqueReasoning();\n continue;\n }\n\n if (message.role === \"system\" || message.role === \"developer\") {\n const custom = isObject(message.metadata)\n ? message.metadata.custom\n : undefined;\n const namespaced = isObject(custom)\n ? custom[AG_UI_METADATA_NAMESPACE]\n : undefined;\n const wireRole =\n message.role === \"system\" &&\n isObject(namespaced) &&\n namespaced.role === \"developer\"\n ? (\"developer\" as const)\n : message.role;\n converted.push({\n id: message.id,\n role: wireRole,\n content: extractText(message.content),\n ...(message.name ? { name: message.name } : {}),\n });\n flushTrailingOpaqueReasoning();\n continue;\n }\n\n if (message.role === \"reasoning\") {\n converted.push({\n id: message.id,\n role: \"reasoning\",\n content: extractText(message.content),\n });\n flushTrailingOpaqueReasoning();\n continue;\n }\n\n flushTrailingOpaqueReasoning();\n }\n\n return converted;\n}\n\ntype AgUiTool = NonNullable<RunAgentParameters[\"tools\"]>[number];\n\nexport function toAgUiTools(\n tools: Record<string, Tool> | undefined,\n): AgUiTool[] {\n if (!tools) return [];\n\n const toolsSchema = toToolsJSONSchema(tools);\n return Object.entries(toolsSchema).map(([name, tool]) => ({\n name,\n description: tool.description ?? \"\",\n parameters: tool.parameters,\n }));\n}\n"],"mappings":";;;;;;;;;AAwHA,MAAM,YAAY,UAChB,OAAO,UAAU,YAAY,UAAU;AAEzC,MAAM,aAAa,QAAiC,QAAgB;CAClE,MAAM,QAAQ,OAAO;CACrB,OAAO,OAAO,UAAU,WAAW,QAAQ,KAAA;AAC7C;AAEA,MAAM,iBAAiB,WACrB,UAAU,QAAQ,YAAY,KAAK,UAAU,QAAQ,cAAc;AAErE,MAAM,qBAAqB,qBAA8B;CACvD,IAAI,CAAC,SAAS,gBAAgB,GAAG,OAAO,KAAA;CACxC,MAAM,aAAa,iBAAiB;CACpC,OAAO,SAAS,UAAU,IAAI,aAAa,KAAA;AAC7C;AAEA,MAAM,yBAAyB,qBAA8B;CAC3D,MAAM,aAAa,kBAAkB,gBAAgB;CACrD,IAAI,CAAC,YAAY,OAAO,CAAC;CACzB,OAAO;EACL,gBAAgB,UAAU,YAAY,gBAAgB;EACtD,aAAa,UAAU,YAAY,aAAa;CAClD;AACF;AAKA,MAAM,sBACJ,MACA,aACG;CACH,MAAM,WAAW;EACf,GAAG,kBAAkB,KAAK,gBAAgB;EAC1C,GAAI,aAAa,KAAA,KAAa,EAAE,SAAS;CAC3C;CACA,OAAO,OAAO,KAAK,QAAQ,CAAC,CAAC,SAAS,IAAI,WAAW,KAAA;AACvD;AAKA,MAAM,qBACJ,aAIG;CACH,IAAI,CAAC,SAAS,QAAQ,GAAG,OAAO,CAAC;CACjC,MAAM,EAAE,UAAU,WAAW,GAAG,SAAS;CACzC,OAAO;EACL,UAAU,UAAU,UAAU,UAAU;EACxC,GAAI,OAAO,KAAK,IAAI,CAAC,CAAC,SAAS,KAAK,EAClC,kBAAkB,GAAA,SACY,KAC9B,EACF;CACF;AACF;AAEA,SAAS,cAAc,OAAwB;CAC7C,IAAI,CAAC,OAAO,OAAO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}
|
|
1
|
+
{"version":3,"file":"conversions.js","names":[],"sources":["../../../src/runtime/adapter/conversions.ts"],"sourcesContent":["\"use client\";\n\nimport type { InputContent, RunAgentParameters } from \"@ag-ui/client\";\nimport { generateId } from \"@assistant-ui/core\";\nimport type {\n ThreadMessageLike as CoreThreadMessageLike,\n PartProviderMetadata,\n ReasoningMessagePart,\n ThreadMessage,\n ToolCallMessagePartMcpMetadata,\n ToolModelContentPart,\n} from \"@assistant-ui/core\";\nimport {\n getAutoStatus,\n parseDataUrl,\n resolveFilePartSource,\n} from \"@assistant-ui/core/internal\";\nimport { type Tool, toToolsJSONSchema } from \"assistant-stream\";\nimport type { ReadonlyJSONObject } from \"assistant-stream/utils\";\nimport {\n AG_UI_METADATA_NAMESPACE,\n A2UI_SURFACE_ACTIVITY_TYPE,\n type AgUiCustomMetadata,\n type AgUiOpaqueReasoning,\n} from \"./run-aggregator\";\nimport {\n applyA2uiOperations,\n convertSurfaceToUISpec,\n type A2uiState,\n type A2uiSurfaceState,\n} from \"@assistant-ui/react-generative-ui/a2ui\";\nimport type { AgUiInterrupt } from \"../types\";\nimport { projectAgUiToolApprovals } from \"./tool-approval\";\nimport {\n parseMcpToolCallResult,\n readMcpAppResourceUri,\n} from \"../mcp-tool-result\";\n\nexport type { InputContent };\n\ntype AttachmentLike = {\n name?: string | undefined;\n contentType?: string | undefined;\n content?: readonly unknown[] | undefined;\n};\n\ntype ThreadMessageLike = {\n id?: string | undefined;\n role: string;\n content: unknown;\n metadata?: unknown;\n name?: string | undefined;\n toolCallId?: string | undefined;\n error?: string | undefined;\n attachments?: readonly AttachmentLike[] | undefined;\n};\n\ntype NormalizedThreadMessageLike = ThreadMessageLike & { id: string };\n\ntype AgUiToolCall = {\n id: string;\n type: \"function\";\n function: { name: string; arguments: string };\n};\n\nexport type AgUiMessage =\n | {\n id: string;\n role: \"user\";\n content: string | InputContent[];\n name?: string;\n }\n | {\n id: string;\n role: \"assistant\";\n content: string;\n name?: string;\n toolCalls?: AgUiToolCall[];\n }\n | {\n id: string;\n role: \"system\" | \"developer\";\n content: string;\n name?: string;\n }\n | {\n id: string;\n role: \"reasoning\";\n content: string;\n encryptedValue?: string;\n }\n | {\n id: string;\n role: \"tool\";\n content: string;\n toolCallId: string;\n error?: string;\n };\n\ntype ToolCallPart = {\n type: \"tool-call\";\n toolCallId?: string;\n toolName: string;\n argsText?: string;\n args?: ReadonlyJSONObject;\n result?: unknown;\n isError?: boolean;\n modelContent?: readonly ToolModelContentPart[];\n unstable_toolMessageId?: string;\n mcp?: ToolCallMessagePartMcpMetadata;\n messages?: readonly ThreadMessage[];\n approval?: CoreToolCallPartApproval;\n};\n\ntype CoreToolCallPartApproval = NonNullable<\n Extract<\n Exclude<CoreThreadMessageLike[\"content\"], string>[number],\n { type: \"tool-call\" }\n >[\"approval\"]\n>;\n\nconst isObject = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null;\n\nconst getString = (record: Record<string, unknown>, key: string) => {\n const value = record[key];\n return typeof value === \"string\" ? value : undefined;\n};\n\nconst getToolCallId = (record: Record<string, unknown>) =>\n getString(record, \"toolCallId\") ?? getString(record, \"tool_call_id\");\n\nconst readAgUiNamespace = (providerMetadata: unknown) => {\n if (!isObject(providerMetadata)) return undefined;\n const namespaced = providerMetadata[AG_UI_METADATA_NAMESPACE];\n return isObject(namespaced) ? namespaced : undefined;\n};\n\nconst readAgUiReasoningMeta = (providerMetadata: unknown) => {\n const namespaced = readAgUiNamespace(providerMetadata);\n if (!namespaced) return {};\n return {\n encryptedValue: getString(namespaced, \"encryptedValue\"),\n reasoningId: getString(namespaced, \"reasoningId\"),\n };\n};\n\n// AG-UI carries per-item extras in `metadata`; anything else on the item is\n// stripped by its schema. The part's own `filename` wins over a key of the\n// same name in the bag.\nconst buildInputMetadata = (\n part: Record<string, unknown>,\n filename?: string | undefined,\n) => {\n const metadata = {\n ...readAgUiNamespace(part.providerMetadata),\n ...(filename !== undefined && { filename }),\n };\n return Object.keys(metadata).length > 0 ? metadata : undefined;\n};\n\n// The inverse: `filename` lands on the part's own field, everything else the\n// item carried goes back into the namespace it came from, so a snapshot echo\n// resends what the host attached.\nconst readInputMetadata = (\n metadata: unknown,\n): {\n filename?: string | undefined;\n providerMetadata?: PartProviderMetadata | undefined;\n} => {\n if (!isObject(metadata)) return {};\n const { filename: _filename, ...rest } = metadata;\n return {\n filename: getString(metadata, \"filename\"),\n ...(Object.keys(rest).length > 0 && {\n providerMetadata: {\n [AG_UI_METADATA_NAMESPACE]: rest as PartProviderMetadata[string],\n },\n }),\n };\n};\n\nfunction parseJSONText(value: string): unknown {\n if (!value) return value;\n try {\n return JSON.parse(value);\n } catch {\n return value;\n }\n}\n\nfunction normalizeToolCall(part: ToolCallPart): {\n id: string;\n call: AgUiToolCall;\n} {\n const id = part.toolCallId ?? generateId();\n const argsText =\n typeof part.argsText === \"string\"\n ? part.argsText\n : JSON.stringify(part.args ?? {});\n\n return {\n id,\n call: {\n id,\n type: \"function\",\n function: {\n name: part.toolName ?? \"tool\",\n arguments: argsText,\n },\n },\n };\n}\n\nfunction extractText(content: unknown): string {\n if (typeof content === \"string\") return content;\n if (!Array.isArray(content)) return \"\";\n\n return content\n .filter(\n (part): part is { type: \"text\"; text: string } =>\n part?.type === \"text\" && typeof part?.text === \"string\",\n )\n .map((part) => part.text)\n .join(\"\\n\");\n}\n\ntype InputContentSource =\n | { type: \"data\"; value: string; mimeType: string }\n | { type: \"url\"; value: string; mimeType?: string };\n\ntype MediaInputType = \"image\" | \"audio\" | \"video\" | \"document\";\n\nfunction mediaTypeForMime(mimeType: string | undefined): MediaInputType {\n if (mimeType?.startsWith(\"image/\")) return \"image\";\n if (mimeType?.startsWith(\"audio/\")) return \"audio\";\n if (mimeType?.startsWith(\"video/\")) return \"video\";\n return \"document\";\n}\n\n// Build an AG-UI multimodal source from a data URL, raw base64 payload, or an\n// http(s) URL. A `url` source may omit the mime type; a `data` source always\n// resolves one (falling back to application/octet-stream). An explicit\n// `sourceType: \"url\"` on the part forces the url leg for non-http references.\nfunction buildInputSource(\n value: string,\n declaredMimeType: string | undefined,\n sourceType?: string,\n): InputContentSource {\n const source = resolveFilePartSource({\n data: value,\n mimeType: declaredMimeType ?? \"application/octet-stream\",\n sourceType,\n });\n if (source.kind === \"url\") {\n return declaredMimeType !== undefined\n ? { type: \"url\", value: source.url, mimeType: declaredMimeType }\n : { type: \"url\", value: source.url };\n }\n return {\n type: \"data\",\n value: source.data,\n mimeType: source.mimeType,\n };\n}\n\nfunction toInputContent(\n part: unknown,\n fallbackMimeType: string | undefined,\n): InputContent | null {\n if (!isObject(part)) return null;\n const type = getString(part, \"type\");\n\n if (type === \"text\") {\n const text = getString(part, \"text\");\n if (text === undefined) return null;\n return { type: \"text\", text };\n }\n\n if (type === \"image\") {\n const image = getString(part, \"image\");\n if (image === undefined) return null;\n const metadata = buildInputMetadata(part, getString(part, \"filename\"));\n return {\n type: \"image\",\n source: buildInputSource(image, fallbackMimeType),\n ...(metadata && { metadata }),\n };\n }\n\n if (type === \"file\") {\n const data = getString(part, \"data\");\n if (data === undefined) return null;\n const declaredMimeType = getString(part, \"mimeType\") || fallbackMimeType;\n const filename = getString(part, \"filename\");\n const source = buildInputSource(\n data,\n declaredMimeType,\n getString(part, \"sourceType\"),\n );\n const metadata = buildInputMetadata(part, filename);\n switch (mediaTypeForMime(source.mimeType)) {\n case \"image\":\n return { type: \"image\", source, ...(metadata && { metadata }) };\n case \"audio\":\n return { type: \"audio\", source, ...(metadata && { metadata }) };\n case \"video\":\n return { type: \"video\", source, ...(metadata && { metadata }) };\n default:\n return { type: \"document\", source, ...(metadata && { metadata }) };\n }\n }\n\n if (type === \"audio\") {\n const audio = part.audio;\n if (!isObject(audio)) return null;\n const data = getString(audio, \"data\");\n const format = getString(audio, \"format\");\n if (data === undefined || format === undefined) return null;\n return {\n type: \"audio\",\n source: buildInputSource(\n parseDataUrl(data)?.data ?? data,\n `audio/${format}`,\n ),\n };\n }\n\n return null;\n}\n\ntype SnapshotAttachment = NonNullable<\n CoreThreadMessageLike[\"attachments\"]\n>[number];\n\nconst mediaInputTypes = new Set([\"image\", \"audio\", \"video\", \"document\"]);\n\n// Inverse of buildInputSource.\nfunction inputSourceToString(\n value: unknown,\n): { value: string; mimeType?: string; isUrl?: boolean } | null {\n if (!isObject(value)) return null;\n const sourceValue = getString(value, \"value\");\n if (sourceValue === undefined) return null;\n const mimeType = getString(value, \"mimeType\");\n const type = getString(value, \"type\");\n if (type === \"url\") {\n return {\n value: sourceValue,\n isUrl: true,\n ...(mimeType !== undefined && { mimeType }),\n };\n }\n if (type === \"data\") {\n const resolvedMimeType = mimeType ?? \"application/octet-stream\";\n return {\n value: `data:${resolvedMimeType};base64,${sourceValue}`,\n mimeType: resolvedMimeType,\n };\n }\n return null;\n}\n\n// Mirrors @ag-ui/client's BackwardCompatibility_0_0_47 middleware.\nfunction upgradeBinaryInputPart(\n part: Record<string, unknown>,\n): Record<string, unknown> | null {\n const mimeType = getString(part, \"mimeType\");\n if (mimeType === undefined) return null;\n const data = getString(part, \"data\");\n const url = getString(part, \"url\");\n const source = data\n ? { type: \"data\", value: data, mimeType }\n : url\n ? { type: \"url\", value: url, mimeType }\n : null;\n if (!source) return null;\n const filename = getString(part, \"filename\");\n return {\n type: mediaTypeForMime(mimeType),\n source,\n ...(filename && { metadata: { filename } }),\n };\n}\n\nfunction toSnapshotAttachments(content: unknown): SnapshotAttachment[] {\n if (!Array.isArray(content)) return [];\n\n const attachments: SnapshotAttachment[] = [];\n for (const rawPart of content) {\n if (!isObject(rawPart)) continue;\n const part =\n getString(rawPart, \"type\") === \"binary\"\n ? upgradeBinaryInputPart(rawPart)\n : rawPart;\n if (!part) continue;\n const type = getString(part, \"type\");\n if (type === undefined || !mediaInputTypes.has(type)) continue;\n const source = inputSourceToString(part.source);\n if (!source) continue;\n\n const { filename, providerMetadata } = readInputMetadata(part.metadata);\n const id = attachments.length.toString();\n\n if (type === \"image\") {\n attachments.push({\n id,\n type: \"image\",\n name: filename ?? \"image\",\n ...(source.mimeType !== undefined && { contentType: source.mimeType }),\n status: { type: \"complete\" },\n content: [\n {\n type: \"image\",\n image: source.value,\n ...(filename !== undefined && { filename }),\n ...(providerMetadata && { providerMetadata }),\n },\n ],\n });\n continue;\n }\n\n const mimeType = source.mimeType ?? \"application/octet-stream\";\n attachments.push({\n id,\n type: type === \"document\" ? \"document\" : \"file\",\n name: filename ?? \"file\",\n contentType: mimeType,\n status: { type: \"complete\" },\n content: [\n {\n type: \"file\",\n data: source.value,\n mimeType,\n ...(source.isUrl && { sourceType: \"url\" as const }),\n ...(filename !== undefined && { filename }),\n ...(providerMetadata && { providerMetadata }),\n },\n ],\n });\n }\n return attachments;\n}\n\nfunction buildUserContent(message: ThreadMessageLike): string | InputContent[] {\n const contentParts = Array.isArray(message.content) ? message.content : [];\n\n const attachments = message.attachments ?? [];\n\n const converted: InputContent[] = [];\n\n // Promote string-form content to a leading text part so it survives when\n // non-text attachments are present (fromAgUiMessages emits string content).\n if (typeof message.content === \"string\" && message.content.length > 0) {\n converted.push({ type: \"text\", text: message.content });\n }\n\n for (const part of contentParts) {\n const input = toInputContent(part, undefined);\n if (input) converted.push(input);\n }\n for (const attachment of attachments) {\n if (!isObject(attachment)) continue;\n const attachmentContent = attachment.content;\n if (!Array.isArray(attachmentContent)) continue;\n const fallbackMime = getString(attachment, \"contentType\");\n for (const part of attachmentContent) {\n const input = toInputContent(part, fallbackMime);\n if (input) converted.push(input);\n }\n }\n\n const hasNonText = converted.some((part) => part.type !== \"text\");\n if (hasNonText) return converted;\n\n // All-text path: collapse to plain string. Join text parts collected from\n // both content and attachments so attachment-sourced text is not dropped.\n if (converted.length === 0) return extractText(message.content);\n return converted\n .filter(\n (part): part is { type: \"text\"; text: string } => part.type === \"text\",\n )\n .map((part) => part.text)\n .join(\"\\n\");\n}\n\nfunction toToolCallPart(value: unknown): ToolCallPart | null {\n if (!isObject(value)) return null;\n const rawFunction = isObject(value.function) ? value.function : null;\n const toolCallId = getString(value, \"toolCallId\") ?? getString(value, \"id\");\n const toolName =\n getString(value, \"toolName\") ??\n getString(value, \"name\") ??\n (rawFunction ? getString(rawFunction, \"name\") : undefined) ??\n \"tool\";\n const argsText =\n getString(value, \"argsText\") ??\n getString(value, \"arguments\") ??\n (rawFunction ? getString(rawFunction, \"arguments\") : undefined);\n\n const parsedArgs =\n typeof argsText === \"string\" ? parseJSONText(argsText) : undefined;\n const args =\n isObject(parsedArgs) && !Array.isArray(parsedArgs)\n ? (parsedArgs as ReadonlyJSONObject)\n : isObject(value.args) && !Array.isArray(value.args)\n ? (value.args as ReadonlyJSONObject)\n : undefined;\n\n const part: ToolCallPart = {\n type: \"tool-call\",\n ...(toolCallId !== undefined ? { toolCallId } : {}),\n toolName,\n argsText: argsText ?? JSON.stringify(args ?? {}),\n ...(args !== undefined ? { args } : {}),\n };\n\n if (value.type === \"tool-call\") {\n const result = value.result;\n const isError = value.isError;\n if (result !== undefined) part.result = result;\n if (typeof isError === \"boolean\") part.isError = isError;\n }\n\n return part;\n}\n\nfunction extractAssistantToolCalls(\n message: Record<string, unknown>,\n): ToolCallPart[] {\n const parts: ToolCallPart[] = [];\n const seenToolCallIds = new Set<string>();\n const pushPart = (part: ToolCallPart | null) => {\n if (!part) return;\n const id = part.toolCallId ?? generateId();\n if (seenToolCallIds.has(id)) return;\n seenToolCallIds.add(id);\n parts.push({\n ...part,\n toolCallId: id,\n });\n };\n\n const content = message.content;\n if (Array.isArray(content)) {\n for (const part of content) {\n if (isObject(part) && part.type === \"tool-call\") {\n pushPart(toToolCallPart(part));\n }\n }\n }\n\n const toolCalls = Array.isArray(message.toolCalls)\n ? message.toolCalls\n : Array.isArray(message.tool_calls)\n ? message.tool_calls\n : [];\n for (const call of toolCalls) {\n pushPart(toToolCallPart(call));\n }\n\n return parts;\n}\n\nfunction validateInterrupts(value: unknown): AgUiInterrupt[] | undefined {\n if (!Array.isArray(value)) return undefined;\n const valid = value.filter(\n (entry): entry is AgUiInterrupt =>\n isObject(entry) &&\n typeof entry.id === \"string\" &&\n typeof entry.reason === \"string\",\n );\n return valid.length > 0 ? valid : undefined;\n}\n\nfunction readPersistedInterrupts(\n metadata: unknown,\n): AgUiInterrupt[] | undefined {\n if (!isObject(metadata)) return undefined;\n const custom = metadata.custom;\n if (!isObject(custom)) return undefined;\n const namespaced = custom[AG_UI_METADATA_NAMESPACE];\n if (!isObject(namespaced)) return undefined;\n return validateInterrupts(namespaced.interrupts);\n}\n\nfunction readOpaqueReasoning(metadata: unknown): AgUiOpaqueReasoning[] {\n if (!isObject(metadata)) return [];\n const custom = metadata.custom;\n if (!isObject(custom)) return [];\n const namespaced = custom[AG_UI_METADATA_NAMESPACE];\n if (!isObject(namespaced)) return [];\n const entries = namespaced.opaqueReasoning;\n if (!Array.isArray(entries)) return [];\n return entries.flatMap((entry) => {\n if (!isObject(entry)) return [];\n const id = getString(entry, \"id\");\n const encryptedValue = getString(entry, \"encryptedValue\");\n if (!id?.trim() || !encryptedValue?.trim()) return [];\n return [\n { id, encryptedValue, ...(entry.after === true ? { after: true } : {}) },\n ];\n });\n}\n\nfunction withOpaqueReasoning(\n message: CoreThreadMessageLike,\n opaqueReasoning: AgUiOpaqueReasoning[],\n): CoreThreadMessageLike {\n const metadata = isObject(message.metadata) ? message.metadata : {};\n const custom = isObject(metadata.custom) ? metadata.custom : {};\n const namespaced = isObject(custom[AG_UI_METADATA_NAMESPACE])\n ? (custom[AG_UI_METADATA_NAMESPACE] as Record<string, unknown>)\n : {};\n return {\n ...message,\n metadata: {\n ...metadata,\n custom: {\n ...custom,\n [AG_UI_METADATA_NAMESPACE]: { ...namespaced, opaqueReasoning },\n },\n },\n } as CoreThreadMessageLike;\n}\n\nfunction toAssistantSnapshotMessage(\n rawMessage: Record<string, unknown>,\n): CoreThreadMessageLike {\n const text = extractText(rawMessage.content);\n const interrupts = readPersistedInterrupts(rawMessage.metadata);\n const restoredToolCalls = extractAssistantToolCalls(rawMessage);\n const approvals = projectAgUiToolApprovals(\n interrupts,\n new Set(\n restoredToolCalls\n .map((part) => part.toolCallId)\n .filter((id): id is string => !!id),\n ),\n );\n const toolCallParts = restoredToolCalls.map((part) => {\n const approval = part.toolCallId\n ? approvals.get(part.toolCallId)\n : undefined;\n return approval ? { ...part, approval } : part;\n });\n const assistantContent = [\n ...(text.length > 0 ? [{ type: \"text\" as const, text }] : []),\n ...toolCallParts,\n ];\n const messageName = getString(rawMessage, \"name\");\n return {\n id: getString(rawMessage, \"id\") ?? generateId(),\n role: \"assistant\",\n content: assistantContent.length > 0 ? assistantContent : \"\",\n ...(messageName !== undefined ? { name: messageName } : {}),\n ...(interrupts\n ? {\n metadata: {\n custom: {\n [AG_UI_METADATA_NAMESPACE]: {\n interrupts,\n } satisfies AgUiCustomMetadata,\n },\n },\n }\n : {}),\n };\n}\n\nfunction toUserOrSystemSnapshotMessage(\n role: \"user\" | \"system\" | \"developer\",\n rawMessage: Record<string, unknown>,\n): CoreThreadMessageLike {\n const messageName = getString(rawMessage, \"name\");\n const attachments =\n role === \"user\" ? toSnapshotAttachments(rawMessage.content) : [];\n return {\n id: getString(rawMessage, \"id\") ?? generateId(),\n // The internal message model has no developer role; it rides as a system\n // message with its wire role kept in metadata so the export restores it.\n role: role === \"developer\" ? \"system\" : role,\n content: extractText(rawMessage.content),\n ...(messageName !== undefined ? { name: messageName } : {}),\n ...(attachments.length > 0 ? { attachments } : {}),\n ...(role === \"developer\"\n ? {\n metadata: {\n custom: {\n [AG_UI_METADATA_NAMESPACE]: {\n role: \"developer\",\n } satisfies AgUiCustomMetadata,\n },\n },\n }\n : {}),\n };\n}\n\n// Rebuilds the a2ui:<surfaceId> \"present\" tool-call parts for one owning\n// assistant message from a bucket of rebuilt surface state, mirroring the\n// live RunAggregator.synthesizeA2uiToolCalls shape. Non-a2ui parts (text,\n// other tool calls) are preserved; existing a2ui parts are replaced wholesale\n// so create/update/delete within the bucket all converge on the rebuilt set.\nfunction attachA2uiSurfaces(\n message: CoreThreadMessageLike,\n state: A2uiState,\n): CoreThreadMessageLike {\n const a2uiParts: ToolCallPart[] = [];\n for (const [surfaceId, surface] of state) {\n const { spec } = convertSurfaceToUISpec(surface);\n if (!spec) continue;\n a2uiParts.push({\n type: \"tool-call\",\n toolCallId: `a2ui:${surfaceId}`,\n toolName: \"present\",\n args: spec as unknown as ReadonlyJSONObject,\n argsText: JSON.stringify(spec),\n result: {},\n });\n }\n\n const content = Array.isArray(message.content) ? message.content : [];\n const preserved = content.filter(\n (part) =>\n !(\n isObject(part) &&\n part.type === \"tool-call\" &&\n typeof part.toolCallId === \"string\" &&\n part.toolCallId.startsWith(\"a2ui:\")\n ),\n );\n return { ...message, content: [...preserved, ...a2uiParts] };\n}\n\n// A tool call that arrives without a `parentMessageId` has no record to join, so\n// the client opens one keyed by the call id. An assistant record whose own id is\n// a call it carries is that container: an id the client invented for the call\n// rather than a boundary an agent drew. The prose the run answers with lands in\n// a record of its own, and nothing on the wire binds the two to the run that\n// produced them.\nfunction isSyntheticToolCallContainer(message: CoreThreadMessageLike): boolean {\n if (message.role !== \"assistant\" || !Array.isArray(message.content))\n return false;\n let carriesOwnId = false;\n for (const part of message.content) {\n if (!isObject(part)) continue;\n // The container is opened empty, so text on the record means an agent\n // addressed it and the id is one it chose.\n if (part.type === \"text\") return false;\n if (\n part.type === \"tool-call\" &&\n getString(part, \"toolCallId\") === message.id\n ) {\n carriesOwnId = true;\n }\n }\n return carriesOwnId;\n}\n\nfunction carriesText(message: CoreThreadMessageLike): boolean {\n return (\n Array.isArray(message.content) &&\n message.content.some((part) => isObject(part) && part.type === \"text\")\n );\n}\n\n// What the run put after the container folds onto it: another container for a\n// parallel call, or the parts of the answer. A record carrying a tool call an\n// agent addressed is a boundary of its own and keeps its message.\nfunction foldsOntoToolCallContainer(message: CoreThreadMessageLike): boolean {\n if (message.role !== \"assistant\" || !Array.isArray(message.content))\n return false;\n if (message.content.length === 0) return false;\n return (\n isSyntheticToolCallContainer(message) ||\n !message.content.some((part) => isObject(part) && part.type === \"tool-call\")\n );\n}\n\nfunction readCustomMetadata(metadata: unknown): Record<string, unknown> {\n if (!isObject(metadata) || !isObject(metadata.custom)) return {};\n return metadata.custom;\n}\n\nfunction readNamespacedMetadata(metadata: unknown): Record<string, unknown> {\n const namespaced = readCustomMetadata(metadata)[AG_UI_METADATA_NAMESPACE];\n return isObject(namespaced) ? namespaced : {};\n}\n\nfunction foldOntoToolCallContainer(\n container: CoreThreadMessageLike,\n message: CoreThreadMessageLike,\n): CoreThreadMessageLike {\n const interrupts = [\n ...(readPersistedInterrupts(container.metadata) ?? []),\n ...(readPersistedInterrupts(message.metadata) ?? []),\n ];\n // An entry that rode the folded record sat ahead of content that now follows\n // the container's calls, so it is replayed after the merged record and its\n // tool results rather than ahead of a message that no longer starts there.\n const opaqueReasoning = [\n ...readOpaqueReasoning(container.metadata),\n ...readOpaqueReasoning(message.metadata).map((entry) => ({\n ...entry,\n after: true,\n })),\n ];\n const namespaced = {\n ...readNamespacedMetadata(container.metadata),\n ...readNamespacedMetadata(message.metadata),\n ...(interrupts.length > 0 ? { interrupts } : {}),\n ...(opaqueReasoning.length > 0 ? { opaqueReasoning } : {}),\n } satisfies AgUiCustomMetadata & Record<string, unknown>;\n const custom = {\n ...readCustomMetadata(container.metadata),\n ...readCustomMetadata(message.metadata),\n ...(Object.keys(namespaced).length > 0\n ? { [AG_UI_METADATA_NAMESPACE]: namespaced }\n : {}),\n };\n const metadata = {\n ...(isObject(container.metadata) ? container.metadata : {}),\n ...(isObject(message.metadata) ? message.metadata : {}),\n ...(Object.keys(custom).length > 0 ? { custom } : {}),\n };\n return {\n ...container,\n ...message,\n // The container's id names a call rather than the turn, so the record the\n // agent addressed its prose to wins: that is the id the next run has to\n // carry for the agent to recognize the message it wrote.\n id: carriesText(message) ? message.id : container.id,\n content: [\n ...(Array.isArray(container.content) ? container.content : []),\n ...(Array.isArray(message.content) ? message.content : []),\n ],\n ...(Object.keys(metadata).length > 0 ? { metadata } : {}),\n } as CoreThreadMessageLike;\n}\n\nexport type FromAgUiMessagesOptions = {\n /**\n * Whether to convert `reasoning` messages into visible reasoning parts.\n * Matches the `showThinking` option of `useAgUiRuntime`. Defaults to `true`.\n */\n showThinking?: boolean;\n};\n\nexport function fromAgUiMessages(\n messages: readonly unknown[],\n options?: FromAgUiMessagesOptions,\n): CoreThreadMessageLike[] {\n const showThinking = options?.showThinking ?? true;\n const converted: CoreThreadMessageLike[] = [];\n const a2uiBuckets = new Map<string, A2uiState>();\n const a2uiBucketOwnerIndices = new Map<string, number>();\n // A zero-data-retention run carries its payload in encryptedValue with no\n // readable content, so the record has no part to become and rides on the\n // neighbouring message instead of being dropped. The anchor is the index the\n // next pushed message will occupy, which is where it sat on the wire.\n const opaqueReasoning: (AgUiOpaqueReasoning & { anchor: number })[] = [];\n // A reasoning record belongs to the assistant record that follows it, which is\n // the binding the export writes and the one the reference integrations read\n // back. Holding it until that assistant arrives rebuilds the pair as the\n // single message the live run produced.\n const pendingReasoning: {\n id: string | undefined;\n part: ReasoningMessagePart;\n }[] = [];\n\n const flushPendingReasoning = () => {\n for (const { id, part } of pendingReasoning) {\n converted.push({\n id: id ?? generateId(),\n role: \"assistant\",\n content: [part],\n });\n }\n pendingReasoning.length = 0;\n };\n\n const withPendingReasoning = (\n message: CoreThreadMessageLike,\n ): CoreThreadMessageLike => {\n if (pendingReasoning.length === 0) return message;\n const parts = pendingReasoning.map(({ part }) => part);\n pendingReasoning.length = 0;\n return {\n ...message,\n content: [\n ...parts,\n ...(Array.isArray(message.content) ? message.content : []),\n ],\n };\n };\n\n for (const rawMessage of messages) {\n if (!isObject(rawMessage)) continue;\n const role = getString(rawMessage, \"role\");\n if (!role) continue;\n\n if (role === \"tool\") {\n flushPendingReasoning();\n const toolCallId = getToolCallId(rawMessage) ?? `tool-${generateId()}`;\n const toolMessageId = getString(rawMessage, \"id\");\n const modelContent = extractText(rawMessage.content);\n const mcpResult = parseMcpToolCallResult(rawMessage, modelContent);\n const mcpModelContent = mcpResult\n ? [{ type: \"text\" as const, text: modelContent }]\n : undefined;\n const result =\n mcpResult ??\n (rawMessage.result !== undefined\n ? rawMessage.result\n : typeof rawMessage.content === \"string\"\n ? parseJSONText(rawMessage.content)\n : rawMessage.content);\n const isError =\n typeof rawMessage.error === \"string\" ||\n rawMessage.isError === true ||\n rawMessage.status === \"error\"\n ? true\n : rawMessage.isError === false\n ? false\n : undefined;\n const mcpAppUri = readMcpAppResourceUri(mcpResult?._meta);\n const mcpApp =\n mcpAppUri !== undefined ? { resourceUri: mcpAppUri } : undefined;\n\n let updated = false;\n for (\n let messageIndex = converted.length - 1;\n messageIndex >= 0 && !updated;\n messageIndex--\n ) {\n const message = converted[messageIndex];\n if (\n !message ||\n message.role !== \"assistant\" ||\n !Array.isArray(message.content)\n )\n continue;\n\n for (\n let partIndex = message.content.length - 1;\n partIndex >= 0;\n partIndex--\n ) {\n const part = message.content[partIndex];\n if (!isObject(part) || part.type !== \"tool-call\") continue;\n if (getString(part, \"toolCallId\") !== toolCallId) continue;\n\n const updatedPart: ToolCallPart = {\n ...(part as ToolCallPart),\n result,\n ...(mcpModelContent ? { modelContent: mcpModelContent } : {}),\n ...(isError !== undefined ? { isError } : {}),\n ...(toolMessageId !== undefined\n ? { unstable_toolMessageId: toolMessageId }\n : {}),\n ...(mcpApp ? { mcp: { app: mcpApp } } : {}),\n };\n const updatedContent = message.content.map((contentPart, index) =>\n index === partIndex ? updatedPart : contentPart,\n );\n converted[messageIndex] = { ...message, content: updatedContent };\n updated = true;\n break;\n }\n }\n\n if (updated) {\n continue;\n }\n\n const id = toolMessageId ?? toolCallId;\n const toolName =\n getString(rawMessage, \"name\") ??\n getString(rawMessage, \"toolName\") ??\n \"tool\";\n converted.push({\n id: `${id}:assistant`,\n role: \"assistant\",\n content: [\n {\n type: \"tool-call\",\n toolCallId,\n toolName,\n args: {},\n argsText: \"{}\",\n result,\n ...(mcpModelContent ? { modelContent: mcpModelContent } : {}),\n ...(isError !== undefined ? { isError } : {}),\n ...(toolMessageId !== undefined\n ? { unstable_toolMessageId: toolMessageId }\n : {}),\n ...(mcpApp ? { mcp: { app: mcpApp } } : {}),\n },\n ],\n });\n continue;\n }\n\n if (role === \"activity\") {\n // Only a2ui-surface activity messages have an assistant-part equivalent\n // to rehydrate; other activity types still have no surface to repaint.\n const activityType = getString(rawMessage, \"activityType\");\n if (activityType !== A2UI_SURFACE_ACTIVITY_TYPE) continue;\n const activityContent = isObject(rawMessage.content)\n ? (rawMessage.content as Record<string, unknown>)\n : null;\n const operations = activityContent?.[\"a2ui_operations\"];\n if (!Array.isArray(operations)) continue;\n\n // A surface belongs to the turn that painted it, and held reasoning is a\n // nearer antecedent than the previous turn's assistant record, so it is\n // released here rather than folded past this record.\n flushPendingReasoning();\n\n let ownerIndex = -1;\n for (let i = converted.length - 1; i >= 0; i--) {\n const candidate = converted[i];\n if (candidate && candidate.role === \"assistant\") {\n ownerIndex = i;\n break;\n }\n }\n if (ownerIndex === -1) continue;\n\n const owner = converted[ownerIndex]!;\n const bucketKey = getString(rawMessage, \"id\") ?? \"a2ui:anonymous\";\n const { state } = applyA2uiOperations(new Map(), operations);\n a2uiBuckets.delete(bucketKey);\n a2uiBucketOwnerIndices.delete(bucketKey);\n a2uiBuckets.set(bucketKey, state);\n a2uiBucketOwnerIndices.set(bucketKey, ownerIndex);\n\n const ownerState = new Map<string, A2uiSurfaceState>();\n for (const [candidateBucketKey, candidateState] of a2uiBuckets) {\n if (a2uiBucketOwnerIndices.get(candidateBucketKey) !== ownerIndex)\n continue;\n for (const [surfaceId, surface] of candidateState) {\n ownerState.set(surfaceId, surface);\n }\n }\n converted[ownerIndex] = attachA2uiSurfaces(owner, ownerState);\n continue;\n }\n\n if (role === \"assistant\") {\n converted.push(\n withPendingReasoning(toAssistantSnapshotMessage(rawMessage)),\n );\n continue;\n }\n\n if (role === \"reasoning\") {\n const text = extractText(rawMessage.content);\n const encryptedValue = getString(rawMessage, \"encryptedValue\");\n if (text.trim().length === 0) {\n // showThinking hides reasoning; this record is never rendered anyway,\n // and dropping it would deny the provider the payload it needs to\n // accept the next run.\n const opaqueId = getString(rawMessage, \"id\");\n if (opaqueId?.trim() && encryptedValue?.trim()) {\n // The anchor counts materialized messages, so anything still held\n // takes its own slot rather than folding past this record.\n flushPendingReasoning();\n opaqueReasoning.push({\n id: opaqueId,\n encryptedValue,\n anchor: converted.length,\n });\n }\n continue;\n }\n // Gate visible reasoning on showThinking so a cold reload matches the\n // live run: the aggregator never stores reasoning parts when it is off.\n // A signature on a hidden record is still transport state, so it is kept\n // opaque rather than discarded with the text.\n if (!showThinking) {\n const hiddenId = getString(rawMessage, \"id\");\n if (hiddenId?.trim() && encryptedValue?.trim()) {\n opaqueReasoning.push({\n id: hiddenId,\n encryptedValue,\n anchor: converted.length,\n });\n }\n continue;\n }\n const rawReasoningId = getString(rawMessage, \"id\");\n // A blank id still wins over a synthesized one on export, which would put\n // an unaddressable record on the wire.\n const reasoningId = rawReasoningId?.trim() ? rawReasoningId : undefined;\n // The fold costs the record its own message id, so it rides the part\n // instead: the export re-emits each block under the id it arrived with.\n const meta = {\n ...(reasoningId !== undefined ? { reasoningId } : {}),\n ...(encryptedValue !== undefined ? { encryptedValue } : {}),\n };\n pendingReasoning.push({\n id: reasoningId,\n part: {\n type: \"reasoning\",\n text,\n ...(Object.keys(meta).length > 0\n ? { providerMetadata: { [AG_UI_METADATA_NAMESPACE]: meta } }\n : {}),\n },\n });\n continue;\n }\n\n if (role === \"user\" || role === \"system\" || role === \"developer\") {\n flushPendingReasoning();\n converted.push(toUserOrSystemSnapshotMessage(role, rawMessage));\n }\n }\n\n flushPendingReasoning();\n\n for (const { anchor, ...entry } of opaqueReasoning) {\n // Nothing followed it on the wire, so it trails the last message instead.\n const trailing = anchor >= converted.length;\n const index = trailing ? converted.length - 1 : anchor;\n const target = converted[index];\n if (!target) continue;\n converted[index] = withOpaqueReasoning(target, [\n ...readOpaqueReasoning(target.metadata),\n ...(trailing ? [{ ...entry, after: true }] : [entry]),\n ]);\n }\n\n // A turn that called a tool before answering sits on the wire as a container\n // and the records that follow it, which the live run renders as one message.\n const folded: CoreThreadMessageLike[] = [];\n for (const message of converted) {\n const previous = folded[folded.length - 1];\n if (\n previous !== undefined &&\n isSyntheticToolCallContainer(previous) &&\n foldsOntoToolCallContainer(message)\n ) {\n folded[folded.length - 1] = foldOntoToolCallContainer(previous, message);\n continue;\n }\n folded.push(message);\n }\n\n for (let i = 0; i < folded.length; i++) {\n const message = folded[i]!;\n if (message.role !== \"assistant\") continue;\n\n const hasInterrupt =\n readPersistedInterrupts(message.metadata) !== undefined;\n const hasPendingToolCall =\n Array.isArray(message.content) &&\n message.content.some(\n (part) =>\n isObject(part) &&\n part.type === \"tool-call\" &&\n part.result === undefined,\n );\n\n if (hasInterrupt || hasPendingToolCall) {\n folded[i] = {\n ...message,\n status: getAutoStatus(\n false,\n false,\n hasInterrupt,\n hasPendingToolCall,\n undefined,\n ),\n };\n }\n }\n\n return folded;\n}\n\nfunction convertAssistantMessage(\n message: NormalizedThreadMessageLike,\n converted: AgUiMessage[],\n): void {\n const content = extractText(message.content);\n const contentArray = Array.isArray(message.content) ? message.content : [];\n\n const toolCallParts = contentArray.filter(\n (part): part is ToolCallPart =>\n part?.type === \"tool-call\" &&\n !(\n typeof part.toolCallId === \"string\" &&\n part.toolCallId.startsWith(\"a2ui:\")\n ),\n );\n\n const toolCalls = toolCallParts.map((part) => ({\n ...normalizeToolCall(part),\n part,\n }));\n\n // An AG-UI assistant record has no reasoning field, so reasoning leaves as\n // the standalone record it arrived as, ahead of the assistant it belongs to.\n const shellIsDropped = content.length === 0 && toolCalls.length === 0;\n let reasoningIndex = 0;\n for (const part of contentArray) {\n if (!isObject(part) || part.type !== \"reasoning\") continue;\n const text = getString(part, \"text\") ?? \"\";\n if (text.trim().length === 0) continue;\n const { encryptedValue, reasoningId } = readAgUiReasoningMeta(\n part.providerMetadata,\n );\n converted.push({\n // The wire id is what a signature was issued against, so it wins over a\n // synthesized one whenever the run carried it.\n id: reasoningId?.trim()\n ? reasoningId\n : shellIsDropped && reasoningIndex === 0\n ? message.id\n : `${message.id}:reasoning-${reasoningIndex}`,\n role: \"reasoning\",\n content: text,\n ...(encryptedValue !== undefined ? { encryptedValue } : {}),\n });\n reasoningIndex++;\n }\n\n // Drop assistant messages with no text or tool calls (e.g. an imported\n // reasoning-only entry) so they are not re-sent as a blank assistant turn.\n if (shellIsDropped) {\n return;\n }\n\n // A subagent's tool calls live on nested assistant messages. Before\n // subagent attribution they flattened to root and went out with this\n // assistant record as their antecedent, so the resume payload restores\n // exactly that shape: the calls join this record's toolCalls and their\n // results follow as tool records — never a tool record without its call.\n // The nested assistant content itself is backend-owned state and is not\n // re-sent.\n const nestedToolCalls: {\n id: string;\n call: AgUiToolCall;\n part: ToolCallPart;\n }[] = [];\n for (const { part } of toolCalls) {\n collectNestedToolCalls(part, nestedToolCalls);\n }\n\n converted.push({\n id: message.id,\n role: \"assistant\",\n content,\n ...(message.name ? { name: message.name } : {}),\n ...(toolCalls.length + nestedToolCalls.length > 0\n ? {\n toolCalls: [...toolCalls, ...nestedToolCalls].map(\n (entry) => entry.call,\n ),\n }\n : {}),\n });\n\n for (const { id: toolCallId, part } of toolCalls) {\n emitToolResult(toolCallId, part, converted);\n }\n for (const { id: toolCallId, part } of nestedToolCalls) {\n // A result recorded while the call's approval gate is still open must not\n // reach the backend as if the gate had been decided.\n const gateOpen =\n part.approval != null &&\n part.approval.approved === undefined &&\n part.approval.resolution === undefined;\n if (gateOpen) continue;\n emitToolResult(toolCallId, part, converted);\n }\n}\n\nfunction collectNestedToolCalls(\n part: ToolCallPart,\n out: { id: string; call: AgUiToolCall; part: ToolCallPart }[],\n): void {\n for (const nested of part.messages ?? []) {\n if (!isObject(nested) || nested.role !== \"assistant\") continue;\n const nestedContent = Array.isArray(nested.content) ? nested.content : [];\n for (const nestedPart of nestedContent) {\n if (!isObject(nestedPart) || nestedPart.type !== \"tool-call\") continue;\n const nestedToolCall = nestedPart as ToolCallPart;\n if (\n typeof nestedToolCall.toolCallId !== \"string\" ||\n nestedToolCall.toolCallId.startsWith(\"a2ui:\")\n ) {\n continue;\n }\n out.push({ ...normalizeToolCall(nestedToolCall), part: nestedToolCall });\n collectNestedToolCalls(nestedToolCall, out);\n }\n }\n}\n\nfunction emitToolResult(\n toolCallId: string,\n part: ToolCallPart,\n converted: AgUiMessage[],\n): void {\n if (part.result === undefined) return;\n\n const resultContent =\n part.modelContent !== undefined\n ? extractText(part.modelContent)\n : typeof part.result === \"string\"\n ? part.result\n : JSON.stringify(part.result);\n\n converted.push({\n id: part.unstable_toolMessageId ?? `${toolCallId}:tool`,\n role: \"tool\",\n content: resultContent,\n toolCallId,\n ...(part.isError ? { error: resultContent } : {}),\n });\n}\n\nfunction convertToolMessage(\n message: NormalizedThreadMessageLike,\n converted: AgUiMessage[],\n): void {\n const content = extractText(message.content);\n const toolCallId = message.toolCallId ?? generateId();\n\n converted.push({\n id: message.id,\n role: \"tool\",\n content,\n toolCallId,\n ...(typeof message.error === \"string\" ? { error: message.error } : {}),\n });\n}\n\nexport function toAgUiMessages(\n messages: readonly ThreadMessageLike[],\n): AgUiMessage[] {\n const converted: AgUiMessage[] = [];\n\n for (const rawMessage of messages) {\n const message: NormalizedThreadMessageLike = {\n ...rawMessage,\n id: rawMessage.id ?? generateId(),\n };\n const opaqueReasoning = readOpaqueReasoning(message.metadata);\n const toOpaqueRecord = (entry: AgUiOpaqueReasoning): AgUiMessage => ({\n id: entry.id,\n role: \"reasoning\",\n content: \"\",\n encryptedValue: entry.encryptedValue,\n });\n for (const entry of opaqueReasoning) {\n if (entry.after !== true) converted.push(toOpaqueRecord(entry));\n }\n const flushTrailingOpaqueReasoning = () => {\n for (const entry of opaqueReasoning) {\n if (entry.after === true) converted.push(toOpaqueRecord(entry));\n }\n };\n\n if (message.role === \"assistant\") {\n convertAssistantMessage(message, converted);\n flushTrailingOpaqueReasoning();\n continue;\n }\n\n if (message.role === \"tool\") {\n convertToolMessage(message, converted);\n flushTrailingOpaqueReasoning();\n continue;\n }\n\n if (message.role === \"user\") {\n converted.push({\n id: message.id,\n role: \"user\",\n content: buildUserContent(message),\n ...(message.name ? { name: message.name } : {}),\n });\n flushTrailingOpaqueReasoning();\n continue;\n }\n\n if (message.role === \"system\" || message.role === \"developer\") {\n const custom = isObject(message.metadata)\n ? message.metadata.custom\n : undefined;\n const namespaced = isObject(custom)\n ? custom[AG_UI_METADATA_NAMESPACE]\n : undefined;\n const wireRole =\n message.role === \"system\" &&\n isObject(namespaced) &&\n namespaced.role === \"developer\"\n ? (\"developer\" as const)\n : message.role;\n converted.push({\n id: message.id,\n role: wireRole,\n content: extractText(message.content),\n ...(message.name ? { name: message.name } : {}),\n });\n flushTrailingOpaqueReasoning();\n continue;\n }\n\n if (message.role === \"reasoning\") {\n converted.push({\n id: message.id,\n role: \"reasoning\",\n content: extractText(message.content),\n });\n flushTrailingOpaqueReasoning();\n continue;\n }\n\n flushTrailingOpaqueReasoning();\n }\n\n return converted;\n}\n\ntype AgUiTool = NonNullable<RunAgentParameters[\"tools\"]>[number];\n\nexport function toAgUiTools(\n tools: Record<string, Tool> | undefined,\n): AgUiTool[] {\n if (!tools) return [];\n\n const toolsSchema = toToolsJSONSchema(tools);\n return Object.entries(toolsSchema).map(([name, tool]) => ({\n name,\n description: tool.description ?? \"\",\n parameters: tool.parameters,\n }));\n}\n"],"mappings":";;;;;;;;;AAyHA,MAAM,YAAY,UAChB,OAAO,UAAU,YAAY,UAAU;AAEzC,MAAM,aAAa,QAAiC,QAAgB;CAClE,MAAM,QAAQ,OAAO;CACrB,OAAO,OAAO,UAAU,WAAW,QAAQ,KAAA;AAC7C;AAEA,MAAM,iBAAiB,WACrB,UAAU,QAAQ,YAAY,KAAK,UAAU,QAAQ,cAAc;AAErE,MAAM,qBAAqB,qBAA8B;CACvD,IAAI,CAAC,SAAS,gBAAgB,GAAG,OAAO,KAAA;CACxC,MAAM,aAAa,iBAAiB;CACpC,OAAO,SAAS,UAAU,IAAI,aAAa,KAAA;AAC7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,SAAgB,YACd,OACY;CACZ,IAAI,CAAC,OAAO,OAAO,CAAC;CAEpB,MAAM,cAAc,kBAAkB,KAAK;CAC3C,OAAO,OAAO,QAAQ,WAAW,CAAC,CAAC,KAAK,CAAC,MAAM,WAAW;EACxD;EACA,aAAa,KAAK,eAAe;EACjC,YAAY,KAAK;CACnB,EAAE;AACJ"}
|
|
@@ -2,13 +2,13 @@ import { Logger } from "../logger.js";
|
|
|
2
2
|
import { AgUiEvent, AgUiInterrupt } from "../types.js";
|
|
3
3
|
import { ChatModelRunResult } from "@assistant-ui/core";
|
|
4
4
|
//#region src/runtime/adapter/run-aggregator.d.ts
|
|
5
|
-
declare const AG_UI_METADATA_NAMESPACE = "agui";
|
|
6
|
-
type AgUiOpaqueReasoning = {
|
|
5
|
+
export declare const AG_UI_METADATA_NAMESPACE = "agui";
|
|
6
|
+
export type AgUiOpaqueReasoning = {
|
|
7
7
|
id: string;
|
|
8
8
|
encryptedValue: string;
|
|
9
9
|
after?: boolean;
|
|
10
10
|
};
|
|
11
|
-
type AgUiCustomMetadata = {
|
|
11
|
+
export type AgUiCustomMetadata = {
|
|
12
12
|
/** Wire role restored on export for messages the internal model cannot
|
|
13
13
|
* represent (a developer record rides as a system message). */
|
|
14
14
|
role?: "developer";
|
|
@@ -16,10 +16,10 @@ type AgUiCustomMetadata = {
|
|
|
16
16
|
opaqueReasoning?: AgUiOpaqueReasoning[];
|
|
17
17
|
};
|
|
18
18
|
type Emit = (update: ChatModelRunResult) => void;
|
|
19
|
-
declare const MCP_APPS_ACTIVITY_TYPE = "mcp-apps";
|
|
20
|
-
declare const A2UI_SURFACE_ACTIVITY_TYPE = "a2ui-surface";
|
|
21
|
-
declare const isPlainObject: (value: unknown) => value is Record<string, unknown>;
|
|
22
|
-
type RunAggregatorOptions = {
|
|
19
|
+
export declare const MCP_APPS_ACTIVITY_TYPE = "mcp-apps";
|
|
20
|
+
export declare const A2UI_SURFACE_ACTIVITY_TYPE = "a2ui-surface";
|
|
21
|
+
export declare const isPlainObject: (value: unknown) => value is Record<string, unknown>;
|
|
22
|
+
export type RunAggregatorOptions = {
|
|
23
23
|
showThinking: boolean;
|
|
24
24
|
logger: Logger;
|
|
25
25
|
emit: Emit;
|
|
@@ -36,7 +36,7 @@ type RunAggregatorOptions = {
|
|
|
36
36
|
* `system:*`, and `MultiAgentHandoff` are forwarded the same way, so apps only
|
|
37
37
|
* need data renderers for names they own.
|
|
38
38
|
*/
|
|
39
|
-
declare class RunAggregator {
|
|
39
|
+
export declare class RunAggregator {
|
|
40
40
|
private readonly emitUpdate;
|
|
41
41
|
private readonly showThinking;
|
|
42
42
|
private readonly logger;
|
|
@@ -108,7 +108,6 @@ declare class RunAggregator {
|
|
|
108
108
|
private handleReasoningContent;
|
|
109
109
|
private handleReasoningEnd;
|
|
110
110
|
}
|
|
111
|
-
declare function tryParseJSON(value: string): unknown;
|
|
111
|
+
export declare function tryParseJSON(value: string): unknown;
|
|
112
112
|
//#endregion
|
|
113
|
-
export { A2UI_SURFACE_ACTIVITY_TYPE, AG_UI_METADATA_NAMESPACE, AgUiCustomMetadata, AgUiOpaqueReasoning, MCP_APPS_ACTIVITY_TYPE, RunAggregator, RunAggregatorOptions, isPlainObject, tryParseJSON };
|
|
114
113
|
//# sourceMappingURL=run-aggregator.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"run-aggregator.d.ts","names":[],"sources":["../../../src/runtime/adapter/run-aggregator.ts"],"mappings":";;;;
|
|
1
|
+
{"version":3,"file":"run-aggregator.d.ts","names":[],"sources":["../../../src/runtime/adapter/run-aggregator.ts"],"mappings":";;;;qBAuBa;YA8CD;EACV;EACA;EACA;;YAGU;;;EAGV;EACA,aAAa;EACb,kBAAkB;;KAGf,QAAQ,QAAQ;qBA6FR;qBAEA;qBAEA,gBACX,mBACC,SAAS;YAGA;EACV;EACA,QAAQ;EACR,MAAM;EACN,qBAAqB;EACrB,sBAAsB;;;;;;;;;;;;qBAaX;mBACM;mBACA;mBACA;mBACA;mBACA;UAIT;UACA;mBACS;mBACA;mBACA;mBACA;mBACA;mBAKA;mBACA;mBACA;UACT;mBACS;UACT;UACA;mBACS;mBACA;mBACA;mBACA;mBACA;UAIT;UAMA;mBACS;mBACA;mBACA;mBACA;mBACA;UACT;UACA;UACA;UACA;UAEA;UACA;UACA;EAEI,YAAA,SAAS;EAQrB,YAAY;EAIZ,OAAO,OAAO;UAoWN;UAmBA;UAiDA;UAWA;UAIA;UA8BA;UAMA;UAOA;UAIA;UAaA;UAKA;UAOA;UAiBA;UAiBA;UAMA;UAwCA;UA4BA;UA0BA;UAyDA;UAcA;UAgBA;UAwBA;UAyCA;UA4HA;UAmHA;UASA;UAgCA;UA+CA;UA0BA;;wBAUM,aAAa"}
|