@assistant-ui/react-ag-ui 0.0.46 → 0.0.47

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.
@@ -1 +1 @@
1
- {"version":3,"file":"AgUiThreadRuntimeCore.d.ts","names":[],"sources":["../../src/runtime/AgUiThreadRuntimeCore.ts"],"mappings":";;;;;;KAqDK,YAAY,YAAY;KACxB,gBACH,SAAS,wBACN,eAAe;KACf;EACH;EACA;EACA,WAAW;EACX,SAAS;;KAGN;EACH,OAAO;EACP,QAAQ;EACR;EACA;EACA,WAAW,OAAO;EAClB;EACA,UAAU;EACV;;cAKW;UACH;UACA;UACA;UACA;UACA;UACA;mBACS;UAET;mBACS;UACT;UACA;UACA;UACA;UACA;UACA;UACA;mBACS;mBACA;UACT;UACA;UACA;EAEI,YAAA,SAAS;EAYrB,cAAc,SAAS,KAAK;EAW5B,cAAc,SAAS;EAIvB;EAIA,wBAAwB;EAIxB,wBAAwB;UAmBhB;UAQA;UAUA;UAIA;UAQA;UAQA;UAMA;UAKA;UAKA;UAKA;EAYR,YAAY;EAIZ;MAII;EAIJ,mBAAmB;EA2Cb,OAAO,SAAS,gBAAgB;UAW9B;UAQA;EAiBF,KAAK,SAAS,gBAAgB;EAI9B,OACJ,yBACA;IAAU,YAAY;MACrB;EAMG,UAAU;EAKV,OAAO,QAAQ,kBAAkB;EAUjC,kBAAkB,mBAAmB,kBAAkB;UAwBrD;UAOA;EAgBR;IACE;IACA,qBAAqB;;EAavB;IACE;IACA;;EAcI,yBACJ,oBAAoB,oBACnB;EAoDG,UACJ,SAAS,qBACT,qBAAqB,oBACpB;UAyCK;UAkBA;UAiCA;UA0BA;EA+BR,yBAAyB;UAkBjB;EAiBR,cAAc,SAAS;UA4Bf;UAYA;UA6BA;EAMR,sBAAsB,mBAAmB;UAgDjC;EAgER,kBAAkB,OAAO;EAKzB,SACE,MACI,sBACE,MAAM,kCAAkC;EAOhD;UAKc;UAkJA;UAyDN;UA6BA;UAqBA;UAKA;UAOA;UAuBA;UA2CA;UAiDA;UA4BA;UA6BA;UA4DA;UAuEA;UA8DA;UAwBA;UAQA;UAIA;UAKA;UAIA;UAQA;UAWA"}
1
+ {"version":3,"file":"AgUiThreadRuntimeCore.d.ts","names":[],"sources":["../../src/runtime/AgUiThreadRuntimeCore.ts"],"mappings":";;;;;;KAsDK,YAAY,YAAY;KACxB,gBACH,SAAS,wBACN,eAAe;KACf;EACH;EACA;EACA,WAAW;EACX,SAAS;;KAGN;EACH,OAAO;EACP,QAAQ;EACR;EACA;EACA,WAAW,OAAO;EAClB;EACA,UAAU;EACV;;cAKW;UACH;UACA;UACA;UACA;UACA;UACA;mBACS;UAET;mBACS;UACT;UACA;UACA;UACA;UACA;UACA;UACA;mBACS;mBACA;UACT;UACA;UACA;EAEI,YAAA,SAAS;EAYrB,cAAc,SAAS,KAAK;EAW5B,cAAc,SAAS;EAIvB;EAIA,wBAAwB;EAIxB,wBAAwB;UAmBhB;UAQA;UAUA;UAIA;UAQA;UAQA;UAMA;UAKA;UAKA;UAKA;EAYR,YAAY;EAIZ;MAII;EAIJ,mBAAmB;EA2Cb,OAAO,SAAS,gBAAgB;UAW9B;UAQA;EAiBF,KAAK,SAAS,gBAAgB;EAI9B,OACJ,yBACA;IAAU,YAAY;MACrB;EAMG,UAAU;EAKV,OAAO,QAAQ,kBAAkB;EAUjC,kBAAkB,mBAAmB,kBAAkB;UAwBrD;UAOA;EAgBR;IACE;IACA,qBAAqB;;EAavB;IACE;IACA;;EAcI,yBACJ,oBAAoB,oBACnB;EAoDG,UACJ,SAAS,qBACT,qBAAqB,oBACpB;UAyCK;UAkBA;UAiCA;UA0BA;EA+BR,yBAAyB;UAkBjB;EAiBR,cAAc,SAAS;UA4Bf;UAYA;UA6BA;EAMR,sBAAsB,mBAAmB;UAgDjC;EAgER,kBAAkB,OAAO;EAKzB,SACE,MACI,sBACE,MAAM,kCAAkC;EAOhD;UAKc;UAkJA;UAyDN;UA6BA;UAqBA;UAKA;UAOA;UAuBA;UA2CA;UAiDA;UA4BA;UA6BA;UA4DA;UA2EA;UA8DA;UAwBA;UAQA;UAIA;UAKA;UAIA;UAQA;UAWA"}
@@ -1,4 +1,5 @@
1
1
  "use client";
2
+ import { readMcpAppResourceUri } from "./mcp-tool-result.js";
2
3
  import { AG_UI_METADATA_NAMESPACE, RunAggregator, isPlainObject, tryParseJSON } from "./adapter/run-aggregator.js";
3
4
  import { fromAgUiMessages, toAgUiMessages, toAgUiTools } from "./adapter/conversions.js";
4
5
  import { createAgUiSubscriber } from "./adapter/subscriber.js";
@@ -911,6 +912,7 @@ var AgUiThreadRuntimeCore = class {
911
912
  if (!this.updateMessage(messageId, (message) => {
912
913
  if (message.role !== "assistant") return message;
913
914
  const assistant = message;
915
+ const mcpAppUri = readMcpAppResourceUri(event.mcpResult?._meta);
914
916
  let matchedToolCall = false;
915
917
  const content = assistant.content.map((part) => {
916
918
  if (part.type !== "tool-call" || part.toolCallId !== event.toolCallId) return part;
@@ -932,6 +934,7 @@ var AgUiThreadRuntimeCore = class {
932
934
  text: event.content
933
935
  }] } : {},
934
936
  ...typeof event.mcpResult?.isError === "boolean" ? { isError: event.mcpResult.isError } : event.role === "tool" ? { isError: false } : {},
937
+ ...part.mcp === void 0 && mcpAppUri !== void 0 ? { mcp: { app: { resourceUri: mcpAppUri } } } : {},
935
938
  ...event.messageId ? { unstable_toolMessageId: event.messageId } : {}
936
939
  };
937
940
  });
@@ -1 +1 @@
1
- {"version":3,"file":"AgUiThreadRuntimeCore.js","names":[],"sources":["../../src/runtime/AgUiThreadRuntimeCore.ts"],"sourcesContent":["\"use client\";\n\nimport {\n generateId,\n fromThreadMessageLike,\n isMcpAppUri,\n} from \"@assistant-ui/core\";\nimport type {\n AddToolResultOptions,\n AppendMessage,\n CreateAppendMessage,\n AssistantRuntime,\n ChatModelRunOptions,\n ChatModelRunResult,\n ExportedMessageRepository,\n MessageStatus,\n ThreadAssistantMessage,\n ThreadHistoryAdapter,\n ThreadMessage,\n ToolCallMessagePart,\n} from \"@assistant-ui/core\";\nimport { MessageRepository } from \"@assistant-ui/core/internal\";\nimport type { AbstractAgent } from \"@ag-ui/client\";\nimport jsonpatch, { type Operation } from \"fast-json-patch\";\nimport type { Logger } from \"./logger\";\nimport type { AgUiEvent, AgUiInterrupt, AgUiResumeEntry } from \"./types\";\nimport type { ReadonlyJSONValue } from \"assistant-stream/utils\";\nimport {\n AG_UI_METADATA_NAMESPACE,\n type AgUiCustomMetadata,\n isPlainObject,\n MCP_APPS_ACTIVITY_TYPE,\n RunAggregator,\n tryParseJSON,\n} from \"./adapter/run-aggregator\";\nimport {\n fromAgUiMessages,\n toAgUiMessages,\n toAgUiTools,\n} from \"./adapter/conversions\";\nimport { createAgUiSubscriber } from \"./adapter/subscriber\";\n\nconst optimisticPrefix = \"__optimistic__\";\nconst generateOptimisticId = () => `${optimisticPrefix}${generateId()}`;\nconst isOptimisticId = (id: string) => id.startsWith(optimisticPrefix);\n\nconst isResolvedToolCall = (\n part: ThreadAssistantMessage[\"content\"][number],\n): boolean =>\n part.type === \"tool-call\" && \"result\" in part && part.result !== undefined;\n\nconst symbolResumeShim = Symbol(\"agui-resume-shim\");\n\ntype RunConfig = NonNullable<AppendMessage[\"runConfig\"]>;\ntype ResumeStream = (\n options: ChatModelRunOptions,\n) => AsyncGenerator<ChatModelRunResult, void, unknown>;\ntype ResumeRunConfig = {\n parentId: string | null;\n sourceId: string | null;\n runConfig: RunConfig;\n stream?: ResumeStream;\n};\n\ntype CoreOptions = {\n agent: AbstractAgent;\n logger: Logger;\n showThinking: boolean;\n autoCancelPendingToolCalls?: boolean | undefined;\n onError?: (error: Error) => void;\n onCancel?: () => void;\n history?: ThreadHistoryAdapter;\n notifyUpdate: () => void;\n};\n\nconst FALLBACK_USER_STATUS = { type: \"complete\", reason: \"unknown\" } as const;\n\nexport class AgUiThreadRuntimeCore {\n private agent: AbstractAgent;\n private logger: Logger;\n private showThinking: boolean;\n private autoCancelPendingToolCalls: boolean | undefined;\n private onError: ((error: Error) => void) | undefined;\n private onCancel: (() => void) | undefined;\n private readonly notifyUpdate: () => void;\n\n private runtime: AssistantRuntime | undefined;\n private readonly repository = new MessageRepository();\n private exportedRepository: ExportedMessageRepository | undefined;\n private isRunningFlag = false;\n private abortController: AbortController | null = null;\n private stateSnapshot: ReadonlyJSONValue | undefined;\n private pendingError: Error | null = null;\n private history: ThreadHistoryAdapter | undefined;\n private lastRunConfig: RunConfig | undefined;\n private readonly assistantHistoryParents = new Map<string, string | null>();\n private readonly recordedHistoryIds = new Set<string>();\n private _isLoading = false;\n private _loadPromise: Promise<void> | undefined;\n private pendingResumeMessageId: string | null = null;\n\n constructor(options: CoreOptions) {\n this.agent = options.agent;\n this.logger = options.logger;\n this.showThinking = options.showThinking;\n this.autoCancelPendingToolCalls = options.autoCancelPendingToolCalls;\n this.onError = options.onError;\n this.onCancel = options.onCancel;\n this.history = options.history;\n this.notifyUpdate = options.notifyUpdate;\n this.installResumeShim();\n }\n\n updateOptions(options: Omit<CoreOptions, \"notifyUpdate\">) {\n this.agent = options.agent;\n this.logger = options.logger;\n this.showThinking = options.showThinking;\n this.autoCancelPendingToolCalls = options.autoCancelPendingToolCalls;\n this.onError = options.onError;\n this.onCancel = options.onCancel;\n this.history = options.history;\n this.installResumeShim();\n }\n\n attachRuntime(runtime: AssistantRuntime) {\n this.runtime = runtime;\n }\n\n detachRuntime() {\n this.runtime = undefined;\n }\n\n getMessages(): readonly ThreadMessage[] {\n return this.repository.getMessages();\n }\n\n getMessageRepository(): ExportedMessageRepository {\n if (this.exportedRepository) return this.exportedRepository;\n\n const exportedRepository = this.repository.export();\n let parentId: string | null = null;\n for (const message of this.repository.getMessages()) {\n if (message.metadata.isOptimistic) {\n exportedRepository.messages.push({ parentId, message });\n }\n parentId = message.id;\n }\n\n this.exportedRepository = {\n ...exportedRepository,\n headId: this.repository.headId,\n };\n return this.exportedRepository;\n }\n\n private tryGetMessage(messageId: string) {\n try {\n return this.repository.getMessage(messageId);\n } catch {\n return undefined;\n }\n }\n\n private tryGetMessages(\n messageId: string,\n ): readonly ThreadMessage[] | undefined {\n try {\n return this.repository.getMessages(messageId);\n } catch {\n return undefined;\n }\n }\n\n private hasMessage(messageId: string): boolean {\n return this.tryGetMessage(messageId) !== undefined;\n }\n\n private addOrUpdateMessage(\n parentId: string | null,\n message: ThreadMessage,\n ): void {\n this.repository.addOrUpdateMessage(parentId, message);\n this.exportedRepository = undefined;\n }\n\n private deleteMessage(\n messageId: string,\n replacementId?: string | null,\n ): void {\n this.repository.deleteMessage(messageId, replacementId);\n this.exportedRepository = undefined;\n }\n\n private tryDeleteMessage(messageId: string): boolean {\n if (!this.hasMessage(messageId)) return false;\n this.deleteMessage(messageId);\n return true;\n }\n\n private switchToBranch(messageId: string): void {\n this.repository.switchToBranch(messageId);\n this.exportedRepository = undefined;\n }\n\n private resetRepositoryHead(messageId: string | null): void {\n this.repository.resetHead(messageId);\n this.exportedRepository = undefined;\n }\n\n private clearRepository(): void {\n this.repository.clear();\n this.exportedRepository = undefined;\n }\n\n private updateMessage(\n messageId: string,\n updater: (message: ThreadMessage) => ThreadMessage,\n ): boolean {\n const item = this.tryGetMessage(messageId);\n if (!item) return false;\n const message = updater(item.message);\n if (message === item.message) return false;\n this.addOrUpdateMessage(item.parentId, message);\n return true;\n }\n\n getState(): ReadonlyJSONValue | undefined {\n return this.stateSnapshot;\n }\n\n isRunning(): boolean {\n return this.isRunningFlag;\n }\n\n get isLoading(): boolean {\n return this._isLoading;\n }\n\n __internal_load(): Promise<void> {\n if (this._loadPromise) return this._loadPromise;\n\n const promise = this.history?.load() ?? Promise.resolve(null);\n\n this._isLoading = true;\n\n this._loadPromise = promise\n .then(async (repo) => {\n if (!repo) return;\n\n this.applyExternalMessageRepository(repo);\n\n if (repo.state !== undefined) {\n this.loadExternalState(repo.state);\n }\n\n if (repo.unstable_resume) {\n const parentId = repo.headId ?? this.repository.headId;\n const resumeStream = this.history?.resume?.bind(this.history);\n await this.startRun(\n parentId,\n this.lastRunConfig,\n undefined,\n resumeStream,\n );\n }\n })\n .catch((error) => {\n this.logger.error?.(\"[agui] failed to load history\", error);\n this.onError?.(\n error instanceof Error ? error : new Error(String(error)),\n );\n })\n .finally(() => {\n this._isLoading = false;\n this.notifyUpdate();\n });\n\n this.notifyUpdate();\n return this._loadPromise;\n }\n\n async append(message: AppendMessage): Promise<void> {\n const startRun = message.startRun ?? message.role === \"user\";\n if (startRun) {\n this.assertNoPendingInterrupts();\n this.maybeAutoCancelPendingToolCalls();\n }\n const threadMessageId = this.appendEntry(message);\n if (!startRun) return;\n await this.startRun(threadMessageId, message.runConfig);\n }\n\n private maybeAutoCancelPendingToolCalls(): void {\n if (this.autoCancelPendingToolCalls === false) return;\n const pending = this.getPendingToolCalls();\n if (!pending) return;\n this.cancelUnresolvedToolCalls(pending.messageId);\n this.maybeCompleteAfterToolResults(pending.messageId);\n }\n\n private appendEntry(message: AppendMessage): string {\n if (message.sourceId) this.tryDeleteMessage(message.sourceId);\n\n const threadMessage = this.toThreadMessage(message);\n const parentId =\n message.parentId === null\n ? null\n : message.parentId && this.hasMessage(message.parentId)\n ? message.parentId\n : this.repository.headId;\n this.addOrUpdateMessage(parentId, threadMessage);\n this.switchToBranch(threadMessage.id);\n this.notifyUpdate();\n this.recordHistoryEntry(parentId, threadMessage);\n return threadMessage.id;\n }\n\n async edit(message: AppendMessage): Promise<void> {\n await this.append(message);\n }\n\n async reload(\n parentId: string | null,\n config: { runConfig?: RunConfig } = {},\n ): Promise<void> {\n this.assertNoPendingInterrupts();\n this.maybeAutoCancelPendingToolCalls();\n await this.startRun(parentId, config.runConfig);\n }\n\n async cancel(): Promise<void> {\n if (!this.abortController) return;\n this.abortController.abort();\n }\n\n async resume(config: ResumeRunConfig): Promise<void> {\n this.assertNoPendingInterrupts();\n await this.startRun(\n config.parentId,\n config.runConfig ?? this.lastRunConfig,\n undefined,\n config.stream,\n );\n }\n\n async resumeInFlightRun(messages: readonly ThreadMessage[]): Promise<void> {\n // Without a resume stream startRun would re-run the agent from scratch.\n const resumeStream = this.history?.resume?.bind(this.history);\n if (!resumeStream) {\n const error = new Error(\n \"[agui] unstable_resume requires a ThreadHistoryAdapter with a resume() method; skipping resume after thread switch\",\n );\n this.logger.error?.(error.message);\n this.onError?.(error);\n return;\n }\n const parentId = messages.at(-1)?.id ?? null;\n try {\n await this.startRun(\n parentId,\n this.lastRunConfig,\n undefined,\n resumeStream,\n );\n } catch {\n // startRun already reported via onError; don't reject the switch.\n }\n }\n\n private assertNoPendingInterrupts(): void {\n if (!this.getPendingInterrupts()) return;\n throw new Error(\n \"[agui] cannot start a new run while interrupts are pending; resolve them with submitInterruptResponses()\",\n );\n }\n\n private findRequiresActionAssistant(\n reason: \"interrupt\" | \"tool-calls\",\n ): ThreadAssistantMessage | null {\n const assistant = this.getMessages().findLast(\n (message) => message.role === \"assistant\",\n ) as ThreadAssistantMessage | undefined;\n if (\n !assistant ||\n assistant.status?.type !== \"requires-action\" ||\n assistant.status.reason !== reason\n ) {\n return null;\n }\n return assistant;\n }\n\n getPendingInterrupts(): {\n messageId: string;\n interrupts: readonly AgUiInterrupt[];\n } | null {\n const assistant = this.findRequiresActionAssistant(\"interrupt\");\n if (!assistant) return null;\n const stored = (\n assistant.metadata.custom[AG_UI_METADATA_NAMESPACE] as\n | AgUiCustomMetadata\n | undefined\n )?.interrupts;\n if (!stored?.length) return null;\n return { messageId: assistant.id, interrupts: stored };\n }\n\n getPendingToolCalls(): {\n messageId: string;\n toolCallIds: string[];\n } | null {\n const assistant = this.findRequiresActionAssistant(\"tool-calls\");\n if (!assistant) return null;\n const toolCallIds: string[] = [];\n for (const part of assistant.content) {\n if (part.type !== \"tool-call\") continue;\n if (isResolvedToolCall(part)) continue;\n toolCallIds.push(part.toolCallId);\n }\n if (toolCallIds.length === 0) return null;\n return { messageId: assistant.id, toolCallIds };\n }\n\n async submitInterruptResponses(\n responses: readonly AgUiResumeEntry[],\n ): Promise<void> {\n const pending = this.getPendingInterrupts();\n if (!pending) {\n throw new Error(\n \"[agui] submitInterruptResponses: no pending interrupts on this thread\",\n );\n }\n\n const responsesById = this.collectInterruptResponses(\n \"submitInterruptResponses\",\n pending.interrupts,\n responses,\n );\n\n const openIds = pending.interrupts.map((i) => i.id);\n const missing = openIds.filter((id) => !responsesById.has(id));\n if (missing.length > 0) {\n throw new Error(\n `[agui] submitInterruptResponses: missing responses for open interrupts: ${missing.join(\", \")}`,\n );\n }\n\n const now = Date.now();\n for (const interrupt of pending.interrupts) {\n if (!interrupt.expiresAt) continue;\n const expiry = new Date(interrupt.expiresAt).getTime();\n if (Number.isNaN(expiry)) {\n throw new Error(\n `[agui] submitInterruptResponses: interrupt ${interrupt.id} has malformed expiresAt \"${interrupt.expiresAt}\"`,\n );\n }\n if (expiry <= now) {\n throw new Error(\n `[agui] submitInterruptResponses: interrupt ${interrupt.id} expired at ${interrupt.expiresAt}`,\n );\n }\n }\n\n const resume: AgUiResumeEntry[] = openIds.map((id) =>\n responsesById.get(id)!,\n );\n\n if (this.isRunningFlag) {\n throw new Error(\n \"[agui] submitInterruptResponses: a run is already in progress\",\n );\n }\n\n this.clearPendingInterrupts(pending.messageId);\n await this.startRun(pending.messageId, this.lastRunConfig, resume);\n }\n\n async steerAway(\n message: CreateAppendMessage,\n responses?: readonly AgUiResumeEntry[],\n ): Promise<void> {\n const pending = this.getPendingInterrupts();\n if (!pending) {\n const pendingTools = this.getPendingToolCalls();\n if (pendingTools) {\n if (responses?.length) {\n throw new Error(\n \"[agui] steerAway: responses are only valid for pending interrupts\",\n );\n }\n if (this.isRunningFlag) {\n throw new Error(\"[agui] steerAway: a run is already in progress\");\n }\n this.cancelUnresolvedToolCalls(pendingTools.messageId);\n this.maybeCompleteAfterToolResults(pendingTools.messageId);\n const normalized = this.toAppendMessage(message);\n const threadMessageId = this.appendEntry(normalized);\n await this.startRun(threadMessageId, normalized.runConfig);\n return;\n }\n if (responses?.length) {\n throw new Error(\n \"[agui] steerAway: no pending interrupts on this thread\",\n );\n }\n await this.append(this.toAppendMessage(message));\n return;\n }\n\n const resume = this.resolveSteerAwayResume(pending.interrupts, responses);\n\n if (this.isRunningFlag) {\n throw new Error(\"[agui] steerAway: a run is already in progress\");\n }\n\n const normalized = this.toAppendMessage(message);\n this.clearPendingInterrupts(pending.messageId);\n const threadMessageId = this.appendEntry(normalized);\n await this.startRun(threadMessageId, normalized.runConfig, resume);\n }\n\n private resolveSteerAwayResume(\n interrupts: readonly AgUiInterrupt[],\n responses: readonly AgUiResumeEntry[] | undefined,\n ): AgUiResumeEntry[] {\n const responsesById = this.collectInterruptResponses(\n \"steerAway\",\n interrupts,\n responses ?? [],\n );\n return interrupts.map(\n (interrupt) =>\n responsesById.get(interrupt.id) ?? {\n interruptId: interrupt.id,\n status: \"cancelled\",\n },\n );\n }\n\n private collectInterruptResponses(\n method: \"submitInterruptResponses\" | \"steerAway\",\n interrupts: readonly AgUiInterrupt[],\n responses: readonly AgUiResumeEntry[],\n ): Map<string, AgUiResumeEntry> {\n const known = new Set(interrupts.map((interrupt) => interrupt.id));\n const responsesById = new Map<string, AgUiResumeEntry>();\n for (const entry of responses) {\n if (!entry || typeof entry.interruptId !== \"string\") {\n throw new Error(\n `[agui] ${method}: every entry must have an interruptId`,\n );\n }\n if (entry.status !== \"resolved\" && entry.status !== \"cancelled\") {\n throw new Error(\n `[agui] ${method}: invalid status \"${entry.status}\" for interrupt ${entry.interruptId}`,\n );\n }\n if (!known.has(entry.interruptId)) {\n throw new Error(\n `[agui] ${method}: unknown interrupt id ${entry.interruptId}`,\n );\n }\n if (responsesById.has(entry.interruptId)) {\n throw new Error(\n `[agui] ${method}: duplicate response for interrupt ${entry.interruptId}`,\n );\n }\n responsesById.set(entry.interruptId, entry);\n }\n return responsesById;\n }\n\n private toAppendMessage(message: CreateAppendMessage): AppendMessage {\n if (typeof message === \"string\") {\n return {\n createdAt: new Date(),\n parentId: this.repository.headId,\n sourceId: null,\n runConfig: {},\n role: \"user\",\n content: [{ type: \"text\", text: message }],\n attachments: [],\n metadata: { custom: {} },\n };\n }\n return {\n createdAt: message.createdAt ?? new Date(),\n parentId: message.parentId ?? this.repository.headId,\n sourceId: message.sourceId ?? null,\n role: message.role ?? \"user\",\n content: message.content,\n attachments: message.attachments ?? [],\n metadata: message.metadata ?? { custom: {} },\n runConfig: message.runConfig ?? {},\n startRun: message.startRun,\n } as AppendMessage;\n }\n\n private clearPendingInterrupts(messageId: string): void {\n const touched = this.updateMessage(messageId, (message) => {\n if (message.role !== \"assistant\") return message;\n const assistant = message as ThreadAssistantMessage;\n if (\n assistant.status?.type !== \"requires-action\" ||\n assistant.status.reason !== \"interrupt\"\n ) {\n return assistant;\n }\n const aguiMeta = assistant.metadata.custom[AG_UI_METADATA_NAMESPACE] as\n | AgUiCustomMetadata\n | undefined;\n const { interrupts: _drop, ...restAgui } = aguiMeta ?? {};\n const newCustom = { ...assistant.metadata.custom };\n if (Object.keys(restAgui).length > 0) {\n newCustom[AG_UI_METADATA_NAMESPACE] = restAgui;\n } else {\n delete newCustom[AG_UI_METADATA_NAMESPACE];\n }\n return {\n ...assistant,\n status: { type: \"complete\" as const, reason: \"unknown\" as const },\n metadata: { ...assistant.metadata, custom: newCustom },\n };\n });\n if (touched) {\n this.notifyUpdate();\n }\n }\n\n findMessageIdForToolCall(toolCallId: string): string | undefined {\n let fallbackMessageId: string | undefined;\n const messages = this.getMessages();\n for (let index = messages.length - 1; index >= 0; index--) {\n const message = messages[index];\n if (!message || message.role !== \"assistant\") continue;\n for (const part of message.content) {\n if (part.type !== \"tool-call\" || part.toolCallId !== toolCallId)\n continue;\n if (!isResolvedToolCall(part)) {\n return message.id;\n }\n fallbackMessageId ??= message.id;\n }\n }\n return fallbackMessageId;\n }\n\n private cancelUnresolvedToolCalls(messageId: string): void {\n const updated = this.updateMessage(messageId, (message) => {\n if (message.role !== \"assistant\") return message;\n const assistant = message as ThreadAssistantMessage;\n const content = assistant.content.map((part) => {\n if (part.type !== \"tool-call\" || isResolvedToolCall(part)) return part;\n return {\n ...part,\n result: { error: \"Tool call cancelled by user\" },\n isError: true,\n };\n });\n return { ...assistant, content };\n });\n if (updated) this.notifyUpdate();\n }\n\n addToolResult(options: AddToolResultOptions): void {\n const updated = this.updateMessage(options.messageId, (message) => {\n if (message.role !== \"assistant\") return message;\n const assistant = message as ThreadAssistantMessage;\n let matchedToolCall = false;\n const content = assistant.content.map((part) => {\n if (part.type !== \"tool-call\" || part.toolCallId !== options.toolCallId)\n return part;\n matchedToolCall = true;\n return {\n ...part,\n result: options.result,\n artifact: options.artifact,\n isError: options.isError,\n };\n });\n if (!matchedToolCall) return message;\n return { ...assistant, content };\n });\n\n if (!updated) return;\n this.notifyUpdate();\n this.maybeResumeAfterToolResults(options.messageId);\n }\n\n // The continuation fires whether the frontend result lands before\n // RUN_FINISHED (the status flips to requires-action only later, while the\n // run is still draining) or after it.\n private maybeResumeAfterToolResults(messageId: string): void {\n if (!this.maybeCompleteAfterToolResults(messageId)) return;\n\n if (this.isRunningFlag) {\n // A run is still draining (RUN_FINISHED arrived but the stream has not\n // closed). Defer until startRun's tail so we never start two runs.\n this.pendingResumeMessageId = messageId;\n return;\n }\n this.startResumeRun(messageId);\n }\n\n private maybeCompleteAfterToolResults(messageId: string): boolean {\n const message = this.tryGetMessage(messageId)?.message;\n if (!message || message.role !== \"assistant\") return false;\n const assistant = message as ThreadAssistantMessage;\n if (\n assistant.status?.type !== \"requires-action\" ||\n assistant.status.reason !== \"tool-calls\"\n ) {\n return false;\n }\n const allResolved = assistant.content.every(\n (part) => part.type !== \"tool-call\" || isResolvedToolCall(part),\n );\n if (!allResolved) return false;\n\n const updated = this.updateMessage(messageId, (current) =>\n current.role === \"assistant\"\n ? {\n ...(current as ThreadAssistantMessage),\n status: { type: \"complete\" as const, reason: \"unknown\" as const },\n }\n : current,\n );\n if (!updated) return false;\n this.notifyUpdate();\n this.persistAssistantHistory(messageId);\n return true;\n }\n\n private startResumeRun(messageId: string): void {\n void this.startRun(messageId, this.lastRunConfig).catch((error) => {\n this.onError?.(error instanceof Error ? error : new Error(String(error)));\n });\n }\n\n applyExternalMessages(messages: readonly ThreadMessage[]): void {\n this.assistantHistoryParents.clear();\n\n if (messages.length === 0) {\n this.clearRepository();\n } else {\n let expectedParentId: string | null = null;\n let lastAppliedId: string | null = null;\n let hardReplace = false;\n const seen = new Set<string>();\n\n for (const message of messages) {\n if (seen.has(message.id)) continue;\n seen.add(message.id);\n const existing = this.tryGetMessage(message.id);\n if (existing && existing.parentId !== expectedParentId) {\n hardReplace = true;\n break;\n }\n this.addOrUpdateMessage(expectedParentId, message);\n expectedParentId = message.id;\n lastAppliedId = message.id;\n }\n\n if (hardReplace) {\n this.clearRepository();\n expectedParentId = null;\n lastAppliedId = null;\n seen.clear();\n for (const message of messages) {\n if (seen.has(message.id)) continue;\n seen.add(message.id);\n this.addOrUpdateMessage(expectedParentId, message);\n expectedParentId = message.id;\n lastAppliedId = message.id;\n }\n }\n\n this.resetRepositoryHead(lastAppliedId);\n }\n\n this.recordedHistoryIds.clear();\n for (const { message } of this.getMessageRepository().messages) {\n this.recordedHistoryIds.add(message.id);\n }\n this.notifyUpdate();\n }\n\n private applyExternalMessageRepository(\n loaded: ExportedMessageRepository,\n ): void {\n const headId = loaded.headId ?? loaded.messages.at(-1)?.message.id ?? null;\n const ids = new Set<string>();\n let degenerate = false;\n for (const { message } of loaded.messages) {\n if (ids.has(message.id)) {\n degenerate = true;\n break;\n }\n ids.add(message.id);\n }\n if (headId !== null && !ids.has(headId)) degenerate = true;\n\n if (!degenerate) {\n this.clearRepository();\n let pending = [...loaded.messages];\n const importedIds = new Set<string>();\n\n while (pending.length > 0) {\n const unresolved: typeof pending = [];\n let progressed = false;\n for (const item of pending) {\n if (item.parentId !== null && !importedIds.has(item.parentId)) {\n unresolved.push(item);\n continue;\n }\n this.addOrUpdateMessage(item.parentId, item.message);\n importedIds.add(item.message.id);\n progressed = true;\n }\n if (!progressed) {\n degenerate = true;\n break;\n }\n pending = unresolved;\n }\n }\n\n if (degenerate) {\n this.clearRepository();\n let previousId: string | null = null;\n for (const { message } of loaded.messages) {\n const existing = this.tryGetMessage(message.id);\n this.addOrUpdateMessage(\n existing ? existing.parentId : previousId,\n message,\n );\n previousId = message.id;\n }\n this.resetRepositoryHead(previousId);\n } else {\n this.resetRepositoryHead(headId);\n }\n\n this.assistantHistoryParents.clear();\n this.recordedHistoryIds.clear();\n for (const { message } of loaded.messages) {\n this.recordedHistoryIds.add(message.id);\n }\n this.notifyUpdate();\n }\n\n loadExternalState(state: ReadonlyJSONValue): void {\n this.stateSnapshot = state;\n this.notifyUpdate();\n }\n\n setState(\n next:\n | ReadonlyJSONValue\n | ((prev: ReadonlyJSONValue | undefined) => ReadonlyJSONValue),\n ): void {\n this.stateSnapshot =\n typeof next === \"function\" ? next(this.stateSnapshot) : next;\n this.notifyUpdate();\n }\n\n resetState(): void {\n this.stateSnapshot = undefined;\n this.notifyUpdate();\n }\n\n private async startRun(\n parentId: string | null,\n runConfig?: RunConfig,\n resume?: AgUiResumeEntry[],\n resumeStream?: ResumeStream,\n ): Promise<void> {\n const normalizedRunConfig = runConfig ?? {};\n this.lastRunConfig = normalizedRunConfig;\n const parent = parentId === null ? undefined : this.tryGetMessage(parentId);\n const shouldEagerlyInsertAssistant =\n parentId !== null &&\n parent !== undefined &&\n parentId !== this.repository.headId;\n const historicalMessages = [\n ...(shouldEagerlyInsertAssistant\n ? (this.tryGetMessages(parentId) ?? this.repository.getMessages())\n : this.repository.getMessages()),\n ];\n\n this.pendingError = null;\n const assistantParentId = parent ? parentId : this.repository.headId;\n let assistantMessageId: string | undefined;\n const ensureAssistant = () => {\n if (assistantMessageId) return assistantMessageId;\n const created = this.insertAssistantPlaceholder(\n assistantParentId ?? null,\n );\n assistantMessageId = created;\n this.markPendingAssistantHistory(created, assistantParentId ?? null);\n return created;\n };\n\n if (shouldEagerlyInsertAssistant) ensureAssistant();\n\n const applyUpdate = (update: ChatModelRunResult) => {\n const resolved = this.updateAssistantMessage(ensureAssistant(), update);\n if (resolved !== assistantMessageId) {\n assistantMessageId = resolved;\n }\n };\n\n const aggregator = new RunAggregator({\n showThinking: this.showThinking,\n logger: this.logger,\n emit: applyUpdate,\n onServerMessageId: (serverId) => {\n const placeholder = ensureAssistant();\n if (placeholder === serverId) return;\n if (this.reassignAssistantId(placeholder, serverId)) {\n assistantMessageId = serverId;\n }\n },\n });\n const dispatch = (event: AgUiEvent) => this.handleEvent(aggregator, event);\n\n const abortController = new AbortController();\n const abortSignal = abortController.signal;\n this.abortController = abortController;\n\n let cancelRun = () => dispatch({ type: \"RUN_CANCELLED\" });\n abortSignal.addEventListener(\n \"abort\",\n () => {\n cancelRun();\n this.finishRun(abortController);\n this.onCancel?.();\n },\n { once: true },\n );\n\n this.setRunning(true);\n\n try {\n if (resumeStream) {\n // Cancel flips only the status; an aggregator RUN_CANCELLED would emit an empty snapshot and wipe the replayed content.\n cancelRun = () =>\n applyUpdate({ status: { type: \"incomplete\", reason: \"cancelled\" } });\n await this.consumeResumeStream(resumeStream, {\n runConfig: normalizedRunConfig,\n threadId: this.agent.threadId || \"main\",\n parentId: assistantParentId,\n historicalMessages,\n abortSignal,\n ensureAssistant,\n applyUpdate,\n getAssistantMessageId: () => assistantMessageId,\n });\n } else {\n const runId = generateId();\n aggregator.handle({ type: \"RUN_STARTED\", runId });\n const input = this.buildRunInput(\n runId,\n normalizedRunConfig,\n historicalMessages,\n resume,\n );\n const subscriber = createAgUiSubscriber({\n dispatch,\n runId,\n logger: this.logger,\n onRunFailed: (error) => {\n this.pendingError = error;\n this.onError?.(error);\n },\n });\n try {\n (this.agent as any).messages = input.messages;\n (this.agent as any).threadId = input.threadId;\n (this.agent as any).state = input.state ?? null;\n } catch {\n // ignore\n }\n await (this.agent as any).runAgent(input, subscriber, {\n signal: abortSignal,\n });\n }\n } catch (error) {\n if (!abortSignal.aborted) {\n const err = error instanceof Error ? error : new Error(String(error));\n dispatch({ type: \"RUN_ERROR\", message: err.message });\n this.onError?.(err);\n this.pendingError = this.pendingError ?? err;\n }\n } finally {\n this.finishRun(abortController);\n }\n\n if (this.pendingError) {\n const err = this.pendingError;\n this.pendingError = null;\n this.pendingResumeMessageId = null;\n throw err;\n }\n\n // A tool result that landed before the run settled deferred its\n // continuation here so a second run never overlaps the first.\n if (this.pendingResumeMessageId !== null) {\n const resumeMessageId = this.pendingResumeMessageId;\n this.pendingResumeMessageId = null;\n if (!abortSignal.aborted) {\n this.startResumeRun(resumeMessageId);\n }\n }\n }\n\n // Replays a persisted run's snapshots into the existing assistant message, bypassing agent.runAgent so it is not re-invoked.\n private async consumeResumeStream(\n stream: ResumeStream,\n ctx: {\n runConfig: RunConfig;\n threadId: string;\n parentId: string | null;\n historicalMessages: readonly ThreadMessage[];\n abortSignal: AbortSignal;\n ensureAssistant: () => string;\n applyUpdate: (update: ChatModelRunResult) => void;\n getAssistantMessageId: () => string | undefined;\n },\n ): Promise<void> {\n const assistantId = ctx.ensureAssistant();\n const currentId = () => ctx.getAssistantMessageId() ?? assistantId;\n const options: ChatModelRunOptions = {\n messages: ctx.historicalMessages,\n runConfig: ctx.runConfig,\n abortSignal: ctx.abortSignal,\n context: this.runtime?.thread.getModelContext() ?? {},\n unstable_assistantMessageId: assistantId,\n unstable_threadId: ctx.threadId,\n unstable_parentId: ctx.parentId,\n unstable_getMessage: () => {\n const message = this.tryGetMessage(currentId())?.message;\n if (!message) {\n throw new Error(\n \"[agui] resume stream requested the assistant message before it existed\",\n );\n }\n return message;\n },\n };\n\n try {\n for await (const result of stream(options)) {\n if (ctx.abortSignal.aborted) return;\n ctx.applyUpdate(result);\n }\n } catch (error) {\n if (ctx.abortSignal.aborted) return;\n const err = error instanceof Error ? error : new Error(String(error));\n ctx.applyUpdate({\n status: { type: \"incomplete\", reason: \"error\", error: err.message },\n });\n this.onError?.(err);\n this.pendingError = this.pendingError ?? err;\n return;\n }\n\n if (ctx.abortSignal.aborted) return;\n const current = this.tryGetMessage(currentId())?.message;\n if (!current || current.status?.type === \"running\") {\n ctx.applyUpdate({ status: { type: \"complete\", reason: \"unknown\" } });\n }\n }\n\n private buildRunInput(\n runId: string,\n runConfig: RunConfig | undefined,\n historyMessages: readonly ThreadMessage[] | undefined,\n resume?: AgUiResumeEntry[],\n ) {\n const threadId = this.agent.threadId || \"main\";\n const messages = toAgUiMessages(\n historyMessages ?? this.repository.getMessages(),\n );\n const context = this.runtime?.thread.getModelContext();\n return {\n threadId,\n runId,\n state: this.stateSnapshot ?? null,\n messages,\n tools: toAgUiTools(context?.tools),\n context: context?.system\n ? [{ description: \"system\", value: context.system }]\n : [],\n forwardedProps: {\n ...(context?.callSettings ?? {}),\n ...(context?.config ?? {}),\n ...(runConfig?.custom ? { runConfig: runConfig.custom } : {}),\n },\n ...(resume !== undefined ? { resume } : {}),\n };\n }\n\n private installResumeShim(): void {\n const agent = this.agent as any;\n if (agent[symbolResumeShim]) return;\n agent[symbolResumeShim] = true;\n const onInstance = Object.hasOwn(agent, \"prepareRunAgentInput\");\n const original = onInstance\n ? agent.prepareRunAgentInput\n : Object.getPrototypeOf(agent)?.prepareRunAgentInput;\n if (typeof original !== \"function\") return;\n agent.prepareRunAgentInput = function (\n this: unknown,\n params: { resume?: unknown } | undefined,\n ) {\n const input = original.call(this, params);\n if (params?.resume !== undefined && input && typeof input === \"object\") {\n return { ...(input as object), resume: params.resume };\n }\n return input;\n };\n }\n\n private setRunning(running: boolean) {\n this.isRunningFlag = running;\n this.notifyUpdate();\n }\n\n private finishRun(controller: AbortController | null) {\n if (this.abortController === controller) {\n this.abortController = null;\n }\n this.setRunning(false);\n }\n\n private insertAssistantPlaceholder(parentId: string | null): string {\n const id = generateOptimisticId();\n const assistant: ThreadAssistantMessage = {\n id,\n role: \"assistant\",\n createdAt: new Date(),\n status: { type: \"running\" },\n content: [],\n metadata: {\n unstable_state: this.stateSnapshot ?? null,\n unstable_annotations: [],\n unstable_data: [],\n steps: [],\n isOptimistic: true,\n custom: {},\n },\n };\n this.addOrUpdateMessage(parentId ?? this.repository.headId, assistant);\n this.switchToBranch(id);\n this.notifyUpdate();\n return id;\n }\n\n private reassignAssistantId(oldId: string, newId: string): boolean {\n if (oldId === newId) return true;\n const oldItem = this.tryGetMessage(oldId);\n if (!oldItem) return false;\n\n const collidesWithExisting = this.hasMessage(newId);\n\n if (collidesWithExisting) {\n this.logger.debug?.(\n \"[agui] reassignAssistantId: server id already present in messages or repository, dropping placeholder\",\n { oldId, newId },\n );\n this.deleteMessage(oldId, oldItem.parentId ?? null);\n } else {\n const { isOptimistic: _, ...metadata } = oldItem.message.metadata;\n this.addOrUpdateMessage(oldItem.parentId, {\n ...oldItem.message,\n id: newId,\n metadata,\n } as ThreadMessage);\n this.switchToBranch(newId);\n this.tryDeleteMessage(oldId);\n }\n\n const pendingParent = this.assistantHistoryParents.get(oldId);\n if (pendingParent !== undefined) {\n this.assistantHistoryParents.delete(oldId);\n if (!collidesWithExisting && !this.assistantHistoryParents.has(newId)) {\n this.assistantHistoryParents.set(newId, pendingParent);\n }\n }\n\n if (this.recordedHistoryIds.has(oldId)) {\n this.recordedHistoryIds.delete(oldId);\n if (!collidesWithExisting) {\n this.recordedHistoryIds.add(newId);\n }\n }\n\n this.notifyUpdate();\n return !collidesWithExisting;\n }\n\n private updateAssistantMessage(\n messageId: string,\n update: ChatModelRunResult,\n ): string {\n let latestStatus: MessageStatus | undefined;\n const touched = this.updateMessage(messageId, (message) => {\n if (message.role !== \"assistant\") return message;\n const assistant = message as ThreadAssistantMessage;\n const metadata = update.metadata\n ? this.mergeAssistantMetadata(assistant.metadata, update.metadata)\n : assistant.metadata;\n latestStatus = update.status ?? assistant.status;\n const content =\n update.content !== undefined\n ? this.preserveToolResults(\n assistant.content,\n update.content as ThreadAssistantMessage[\"content\"],\n )\n : assistant.content;\n return {\n ...assistant,\n content,\n status: latestStatus,\n metadata,\n };\n });\n if (!touched) return messageId;\n\n let resolvedMessageId = messageId;\n const isSettled =\n latestStatus !== undefined && latestStatus.type !== \"running\";\n if (isSettled && isOptimisticId(messageId)) {\n const stableId = generateId();\n this.reassignAssistantId(messageId, stableId);\n resolvedMessageId = stableId;\n } else {\n this.notifyUpdate();\n }\n if (this.isPersistableStatus(latestStatus)) {\n this.persistAssistantHistory(resolvedMessageId);\n }\n this.maybeResumeAfterToolResults(resolvedMessageId);\n return resolvedMessageId;\n }\n\n // The RunAggregator rebuilds the assistant content from stream events only,\n // so a fresh snapshot omits results injected via addToolResult (frontend tool\n // execution). Carry those results forward so the aggregator never clobbers\n // them. Results are only ever added in this flow, so preserving is safe.\n private preserveToolResults(\n previous: ThreadAssistantMessage[\"content\"],\n next: ThreadAssistantMessage[\"content\"],\n ): ThreadAssistantMessage[\"content\"] {\n const resolved = new Map<string, ToolCallMessagePart>();\n for (const part of previous) {\n if (part.type === \"tool-call\" && isResolvedToolCall(part)) {\n resolved.set(part.toolCallId, part);\n }\n }\n if (resolved.size === 0) return next;\n\n let changed = false;\n const merged = next.map((part) => {\n if (part.type !== \"tool-call\" || isResolvedToolCall(part)) return part;\n const prior = resolved.get(part.toolCallId);\n if (!prior) return part;\n changed = true;\n return {\n ...part,\n result: prior.result,\n ...(prior.artifact !== undefined ? { artifact: prior.artifact } : {}),\n ...(prior.isError !== undefined ? { isError: prior.isError } : {}),\n };\n });\n return changed ? (merged as ThreadAssistantMessage[\"content\"]) : next;\n }\n\n private mergeAssistantMetadata(\n current: ThreadAssistantMessage[\"metadata\"],\n incoming: NonNullable<ChatModelRunResult[\"metadata\"]>,\n ): ThreadAssistantMessage[\"metadata\"] {\n const annotations = incoming.unstable_annotations\n ? [...current.unstable_annotations, ...incoming.unstable_annotations]\n : current.unstable_annotations;\n const data = incoming.unstable_data\n ? [...current.unstable_data, ...incoming.unstable_data]\n : current.unstable_data;\n const steps = incoming.steps\n ? [...current.steps, ...incoming.steps]\n : current.steps;\n return {\n unstable_state:\n incoming.unstable_state !== undefined\n ? incoming.unstable_state\n : current.unstable_state,\n unstable_annotations: annotations,\n unstable_data: data,\n steps,\n ...(current.isOptimistic ? { isOptimistic: true } : {}),\n ...(incoming.timing ? { timing: incoming.timing } : {}),\n custom: incoming.custom\n ? { ...current.custom, ...incoming.custom }\n : current.custom,\n };\n }\n\n private handleEvent(aggregator: RunAggregator, event: AgUiEvent) {\n switch (event.type) {\n case \"STATE_SNAPSHOT\": {\n this.stateSnapshot = event.snapshot as ReadonlyJSONValue;\n this.notifyUpdate();\n return;\n }\n case \"STATE_DELTA\": {\n if (event.delta.length === 0) return;\n try {\n const state = this.stateSnapshot ?? {};\n const result = jsonpatch.applyPatch(\n state,\n event.delta as Operation[],\n /* validateOperation */ true,\n /* mutateDocument */ false,\n );\n this.stateSnapshot = result.newDocument as ReadonlyJSONValue;\n this.notifyUpdate();\n } catch (error) {\n this.logger.error?.(\"[agui] failed to apply state delta\", error);\n }\n return;\n }\n case \"MESSAGES_SNAPSHOT\": {\n this.importMessagesSnapshot(event.messages);\n return;\n }\n case \"TOOL_CALL_RESULT\": {\n if (!aggregator.hasToolCall(event.toolCallId)) {\n const messageId = this.findMessageIdForToolCall(event.toolCallId);\n if (messageId !== undefined) {\n this.applyCrossRunToolResult(messageId, event);\n return;\n }\n }\n aggregator.handle(event);\n return;\n }\n case \"ACTIVITY_SNAPSHOT\": {\n const toolCallId = event.content[\"toolCallId\"];\n if (\n event.activityType === MCP_APPS_ACTIVITY_TYPE &&\n typeof toolCallId === \"string\" &&\n !aggregator.hasToolCall(toolCallId)\n ) {\n const messageId = this.findMessageIdForToolCall(toolCallId);\n if (messageId !== undefined) {\n this.applyCrossRunActivitySnapshot(messageId, toolCallId, event);\n return;\n }\n }\n aggregator.handle(event);\n return;\n }\n default:\n aggregator.handle(event);\n }\n }\n\n private applyCrossRunToolResult(\n messageId: string,\n event: Extract<AgUiEvent, { type: \"TOOL_CALL_RESULT\" }>,\n ): void {\n const updated = this.updateMessage(messageId, (message) => {\n if (message.role !== \"assistant\") return message;\n const assistant = message as ThreadAssistantMessage;\n let matchedToolCall = false;\n const content = assistant.content.map((part) => {\n if (part.type !== \"tool-call\" || part.toolCallId !== event.toolCallId)\n return part;\n matchedToolCall = true;\n // An applied activity snapshot owns part.result; a later result only\n // fills what is missing, mirroring the aggregator's finishToolCall.\n // The aggregator's flag is set only when the snapshot carried a\n // result, so app presence alone is not enough: the current result\n // must be CallToolResult-shaped (a required content array).\n const snapshotResultApplied =\n part.mcp?.app !== undefined &&\n isPlainObject(part.result) &&\n Array.isArray((part.result as Record<string, unknown>)[\"content\"]);\n if (snapshotResultApplied) {\n return {\n ...part,\n ...(part.modelContent === undefined && event.content\n ? {\n modelContent: [\n { type: \"text\" as const, text: event.content },\n ],\n }\n : {}),\n ...(part.isError === undefined\n ? typeof event.mcpResult?.isError === \"boolean\"\n ? { isError: event.mcpResult.isError }\n : event.role === \"tool\"\n ? { isError: false }\n : {}\n : {}),\n ...(event.messageId\n ? { unstable_toolMessageId: event.messageId }\n : {}),\n };\n }\n return {\n ...part,\n result: (event.mcpResult ??\n tryParseJSON(event.content ?? \"\")) as ReadonlyJSONValue,\n ...(event.mcpResult !== undefined\n ? { modelContent: [{ type: \"text\" as const, text: event.content }] }\n : {}),\n ...(typeof event.mcpResult?.isError === \"boolean\"\n ? { isError: event.mcpResult.isError }\n : event.role === \"tool\"\n ? { isError: false }\n : {}),\n ...(event.messageId\n ? { unstable_toolMessageId: event.messageId }\n : {}),\n };\n });\n if (!matchedToolCall) return message;\n return { ...assistant, content };\n });\n\n if (!updated) return;\n this.notifyUpdate();\n // Not maybeResumeAfterToolResults: the delivering run is already in\n // flight, and a resume from the owner would reset the head past it.\n this.maybeCompleteAfterToolResults(messageId);\n }\n\n private applyCrossRunActivitySnapshot(\n messageId: string,\n toolCallId: string,\n event: Extract<AgUiEvent, { type: \"ACTIVITY_SNAPSHOT\" }>,\n ): void {\n const resourceUri = event.content[\"resourceUri\"];\n if (typeof resourceUri !== \"string\" || !isMcpAppUri(resourceUri)) return;\n const serverId = event.content[\"serverId\"];\n const serverHash = event.content[\"serverHash\"];\n const appServerId =\n typeof serverId === \"string\" && serverId.length > 0\n ? serverId\n : typeof serverHash === \"string\" && serverHash.length > 0\n ? serverHash\n : undefined;\n const result = event.content[\"result\"];\n const updated = this.updateMessage(messageId, (message) => {\n if (message.role !== \"assistant\") return message;\n const assistant = message as ThreadAssistantMessage;\n let matchedToolCall = false;\n const content = assistant.content.map((part) => {\n if (part.type !== \"tool-call\" || part.toolCallId !== toolCallId)\n return part;\n matchedToolCall = true;\n return {\n ...part,\n mcp: {\n app: {\n resourceUri,\n ...(appServerId ? { serverId: appServerId } : {}),\n },\n },\n ...(isPlainObject(result)\n ? {\n ...(part.result !== undefined && part.modelContent === undefined\n ? {\n modelContent: [\n {\n type: \"text\" as const,\n text:\n typeof part.result === \"string\"\n ? part.result\n : JSON.stringify(part.result),\n },\n ],\n }\n : {}),\n result: result as ReadonlyJSONValue,\n isError: result[\"isError\"] === true,\n }\n : {}),\n };\n });\n if (!matchedToolCall) return message;\n return { ...assistant, content };\n });\n\n if (!updated) return;\n this.notifyUpdate();\n this.maybeCompleteAfterToolResults(messageId);\n }\n\n private importMessagesSnapshot(rawMessages: readonly unknown[]) {\n try {\n const normalized = fromAgUiMessages(rawMessages, {\n showThinking: this.showThinking,\n });\n const converted: ThreadMessage[] = [];\n for (const message of normalized) {\n try {\n converted.push(\n fromThreadMessageLike(message, generateId(), FALLBACK_USER_STATUS),\n );\n } catch (error) {\n this.logger.error?.(\n \"[agui] failed to import message from snapshot\",\n error,\n );\n }\n }\n this.applyExternalMessages(converted);\n } catch (error) {\n this.logger.error?.(\"[agui] failed to import messages snapshot\", error);\n }\n }\n\n private toThreadMessage(message: AppendMessage): ThreadMessage {\n return fromThreadMessageLike(\n message as any,\n generateId(),\n FALLBACK_USER_STATUS,\n );\n }\n\n private isTerminalStatus(status?: MessageStatus): boolean {\n return status?.type === \"complete\" || status?.type === \"incomplete\";\n }\n\n private isPersistableStatus(status?: MessageStatus): boolean {\n if (this.isTerminalStatus(status)) return true;\n return status?.type === \"requires-action\" && status.reason === \"interrupt\";\n }\n\n private recordHistoryEntry(parentId: string | null, message: ThreadMessage) {\n this.appendHistoryItem(parentId, message);\n }\n\n private markPendingAssistantHistory(\n messageId: string,\n parentId: string | null,\n ) {\n if (!this.history) return;\n this.assistantHistoryParents.set(messageId, parentId);\n }\n\n private persistAssistantHistory(messageId: string) {\n if (!this.history) return;\n const parentId = this.assistantHistoryParents.get(messageId);\n if (parentId === undefined) return;\n const message = this.tryGetMessage(messageId)?.message;\n if (!message || message.role !== \"assistant\") return;\n if (!this.isPersistableStatus(message.status)) return;\n this.assistantHistoryParents.delete(messageId);\n this.appendHistoryItem(parentId, message);\n }\n\n private appendHistoryItem(parentId: string | null, message: ThreadMessage) {\n if (!this.history || this.recordedHistoryIds.has(message.id)) return;\n this.recordedHistoryIds.add(message.id);\n void this.history.append({ parentId, message }).catch((error) => {\n this.recordedHistoryIds.delete(message.id);\n this.logger.error?.(\"[agui] failed to append history entry\", error);\n });\n }\n}\n"],"mappings":";;;;;;;;AA0CA,MAAM,mBAAmB;AACzB,MAAM,6BAA6B,GAAG,mBAAmB,WAAW;AACpE,MAAM,kBAAkB,OAAe,GAAG,WAAW,gBAAgB;AAErE,MAAM,sBACJ,SAEA,KAAK,SAAS,eAAe,YAAY,QAAQ,KAAK,WAAW,KAAA;AAEnE,MAAM,mBAAmB,OAAO,kBAAkB;AAwBlD,MAAM,uBAAuB;CAAE,MAAM;CAAY,QAAQ;AAAU;AAEnE,IAAa,wBAAb,MAAmC;CACjC;CACA;CACA;CACA;CACA;CACA;CACA;CAEA;CACA,aAA8B,IAAI,kBAAkB;CACpD;CACA,gBAAwB;CACxB,kBAAkD;CAClD;CACA,eAAqC;CACrC;CACA;CACA,0CAA2C,IAAI,IAA2B;CAC1E,qCAAsC,IAAI,IAAY;CACtD,aAAqB;CACrB;CACA,yBAAgD;CAEhD,YAAY,SAAsB;EAChC,KAAK,QAAQ,QAAQ;EACrB,KAAK,SAAS,QAAQ;EACtB,KAAK,eAAe,QAAQ;E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OAAO,QAAQ,EAAE;GACzC,KAAK,OAAO,QAAQ,yCAAyC,KAAK;EACpE,CAAC;CACH;AACF"}
1
+ {"version":3,"file":"AgUiThreadRuntimeCore.js","names":[],"sources":["../../src/runtime/AgUiThreadRuntimeCore.ts"],"sourcesContent":["\"use client\";\n\nimport {\n generateId,\n fromThreadMessageLike,\n isMcpAppUri,\n} from \"@assistant-ui/core\";\nimport type {\n AddToolResultOptions,\n AppendMessage,\n CreateAppendMessage,\n AssistantRuntime,\n ChatModelRunOptions,\n ChatModelRunResult,\n ExportedMessageRepository,\n MessageStatus,\n ThreadAssistantMessage,\n ThreadHistoryAdapter,\n ThreadMessage,\n ToolCallMessagePart,\n} from \"@assistant-ui/core\";\nimport { MessageRepository } from \"@assistant-ui/core/internal\";\nimport type { AbstractAgent } from \"@ag-ui/client\";\nimport jsonpatch, { type Operation } from \"fast-json-patch\";\nimport type { Logger } from \"./logger\";\nimport { readMcpAppResourceUri } from \"./mcp-tool-result\";\nimport type { AgUiEvent, AgUiInterrupt, AgUiResumeEntry } from \"./types\";\nimport type { ReadonlyJSONValue } from \"assistant-stream/utils\";\nimport {\n AG_UI_METADATA_NAMESPACE,\n type AgUiCustomMetadata,\n isPlainObject,\n MCP_APPS_ACTIVITY_TYPE,\n RunAggregator,\n tryParseJSON,\n} from \"./adapter/run-aggregator\";\nimport {\n fromAgUiMessages,\n toAgUiMessages,\n toAgUiTools,\n} from \"./adapter/conversions\";\nimport { createAgUiSubscriber } from \"./adapter/subscriber\";\n\nconst optimisticPrefix = \"__optimistic__\";\nconst generateOptimisticId = () => `${optimisticPrefix}${generateId()}`;\nconst isOptimisticId = (id: string) => id.startsWith(optimisticPrefix);\n\nconst isResolvedToolCall = (\n part: ThreadAssistantMessage[\"content\"][number],\n): boolean =>\n part.type === \"tool-call\" && \"result\" in part && part.result !== undefined;\n\nconst symbolResumeShim = Symbol(\"agui-resume-shim\");\n\ntype RunConfig = NonNullable<AppendMessage[\"runConfig\"]>;\ntype ResumeStream = (\n options: ChatModelRunOptions,\n) => AsyncGenerator<ChatModelRunResult, void, unknown>;\ntype ResumeRunConfig = {\n parentId: string | null;\n sourceId: string | null;\n runConfig: RunConfig;\n stream?: ResumeStream;\n};\n\ntype CoreOptions = {\n agent: AbstractAgent;\n logger: Logger;\n showThinking: boolean;\n autoCancelPendingToolCalls?: boolean | undefined;\n onError?: (error: Error) => void;\n onCancel?: () => void;\n history?: ThreadHistoryAdapter;\n notifyUpdate: () => void;\n};\n\nconst FALLBACK_USER_STATUS = { type: \"complete\", reason: \"unknown\" } as const;\n\nexport class AgUiThreadRuntimeCore {\n private agent: AbstractAgent;\n private logger: Logger;\n private showThinking: boolean;\n private autoCancelPendingToolCalls: boolean | undefined;\n private onError: ((error: Error) => void) | undefined;\n private onCancel: (() => void) | undefined;\n private readonly notifyUpdate: () => void;\n\n private runtime: AssistantRuntime | undefined;\n private readonly repository = new MessageRepository();\n private exportedRepository: ExportedMessageRepository | undefined;\n private isRunningFlag = false;\n private abortController: AbortController | null = null;\n private stateSnapshot: ReadonlyJSONValue | undefined;\n private pendingError: Error | null = null;\n private history: ThreadHistoryAdapter | undefined;\n private lastRunConfig: RunConfig | undefined;\n private readonly assistantHistoryParents = new Map<string, string | null>();\n private readonly recordedHistoryIds = new Set<string>();\n private _isLoading = false;\n private _loadPromise: Promise<void> | undefined;\n private pendingResumeMessageId: string | null = null;\n\n constructor(options: CoreOptions) {\n this.agent = options.agent;\n this.logger = options.logger;\n this.showThinking = options.showThinking;\n this.autoCancelPendingToolCalls = options.autoCancelPendingToolCalls;\n this.onError = options.onError;\n this.onCancel = options.onCancel;\n this.history = options.history;\n this.notifyUpdate = options.notifyUpdate;\n this.installResumeShim();\n }\n\n updateOptions(options: Omit<CoreOptions, \"notifyUpdate\">) {\n this.agent = options.agent;\n this.logger = options.logger;\n this.showThinking = options.showThinking;\n this.autoCancelPendingToolCalls = options.autoCancelPendingToolCalls;\n this.onError = options.onError;\n this.onCancel = options.onCancel;\n this.history = options.history;\n this.installResumeShim();\n }\n\n attachRuntime(runtime: AssistantRuntime) {\n this.runtime = runtime;\n }\n\n detachRuntime() {\n this.runtime = undefined;\n }\n\n getMessages(): readonly ThreadMessage[] {\n return this.repository.getMessages();\n }\n\n getMessageRepository(): ExportedMessageRepository {\n if (this.exportedRepository) return this.exportedRepository;\n\n const exportedRepository = this.repository.export();\n let parentId: string | null = null;\n for (const message of this.repository.getMessages()) {\n if (message.metadata.isOptimistic) {\n exportedRepository.messages.push({ parentId, message });\n }\n parentId = message.id;\n }\n\n this.exportedRepository = {\n ...exportedRepository,\n headId: this.repository.headId,\n };\n return this.exportedRepository;\n }\n\n private tryGetMessage(messageId: string) {\n try {\n return this.repository.getMessage(messageId);\n } catch {\n return undefined;\n }\n }\n\n private tryGetMessages(\n messageId: string,\n ): readonly ThreadMessage[] | undefined {\n try {\n return this.repository.getMessages(messageId);\n } catch {\n return undefined;\n }\n }\n\n private hasMessage(messageId: string): boolean {\n return this.tryGetMessage(messageId) !== undefined;\n }\n\n private addOrUpdateMessage(\n parentId: string | null,\n message: ThreadMessage,\n ): void {\n this.repository.addOrUpdateMessage(parentId, message);\n this.exportedRepository = undefined;\n }\n\n private deleteMessage(\n messageId: string,\n replacementId?: string | null,\n ): void {\n this.repository.deleteMessage(messageId, replacementId);\n this.exportedRepository = undefined;\n }\n\n private tryDeleteMessage(messageId: string): boolean {\n if (!this.hasMessage(messageId)) return false;\n this.deleteMessage(messageId);\n return true;\n }\n\n private switchToBranch(messageId: string): void {\n this.repository.switchToBranch(messageId);\n this.exportedRepository = undefined;\n }\n\n private resetRepositoryHead(messageId: string | null): void {\n this.repository.resetHead(messageId);\n this.exportedRepository = undefined;\n }\n\n private clearRepository(): void {\n this.repository.clear();\n this.exportedRepository = undefined;\n }\n\n private updateMessage(\n messageId: string,\n updater: (message: ThreadMessage) => ThreadMessage,\n ): boolean {\n const item = this.tryGetMessage(messageId);\n if (!item) return false;\n const message = updater(item.message);\n if (message === item.message) return false;\n this.addOrUpdateMessage(item.parentId, message);\n return true;\n }\n\n getState(): ReadonlyJSONValue | undefined {\n return this.stateSnapshot;\n }\n\n isRunning(): boolean {\n return this.isRunningFlag;\n }\n\n get isLoading(): boolean {\n return this._isLoading;\n }\n\n __internal_load(): Promise<void> {\n if (this._loadPromise) return this._loadPromise;\n\n const promise = this.history?.load() ?? Promise.resolve(null);\n\n this._isLoading = true;\n\n this._loadPromise = promise\n .then(async (repo) => {\n if (!repo) return;\n\n this.applyExternalMessageRepository(repo);\n\n if (repo.state !== undefined) {\n this.loadExternalState(repo.state);\n }\n\n if (repo.unstable_resume) {\n const parentId = repo.headId ?? this.repository.headId;\n const resumeStream = this.history?.resume?.bind(this.history);\n await this.startRun(\n parentId,\n this.lastRunConfig,\n undefined,\n resumeStream,\n );\n }\n })\n .catch((error) => {\n this.logger.error?.(\"[agui] failed to load history\", error);\n this.onError?.(\n error instanceof Error ? error : new Error(String(error)),\n );\n })\n .finally(() => {\n this._isLoading = false;\n this.notifyUpdate();\n });\n\n this.notifyUpdate();\n return this._loadPromise;\n }\n\n async append(message: AppendMessage): Promise<void> {\n const startRun = message.startRun ?? message.role === \"user\";\n if (startRun) {\n this.assertNoPendingInterrupts();\n this.maybeAutoCancelPendingToolCalls();\n }\n const threadMessageId = this.appendEntry(message);\n if (!startRun) return;\n await this.startRun(threadMessageId, message.runConfig);\n }\n\n private maybeAutoCancelPendingToolCalls(): void {\n if (this.autoCancelPendingToolCalls === false) return;\n const pending = this.getPendingToolCalls();\n if (!pending) return;\n this.cancelUnresolvedToolCalls(pending.messageId);\n this.maybeCompleteAfterToolResults(pending.messageId);\n }\n\n private appendEntry(message: AppendMessage): string {\n if (message.sourceId) this.tryDeleteMessage(message.sourceId);\n\n const threadMessage = this.toThreadMessage(message);\n const parentId =\n message.parentId === null\n ? null\n : message.parentId && this.hasMessage(message.parentId)\n ? message.parentId\n : this.repository.headId;\n this.addOrUpdateMessage(parentId, threadMessage);\n this.switchToBranch(threadMessage.id);\n this.notifyUpdate();\n this.recordHistoryEntry(parentId, threadMessage);\n return threadMessage.id;\n }\n\n async edit(message: AppendMessage): Promise<void> {\n await this.append(message);\n }\n\n async reload(\n parentId: string | null,\n config: { runConfig?: RunConfig } = {},\n ): Promise<void> {\n this.assertNoPendingInterrupts();\n this.maybeAutoCancelPendingToolCalls();\n await this.startRun(parentId, config.runConfig);\n }\n\n async cancel(): Promise<void> {\n if (!this.abortController) return;\n this.abortController.abort();\n }\n\n async resume(config: ResumeRunConfig): Promise<void> {\n this.assertNoPendingInterrupts();\n await this.startRun(\n config.parentId,\n config.runConfig ?? this.lastRunConfig,\n undefined,\n config.stream,\n );\n }\n\n async resumeInFlightRun(messages: readonly ThreadMessage[]): Promise<void> {\n // Without a resume stream startRun would re-run the agent from scratch.\n const resumeStream = this.history?.resume?.bind(this.history);\n if (!resumeStream) {\n const error = new Error(\n \"[agui] unstable_resume requires a ThreadHistoryAdapter with a resume() method; skipping resume after thread switch\",\n );\n this.logger.error?.(error.message);\n this.onError?.(error);\n return;\n }\n const parentId = messages.at(-1)?.id ?? null;\n try {\n await this.startRun(\n parentId,\n this.lastRunConfig,\n undefined,\n resumeStream,\n );\n } catch {\n // startRun already reported via onError; don't reject the switch.\n }\n }\n\n private assertNoPendingInterrupts(): void {\n if (!this.getPendingInterrupts()) return;\n throw new Error(\n \"[agui] cannot start a new run while interrupts are pending; resolve them with submitInterruptResponses()\",\n );\n }\n\n private findRequiresActionAssistant(\n reason: \"interrupt\" | \"tool-calls\",\n ): ThreadAssistantMessage | null {\n const assistant = this.getMessages().findLast(\n (message) => message.role === \"assistant\",\n ) as ThreadAssistantMessage | undefined;\n if (\n !assistant ||\n assistant.status?.type !== \"requires-action\" ||\n assistant.status.reason !== reason\n ) {\n return null;\n }\n return assistant;\n }\n\n getPendingInterrupts(): {\n messageId: string;\n interrupts: readonly AgUiInterrupt[];\n } | null {\n const assistant = this.findRequiresActionAssistant(\"interrupt\");\n if (!assistant) return null;\n const stored = (\n assistant.metadata.custom[AG_UI_METADATA_NAMESPACE] as\n | AgUiCustomMetadata\n | undefined\n )?.interrupts;\n if (!stored?.length) return null;\n return { messageId: assistant.id, interrupts: stored };\n }\n\n getPendingToolCalls(): {\n messageId: string;\n toolCallIds: string[];\n } | null {\n const assistant = this.findRequiresActionAssistant(\"tool-calls\");\n if (!assistant) return null;\n const toolCallIds: string[] = [];\n for (const part of assistant.content) {\n if (part.type !== \"tool-call\") continue;\n if (isResolvedToolCall(part)) continue;\n toolCallIds.push(part.toolCallId);\n }\n if (toolCallIds.length === 0) return null;\n return { messageId: assistant.id, toolCallIds };\n }\n\n async submitInterruptResponses(\n responses: readonly AgUiResumeEntry[],\n ): Promise<void> {\n const pending = this.getPendingInterrupts();\n if (!pending) {\n throw new Error(\n \"[agui] submitInterruptResponses: no pending interrupts on this thread\",\n );\n }\n\n const responsesById = this.collectInterruptResponses(\n \"submitInterruptResponses\",\n pending.interrupts,\n responses,\n );\n\n const openIds = pending.interrupts.map((i) => i.id);\n const missing = openIds.filter((id) => !responsesById.has(id));\n if (missing.length > 0) {\n throw new Error(\n `[agui] submitInterruptResponses: missing responses for open interrupts: ${missing.join(\", \")}`,\n );\n }\n\n const now = Date.now();\n for (const interrupt of pending.interrupts) {\n if (!interrupt.expiresAt) continue;\n const expiry = new Date(interrupt.expiresAt).getTime();\n if (Number.isNaN(expiry)) {\n throw new Error(\n `[agui] submitInterruptResponses: interrupt ${interrupt.id} has malformed expiresAt \"${interrupt.expiresAt}\"`,\n );\n }\n if (expiry <= now) {\n throw new Error(\n `[agui] submitInterruptResponses: interrupt ${interrupt.id} expired at ${interrupt.expiresAt}`,\n );\n }\n }\n\n const resume: AgUiResumeEntry[] = openIds.map((id) =>\n responsesById.get(id)!,\n );\n\n if (this.isRunningFlag) {\n throw new Error(\n \"[agui] submitInterruptResponses: a run is already in progress\",\n );\n }\n\n this.clearPendingInterrupts(pending.messageId);\n await this.startRun(pending.messageId, this.lastRunConfig, resume);\n }\n\n async steerAway(\n message: CreateAppendMessage,\n responses?: readonly AgUiResumeEntry[],\n ): Promise<void> {\n const pending = this.getPendingInterrupts();\n if (!pending) {\n const pendingTools = this.getPendingToolCalls();\n if (pendingTools) {\n if (responses?.length) {\n throw new Error(\n \"[agui] steerAway: responses are only valid for pending interrupts\",\n );\n }\n if (this.isRunningFlag) {\n throw new Error(\"[agui] steerAway: a run is already in progress\");\n }\n this.cancelUnresolvedToolCalls(pendingTools.messageId);\n this.maybeCompleteAfterToolResults(pendingTools.messageId);\n const normalized = this.toAppendMessage(message);\n const threadMessageId = this.appendEntry(normalized);\n await this.startRun(threadMessageId, normalized.runConfig);\n return;\n }\n if (responses?.length) {\n throw new Error(\n \"[agui] steerAway: no pending interrupts on this thread\",\n );\n }\n await this.append(this.toAppendMessage(message));\n return;\n }\n\n const resume = this.resolveSteerAwayResume(pending.interrupts, responses);\n\n if (this.isRunningFlag) {\n throw new Error(\"[agui] steerAway: a run is already in progress\");\n }\n\n const normalized = this.toAppendMessage(message);\n this.clearPendingInterrupts(pending.messageId);\n const threadMessageId = this.appendEntry(normalized);\n await this.startRun(threadMessageId, normalized.runConfig, resume);\n }\n\n private resolveSteerAwayResume(\n interrupts: readonly AgUiInterrupt[],\n responses: readonly AgUiResumeEntry[] | undefined,\n ): AgUiResumeEntry[] {\n const responsesById = this.collectInterruptResponses(\n \"steerAway\",\n interrupts,\n responses ?? [],\n );\n return interrupts.map(\n (interrupt) =>\n responsesById.get(interrupt.id) ?? {\n interruptId: interrupt.id,\n status: \"cancelled\",\n },\n );\n }\n\n private collectInterruptResponses(\n method: \"submitInterruptResponses\" | \"steerAway\",\n interrupts: readonly AgUiInterrupt[],\n responses: readonly AgUiResumeEntry[],\n ): Map<string, AgUiResumeEntry> {\n const known = new Set(interrupts.map((interrupt) => interrupt.id));\n const responsesById = new Map<string, AgUiResumeEntry>();\n for (const entry of responses) {\n if (!entry || typeof entry.interruptId !== \"string\") {\n throw new Error(\n `[agui] ${method}: every entry must have an interruptId`,\n );\n }\n if (entry.status !== \"resolved\" && entry.status !== \"cancelled\") {\n throw new Error(\n `[agui] ${method}: invalid status \"${entry.status}\" for interrupt ${entry.interruptId}`,\n );\n }\n if (!known.has(entry.interruptId)) {\n throw new Error(\n `[agui] ${method}: unknown interrupt id ${entry.interruptId}`,\n );\n }\n if (responsesById.has(entry.interruptId)) {\n throw new Error(\n `[agui] ${method}: duplicate response for interrupt ${entry.interruptId}`,\n );\n }\n responsesById.set(entry.interruptId, entry);\n }\n return responsesById;\n }\n\n private toAppendMessage(message: CreateAppendMessage): AppendMessage {\n if (typeof message === \"string\") {\n return {\n createdAt: new Date(),\n parentId: this.repository.headId,\n sourceId: null,\n runConfig: {},\n role: \"user\",\n content: [{ type: \"text\", text: message }],\n attachments: [],\n metadata: { custom: {} },\n };\n }\n return {\n createdAt: message.createdAt ?? new Date(),\n parentId: message.parentId ?? this.repository.headId,\n sourceId: message.sourceId ?? null,\n role: message.role ?? \"user\",\n content: message.content,\n attachments: message.attachments ?? [],\n metadata: message.metadata ?? { custom: {} },\n runConfig: message.runConfig ?? {},\n startRun: message.startRun,\n } as AppendMessage;\n }\n\n private clearPendingInterrupts(messageId: string): void {\n const touched = this.updateMessage(messageId, (message) => {\n if (message.role !== \"assistant\") return message;\n const assistant = message as ThreadAssistantMessage;\n if (\n assistant.status?.type !== \"requires-action\" ||\n assistant.status.reason !== \"interrupt\"\n ) {\n return assistant;\n }\n const aguiMeta = assistant.metadata.custom[AG_UI_METADATA_NAMESPACE] as\n | AgUiCustomMetadata\n | undefined;\n const { interrupts: _drop, ...restAgui } = aguiMeta ?? {};\n const newCustom = { ...assistant.metadata.custom };\n if (Object.keys(restAgui).length > 0) {\n newCustom[AG_UI_METADATA_NAMESPACE] = restAgui;\n } else {\n delete newCustom[AG_UI_METADATA_NAMESPACE];\n }\n return {\n ...assistant,\n status: { type: \"complete\" as const, reason: \"unknown\" as const },\n metadata: { ...assistant.metadata, custom: newCustom },\n };\n });\n if (touched) {\n this.notifyUpdate();\n }\n }\n\n findMessageIdForToolCall(toolCallId: string): string | undefined {\n let fallbackMessageId: string | undefined;\n const messages = this.getMessages();\n for (let index = messages.length - 1; index >= 0; index--) {\n const message = messages[index];\n if (!message || message.role !== \"assistant\") continue;\n for (const part of message.content) {\n if (part.type !== \"tool-call\" || part.toolCallId !== toolCallId)\n continue;\n if (!isResolvedToolCall(part)) {\n return message.id;\n }\n fallbackMessageId ??= message.id;\n }\n }\n return fallbackMessageId;\n }\n\n private cancelUnresolvedToolCalls(messageId: string): void {\n const updated = this.updateMessage(messageId, (message) => {\n if (message.role !== \"assistant\") return message;\n const assistant = message as ThreadAssistantMessage;\n const content = assistant.content.map((part) => {\n if (part.type !== \"tool-call\" || isResolvedToolCall(part)) return part;\n return {\n ...part,\n result: { error: \"Tool call cancelled by user\" },\n isError: true,\n };\n });\n return { ...assistant, content };\n });\n if (updated) this.notifyUpdate();\n }\n\n addToolResult(options: AddToolResultOptions): void {\n const updated = this.updateMessage(options.messageId, (message) => {\n if (message.role !== \"assistant\") return message;\n const assistant = message as ThreadAssistantMessage;\n let matchedToolCall = false;\n const content = assistant.content.map((part) => {\n if (part.type !== \"tool-call\" || part.toolCallId !== options.toolCallId)\n return part;\n matchedToolCall = true;\n return {\n ...part,\n result: options.result,\n artifact: options.artifact,\n isError: options.isError,\n };\n });\n if (!matchedToolCall) return message;\n return { ...assistant, content };\n });\n\n if (!updated) return;\n this.notifyUpdate();\n this.maybeResumeAfterToolResults(options.messageId);\n }\n\n // The continuation fires whether the frontend result lands before\n // RUN_FINISHED (the status flips to requires-action only later, while the\n // run is still draining) or after it.\n private maybeResumeAfterToolResults(messageId: string): void {\n if (!this.maybeCompleteAfterToolResults(messageId)) return;\n\n if (this.isRunningFlag) {\n // A run is still draining (RUN_FINISHED arrived but the stream has not\n // closed). Defer until startRun's tail so we never start two runs.\n this.pendingResumeMessageId = messageId;\n return;\n }\n this.startResumeRun(messageId);\n }\n\n private maybeCompleteAfterToolResults(messageId: string): boolean {\n const message = this.tryGetMessage(messageId)?.message;\n if (!message || message.role !== \"assistant\") return false;\n const assistant = message as ThreadAssistantMessage;\n if (\n assistant.status?.type !== \"requires-action\" ||\n assistant.status.reason !== \"tool-calls\"\n ) {\n return false;\n }\n const allResolved = assistant.content.every(\n (part) => part.type !== \"tool-call\" || isResolvedToolCall(part),\n );\n if (!allResolved) return false;\n\n const updated = this.updateMessage(messageId, (current) =>\n current.role === \"assistant\"\n ? {\n ...(current as ThreadAssistantMessage),\n status: { type: \"complete\" as const, reason: \"unknown\" as const },\n }\n : current,\n );\n if (!updated) return false;\n this.notifyUpdate();\n this.persistAssistantHistory(messageId);\n return true;\n }\n\n private startResumeRun(messageId: string): void {\n void this.startRun(messageId, this.lastRunConfig).catch((error) => {\n this.onError?.(error instanceof Error ? error : new Error(String(error)));\n });\n }\n\n applyExternalMessages(messages: readonly ThreadMessage[]): void {\n this.assistantHistoryParents.clear();\n\n if (messages.length === 0) {\n this.clearRepository();\n } else {\n let expectedParentId: string | null = null;\n let lastAppliedId: string | null = null;\n let hardReplace = false;\n const seen = new Set<string>();\n\n for (const message of messages) {\n if (seen.has(message.id)) continue;\n seen.add(message.id);\n const existing = this.tryGetMessage(message.id);\n if (existing && existing.parentId !== expectedParentId) {\n hardReplace = true;\n break;\n }\n this.addOrUpdateMessage(expectedParentId, message);\n expectedParentId = message.id;\n lastAppliedId = message.id;\n }\n\n if (hardReplace) {\n this.clearRepository();\n expectedParentId = null;\n lastAppliedId = null;\n seen.clear();\n for (const message of messages) {\n if (seen.has(message.id)) continue;\n seen.add(message.id);\n this.addOrUpdateMessage(expectedParentId, message);\n expectedParentId = message.id;\n lastAppliedId = message.id;\n }\n }\n\n this.resetRepositoryHead(lastAppliedId);\n }\n\n this.recordedHistoryIds.clear();\n for (const { message } of this.getMessageRepository().messages) {\n this.recordedHistoryIds.add(message.id);\n }\n this.notifyUpdate();\n }\n\n private applyExternalMessageRepository(\n loaded: ExportedMessageRepository,\n ): void {\n const headId = loaded.headId ?? loaded.messages.at(-1)?.message.id ?? null;\n const ids = new Set<string>();\n let degenerate = false;\n for (const { message } of loaded.messages) {\n if (ids.has(message.id)) {\n degenerate = true;\n break;\n }\n ids.add(message.id);\n }\n if (headId !== null && !ids.has(headId)) degenerate = true;\n\n if (!degenerate) {\n this.clearRepository();\n let pending = [...loaded.messages];\n const importedIds = new Set<string>();\n\n while (pending.length > 0) {\n const unresolved: typeof pending = [];\n let progressed = false;\n for (const item of pending) {\n if (item.parentId !== null && !importedIds.has(item.parentId)) {\n unresolved.push(item);\n continue;\n }\n this.addOrUpdateMessage(item.parentId, item.message);\n importedIds.add(item.message.id);\n progressed = true;\n }\n if (!progressed) {\n degenerate = true;\n break;\n }\n pending = unresolved;\n }\n }\n\n if (degenerate) {\n this.clearRepository();\n let previousId: string | null = null;\n for (const { message } of loaded.messages) {\n const existing = this.tryGetMessage(message.id);\n this.addOrUpdateMessage(\n existing ? existing.parentId : previousId,\n message,\n );\n previousId = message.id;\n }\n this.resetRepositoryHead(previousId);\n } else {\n this.resetRepositoryHead(headId);\n }\n\n this.assistantHistoryParents.clear();\n this.recordedHistoryIds.clear();\n for (const { message } of loaded.messages) {\n this.recordedHistoryIds.add(message.id);\n }\n this.notifyUpdate();\n }\n\n loadExternalState(state: ReadonlyJSONValue): void {\n this.stateSnapshot = state;\n this.notifyUpdate();\n }\n\n setState(\n next:\n | ReadonlyJSONValue\n | ((prev: ReadonlyJSONValue | undefined) => ReadonlyJSONValue),\n ): void {\n this.stateSnapshot =\n typeof next === \"function\" ? next(this.stateSnapshot) : next;\n this.notifyUpdate();\n }\n\n resetState(): void {\n this.stateSnapshot = undefined;\n this.notifyUpdate();\n }\n\n private async startRun(\n parentId: string | null,\n runConfig?: RunConfig,\n resume?: AgUiResumeEntry[],\n resumeStream?: ResumeStream,\n ): Promise<void> {\n const normalizedRunConfig = runConfig ?? {};\n this.lastRunConfig = normalizedRunConfig;\n const parent = parentId === null ? undefined : this.tryGetMessage(parentId);\n const shouldEagerlyInsertAssistant =\n parentId !== null &&\n parent !== undefined &&\n parentId !== this.repository.headId;\n const historicalMessages = [\n ...(shouldEagerlyInsertAssistant\n ? (this.tryGetMessages(parentId) ?? this.repository.getMessages())\n : this.repository.getMessages()),\n ];\n\n this.pendingError = null;\n const assistantParentId = parent ? parentId : this.repository.headId;\n let assistantMessageId: string | undefined;\n const ensureAssistant = () => {\n if (assistantMessageId) return assistantMessageId;\n const created = this.insertAssistantPlaceholder(\n assistantParentId ?? null,\n );\n assistantMessageId = created;\n this.markPendingAssistantHistory(created, assistantParentId ?? null);\n return created;\n };\n\n if (shouldEagerlyInsertAssistant) ensureAssistant();\n\n const applyUpdate = (update: ChatModelRunResult) => {\n const resolved = this.updateAssistantMessage(ensureAssistant(), update);\n if (resolved !== assistantMessageId) {\n assistantMessageId = resolved;\n }\n };\n\n const aggregator = new RunAggregator({\n showThinking: this.showThinking,\n logger: this.logger,\n emit: applyUpdate,\n onServerMessageId: (serverId) => {\n const placeholder = ensureAssistant();\n if (placeholder === serverId) return;\n if (this.reassignAssistantId(placeholder, serverId)) {\n assistantMessageId = serverId;\n }\n },\n });\n const dispatch = (event: AgUiEvent) => this.handleEvent(aggregator, event);\n\n const abortController = new AbortController();\n const abortSignal = abortController.signal;\n this.abortController = abortController;\n\n let cancelRun = () => dispatch({ type: \"RUN_CANCELLED\" });\n abortSignal.addEventListener(\n \"abort\",\n () => {\n cancelRun();\n this.finishRun(abortController);\n this.onCancel?.();\n },\n { once: true },\n );\n\n this.setRunning(true);\n\n try {\n if (resumeStream) {\n // Cancel flips only the status; an aggregator RUN_CANCELLED would emit an empty snapshot and wipe the replayed content.\n cancelRun = () =>\n applyUpdate({ status: { type: \"incomplete\", reason: \"cancelled\" } });\n await this.consumeResumeStream(resumeStream, {\n runConfig: normalizedRunConfig,\n threadId: this.agent.threadId || \"main\",\n parentId: assistantParentId,\n historicalMessages,\n abortSignal,\n ensureAssistant,\n applyUpdate,\n getAssistantMessageId: () => assistantMessageId,\n });\n } else {\n const runId = generateId();\n aggregator.handle({ type: \"RUN_STARTED\", runId });\n const input = this.buildRunInput(\n runId,\n normalizedRunConfig,\n historicalMessages,\n resume,\n );\n const subscriber = createAgUiSubscriber({\n dispatch,\n runId,\n logger: this.logger,\n onRunFailed: (error) => {\n this.pendingError = error;\n this.onError?.(error);\n },\n });\n try {\n (this.agent as any).messages = input.messages;\n (this.agent as any).threadId = input.threadId;\n (this.agent as any).state = input.state ?? null;\n } catch {\n // ignore\n }\n await (this.agent as any).runAgent(input, subscriber, {\n signal: abortSignal,\n });\n }\n } catch (error) {\n if (!abortSignal.aborted) {\n const err = error instanceof Error ? error : new Error(String(error));\n dispatch({ type: \"RUN_ERROR\", message: err.message });\n this.onError?.(err);\n this.pendingError = this.pendingError ?? err;\n }\n } finally {\n this.finishRun(abortController);\n }\n\n if (this.pendingError) {\n const err = this.pendingError;\n this.pendingError = null;\n this.pendingResumeMessageId = null;\n throw err;\n }\n\n // A tool result that landed before the run settled deferred its\n // continuation here so a second run never overlaps the first.\n if (this.pendingResumeMessageId !== null) {\n const resumeMessageId = this.pendingResumeMessageId;\n this.pendingResumeMessageId = null;\n if (!abortSignal.aborted) {\n this.startResumeRun(resumeMessageId);\n }\n }\n }\n\n // Replays a persisted run's snapshots into the existing assistant message, bypassing agent.runAgent so it is not re-invoked.\n private async consumeResumeStream(\n stream: ResumeStream,\n ctx: {\n runConfig: RunConfig;\n threadId: string;\n parentId: string | null;\n historicalMessages: readonly ThreadMessage[];\n abortSignal: AbortSignal;\n ensureAssistant: () => string;\n applyUpdate: (update: ChatModelRunResult) => void;\n getAssistantMessageId: () => string | undefined;\n },\n ): Promise<void> {\n const assistantId = ctx.ensureAssistant();\n const currentId = () => ctx.getAssistantMessageId() ?? assistantId;\n const options: ChatModelRunOptions = {\n messages: ctx.historicalMessages,\n runConfig: ctx.runConfig,\n abortSignal: ctx.abortSignal,\n context: this.runtime?.thread.getModelContext() ?? {},\n unstable_assistantMessageId: assistantId,\n unstable_threadId: ctx.threadId,\n unstable_parentId: ctx.parentId,\n unstable_getMessage: () => {\n const message = this.tryGetMessage(currentId())?.message;\n if (!message) {\n throw new Error(\n \"[agui] resume stream requested the assistant message before it existed\",\n );\n }\n return message;\n },\n };\n\n try {\n for await (const result of stream(options)) {\n if (ctx.abortSignal.aborted) return;\n ctx.applyUpdate(result);\n }\n } catch (error) {\n if (ctx.abortSignal.aborted) return;\n const err = error instanceof Error ? error : new Error(String(error));\n ctx.applyUpdate({\n status: { type: \"incomplete\", reason: \"error\", error: err.message },\n });\n this.onError?.(err);\n this.pendingError = this.pendingError ?? err;\n return;\n }\n\n if (ctx.abortSignal.aborted) return;\n const current = this.tryGetMessage(currentId())?.message;\n if (!current || current.status?.type === \"running\") {\n ctx.applyUpdate({ status: { type: \"complete\", reason: \"unknown\" } });\n }\n }\n\n private buildRunInput(\n runId: string,\n runConfig: RunConfig | undefined,\n historyMessages: readonly ThreadMessage[] | undefined,\n resume?: AgUiResumeEntry[],\n ) {\n const threadId = this.agent.threadId || \"main\";\n const messages = toAgUiMessages(\n historyMessages ?? this.repository.getMessages(),\n );\n const context = this.runtime?.thread.getModelContext();\n return {\n threadId,\n runId,\n state: this.stateSnapshot ?? null,\n messages,\n tools: toAgUiTools(context?.tools),\n context: context?.system\n ? [{ description: \"system\", value: context.system }]\n : [],\n forwardedProps: {\n ...(context?.callSettings ?? {}),\n ...(context?.config ?? {}),\n ...(runConfig?.custom ? { runConfig: runConfig.custom } : {}),\n },\n ...(resume !== undefined ? { resume } : {}),\n };\n }\n\n private installResumeShim(): void {\n const agent = this.agent as any;\n if (agent[symbolResumeShim]) return;\n agent[symbolResumeShim] = true;\n const onInstance = Object.hasOwn(agent, \"prepareRunAgentInput\");\n const original = onInstance\n ? agent.prepareRunAgentInput\n : Object.getPrototypeOf(agent)?.prepareRunAgentInput;\n if (typeof original !== \"function\") return;\n agent.prepareRunAgentInput = function (\n this: unknown,\n params: { resume?: unknown } | undefined,\n ) {\n const input = original.call(this, params);\n if (params?.resume !== undefined && input && typeof input === \"object\") {\n return { ...(input as object), resume: params.resume };\n }\n return input;\n };\n }\n\n private setRunning(running: boolean) {\n this.isRunningFlag = running;\n this.notifyUpdate();\n }\n\n private finishRun(controller: AbortController | null) {\n if (this.abortController === controller) {\n this.abortController = null;\n }\n this.setRunning(false);\n }\n\n private insertAssistantPlaceholder(parentId: string | null): string {\n const id = generateOptimisticId();\n const assistant: ThreadAssistantMessage = {\n id,\n role: \"assistant\",\n createdAt: new Date(),\n status: { type: \"running\" },\n content: [],\n metadata: {\n unstable_state: this.stateSnapshot ?? null,\n unstable_annotations: [],\n unstable_data: [],\n steps: [],\n isOptimistic: true,\n custom: {},\n },\n };\n this.addOrUpdateMessage(parentId ?? this.repository.headId, assistant);\n this.switchToBranch(id);\n this.notifyUpdate();\n return id;\n }\n\n private reassignAssistantId(oldId: string, newId: string): boolean {\n if (oldId === newId) return true;\n const oldItem = this.tryGetMessage(oldId);\n if (!oldItem) return false;\n\n const collidesWithExisting = this.hasMessage(newId);\n\n if (collidesWithExisting) {\n this.logger.debug?.(\n \"[agui] reassignAssistantId: server id already present in messages or repository, dropping placeholder\",\n { oldId, newId },\n );\n this.deleteMessage(oldId, oldItem.parentId ?? null);\n } else {\n const { isOptimistic: _, ...metadata } = oldItem.message.metadata;\n this.addOrUpdateMessage(oldItem.parentId, {\n ...oldItem.message,\n id: newId,\n metadata,\n } as ThreadMessage);\n this.switchToBranch(newId);\n this.tryDeleteMessage(oldId);\n }\n\n const pendingParent = this.assistantHistoryParents.get(oldId);\n if (pendingParent !== undefined) {\n this.assistantHistoryParents.delete(oldId);\n if (!collidesWithExisting && !this.assistantHistoryParents.has(newId)) {\n this.assistantHistoryParents.set(newId, pendingParent);\n }\n }\n\n if (this.recordedHistoryIds.has(oldId)) {\n this.recordedHistoryIds.delete(oldId);\n if (!collidesWithExisting) {\n this.recordedHistoryIds.add(newId);\n }\n }\n\n this.notifyUpdate();\n return !collidesWithExisting;\n }\n\n private updateAssistantMessage(\n messageId: string,\n update: ChatModelRunResult,\n ): string {\n let latestStatus: MessageStatus | undefined;\n const touched = this.updateMessage(messageId, (message) => {\n if (message.role !== \"assistant\") return message;\n const assistant = message as ThreadAssistantMessage;\n const metadata = update.metadata\n ? this.mergeAssistantMetadata(assistant.metadata, update.metadata)\n : assistant.metadata;\n latestStatus = update.status ?? assistant.status;\n const content =\n update.content !== undefined\n ? this.preserveToolResults(\n assistant.content,\n update.content as ThreadAssistantMessage[\"content\"],\n )\n : assistant.content;\n return {\n ...assistant,\n content,\n status: latestStatus,\n metadata,\n };\n });\n if (!touched) return messageId;\n\n let resolvedMessageId = messageId;\n const isSettled =\n latestStatus !== undefined && latestStatus.type !== \"running\";\n if (isSettled && isOptimisticId(messageId)) {\n const stableId = generateId();\n this.reassignAssistantId(messageId, stableId);\n resolvedMessageId = stableId;\n } else {\n this.notifyUpdate();\n }\n if (this.isPersistableStatus(latestStatus)) {\n this.persistAssistantHistory(resolvedMessageId);\n }\n this.maybeResumeAfterToolResults(resolvedMessageId);\n return resolvedMessageId;\n }\n\n // The RunAggregator rebuilds the assistant content from stream events only,\n // so a fresh snapshot omits results injected via addToolResult (frontend tool\n // execution). Carry those results forward so the aggregator never clobbers\n // them. Results are only ever added in this flow, so preserving is safe.\n private preserveToolResults(\n previous: ThreadAssistantMessage[\"content\"],\n next: ThreadAssistantMessage[\"content\"],\n ): ThreadAssistantMessage[\"content\"] {\n const resolved = new Map<string, ToolCallMessagePart>();\n for (const part of previous) {\n if (part.type === \"tool-call\" && isResolvedToolCall(part)) {\n resolved.set(part.toolCallId, part);\n }\n }\n if (resolved.size === 0) return next;\n\n let changed = false;\n const merged = next.map((part) => {\n if (part.type !== \"tool-call\" || isResolvedToolCall(part)) return part;\n const prior = resolved.get(part.toolCallId);\n if (!prior) return part;\n changed = true;\n return {\n ...part,\n result: prior.result,\n ...(prior.artifact !== undefined ? { artifact: prior.artifact } : {}),\n ...(prior.isError !== undefined ? { isError: prior.isError } : {}),\n };\n });\n return changed ? (merged as ThreadAssistantMessage[\"content\"]) : next;\n }\n\n private mergeAssistantMetadata(\n current: ThreadAssistantMessage[\"metadata\"],\n incoming: NonNullable<ChatModelRunResult[\"metadata\"]>,\n ): ThreadAssistantMessage[\"metadata\"] {\n const annotations = incoming.unstable_annotations\n ? [...current.unstable_annotations, ...incoming.unstable_annotations]\n : current.unstable_annotations;\n const data = incoming.unstable_data\n ? [...current.unstable_data, ...incoming.unstable_data]\n : current.unstable_data;\n const steps = incoming.steps\n ? [...current.steps, ...incoming.steps]\n : current.steps;\n return {\n unstable_state:\n incoming.unstable_state !== undefined\n ? incoming.unstable_state\n : current.unstable_state,\n unstable_annotations: annotations,\n unstable_data: data,\n steps,\n ...(current.isOptimistic ? { isOptimistic: true } : {}),\n ...(incoming.timing ? { timing: incoming.timing } : {}),\n custom: incoming.custom\n ? { ...current.custom, ...incoming.custom }\n : current.custom,\n };\n }\n\n private handleEvent(aggregator: RunAggregator, event: AgUiEvent) {\n switch (event.type) {\n case \"STATE_SNAPSHOT\": {\n this.stateSnapshot = event.snapshot as ReadonlyJSONValue;\n this.notifyUpdate();\n return;\n }\n case \"STATE_DELTA\": {\n if (event.delta.length === 0) return;\n try {\n const state = this.stateSnapshot ?? {};\n const result = jsonpatch.applyPatch(\n state,\n event.delta as Operation[],\n /* validateOperation */ true,\n /* mutateDocument */ false,\n );\n this.stateSnapshot = result.newDocument as ReadonlyJSONValue;\n this.notifyUpdate();\n } catch (error) {\n this.logger.error?.(\"[agui] failed to apply state delta\", error);\n }\n return;\n }\n case \"MESSAGES_SNAPSHOT\": {\n this.importMessagesSnapshot(event.messages);\n return;\n }\n case \"TOOL_CALL_RESULT\": {\n if (!aggregator.hasToolCall(event.toolCallId)) {\n const messageId = this.findMessageIdForToolCall(event.toolCallId);\n if (messageId !== undefined) {\n this.applyCrossRunToolResult(messageId, event);\n return;\n }\n }\n aggregator.handle(event);\n return;\n }\n case \"ACTIVITY_SNAPSHOT\": {\n const toolCallId = event.content[\"toolCallId\"];\n if (\n event.activityType === MCP_APPS_ACTIVITY_TYPE &&\n typeof toolCallId === \"string\" &&\n !aggregator.hasToolCall(toolCallId)\n ) {\n const messageId = this.findMessageIdForToolCall(toolCallId);\n if (messageId !== undefined) {\n this.applyCrossRunActivitySnapshot(messageId, toolCallId, event);\n return;\n }\n }\n aggregator.handle(event);\n return;\n }\n default:\n aggregator.handle(event);\n }\n }\n\n private applyCrossRunToolResult(\n messageId: string,\n event: Extract<AgUiEvent, { type: \"TOOL_CALL_RESULT\" }>,\n ): void {\n const updated = this.updateMessage(messageId, (message) => {\n if (message.role !== \"assistant\") return message;\n const assistant = message as ThreadAssistantMessage;\n const mcpAppUri = readMcpAppResourceUri(event.mcpResult?._meta);\n let matchedToolCall = false;\n const content = assistant.content.map((part) => {\n if (part.type !== \"tool-call\" || part.toolCallId !== event.toolCallId)\n return part;\n matchedToolCall = true;\n // An applied activity snapshot owns part.result; a later result only\n // fills what is missing, mirroring the aggregator's finishToolCall.\n // The aggregator's flag is set only when the snapshot carried a\n // result, so app presence alone is not enough: the current result\n // must be CallToolResult-shaped (a required content array).\n const snapshotResultApplied =\n part.mcp?.app !== undefined &&\n isPlainObject(part.result) &&\n Array.isArray((part.result as Record<string, unknown>)[\"content\"]);\n if (snapshotResultApplied) {\n return {\n ...part,\n ...(part.modelContent === undefined && event.content\n ? {\n modelContent: [\n { type: \"text\" as const, text: event.content },\n ],\n }\n : {}),\n ...(part.isError === undefined\n ? typeof event.mcpResult?.isError === \"boolean\"\n ? { isError: event.mcpResult.isError }\n : event.role === \"tool\"\n ? { isError: false }\n : {}\n : {}),\n ...(event.messageId\n ? { unstable_toolMessageId: event.messageId }\n : {}),\n };\n }\n return {\n ...part,\n result: (event.mcpResult ??\n tryParseJSON(event.content ?? \"\")) as ReadonlyJSONValue,\n ...(event.mcpResult !== undefined\n ? { modelContent: [{ type: \"text\" as const, text: event.content }] }\n : {}),\n ...(typeof event.mcpResult?.isError === \"boolean\"\n ? { isError: event.mcpResult.isError }\n : event.role === \"tool\"\n ? { isError: false }\n : {}),\n ...(part.mcp === undefined && mcpAppUri !== undefined\n ? { mcp: { app: { resourceUri: mcpAppUri } } }\n : {}),\n ...(event.messageId\n ? { unstable_toolMessageId: event.messageId }\n : {}),\n };\n });\n if (!matchedToolCall) return message;\n return { ...assistant, content };\n });\n\n if (!updated) return;\n this.notifyUpdate();\n // Not maybeResumeAfterToolResults: the delivering run is already in\n // flight, and a resume from the owner would reset the head past it.\n this.maybeCompleteAfterToolResults(messageId);\n }\n\n private applyCrossRunActivitySnapshot(\n messageId: string,\n toolCallId: string,\n event: Extract<AgUiEvent, { type: \"ACTIVITY_SNAPSHOT\" }>,\n ): void {\n const resourceUri = event.content[\"resourceUri\"];\n if (typeof resourceUri !== \"string\" || !isMcpAppUri(resourceUri)) return;\n const serverId = event.content[\"serverId\"];\n const serverHash = event.content[\"serverHash\"];\n const appServerId =\n typeof serverId === \"string\" && serverId.length > 0\n ? serverId\n : typeof serverHash === \"string\" && serverHash.length > 0\n ? serverHash\n : undefined;\n const result = event.content[\"result\"];\n const updated = this.updateMessage(messageId, (message) => {\n if (message.role !== \"assistant\") return message;\n const assistant = message as ThreadAssistantMessage;\n let matchedToolCall = false;\n const content = assistant.content.map((part) => {\n if (part.type !== \"tool-call\" || part.toolCallId !== toolCallId)\n return part;\n matchedToolCall = true;\n return {\n ...part,\n mcp: {\n app: {\n resourceUri,\n ...(appServerId ? { serverId: appServerId } : {}),\n },\n },\n ...(isPlainObject(result)\n ? {\n ...(part.result !== undefined && part.modelContent === undefined\n ? {\n modelContent: [\n {\n type: \"text\" as const,\n text:\n typeof part.result === \"string\"\n ? part.result\n : JSON.stringify(part.result),\n },\n ],\n }\n : {}),\n result: result as ReadonlyJSONValue,\n isError: result[\"isError\"] === true,\n }\n : {}),\n };\n });\n if (!matchedToolCall) return message;\n return { ...assistant, content };\n });\n\n if (!updated) return;\n this.notifyUpdate();\n this.maybeCompleteAfterToolResults(messageId);\n }\n\n private importMessagesSnapshot(rawMessages: readonly unknown[]) {\n try {\n const normalized = fromAgUiMessages(rawMessages, {\n showThinking: this.showThinking,\n });\n const converted: ThreadMessage[] = [];\n for (const message of normalized) {\n try {\n converted.push(\n fromThreadMessageLike(message, generateId(), FALLBACK_USER_STATUS),\n );\n } catch (error) {\n this.logger.error?.(\n \"[agui] failed to import message from snapshot\",\n error,\n );\n }\n }\n this.applyExternalMessages(converted);\n } catch (error) {\n this.logger.error?.(\"[agui] failed to import messages snapshot\", error);\n }\n }\n\n private toThreadMessage(message: AppendMessage): ThreadMessage {\n return fromThreadMessageLike(\n message as any,\n generateId(),\n FALLBACK_USER_STATUS,\n );\n }\n\n private isTerminalStatus(status?: MessageStatus): boolean {\n return status?.type === \"complete\" || status?.type === \"incomplete\";\n }\n\n private isPersistableStatus(status?: MessageStatus): boolean {\n if (this.isTerminalStatus(status)) return true;\n return status?.type === \"requires-action\" && status.reason === \"interrupt\";\n }\n\n private recordHistoryEntry(parentId: string | null, message: ThreadMessage) {\n this.appendHistoryItem(parentId, message);\n }\n\n private markPendingAssistantHistory(\n messageId: string,\n parentId: string | null,\n ) {\n if (!this.history) return;\n this.assistantHistoryParents.set(messageId, parentId);\n }\n\n private persistAssistantHistory(messageId: string) {\n if (!this.history) return;\n const parentId = this.assistantHistoryParents.get(messageId);\n if (parentId === undefined) return;\n const message = this.tryGetMessage(messageId)?.message;\n if (!message || message.role !== \"assistant\") return;\n if (!this.isPersistableStatus(message.status)) return;\n this.assistantHistoryParents.delete(messageId);\n this.appendHistoryItem(parentId, message);\n }\n\n private appendHistoryItem(parentId: string | null, message: ThreadMessage) {\n if (!this.history || this.recordedHistoryIds.has(message.id)) return;\n this.recordedHistoryIds.add(message.id);\n void this.history.append({ parentId, message }).catch((error) => {\n this.recordedHistoryIds.delete(message.id);\n this.logger.error?.(\"[agui] failed to append history entry\", error);\n });\n }\n}\n"],"mappings":";;;;;;;;;AA2CA,MAAM,mBAAmB;AACzB,MAAM,6BAA6B,GAAG,mBAAmB,W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AwB;EAC1E,KAAK,kBAAkB,UAAU,OAAO;CAC1C;CAEA,4BACE,WACA,UACA;EACA,IAAI,CAAC,KAAK,SAAS;EACnB,KAAK,wBAAwB,IAAI,WAAW,QAAQ;CACtD;CAEA,wBAAgC,WAAmB;EACjD,IAAI,CAAC,KAAK,SAAS;EACnB,MAAM,WAAW,KAAK,wBAAwB,IAAI,SAAS;EAC3D,IAAI,aAAa,KAAA,GAAW;EAC5B,MAAM,UAAU,KAAK,cAAc,SAAS,CAAC,EAAE;EAC/C,IAAI,CAAC,WAAW,QAAQ,SAAS,aAAa;EAC9C,IAAI,CAAC,KAAK,oBAAoB,QAAQ,MAAM,GAAG;EAC/C,KAAK,wBAAwB,OAAO,SAAS;EAC7C,KAAK,kBAAkB,UAAU,OAAO;CAC1C;CAEA,kBAA0B,UAAyB,SAAwB;EACzE,IAAI,CAAC,KAAK,WAAW,KAAK,mBAAmB,IAAI,QAAQ,EAAE,GAAG;EAC9D,KAAK,mBAAmB,IAAI,QAAQ,EAAE;EACtC,KAAU,QAAQ,OAAO;GAAE;GAAU;EAAQ,CAAC,CAAC,CAAC,OAAO,UAAU;GAC/D,KAAK,mBAAmB,OAAO,QAAQ,EAAE;GACzC,KAAK,OAAO,QAAQ,yCAAyC,KAAK;EACpE,CAAC;CACH;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"conversions.d.ts","names":[],"sources":["../../../src/runtime/adapter/conversions.ts"],"mappings":";;;;KAuBK;EACH;EACA;EACA;;KAGG;EACH;EACA;EACA;EACA;EACA;EACA;EACA,uBAAuB;;KAGpB;EACH;EACA;EACA;IAAY;IAAc;;;KAGhB;EAEN;EACA;EACA,kBAAkB;EAClB;EACA,YAAY;;EAGZ;EACA;EACA;EACA;EACA;;KAwcM;;;;;EAKV;;iBAGc,iBACd,8BACA,UAAU,0BACT;iBA8Oa,eACd,mBAAmB,wBAClB;KA+BE;EACH;EACA;EACA;;iBAGc,YACd,OAAO,eAAe,oBACrB"}
1
+ {"version":3,"file":"conversions.d.ts","names":[],"sources":["../../../src/runtime/adapter/conversions.ts"],"mappings":";;;;KA2BK;EACH;EACA;EACA;;KAGG;EACH;EACA;EACA;EACA;EACA;EACA;EACA,uBAAuB;;KAGpB;EACH;EACA;EACA;IAAY;IAAc;;;KAGhB;EAEN;EACA;EACA,kBAAkB;EAClB;EACA,YAAY;;EAGZ;EACA;EACA;EACA;EACA;;KAycM;;;;;EAKV;;iBAGc,iBACd,8BACA,UAAU,0BACT;iBAmPa,eACd,mBAAmB,wBAClB;KA+BE;EACH;EACA;EACA;;iBAGc,YACd,OAAO,eAAe,oBACrB"}
@@ -1,6 +1,6 @@
1
1
  "use client";
2
+ import { parseMcpToolCallResult, readMcpAppResourceUri } from "../mcp-tool-result.js";
2
3
  import { AG_UI_METADATA_NAMESPACE } from "./run-aggregator.js";
3
- import { parseMcpToolCallResult } from "../mcp-tool-result.js";
4
4
  import { getAutoStatus, httpUrlPattern, parseDataUrl } from "@assistant-ui/core/internal";
5
5
  import { toToolsJSONSchema } from "assistant-stream";
6
6
  //#region src/runtime/adapter/conversions.ts
@@ -335,6 +335,8 @@ function fromAgUiMessages(messages, options) {
335
335
  }] : void 0;
336
336
  const result = mcpResult ?? (rawMessage.result !== void 0 ? rawMessage.result : typeof rawMessage.content === "string" ? parseJSONText(rawMessage.content) : rawMessage.content);
337
337
  const isError = typeof rawMessage.error === "string" || rawMessage.isError === true || rawMessage.status === "error" ? true : rawMessage.isError === false ? false : void 0;
338
+ const mcpAppUri = readMcpAppResourceUri(mcpResult?._meta);
339
+ const mcpApp = mcpAppUri !== void 0 ? { resourceUri: mcpAppUri } : void 0;
338
340
  let updated = false;
339
341
  for (let messageIndex = converted.length - 1; messageIndex >= 0 && !updated; messageIndex--) {
340
342
  const message = converted[messageIndex];
@@ -348,7 +350,8 @@ function fromAgUiMessages(messages, options) {
348
350
  result,
349
351
  ...mcpModelContent ? { modelContent: mcpModelContent } : {},
350
352
  ...isError !== void 0 ? { isError } : {},
351
- ...toolMessageId !== void 0 ? { unstable_toolMessageId: toolMessageId } : {}
353
+ ...toolMessageId !== void 0 ? { unstable_toolMessageId: toolMessageId } : {},
354
+ ...mcpApp ? { mcp: { app: mcpApp } } : {}
352
355
  };
353
356
  const updatedContent = message.content.map((contentPart, index) => index === partIndex ? updatedPart : contentPart);
354
357
  converted[messageIndex] = {
@@ -374,7 +377,8 @@ function fromAgUiMessages(messages, options) {
374
377
  result,
375
378
  ...mcpModelContent ? { modelContent: mcpModelContent } : {},
376
379
  ...isError !== void 0 ? { isError } : {},
377
- ...toolMessageId !== void 0 ? { unstable_toolMessageId: toolMessageId } : {}
380
+ ...toolMessageId !== void 0 ? { unstable_toolMessageId: toolMessageId } : {},
381
+ ...mcpApp ? { mcp: { app: mcpApp } } : {}
378
382
  }]
379
383
  });
380
384
  continue;
@@ -1 +1 @@
1
- {"version":3,"file":"conversions.js","names":[],"sources":["../../../src/runtime/adapter/conversions.ts"],"sourcesContent":["\"use client\";\n\nimport type { InputContent } from \"@ag-ui/client\";\nimport type {\n ThreadMessageLike as CoreThreadMessageLike,\n ToolModelContentPart,\n} from \"@assistant-ui/core\";\nimport {\n getAutoStatus,\n httpUrlPattern,\n parseDataUrl,\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 type AgUiCustomMetadata,\n} from \"./run-aggregator\";\nimport type { AgUiInterrupt } from \"../types\";\nimport { parseMcpToolCallResult } 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 name?: string;\n toolCallId?: string;\n error?: string;\n attachments?: readonly AttachmentLike[];\n};\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: string;\n content: string | InputContent[];\n name?: string;\n toolCalls?: AgUiToolCall[];\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};\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\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 generateId(): string {\n return (\n (globalThis.crypto as { randomUUID?: () => string })?.randomUUID?.() ??\n Math.random().toString(36).slice(2)\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).\nfunction buildInputSource(\n value: string,\n declaredMimeType: string | undefined,\n): InputContentSource {\n if (httpUrlPattern.test(value)) {\n return declaredMimeType !== undefined\n ? { type: \"url\", value, mimeType: declaredMimeType }\n : { type: \"url\", value };\n }\n const parsed = parseDataUrl(value);\n return {\n type: \"data\",\n value: parsed?.data ?? value,\n mimeType:\n parsed?.mimeType ?? declaredMimeType ?? \"application/octet-stream\",\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 return { type: \"image\", source: buildInputSource(image, fallbackMimeType) };\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(data, declaredMimeType);\n const metadata = filename !== undefined ? { filename } : undefined;\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 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 } | 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 { value: sourceValue, ...(mimeType !== undefined && { mimeType }) };\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 = isObject(part.metadata)\n ? getString(part.metadata, \"filename\")\n : undefined;\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 },\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 ...(filename !== undefined && { filename }),\n },\n ],\n });\n }\n return attachments;\n}\n\nfunction buildUserContent(message: ThreadMessageLike): string | InputContent[] {\n // File parts in message.content are intentionally skipped: the canonical\n // binary payload for files always flows through message.attachments.\n const contentParts = Array.isArray(message.content)\n ? message.content.filter(\n (part) => !(isObject(part) && part.type === \"file\"),\n )\n : [];\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 toAssistantSnapshotMessage(\n rawMessage: Record<string, unknown>,\n): CoreThreadMessageLike {\n const text = extractText(rawMessage.content);\n const toolCallParts = extractAssistantToolCalls(rawMessage);\n const assistantContent = [\n ...(text.length > 0 ? [{ type: \"text\" as const, text }] : []),\n ...toolCallParts,\n ];\n const messageName = getString(rawMessage, \"name\");\n const interrupts = readPersistedInterrupts(rawMessage.metadata);\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\",\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 role,\n content: extractText(rawMessage.content),\n ...(messageName !== undefined ? { name: messageName } : {}),\n ...(attachments.length > 0 ? { attachments } : {}),\n };\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\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\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 };\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 },\n ],\n });\n continue;\n }\n\n if (role === \"assistant\") {\n converted.push(toAssistantSnapshotMessage(rawMessage));\n continue;\n }\n\n if (role === \"reasoning\") {\n // Gate on showThinking so a cold reload matches the live run: the\n // aggregator never stores reasoning parts when showThinking is false.\n if (!showThinking) continue;\n const text = extractText(rawMessage.content);\n if (text.trim().length === 0) continue;\n converted.push({\n id: getString(rawMessage, \"id\") ?? generateId(),\n role: \"assistant\",\n content: [{ type: \"reasoning\", text }],\n });\n continue;\n }\n\n if (role === \"user\" || role === \"system\") {\n converted.push(toUserOrSystemSnapshotMessage(role, rawMessage));\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: ThreadMessageLike,\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 => part?.type === \"tool-call\",\n );\n\n const toolCalls = toolCallParts.map((part) => ({\n ...normalizeToolCall(part),\n part,\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 (content.length === 0 && toolCalls.length === 0) {\n return;\n }\n\n const assistantMessage: AgUiMessage = {\n id: message.id,\n role: \"assistant\",\n content,\n };\n if (message.name) {\n assistantMessage.name = message.name;\n }\n if (toolCalls.length > 0) {\n assistantMessage.toolCalls = toolCalls.map((entry) => entry.call);\n }\n converted.push(assistantMessage);\n\n for (const { id: toolCallId, part } of toolCalls) {\n if (part.result === undefined) continue;\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 const toolMessage: AgUiMessage = {\n id: part.unstable_toolMessageId ?? `${toolCallId}:tool`,\n role: \"tool\",\n content: resultContent,\n toolCallId,\n };\n if (part.isError) {\n toolMessage.error = resultContent;\n }\n converted.push(toolMessage);\n }\n}\n\nfunction convertToolMessage(\n message: ThreadMessageLike,\n converted: AgUiMessage[],\n): void {\n const content = extractText(message.content);\n const toolCallId = message.toolCallId ?? generateId();\n\n const toolMessage: AgUiMessage = {\n id: message.id,\n role: \"tool\",\n content,\n toolCallId,\n };\n if (typeof message.error === \"string\") {\n toolMessage.error = message.error;\n }\n converted.push(toolMessage);\n}\n\nexport function toAgUiMessages(\n messages: readonly ThreadMessageLike[],\n): AgUiMessage[] {\n const converted: AgUiMessage[] = [];\n\n for (const message of messages) {\n if (message.role === \"assistant\") {\n convertAssistantMessage(message, converted);\n continue;\n }\n\n if (message.role === \"tool\") {\n convertToolMessage(message, converted);\n continue;\n }\n\n const genericMessage: AgUiMessage = {\n id: message.id,\n role: message.role,\n content:\n message.role === \"user\"\n ? buildUserContent(message)\n : extractText(message.content),\n };\n if (message.name) {\n genericMessage.name = message.name;\n }\n converted.push(genericMessage);\n }\n\n return converted;\n}\n\ntype AgUiTool = {\n name: string;\n description: string | undefined;\n parameters: unknown;\n};\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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AEA,SAAS,mBACP,SACA,WACM;CACN,MAAM,UAAU,YAAY,QAAQ,OAAO;CAC3C,MAAM,aAAa,QAAQ,cAAc,WAAW;CAEpD,MAAM,cAA2B;EAC/B,IAAI,QAAQ;EACZ,MAAM;EACN;EACA;CACF;CACA,IAAI,OAAO,QAAQ,UAAU,UAC3B,YAAY,QAAQ,QAAQ;CAE9B,UAAU,KAAK,WAAW;AAC5B;AAEA,SAAgB,eACd,UACe;CACf,MAAM,YAA2B,CAAC;CAElC,KAAK,MAAM,WAAW,UAAU;EAC9B,IAAI,QAAQ,SAAS,aAAa;GAChC,wBAAwB,SAAS,SAAS;GAC1C;EACF;EAEA,IAAI,QAAQ,SAAS,QAAQ;GAC3B,mBAAmB,SAAS,SAAS;GACrC;EACF;EAEA,MAAM,iBAA8B;GAClC,IAAI,QAAQ;GACZ,MAAM,QAAQ;GACd,SACE,QAAQ,SAAS,SACb,iBAAiB,OAAO,IACxB,YAAY,QAAQ,OAAO;EACnC;EACA,IAAI,QAAQ,MACV,eAAe,OAAO,QAAQ;EAEhC,UAAU,KAAK,cAAc;CAC/B;CAEA,OAAO;AACT;AAQA,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;EAClB,YAAY,KAAK;CACnB,EAAE;AACJ"}
1
+ {"version":3,"file":"conversions.js","names":[],"sources":["../../../src/runtime/adapter/conversions.ts"],"sourcesContent":["\"use client\";\n\nimport type { InputContent } from \"@ag-ui/client\";\nimport type {\n ThreadMessageLike as CoreThreadMessageLike,\n ToolCallMessagePartMcpMetadata,\n ToolModelContentPart,\n} from \"@assistant-ui/core\";\nimport {\n getAutoStatus,\n httpUrlPattern,\n parseDataUrl,\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 type AgUiCustomMetadata,\n} from \"./run-aggregator\";\nimport type { AgUiInterrupt } from \"../types\";\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 name?: string;\n toolCallId?: string;\n error?: string;\n attachments?: readonly AttachmentLike[];\n};\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: string;\n content: string | InputContent[];\n name?: string;\n toolCalls?: AgUiToolCall[];\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};\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\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 generateId(): string {\n return (\n (globalThis.crypto as { randomUUID?: () => string })?.randomUUID?.() ??\n Math.random().toString(36).slice(2)\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).\nfunction buildInputSource(\n value: string,\n declaredMimeType: string | undefined,\n): InputContentSource {\n if (httpUrlPattern.test(value)) {\n return declaredMimeType !== undefined\n ? { type: \"url\", value, mimeType: declaredMimeType }\n : { type: \"url\", value };\n }\n const parsed = parseDataUrl(value);\n return {\n type: \"data\",\n value: parsed?.data ?? value,\n mimeType:\n parsed?.mimeType ?? declaredMimeType ?? \"application/octet-stream\",\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 return { type: \"image\", source: buildInputSource(image, fallbackMimeType) };\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(data, declaredMimeType);\n const metadata = filename !== undefined ? { filename } : undefined;\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 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 } | 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 { value: sourceValue, ...(mimeType !== undefined && { mimeType }) };\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 = isObject(part.metadata)\n ? getString(part.metadata, \"filename\")\n : undefined;\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 },\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 ...(filename !== undefined && { filename }),\n },\n ],\n });\n }\n return attachments;\n}\n\nfunction buildUserContent(message: ThreadMessageLike): string | InputContent[] {\n // File parts in message.content are intentionally skipped: the canonical\n // binary payload for files always flows through message.attachments.\n const contentParts = Array.isArray(message.content)\n ? message.content.filter(\n (part) => !(isObject(part) && part.type === \"file\"),\n )\n : [];\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 toAssistantSnapshotMessage(\n rawMessage: Record<string, unknown>,\n): CoreThreadMessageLike {\n const text = extractText(rawMessage.content);\n const toolCallParts = extractAssistantToolCalls(rawMessage);\n const assistantContent = [\n ...(text.length > 0 ? [{ type: \"text\" as const, text }] : []),\n ...toolCallParts,\n ];\n const messageName = getString(rawMessage, \"name\");\n const interrupts = readPersistedInterrupts(rawMessage.metadata);\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\",\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 role,\n content: extractText(rawMessage.content),\n ...(messageName !== undefined ? { name: messageName } : {}),\n ...(attachments.length > 0 ? { attachments } : {}),\n };\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\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 === \"assistant\") {\n converted.push(toAssistantSnapshotMessage(rawMessage));\n continue;\n }\n\n if (role === \"reasoning\") {\n // Gate on showThinking so a cold reload matches the live run: the\n // aggregator never stores reasoning parts when showThinking is false.\n if (!showThinking) continue;\n const text = extractText(rawMessage.content);\n if (text.trim().length === 0) continue;\n converted.push({\n id: getString(rawMessage, \"id\") ?? generateId(),\n role: \"assistant\",\n content: [{ type: \"reasoning\", text }],\n });\n continue;\n }\n\n if (role === \"user\" || role === \"system\") {\n converted.push(toUserOrSystemSnapshotMessage(role, rawMessage));\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: ThreadMessageLike,\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 => part?.type === \"tool-call\",\n );\n\n const toolCalls = toolCallParts.map((part) => ({\n ...normalizeToolCall(part),\n part,\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 (content.length === 0 && toolCalls.length === 0) {\n return;\n }\n\n const assistantMessage: AgUiMessage = {\n id: message.id,\n role: \"assistant\",\n content,\n };\n if (message.name) {\n assistantMessage.name = message.name;\n }\n if (toolCalls.length > 0) {\n assistantMessage.toolCalls = toolCalls.map((entry) => entry.call);\n }\n converted.push(assistantMessage);\n\n for (const { id: toolCallId, part } of toolCalls) {\n if (part.result === undefined) continue;\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 const toolMessage: AgUiMessage = {\n id: part.unstable_toolMessageId ?? `${toolCallId}:tool`,\n role: \"tool\",\n content: resultContent,\n toolCallId,\n };\n if (part.isError) {\n toolMessage.error = resultContent;\n }\n converted.push(toolMessage);\n }\n}\n\nfunction convertToolMessage(\n message: ThreadMessageLike,\n converted: AgUiMessage[],\n): void {\n const content = extractText(message.content);\n const toolCallId = message.toolCallId ?? generateId();\n\n const toolMessage: AgUiMessage = {\n id: message.id,\n role: \"tool\",\n content,\n toolCallId,\n };\n if (typeof message.error === \"string\") {\n toolMessage.error = message.error;\n }\n converted.push(toolMessage);\n}\n\nexport function toAgUiMessages(\n messages: readonly ThreadMessageLike[],\n): AgUiMessage[] {\n const converted: AgUiMessage[] = [];\n\n for (const message of messages) {\n if (message.role === \"assistant\") {\n convertAssistantMessage(message, converted);\n continue;\n }\n\n if (message.role === \"tool\") {\n convertToolMessage(message, converted);\n continue;\n }\n\n const genericMessage: AgUiMessage = {\n id: message.id,\n role: message.role,\n content:\n message.role === \"user\"\n ? buildUserContent(message)\n : extractText(message.content),\n };\n if (message.name) {\n genericMessage.name = message.name;\n }\n converted.push(genericMessage);\n }\n\n return converted;\n}\n\ntype AgUiTool = {\n name: string;\n description: string | undefined;\n parameters: unknown;\n};\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":";;;;;;AA8EA,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,SAAS,cAAc,OAAwB;CAC7C,IAAI,CAAC,OAAO,OAAO;CACnB,IAAI;EACF,OAAO,KAAK,MAAM,KAAK;CACzB,QAAQ;EACN,OAAO;CACT;AACF;AAEA,SAAS,aAAqB;CAC5B,OACG,WAAW,QAA0C,aAAa,KACnE,KAAK,OAAO,CAAC,CAAC,SAAS,EAAE,CAAC,CAAC,MAAM,CAAC;AAEtC;AAEA,SAAS,kBAAkB,MAGzB;CACA,MAAM,KAAK,KAAK,cAAc,WAAW;CACzC,MAAM,WACJ,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AAI,QAAQ,SAAS,aAAa;GAChC,wBAAwB,SAAS,SAAS;GAC1C;EACF;EAEA,IAAI,QAAQ,SAAS,QAAQ;GAC3B,mBAAmB,SAAS,SAAS;GACrC;EACF;EAEA,MAAM,iBAA8B;GAClC,IAAI,QAAQ;GACZ,MAAM,QAAQ;GACd,SACE,QAAQ,SAAS,SACb,iBAAiB,OAAO,IACxB,YAAY,QAAQ,OAAO;EACnC;EACA,IAAI,QAAQ,MACV,eAAe,OAAO,QAAQ;EAEhC,UAAU,KAAK,cAAc;CAC/B;CAEA,OAAO;AACT;AAQA,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;EAClB,YAAY,KAAK;CACnB,EAAE;AACJ"}
@@ -1 +1 @@
1
- {"version":3,"file":"run-aggregator.d.ts","names":[],"sources":["../../../src/runtime/adapter/run-aggregator.ts"],"mappings":";;;;cAaa;KAED;EACV,aAAa;;KAGV,QAAQ,QAAQ;cAiBR;cAEA,gBACX,mBACC,SAAS;KAGA;EACV;EACA,QAAQ;EACR,MAAM;EACN,qBAAqB;;;;;;;;cASV;mBACM;mBACA;mBACA;mBACA;UAET;UACA;mBACS;UAIT;mBACS;UACT;UACA;mBACS;UACT;mBACS;UAKT;UACA;UAEA;UACA;UACA;EAEI,YAAA,SAAS;EAOrB,YAAY;EAIZ,OAAO,OAAO;UAiNN;UAMA;UAIA;UAKA;UAOA;UAiBA;UAWA;UAMA;UAQA;UAiCA;UA2BA;UAgBA;UAkDA;UA4EA;UASA;UAgCA;UAcA;UAYA;;iBAOM,aAAa"}
1
+ {"version":3,"file":"run-aggregator.d.ts","names":[],"sources":["../../../src/runtime/adapter/run-aggregator.ts"],"mappings":";;;;cAca;KAED;EACV,aAAa;;KAGV,QAAQ,QAAQ;cAiBR;cAEA,gBACX,mBACC,SAAS;KAGA;EACV;EACA,QAAQ;EACR,MAAM;EACN,qBAAqB;;;;;;;;cASV;mBACM;mBACA;mBACA;mBACA;UAET;UACA;mBACS;UAIT;mBACS;UACT;UACA;mBACS;UACT;mBACS;UAKT;UACA;UAEA;UACA;UACA;EAEI,YAAA,SAAS;EAOrB,YAAY;EAIZ,OAAO,OAAO;UAiNN;UAMA;UAIA;UAKA;UAOA;UAiBA;UAWA;UAMA;UAQA;UAiCA;UA2BA;UAgBA;UAsDA;UA4EA;UASA;UAgCA;UAcA;UAYA;;iBAOM,aAAa"}
@@ -1,4 +1,5 @@
1
1
  "use client";
2
+ import { readMcpAppResourceUri } from "../mcp-tool-result.js";
2
3
  import { isMcpAppUri } from "@assistant-ui/core";
3
4
  //#region src/runtime/adapter/run-aggregator.ts
4
5
  const AG_UI_METADATA_NAMESPACE = "agui";
@@ -321,6 +322,10 @@ var RunAggregator = class {
321
322
  }];
322
323
  entry.snapshotResultApplied = true;
323
324
  entry.isError = isError;
325
+ if (entry.mcpAppResourceUri === void 0) {
326
+ const uri = readMcpAppResourceUri(mcpResult._meta);
327
+ if (uri !== void 0) entry.mcpAppResourceUri = uri;
328
+ }
324
329
  } else if (entry.snapshotResultApplied) {
325
330
  if (entry.modelContent === void 0) entry.modelContent = [{
326
331
  type: "text",
@@ -1 +1 @@
1
- {"version":3,"file":"run-aggregator.js","names":[],"sources":["../../../src/runtime/adapter/run-aggregator.ts"],"sourcesContent":["\"use client\";\n\nimport {\n isMcpAppUri,\n type ChatModelRunResult,\n type MessageTiming,\n type ThreadAssistantMessagePart,\n type ToolCallMessagePart,\n type ToolModelContentPart,\n} from \"@assistant-ui/core\";\nimport type { AgUiEvent, AgUiInterrupt } from \"../types\";\nimport type { Logger } from \"../logger\";\n\nexport const AG_UI_METADATA_NAMESPACE = \"agui\";\n\nexport type AgUiCustomMetadata = {\n interrupts?: AgUiInterrupt[];\n};\n\ntype Emit = (update: ChatModelRunResult) => void;\n\ntype ToolCallState = {\n toolCallId: string;\n toolCallName: string;\n argsText: string;\n parsedArgs: Record<string, unknown> | undefined;\n result: unknown;\n isError: boolean | undefined;\n parentMessageId?: string;\n toolMessageId?: string;\n mcpAppResourceUri?: string;\n mcpAppServerId?: string;\n modelContent?: ToolModelContentPart[];\n snapshotResultApplied: boolean;\n};\n\nexport const MCP_APPS_ACTIVITY_TYPE = \"mcp-apps\";\n\nexport const isPlainObject = (\n value: unknown,\n): value is Record<string, unknown> =>\n !!value && typeof value === \"object\" && !Array.isArray(value);\n\nexport type RunAggregatorOptions = {\n showThinking: boolean;\n logger: Logger;\n emit: Emit;\n onServerMessageId?: (messageId: string) => void;\n};\n\n/**\n * Collects AG-UI events into assistant-ui run snapshots that can be yielded from a ChatModelAdapter.\n *\n * The aggregator keeps a single assistant message worth of parts. Each incoming event updates the parts and\n * emits a fresh snapshot through the provided `emit` callback.\n */\nexport class RunAggregator {\n private readonly emitUpdate: Emit;\n private readonly showThinking: boolean;\n private readonly logger: Logger;\n private readonly onServerMessageId: ((messageId: string) => void) | undefined;\n\n private status: ChatModelRunResult[\"status\"] | undefined;\n private interrupts: AgUiInterrupt[] | undefined;\n private readonly textParts = new Map<\n string,\n { buffer: string; touched: boolean }\n >();\n private activeTextMessageId: string | undefined;\n private readonly reasoningParts = new Map<string, string>(); // key → buffer\n private activeReasoningKey: string | undefined;\n private reasoningPartCounter = 0;\n private readonly toolCalls = new Map<string, ToolCallState>();\n private lastResolvedToolCallId: string | undefined;\n private readonly partOrder: (\n | { kind: \"text\"; key: string }\n | { kind: \"reasoning\"; key: string }\n | { kind: \"tool-call\"; toolCallId: string }\n )[] = [];\n private textPartCounter = 0;\n private serverMessageIdReported = false;\n\n private streamStartTime: number | undefined;\n private firstTokenTime: number | undefined;\n private totalChunks = 0;\n\n constructor(options: RunAggregatorOptions) {\n this.emitUpdate = options.emit;\n this.showThinking = options.showThinking;\n this.logger = options.logger;\n this.onServerMessageId = options.onServerMessageId;\n }\n\n hasToolCall(toolCallId: string): boolean {\n return this.toolCalls.has(toolCallId);\n }\n\n handle(event: AgUiEvent): void {\n switch (event.type) {\n case \"RUN_STARTED\": {\n this.clearTextParts();\n this.reasoningParts.clear();\n this.activeReasoningKey = undefined;\n this.reasoningPartCounter = 0;\n this.toolCalls.clear();\n this.lastResolvedToolCallId = undefined;\n this.partOrder.length = 0;\n this.textPartCounter = 0;\n this.activeTextMessageId = undefined;\n this.interrupts = undefined;\n this.serverMessageIdReported = false;\n this.streamStartTime = Date.now();\n this.firstTokenTime = undefined;\n this.totalChunks = 0;\n this.status = { type: \"running\" };\n this.emit();\n break;\n }\n case \"RUN_FINISHED\": {\n if (event.outcome?.type === \"interrupt\") {\n this.interrupts = event.outcome.interrupts;\n this.status = { type: \"requires-action\", reason: \"interrupt\" };\n this.emit();\n break;\n }\n\n this.interrupts = undefined;\n const hasUnresolvedToolCalls = Array.from(this.toolCalls.values()).some(\n (tc) => tc.result === undefined,\n );\n\n this.status =\n event.outcome?.type === \"success\" || !hasUnresolvedToolCalls\n ? { type: \"complete\", reason: \"unknown\" }\n : { type: \"requires-action\", reason: \"tool-calls\" };\n this.emit();\n break;\n }\n case \"RUN_ERROR\": {\n this.status = {\n type: \"incomplete\",\n reason: \"error\",\n ...(event.message !== undefined ? { error: event.message } : {}),\n };\n this.emit();\n break;\n }\n case \"RUN_CANCELLED\": {\n this.status = { type: \"incomplete\", reason: \"cancelled\" };\n this.emit();\n break;\n }\n\n case \"TEXT_MESSAGE_START\": {\n this.reportServerMessageId(event.messageId);\n const id = this.startTextMessage(event.messageId);\n if (id) {\n this.markTextPartTouched(id);\n }\n this.emit();\n break;\n }\n case \"TEXT_MESSAGE_CONTENT\":\n case \"TEXT_MESSAGE_CHUNK\": {\n const incomingId = \"messageId\" in event ? event.messageId : undefined;\n this.reportServerMessageId(incomingId);\n if (!event.delta) break;\n this.recordFirstToken();\n const id = this.resolveTextMessageId(incomingId);\n this.appendText(id, event.delta);\n this.totalChunks++;\n this.emit();\n break;\n }\n case \"TEXT_MESSAGE_END\": {\n this.reportServerMessageId(event.messageId);\n if (event.messageId && this.activeTextMessageId === event.messageId) {\n this.activeTextMessageId = undefined;\n }\n this.emit();\n break;\n }\n\n case \"THINKING_START\":\n case \"THINKING_TEXT_MESSAGE_START\":\n case \"REASONING_START\":\n case \"REASONING_MESSAGE_START\":\n this.handleReasoningStart(\n \"messageId\" in event ? event.messageId : undefined,\n );\n break;\n case \"THINKING_TEXT_MESSAGE_CONTENT\":\n this.handleReasoningContent(event.delta);\n this.totalChunks++;\n this.recordFirstToken();\n break;\n case \"REASONING_MESSAGE_CONTENT\":\n this.handleReasoningContent(\n event.delta,\n \"messageId\" in event ? event.messageId : undefined,\n );\n this.totalChunks++;\n this.recordFirstToken();\n break;\n case \"THINKING_TEXT_MESSAGE_END\":\n case \"THINKING_END\":\n case \"REASONING_MESSAGE_END\":\n case \"REASONING_END\":\n this.handleReasoningEnd();\n break;\n\n case \"TOOL_CALL_START\": {\n this.reportServerMessageId(event.parentMessageId);\n this.startToolCall(\n event.toolCallId,\n event.toolCallName,\n event.parentMessageId,\n );\n this.emit();\n break;\n }\n case \"TOOL_CALL_ARGS\":\n case \"TOOL_CALL_CHUNK\": {\n if (event.type === \"TOOL_CALL_CHUNK\") {\n this.reportServerMessageId(event.parentMessageId);\n }\n if (!event.delta) break;\n this.appendToolArgs(event.toolCallId, event.delta);\n this.emit();\n break;\n }\n case \"TOOL_CALL_END\": {\n this.emit();\n break;\n }\n case \"TOOL_CALL_RESULT\": {\n this.finishToolCall(\n event.toolCallId,\n event.content ?? \"\",\n typeof event.mcpResult?.isError === \"boolean\"\n ? event.mcpResult.isError\n : event.role === \"tool\"\n ? false\n : undefined,\n event.messageId,\n event.mcpResult,\n );\n this.emit();\n break;\n }\n case \"ACTIVITY_SNAPSHOT\": {\n if (event.activityType !== MCP_APPS_ACTIVITY_TYPE) break;\n const toolCallId = event.content.toolCallId;\n const entry =\n typeof toolCallId === \"string\"\n ? this.toolCalls.get(toolCallId)\n : this.lastResolvedToolCallId\n ? this.toolCalls.get(this.lastResolvedToolCallId)\n : undefined;\n const resourceUri = event.content.resourceUri;\n if (\n entry &&\n typeof resourceUri === \"string\" &&\n isMcpAppUri(resourceUri)\n ) {\n entry.mcpAppResourceUri = resourceUri;\n const id = event.content.serverId;\n const hash = event.content.serverHash;\n if (typeof id === \"string\" && id.length > 0) {\n entry.mcpAppServerId = id;\n } else if (typeof hash === \"string\" && hash.length > 0) {\n entry.mcpAppServerId = hash;\n }\n const result = event.content.result;\n if (isPlainObject(result)) {\n if (\n entry.result !== undefined &&\n entry.modelContent === undefined\n ) {\n entry.modelContent = [\n {\n type: \"text\",\n text:\n typeof entry.result === \"string\"\n ? entry.result\n : JSON.stringify(entry.result),\n },\n ];\n }\n entry.result = result;\n entry.snapshotResultApplied = true;\n if (typeof result.isError === \"boolean\") {\n entry.isError = result.isError;\n }\n }\n this.emit();\n }\n break;\n }\n\n default: {\n this.logger.debug?.(\"[agui] aggregator ignored event\", event);\n }\n }\n }\n\n private reportServerMessageId(messageId: string | undefined): void {\n if (this.serverMessageIdReported || !messageId) return;\n this.serverMessageIdReported = true;\n this.onServerMessageId?.(messageId);\n }\n\n private clearTextParts(): void {\n this.textParts.clear();\n }\n\n private generateTextKey(): string {\n this.textPartCounter += 1;\n return `text-${this.textPartCounter}`;\n }\n\n private startTextMessage(messageId?: string): string {\n const id = messageId ?? this.generateTextKey();\n this.ensureTextPart(id);\n this.activeTextMessageId = id;\n return id;\n }\n\n private resolveTextMessageId(messageId?: string): string {\n if (messageId) {\n this.ensureTextPart(messageId);\n this.activeTextMessageId = messageId;\n return messageId;\n }\n\n if (this.activeTextMessageId) {\n return this.activeTextMessageId;\n }\n\n const generated = this.generateTextKey();\n this.ensureTextPart(generated);\n this.activeTextMessageId = generated;\n return generated;\n }\n\n private ensureTextPart(id: string): void {\n if (!this.textParts.has(id)) {\n this.textParts.set(id, { buffer: \"\", touched: false });\n if (\n !this.partOrder.some((part) => part.kind === \"text\" && part.key === id)\n ) {\n this.partOrder.push({ kind: \"text\", key: id });\n }\n }\n }\n\n private markTextPartTouched(id: string): void {\n const entry = this.textParts.get(id);\n if (!entry) return;\n entry.touched = true;\n }\n\n private appendText(id: string, delta: string): void {\n this.ensureTextPart(id);\n const entry = this.textParts.get(id);\n if (!entry) return;\n entry.buffer += delta;\n entry.touched = true;\n }\n\n private startToolCall(\n id: string | undefined,\n name?: string,\n parentMessageId?: string,\n ) {\n if (!id) return;\n // A new tool call acts as a boundary: any anonymous text that arrives\n // after it should be a new part, not appended to the pre-tool text.\n this.activeTextMessageId = undefined;\n if (\n !this.partOrder.some(\n (part) => part.kind === \"tool-call\" && part.toolCallId === id,\n )\n ) {\n this.insertToolPart(id, parentMessageId);\n }\n const state: ToolCallState = {\n toolCallId: id,\n toolCallName: name ?? \"tool\",\n argsText: \"\",\n parsedArgs: undefined,\n result: undefined,\n isError: undefined,\n snapshotResultApplied: false,\n };\n if (parentMessageId) {\n state.parentMessageId = parentMessageId;\n }\n this.toolCalls.set(id, state);\n }\n\n // The message and tool-call channels are unordered on the wire, so anchor a\n // tool call under its parentMessageId text part instead of appending it.\n private insertToolPart(id: string, parentMessageId?: string) {\n const entry = { kind: \"tool-call\", toolCallId: id } as const;\n if (parentMessageId) {\n const parentIndex = this.partOrder.findIndex(\n (part) => part.kind === \"text\" && part.key === parentMessageId,\n );\n if (parentIndex !== -1) {\n let insertAt = parentIndex + 1;\n while (insertAt < this.partOrder.length) {\n const part = this.partOrder[insertAt];\n if (\n part?.kind === \"tool-call\" &&\n this.toolCalls.get(part.toolCallId)?.parentMessageId ===\n parentMessageId\n ) {\n insertAt += 1;\n continue;\n }\n break;\n }\n this.partOrder.splice(insertAt, 0, entry);\n return;\n }\n }\n this.partOrder.push(entry);\n }\n\n private appendToolArgs(id: string | undefined, delta: string) {\n const entry = id ? this.toolCalls.get(id) : undefined;\n if (!entry) return;\n entry.argsText += delta;\n try {\n const parsed = JSON.parse(entry.argsText);\n if (parsed && typeof parsed === \"object\") {\n entry.parsedArgs = parsed as Record<string, unknown>;\n } else {\n entry.parsedArgs = undefined;\n }\n } catch {\n entry.parsedArgs = undefined;\n }\n }\n\n private finishToolCall(\n id: string,\n content: string,\n isError?: boolean,\n toolMessageId?: string,\n mcpResult?: Record<string, unknown>,\n ) {\n if (!id) return;\n let entry = this.toolCalls.get(id);\n if (!entry) {\n entry = {\n toolCallId: id,\n toolCallName: \"tool\",\n argsText: \"\",\n parsedArgs: undefined,\n result: undefined,\n isError: undefined,\n snapshotResultApplied: false,\n };\n this.toolCalls.set(id, entry);\n }\n if (\n !this.partOrder.some(\n (part) => part.kind === \"tool-call\" && part.toolCallId === id,\n )\n ) {\n this.partOrder.push({ kind: \"tool-call\", toolCallId: id });\n }\n if (mcpResult !== undefined && !entry.snapshotResultApplied) {\n entry.result = mcpResult;\n entry.modelContent = [{ type: \"text\", text: content }];\n entry.snapshotResultApplied = true;\n entry.isError = isError;\n } else if (entry.snapshotResultApplied) {\n if (entry.modelContent === undefined) {\n entry.modelContent = [{ type: \"text\", text: content }];\n }\n if (entry.isError === undefined) {\n entry.isError = isError;\n }\n } else {\n entry.result = tryParseJSON(content);\n entry.isError = isError;\n }\n if (toolMessageId) {\n entry.toolMessageId = toolMessageId;\n }\n this.lastResolvedToolCallId = id;\n }\n\n private emit(): void {\n const snapshot: ThreadAssistantMessagePart[] = [];\n\n for (const part of this.partOrder) {\n if (part.kind === \"reasoning\") {\n if (this.showThinking) {\n const buffer = this.reasoningParts.get(part.key) ?? \"\";\n if (buffer.length > 0 || this.activeReasoningKey === part.key) {\n snapshot.push({ type: \"reasoning\", text: buffer } as const);\n }\n }\n continue;\n }\n\n if (part.kind === \"text\") {\n const entry = this.textParts.get(part.key);\n if (entry?.touched) {\n snapshot.push({ type: \"text\", text: entry.buffer } as const);\n }\n continue;\n }\n\n const entry = this.toolCalls.get(part.toolCallId);\n if (!entry) continue;\n const toolPart: ToolCallMessagePart = {\n type: \"tool-call\",\n toolCallId: entry.toolCallId,\n toolName: entry.toolCallName,\n args: (entry.parsedArgs ?? {}) as any,\n argsText: entry.argsText,\n ...(entry.result !== undefined ? { result: entry.result } : {}),\n ...(entry.modelContent !== undefined\n ? { modelContent: entry.modelContent }\n : {}),\n ...(entry.isError !== undefined ? { isError: entry.isError } : {}),\n ...(entry.mcpAppResourceUri\n ? {\n mcp: {\n app: {\n resourceUri: entry.mcpAppResourceUri,\n ...(entry.mcpAppServerId\n ? { serverId: entry.mcpAppServerId }\n : {}),\n },\n },\n }\n : {}),\n ...(entry.parentMessageId ? { parentId: entry.parentMessageId } : {}),\n ...(entry.toolMessageId\n ? { unstable_toolMessageId: entry.toolMessageId }\n : {}),\n } as ToolCallMessagePart & { unstable_toolMessageId?: string };\n snapshot.push(toolPart);\n }\n\n const timing = this.getTiming();\n const metadata = {\n ...(timing ? { timing } : {}),\n ...(this.interrupts\n ? {\n custom: {\n [AG_UI_METADATA_NAMESPACE]: {\n interrupts: this.interrupts,\n } satisfies AgUiCustomMetadata,\n },\n }\n : {}),\n };\n const result: ChatModelRunResult = {\n content: snapshot,\n ...(this.status ? { status: this.status } : undefined),\n ...(Object.keys(metadata).length > 0 ? { metadata } : undefined),\n };\n this.emitUpdate(result);\n }\n\n private recordFirstToken(): void {\n if (\n this.firstTokenTime === undefined &&\n this.streamStartTime !== undefined\n ) {\n this.firstTokenTime = Date.now() - this.streamStartTime;\n }\n }\n\n private getTiming(): MessageTiming | undefined {\n if (this.streamStartTime === undefined) return undefined;\n\n const now = Date.now();\n const totalStreamTime = now - this.streamStartTime;\n const tokenCount =\n this.totalChunks > 0\n ? Math.ceil(\n Array.from(this.textParts.values()).reduce(\n (sum, p) => sum + p.buffer.length,\n 0,\n ) / 4,\n )\n : undefined;\n const tokensPerSecond =\n tokenCount && totalStreamTime > 0\n ? (tokenCount / totalStreamTime) * 1000\n : undefined;\n\n return {\n streamStartTime: this.streamStartTime,\n ...(this.firstTokenTime !== undefined\n ? { firstTokenTime: this.firstTokenTime }\n : {}),\n totalStreamTime,\n ...(tokenCount !== undefined ? { tokenCount } : {}),\n ...(tokensPerSecond !== undefined ? { tokensPerSecond } : {}),\n totalChunks: this.totalChunks,\n toolCallCount: this.toolCalls.size,\n };\n }\n\n private handleReasoningStart(messageId?: string): void {\n if (!this.showThinking) return;\n // A reasoning block acts as a boundary: anonymous text arriving after it\n // should be a new part, not appended to any pre-reasoning text.\n this.activeTextMessageId = undefined;\n const key = messageId ?? `__auto-reasoning-${++this.reasoningPartCounter}`;\n if (!this.reasoningParts.has(key)) {\n this.reasoningParts.set(key, \"\");\n this.partOrder.push({ kind: \"reasoning\", key });\n }\n this.activeReasoningKey = key;\n this.emit();\n }\n\n private handleReasoningContent(delta: string, messageId?: string): void {\n if (!this.showThinking || !delta) return;\n if (!this.activeReasoningKey) {\n // Content arrived without a preceding START — create the slot lazily.\n this.handleReasoningStart(messageId);\n }\n const key = this.activeReasoningKey;\n if (!key) return;\n this.reasoningParts.set(key, (this.reasoningParts.get(key) ?? \"\") + delta);\n this.emit();\n }\n\n private handleReasoningEnd(): void {\n if (!this.showThinking) return;\n this.activeReasoningKey = undefined;\n this.emit();\n }\n}\n\nexport function tryParseJSON(value: string): unknown {\n if (!value) return value;\n try {\n return JSON.parse(value);\n } catch {\n return value;\n }\n}\n"],"mappings":";;;AAaA,MAAa,2BAA2B;AAuBxC,MAAa,yBAAyB;AAEtC,MAAa,iBACX,UAEA,CAAC,CAAC,SAAS,OAAO,UAAU,YAAY,CAAC,MAAM,QAAQ,KAAK;;;;;;;AAe9D,IAAa,gBAAb,MAA2B;CACzB;CACA;CACA;CACA;CAEA;CACA;CACA,4BAA6B,IAAI,IAG/B;CACF;CACA,iCAAkC,IAAI,IAAoB;CAC1D;CACA,uBAA+B;CAC/B,4BAA6B,IAAI,IAA2B;CAC5D;CACA,YAIM,CAAC;CACP,kBAA0B;CAC1B,0BAAkC;CAElC;CACA;CACA,cAAsB;CAEtB,YAAY,SAA+B;EACzC,KAAK,aAAa,QAAQ;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C,KAAK,cAAc;EACxB,KAAK,qBAAqB,KAAA;EAC1B,KAAK,KAAK;CACZ;AACF;AAEA,SAAgB,aAAa,OAAwB;CACnD,IAAI,CAAC,OAAO,OAAO;CACnB,IAAI;EACF,OAAO,KAAK,MAAM,KAAK;CACzB,QAAQ;EACN,OAAO;CACT;AACF"}
1
+ {"version":3,"file":"run-aggregator.js","names":[],"sources":["../../../src/runtime/adapter/run-aggregator.ts"],"sourcesContent":["\"use client\";\n\nimport {\n isMcpAppUri,\n type ChatModelRunResult,\n type MessageTiming,\n type ThreadAssistantMessagePart,\n type ToolCallMessagePart,\n type ToolModelContentPart,\n} from \"@assistant-ui/core\";\nimport { readMcpAppResourceUri } from \"../mcp-tool-result\";\nimport type { AgUiEvent, AgUiInterrupt } from \"../types\";\nimport type { Logger } from \"../logger\";\n\nexport const AG_UI_METADATA_NAMESPACE = \"agui\";\n\nexport type AgUiCustomMetadata = {\n interrupts?: AgUiInterrupt[];\n};\n\ntype Emit = (update: ChatModelRunResult) => void;\n\ntype ToolCallState = {\n toolCallId: string;\n toolCallName: string;\n argsText: string;\n parsedArgs: Record<string, unknown> | undefined;\n result: unknown;\n isError: boolean | undefined;\n parentMessageId?: string;\n toolMessageId?: string;\n mcpAppResourceUri?: string;\n mcpAppServerId?: string;\n modelContent?: ToolModelContentPart[];\n snapshotResultApplied: boolean;\n};\n\nexport const MCP_APPS_ACTIVITY_TYPE = \"mcp-apps\";\n\nexport const isPlainObject = (\n value: unknown,\n): value is Record<string, unknown> =>\n !!value && typeof value === \"object\" && !Array.isArray(value);\n\nexport type RunAggregatorOptions = {\n showThinking: boolean;\n logger: Logger;\n emit: Emit;\n onServerMessageId?: (messageId: string) => void;\n};\n\n/**\n * Collects AG-UI events into assistant-ui run snapshots that can be yielded from a ChatModelAdapter.\n *\n * The aggregator keeps a single assistant message worth of parts. Each incoming event updates the parts and\n * emits a fresh snapshot through the provided `emit` callback.\n */\nexport class RunAggregator {\n private readonly emitUpdate: Emit;\n private readonly showThinking: boolean;\n private readonly logger: Logger;\n private readonly onServerMessageId: ((messageId: string) => void) | undefined;\n\n private status: ChatModelRunResult[\"status\"] | undefined;\n private interrupts: AgUiInterrupt[] | undefined;\n private readonly textParts = new Map<\n string,\n { buffer: string; touched: boolean }\n >();\n private activeTextMessageId: string | undefined;\n private readonly reasoningParts = new Map<string, string>(); // key → buffer\n private activeReasoningKey: string | undefined;\n private reasoningPartCounter = 0;\n private readonly toolCalls = new Map<string, ToolCallState>();\n private lastResolvedToolCallId: string | undefined;\n private readonly partOrder: (\n | { kind: \"text\"; key: string }\n | { kind: \"reasoning\"; key: string }\n | { kind: \"tool-call\"; toolCallId: string }\n )[] = [];\n private textPartCounter = 0;\n private serverMessageIdReported = false;\n\n private streamStartTime: number | undefined;\n private firstTokenTime: number | undefined;\n private totalChunks = 0;\n\n constructor(options: RunAggregatorOptions) {\n this.emitUpdate = options.emit;\n this.showThinking = options.showThinking;\n this.logger = options.logger;\n this.onServerMessageId = options.onServerMessageId;\n }\n\n hasToolCall(toolCallId: string): boolean {\n return this.toolCalls.has(toolCallId);\n }\n\n handle(event: AgUiEvent): void {\n switch (event.type) {\n case \"RUN_STARTED\": {\n this.clearTextParts();\n this.reasoningParts.clear();\n this.activeReasoningKey = undefined;\n this.reasoningPartCounter = 0;\n this.toolCalls.clear();\n this.lastResolvedToolCallId = undefined;\n this.partOrder.length = 0;\n this.textPartCounter = 0;\n this.activeTextMessageId = undefined;\n this.interrupts = undefined;\n this.serverMessageIdReported = false;\n this.streamStartTime = Date.now();\n this.firstTokenTime = undefined;\n this.totalChunks = 0;\n this.status = { type: \"running\" };\n this.emit();\n break;\n }\n case \"RUN_FINISHED\": {\n if (event.outcome?.type === \"interrupt\") {\n this.interrupts = event.outcome.interrupts;\n this.status = { type: \"requires-action\", reason: \"interrupt\" };\n this.emit();\n break;\n }\n\n this.interrupts = undefined;\n const hasUnresolvedToolCalls = Array.from(this.toolCalls.values()).some(\n (tc) => tc.result === undefined,\n );\n\n this.status =\n event.outcome?.type === \"success\" || !hasUnresolvedToolCalls\n ? { type: \"complete\", reason: \"unknown\" }\n : { type: \"requires-action\", reason: \"tool-calls\" };\n this.emit();\n break;\n }\n case \"RUN_ERROR\": {\n this.status = {\n type: \"incomplete\",\n reason: \"error\",\n ...(event.message !== undefined ? { error: event.message } : {}),\n };\n this.emit();\n break;\n }\n case \"RUN_CANCELLED\": {\n this.status = { type: \"incomplete\", reason: \"cancelled\" };\n this.emit();\n break;\n }\n\n case \"TEXT_MESSAGE_START\": {\n this.reportServerMessageId(event.messageId);\n const id = this.startTextMessage(event.messageId);\n if (id) {\n this.markTextPartTouched(id);\n }\n this.emit();\n break;\n }\n case \"TEXT_MESSAGE_CONTENT\":\n case \"TEXT_MESSAGE_CHUNK\": {\n const incomingId = \"messageId\" in event ? event.messageId : undefined;\n this.reportServerMessageId(incomingId);\n if (!event.delta) break;\n this.recordFirstToken();\n const id = this.resolveTextMessageId(incomingId);\n this.appendText(id, event.delta);\n this.totalChunks++;\n this.emit();\n break;\n }\n case \"TEXT_MESSAGE_END\": {\n this.reportServerMessageId(event.messageId);\n if (event.messageId && this.activeTextMessageId === event.messageId) {\n this.activeTextMessageId = undefined;\n }\n this.emit();\n break;\n }\n\n case \"THINKING_START\":\n case \"THINKING_TEXT_MESSAGE_START\":\n case \"REASONING_START\":\n case \"REASONING_MESSAGE_START\":\n this.handleReasoningStart(\n \"messageId\" in event ? event.messageId : undefined,\n );\n break;\n case \"THINKING_TEXT_MESSAGE_CONTENT\":\n this.handleReasoningContent(event.delta);\n this.totalChunks++;\n this.recordFirstToken();\n break;\n case \"REASONING_MESSAGE_CONTENT\":\n this.handleReasoningContent(\n event.delta,\n \"messageId\" in event ? event.messageId : undefined,\n );\n this.totalChunks++;\n this.recordFirstToken();\n break;\n case \"THINKING_TEXT_MESSAGE_END\":\n case \"THINKING_END\":\n case \"REASONING_MESSAGE_END\":\n case \"REASONING_END\":\n this.handleReasoningEnd();\n break;\n\n case \"TOOL_CALL_START\": {\n this.reportServerMessageId(event.parentMessageId);\n this.startToolCall(\n event.toolCallId,\n event.toolCallName,\n event.parentMessageId,\n );\n this.emit();\n break;\n }\n case \"TOOL_CALL_ARGS\":\n case \"TOOL_CALL_CHUNK\": {\n if (event.type === \"TOOL_CALL_CHUNK\") {\n this.reportServerMessageId(event.parentMessageId);\n }\n if (!event.delta) break;\n this.appendToolArgs(event.toolCallId, event.delta);\n this.emit();\n break;\n }\n case \"TOOL_CALL_END\": {\n this.emit();\n break;\n }\n case \"TOOL_CALL_RESULT\": {\n this.finishToolCall(\n event.toolCallId,\n event.content ?? \"\",\n typeof event.mcpResult?.isError === \"boolean\"\n ? event.mcpResult.isError\n : event.role === \"tool\"\n ? false\n : undefined,\n event.messageId,\n event.mcpResult,\n );\n this.emit();\n break;\n }\n case \"ACTIVITY_SNAPSHOT\": {\n if (event.activityType !== MCP_APPS_ACTIVITY_TYPE) break;\n const toolCallId = event.content.toolCallId;\n const entry =\n typeof toolCallId === \"string\"\n ? this.toolCalls.get(toolCallId)\n : this.lastResolvedToolCallId\n ? this.toolCalls.get(this.lastResolvedToolCallId)\n : undefined;\n const resourceUri = event.content.resourceUri;\n if (\n entry &&\n typeof resourceUri === \"string\" &&\n isMcpAppUri(resourceUri)\n ) {\n entry.mcpAppResourceUri = resourceUri;\n const id = event.content.serverId;\n const hash = event.content.serverHash;\n if (typeof id === \"string\" && id.length > 0) {\n entry.mcpAppServerId = id;\n } else if (typeof hash === \"string\" && hash.length > 0) {\n entry.mcpAppServerId = hash;\n }\n const result = event.content.result;\n if (isPlainObject(result)) {\n if (\n entry.result !== undefined &&\n entry.modelContent === undefined\n ) {\n entry.modelContent = [\n {\n type: \"text\",\n text:\n typeof entry.result === \"string\"\n ? entry.result\n : JSON.stringify(entry.result),\n },\n ];\n }\n entry.result = result;\n entry.snapshotResultApplied = true;\n if (typeof result.isError === \"boolean\") {\n entry.isError = result.isError;\n }\n }\n this.emit();\n }\n break;\n }\n\n default: {\n this.logger.debug?.(\"[agui] aggregator ignored event\", event);\n }\n }\n }\n\n private reportServerMessageId(messageId: string | undefined): void {\n if (this.serverMessageIdReported || !messageId) return;\n this.serverMessageIdReported = true;\n this.onServerMessageId?.(messageId);\n }\n\n private clearTextParts(): void {\n this.textParts.clear();\n }\n\n private generateTextKey(): string {\n this.textPartCounter += 1;\n return `text-${this.textPartCounter}`;\n }\n\n private startTextMessage(messageId?: string): string {\n const id = messageId ?? this.generateTextKey();\n this.ensureTextPart(id);\n this.activeTextMessageId = id;\n return id;\n }\n\n private resolveTextMessageId(messageId?: string): string {\n if (messageId) {\n this.ensureTextPart(messageId);\n this.activeTextMessageId = messageId;\n return messageId;\n }\n\n if (this.activeTextMessageId) {\n return this.activeTextMessageId;\n }\n\n const generated = this.generateTextKey();\n this.ensureTextPart(generated);\n this.activeTextMessageId = generated;\n return generated;\n }\n\n private ensureTextPart(id: string): void {\n if (!this.textParts.has(id)) {\n this.textParts.set(id, { buffer: \"\", touched: false });\n if (\n !this.partOrder.some((part) => part.kind === \"text\" && part.key === id)\n ) {\n this.partOrder.push({ kind: \"text\", key: id });\n }\n }\n }\n\n private markTextPartTouched(id: string): void {\n const entry = this.textParts.get(id);\n if (!entry) return;\n entry.touched = true;\n }\n\n private appendText(id: string, delta: string): void {\n this.ensureTextPart(id);\n const entry = this.textParts.get(id);\n if (!entry) return;\n entry.buffer += delta;\n entry.touched = true;\n }\n\n private startToolCall(\n id: string | undefined,\n name?: string,\n parentMessageId?: string,\n ) {\n if (!id) return;\n // A new tool call acts as a boundary: any anonymous text that arrives\n // after it should be a new part, not appended to the pre-tool text.\n this.activeTextMessageId = undefined;\n if (\n !this.partOrder.some(\n (part) => part.kind === \"tool-call\" && part.toolCallId === id,\n )\n ) {\n this.insertToolPart(id, parentMessageId);\n }\n const state: ToolCallState = {\n toolCallId: id,\n toolCallName: name ?? \"tool\",\n argsText: \"\",\n parsedArgs: undefined,\n result: undefined,\n isError: undefined,\n snapshotResultApplied: false,\n };\n if (parentMessageId) {\n state.parentMessageId = parentMessageId;\n }\n this.toolCalls.set(id, state);\n }\n\n // The message and tool-call channels are unordered on the wire, so anchor a\n // tool call under its parentMessageId text part instead of appending it.\n private insertToolPart(id: string, parentMessageId?: string) {\n const entry = { kind: \"tool-call\", toolCallId: id } as const;\n if (parentMessageId) {\n const parentIndex = this.partOrder.findIndex(\n (part) => part.kind === \"text\" && part.key === parentMessageId,\n );\n if (parentIndex !== -1) {\n let insertAt = parentIndex + 1;\n while (insertAt < this.partOrder.length) {\n const part = this.partOrder[insertAt];\n if (\n part?.kind === \"tool-call\" &&\n this.toolCalls.get(part.toolCallId)?.parentMessageId ===\n parentMessageId\n ) {\n insertAt += 1;\n continue;\n }\n break;\n }\n this.partOrder.splice(insertAt, 0, entry);\n return;\n }\n }\n this.partOrder.push(entry);\n }\n\n private appendToolArgs(id: string | undefined, delta: string) {\n const entry = id ? this.toolCalls.get(id) : undefined;\n if (!entry) return;\n entry.argsText += delta;\n try {\n const parsed = JSON.parse(entry.argsText);\n if (parsed && typeof parsed === \"object\") {\n entry.parsedArgs = parsed as Record<string, unknown>;\n } else {\n entry.parsedArgs = undefined;\n }\n } catch {\n entry.parsedArgs = undefined;\n }\n }\n\n private finishToolCall(\n id: string,\n content: string,\n isError?: boolean,\n toolMessageId?: string,\n mcpResult?: Record<string, unknown>,\n ) {\n if (!id) return;\n let entry = this.toolCalls.get(id);\n if (!entry) {\n entry = {\n toolCallId: id,\n toolCallName: \"tool\",\n argsText: \"\",\n parsedArgs: undefined,\n result: undefined,\n isError: undefined,\n snapshotResultApplied: false,\n };\n this.toolCalls.set(id, entry);\n }\n if (\n !this.partOrder.some(\n (part) => part.kind === \"tool-call\" && part.toolCallId === id,\n )\n ) {\n this.partOrder.push({ kind: \"tool-call\", toolCallId: id });\n }\n if (mcpResult !== undefined && !entry.snapshotResultApplied) {\n entry.result = mcpResult;\n entry.modelContent = [{ type: \"text\", text: content }];\n entry.snapshotResultApplied = true;\n entry.isError = isError;\n if (entry.mcpAppResourceUri === undefined) {\n const uri = readMcpAppResourceUri(mcpResult._meta);\n if (uri !== undefined) entry.mcpAppResourceUri = uri;\n }\n } else if (entry.snapshotResultApplied) {\n if (entry.modelContent === undefined) {\n entry.modelContent = [{ type: \"text\", text: content }];\n }\n if (entry.isError === undefined) {\n entry.isError = isError;\n }\n } else {\n entry.result = tryParseJSON(content);\n entry.isError = isError;\n }\n if (toolMessageId) {\n entry.toolMessageId = toolMessageId;\n }\n this.lastResolvedToolCallId = id;\n }\n\n private emit(): void {\n const snapshot: ThreadAssistantMessagePart[] = [];\n\n for (const part of this.partOrder) {\n if (part.kind === \"reasoning\") {\n if (this.showThinking) {\n const buffer = this.reasoningParts.get(part.key) ?? \"\";\n if (buffer.length > 0 || this.activeReasoningKey === part.key) {\n snapshot.push({ type: \"reasoning\", text: buffer } as const);\n }\n }\n continue;\n }\n\n if (part.kind === \"text\") {\n const entry = this.textParts.get(part.key);\n if (entry?.touched) {\n snapshot.push({ type: \"text\", text: entry.buffer } as const);\n }\n continue;\n }\n\n const entry = this.toolCalls.get(part.toolCallId);\n if (!entry) continue;\n const toolPart: ToolCallMessagePart = {\n type: \"tool-call\",\n toolCallId: entry.toolCallId,\n toolName: entry.toolCallName,\n args: (entry.parsedArgs ?? {}) as any,\n argsText: entry.argsText,\n ...(entry.result !== undefined ? { result: entry.result } : {}),\n ...(entry.modelContent !== undefined\n ? { modelContent: entry.modelContent }\n : {}),\n ...(entry.isError !== undefined ? { isError: entry.isError } : {}),\n ...(entry.mcpAppResourceUri\n ? {\n mcp: {\n app: {\n resourceUri: entry.mcpAppResourceUri,\n ...(entry.mcpAppServerId\n ? { serverId: entry.mcpAppServerId }\n : {}),\n },\n },\n }\n : {}),\n ...(entry.parentMessageId ? { parentId: entry.parentMessageId } : {}),\n ...(entry.toolMessageId\n ? { unstable_toolMessageId: entry.toolMessageId }\n : {}),\n } as ToolCallMessagePart & { unstable_toolMessageId?: string };\n snapshot.push(toolPart);\n }\n\n const timing = this.getTiming();\n const metadata = {\n ...(timing ? { timing } : {}),\n ...(this.interrupts\n ? {\n custom: {\n [AG_UI_METADATA_NAMESPACE]: {\n interrupts: this.interrupts,\n } satisfies AgUiCustomMetadata,\n },\n }\n : {}),\n };\n const result: ChatModelRunResult = {\n content: snapshot,\n ...(this.status ? { status: this.status } : undefined),\n ...(Object.keys(metadata).length > 0 ? { metadata } : undefined),\n };\n this.emitUpdate(result);\n }\n\n private recordFirstToken(): void {\n if (\n this.firstTokenTime === undefined &&\n this.streamStartTime !== undefined\n ) {\n this.firstTokenTime = Date.now() - this.streamStartTime;\n }\n }\n\n private getTiming(): MessageTiming | undefined {\n if (this.streamStartTime === undefined) return undefined;\n\n const now = Date.now();\n const totalStreamTime = now - this.streamStartTime;\n const tokenCount =\n this.totalChunks > 0\n ? Math.ceil(\n Array.from(this.textParts.values()).reduce(\n (sum, p) => sum + p.buffer.length,\n 0,\n ) / 4,\n )\n : undefined;\n const tokensPerSecond =\n tokenCount && totalStreamTime > 0\n ? (tokenCount / totalStreamTime) * 1000\n : undefined;\n\n return {\n streamStartTime: this.streamStartTime,\n ...(this.firstTokenTime !== undefined\n ? { firstTokenTime: this.firstTokenTime }\n : {}),\n totalStreamTime,\n ...(tokenCount !== undefined ? { tokenCount } : {}),\n ...(tokensPerSecond !== undefined ? { tokensPerSecond } : {}),\n totalChunks: this.totalChunks,\n toolCallCount: this.toolCalls.size,\n };\n }\n\n private handleReasoningStart(messageId?: string): void {\n if (!this.showThinking) return;\n // A reasoning block acts as a boundary: anonymous text arriving after it\n // should be a new part, not appended to any pre-reasoning text.\n this.activeTextMessageId = undefined;\n const key = messageId ?? `__auto-reasoning-${++this.reasoningPartCounter}`;\n if (!this.reasoningParts.has(key)) {\n this.reasoningParts.set(key, \"\");\n this.partOrder.push({ kind: \"reasoning\", key });\n }\n this.activeReasoningKey = key;\n this.emit();\n }\n\n private handleReasoningContent(delta: string, messageId?: string): void {\n if (!this.showThinking || !delta) return;\n if (!this.activeReasoningKey) {\n // Content arrived without a preceding START — create the slot lazily.\n this.handleReasoningStart(messageId);\n }\n const key = this.activeReasoningKey;\n if (!key) return;\n this.reasoningParts.set(key, (this.reasoningParts.get(key) ?? \"\") + delta);\n this.emit();\n }\n\n private handleReasoningEnd(): void {\n if (!this.showThinking) return;\n this.activeReasoningKey = undefined;\n this.emit();\n }\n}\n\nexport function tryParseJSON(value: string): unknown {\n if (!value) return value;\n try {\n return JSON.parse(value);\n } catch {\n return value;\n }\n}\n"],"mappings":";;;;AAcA,MAAa,2BAA2B;AAuBxC,MAAa,yBAAyB;AAEtC,MAAa,iBACX,UAEA,CAAC,CAAC,SAAS,OAAO,UAAU,YAAY,CAAC,MAAM,QAAQ,KAAK;;;;;;;AAe9D,IAAa,gBAAb,MAA2B;CACzB;CACA;CACA;CACA;CAEA;CACA;CACA,4BAA6B,IAAI,IAG/B;CACF;CACA,iCAAkC,IAAI,IAAoB;CAC1D;CACA,uBAA+B;CAC/B,4BAA6B,IAAI,IAA2B;CAC5D;CACA,YAIM,CAAC;CACP,kBAA0B;CAC1B,0BAAkC;CAElC;CACA;CACA,cAAsB;CAEtB,YAAY,SAA+B;EACzC,KAAK,aAAa,QAAQ;EAC1B,KAAK,eAAe,QAAQ;EAC5B,KAAK,SAAS,QAAQ;EACtB,KAAK,oBAAoB,QAAQ;CACnC;CAEA,YAAY,YAA6B;EACvC,OAAO,KAAK,UAAU,IAAI,UAAU;CACtC;CAEA,OAAO,OAAwB;EAC7B,QAAQ,MAAM,MAAd;GACE,KAAK;IACH,KAAK,eAAe;IACpB,KAAK,eAAe,MAAM;IAC1B,KAAK,qBAAqB,KAAA;IAC1B,KAAK,uBAAuB;IAC5B,KAAK,UAAU,MAAM;IACrB,KAAK,yBAAyB,KAAA;IAC9B,KAAK,UAAU,SAAS;IACxB,KAAK,kBAAkB;IACvB,KAAK,sBAAsB,KAAA;IAC3B,KAAK,aAAa,KAAA;IAClB,KAAK,0BAA0B;IAC/B,KAAK,kBAAkB,KAAK,IA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KAAK;GACtB,GAAI,KAAK,mBAAmB,KAAA,IACxB,EAAE,gBAAgB,KAAK,eAAe,IACtC,CAAC;GACL;GACA,GAAI,eAAe,KAAA,IAAY,EAAE,WAAW,IAAI,CAAC;GACjD,GAAI,oBAAoB,KAAA,IAAY,EAAE,gBAAgB,IAAI,CAAC;GAC3D,aAAa,KAAK;GAClB,eAAe,KAAK,UAAU;EAChC;CACF;CAEA,qBAA6B,WAA0B;EACrD,IAAI,CAAC,KAAK,cAAc;EAGxB,KAAK,sBAAsB,KAAA;EAC3B,MAAM,MAAM,aAAa,oBAAoB,EAAE,KAAK;EACpD,IAAI,CAAC,KAAK,eAAe,IAAI,GAAG,GAAG;GACjC,KAAK,eAAe,IAAI,KAAK,EAAE;GAC/B,KAAK,UAAU,KAAK;IAAE,MAAM;IAAa;GAAI,CAAC;EAChD;EACA,KAAK,qBAAqB;EAC1B,KAAK,KAAK;CACZ;CAEA,uBAA+B,OAAe,WAA0B;EACtE,IAAI,CAAC,KAAK,gBAAgB,CAAC,OAAO;EAClC,IAAI,CAAC,KAAK,oBAER,KAAK,qBAAqB,SAAS;EAErC,MAAM,MAAM,KAAK;EACjB,IAAI,CAAC,KAAK;EACV,KAAK,eAAe,IAAI,MAAM,KAAK,eAAe,IAAI,GAAG,KAAK,MAAM,KAAK;EACzE,KAAK,KAAK;CACZ;CAEA,qBAAmC;EACjC,IAAI,CAAC,KAAK,cAAc;EACxB,KAAK,qBAAqB,KAAA;EAC1B,KAAK,KAAK;CACZ;AACF;AAEA,SAAgB,aAAa,OAAwB;CACnD,IAAI,CAAC,OAAO,OAAO;CACnB,IAAI;EACF,OAAO,KAAK,MAAM,KAAK;CACzB,QAAQ;EACN,OAAO;CACT;AACF"}
@@ -6,6 +6,7 @@ type McpToolCallResult = Record<string, unknown> & {
6
6
  isError?: boolean;
7
7
  };
8
8
  declare const parseMcpToolCallResult: (source: Record<string, unknown>, modelContent: string) => McpToolCallResult | undefined;
9
+ declare const readMcpAppResourceUri: (meta: unknown) => string | undefined;
9
10
  //#endregion
10
- export { McpToolCallResult, parseMcpToolCallResult };
11
+ export { McpToolCallResult, parseMcpToolCallResult, readMcpAppResourceUri };
11
12
  //# sourceMappingURL=mcp-tool-result.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"mcp-tool-result.d.ts","names":[],"sources":["../../src/runtime/mcp-tool-result.ts"],"mappings":";KAEY,oBAAoB;EAC9B;EACA,oBAAoB;EACpB,QAAQ;EACR;;cAGW,yBACX,QAAQ,yBACR,yBACC"}
1
+ {"version":3,"file":"mcp-tool-result.d.ts","names":[],"sources":["../../src/runtime/mcp-tool-result.ts"],"mappings":";KAGY,oBAAoB;EAC9B;EACA,oBAAoB;EACpB,QAAQ;EACR;;cAGW,yBACX,QAAQ,yBACR,yBACC;cAmBU,wBAAyB"}
@@ -1,4 +1,5 @@
1
1
  import { isRecord } from "@assistant-ui/core/internal";
2
+ import { isMcpAppUri } from "@assistant-ui/core";
2
3
  //#region src/runtime/mcp-tool-result.ts
3
4
  const parseMcpToolCallResult = (source, modelContent) => {
4
5
  const structuredContent = isRecord(source.structuredContent) ? source.structuredContent : void 0;
@@ -14,7 +15,12 @@ const parseMcpToolCallResult = (source, modelContent) => {
14
15
  ...typeof source.isError === "boolean" ? { isError: source.isError } : {}
15
16
  };
16
17
  };
18
+ const readMcpAppResourceUri = (meta) => {
19
+ if (!isRecord(meta)) return void 0;
20
+ const uri = meta["ui/resourceUri"];
21
+ return typeof uri === "string" && isMcpAppUri(uri) ? uri : void 0;
22
+ };
17
23
  //#endregion
18
- export { parseMcpToolCallResult };
24
+ export { parseMcpToolCallResult, readMcpAppResourceUri };
19
25
 
20
26
  //# sourceMappingURL=mcp-tool-result.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"mcp-tool-result.js","names":[],"sources":["../../src/runtime/mcp-tool-result.ts"],"sourcesContent":["import { isRecord } from \"@assistant-ui/core/internal\";\n\nexport type McpToolCallResult = Record<string, unknown> & {\n content: unknown[];\n structuredContent?: Record<string, unknown>;\n _meta?: Record<string, unknown>;\n isError?: boolean;\n};\n\nexport const parseMcpToolCallResult = (\n source: Record<string, unknown>,\n modelContent: string,\n): McpToolCallResult | undefined => {\n const structuredContent = isRecord(source.structuredContent)\n ? source.structuredContent\n : undefined;\n const meta = isRecord(source._meta) ? source._meta : undefined;\n if (!structuredContent && !meta) return undefined;\n\n return {\n content: modelContent ? [{ type: \"text\", text: modelContent }] : [],\n ...(structuredContent ? { structuredContent } : {}),\n ...(meta ? { _meta: meta } : {}),\n ...(typeof source.isError === \"boolean\" ? { isError: source.isError } : {}),\n };\n};\n"],"mappings":";;AASA,MAAa,0BACX,QACA,iBACkC;CAClC,MAAM,oBAAoB,SAAS,OAAO,iBAAiB,IACvD,OAAO,oBACP,KAAA;CACJ,MAAM,OAAO,SAAS,OAAO,KAAK,IAAI,OAAO,QAAQ,KAAA;CACrD,IAAI,CAAC,qBAAqB,CAAC,MAAM,OAAO,KAAA;CAExC,OAAO;EACL,SAAS,eAAe,CAAC;GAAE,MAAM;GAAQ,MAAM;EAAa,CAAC,IAAI,CAAC;EAClE,GAAI,oBAAoB,EAAE,kBAAkB,IAAI,CAAC;EACjD,GAAI,OAAO,EAAE,OAAO,KAAK,IAAI,CAAC;EAC9B,GAAI,OAAO,OAAO,YAAY,YAAY,EAAE,SAAS,OAAO,QAAQ,IAAI,CAAC;CAC3E;AACF"}
1
+ {"version":3,"file":"mcp-tool-result.js","names":[],"sources":["../../src/runtime/mcp-tool-result.ts"],"sourcesContent":["import { isRecord } from \"@assistant-ui/core/internal\";\nimport { isMcpAppUri } from \"@assistant-ui/core\";\n\nexport type McpToolCallResult = Record<string, unknown> & {\n content: unknown[];\n structuredContent?: Record<string, unknown>;\n _meta?: Record<string, unknown>;\n isError?: boolean;\n};\n\nexport const parseMcpToolCallResult = (\n source: Record<string, unknown>,\n modelContent: string,\n): McpToolCallResult | undefined => {\n const structuredContent = isRecord(source.structuredContent)\n ? source.structuredContent\n : undefined;\n const meta = isRecord(source._meta) ? source._meta : undefined;\n if (!structuredContent && !meta) return undefined;\n\n return {\n content: modelContent ? [{ type: \"text\", text: modelContent }] : [],\n ...(structuredContent ? { structuredContent } : {}),\n ...(meta ? { _meta: meta } : {}),\n ...(typeof source.isError === \"boolean\" ? { isError: source.isError } : {}),\n };\n};\n\n// _meta[\"ui/resourceUri\"] is the MCP-UI pointer react-ai-sdk reads off\n// CallToolResult._meta; only ui:// URIs identify an MCP Apps widget. A\n// structured carrier is deliberately not read until upstream AG-UI settles\n// one (agno-agi/agno#9087).\nexport const readMcpAppResourceUri = (meta: unknown): string | undefined => {\n if (!isRecord(meta)) return undefined;\n const uri = meta[\"ui/resourceUri\"];\n return typeof uri === \"string\" && isMcpAppUri(uri) ? uri : undefined;\n};\n"],"mappings":";;;AAUA,MAAa,0BACX,QACA,iBACkC;CAClC,MAAM,oBAAoB,SAAS,OAAO,iBAAiB,IACvD,OAAO,oBACP,KAAA;CACJ,MAAM,OAAO,SAAS,OAAO,KAAK,IAAI,OAAO,QAAQ,KAAA;CACrD,IAAI,CAAC,qBAAqB,CAAC,MAAM,OAAO,KAAA;CAExC,OAAO;EACL,SAAS,eAAe,CAAC;GAAE,MAAM;GAAQ,MAAM;EAAa,CAAC,IAAI,CAAC;EAClE,GAAI,oBAAoB,EAAE,kBAAkB,IAAI,CAAC;EACjD,GAAI,OAAO,EAAE,OAAO,KAAK,IAAI,CAAC;EAC9B,GAAI,OAAO,OAAO,YAAY,YAAY,EAAE,SAAS,OAAO,QAAQ,IAAI,CAAC;CAC3E;AACF;AAMA,MAAa,yBAAyB,SAAsC;CAC1E,IAAI,CAAC,SAAS,IAAI,GAAG,OAAO,KAAA;CAC5B,MAAM,MAAM,KAAK;CACjB,OAAO,OAAO,QAAQ,YAAY,YAAY,GAAG,IAAI,MAAM,KAAA;AAC7D"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@assistant-ui/react-ag-ui",
3
- "version": "0.0.46",
3
+ "version": "0.0.47",
4
4
  "description": "AG-UI protocol adapter for assistant-ui",
5
5
  "keywords": [
6
6
  "ag-ui",
@@ -30,9 +30,9 @@
30
30
  "sideEffects": false,
31
31
  "dependencies": {
32
32
  "@ag-ui/client": "^0.0.57",
33
- "@assistant-ui/core": "^0.2.22",
34
- "@assistant-ui/store": "^0.2.21",
35
- "assistant-stream": "^0.3.27",
33
+ "@assistant-ui/core": "^0.2.23",
34
+ "@assistant-ui/store": "^0.2.22",
35
+ "assistant-stream": "^0.3.28",
36
36
  "fast-json-patch": "^3.1.1"
37
37
  },
38
38
  "peerDependencies": {
@@ -49,7 +49,7 @@
49
49
  "react": "^19.2.8",
50
50
  "vitest": "^4.1.10",
51
51
  "zod": "^4.4.3",
52
- "@assistant-ui/x-buildutils": "0.0.19"
52
+ "@assistant-ui/x-buildutils": "0.0.20"
53
53
  },
54
54
  "publishConfig": {
55
55
  "access": "public",
@@ -23,6 +23,7 @@ import { MessageRepository } from "@assistant-ui/core/internal";
23
23
  import type { AbstractAgent } from "@ag-ui/client";
24
24
  import jsonpatch, { type Operation } from "fast-json-patch";
25
25
  import type { Logger } from "./logger";
26
+ import { readMcpAppResourceUri } from "./mcp-tool-result";
26
27
  import type { AgUiEvent, AgUiInterrupt, AgUiResumeEntry } from "./types";
27
28
  import type { ReadonlyJSONValue } from "assistant-stream/utils";
28
29
  import {
@@ -1373,6 +1374,7 @@ export class AgUiThreadRuntimeCore {
1373
1374
  const updated = this.updateMessage(messageId, (message) => {
1374
1375
  if (message.role !== "assistant") return message;
1375
1376
  const assistant = message as ThreadAssistantMessage;
1377
+ const mcpAppUri = readMcpAppResourceUri(event.mcpResult?._meta);
1376
1378
  let matchedToolCall = false;
1377
1379
  const content = assistant.content.map((part) => {
1378
1380
  if (part.type !== "tool-call" || part.toolCallId !== event.toolCallId)
@@ -1421,6 +1423,9 @@ export class AgUiThreadRuntimeCore {
1421
1423
  : event.role === "tool"
1422
1424
  ? { isError: false }
1423
1425
  : {}),
1426
+ ...(part.mcp === undefined && mcpAppUri !== undefined
1427
+ ? { mcp: { app: { resourceUri: mcpAppUri } } }
1428
+ : {}),
1424
1429
  ...(event.messageId
1425
1430
  ? { unstable_toolMessageId: event.messageId }
1426
1431
  : {}),
@@ -3,6 +3,7 @@
3
3
  import type { InputContent } from "@ag-ui/client";
4
4
  import type {
5
5
  ThreadMessageLike as CoreThreadMessageLike,
6
+ ToolCallMessagePartMcpMetadata,
6
7
  ToolModelContentPart,
7
8
  } from "@assistant-ui/core";
8
9
  import {
@@ -17,7 +18,10 @@ import {
17
18
  type AgUiCustomMetadata,
18
19
  } from "./run-aggregator";
19
20
  import type { AgUiInterrupt } from "../types";
20
- import { parseMcpToolCallResult } from "../mcp-tool-result";
21
+ import {
22
+ parseMcpToolCallResult,
23
+ readMcpAppResourceUri,
24
+ } from "../mcp-tool-result";
21
25
 
22
26
  export type { InputContent };
23
27
 
@@ -69,6 +73,7 @@ type ToolCallPart = {
69
73
  isError?: boolean;
70
74
  modelContent?: readonly ToolModelContentPart[];
71
75
  unstable_toolMessageId?: string;
76
+ mcp?: ToolCallMessagePartMcpMetadata;
72
77
  };
73
78
 
74
79
  const isObject = (value: unknown): value is Record<string, unknown> =>
@@ -555,6 +560,9 @@ export function fromAgUiMessages(
555
560
  : rawMessage.isError === false
556
561
  ? false
557
562
  : undefined;
563
+ const mcpAppUri = readMcpAppResourceUri(mcpResult?._meta);
564
+ const mcpApp =
565
+ mcpAppUri !== undefined ? { resourceUri: mcpAppUri } : undefined;
558
566
 
559
567
  let updated = false;
560
568
  for (
@@ -587,6 +595,7 @@ export function fromAgUiMessages(
587
595
  ...(toolMessageId !== undefined
588
596
  ? { unstable_toolMessageId: toolMessageId }
589
597
  : {}),
598
+ ...(mcpApp ? { mcp: { app: mcpApp } } : {}),
590
599
  };
591
600
  const updatedContent = message.content.map((contentPart, index) =>
592
601
  index === partIndex ? updatedPart : contentPart,
@@ -622,6 +631,7 @@ export function fromAgUiMessages(
622
631
  ...(toolMessageId !== undefined
623
632
  ? { unstable_toolMessageId: toolMessageId }
624
633
  : {}),
634
+ ...(mcpApp ? { mcp: { app: mcpApp } } : {}),
625
635
  },
626
636
  ],
627
637
  });
@@ -8,6 +8,7 @@ import {
8
8
  type ToolCallMessagePart,
9
9
  type ToolModelContentPart,
10
10
  } from "@assistant-ui/core";
11
+ import { readMcpAppResourceUri } from "../mcp-tool-result";
11
12
  import type { AgUiEvent, AgUiInterrupt } from "../types";
12
13
  import type { Logger } from "../logger";
13
14
 
@@ -477,6 +478,10 @@ export class RunAggregator {
477
478
  entry.modelContent = [{ type: "text", text: content }];
478
479
  entry.snapshotResultApplied = true;
479
480
  entry.isError = isError;
481
+ if (entry.mcpAppResourceUri === undefined) {
482
+ const uri = readMcpAppResourceUri(mcpResult._meta);
483
+ if (uri !== undefined) entry.mcpAppResourceUri = uri;
484
+ }
480
485
  } else if (entry.snapshotResultApplied) {
481
486
  if (entry.modelContent === undefined) {
482
487
  entry.modelContent = [{ type: "text", text: content }];
@@ -1,4 +1,5 @@
1
1
  import { isRecord } from "@assistant-ui/core/internal";
2
+ import { isMcpAppUri } from "@assistant-ui/core";
2
3
 
3
4
  export type McpToolCallResult = Record<string, unknown> & {
4
5
  content: unknown[];
@@ -24,3 +25,13 @@ export const parseMcpToolCallResult = (
24
25
  ...(typeof source.isError === "boolean" ? { isError: source.isError } : {}),
25
26
  };
26
27
  };
28
+
29
+ // _meta["ui/resourceUri"] is the MCP-UI pointer react-ai-sdk reads off
30
+ // CallToolResult._meta; only ui:// URIs identify an MCP Apps widget. A
31
+ // structured carrier is deliberately not read until upstream AG-UI settles
32
+ // one (agno-agi/agno#9087).
33
+ export const readMcpAppResourceUri = (meta: unknown): string | undefined => {
34
+ if (!isRecord(meta)) return undefined;
35
+ const uri = meta["ui/resourceUri"];
36
+ return typeof uri === "string" && isMcpAppUri(uri) ? uri : undefined;
37
+ };