@wodecorp/openui-vue-headless 0.1.2 → 0.1.4

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":"index.mjs","names":["extractTextContent","isDev","PROVIDER_EXECUTED_TOOLS_UNSUPPORTED_MESSAGE","serialize"],"sources":["../src/store/ArtifactStorageContext.ts","../src/cloud/artifactStream.ts","../src/cloud/interpreter.ts","../src/cloud/sse.ts","../src/cloud/wire.ts","../src/cloud/artifactStorage.ts","../src/cloud/frontendTokenManager.ts","../src/stream/formats/openai-conversation-message-format.ts","../src/cloud/items.ts","../src/cloud/threadStorage.ts","../src/cloud/openuiCloud.ts","../src/cloud/pollInterval.ts","../src/cloud/OpenUICloudProvider.ts","../src/store/useStore.ts","../src/store/DetailedViewContext.ts","../src/hooks/useActiveDetailedView.ts","../src/store/ThreadContextContext.ts","../src/hooks/useArtifactList.ts","../src/store/ArtifactRenderersContext.ts","../src/hooks/useArtifactRenderer.ts","../src/hooks/useDetailedView.ts","../src/hooks/useDetailedViewPortalTarget.ts","../src/hooks/useMessage.ts","../src/store/ChatContext.ts","../src/hooks/useThread.ts","../src/store/toolActivity.ts","../src/hooks/useToolActivities.ts","../src/store/artifactCategories.ts","../src/store/ArtifactCategoriesContext.ts","../src/store/artifactRendererTypes.ts","../src/store/artifactViewId.ts","../src/adapters/_defaultStorage.ts","../src/store/artifactAutoOpenWatcher.ts","../src/adapters/httpError.ts","../src/types/messageFormat.ts","../src/stream/adapters/_shared/sseLines.ts","../src/stream/adapters/ag-ui.ts","../src/stream/adapters/eve.ts","../src/stream/adapters/langgraph.ts","../src/stream/adapters/openai-completions.ts","../src/stream/adapters/openai-readable-stream.ts","../src/stream/adapters/openai-responses.ts","../src/stream/adapters/vercel-ai-sdk.ts","../src/stream/processStreamedMessage.ts","../src/store/observability.ts","../src/store/createChatStore.ts","../src/store/createDetailedViewStore.ts","../src/store/createThreadContextStore.ts","../src/store/ChatProvider.ts","../src/stream/formats/langgraph-message-format.ts","../src/stream/formats/openai-message-format.ts","../src/stream/formats/vercel-ai-message-format.ts","../src/adapters/fetchLLM.ts","../src/adapters/restStorage.ts"],"sourcesContent":["import { inject, type InjectionKey } from \"vue\";\nimport type { ArtifactStorage } from \"../adapters/types\";\n\n/** @internal Provided by `ChatProvider` from `storage.artifact`. */\nexport const ArtifactStorageContext = Symbol(\"ArtifactStorageContext\") as InjectionKey<ArtifactStorage | null>;\n\n/**\n * Returns the configured global {@link ArtifactStorage} channel, or `null`\n * when the storage adapter doesn't provide one.\n *\n * Renderer implementations use this to lazily fetch (`get`) or persist\n * (`update`) artifact content; the artifact browser uses it for `list`.\n *\n * @category Hooks\n */\nexport const useArtifactStorage = (): ArtifactStorage | null => inject(ArtifactStorageContext, null);\n","import { computed, shallowRef, toValue, watch, type ComputedRef, type MaybeRefOrGetter } from \"vue\";\nimport type {\n ArtifactBuildStep,\n ArtifactStorage,\n ArtifactStreamEvent,\n ArtifactSummary,\n} from \"../adapters/types\";\nimport { useArtifactStorage } from \"../store/ArtifactStorageContext\";\n\n/** Why an artifact can't be shown. @category Types */\nexport type ArtifactStreamErrorCode =\n \"not-found\" | \"generation-failed\" | \"network-error\" | \"unauthorized\";\n\n/** @category Types */\nexport interface ArtifactStreamError {\n source: \"artifact\";\n code: ArtifactStreamErrorCode;\n message: string;\n /** The underlying error, for logs. `message` is meant for users. */\n cause?: unknown;\n}\n\n/** An artifact as it streams in. Replaced on every change, never mutated. @category Types */\nexport interface ArtifactStreamSnapshot extends Pick<ArtifactSummary, \"isOwner\" | \"isEditable\"> {\n id: string;\n type?: string;\n title?: string;\n /** The program to render. `null` until the first content arrives. */\n program: string | null;\n /** The stored version `program` is, so a script runs against the one on screen. */\n version?: string;\n isStreaming: boolean;\n /**\n * What a dashboard being built is doing, until it starts writing: the data tools it called\n * and the scripts it's saving. Undefined otherwise.\n */\n step?: ArtifactBuildStep;\n justUpdated: boolean;\n error: ArtifactStreamError | null;\n}\n\n/** Called on every change to an artifact's stream. @internal */\nexport type ArtifactStreamWatcher = (\n id: string,\n before: ArtifactStreamSnapshot,\n after: ArtifactStreamSnapshot,\n) => void;\n\ntype Settled = { program: string; version?: string };\n\ninterface Entry {\n snapshot: ArtifactStreamSnapshot;\n listeners: Set<() => void>;\n controller: AbortController | null;\n started: boolean;\n /** The version being streamed, from its `reference`. */\n version?: string;\n /** A new version streams into `program`, live; the same version again loads into `pending`. */\n target: \"program\" | \"pending\";\n pending: string;\n replace: boolean;\n /** What was on screen before a new version started streaming over it. A failed edit goes back to it. */\n settled: Settled | null;\n reconnects: number;\n versions: Set<string>;\n /** A newer revision was seen while a stream was still running. */\n stale: boolean;\n idleTimer: ReturnType<typeof setTimeout> | null;\n /** A re-read started by `versionMismatch`, and its pending answer. */\n reread: { version: string; answer: Promise<\"rerun\" | \"show\">; settle: Settle } | null;\n rereadAt: number;\n /** The last reference's `tag`: what a poll asks the server to compare. */\n tag?: string;\n /** Each polling renderer's interval. The shortest one wins. */\n pollers: Map<symbol, number>;\n pollTimer: ReturnType<typeof setTimeout> | null;\n /** Polls failed in a row; each one doubles the wait. */\n pollFailures: number;\n /** Turns `justUpdated` off again. */\n justUpdatedTimer: ReturnType<typeof setTimeout> | null;\n}\n\ntype Settle = (answer: \"rerun\" | \"show\") => void;\n\nconst MAX_RECONNECTS = 3;\n/** Refused data calls re-read an artifact at most this often, so they can't loop. */\nconst REREAD_INTERVAL_MS = 10_000;\n/** A connection that stayed open this long was healthy, so its drop doesn't count against `MAX_RECONNECTS`. */\nconst STABLE_CONNECTION_MS = 10_000;\nconst MIN_POLL_INTERVAL_MS = 3_000;\n/** The longest failures stretch the wait between checks, unless the interval itself is longer. */\nconst MAX_POLL_BACKOFF_MS = 5 * 60_000;\n/** The longest `setTimeout` takes: a longer wait would fire at once. */\nconst MAX_TIMEOUT_MS = 2 ** 31 - 1;\n/** How long `justUpdated` stays on. */\nconst JUST_UPDATED_MS = 10_000;\nconst ERROR_CODES = new Set<string>([\n \"not-found\",\n \"generation-failed\",\n \"network-error\",\n \"unauthorized\",\n]);\n\n/** A step's names, or `undefined` for an empty or malformed one. */\nconst stepOf = (data: unknown): ArtifactBuildStep | undefined => {\n const names = (value: unknown) =>\n Array.isArray(value) ? value.filter((name): name is string => typeof name === \"string\") : [];\n const { tools, scripts } = (data ?? {}) as Partial<Record<keyof ArtifactBuildStep, unknown>>;\n const step = { tools: names(tools), scripts: names(scripts) };\n return step.tools.length > 0 || step.scripts.length > 0 ? step : undefined;\n};\n\nconst sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));\n\n/** Deleted, or the user lost access. */\nconst isGone = (entry: Entry) => entry.snapshot.error?.code === \"not-found\";\n\n/**\n * Whether to keep checking: a renderer polls, the server tags what it sends (older\n * servers and storages without `stream` don't), and the user is still signed in.\n */\nconst polls = (entry: Entry) =>\n entry.pollers.size > 0 &&\n entry.tag !== undefined &&\n entry.snapshot.error?.code !== \"unauthorized\";\n\nconst streamError = (\n code: ArtifactStreamErrorCode,\n message: string,\n cause?: unknown,\n): ArtifactStreamError => ({\n source: \"artifact\",\n code,\n message,\n ...(cause !== undefined && { cause }),\n});\n\n/**\n * One stream per artifact, shared by every renderer showing it, so an edit\n * streamed by one renderer updates them all. Reads `storage.stream` when the\n * storage has it, and falls back to `storage.get` otherwise.\n *\n * @internal Exported for tests.\n */\nexport class ArtifactStreamStore {\n private readonly entries = new Map<string, Entry>();\n private readonly watchers = new Set<ArtifactStreamWatcher>();\n /** Artifacts whose poll came due while the tab was hidden. */\n private readonly dueWhileHidden = new Set<string>();\n\n constructor(private readonly storage: ArtifactStorage) {}\n\n /** Calls `watcher` on every change to any artifact's stream. Returns a function that stops it. */\n watch(watcher: ArtifactStreamWatcher): () => void {\n this.watchers.add(watcher);\n return () => this.watchers.delete(watcher);\n }\n\n getSnapshot(id: string): ArtifactStreamSnapshot {\n return this.entry(id).snapshot;\n }\n\n subscribe(id: string, listener: () => void): () => void {\n const entry = this.entry(id);\n entry.listeners.add(listener);\n if (entry.idleTimer) {\n clearTimeout(entry.idleTimer);\n entry.idleTimer = null;\n }\n if (!entry.started) {\n entry.started = true;\n void this.connect(id);\n }\n return () => {\n entry.listeners.delete(listener);\n if (entry.listeners.size > 0 || !entry.controller) return;\n // Deferred, so a StrictMode remount doesn't drop the stream.\n entry.idleTimer = setTimeout(() => {\n entry.idleTimer = null;\n if (entry.listeners.size > 0 || !entry.controller) return;\n entry.controller.abort();\n entry.controller = null;\n entry.started = false;\n }, 0);\n };\n }\n\n poll(id: string, intervalMs: number): () => void {\n const entry = this.entry(id);\n const key = Symbol();\n entry.pollers.set(key, Math.max(intervalMs, MIN_POLL_INTERVAL_MS));\n this.schedulePoll(id);\n return () => {\n entry.pollers.delete(key);\n this.schedulePoll(id);\n };\n }\n\n /** A version not seen before means there's a newer revision to fetch. */\n noteVersion(id: string, version: string | undefined): void {\n if (!version) return;\n const entry = this.entry(id);\n if (entry.versions.has(version)) return;\n const isFirst = entry.versions.size === 0;\n entry.versions.add(version);\n if (isFirst || !entry.started) return;\n // An ended stream can hold its controller a few microtasks longer.\n if (entry.controller && entry.snapshot.isStreaming) entry.stale = true;\n else void this.connect(id);\n }\n\n retry(id: string): void {\n const entry = this.entry(id);\n entry.reconnects = 0;\n entry.started = true;\n void this.connect(id);\n }\n\n /**\n * A data call was refused for `version` (`ARTIFACT_VERSION_MISMATCH`). \"rerun\" if\n * a newer version is on screen or a re-read brings one; else \"show\". Renderers\n * refused together share one re-read.\n */\n versionMismatch(id: string, version: string): Promise<\"rerun\" | \"show\"> {\n const entry = this.entry(id);\n if (version !== entry.snapshot.version) return Promise.resolve(\"rerun\");\n if (entry.reread?.version === version) return entry.reread.answer;\n const now = performance.now();\n if (!entry.started || now - entry.rereadAt < REREAD_INTERVAL_MS) {\n return Promise.resolve(\"show\");\n }\n entry.rereadAt = now;\n let settle!: Settle;\n const answer = new Promise<\"rerun\" | \"show\">((resolve) => (settle = resolve));\n entry.reread = { version, answer, settle };\n this.refresh(id);\n return answer;\n }\n\n /** A read ended: answer a pending re-read. */\n private afterRead(id: string): void {\n const entry = this.entry(id);\n const reread = entry.reread;\n if (!reread || entry.snapshot.isStreaming) return;\n entry.reread = null;\n reread.settle(entry.snapshot.version === reread.version ? \"show\" : \"rerun\");\n }\n\n /** Reads the artifact again, after the running stream if there is one. */\n private refresh(id: string): void {\n const entry = this.entry(id);\n if (!entry.started) return;\n if (entry.controller && entry.snapshot.isStreaming) entry.stale = true;\n else {\n entry.reconnects = 0;\n void this.connect(id);\n }\n }\n\n /** True while `version` is newer than any version recorded: the program on screen is behind. */\n awaits(id: string, version: string | undefined): boolean {\n if (!version) return false;\n const entry = this.entry(id);\n return (\n entry.started &&\n entry.snapshot.program !== null &&\n entry.versions.size > 0 &&\n !entry.versions.has(version)\n );\n }\n\n private entry(id: string): Entry {\n let entry = this.entries.get(id);\n if (!entry) {\n entry = {\n snapshot: { id, program: null, isStreaming: false, justUpdated: false, error: null },\n listeners: new Set(),\n controller: null,\n started: false,\n target: \"program\",\n pending: \"\",\n replace: false,\n settled: null,\n reconnects: 0,\n versions: new Set(),\n stale: false,\n idleTimer: null,\n reread: null,\n rereadAt: -Infinity,\n pollers: new Map(),\n pollTimer: null,\n pollFailures: 0,\n justUpdatedTimer: null,\n };\n this.entries.set(id, entry);\n }\n return entry;\n }\n\n private update(id: string, patch: Partial<ArtifactStreamSnapshot>): void {\n const entry = this.entry(id);\n const before = entry.snapshot;\n entry.snapshot = { ...before, ...patch };\n this.watchers.forEach((watcher) => watcher(id, before, entry.snapshot));\n entry.listeners.forEach((listener) => listener());\n }\n\n /** With `fetchLatest`, a poll: it stays quiet until the server sends something new. */\n private async connect(id: string, fetchLatest?: string): Promise<void> {\n const entry = this.entry(id);\n entry.started = true;\n entry.controller?.abort();\n const controller = new AbortController();\n entry.controller = controller;\n const poll = fetchLatest !== undefined;\n if (!poll) this.update(id, { isStreaming: true, error: null });\n\n const connectedAt = Date.now();\n let finished = false;\n let referenced = false;\n let failure: unknown;\n try {\n if (!this.storage.stream) {\n finished = true;\n await this.load(id);\n return;\n }\n for await (const event of this.storage.stream(id, {\n signal: controller.signal,\n fetchLatest,\n })) {\n if (controller.signal.aborted) return;\n if (event.type === \"end\" || event.type === \"error\" || event.type === \"unchanged\") {\n finished = true;\n this.onEvent(id, event);\n break;\n }\n if (event.type === \"reference\") referenced = true;\n this.onEvent(id, event);\n entry.reconnects = 0;\n }\n } catch (error) {\n if (controller.signal.aborted) return;\n failure = error;\n } finally {\n if (entry.controller === controller) entry.controller = null;\n }\n if (controller.signal.aborted) return;\n // Done, or a poll that failed before anything changed (what's on screen stays): poll again\n // later. Each failure doubles the wait; a 404 is an answer, so a gone artifact keeps the interval.\n if (finished || (poll && !referenced)) {\n entry.pollFailures = finished ? 0 : entry.pollFailures + 1;\n this.schedulePoll(id);\n return;\n }\n\n // The stream dropped before it ended: resume after a backoff, then give up.\n // Proxies cut streams that go quiet, as an edit's does until it's done, so a\n // connection that stayed up a while starts the count again.\n if (Date.now() - connectedAt >= STABLE_CONNECTION_MS) entry.reconnects = 0;\n if (entry.reconnects < MAX_RECONNECTS) {\n entry.reconnects += 1;\n await sleep(500 * 2 ** (entry.reconnects - 1));\n // A new version may have reconnected already.\n if (entry.controller) return;\n if (entry.listeners.size > 0) void this.connect(id);\n else entry.started = false;\n return;\n }\n this.update(id, {\n ...this.endRead(entry),\n isStreaming: false,\n error: streamError(\"network-error\", \"Couldn't reach the artifact's storage.\", failure),\n });\n this.afterRead(id);\n }\n\n /**\n * A read is over: resets it, and returns what was on screen before a new version\n * started streaming over it, if one did. A read that failed goes back to that.\n */\n private endRead(entry: Entry): Settled | null {\n const settled = entry.settled;\n entry.target = \"program\";\n entry.pending = \"\";\n entry.version = undefined;\n entry.settled = null;\n return settled;\n }\n\n /** Turns `justUpdated` on for a while. */\n private markUpdated(id: string): void {\n const entry = this.entry(id);\n if (entry.justUpdatedTimer) clearTimeout(entry.justUpdatedTimer);\n entry.justUpdatedTimer = setTimeout(() => {\n entry.justUpdatedTimer = null;\n this.update(id, { justUpdated: false });\n }, JUST_UPDATED_MS);\n this.update(id, { justUpdated: true });\n }\n\n /** Storages without `stream`: read the stored artifact once. */\n private async load(id: string): Promise<void> {\n try {\n const artifact = await this.storage.get(id);\n this.update(id, {\n type: artifact.type,\n title: artifact.title,\n program: typeof artifact.content === \"string\" ? artifact.content : null,\n isStreaming: false,\n });\n } catch (error) {\n this.update(id, {\n isStreaming: false,\n error: streamError(\n \"not-found\",\n error instanceof Error ? error.message : \"This artifact couldn't be loaded.\",\n error,\n ),\n });\n }\n this.afterRead(id);\n }\n\n /** Sets the next poll, if a renderer polls and the last read went well enough to compare against. */\n private schedulePoll(id: string): void {\n const entry = this.entry(id);\n if (entry.pollTimer) clearTimeout(entry.pollTimer);\n entry.pollTimer = null;\n if (!polls(entry)) return;\n const interval = Math.min(...entry.pollers.values());\n // Each failure doubles the wait, up to 5 minutes. Jitter, so renderers opened together don't poll together.\n const backoff = Math.min(\n interval * 2 ** entry.pollFailures,\n Math.max(interval, MAX_POLL_BACKOFF_MS),\n );\n const wait = backoff * (0.9 + Math.random() * 0.2);\n entry.pollTimer = setTimeout(() => this.pollNow(id), Math.min(wait, MAX_TIMEOUT_MS));\n // Coming back to the tab checks again right away.\n if (entry.pollFailures > 0) this.listenForVisible();\n }\n\n private pollNow(id: string): void {\n const entry = this.entry(id);\n if (entry.pollTimer) clearTimeout(entry.pollTimer);\n entry.pollTimer = null;\n // A read in progress schedules the next poll when it ends.\n if (!polls(entry) || entry.controller) return;\n if (typeof document !== \"undefined\" && document.hidden) {\n this.dueWhileHidden.add(id);\n this.listenForVisible();\n return;\n }\n // Gone, so nothing on screen to compare: a full read, which brings it back if it's shared again.\n void this.connect(id, isGone(entry) ? \"\" : entry.tag);\n }\n\n private listenForVisible(): void {\n if (typeof document !== \"undefined\")\n document.addEventListener(\"visibilitychange\", this.onVisible);\n }\n\n /**\n * The tab is back: run the polls that came due while it was hidden, and check now on\n * artifacts waiting out failures, starting their wait over.\n */\n private readonly onVisible = (): void => {\n if (document.hidden) return;\n document.removeEventListener(\"visibilitychange\", this.onVisible);\n const due = new Set(this.dueWhileHidden);\n this.dueWhileHidden.clear();\n for (const [id, entry] of this.entries) {\n if (entry.pollFailures === 0 || !polls(entry)) continue;\n entry.pollFailures = 0;\n due.add(id);\n }\n due.forEach((id) => this.pollNow(id));\n };\n\n /** Fetches a revision noted while the stream that just ended was running. */\n private catchUp(id: string): void {\n const entry = this.entry(id);\n if (!entry.stale) return;\n entry.stale = false;\n void this.connect(id);\n }\n\n private onEvent(id: string, event: ArtifactStreamEvent): void {\n const entry = this.entry(id);\n const snapshot = entry.snapshot;\n switch (event.type) {\n case \"reference\": {\n const { version, tag, is_owner, is_editable } = event.data ?? {};\n // Seen, so an edit's version noted later counts as newer.\n if (version) entry.versions.add(version);\n entry.tag = tag;\n const shown = snapshot.program;\n const newVersion = version !== snapshot.version;\n // A reconnect into the version being streamed sends it whole again.\n const reconnect = version !== undefined && version === entry.version;\n // A new version streams onto the screen as it's generated: an edit sends its prior\n // program first, then its patch, which the parser merges in. What's on screen stays\n // until its first delta replaces it.\n const overShown = shown !== null && newVersion;\n entry.version = version;\n if (!reconnect) {\n // The same version again (a rename, an access change, a re-read) loads out of sight.\n entry.target = shown === null || newVersion ? \"program\" : \"pending\";\n entry.pending = \"\";\n if (overShown) entry.settled ??= { program: shown, version: snapshot.version };\n }\n entry.replace = reconnect || overShown;\n // The stream resends the build's current step after its reference.\n this.update(id, {\n type: event.data?.type ?? snapshot.type,\n title: event.data?.title ?? snapshot.title,\n isOwner: is_owner ?? snapshot.isOwner,\n isEditable: is_editable ?? snapshot.isEditable,\n // A poll that found only a rename or an access change doesn't show as loading.\n isStreaming: snapshot.isStreaming || newVersion,\n step: undefined,\n error: null,\n ...(entry.target === \"program\" && { version, program: shown ?? \"\" }),\n });\n return;\n }\n case \"unchanged\":\n this.afterRead(id);\n return;\n case \"delta\": {\n const text = event.data?.text;\n if (typeof text !== \"string\") return;\n const replace = entry.replace;\n entry.replace = false;\n if (entry.target === \"pending\") entry.pending = (replace ? \"\" : entry.pending) + text;\n // The first content a build writes ends its step.\n else {\n this.update(id, {\n program: (replace ? \"\" : (snapshot.program ?? \"\")) + text,\n step: undefined,\n });\n }\n return;\n }\n case \"step\": {\n this.update(id, { step: stepOf(event.data) });\n return;\n }\n case \"end\": {\n const swapped =\n entry.target === \"pending\" ? { program: entry.pending, version: entry.version } : {};\n const replaced = this.endRead(entry) !== null;\n this.update(id, { ...swapped, isStreaming: false, step: undefined });\n if (replaced) this.markUpdated(id);\n this.catchUp(id);\n this.afterRead(id);\n return;\n }\n case \"error\": {\n const code = event.data?.code;\n const errorCode =\n code && ERROR_CODES.has(code) ? (code as ArtifactStreamErrorCode) : \"generation-failed\";\n const gone = errorCode === \"not-found\";\n // The next renderer to open it reads it again.\n if (gone) entry.started = false;\n this.update(id, {\n ...this.endRead(entry),\n // Deleted or unshared: nothing of it stays on screen.\n ...(gone && { program: null, version: undefined }),\n isStreaming: false,\n step: undefined,\n error: streamError(\n errorCode,\n event.data?.message ?? \"The artifact couldn't be generated.\",\n ),\n });\n this.catchUp(id);\n this.afterRead(id);\n }\n }\n }\n}\n\nconst stores = new WeakMap<ArtifactStorage, ArtifactStreamStore>();\nconst storeFor = (storage: ArtifactStorage): ArtifactStreamStore => {\n let store = stores.get(storage);\n if (!store) {\n store = new ArtifactStreamStore(storage);\n stores.set(storage, store);\n }\n return store;\n};\n\n/**\n * Tells every renderer showing `id` that `version` was just saved, so they load\n * it now instead of on their next poll.\n *\n * @internal Used by `@openuidev/react-ui/cloud`'s `useArtifactUpdate`.\n */\nexport function noteArtifactVersion(\n storage: ArtifactStorage,\n id: string,\n version: string | undefined,\n): void {\n stores.get(storage)?.noteVersion(id, version);\n}\n\n/**\n * Calls `watcher` on every change to any artifact's stream on `storage`, such as\n * a rename, an access change or a `not-found` a poll picked up. Returns a function\n * that stops it.\n *\n * @internal Used by `@openuidev/react-ui/cloud`'s artifact cache.\n */\nexport function watchArtifactStreams(\n storage: ArtifactStorage,\n watcher: ArtifactStreamWatcher,\n): () => void {\n return storeFor(storage).watch(watcher);\n}\n\n/** @category Types */\nexport interface UseArtifactStreamOptions {\n /** The artifact to show. */\n id: string | null | undefined;\n /** The version from the artifact's tool response. A new one fetches the newer revision. */\n version?: string;\n /** The artifact's saved content, when you keep artifacts in your own storage. Never streams. */\n content?: string;\n pollInterval?: number | false;\n}\n\n/** @category Types */\nexport interface ArtifactStreamState extends Omit<ArtifactStreamSnapshot, \"id\"> {\n /** Reconnects after a `network-error`. Undefined when there's nothing to retry. */\n retry?: () => void;\n /** For a data call refused because the artifact moved on: run the queries again, or show the error. */\n reportVersionMismatch?: (version: string) => Promise<\"rerun\" | \"show\">;\n}\n\nconst IDLE: ArtifactStreamState = {\n program: null,\n isStreaming: false,\n justUpdated: false,\n error: null,\n};\n\n/**\n * Streams an artifact in by id from the configured {@link ArtifactStorage},\n * sharing one stream per artifact across every component that shows it.\n *\n * - While it's generated, `program` grows and `isStreaming` is `true`.\n * - After a reload, it replays everything generated so far, then continues.\n * - A new version streams in live: an edit shows its prior program, then its patch\n * merging in. One that fails goes back to the version before it.\n * - Storages without `stream` are read once with `get`.\n * - With `pollInterval`, it picks up a newer version, a rename or an access\n * change, and the `not-found` error once the artifact is deleted or unshared.\n *\n * @internal Used by the `@openuidev/react-ui/cloud` renderers.\n */\nexport function useArtifactStream(\n options: MaybeRefOrGetter<UseArtifactStreamOptions>,\n): ComputedRef<ArtifactStreamState> {\n const storage = useArtifactStorage();\n const snapshotRef = shallowRef<ArtifactStreamSnapshot | null>(null);\n\n const resolved = computed(() => toValue(options));\n const activeStore = computed(() => {\n const opts = resolved.value;\n const ownContent = opts.content !== undefined;\n return storage && !ownContent && opts.id ? storeFor(storage) : null;\n });\n\n watch(\n [activeStore, () => resolved.value.id],\n ([store, id], _prev, onCleanup) => {\n if (!store || !id) {\n snapshotRef.value = null;\n return;\n }\n snapshotRef.value = store.getSnapshot(id);\n const unsub = store.subscribe(id, () => {\n snapshotRef.value = store.getSnapshot(id);\n });\n onCleanup(unsub);\n },\n { immediate: true },\n );\n\n watch(\n [activeStore, () => resolved.value.id, () => resolved.value.version],\n ([store, id, version]) => {\n if (store && id) store.noteVersion(id, version);\n },\n { immediate: true, flush: \"post\" },\n );\n\n watch(\n [activeStore, () => resolved.value.id, () => resolved.value.pollInterval],\n ([store, id, pollInterval], _prev, onCleanup) => {\n if (!store || !id || !pollInterval) return;\n const stop = store.poll(id, pollInterval);\n onCleanup(stop);\n },\n { immediate: true, flush: \"post\" },\n );\n\n return computed<ArtifactStreamState>(() => {\n const opts = resolved.value;\n const store = activeStore.value;\n const id = opts.id;\n const ownContent = opts.content !== undefined;\n if (ownContent) return { ...IDLE, program: opts.content! };\n\n const snapshot = snapshotRef.value;\n if (!snapshot) {\n if (id && !storage) {\n return {\n ...IDLE,\n error: streamError(\"not-found\", \"No artifact storage is configured.\"),\n };\n }\n return IDLE;\n }\n\n const awaiting = store && id ? store.awaits(id, opts.version) : false;\n const reportVersionMismatch =\n store && id ? (refused: string) => store.versionMismatch(id, refused) : undefined;\n const { id: _id, ...rest } = snapshot;\n const retry =\n snapshot.error?.code === \"network-error\" && store && id ? () => store.retry(id) : undefined;\n return { ...rest, isStreaming: rest.isStreaming || awaiting, retry, reportVersionMismatch };\n });\n}\n","/**\n * The interpreter runs an artifact's data tools on the developer's server.\n * This module bridges `Query()`/`Mutation()` calls from the renderer to it.\n */\n\n/** What the renderer sends your interpreter for each data tool call. @category Types */\nexport interface InterpreterRequest {\n /** The artifact's id. */\n id: string;\n /** The version on screen; OpenUI Cloud refuses a script run when the artifact has moved on. */\n version?: string;\n /** The query or tool to run. */\n name: string;\n arguments: Record<string, unknown>;\n}\n\n/** Your interpreter endpoint: it receives an `InterpreterRequest` as JSON and returns `{ result }`. @category Types */\nexport interface InterpreterConfig {\n url: string;\n /** Headers to send with each request, such as an auth header. */\n headers?: HeadersInit;\n}\n\n/** An async function that runs the request, such as a server action. @category Types */\nexport type InterpreterFunction = (request: InterpreterRequest) => Promise<unknown>;\n\n/** Where an artifact's data tools run. @category Types */\nexport type Interpreter = InterpreterConfig | InterpreterFunction;\n\n/** The shape react-lang's `Renderer` accepts as an MCP-style `toolProvider`. */\nexport interface InterpreterToolProvider {\n callTool(params: { name: string; arguments?: Record<string, unknown> }): Promise<{\n content: Array<{ type: string; text?: string }>;\n structuredContent?: unknown;\n }>;\n}\n\n/** @category Types */\nexport interface InterpreterToolProviderOptions {\n /** Read on every call, so the provider's identity can stay stable. */\n getInterpreter: () => Interpreter | undefined;\n /** The artifact the calls are for. */\n getRequest: () => { id: string | null | undefined; version?: string };\n /** Defaults to the global `fetch`. */\n fetch?: typeof fetch;\n /** Called when a call starts. */\n onStart?: (toolName: string) => void;\n /**\n * Called when a call settles; `message` is `null` on success. On failure, `detail`\n * has the error's `code`, if any, and the artifact `id` and `version` the call ran with.\n */\n onSettle?: (\n toolName: string,\n message: string | null,\n detail?: { code?: string; id: string; version?: string },\n ) => void;\n}\n\nfunction errorMessage(error: unknown): string | undefined {\n if (typeof error === \"string\") return error;\n if (error && typeof error === \"object\" && \"message\" in error) {\n const { message } = error as { message: unknown };\n if (typeof message === \"string\") return message;\n }\n return undefined;\n}\n\nfunction errorCode(error: unknown): string | undefined {\n if (error && typeof error === \"object\" && \"code\" in error) {\n const { code } = error as { code: unknown };\n if (typeof code === \"string\") return code;\n }\n return undefined;\n}\n\nasync function callEndpoint(\n fetchImpl: typeof fetch,\n config: InterpreterConfig,\n request: InterpreterRequest,\n): Promise<unknown> {\n const headers = new Headers(config.headers);\n headers.set(\"Content-Type\", \"application/json\");\n const res = await fetchImpl(config.url, {\n method: \"POST\",\n headers,\n body: JSON.stringify(request),\n });\n let body: { result?: unknown; error?: unknown } | null = null;\n try {\n body = (await res.json()) as { result?: unknown; error?: unknown };\n } catch {\n body = null;\n }\n if (!res.ok || (body?.error !== undefined && body.error !== null)) {\n const message = errorMessage(body?.error) ?? `Interpreter request failed: ${res.status}`;\n throw Object.assign(new Error(message), { code: errorCode(body?.error) });\n }\n return body?.result;\n}\n\n/**\n * A `toolProvider` for react-lang's `Renderer` that sends an artifact's data\n * tool calls to your interpreter, endpoint or function. Results come back as\n * `structuredContent`, so `Renderer` unwraps them the usual way.\n *\n * @internal Used by the `@openuidev/react-ui/cloud` renderers.\n */\nexport function createInterpreterToolProvider(\n options: InterpreterToolProviderOptions,\n): InterpreterToolProvider {\n return {\n async callTool({ name, arguments: args = {} }) {\n const interpreter = options.getInterpreter();\n const { id, version } = options.getRequest();\n if (!interpreter) throw new Error(\"This artifact has no interpreter.\");\n if (!id) throw new Error(\"This artifact has no id yet.\");\n\n const request: InterpreterRequest = {\n id,\n ...(version !== undefined && { version }),\n name,\n arguments: args,\n };\n options.onStart?.(name);\n try {\n const result =\n typeof interpreter === \"function\"\n ? await interpreter(request)\n : await callEndpoint(\n options.fetch ?? globalThis.fetch.bind(globalThis),\n interpreter,\n request,\n );\n options.onSettle?.(name, null);\n return { content: [], structuredContent: result ?? null };\n } catch (error) {\n const code = errorCode(error);\n options.onSettle?.(name, errorMessage(error) ?? \"The data tool failed.\", {\n ...(code !== undefined && { code }),\n id,\n ...(version !== undefined && { version }),\n });\n throw error;\n }\n },\n };\n}\n","/**\n * A minimal server-sent events reader over `fetch`.\n *\n * `EventSource` can't send the frontend-token header, so streams are read from\n * a `fetch` body instead. Handles `id:`, `event:` and multi-line `data:`\n * fields, `:` comments, and both `\\n` and `\\r\\n` line endings.\n */\n\nexport interface SseMessage {\n id?: string;\n event: string;\n data: string;\n}\n\nexport async function* readSse(body: ReadableStream<Uint8Array>): AsyncGenerator<SseMessage> {\n const reader = body.getReader();\n const decoder = new TextDecoder();\n let buffer = \"\";\n let id: string | undefined;\n let event = \"\";\n let data: string[] = [];\n\n const dispatch = (): SseMessage | null => {\n if (data.length === 0 && !event) return null;\n const message: SseMessage = { id, event: event || \"message\", data: data.join(\"\\n\") };\n event = \"\";\n data = [];\n return message;\n };\n\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n buffer += decoder.decode(value, { stream: true });\n\n let newline = buffer.search(/\\r?\\n/);\n while (newline !== -1) {\n const line = buffer.slice(0, newline);\n buffer = buffer.slice(buffer[newline] === \"\\r\" ? newline + 2 : newline + 1);\n\n if (line === \"\") {\n const message = dispatch();\n if (message) yield message;\n } else if (!line.startsWith(\":\")) {\n const colon = line.indexOf(\":\");\n const field = colon === -1 ? line : line.slice(0, colon);\n let value = colon === -1 ? \"\" : line.slice(colon + 1);\n if (value.startsWith(\" \")) value = value.slice(1);\n if (field === \"data\") data.push(value);\n else if (field === \"event\") event = value;\n else if (field === \"id\") id = value;\n }\n newline = buffer.search(/\\r?\\n/);\n }\n }\n const message = dispatch();\n if (message) yield message;\n } finally {\n reader.releaseLock();\n }\n}\n","/**\n * Wire types for the OpenUI Cloud /v1 API, plus the shared list envelope,\n * cursor rule, and request helper. Field-for-field mirrors of the API DTOs.\n */\n\n/** A conversation. `created_at` is unix SECONDS. */\nexport interface CloudConversation {\n id: string;\n object: \"conversation\";\n created_at: number;\n title?: string;\n metadata?: Record<string, unknown>;\n user_id?: string;\n app_id?: string;\n}\n\n/** A conversation item (full Responses item shape). */\nexport interface CloudConversationItem {\n id: string;\n object: \"conversation.item\";\n type: string; // message | function_call | function_call_output | ...\n role?: string;\n status?: string;\n content?: unknown;\n metadata?: Record<string, unknown>;\n created_at: number;\n call_id?: string;\n name?: string;\n arguments?: string;\n output?: unknown;\n}\n\n/** A stored artifact. `content` is the renderer-ready openui-lang program. */\nexport interface CloudArtifact {\n id: string;\n object: \"openui.artifact\";\n conversation_id?: string;\n kind: string; // 'slides' | 'report' | 'dashboard'\n name?: string;\n version?: string; // server bumps via String(Date.now()) when omitted\n content?: string;\n pinned?: boolean; // by the caller\n is_owner?: boolean;\n is_editable?: boolean;\n shares?: CloudArtifactShare[]; // only when is_editable\n created_at: number;\n updated_at?: number;\n}\n\n/** One share on an artifact. `created_at` is unix SECONDS. */\nexport interface CloudArtifactShare {\n object: \"openui.artifact.share\";\n type: \"user\" | \"group\";\n id: string;\n access: \"view\" | \"edit\";\n created_by: string;\n created_at: number;\n}\n\n/** List envelope shared by all paged endpoints. */\nexport interface CloudListEnvelope<T> {\n object: \"list\";\n data: T[];\n has_more: boolean;\n first_id?: string;\n last_id?: string;\n}\n\n/** Forward cursor: pass `last_id` back as `?after=` when there's another page. */\nexport function nextCursorOf(envelope: CloudListEnvelope<unknown>): string | undefined {\n return envelope.has_more && envelope.last_id ? envelope.last_id : undefined;\n}\n\n/**\n * Request helper: prefix baseUrl, set JSON content-type only when sending a\n * body, throw on non-2xx. `fetchImpl` is the token-injecting fetch — auth\n * lives there, never here.\n */\nexport function cloudRequest(fetchImpl: typeof fetch, baseUrl: string) {\n const base = baseUrl.replace(/\\/+$/, \"\");\n return async (path: string, init?: RequestInit): Promise<Response> => {\n const res = await fetchImpl(`${base}${path}`, {\n ...init,\n headers: {\n ...(init?.body ? { \"Content-Type\": \"application/json\" } : {}),\n ...init?.headers,\n },\n });\n if (!res.ok) {\n throw new Error(\n `OpenUI Cloud: ${init?.method ?? \"GET\"} ${path} failed: ${res.status} ${res.statusText}`,\n );\n }\n return res;\n };\n}\n","import type {\n Artifact,\n ArtifactAccess,\n ArtifactListParams,\n ArtifactShare,\n ArtifactShareTarget,\n ArtifactStorage,\n ArtifactStreamEvent,\n ArtifactStreamOptions,\n ArtifactSummary,\n} from \"../adapters/types\";\nimport { readSse } from \"./sse\";\nimport {\n cloudRequest,\n nextCursorOf,\n type CloudArtifact,\n type CloudArtifactShare,\n type CloudListEnvelope,\n} from \"./wire\";\n\nconst STREAM_EVENT_TYPES = new Set([\"reference\", \"delta\", \"step\", \"end\", \"error\"]);\n\nfunction parseJson(data: string): unknown {\n try {\n return JSON.parse(data);\n } catch {\n return null;\n }\n}\n\nexport interface CloudArtifactStorageOptions {\n /** OpenUI Cloud API origin, e.g. \"http://localhost:3102\". */\n baseUrl: string;\n /** The token-injecting fetch from createFctFetch. */\n fetch: typeof fetch;\n /** Default page size when the caller passes no limit. */\n pageLimit?: number;\n /**\n * Dashboards show each query's last result while it reloads; the results are\n * kept in OpenUI Cloud for 24 hours, per user. `false` turns this off. Default true.\n */\n cacheQueryResults?: boolean;\n}\n\nfunction toSummary(artifact: CloudArtifact): ArtifactSummary {\n return {\n id: artifact.id,\n title: artifact.name ?? artifact.id,\n type: artifact.kind,\n threadId: artifact.conversation_id ?? \"\",\n updatedAt: (artifact.updated_at ?? artifact.created_at) * 1000,\n ...(artifact.pinned !== undefined && { pinned: artifact.pinned }),\n ...(artifact.is_owner !== undefined && { isOwner: artifact.is_owner }),\n ...(artifact.is_editable !== undefined && { isEditable: artifact.is_editable }),\n ...(artifact.shares !== undefined && { shares: artifact.shares.map(toShare) }),\n ...(artifact.version !== undefined && { version: artifact.version }),\n };\n}\n\nfunction toShare(share: CloudArtifactShare): ArtifactShare {\n return {\n type: share.type,\n id: share.id,\n access: share.access,\n createdBy: share.created_by,\n createdAt: share.created_at * 1000,\n };\n}\n\nexport function cloudArtifactStorage({\n baseUrl,\n fetch: fetchImpl,\n pageLimit = 100,\n cacheQueryResults = true,\n}: CloudArtifactStorageOptions): ArtifactStorage {\n const request = cloudRequest(fetchImpl, baseUrl);\n const base = baseUrl.replace(/\\/+$/, \"\");\n\n return {\n /** GET /v1/artifacts?[name=][kind=…]&limit[&after=]. Omitting the\n * conversation scope lists across conversations, token-scoped to the user. */\n async list(params?: ArtifactListParams) {\n const query = new URLSearchParams();\n if (params?.name !== undefined && params.name !== \"\") query.set(\"name\", params.name);\n for (const type of params?.type ?? []) query.append(\"kind\", type);\n if (params?.pinned !== undefined) query.set(\"pinned\", String(params.pinned));\n if (params?.isOwner !== undefined) query.set(\"is_owner\", String(params.isOwner));\n if (params?.order !== undefined) query.set(\"order\", params.order);\n if (params?.cursor !== undefined) query.set(\"after\", params.cursor);\n query.set(\"limit\", String(params?.limit ?? pageLimit));\n const res = await request(`/v1/artifacts?${query.toString()}`);\n const envelope = (await res.json()) as CloudListEnvelope<CloudArtifact>;\n return {\n artifacts: envelope.data.map(toSummary),\n nextCursor: nextCursorOf(envelope),\n };\n },\n\n /** GET /v1/artifacts/:id → the stored openui-lang program (bare program;\n * the renderer's parser sniffs the `root = …` root). */\n async get(id: string): Promise<Artifact> {\n const res = await request(`/v1/artifacts/${encodeURIComponent(id)}`);\n const artifact = (await res.json()) as CloudArtifact;\n return { ...toSummary(artifact), content: artifact.content };\n },\n\n /** POST /v1/artifacts/:id {content?, name?}. New content (the edited inner program) is a\n * new version, which the server bumps; a title alone renames it. */\n async update(patch: {\n id: string;\n content?: unknown;\n title?: string;\n }): Promise<ArtifactSummary> {\n const body = {\n ...(patch.content !== undefined && {\n content:\n typeof patch.content === \"string\" ? patch.content : JSON.stringify(patch.content),\n }),\n ...(patch.title !== undefined && { name: patch.title }),\n };\n const res = await request(`/v1/artifacts/${encodeURIComponent(patch.id)}`, {\n method: \"POST\",\n body: JSON.stringify(body),\n });\n return toSummary((await res.json()) as CloudArtifact);\n },\n\n /** POST /v1/artifacts/:id/pin. */\n async pin(id: string): Promise<ArtifactSummary> {\n const res = await request(`/v1/artifacts/${encodeURIComponent(id)}/pin`, { method: \"POST\" });\n return toSummary((await res.json()) as CloudArtifact);\n },\n\n /** POST /v1/artifacts/:id/unpin. */\n async unpin(id: string): Promise<ArtifactSummary> {\n const res = await request(`/v1/artifacts/${encodeURIComponent(id)}/unpin`, {\n method: \"POST\",\n });\n return toSummary((await res.json()) as CloudArtifact);\n },\n\n /** DELETE /v1/artifacts/:id. */\n async delete(id: string): Promise<void> {\n await request(`/v1/artifacts/${encodeURIComponent(id)}`, { method: \"DELETE\" });\n },\n\n /** POST /v1/artifacts/:id/share {type, id, access}. Sends only those fields. */\n async share(\n id: string,\n share: ArtifactShareTarget & { access: ArtifactAccess },\n ): Promise<ArtifactSummary> {\n const res = await request(`/v1/artifacts/${encodeURIComponent(id)}/share`, {\n method: \"POST\",\n body: JSON.stringify({ type: share.type, id: share.id, access: share.access }),\n });\n return toSummary((await res.json()) as CloudArtifact);\n },\n\n /** POST /v1/artifacts/:id/unshare {type, id}. Sends only those fields. */\n async unshare(id: string, target: ArtifactShareTarget): Promise<ArtifactSummary> {\n const res = await request(`/v1/artifacts/${encodeURIComponent(id)}/unshare`, {\n method: \"POST\",\n body: JSON.stringify({ type: target.type, id: target.id }),\n });\n return toSummary((await res.json()) as CloudArtifact);\n },\n\n ...(cacheQueryResults && {\n /** GET /v1/artifacts/:id/query-results → the saved entries by key. */\n async getQueryResults(id: string): Promise<Record<string, unknown>> {\n const res = await request(`/v1/artifacts/${encodeURIComponent(id)}/query-results`);\n return ((await res.json()) as { results?: Record<string, unknown> }).results ?? {};\n },\n\n /** PUT /v1/artifacts/:id/query-results {key, value}. Not awaited; a failure is dropped. */\n putQueryResult(id: string, entry: { key: string; value: unknown }): void {\n request(`/v1/artifacts/${encodeURIComponent(id)}/query-results`, {\n method: \"PUT\",\n body: JSON.stringify(entry),\n }).catch(() => {});\n },\n }),\n\n /** GET /v1/artifacts/:id/stream[?fetch_latest=] (SSE). Replays a finished artifact\n * the same way; every connection starts from the whole program. 304: unchanged. */\n async *stream(\n id: string,\n options?: ArtifactStreamOptions,\n ): AsyncGenerator<ArtifactStreamEvent> {\n const query = options?.fetchLatest\n ? `?${new URLSearchParams({ fetch_latest: options.fetchLatest }).toString()}`\n : \"\";\n const res = await fetchImpl(`${base}/v1/artifacts/${encodeURIComponent(id)}/stream${query}`, {\n headers: { Accept: \"text/event-stream\" },\n signal: options?.signal,\n });\n if (res.status === 304) {\n yield { type: \"unchanged\" };\n return;\n }\n if (res.status === 404) {\n yield {\n type: \"error\",\n data: { code: \"not-found\", message: \"This artifact was deleted, or you can't see it.\" },\n };\n return;\n }\n // A 401 already got a fresh token (createFctFetch); retrying won't change either.\n if (res.status === 401 || res.status === 403) {\n yield {\n type: \"error\",\n data: {\n code: \"unauthorized\",\n message: \"Your session expired, or you can't see this artifact.\",\n },\n };\n return;\n }\n if (!res.ok || !res.body) {\n throw new Error(`OpenUI Cloud: stream ${id} failed: ${res.status} ${res.statusText}`);\n }\n for await (const message of readSse(res.body)) {\n if (!STREAM_EVENT_TYPES.has(message.event)) continue;\n yield {\n type: message.event,\n data: parseJson(message.data),\n } as ArtifactStreamEvent;\n }\n },\n };\n}\n","/**\n * Frontend session-token (fct_) lifecycle for the browser plane.\n *\n * - The token rides ONLY the `x-thesys-frontend-token` header; `Authorization`\n * on /v1/* always means the master key (server-side).\n * - Minting happens on YOUR backend (here, the /api/frontend-token proxy),\n * which calls the cloud mint endpoint with the master key and decides the\n * end-user identity server-side. The browser sends no body and never names\n * its own user.\n * - Mint response: { token: 'fct_…', expires_at: <unix seconds> }, TTL ~15 min.\n *\n * A fetch override (not static headers) is used so the token can refresh\n * mid-session — the chat provider captures the storage object once at mount.\n */\n\nexport const FRONTEND_TOKEN_HEADER = \"x-thesys-frontend-token\";\n\nexport interface MintFrontendTokenResponse {\n token: string;\n expires_at: number; // unix seconds\n}\n\nexport interface FrontendTokenManagerOptions {\n /** Your backend mint endpoint, e.g. \"/api/frontend-token\". */\n mintUrl: string;\n /** Override for tests / SSR. Defaults to globalThis.fetch. */\n fetch?: typeof fetch;\n /** Refresh this many seconds before expiry. Default 60. */\n refreshSkewSeconds?: number;\n}\n\nexport interface FrontendTokenManager {\n /** A token valid for at least refreshSkewSeconds (single-flight mint). */\n getToken(): Promise<string>;\n /** Drop the cached token. Pass the token that 401'd so a concurrent refresh\n * is not discarded. */\n invalidate(staleToken?: string): void;\n}\n\nexport function createFrontendTokenManager({\n mintUrl,\n fetch: customFetch,\n refreshSkewSeconds = 60,\n}: FrontendTokenManagerOptions): FrontendTokenManager {\n const fetchImpl = customFetch ?? globalThis.fetch.bind(globalThis);\n\n let token: string | null = null;\n let expiresAt = 0; // unix seconds\n let inflight: Promise<string> | null = null;\n\n const mint = async (): Promise<string> => {\n const res = await fetchImpl(mintUrl, { method: \"POST\" });\n if (!res.ok) {\n throw new Error(`frontend-token mint failed: ${res.status} ${res.statusText}`);\n }\n const body = (await res.json()) as MintFrontendTokenResponse;\n token = body.token;\n expiresAt = body.expires_at;\n return body.token;\n };\n\n return {\n async getToken(): Promise<string> {\n const nowSeconds = Date.now() / 1000;\n if (token !== null && nowSeconds < expiresAt - refreshSkewSeconds) return token;\n // Single-flight: callers during a refresh await the same mint.\n if (inflight === null) {\n inflight = mint().finally(() => {\n inflight = null;\n });\n }\n return inflight;\n },\n\n invalidate(staleToken?: string): void {\n if (staleToken === undefined || staleToken === token) {\n token = null;\n expiresAt = 0;\n }\n },\n };\n}\n\n/** Where a frontend token comes from: your mint endpoint's URL, or a function\n * returning a fresh token (you own caching). */\nexport type FrontendTokenSource = string | (() => Promise<string>);\n\n/** Normalize a token source into a FrontendTokenManager. */\nexport function toFrontendTokenManager(\n source: FrontendTokenSource,\n options: Omit<FrontendTokenManagerOptions, \"mintUrl\"> = {},\n): FrontendTokenManager {\n if (typeof source === \"string\") {\n return createFrontendTokenManager({ ...options, mintUrl: source });\n }\n let current: string | null = null;\n return {\n async getToken(): Promise<string> {\n current = await source();\n return current;\n },\n invalidate(staleToken?: string): void {\n if (staleToken === undefined || staleToken === current) current = null;\n },\n };\n}\n\n/**\n * Wrap a base fetch so every request carries a fresh token, with one reactive\n * retry on 401. The request is re-sent with the same init — pass re-readable\n * (string) bodies only.\n */\nexport function createFctFetch(\n tokens: FrontendTokenManager,\n baseFetch?: typeof fetch,\n): typeof fetch {\n const fetchImpl = baseFetch ?? globalThis.fetch.bind(globalThis);\n\n return async (input: RequestInfo | URL, init?: RequestInit): Promise<Response> => {\n const token = await tokens.getToken();\n const headers = new Headers(init?.headers);\n headers.set(FRONTEND_TOKEN_HEADER, token);\n\n let res = await fetchImpl(input, { ...init, headers });\n\n if (res.status === 401) {\n tokens.invalidate(token);\n const freshToken = await tokens.getToken();\n const retryHeaders = new Headers(init?.headers);\n retryHeaders.set(FRONTEND_TOKEN_HEADER, freshToken);\n res = await fetchImpl(input, { ...init, headers: retryHeaders });\n }\n\n return res;\n };\n}\n","import type { Message as ConversationMessage } from \"openai/resources/conversations/conversations\";\nimport type { ConversationItem } from \"openai/resources/conversations/items\";\nimport type {\n EasyInputMessage,\n ResponseFunctionToolCall,\n ResponseFunctionToolCallOutputItem,\n ResponseInputItem,\n ResponseInputMessageContentList,\n} from \"openai/resources/responses/responses\";\nimport type { AssistantMessage, Message, ToolMessage, UserMessage } from \"../../types\";\nimport type { MessageFormat } from \"../../types/messageFormat\";\n\n// ── Outbound (AG-UI → OpenAI Responses/Conversations input) ─────\n\n/**\n * Both the Responses API and the Conversations API accept\n * `ResponseInputItem[]` as input, so a single outbound conversion\n * works for both.\n *\n * Tool calls are *sibling items* of the assistant message, not nested\n * inside it. We flatten each AG-UI assistant message into:\n * 1. An `EasyInputMessage` with `role: \"assistant\"` (text part)\n * 2. One `ResponseFunctionToolCall` per tool call\n *\n * Tool result messages become `FunctionCallOutput` items.\n */\nfunction toItems(message: Message): ResponseInputItem[] {\n switch (message.role) {\n case \"user\":\n return [toInputMessage(message)];\n\n case \"assistant\": {\n const items: ResponseInputItem[] = [];\n\n if (message.content) {\n items.push({\n role: \"assistant\",\n content: message.content,\n type: \"message\",\n } satisfies EasyInputMessage);\n }\n\n if (message.toolCalls?.length) {\n for (const tc of message.toolCalls) {\n items.push({\n type: \"function_call\",\n call_id: tc.id,\n name: tc.function.name,\n arguments: tc.function.arguments,\n } satisfies ResponseFunctionToolCall);\n }\n }\n\n return items;\n }\n\n case \"tool\":\n return [\n {\n type: \"function_call_output\",\n call_id: message.toolCallId,\n output: message.content,\n } as ResponseInputItem,\n ];\n\n case \"system\":\n return [\n { role: \"system\", content: message.content, type: \"message\" } satisfies EasyInputMessage,\n ];\n\n case \"developer\":\n return [\n { role: \"developer\", content: message.content, type: \"message\" } satisfies EasyInputMessage,\n ];\n\n default:\n return [];\n }\n}\n\nfunction toInputMessage(message: UserMessage): EasyInputMessage {\n const content = message.content;\n\n if (typeof content === \"string\") {\n return { role: \"user\", content, type: \"message\" };\n }\n\n const parts: ResponseInputMessageContentList =\n content?.map((part) => {\n if (part.type === \"text\") {\n return { type: \"input_text\" as const, text: part.text };\n }\n if (part.type === \"binary\") {\n const url = part.url ?? `data:${part.mimeType};base64,${part.data ?? \"\"}`;\n return { type: \"input_image\" as const, image_url: url, detail: \"auto\" as const };\n }\n return { type: \"input_text\" as const, text: \"\" };\n }) ?? [];\n\n return { role: \"user\", content: parts, type: \"message\" };\n}\n\n// ── Inbound (OpenAI Conversations/Responses → AG-UI) ────────────\n\n/**\n * Converts `ConversationItem[]` (from the Conversations API) or\n * `ResponseItem[]` (from the Responses API) into AG-UI `Message[]`.\n *\n * Both APIs return items as a flat list with `type` discriminator:\n * - `\"message\"` → user / assistant / system / developer / tool message\n * - `\"function_call\"` → tool call (grouped into the preceding assistant)\n * - `\"function_call_output\"` → tool result\n *\n * The Conversations API `Message` type is a superset that also handles\n * `reasoning_text`, `summary_text`, and `text` content parts, as well\n * as additional roles like `tool` and `critic`.\n */\nfunction fromItems(items: ConversationItem[]): Message[] {\n const messages: Message[] = [];\n let currentAssistant: AssistantMessage | null = null;\n // Tool outputs for the in-progress assistant turn. BUFFERED rather than\n // pushed immediately so that an assistant turn with MULTIPLE tool calls\n // (e.g. thesys_get_artifact_description THEN thesys_generate_artifact)\n // reconstructs as ONE assistant message + its tool messages — matching the\n // live stream shape — instead of one assistant message PER tool call. The\n // latter renders a duplicate \"Behind the scenes\" group for every call on\n // reload, because each function_call_output used to flush the assistant.\n let pendingToolMsgs: ToolMessage[] = [];\n\n // Emit the in-progress assistant turn: the assistant message first, then its\n // buffered tool results (the renderer pairs tool messages that immediately\n // follow their assistant message).\n const flushAssistant = () => {\n if (currentAssistant) {\n messages.push(currentAssistant);\n currentAssistant = null;\n }\n if (pendingToolMsgs.length > 0) {\n messages.push(...pendingToolMsgs);\n pendingToolMsgs = [];\n }\n };\n\n for (const item of items) {\n switch (item.type) {\n case \"message\": {\n // A non-tool message ends the current assistant turn.\n flushAssistant();\n\n const msg = item as ConversationMessage;\n\n if (msg.role === \"assistant\") {\n currentAssistant = {\n id: msg.id,\n role: \"assistant\",\n content: extractTextContent(msg) || undefined,\n };\n } else if (msg.role === \"tool\") {\n // Conversations API can have tool messages with type: \"message\"\n messages.push({\n id: msg.id,\n role: \"tool\",\n content: extractTextContent(msg),\n toolCallId: \"\",\n } as ToolMessage);\n } else if (msg.role === \"user\") {\n messages.push(fromUserMessage(msg));\n } else {\n // system / developer / unknown / critic / discriminator\n const role = msg.role === \"developer\" ? \"developer\" : \"system\";\n messages.push({\n id: msg.id,\n role,\n content: extractTextContent(msg),\n } as Message);\n }\n break;\n }\n\n case \"function_call\": {\n const tc = item as { id?: string; call_id: string; name: string; arguments: string };\n\n if (!currentAssistant) {\n currentAssistant = { id: crypto.randomUUID(), role: \"assistant\" };\n }\n\n currentAssistant = {\n ...currentAssistant,\n toolCalls: [\n ...(currentAssistant.toolCalls ?? []),\n {\n id: tc.call_id,\n type: \"function\" as const,\n function: { name: tc.name, arguments: tc.arguments },\n },\n ],\n };\n break;\n }\n\n case \"function_call_output\": {\n // Buffer alongside the current assistant — do NOT flush here, so\n // sibling tool calls in the same turn stay on one assistant message.\n const output = item as ResponseFunctionToolCallOutputItem;\n pendingToolMsgs.push({\n id: output.id,\n role: \"tool\",\n content:\n typeof output.output === \"string\" ? output.output : JSON.stringify(output.output),\n toolCallId: output.call_id,\n } as ToolMessage);\n break;\n }\n\n case \"mcp_call\": {\n if (!currentAssistant) {\n currentAssistant = { id: crypto.randomUUID(), role: \"assistant\" };\n }\n\n currentAssistant = {\n ...currentAssistant,\n toolCalls: [\n ...(currentAssistant.toolCalls ?? []),\n {\n id: item.id,\n type: \"function\" as const,\n function: { name: item.name, arguments: item.arguments },\n },\n ],\n };\n\n const errorText =\n typeof item.error === \"string\" && item.error.length > 0 ? item.error : undefined;\n pendingToolMsgs.push({\n id: `${item.id}-output`,\n role: \"tool\",\n content: item.output ?? \"\",\n toolCallId: item.id,\n ...(errorText ? { error: errorText } : {}),\n } as ToolMessage);\n break;\n }\n\n default:\n // file_search, web_search, computer_call, reasoning, etc. — skip\n break;\n }\n }\n\n flushAssistant();\n\n return messages;\n}\n\n/**\n * Extract text content from a Conversations API `Message`.\n *\n * Handles the full content union:\n * - `output_text` (assistant output)\n * - `input_text` (user/system/developer input)\n * - `text` (generic text)\n * - `summary_text`, `reasoning_text` (appended)\n * - `refusal` (mapped to text)\n */\nfunction extractTextContent(msg: ConversationMessage): string {\n return msg.content\n .map((part) => {\n switch (part.type) {\n case \"output_text\":\n return part.text;\n case \"input_text\":\n return part.text;\n case \"text\":\n return part.text;\n case \"summary_text\":\n return part.text;\n case \"reasoning_text\":\n return part.text;\n case \"refusal\":\n return `[Refusal]: ${part.refusal}`;\n default:\n return \"\";\n }\n })\n .filter(Boolean)\n .join(\"\");\n}\n\nfunction fromUserMessage(msg: ConversationMessage): UserMessage {\n // Check if content has images/files — if so, use multipart\n const hasMedia = msg.content.some(\n (part) => part.type === \"input_image\" || part.type === \"input_file\",\n );\n\n if (!hasMedia) {\n return { id: msg.id, role: \"user\", content: extractTextContent(msg) };\n }\n\n const parts = msg.content.map(\n (part): { type: \"text\"; text: string } | { type: \"binary\"; url: string; mimeType: string } => {\n if (part.type === \"input_text\" || part.type === \"text\") {\n return { type: \"text\", text: part.text };\n }\n if (part.type === \"input_image\" && part.image_url) {\n return { type: \"binary\", url: part.image_url, mimeType: \"image/*\" };\n }\n return { type: \"text\", text: \"\" };\n },\n );\n\n return { id: msg.id, role: \"user\", content: parts };\n}\n\n// ── MessageFormat implementation ─────────────────────────────────\n\n/**\n * Converts between AG-UI message format and OpenAI's item-based format,\n * compatible with both the **Responses API** and **Conversations API**.\n *\n * AG-UI → OpenAI (toApi):\n * - Returns `ResponseInputItem[]` — works for both `responses.create({ input })`\n * and `conversations.items.create({ items })`\n * - Flattens assistant messages: text → `EasyInputMessage`, tool calls → `ResponseFunctionToolCall`\n *\n * OpenAI → AG-UI (fromApi):\n * - Accepts `ConversationItem[]` (or `ResponseItem[]`, which is a subset)\n * - Groups adjacent assistant messages + function_calls into `AssistantMessage`\n * - Handles Conversations-specific content types (`reasoning_text`, `summary_text`, etc.)\n */\nexport const openAIConversationMessageFormat: MessageFormat = {\n toApi(messages: Message[]): ResponseInputItem[] {\n return messages.flatMap(toItems);\n },\n\n fromApi(data: unknown): Message[] {\n return fromItems(data as ConversationItem[]);\n },\n};\n","import { openAIConversationMessageFormat } from \"../stream/formats/openai-conversation-message-format\";\nimport type { Message } from \"../types/message\";\nimport type { CloudConversationItem } from \"./wire\";\n\n/**\n * Convert /v1 conversation items to AG-UI Message[]. Each item is normalized\n * into the OpenAI ConversationItem shape that openAIConversationMessageFormat\n * .fromApi expects, then delegated — the grouping logic (function_call →\n * assistant toolCalls, function_call_output → ToolMessage) stays in the SDK.\n *\n * Normalizations:\n * - message content: assistant outputs arrive as part arrays; user inputs\n * arrive as a plain string → wrap strings as a single text part.\n * - function_call / function_call_output: a malformed row (missing the\n * top-level call_id/name/output) is skipped so it can't crash fromApi.\n * - other item types are skipped.\n */\nfunction normalizeItem(item: CloudConversationItem): Record<string, unknown> | null {\n switch (item.type) {\n case \"message\": {\n const content = item.content;\n const parts = Array.isArray(content)\n ? content\n : [\n {\n type: item.role === \"assistant\" ? \"output_text\" : \"input_text\",\n text: typeof content === \"string\" ? content : \"\",\n },\n ];\n return {\n id: item.id,\n type: \"message\",\n role: item.role ?? \"user\",\n status: item.status ?? \"completed\",\n content: parts,\n };\n }\n\n case \"function_call\": {\n if (typeof item.call_id !== \"string\" || typeof item.name !== \"string\") return null;\n return {\n id: item.id,\n type: \"function_call\",\n call_id: item.call_id,\n name: item.name,\n arguments:\n typeof item.arguments === \"string\"\n ? item.arguments\n : JSON.stringify(item.arguments ?? {}),\n };\n }\n\n case \"function_call_output\": {\n if (typeof item.call_id !== \"string\" || item.output === undefined) return null;\n return {\n id: item.id,\n type: \"function_call_output\",\n call_id: item.call_id,\n output: item.output,\n };\n }\n\n default:\n return null;\n }\n}\n\nexport function cloudItemsToMessages(items: CloudConversationItem[]): Message[] {\n const normalized = items\n .map(normalizeItem)\n .filter((i): i is Record<string, unknown> => i !== null);\n return openAIConversationMessageFormat.fromApi(normalized);\n}\n","import type { ThreadStorage } from \"../adapters/types\";\nimport type { Thread } from \"../store/types\";\nimport type { Message, UserMessage } from \"../types/message\";\nimport { cloudItemsToMessages } from \"./items\";\nimport {\n cloudRequest,\n nextCursorOf,\n type CloudConversation,\n type CloudConversationItem,\n type CloudListEnvelope,\n} from \"./wire\";\n\nexport interface CloudThreadStorageOptions {\n /** OpenUI Cloud API origin, e.g. \"http://localhost:3102\". */\n baseUrl: string;\n /** The token-injecting fetch from createFctFetch. */\n fetch: typeof fetch;\n /** Page size for list/items calls. */\n pageLimit?: number;\n}\n\n/** Hard stop for the items pagination loop. */\nconst MAX_ITEM_PAGES = 50;\n\nfunction toThread(conversation: CloudConversation): Thread {\n return {\n id: conversation.id,\n title: conversation.title ?? \"New conversation\",\n createdAt: conversation.created_at * 1000, // unix seconds → ms\n };\n}\n\n/** Client-side title from the first user message (the API does not auto-title). */\nexport function deriveTitle(firstMessage: UserMessage): string {\n const content = firstMessage.content;\n let text = \"\";\n if (typeof content === \"string\") {\n text = content;\n } else if (Array.isArray(content)) {\n for (const part of content) {\n if (part.type === \"text\" && typeof part.text === \"string\" && part.text.trim() !== \"\") {\n text = part.text;\n break;\n }\n }\n }\n text = text.trim();\n return (text === \"\" ? \"New conversation\" : text).slice(0, 60);\n}\n\nexport function cloudThreadStorage({\n baseUrl,\n fetch: fetchImpl,\n pageLimit = 100,\n}: CloudThreadStorageOptions): ThreadStorage {\n const request = cloudRequest(fetchImpl, baseUrl);\n\n return {\n /** GET /v1/conversations?limit[&after]. Newest-first. */\n async listThreads(cursor?: string) {\n const query = new URLSearchParams({ limit: String(pageLimit) });\n if (cursor !== undefined) query.set(\"after\", cursor);\n const res = await request(`/v1/conversations?${query.toString()}`);\n const envelope = (await res.json()) as CloudListEnvelope<CloudConversation>;\n return {\n threads: envelope.data.map(toThread),\n nextCursor: nextCursorOf(envelope),\n };\n },\n\n /** POST /v1/conversations {title}. No messages and no user_id — the user is\n * bound from the token; the first message arrives later on the generation\n * plane (conversation linkage). */\n async createThread(firstMessage: UserMessage): Promise<Thread> {\n const res = await request(`/v1/conversations`, {\n method: \"POST\",\n body: JSON.stringify({ title: deriveTitle(firstMessage) }),\n });\n return toThread((await res.json()) as CloudConversation);\n },\n\n /** GET /v1/conversations/:id/items?order=asc, paged, then mapped to Messages. */\n async getMessages(threadId: string): Promise<Message[]> {\n const items: CloudConversationItem[] = [];\n let after: string | undefined;\n for (let page = 0; page < MAX_ITEM_PAGES; page++) {\n const query = new URLSearchParams({\n order: \"asc\",\n limit: String(pageLimit),\n });\n if (after !== undefined) query.set(\"after\", after);\n const res = await request(\n `/v1/conversations/${encodeURIComponent(threadId)}/items?${query.toString()}`,\n );\n const envelope = (await res.json()) as CloudListEnvelope<CloudConversationItem>;\n items.push(...envelope.data);\n after = nextCursorOf(envelope);\n if (after === undefined) break;\n }\n return cloudItemsToMessages(items);\n },\n\n /** POST /v1/conversations/:id {title}. */\n async updateThread(thread: Thread): Promise<Thread> {\n const res = await request(`/v1/conversations/${encodeURIComponent(thread.id)}`, {\n method: \"POST\",\n body: JSON.stringify({ title: thread.title }),\n });\n return toThread((await res.json()) as CloudConversation);\n },\n\n /** DELETE /v1/conversations/:id (soft delete). */\n async deleteThread(id: string): Promise<void> {\n await request(`/v1/conversations/${encodeURIComponent(id)}`, {\n method: \"DELETE\",\n });\n },\n };\n}\n","import { computed, toValue, type MaybeRefOrGetter, type ComputedRef } from \"vue\";\nimport type { ChatStorage } from \"../adapters/types\";\n\nimport { cloudArtifactStorage } from \"./artifactStorage\";\nimport {\n createFctFetch,\n toFrontendTokenManager,\n type FrontendTokenSource,\n} from \"./frontendTokenManager\";\nimport { cloudThreadStorage } from \"./threadStorage\";\n\n/** Which storage surfaces useOpenuiCloudStorage wires. */\nexport interface OpenuiCloudFeatures {\n /** Stored-artifact reads + edits. Default true. */\n artifact?: boolean;\n}\n\nexport interface OpenuiCloudOptions {\n /**\n * The OpenUI Cloud API origin. Defaults to \"https://api.thesys.dev\" (the\n * storage layer appends `/v1/...`). Set this to e.g. \"http://localhost:3102\"\n * to run against a local stack. The browser calls this directly with the\n * fct_ token — there is no same-origin proxy in between.\n */\n apiBaseUrl?: string;\n /**\n * Where the short-lived fct_ session token comes from — either a URL of your\n * backend mint endpoint (POST → { token, expires_at }, cached + refreshed\n * here) or a function returning a fresh token (you own caching). The token\n * rides the `x-thesys-frontend-token` header on every /v1 call. The frontend\n * token is minted server-side; the master key never reaches the browser.\n */\n token: FrontendTokenSource;\n /** Which storage surfaces to wire. Omit to enable all. */\n features?: OpenuiCloudFeatures;\n /**\n * Dashboards show each query's last result while it reloads; the results are\n * kept in OpenUI Cloud for 24 hours, per user. `false` turns this off. Default true.\n */\n cacheQueryResults?: boolean;\n /** fetch override (tests / SSR). Defaults to globalThis.fetch. */\n fetch?: typeof fetch;\n /** Refresh the cached token this many seconds before expiry (URL form). Default 60. */\n refreshSkewSeconds?: number;\n}\n\n/** OpenUI Cloud API origin used when `apiBaseUrl` is omitted. The storage\n * layer appends `/v1/...` to it. */\nconst DEFAULT_API_BASE_URL = \"https://api.thesys.dev\";\n\n/**\n * One-call browser wiring for OpenUI Cloud, as a hook: a memoised `ChatStorage`\n * backed by the /v1 API, authenticated per-request with an fct_ session token.\n * Pass it straight to `<AgentInterface storage={…} />`.\n *\n * As a hook the storage (and its fct_ token manager) is created on mount and\n * re-created only when its options change. Tokens are minted lazily on the first\n * storage request. ChatProvider captures storage at mount; remount the provider\n * when switching users or storage configurations.\n *\n * This is the READ/EDIT plane (browser → /v1/* with the fct_ token). Generation\n * is the separate ChatLLM plane (browser → your backend → /v1/embed/responses\n * with the master key).\n */\nexport function useOpenuiCloudStorage(options: MaybeRefOrGetter<OpenuiCloudOptions>): ComputedRef<ChatStorage> {\n let previous: readonly unknown[] | undefined;\n let storage: ChatStorage;\n return computed(() => {\n const current = toValue(options);\n // Match frozen React useMemo dependencies exactly: only artifact is\n // normalized; omitted origin/skew are distinct from explicit defaults.\n const dependencies = [current.apiBaseUrl, current.token, current.fetch,\n current.refreshSkewSeconds, current.cacheQueryResults, current.features?.artifact ?? true];\n if (!previous || dependencies.some((value, index) => !Object.is(value, previous![index]))) {\n storage = createCloudStorage(current);\n previous = dependencies;\n }\n return storage;\n });\n}\n\n/** The actual storage wiring — a pure factory with no Vue, memoised by the\n * composable above. */\nfunction createCloudStorage(options: OpenuiCloudOptions): ChatStorage {\n const tokens = toFrontendTokenManager(options.token, {\n fetch: options.fetch,\n refreshSkewSeconds: options.refreshSkewSeconds,\n });\n const fctFetch = createFctFetch(tokens, options.fetch);\n const artifactOn = options.features?.artifact ?? true;\n const baseUrl = options.apiBaseUrl ?? DEFAULT_API_BASE_URL;\n\n const storage: ChatStorage = {\n thread: cloudThreadStorage({ baseUrl, fetch: fctFetch }),\n };\n if (artifactOn) {\n storage.artifact = cloudArtifactStorage({\n baseUrl,\n fetch: fctFetch,\n cacheQueryResults: options.cacheQueryResults,\n });\n }\n return storage;\n}\n","import { inject, toValue, type InjectionKey, type MaybeRefOrGetter } from \"vue\";\n\n/** @internal Set by `OpenUICloudProvider`'s `pollInterval`. */\nexport const ArtifactPollIntervalContext = Symbol(\"ArtifactPollIntervalContext\") as InjectionKey<\n MaybeRefOrGetter<number | false | undefined>\n>;\n\n/**\n * How often open artifacts check for changes, as set on `OpenUICloudProvider`.\n * Undefined when it doesn't say.\n */\nexport const useArtifactPollInterval = (): number | false | undefined =>\n toValue(inject(ArtifactPollIntervalContext, undefined));\n","import { computed, defineComponent, provide, type PropType } from \"vue\";\nimport { ArtifactStorageContext } from \"../store/ArtifactStorageContext\";\nimport type { FrontendTokenSource } from \"./frontendTokenManager\";\nimport { useOpenuiCloudStorage, type OpenuiCloudOptions } from \"./openuiCloud\";\nimport { ArtifactPollIntervalContext } from \"./pollInterval\";\n\n/** @category Types */\nexport interface OpenUICloudProviderProps extends Omit<OpenuiCloudOptions, \"features\"> {\n /**\n * How often every open artifact checks for a newer version, a rename or an\n * access change, in ms (at least 3s), unless its renderer sets its own.\n * `false`: never. Default 30s.\n */\n pollInterval?: number | false;\n}\n\nexport const OpenUICloudProvider = defineComponent({\n name: \"OpenUICloudProvider\",\n props: {\n apiBaseUrl: { type: String as PropType<string | undefined>, default: undefined },\n token: {\n type: [String, Function] as PropType<FrontendTokenSource>,\n required: true as const,\n },\n cacheQueryResults: { type: Boolean as PropType<boolean | undefined>, default: undefined },\n fetch: { type: Function as PropType<typeof fetch | undefined>, default: undefined },\n refreshSkewSeconds: { type: Number as PropType<number | undefined>, default: undefined },\n pollInterval: {\n type: [Number, Boolean] as PropType<number | false | undefined>,\n default: undefined,\n },\n },\n setup(props, { slots }) {\n const stableReadToken = () => {\n const current = props.token;\n return typeof current === \"string\" ? Promise.resolve(current) : current();\n };\n const storage = useOpenuiCloudStorage(() => ({\n apiBaseUrl: props.apiBaseUrl,\n token: typeof props.token === \"string\" ? props.token : stableReadToken,\n cacheQueryResults: props.cacheQueryResults,\n fetch: props.fetch,\n refreshSkewSeconds: props.refreshSkewSeconds,\n }));\n\n const artifactStorage = computed(() => storage.value.artifact ?? null);\n provide(ArtifactStorageContext, artifactStorage.value);\n provide(ArtifactPollIntervalContext, () => props.pollInterval);\n\n return () => slots.default?.() ?? null;\n },\n});\n","import { computed, getCurrentInstance, getCurrentScope, inject, onScopeDispose, shallowRef, ssrContextKey, watchEffect, type ComputedRef } from 'vue'\nimport type { StoreApi } from 'zustand/vanilla'\n\n/** Vue binding for the pinned Zustand vanilla store; the owner scope owns cleanup. */\nexport function useStore<S, T>(store: StoreApi<S>, selector: (state: S) => T): ComputedRef<T> {\n if (!getCurrentScope()) throw new Error('useStore must be used within a Vue setup or effect scope')\n // Server scopes are not unmounted. Like useSyncExternalStore, SSR reads a\n // snapshot without installing a listener; use only Vue's public SSR key.\n if (getCurrentInstance() && inject(ssrContextKey, null) !== null) {\n return computed(() => selector(store.getInitialState()))\n }\n const snapshot = shallowRef(store.getState())\n const selected = shallowRef<T>()\n // Eager selection is necessary on Vue 3.3: a lazy computed invalidates its\n // consumers even when its next value is identical. Track external ref/getter\n // dependencies too (e.g. a changing detailed-view ID).\n watchEffect(() => { selected.value = selector(snapshot.value) }, { flush: 'sync' })\n const unsubscribe = store.subscribe(state => { snapshot.value = state })\n snapshot.value = store.getState()\n onScopeDispose(unsubscribe)\n return computed(() => selected.value as T)\n}\n\n/** Per-consumer useShallow equivalent for the default thread slices only. */\nexport function shallowSelector<S, T extends object>(selector: (state: S) => T): (state: S) => T {\n let previous: T | undefined\n return state => {\n const next = selector(state)\n const keys = Object.keys(next) as Array<keyof T>\n if (previous && keys.length === Object.keys(previous).length && keys.every(key => Object.prototype.hasOwnProperty.call(previous, key) && Object.is(previous![key], next[key]))) return previous\n previous = next\n return next\n }\n}\n","import { inject, type InjectionKey } from \"vue\";\nimport type { StoreApi } from \"zustand/vanilla\";\nimport type { DetailedViewStore } from \"./detailedViewTypes\";\n\n/** @internal React context holding the detailed-view Zustand store. Provided by `ChatProvider`. */\nexport const DetailedViewContext = Symbol(\"DetailedViewContext\") as InjectionKey<StoreApi<DetailedViewStore> | null>;\n\n/**\n * Returns the raw detailed-view Zustand store for advanced use cases.\n *\n * Prefer {@link useDetailedView} or {@link useActiveDetailedView} for most cases —\n * this hook is an escape hatch when you need direct store access.\n *\n * @category Hooks\n * @returns The Zustand `StoreApi<DetailedViewStore>` instance\n * @throws Error if called outside a `<ChatProvider>`\n */\nexport const useDetailedViewStore = (): StoreApi<DetailedViewStore> => {\n const store = inject(DetailedViewContext, null);\n if (!store) {\n throw new Error(\"useDetailedViewStore must be used within a <ChatProvider>\");\n }\n return store;\n};\n","import { computed } from 'vue'\nimport { useStore } from '../store/useStore'\nimport { useDetailedViewStore } from '../store/DetailedViewContext'\nexport function useActiveDetailedView() {\n const store = useDetailedViewStore()\n const activeDetailedViewId = useStore(store, state => state.activeDetailedViewId)\n const isDetailedViewActive = computed(() => activeDetailedViewId.value !== null)\n const closeDetailedView = () => {\n if (store.getState().activeDetailedViewId !== null) store.getState().setActiveDetailedView(null)\n }\n return { activeDetailedViewId, isDetailedViewActive, closeDetailedView }\n}\n","import { inject, type InjectionKey } from \"vue\";\nimport type { StoreApi } from \"zustand/vanilla\";\nimport type { ThreadContextStore } from \"./threadContextTypes\";\n\n/** @internal React context holding the ThreadContext Zustand store. Provided by `ChatProvider`. */\nexport const ThreadContextContext = Symbol(\"ThreadContextContext\") as InjectionKey<StoreApi<ThreadContextStore> | null>;\n\n/**\n * Returns the raw ThreadContext Zustand store for advanced use cases.\n *\n * Prefer {@link useDetailedView}, {@link useActiveDetailedView}, {@link useAppList},\n * or {@link useArtifactList} for most cases — this hook is an escape hatch when you\n * need direct store access.\n *\n * @category Hooks\n * @returns The Zustand `StoreApi<ThreadContextStore>` instance\n * @throws Error if called outside a `<ChatProvider>`\n */\nexport const useThreadContextStore = (): StoreApi<ThreadContextStore> => {\n const store = inject(ThreadContextContext, null);\n if (!store) {\n throw new Error(\"useThreadContextStore must be used within a <ChatProvider>\");\n }\n return store;\n};\n","import { computed, toValue, type MaybeRefOrGetter } from 'vue'\nimport { useStore } from '../store/useStore'\nimport { useThreadContextStore } from '../store/ThreadContextContext'\nimport type { ArtifactEntry } from '../store/threadContextTypes'\nexport interface ArtifactListFilter { type?: string[] }\nexport function useArtifactList(filter?: MaybeRefOrGetter<ArtifactListFilter | undefined>) {\n const store = useThreadContextStore()\n const artifacts = useStore(store, state => state.artifacts)\n let previous: { artifacts: Record<string, ArtifactEntry[]>; typeKey: string | undefined; value: Record<string, ArtifactEntry[]> } | undefined\n return computed(() => {\n const typeKey = toValue(filter)?.type?.join(' ')\n const current = artifacts.value\n if (previous && previous.artifacts === current && previous.typeKey === typeKey) return previous.value\n if (typeKey === undefined) {\n previous = { artifacts: current, typeKey, value: current }\n return current\n }\n const allowed = new Set(typeKey.split(' '))\n const result: Record<string, ArtifactEntry[]> = {}\n for (const [id, versions] of Object.entries(current)) {\n const latest = versions[versions.length - 1]\n if (latest && allowed.has(latest.type)) result[id] = versions\n }\n previous = { artifacts: current, typeKey, value: result }\n return result\n })\n}\n","import { inject, type InjectionKey } from \"vue\";\nimport type { ArtifactRendererConfig } from \"./artifactRendererTypes\";\n\n/**\n * Pre-built lookup structure for artifact-renderer matching.\n *\n * Built once at `ChatProvider` mount from the user-supplied `artifactRenderers`\n * array. Subsequent prop changes are ignored (with a dev-mode warning) so\n * renderer registration stays stable for the lifetime of the provider.\n *\n * @internal\n */\nexport type ArtifactRendererRegistry = {\n /** toolName → renderer. A renderer with several toolNames appears once per name. */\n byToolName: Map<string, ArtifactRendererConfig<unknown>>;\n /** artifact type → renderer. Used by the artifact browser to render stored artifacts. */\n byType: Map<string, ArtifactRendererConfig<unknown>>;\n};\n\nconst isDev = () => typeof process !== \"undefined\" && process.env?.[\"NODE_ENV\"] !== \"production\";\n\n/**\n * Builds an {@link ArtifactRendererRegistry} from a list of configs.\n *\n * First-wins on duplicate `toolName` or `type`: subsequent registrations are\n * ignored with a dev-mode warning so the user can reorder their array\n * (custom renderers should come *before* SDK defaults).\n *\n * @internal\n */\nexport function buildArtifactRendererRegistry(\n configs: ReadonlyArray<ArtifactRendererConfig<any>>,\n): ArtifactRendererRegistry {\n const byToolName = new Map<string, ArtifactRendererConfig<unknown>>();\n const byType = new Map<string, ArtifactRendererConfig<unknown>>();\n\n for (const config of configs) {\n const toolNames = Array.isArray(config.toolName) ? config.toolName : [config.toolName];\n for (const name of toolNames) {\n if (byToolName.has(name)) {\n if (isDev()) {\n console.warn(\n `[OpenUI] Artifact renderer for toolName \"${name}\" was ignored ` +\n `(already registered earlier in the array).`,\n );\n }\n continue;\n }\n byToolName.set(name, config);\n }\n\n if (byType.has(config.type)) {\n if (isDev()) {\n console.warn(\n `[OpenUI] Artifact renderer for type \"${config.type}\" was ignored for type-based ` +\n `lookup (already registered earlier in the array).`,\n );\n }\n continue;\n }\n byType.set(config.type, config);\n }\n\n return { byToolName, byType };\n}\n\n/** Resolves the renderer matching a tool name, or `null`. @internal */\nexport function lookupArtifactRenderer(\n registry: ArtifactRendererRegistry,\n toolName: string,\n): ArtifactRendererConfig<unknown> | null {\n return registry.byToolName.get(toolName) ?? null;\n}\n\n/** Resolves the renderer matching an artifact type, or `null`. @internal */\nexport function lookupArtifactRendererByType(\n registry: ArtifactRendererRegistry,\n type: string,\n): ArtifactRendererConfig<unknown> | null {\n return registry.byType.get(type) ?? null;\n}\n\n/** @internal React context holding the renderer registry. Provided by `ChatProvider`. */\nexport const ArtifactRenderersContext = Symbol(\"ArtifactRenderersContext\") as InjectionKey<ArtifactRendererRegistry | null>;\n\n/**\n * Returns the raw artifact-renderer registry for advanced use cases.\n *\n * Prefer {@link useArtifactRenderer} for resolving a specific tool name —\n * this hook is an escape hatch for custom dispatching.\n *\n * Returns `null` if no `artifactRenderers` were provided to the `<ChatProvider>` —\n * this is not an error since renderers are optional.\n *\n * @category Hooks\n */\nexport const useArtifactRendererRegistry = (): ArtifactRendererRegistry | null => {\n return inject(ArtifactRenderersContext, null);\n};\n","import { computed, toValue, type MaybeRefOrGetter } from 'vue'\nimport { lookupArtifactRenderer, useArtifactRendererRegistry } from '../store/ArtifactRenderersContext'\nexport function useArtifactRenderer(toolName: MaybeRefOrGetter<string>) {\n const registry = useArtifactRendererRegistry()\n return computed(() => registry ? lookupArtifactRenderer(registry, toValue(toolName)) : null)\n}\n","import { toValue, type MaybeRefOrGetter } from 'vue'\nimport { useStore } from '../store/useStore'\nimport { useDetailedViewStore } from '../store/DetailedViewContext'\nexport function useDetailedView(viewId: MaybeRefOrGetter<string>) {\n const store = useDetailedViewStore()\n const isActive = useStore(store, state => state.activeDetailedViewId === toValue(viewId))\n const open = () => store.getState().setActiveDetailedView(toValue(viewId))\n const close = () => {\n if (store.getState().activeDetailedViewId === toValue(viewId)) store.getState().setActiveDetailedView(null)\n }\n const toggle = () => {\n const id = toValue(viewId)\n store.getState().setActiveDetailedView(store.getState().activeDetailedViewId === id ? null : id)\n }\n return { isActive, open, close, toggle }\n}\n","import { useStore } from '../store/useStore'\nimport { useDetailedViewStore } from '../store/DetailedViewContext'\nexport function useDetailedViewPortalTarget() {\n const store = useDetailedViewStore()\n const node = useStore(store, state => state._detailedViewPanelNode)\n return { node, setNode: (node: HTMLElement | null) => store.getState()._setDetailedViewPanelNode(node) }\n}\n","import { defineComponent, inject, provide, type InjectionKey, type PropType } from 'vue'\nimport type { Message } from '../types'\nexport const MessageContext = Symbol('MessageContext') as InjectionKey<{ readonly message: Message }>\nexport function useMessage() {\n const context = inject(MessageContext, null)\n if (!context) throw new Error('useMessage must be used within a MessageProvider')\n return context\n}\nexport const MessageProvider = defineComponent({\n name: 'OpenUIMessageProvider',\n props: { message: { type: Object as PropType<Message>, required: true } },\n setup(props, { slots }) {\n provide(MessageContext, { get message() { return props.message } })\n return () => slots.default?.()\n },\n})\n","import { inject, type InjectionKey } from \"vue\";\nimport type { StoreApi } from \"zustand/vanilla\";\nimport type { ChatStore } from \"./types\";\n\nexport const ChatContext = Symbol(\"ChatContext\") as InjectionKey<StoreApi<ChatStore> | null>;\n\nexport const useChatStore = (): StoreApi<ChatStore> => {\n const store = inject(ChatContext, null);\n if (!store) {\n throw new Error(\"useChatStore must be used within a <ChatProvider>\");\n }\n return store;\n};\n","import { shallowSelector, useStore } from \"../store/useStore\";\nimport type { ComputedRef } from \"vue\";\nimport { useChatStore } from \"../store/ChatContext\";\nimport type {\n ChatStore,\n ThreadActions,\n ThreadListActions,\n ThreadListState,\n ThreadState,\n} from \"../store/types\";\n\ntype ThreadSlice = ThreadState & ThreadActions;\ntype ThreadListSlice = ThreadListState & ThreadListActions;\n\nconst threadSelector = (s: ChatStore): ThreadSlice => ({\n messages: s.messages,\n isRunning: s.isRunning,\n isLoadingMessages: s.isLoadingMessages,\n threadError: s.threadError,\n executingToolCallIds: s.executingToolCallIds,\n processMessage: s.processMessage,\n appendMessages: s.appendMessages,\n updateMessage: s.updateMessage,\n setMessages: s.setMessages,\n deleteMessage: s.deleteMessage,\n cancelMessage: s.cancelMessage,\n});\n\nconst threadListSelector = (s: ChatStore): ThreadListSlice => ({\n threads: s.threads,\n isLoadingThreads: s.isLoadingThreads,\n threadListError: s.threadListError,\n selectedThreadId: s.selectedThreadId,\n hasMoreThreads: s.hasMoreThreads,\n loadThreads: s.loadThreads,\n loadMoreThreads: s.loadMoreThreads,\n switchToNewThread: s.switchToNewThread,\n createThread: s.createThread,\n selectThread: s.selectThread,\n updateThread: s.updateThread,\n deleteThread: s.deleteThread,\n});\n\nexport function useThread(): ComputedRef<ThreadSlice>;\nexport function useThread<T>(selector: (state: ThreadSlice) => T): ComputedRef<T>;\nexport function useThread<T>(selector?: (state: ThreadSlice) => T) {\n const store = useChatStore();\n if (selector) {\n return useStore(store, (s) => selector(threadSelector(s)));\n }\n return useStore(store, shallowSelector(threadSelector));\n}\n\nexport function useThreadList(): ComputedRef<ThreadListSlice>;\nexport function useThreadList<T>(selector: (state: ThreadListSlice) => T): ComputedRef<T>;\nexport function useThreadList<T>(selector?: (state: ThreadListSlice) => T) {\n const store = useChatStore();\n if (selector) {\n return useStore(store, (s) => selector(threadListSelector(s)));\n }\n return useStore(store, shallowSelector(threadListSelector));\n}\n","import type { AssistantMessage, Message, ToolCall, ToolMessage } from \"../types\";\n\n/**\n * Real per-call lifecycle of a tool invocation.\n *\n * Derived from AG-UI stream events (never faked from `!!content`):\n * - `streaming` — arguments are still arriving (`TOOL_CALL_ARGS` deltas).\n * - `executing` — arguments closed (`TOOL_CALL_END` seen), awaiting a result.\n * - `complete` — a `TOOL_CALL_RESULT` landed without an error.\n * - `error` — a `TOOL_CALL_RESULT`/`RUN_ERROR` carried a failure.\n *\n * @category Types\n */\nexport type ToolCallStatus = \"streaming\" | \"executing\" | \"complete\" | \"error\";\n\n/**\n * Single source of truth for one tool call + its (optional) result, used by the\n * UI layer instead of reading raw `ToolCall`/`ToolMessage` separately.\n *\n * Discriminated by `status` so impossible states are unrepresentable: the view\n * literally cannot read `result`/`errorText` in a state where they don't exist,\n * nor render an error as a success.\n *\n * - `streaming` → args still arriving; `input` is `Partial<T>`, no result.\n * - `executing` → args closed; `input` is `T`, awaiting result.\n * - `complete` → result landed OK; `input` is `T`, `result` is a string.\n * - `error` → result landed with a failure; `errorText` present.\n *\n * `input` is {@link partialJSONParse}'d **once** by the selector — never a raw\n * string for the consumer to parse.\n *\n * @category Types\n */\nexport type ToolActivity<T = unknown> =\n | {\n status: \"streaming\";\n id: string;\n toolName: string;\n toolCall: ToolCall;\n toolMessage: null;\n input: Partial<T>;\n result?: undefined;\n isError: false;\n errorText?: undefined;\n statusMessage?: string;\n }\n | {\n status: \"executing\";\n id: string;\n toolName: string;\n toolCall: ToolCall;\n toolMessage: null;\n input: T;\n result?: undefined;\n isError: false;\n errorText?: undefined;\n statusMessage?: string;\n }\n | {\n status: \"complete\";\n id: string;\n toolName: string;\n toolCall: ToolCall;\n toolMessage: ToolMessage;\n input: T;\n result: string;\n isError: false;\n errorText?: undefined;\n statusMessage?: string;\n }\n | {\n status: \"error\";\n id: string;\n toolName: string;\n toolCall: ToolCall;\n toolMessage: ToolMessage;\n input: T;\n result: string;\n isError: true;\n errorText?: string;\n statusMessage?: string;\n };\n\nconst isDev = () => typeof process !== \"undefined\" && process.env?.[\"NODE_ENV\"] !== \"production\";\n\n/**\n * Closes dangling brackets/quotes for a partial (mid-stream) JSON string so it\n * can be parsed for a best-effort snapshot. Conservative: only trims a trailing\n * object key that is provably awaiting a value (signalled by a trailing colon),\n * leaving complete array/values intact.\n */\nfunction balanceOpenJSON(raw: string): string {\n const closers: string[] = [];\n let inString = false;\n let escaped = false;\n\n for (let i = 0; i < raw.length; i++) {\n const ch = raw[i];\n if (inString) {\n if (escaped) escaped = false;\n else if (ch === \"\\\\\") escaped = true;\n else if (ch === '\"') inString = false;\n continue;\n }\n if (ch === '\"') inString = true;\n else if (ch === \"{\") closers.push(\"}\");\n else if (ch === \"[\") closers.push(\"]\");\n else if (ch === \"}\" || ch === \"]\") closers.pop();\n }\n\n let out = raw;\n if (inString) {\n // Mid-string: drop a dangling escape, then close the string literal.\n if (escaped) out = out.slice(0, -1);\n out += '\"';\n }\n\n // Drop a dangling object key with no value yet (`… \"key\":`). The colon is the\n // reliable \"awaiting value\" signal — a trailing string WITHOUT a colon may be\n // a complete array element/value, so leave it. Then drop any exposed comma.\n out = out.replace(/(?:,\\s*)?\"(?:[^\"\\\\]|\\\\.)*\"\\s*:\\s*$/, \"\");\n out = out.replace(/,\\s*$/, \"\");\n\n for (let i = closers.length - 1; i >= 0; i--) out += closers[i];\n return out;\n}\n\n/**\n * Tolerant single-pass JSON parse for streamed tool arguments. Tries a straight\n * parse, then a bracket-balanced parse for partial input. **Never throws** —\n * returns `{}` when nothing parseable can be recovered.\n *\n * @category Utilities\n */\nexport function partialJSONParse(raw: string): unknown {\n if (!raw) return {};\n try {\n return JSON.parse(raw);\n } catch {\n /* fall through to the balanced attempt */\n }\n try {\n return JSON.parse(balanceOpenJSON(raw));\n } catch {\n return {};\n }\n}\n\nlet warnedTitle = false;\n\n/**\n * Maps the deprecated `_title` tool-arg key onto a typed `statusMessage` for one\n * minor release (with a one-time dev warning). Prefer a renderer-owned typed\n * field going forward.\n */\nfunction readStatusMessage(input: unknown): string | undefined {\n if (input && typeof input === \"object\" && \"_title\" in input) {\n const value = (input as Record<string, unknown>)[\"_title\"];\n if (typeof value === \"string\") {\n if (isDev() && !warnedTitle) {\n warnedTitle = true;\n console.warn(\n \"[OpenUI] The `_title` tool-arg key is deprecated and will be removed; \" +\n \"the renderer now exposes a typed `statusMessage` on ToolActivity instead.\",\n );\n }\n return value;\n }\n }\n return undefined;\n}\n\n/**\n * Pairs every tool call on an assistant message with its result message **by\n * `toolCallId`** (id-keyed, no positional `break`), producing a typed\n * {@link ToolActivity} per call. Turn-safe even when tool messages trail or\n * interleave with other messages.\n *\n * @param message The assistant message owning the tool calls.\n * @param allMessages The full thread message list (scanned for tool results).\n * @param executingIds Tool-call ids whose args have closed but whose result\n * hasn't landed (the store's `executingToolCallIds`).\n *\n * @category Utilities\n */\nexport function pairToolActivity(\n message: AssistantMessage,\n allMessages: ReadonlyArray<Message>,\n executingIds: ReadonlySet<string> = new Set(),\n): ToolActivity[] {\n const byCallId = new Map<string, ToolMessage>();\n // Every tool-call id owned by ANY assistant message — used to detect orphan\n // tool results (a `role:\"tool\"` message whose call exists nowhere).\n const ownedCallIds = new Set<string>();\n for (const m of allMessages) {\n if (m.role === \"tool\") {\n const tm = m as ToolMessage;\n if (tm.toolCallId) byCallId.set(tm.toolCallId, tm);\n } else if (m.role === \"assistant\") {\n for (const tc of (m as AssistantMessage).toolCalls ?? []) ownedCallIds.add(tc.id);\n }\n }\n\n const activities = (message.toolCalls ?? []).map((toolCall): ToolActivity => {\n const toolMessage = byCallId.get(toolCall.id) ?? null;\n const input = partialJSONParse(toolCall.function.arguments) as Record<string, unknown>;\n const statusMessage = readStatusMessage(input);\n const base = {\n id: toolCall.id,\n toolName: toolCall.function.name,\n toolCall,\n statusMessage,\n };\n\n if (toolMessage) {\n return toolMessage.error\n ? {\n ...base,\n status: \"error\",\n toolMessage,\n input: input as never,\n result: toolMessage.content,\n isError: true,\n errorText: toolMessage.error,\n }\n : {\n ...base,\n status: \"complete\",\n toolMessage,\n input: input as never,\n result: toolMessage.content,\n isError: false,\n };\n }\n\n return executingIds.has(toolCall.id)\n ? {\n ...base,\n status: \"executing\",\n toolMessage: null,\n input: input as never,\n isError: false,\n }\n : {\n ...base,\n status: \"streaming\",\n toolMessage: null,\n input: input as Partial<unknown>,\n isError: false,\n };\n });\n\n // Orphan tool results: tool messages that trail THIS assistant message but\n // belong to no tool call anywhere. Previously these still rendered (as a\n // generic result chip); pairing by id alone would drop them. Attribute each\n // to the assistant message it positionally trails so it renders exactly once.\n const msgIndex = allMessages.findIndex((m) => m.id === message.id);\n if (msgIndex !== -1) {\n for (let i = msgIndex + 1; i < allMessages.length; i++) {\n const m = allMessages[i];\n if (!m || m.role !== \"tool\") break;\n const tm = m as ToolMessage;\n if (!tm.toolCallId || ownedCallIds.has(tm.toolCallId)) continue;\n const orphanCall: ToolCall = {\n id: tm.toolCallId,\n type: \"function\",\n function: { name: \"\", arguments: \"\" },\n };\n // Key by the (unique) tool-message id, not the toolCallId — two orphan\n // results can share a toolCallId in persisted history and would otherwise\n // collide on the React key.\n const base = { id: tm.id, toolName: \"\", toolCall: orphanCall };\n activities.push(\n tm.error\n ? {\n ...base,\n status: \"error\",\n toolMessage: tm,\n input: {} as never,\n result: tm.content,\n isError: true,\n errorText: tm.error,\n }\n : {\n ...base,\n status: \"complete\",\n toolMessage: tm,\n input: {} as never,\n result: tm.content,\n isError: false,\n },\n );\n }\n }\n\n return activities;\n}\n","import { computed, toValue, type MaybeRefOrGetter } from 'vue'\nimport { pairToolActivity, type ToolActivity } from '../store/toolActivity'\nimport type { AssistantMessage, Message, ToolMessage } from '../types'\nimport { useThread } from './useThread'\nexport function useToolActivities(message: MaybeRefOrGetter<AssistantMessage>, allMessages: MaybeRefOrGetter<Message[]>) {\n const executingIds = useThread(state => state.executingToolCallIds)\n let previous: { id: string; args: string; result: string; executing: Set<string>; value: ToolActivity[] } | undefined\n return computed(() => {\n const current = toValue(message); const messages = toValue(allMessages)\n const args = (current.toolCalls ?? []).map(tool => `${tool.id}:${tool.function.arguments.length}`).join('|')\n const result = messages.filter((item): item is ToolMessage => item.role === 'tool').map(item => `${item.toolCallId}:${item.content?.length ?? 0}:${item.error ? 1 : 0}`).join('|')\n const executing = executingIds.value\n // Preserve the original React memo invalidation contract, including its\n // length-based keys; do not silently change same-length update behavior.\n if (previous && previous.id === current.id && previous.args === args && previous.result === result && previous.executing === executing) return previous.value\n previous = { id: current.id, args, result, executing, value: pairToolActivity(current, messages, executing) }\n return previous.value\n })\n}\n","import type { VNodeChild } from \"vue\";\n\nimport type { ArtifactCategory } from \"../adapters/types\";\nimport type { ArtifactRendererConfig } from \"./artifactRendererTypes\";\n\n/**\n * One named artifact category and the renderers that belong to it. Passed to\n * {@link defineArtifactCategories}.\n *\n * @category Types\n */\nexport interface ArtifactCategoryGroup {\n /** Display label and key for the category, e.g. `\"Reports\"`. */\n name: string;\n /**\n * Renderers in this category. Each renderer's `type` populates the category's\n * filter, and the renderers themselves are collected into `artifactRenderers`.\n */\n renderers: ArtifactRendererConfig<any>[];\n /** Sidebar nav icon for the category. Omit to fall back to the default. */\n icon?: VNodeChild;\n}\n\n/**\n * Wraps the manual `artifactRenderers` + `artifactCategories` wiring: declare\n * each category once with its renderers, and get both props back, ready to\n * spread onto `<AgentInterface>`.\n *\n * - `artifactRenderers` is every group's renderers, in order, de-duplicated by\n * identity (a renderer listed in two groups registers once).\n * - `artifactCategories` is one {@link ArtifactCategory} per group, its\n * `filter.type` collected from the group's renderer `type`s (de-duplicated).\n *\n * @category Functions\n *\n * @example\n * ```tsx\n * const artifacts = defineArtifactCategories([\n * { name: \"Reports\", renderers: [reportRenderer], icon: <ReportIcon /> },\n * { name: \"Dashboards\", renderers: [dashboardRenderer], icon: <AppIcon /> },\n * ]);\n *\n * <AgentInterface llm={llm} {...artifacts} />;\n * ```\n */\nexport function defineArtifactCategories(groups: ArtifactCategoryGroup[]): {\n artifactRenderers: ArtifactRendererConfig<any>[];\n artifactCategories: ArtifactCategory[];\n} {\n const artifactRenderers: ArtifactRendererConfig<any>[] = [];\n const seenRenderers = new Set<ArtifactRendererConfig<any>>();\n\n const artifactCategories = groups.map((group): ArtifactCategory => {\n const type: string[] = [];\n const seenTypes = new Set<string>();\n\n for (const renderer of group.renderers) {\n if (!seenRenderers.has(renderer)) {\n seenRenderers.add(renderer);\n artifactRenderers.push(renderer);\n }\n if (!seenTypes.has(renderer.type)) {\n seenTypes.add(renderer.type);\n type.push(renderer.type);\n }\n }\n\n return { name: group.name, filter: { type }, icon: group.icon };\n });\n\n return { artifactRenderers, artifactCategories };\n}\n","import { computed, inject, type ComputedRef, type InjectionKey } from 'vue'\nimport type { ArtifactCategory } from '../adapters/types'\nexport const ArtifactCategoriesContext = Symbol('ArtifactCategoriesContext') as InjectionKey<ComputedRef<ArtifactCategory[]>>\nexport const useArtifactCategories = () => inject(ArtifactCategoriesContext, computed(() => []))\n","import type { VNodeChild } from \"vue\";\n\n/**\n * Controls passed to a renderer's `preview` and `actual` render functions.\n *\n * @category Types\n */\nexport interface ArtifactRendererControls {\n /** Whether this renderer's detailed view is the currently active one. */\n isActive: boolean;\n /**\n * `true` while the tool call is still streaming — i.e. its arguments are\n * arriving incrementally and no tool result has been paired in yet. Becomes\n * `false` once the tool result message lands and the renderer is invoked\n * with the full `response`. Always `false` for storage-opened artifacts.\n *\n * The same component instance is reused across the streaming → completed\n * transition, so renderers can rely on this flag to swap UI states (e.g.\n * show a skeleton or \"streaming…\" badge during partial args, then the final\n * view) without remounting.\n */\n isStreaming: boolean;\n /** Activates this renderer's detailed view. */\n open: () => void;\n /** Closes this renderer's detailed view if currently active. */\n close: () => void;\n /** Toggles this renderer's detailed view. */\n toggle: () => void;\n}\n\n/**\n * Result of a renderer's `parser`.\n *\n * - Returning `null` from `parser` skips rendering this tool call entirely.\n * - `meta: null` renders preview/actual but skips ThreadContext registration —\n * a common pattern while `ctx.isStreaming` is `true` so the entry only\n * appears in the registry once the tool result has arrived.\n *\n * @category Types\n */\nexport interface ParsedArtifact<Props> {\n props: Props;\n // `type`, when a parser provides it, is the artifact's REAL kind. It lets the\n // ThreadContext registration label/resolve the artifact by its own kind even\n // when a single tool-owning renderer matched the tool name (e.g. one renderer\n // owns the generate/edit tools but emits both presentations and reports).\n // Optional: parsers that don't set it fall back to the matched renderer's type.\n meta: { id: string; version: number; heading: string; type?: string } | null;\n}\n\n/**\n * Configuration for a single artifact renderer, returned by {@link defineArtifactRenderer}.\n *\n * Renderers are matched against tool calls by `toolName` (one or many literal\n * strings) and against stored artifacts by `type`. When a match fires, `parser`\n * converts the raw envelope into typed `Props` + an optional ThreadContext\n * `meta` entry, and `preview` / `actual` render the inline chat preview and\n * the full view respectively.\n *\n * @category Types\n */\nexport interface ArtifactRendererConfig<Props = unknown> {\n /**\n * Artifact type this renderer handles, e.g. `\"th_presentation\"`.\n * Links the renderer to {@link ArtifactCategory} filters and to stored\n * artifacts (`ArtifactSummary.type`) for thread-independent rendering.\n */\n type: string;\n /**\n * Tool name(s) to match. Literal strings only; first registration wins on\n * duplicates. An array registers the same renderer for several tools.\n */\n toolName: string | string[];\n /**\n * Converts the raw envelope into `{ props, meta }`.\n *\n * Tool-call path: receives `{ args, response }` exactly as the backend\n * emitted them — the SDK does not pre-parse JSON. Called on every update,\n * including during streaming, so implementations must tolerate:\n * - `args` as a *partial* JSON string (the LLM is still emitting it), and\n * - `response` as `null` (the tool result hasn't arrived yet — see\n * {@link ArtifactRendererControls.isStreaming}).\n *\n * Storage path (artifact browser): receives `{ args: undefined, response: artifact.content }` —\n * stored `content` must therefore have the same shape as the tool-call response.\n *\n * Return `null` to skip rendering. Return `meta: null` to render without\n * registering in the ThreadContext (entry hidden from workspace lists).\n * `meta.id` should be stable across re-runs of the same logical entry —\n * when `(id, version)` changes, the registry entry is re-registered.\n */\n parser: (\n raw: { args: unknown; response: unknown; id?: string },\n ctx: { isStreaming: boolean },\n ) => ParsedArtifact<Props> | null;\n /** Renders the inline preview shown in the chat message. */\n preview: (props: Props, controls: ArtifactRendererControls) => VNodeChild;\n /** Renders the full artifact view (side panel in-thread, full page in the artifact browser). */\n actual: (props: Props, controls: ArtifactRendererControls) => VNodeChild;\n /**\n * `false`: the side panel draws no header (title and close) around `actual`, for a renderer\n * that brings its own and closes with `controls.close`. Defaults to `true`.\n */\n panelHeader?: boolean;\n /**\n * Icon for this artifact type, used by the artifact nav for the category this\n * type belongs to. A platform-neutral node (a web element or a React Native\n * element). When a category groups several types, the nav uses the first\n * member type's icon; if none is set the UI falls back to a generic default.\n */\n icon?: VNodeChild;\n /**\n * Human-readable display label for this artifact type, shown as the type\n * metadata on artifact browser cards and workspace items (e.g. `\"Report\"`).\n * When omitted, the UI prettifies the `type` id (never shows the raw id).\n * Mirrors `icon` — declared via `defineArtifactRenderer({ label })`.\n */\n label?: string;\n}\n\n/**\n * Identity helper that returns its argument while preserving `Props` inference.\n *\n * Without this, users would have to write `const r: ArtifactRendererConfig<MyProps> = {...}`\n * to get type checking. With it, `defineArtifactRenderer({...})` infers `Props`\n * from `parser`'s return type.\n *\n * @category Functions\n *\n * @example\n * ```ts\n * const presentationRenderer = defineArtifactRenderer({\n * type: \"th_presentation\",\n * toolName: [\"presentation:create\", \"presentation:edit\"],\n * parser: ({ response }) => {\n * const slides = response as { id: string; slides: Slide[] } | null;\n * if (!slides) return null;\n * return {\n * props: slides,\n * meta: { id: slides.id, version: 1, heading: `Presentation ${slides.id}` },\n * };\n * },\n * preview: (props, controls) => <PresentationCard onOpen={controls.open} />,\n * actual: (props) => <SlideDeck slides={props.slides} />,\n * });\n * ```\n */\nexport function defineArtifactRenderer<Props>(\n config: ArtifactRendererConfig<Props>,\n): ArtifactRendererConfig<Props> {\n return config;\n}\n","/**\n * Builds the detailed-view id for an artifact version. This is the contract\n * between everything that opens artifact panels (auto-open watcher, workspace\n * rail) and the renderer that registers them — always build/read the id\n * through these helpers, never hand-roll the string.\n */\nexport function artifactViewId(id: string, version: number): string {\n return `${id}:${version}`;\n}\n\n/**\n * Splits a detailed-view id back into artifact id + version. Returns null\n * when the string isn't an artifact view id (e.g. a useId fallback).\n */\nexport function parseArtifactViewId(viewId: string): { id: string; version: number } | null {\n const sep = viewId.lastIndexOf(\":\");\n if (sep <= 0) return null;\n const versionPart = viewId.slice(sep + 1);\n if (!/^\\d+$/.test(versionPart)) return null;\n return { id: viewId.slice(0, sep), version: Number(versionPart) };\n}\n","import type { Thread } from \"../store/types\";\nimport type { Message, UserMessage } from \"../types/message\";\nimport type { ChatStorage } from \"./types\";\n\n/**\n * Internal default storage — in-memory, no persistence across reload.\n * Used by `<ChatProvider>` when no `storage` prop is provided. Not exported\n * from the package; callers who want explicit in-memory behavior should\n * construct their own adapter object.\n */\nexport function createDefaultInMemoryStorage(): ChatStorage {\n let threads: Thread[] = [];\n const messagesByThread = new Map<string, Message[]>();\n\n return {\n thread: {\n async listThreads() {\n return { threads };\n },\n async createThread(firstMessage: UserMessage) {\n const thread: Thread = {\n id: crypto.randomUUID(),\n title:\n typeof firstMessage.content === \"string\"\n ? firstMessage.content.slice(0, 40) || \"New thread\"\n : \"New thread\",\n createdAt: new Date().toISOString(),\n };\n threads = [thread, ...threads];\n messagesByThread.set(thread.id, [\n { ...firstMessage, id: firstMessage.id ?? crypto.randomUUID() },\n ]);\n return thread;\n },\n async getMessages(threadId: string) {\n return messagesByThread.get(threadId) ?? [];\n },\n async updateThread(thread: Thread) {\n threads = threads.map((t) => (t.id === thread.id ? thread : t));\n return thread;\n },\n async deleteThread(id: string) {\n threads = threads.filter((t) => t.id !== id);\n messagesByThread.delete(id);\n },\n },\n };\n}\n","import { onMounted, onUpdated, onScopeDispose, toValue, type MaybeRefOrGetter } from \"vue\";\nimport { artifactViewId } from \"./artifactViewId\";\nimport type { createChatStore } from \"./createChatStore\";\nimport type { createDetailedViewStore } from \"./createDetailedViewStore\";\nimport type { createThreadContextStore } from \"./createThreadContextStore\";\nimport type { ArtifactEntry } from \"./threadContextTypes\";\n\n/**\n * One pass over every artifact registered in the thread. Each artifact\n * version (`id:version`) gets a single chance to auto-open — recorded in\n * `claimedIds` the first time we see it, whether or not it opens — so an\n * edit's new version qualifies again. Returns true when a panel opened.\n */\nexport function evaluateRegisteredArtifacts(\n artifacts: Record<string, ArtifactEntry[]>, // all artifacts in the thread context: id → versions, ascending\n mayOpen: boolean, // \"is opening allowed right now\" — streaming and nothing opened yet this stream\n claimedIds: Set<string>, // \"id:version\" keys that already used their chance (cleared per thread)\n detailedViewStore: ReturnType<typeof createDetailedViewStore>,\n): boolean {\n let opened = false;\n // artifacts = {\n // \"report-abc\": [ {id:\"report-abc\", version:1, …}, {id:\"report-abc\", version:2, …} ],\n // \"deck-xyz\": [ {id:\"deck-xyz\", version:1, …} ],\n // }\n // artifactsWithVersions = [\n // [ {id:\"report-abc\", version:1, …}, {id:\"report-abc\", version:2, …} ],\n // [ {id:\"deck-xyz\", version:1, …} ],\n // ]\n const artifactsWithVersions = Object.values(artifacts);\n for (let i = 0; i < artifactsWithVersions.length; i++) {\n const versions = artifactsWithVersions[i];\n // versions = [ {id:\"report-abc\", version:1, …}, {id:\"report-abc\", version:2, …} ]\n // no list at this index (can't happen; strict TS guard)\n if (!versions) continue;\n // versions are sorted ascending, so the last entry is the newest one\n // latest = {id:\"report-abc\", version:2, …}\n const latest = versions[versions.length - 1];\n // no versions at all (can't happen in practice; keeps strict TS happy)\n if (!latest) continue;\n // claim keyed by id:version so an EDIT (new version, same id) gets a\n // fresh chance to open, while re-registrations of the same version are\n // ignored (a user's close sticks)\n const key = artifactViewId(latest.id, latest.version);\n if (claimedIds.has(key)) continue;\n claimedIds.add(key);\n // allowed to open right now? and only one open per pass\n if (!mayOpen || opened) continue;\n // takes over the panel even if it is already open: a new stream's first\n // artifact (or a streaming edit) re-points an open panel to itself\n detailedViewStore.getState().setActiveDetailedView(key);\n opened = true;\n }\n return opened;\n}\n\n/**\n * Runs inside ChatProvider: re-evaluates whenever an artifact registers in\n * the thread context, opening at most one artifact per stream.\n */\nexport function useArtifactAutoOpenWatcher(\n artifactAutoOpen: MaybeRefOrGetter<boolean>,\n chatStore: ReturnType<typeof createChatStore>,\n threadContextStore: ReturnType<typeof createThreadContextStore>,\n detailedViewStore: ReturnType<typeof createDetailedViewStore>,\n): void {\n // \"did this stream already auto-open something\" — re-armed on each new stream\n const openedThisRunRef = { current: false };\n // id:version keys that used their one auto-open chance — cleared on thread switch\n const claimedIdsRef = { current: new Set<string>() };\n\n let enabled: boolean | undefined;\n let cleanup: (() => void) | undefined;\n // This hook is internal to ChatProvider. Its input is a Provider prop,\n // so reconcile after the Provider commits, not in a post-flush watcher:\n // post watchers can precede child mounted/updated hooks. React's previous\n // passive effect remains installed through the child's layout commit.\n const reconcile = () => {\n const nextEnabled = toValue(artifactAutoOpen);\n if (nextEnabled === enabled) return;\n cleanup?.();\n cleanup = undefined;\n enabled = nextEnabled;\n if (!enabled) return;\n const unsubscribeThread = chatStore.subscribe(\n (s) => s.selectedThreadId,\n () => {\n claimedIdsRef.current.clear();\n openedThisRunRef.current = false;\n },\n );\n const unsubscribeRun = chatStore.subscribe(\n (s) => s.isRunning,\n (isRunning) => {\n if (isRunning) openedThisRunRef.current = false;\n },\n );\n const unsubscribeArtifacts = threadContextStore.subscribe(\n (s) => s.artifacts,\n (artifacts) => {\n const mayOpen = chatStore.getState().isRunning && !openedThisRunRef.current;\n if (\n evaluateRegisteredArtifacts(artifacts, mayOpen, claimedIdsRef.current, detailedViewStore)\n ) {\n openedThisRunRef.current = true;\n }\n },\n // also evaluate artifacts that registered before this watcher mounted\n { fireImmediately: true },\n );\n cleanup = () => {\n unsubscribeThread();\n unsubscribeRun();\n unsubscribeArtifacts();\n };\n };\n onMounted(reconcile);\n onUpdated(reconcile);\n onScopeDispose(() => cleanup?.());\n}\n","export async function getResponseErrorMessage(response: Response): Promise<string> {\n try {\n const data = (await response.clone().json()) as {\n error?: { message?: unknown } | string;\n message?: unknown;\n };\n const message =\n typeof data.error === \"string\"\n ? data.error\n : typeof data.error?.message === \"string\"\n ? data.error.message\n : typeof data.message === \"string\"\n ? data.message\n : null;\n\n if (message?.trim()) return message;\n } catch {\n // Fall through to the status-based message.\n }\n\n return `Request failed: ${response.status} ${response.statusText}`.trim();\n}\n","import type { Message } from \"./message\";\n\n/**\n * Converts messages between AG-UI format (used internally) and the\n * format your backend / storage layer expects.\n *\n * Both methods operate on **arrays** so that formats where a single\n * AG-UI message maps to multiple backend items (e.g. OpenAI Responses\n * API) work seamlessly alongside 1-to-1 formats (e.g. Completions).\n *\n * @example\n * // Identity (default) — no conversion\n * const identity: MessageFormat = {\n * toApi: (messages) => messages,\n * fromApi: (data) => data as Message[],\n * };\n */\nexport interface MessageFormat {\n /** Convert AG-UI messages to the format your backend expects (outbound). */\n toApi(messages: Message[]): unknown;\n /** Convert messages from your backend/storage format to AG-UI (inbound). */\n fromApi(data: unknown): Message[];\n}\n\n/**\n * Default identity message format — no conversion.\n * Messages are sent and received as-is in AG-UI format.\n */\nexport const identityMessageFormat: MessageFormat = {\n toApi: (messages) => messages,\n fromApi: (data) => data as Message[],\n};\n","/**\n * Shared line iterator for streamed HTTP responses.\n *\n * Buffers the leftover partial line between network chunks so an SSE event (or\n * NDJSON record) split across two `reader.read()` results is reassembled rather\n * than silently dropped. The reference implementation lived in\n * `openai-readable-stream.ts`; this extracts it so `ag-ui.ts` and\n * `openai-completions.ts` share the same correct buffering.\n *\n * Yields each complete line verbatim (caller strips any `data: ` SSE prefix);\n * blank lines are skipped. The trailing buffered line is flushed on stream end.\n *\n * @internal\n */\nexport async function* sseLineIterator(response: Response): AsyncGenerator<string> {\n const reader = response.body?.getReader();\n if (!reader) throw new Error(\"No response body\");\n\n const decoder = new TextDecoder();\n let buffer = \"\";\n\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split(\"\\n\");\n // Keep the straddling partial line (everything after the last \"\\n\") for the\n // next chunk; it may be completed by the bytes that follow.\n buffer = lines.pop() ?? \"\";\n\n for (const line of lines) {\n if (line.trim()) yield line;\n }\n }\n\n // Flush the tail — a stream that ends without a trailing newline still has a\n // complete final line sitting in the buffer.\n if (buffer.trim()) yield buffer;\n}\n","import { AGUIEvent, StreamProtocolAdapter } from \"../../types\";\nimport { sseLineIterator } from \"./_shared/sseLines\";\n\nexport const agUIAdapter = (): StreamProtocolAdapter => ({\n async *parse(response: Response): AsyncIterable<AGUIEvent> {\n for await (const line of sseLineIterator(response)) {\n if (!line.startsWith(\"data: \")) continue;\n const data = line.slice(6).trim();\n if (!data || data === \"[DONE]\") continue;\n\n try {\n const event = JSON.parse(data);\n yield event as AGUIEvent;\n } catch (e) {\n console.error(\"Failed to parse SSE event\", e);\n }\n }\n },\n});\n","import type { HandleMessageStreamEvent } from \"eve/client\";\nimport { AGUIEvent, EventType, StreamProtocolAdapter } from \"../../types\";\nimport { sseLineIterator } from \"./_shared/sseLines\";\n\nexport type {\n InputOption as EveInputOption,\n InputRequest as EveInputRequest,\n HandleMessageStreamEvent as EveStreamEvent,\n} from \"eve/client\";\n\n/**\n * Options for the Eve adapter.\n */\nexport interface EveAdapterOptions {\n /** Called with every raw Eve event before translation (including unmapped types). */\n onEvent?: (event: HandleMessageStreamEvent) => void;\n}\n\nexport const EVE_INPUT_REQUESTED_EVENT = \"eve.input.requested\";\n\nconst TURN_BOUNDARY_TYPES = new Set([\"session.completed\", \"session.failed\", \"session.waiting\"]);\n\n/**\n * Adapter for Eve session streams (`GET /eve/v1/session/:id/stream`).\n *\n * Eve emits newline-delimited JSON harness events. The adapter handles\n * `actions.requested`, `action.result`, `message.appended`, `message.completed`,\n * `input.requested`, `turn.failed`, and `session.failed` and maps tool calls,\n * assistant text, input prompts, and failures to AG-UI events. Parsing stops at\n * turn boundaries (`session.completed`, `session.waiting`, `session.failed`).\n * Pass `onEvent` for unmapped events such as `session.started`.\n */\nexport const eveAdapter = (options: EveAdapterOptions = {}): StreamProtocolAdapter => ({\n async *parse(response: Response): AsyncIterable<AGUIEvent> {\n const messageId = crypto.randomUUID();\n const streamedSteps = new Set<number>();\n let started = false;\n\n const start = (): AGUIEvent[] => {\n if (started) return [];\n started = true;\n return [{ type: EventType.TEXT_MESSAGE_START, messageId, role: \"assistant\" }];\n };\n\n for await (const line of sseLineIterator(response)) {\n let event: HandleMessageStreamEvent;\n try {\n event = JSON.parse(line) as HandleMessageStreamEvent;\n } catch (e) {\n console.error(\"Failed to parse Eve stream event\", e);\n continue;\n }\n options.onEvent?.(event);\n\n if (event.type === \"actions.requested\") {\n for (const action of event.data.actions) {\n if (action.kind !== \"tool-call\") continue;\n yield* start();\n yield {\n type: EventType.TOOL_CALL_START,\n toolCallId: action.callId,\n toolCallName: action.toolName,\n parentMessageId: messageId,\n };\n const args = JSON.stringify(action.input ?? {});\n if (args && args !== \"{}\") {\n yield { type: EventType.TOOL_CALL_ARGS, toolCallId: action.callId, delta: args };\n }\n yield { type: EventType.TOOL_CALL_END, toolCallId: action.callId };\n }\n } else if (event.type === \"action.result\") {\n const { result, status, error } = event.data;\n if (result.kind !== \"tool-result\") continue;\n const content =\n status === \"completed\"\n ? typeof result.output === \"string\"\n ? result.output\n : JSON.stringify(result.output ?? null)\n : JSON.stringify({ error: error?.message ?? `tool ${status}` });\n yield {\n type: EventType.TOOL_CALL_RESULT,\n messageId: crypto.randomUUID(),\n toolCallId: result.callId,\n content,\n role: \"tool\",\n };\n } else if (event.type === \"message.appended\") {\n const { messageDelta, stepIndex } = event.data;\n if (!messageDelta) continue;\n streamedSteps.add(stepIndex);\n yield* start();\n yield { type: EventType.TEXT_MESSAGE_CONTENT, messageId, delta: messageDelta };\n } else if (event.type === \"message.completed\") {\n const { message, stepIndex } = event.data;\n if (!message || streamedSteps.has(stepIndex)) continue;\n yield* start();\n yield { type: EventType.TEXT_MESSAGE_CONTENT, messageId, delta: message };\n } else if (event.type === \"input.requested\") {\n yield {\n type: EventType.CUSTOM,\n name: EVE_INPUT_REQUESTED_EVENT,\n value: event.data.requests,\n };\n } else if (event.type === \"turn.failed\" || event.type === \"session.failed\") {\n yield { type: EventType.RUN_ERROR, message: event.data.message };\n }\n\n if (TURN_BOUNDARY_TYPES.has(event.type)) break;\n }\n\n if (started) yield { type: EventType.TEXT_MESSAGE_END, messageId };\n },\n});\n","import { AGUIEvent, EventType, StreamProtocolAdapter } from \"../../types\";\n\ntype LangGraphContent = string | Array<{ type: string; text?: string }>;\n\n/** LangGraph AI message (or chunk) received in `messages` stream mode. */\ninterface LangGraphAIMessage {\n id?: string;\n type: \"ai\" | \"AIMessageChunk\" | \"AIMessage\";\n content: LangGraphContent;\n tool_calls?: Array<{\n id: string;\n name: string;\n args: Record<string, unknown> | string;\n }>;\n tool_call_chunks?: Array<{\n id?: string;\n name?: string;\n args?: string;\n index?: number;\n }>;\n}\n\n/** LangGraph tool result (or chunk) received between model invocations. */\ninterface LangGraphToolMessage {\n id?: string;\n type: \"tool\" | \"ToolMessage\" | \"ToolMessageChunk\";\n content: LangGraphContent;\n tool_call_id: string;\n status?: \"success\" | \"error\";\n}\n\ntype LangGraphMessage = LangGraphAIMessage | LangGraphToolMessage;\n\n/**\n * Metadata attached to each message tuple in the `messages` stream mode.\n */\ninterface LangGraphMessageMetadata {\n langgraph_node?: string;\n langgraph_step?: number;\n langgraph_triggers?: string[];\n langgraph_checkpoint_ns?: string;\n tags?: string[];\n ls_model_name?: string;\n}\n\n/**\n * Options for the LangGraph adapter.\n */\nexport interface LangGraphAdapterOptions {\n /**\n * Called when a LangGraph interrupt is encountered in an `updates` event.\n * The interrupt payload is the value of the `__interrupt__` key.\n */\n onInterrupt?: (interrupt: unknown) => void;\n}\n\n/**\n * Adapter for LangGraph streaming responses.\n *\n * LangGraph uses named SSE events (`event: <type>\\ndata: <json>\\n\\n`)\n * rather than the `data:`-only format used by OpenAI. The adapter handles\n * the `messages`, `metadata`, `updates`, and `error` event types and maps\n * model steps and tool results to ordered AG-UI events.\n *\n * Usage:\n * ```tsx\n * <ChatProvider\n * apiUrl=\"/api/langgraph\"\n * streamProtocol={langGraphAdapter()}\n * />\n * ```\n */\nexport const langGraphAdapter = (options?: LangGraphAdapterOptions): StreamProtocolAdapter => ({\n async *parse(response: Response): AsyncIterable<AGUIEvent> {\n const reader = response.body?.getReader();\n if (!reader) throw new Error(\"No response body\");\n\n const decoder = new TextDecoder();\n let fallbackMessageId = crypto.randomUUID();\n let currentMessageId: string | null = null;\n let currentGraphStep: number | undefined;\n const toolCallIdsByIndex = new Map<number, string>();\n const startedToolCallIds = new Set<string>();\n const openToolCallIds = new Set<string>();\n const toolCallArgsSeen = new Set<string>();\n // Every id already spent on an assistant segment, so a repeated wire id can\n // be given a distinct one (see the segment-opening branch below).\n const usedMessageIds = new Set<string>();\n let duplicateMessageIds = 0;\n let messageStarted = false;\n let sawToolsOnCurrentMessage = false;\n let buffer = \"\";\n\n while (true) {\n const { done, value } = await reader.read();\n\n // Accumulate across reads: an SSE event block (e.g. a multi-KB artifact\n // function_call_arguments payload) can span several network reads. Hold the\n // trailing partial block until the next read; on done, flush what remains\n // (the old early `if (done) break` dropped the final un-terminated block).\n buffer += done ? decoder.decode() : decoder.decode(value, { stream: true });\n\n // SSE events are separated by double newlines; keep the last (possibly\n // incomplete) block in the buffer until more arrives.\n const blocks = buffer.split(\"\\n\\n\");\n buffer = done ? \"\" : (blocks.pop() ?? \"\");\n\n for (const block of blocks) {\n const trimmed = block.trim();\n if (!trimmed) continue;\n\n const { event, data } = parseSSEBlock(trimmed);\n if (!data) continue;\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(data);\n } catch (e) {\n console.error(\"Failed to parse LangGraph SSE data\", e);\n continue;\n }\n\n switch (event) {\n case \"metadata\": {\n // Metadata event signals the run has started.\n // Payload: { run_id: string, thread_id: string }\n // We don't emit RUN_STARTED because processStreamedMessage\n // doesn't handle it — it's informational only.\n break;\n }\n\n case \"messages\": {\n // Payload is a tuple: [message_chunk, metadata]\n // or just a message object depending on the stream version.\n const tuple = parsed as [LangGraphMessage, LangGraphMessageMetadata] | LangGraphMessage;\n const msg = Array.isArray(tuple) ? tuple[0] : tuple;\n const metadata = Array.isArray(tuple) ? tuple[1] : undefined;\n\n if (isToolMessage(msg)) {\n // A ToolMessage marks the end of the model step that requested\n // the tool. Close both the call and assistant segment before\n // emitting its result so live history remains ai → tool → ai.\n if (openToolCallIds.delete(msg.tool_call_id)) {\n yield {\n type: EventType.TOOL_CALL_END,\n toolCallId: msg.tool_call_id,\n };\n }\n if (messageStarted && currentMessageId) {\n yield {\n type: EventType.TEXT_MESSAGE_END,\n messageId: currentMessageId,\n };\n }\n messageStarted = false;\n currentMessageId = null;\n sawToolsOnCurrentMessage = false;\n currentGraphStep = undefined;\n fallbackMessageId = crypto.randomUUID();\n toolCallIdsByIndex.clear();\n\n const content = serializeToolContent(msg.content);\n yield {\n type: EventType.TOOL_CALL_RESULT,\n messageId: msg.id ?? `tool-result-${msg.tool_call_id}`,\n toolCallId: msg.tool_call_id,\n content,\n role: \"tool\",\n ...(msg.status === \"error\" ? { isError: true, error: content } : {}),\n } as AGUIEvent;\n break;\n }\n\n if (!isAIMessage(msg)) break;\n\n const graphStep = metadata?.langgraph_step;\n const graphStepChanged =\n graphStep !== undefined &&\n currentGraphStep !== undefined &&\n graphStep !== currentGraphStep;\n let nextMessageId =\n msg.id ??\n (graphStep === undefined ? fallbackMessageId : `langgraph-step-${graphStep}`);\n\n const textContent = extractTextContent(msg.content);\n // Text after tool calls is a new assistant item so commentary like\n // \"Let me do this\" stays on the tool-bearing message and the answer\n // text after it is not concatenated onto the same message.\n const splitAfterTools = !!textContent && sawToolsOnCurrentMessage && messageStarted;\n\n const isNewModelStep =\n !messageStarted ||\n nextMessageId !== currentMessageId ||\n graphStepChanged ||\n splitAfterTools;\n\n // LangGraph repeats a wire id across segment boundaries — both when\n // the graph step advances and after a tool call — so an id already\n // spent on a closed segment needs a fresh one for consumers to keep\n // both. Only when opening a segment: mid-message chunks must keep\n // streaming into currentMessageId.\n if (isNewModelStep && usedMessageIds.has(nextMessageId)) {\n nextMessageId = `${nextMessageId}#${++duplicateMessageIds}`;\n }\n\n if (isNewModelStep) {\n if (messageStarted && currentMessageId) {\n yield {\n type: EventType.TEXT_MESSAGE_END,\n messageId: currentMessageId,\n };\n }\n currentMessageId = nextMessageId;\n usedMessageIds.add(nextMessageId);\n currentGraphStep = graphStep;\n sawToolsOnCurrentMessage = false;\n toolCallIdsByIndex.clear();\n yield {\n type: EventType.TEXT_MESSAGE_START,\n messageId: currentMessageId,\n role: \"assistant\",\n };\n messageStarted = true;\n }\n\n if (textContent) {\n yield {\n type: EventType.TEXT_MESSAGE_CONTENT,\n messageId: currentMessageId!,\n delta: textContent,\n };\n }\n\n // Handle streaming tool call chunks (partial arguments)\n if (msg.tool_call_chunks) {\n for (const chunk of msg.tool_call_chunks) {\n const index = chunk.index ?? 0;\n\n if (chunk.id) toolCallIdsByIndex.set(index, chunk.id);\n const toolCallId = chunk.id ?? toolCallIdsByIndex.get(index);\n\n if (toolCallId && !startedToolCallIds.has(toolCallId)) {\n startedToolCallIds.add(toolCallId);\n openToolCallIds.add(toolCallId);\n sawToolsOnCurrentMessage = true;\n yield {\n type: EventType.TOOL_CALL_START,\n toolCallId,\n toolCallName: chunk.name || \"\",\n };\n }\n\n if (chunk.args && toolCallId) {\n toolCallArgsSeen.add(toolCallId);\n yield {\n type: EventType.TOOL_CALL_ARGS,\n toolCallId,\n delta: chunk.args,\n };\n }\n }\n }\n\n // Handle complete tool calls only for non-streaming messages.\n // LangChain chunks can also carry a provisional tool_calls\n // projection (often with args: {}). tool_call_chunks is the\n // authoritative source whenever that field is present.\n if (msg.tool_call_chunks === undefined && msg.tool_calls && msg.tool_calls.length > 0) {\n for (let i = 0; i < msg.tool_calls.length; i++) {\n const tc = msg.tool_calls[i];\n if (!tc) continue;\n\n const toolCallId = tc.id || crypto.randomUUID();\n\n if (!startedToolCallIds.has(toolCallId)) {\n startedToolCallIds.add(toolCallId);\n openToolCallIds.add(toolCallId);\n sawToolsOnCurrentMessage = true;\n yield {\n type: EventType.TOOL_CALL_START,\n toolCallId,\n toolCallName: tc.name,\n };\n }\n\n if (!toolCallArgsSeen.has(toolCallId)) {\n const argsStr = typeof tc.args === \"string\" ? tc.args : JSON.stringify(tc.args);\n toolCallArgsSeen.add(toolCallId);\n yield {\n type: EventType.TOOL_CALL_ARGS,\n toolCallId,\n delta: argsStr,\n };\n }\n\n if (openToolCallIds.delete(toolCallId)) {\n yield {\n type: EventType.TOOL_CALL_END,\n toolCallId,\n };\n }\n }\n }\n\n break;\n }\n\n case \"updates\": {\n // Payload: { [node_name]: node_output }\n // Check for interrupts\n const updates = parsed as Record<string, unknown>;\n if (\"__interrupt__\" in updates && options?.onInterrupt) {\n options.onInterrupt(updates[\"__interrupt__\"]);\n }\n break;\n }\n\n case \"error\": {\n // Payload: { error: string, message: string }\n const err = parsed as { error?: string; message?: string };\n yield {\n type: EventType.RUN_ERROR,\n message: err.message || err.error || \"Unknown error\",\n code: err.error ?? undefined,\n };\n break;\n }\n\n case \"end\": {\n // Stream has ended — close out any open message/tool calls.\n if (messageStarted) {\n // End any open streaming tool calls\n for (const toolCallId of openToolCallIds) {\n yield {\n type: EventType.TOOL_CALL_END,\n toolCallId,\n };\n }\n openToolCallIds.clear();\n\n yield {\n type: EventType.TEXT_MESSAGE_END,\n messageId: currentMessageId!,\n };\n messageStarted = false; // Prevent duplicate end in fallback\n }\n break;\n }\n\n // Intentionally unhandled: values, debug, tasks, checkpoints, custom\n default:\n break;\n }\n }\n\n if (done) break;\n }\n\n // If stream ended without an explicit \"end\" event, close out.\n if (messageStarted) {\n for (const toolCallId of openToolCallIds) {\n yield {\n type: EventType.TOOL_CALL_END,\n toolCallId,\n };\n }\n openToolCallIds.clear();\n yield {\n type: EventType.TEXT_MESSAGE_END,\n messageId: currentMessageId!,\n };\n }\n },\n});\n\n/**\n * Parse an SSE block into its event name and data payload.\n *\n * LangGraph SSE format:\n * ```\n * event: messages\n * data: [{\"content\": \"Hello\", ...}, {\"langgraph_node\": \"agent\"}]\n * ```\n */\nfunction parseSSEBlock(block: string): { event: string; data: string } {\n let event = \"\";\n const dataLines: string[] = [];\n\n for (const line of block.split(\"\\n\")) {\n if (line.startsWith(\"event:\")) {\n event = line.slice(6).trim();\n } else if (line.startsWith(\"data:\")) {\n dataLines.push(line.slice(5).trim());\n }\n // Ignore id:, retry:, and comment lines\n }\n\n return { event, data: dataLines.join(\"\\n\") };\n}\n\n/**\n * Extract text content from a LangGraph message content field.\n * Content can be a plain string or an array of typed content blocks.\n */\nfunction extractTextContent(content: string | Array<{ type: string; text?: string }>): string {\n if (typeof content === \"string\") return content;\n\n return content\n .filter((block) => block.type === \"text\" && block.text)\n .map((block) => block.text!)\n .join(\"\");\n}\n\nfunction serializeToolContent(content: LangGraphContent): string {\n return typeof content === \"string\" ? content : JSON.stringify(content);\n}\n\nfunction isAIMessage(message: LangGraphMessage): message is LangGraphAIMessage {\n return message.type === \"ai\" || message.type === \"AIMessage\" || message.type === \"AIMessageChunk\";\n}\n\nfunction isToolMessage(message: LangGraphMessage): message is LangGraphToolMessage {\n return (\n message.type === \"tool\" || message.type === \"ToolMessage\" || message.type === \"ToolMessageChunk\"\n );\n}\n","import type { ChatCompletionChunk } from \"openai/resources/chat/completions\";\nimport { AGUIEvent, EventType, StreamProtocolAdapter } from \"../../types\";\nimport { sseLineIterator } from \"./_shared/sseLines\";\n\nexport const openAIAdapter = (): StreamProtocolAdapter => ({\n async *parse(response: Response): AsyncIterable<AGUIEvent> {\n const messageId = crypto.randomUUID();\n const toolCallIds: Record<number, string> = {};\n let messageStarted = false;\n\n for await (const line of sseLineIterator(response)) {\n if (!line.startsWith(\"data: \")) continue;\n const data = line.slice(6).trim();\n if (!data || data === \"[DONE]\") continue;\n\n try {\n const json = JSON.parse(data) as ChatCompletionChunk;\n const choice = json.choices?.[0];\n const delta = choice?.delta;\n\n if (!delta) continue;\n\n // Emit TEXT_MESSAGE_START on first meaningful delta\n if (!messageStarted && (delta.content || delta.role)) {\n yield {\n type: EventType.TEXT_MESSAGE_START,\n messageId,\n role: \"assistant\",\n };\n messageStarted = true;\n }\n\n if (delta.content) {\n yield {\n type: EventType.TEXT_MESSAGE_CONTENT,\n messageId,\n delta: delta.content,\n };\n }\n\n if (delta.tool_calls) {\n for (const toolCall of delta.tool_calls) {\n const index = toolCall.index;\n\n if (toolCall.id) {\n toolCallIds[index] = toolCall.id;\n yield {\n type: EventType.TOOL_CALL_START,\n toolCallId: toolCall.id,\n toolCallName: toolCall.function?.name || \"\",\n };\n }\n\n if (toolCall.function?.arguments) {\n const toolCallId = toolCallIds[index];\n if (toolCallId) {\n yield {\n type: EventType.TOOL_CALL_ARGS,\n toolCallId,\n delta: toolCall.function.arguments,\n };\n }\n }\n }\n }\n\n // Emit end events based on finish_reason\n if (choice?.finish_reason === \"stop\") {\n yield {\n type: EventType.TEXT_MESSAGE_END,\n messageId,\n };\n } else if (choice?.finish_reason === \"tool_calls\") {\n for (const toolCallId of Object.values(toolCallIds)) {\n yield {\n type: EventType.TOOL_CALL_END,\n toolCallId,\n };\n }\n }\n } catch (e) {\n console.error(\"Failed to parse OpenAI SSE event\", e);\n }\n }\n },\n});\n","import type { ChatCompletionChunk } from \"openai/resources/chat/completions\";\nimport { AGUIEvent, EventType, StreamProtocolAdapter } from \"../../types\";\nimport { sseLineIterator } from \"./_shared/sseLines\";\n\n/**\n * Adapter for streams produced by the OpenAI SDK's `Stream.toReadableStream()`.\n * That method emits NDJSON (one JSON object per line, no `data: ` SSE prefix),\n * which differs from the raw SSE format that `openAIAdapter` expects.\n */\nexport const openAIReadableStreamAdapter = (): StreamProtocolAdapter => ({\n async *parse(response: Response): AsyncIterable<AGUIEvent> {\n const messageId = crypto.randomUUID();\n const toolCallIds: Record<number, string> = {};\n let messageStarted = false;\n\n for await (const line of sseLineIterator(response)) {\n const data = line.trim();\n if (!data) continue;\n\n try {\n const json = JSON.parse(data) as ChatCompletionChunk;\n const choice = json.choices?.[0];\n const delta = choice?.delta;\n\n if (!delta) continue;\n\n if (!messageStarted && (delta.content || delta.role)) {\n yield {\n type: EventType.TEXT_MESSAGE_START,\n messageId,\n role: \"assistant\",\n };\n messageStarted = true;\n }\n\n if (delta.content) {\n yield {\n type: EventType.TEXT_MESSAGE_CONTENT,\n messageId,\n delta: delta.content,\n };\n }\n\n if (delta.tool_calls) {\n for (const toolCall of delta.tool_calls) {\n const index = toolCall.index;\n\n if (toolCall.id) {\n toolCallIds[index] = toolCall.id;\n yield {\n type: EventType.TOOL_CALL_START,\n toolCallId: toolCall.id,\n toolCallName: toolCall.function?.name || \"\",\n };\n }\n\n if (toolCall.function?.arguments) {\n const toolCallId = toolCallIds[index];\n if (toolCallId) {\n yield {\n type: EventType.TOOL_CALL_ARGS,\n toolCallId,\n delta: toolCall.function.arguments,\n };\n }\n }\n }\n }\n\n if (choice?.finish_reason === \"stop\") {\n yield {\n type: EventType.TEXT_MESSAGE_END,\n messageId,\n };\n } else if (choice?.finish_reason === \"tool_calls\") {\n for (const toolCallId of Object.values(toolCallIds)) {\n yield {\n type: EventType.TOOL_CALL_END,\n toolCallId,\n };\n }\n }\n } catch (e) {\n console.error(\"Failed to parse OpenAI NDJSON chunk\", e);\n }\n }\n },\n});\n","import type {\n ResponseFunctionToolCallOutputItem,\n ResponseStreamEvent,\n} from \"openai/resources/responses/responses\";\nimport { AGUIEvent, EventType, StreamProtocolAdapter } from \"../../types\";\n\n/** A tool result's `output` as a string (JSON-encoded if structured, \"\" if absent). */\nconst stringifyOutput = (output: unknown): string =>\n typeof output === \"string\" ? output : output != null ? JSON.stringify(output) : \"\";\n\nexport const openAIResponsesAdapter = (): StreamProtocolAdapter => ({\n async *parse(response: Response): AsyncIterable<AGUIEvent> {\n const reader = response.body?.getReader();\n if (!reader) throw new Error(\"No response body\");\n\n const decoder = new TextDecoder();\n // Map item_id → call_id so TOOL_CALL_ARGS can reference the correct toolCallId\n const itemIdToCallId: Record<string, string> = {};\n // The text output-item currently streaming.\n let textItemId: string | null = null;\n\n let buffer = \"\";\n while (true) {\n const { done, value } = await reader.read();\n // Accumulate across reads: a single SSE `data:` line (e.g. a multi-KB\n // artifact function_call_output payload) can span several network\n // chunks. Splitting each chunk independently tears that line in two and\n // drops it on JSON.parse. Hold the trailing partial line until the next\n // read; on done, flush whatever remains.\n buffer += done ? decoder.decode() : decoder.decode(value, { stream: true });\n const lines = buffer.split(\"\\n\");\n buffer = done ? \"\" : (lines.pop() ?? \"\");\n\n for (const line of lines) {\n if (!line.startsWith(\"data: \")) continue;\n const data = line.slice(6).trim();\n if (!data || data === \"[DONE]\") continue;\n\n try {\n const event = JSON.parse(data) as ResponseStreamEvent;\n\n switch (event.type) {\n case \"response.output_item.added\": {\n // OpenAI's Conversations API surfaces function_call_output as an\n // output item even though the SDK's ResponseOutputItem union does\n // not declare it. Widen the type so we can branch on it below.\n const item = event.item as typeof event.item | ResponseFunctionToolCallOutputItem;\n if (item.type === \"message\" && item.role === \"assistant\") {\n textItemId = item.id;\n yield {\n type: EventType.TEXT_MESSAGE_START,\n messageId: item.id,\n role: \"assistant\",\n };\n } else if (item.type === \"function_call\") {\n // Store the mapping so we can resolve it in arguments.delta\n itemIdToCallId[item.id ?? item.call_id] = item.call_id;\n yield {\n type: EventType.TOOL_CALL_START,\n toolCallId: item.call_id,\n toolCallName: item.name,\n };\n } else if (item.type === \"function_call_output\") {\n yield {\n type: EventType.TOOL_CALL_RESULT,\n messageId: item.id,\n toolCallId: item.call_id,\n content: stringifyOutput(item.output),\n };\n } else if (item.type === \"web_search_call\") {\n yield {\n type: EventType.TOOL_CALL_START,\n toolCallId: item.id,\n toolCallName: \"web_search\",\n };\n } else if (item.type === \"mcp_call\") {\n yield {\n type: EventType.TOOL_CALL_START,\n toolCallId: item.id,\n toolCallName: item.name,\n };\n } else if (item.type === \"mcp_list_tools\") {\n yield {\n type: EventType.TOOL_CALL_START,\n toolCallId: item.id,\n toolCallName: \"mcp_list_tools\",\n };\n yield {\n type: EventType.TOOL_CALL_ARGS,\n toolCallId: item.id,\n delta: JSON.stringify({ server_label: item.server_label }),\n };\n yield {\n type: EventType.TOOL_CALL_END,\n toolCallId: item.id,\n };\n }\n break;\n }\n\n case \"response.output_text.delta\":\n // A delta for a not-yet-seen item id opens its message — covers\n // backends that switch item id on the delta without a preceding\n // `output_item.added` (idempotent when that event did fire).\n if (event.item_id !== textItemId) {\n textItemId = event.item_id;\n yield {\n type: EventType.TEXT_MESSAGE_START,\n messageId: event.item_id,\n role: \"assistant\",\n };\n }\n yield {\n type: EventType.TEXT_MESSAGE_CONTENT,\n messageId: event.item_id,\n delta: event.delta,\n };\n break;\n\n case \"response.output_text.done\":\n yield {\n type: EventType.TEXT_MESSAGE_END,\n messageId: event.item_id,\n };\n break;\n\n case \"response.function_call_arguments.delta\": {\n const callId = itemIdToCallId[event.item_id] ?? event.item_id;\n yield {\n type: EventType.TOOL_CALL_ARGS,\n toolCallId: callId,\n delta: event.delta,\n };\n break;\n }\n\n case \"response.function_call_arguments.done\": {\n const callId = itemIdToCallId[event.item_id] ?? event.item_id;\n yield {\n type: EventType.TOOL_CALL_END,\n toolCallId: callId,\n };\n break;\n }\n\n case \"response.mcp_call_arguments.delta\":\n yield {\n type: EventType.TOOL_CALL_ARGS,\n toolCallId: event.item_id,\n delta: event.delta,\n };\n break;\n\n case \"response.mcp_call_arguments.done\":\n yield {\n type: EventType.TOOL_CALL_END,\n toolCallId: event.item_id,\n };\n break;\n\n case \"response.output_item.done\": {\n // Server-executed tools deliver their result on the done item —\n // there's no function_call_output for them: mcp_call carries\n // output/error, web_search carries output/action. Every other item\n // type closes via its own event (function_call →\n // function_call_arguments.done, message → output_text.done).\n if (event.item.type === \"mcp_call\") {\n const mcp = event.item;\n const errorText =\n typeof mcp.error === \"string\" && mcp.error.length > 0 ? mcp.error : undefined;\n yield {\n type: EventType.TOOL_CALL_RESULT,\n messageId: mcp.id,\n toolCallId: mcp.id,\n content: stringifyOutput(mcp.output),\n ...(errorText ? { isError: true, error: errorText } : {}),\n };\n break;\n }\n\n if (event.item.type === \"mcp_list_tools\") {\n const list = event.item;\n // Summarize to names only\n const toolNames = list.tools.map((t) => t.name);\n const listError =\n typeof list.error === \"string\" && list.error.length > 0 ? list.error : undefined;\n yield {\n type: EventType.TOOL_CALL_RESULT,\n messageId: list.id,\n toolCallId: list.id,\n content: JSON.stringify({\n server_label: list.server_label,\n tool_count: toolNames.length,\n tools: toolNames,\n }),\n ...(listError ? { isError: true, error: listError } : {}),\n };\n break;\n }\n\n const item = event.item as {\n type?: string;\n id?: string;\n status?: string;\n output?: unknown;\n error?: unknown;\n action?: unknown;\n };\n if (item.type !== \"web_search_call\") break;\n\n const toolCallId = item.id ?? \"web_search_call\";\n\n // web_search streams no argument deltas — its query lives in\n // `action`. Surface it as the tool-call args so the card shows the\n // query live, matching a reload's persisted function_call args.\n if (item.action && typeof item.action === \"object\") {\n yield {\n type: EventType.TOOL_CALL_ARGS,\n toolCallId,\n delta: JSON.stringify(item.action),\n };\n }\n\n const content = stringifyOutput(item.output);\n yield {\n type: EventType.TOOL_CALL_RESULT,\n messageId: toolCallId,\n toolCallId,\n content,\n };\n break;\n }\n\n case \"error\":\n yield {\n type: EventType.RUN_ERROR,\n message: event.message,\n code: event.code ?? undefined,\n };\n break;\n\n case \"response.failed\":\n yield {\n type: EventType.RUN_ERROR,\n message: event.response?.error?.message ?? \"Response failed\",\n code: event.response?.error?.code ?? undefined,\n };\n break;\n\n // Intentionally unhandled — these are lifecycle/metadata events:\n // response.created, response.in_progress, response.completed,\n // response.content_part.added, response.content_part.done,\n // web_search's *.in_progress/searching/completed status events,\n // response.mcp_call.in_progress/.completed/.failed and\n // response.mcp_list_tools.* (the respective output_item.added/.done\n // handling above covers all three), and the mcp_approval_request\n // output item (HITL approval flow — no tray), etc.\n default:\n break;\n }\n } catch (e) {\n console.error(\"Failed to parse OpenAI Responses SSE event\", e);\n }\n }\n if (done) break;\n }\n },\n});\n","import type { UIMessage, UIMessageChunk } from \"ai\";\nimport { AGUIEvent, EventType, StreamProtocolAdapter } from \"../../types\";\n\nconst MISSING_AI_SDK_MESSAGE =\n 'vercelAIAdapter requires the optional peer dependency \"ai\" (Vercel AI SDK v6 or v7).';\nconst PROVIDER_EXECUTED_TOOLS_UNSUPPORTED_MESSAGE =\n \"Vercel AI SDK provider-executed tools are not supported because AG-UI messages cannot preserve providerExecuted semantics.\";\nconst TOOL_EXECUTION_DENIED_MESSAGE = \"Tool execution was denied\";\n\nfunction serialize(value: unknown): string {\n if (typeof value === \"string\") return value;\n return JSON.stringify(value) ?? String(value);\n}\n\nasync function parseUIMessageStream(\n body: ReadableStream<Uint8Array>,\n): Promise<ReadableStream<UIMessageChunk>> {\n let DefaultChatTransport: typeof import(\"ai\").DefaultChatTransport;\n\n try {\n ({ DefaultChatTransport } = await import(\"ai\"));\n } catch (cause) {\n throw new Error(MISSING_AI_SDK_MESSAGE, { cause });\n }\n\n // Some bundlers replace a missing optional peer with an empty module rather\n // than rejecting the dynamic import. Keep that path on the same actionable\n // error instead of failing later with \"Class extends undefined\".\n if (typeof DefaultChatTransport !== \"function\") {\n throw new Error(MISSING_AI_SDK_MESSAGE);\n }\n\n class UIMessageStreamParser extends DefaultChatTransport<UIMessage> {\n parseBody(stream: ReadableStream<Uint8Array>): ReadableStream<UIMessageChunk> {\n return this.processResponseStream(stream);\n }\n }\n\n return new UIMessageStreamParser().parseBody(body);\n}\n\nasync function* readChunks(stream: ReadableStream<UIMessageChunk>): AsyncIterable<UIMessageChunk> {\n const reader = stream.getReader();\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) return;\n yield value;\n }\n } finally {\n reader.releaseLock();\n }\n}\n\nfunction toolResult(toolCallId: string, content: string, error?: string): AGUIEvent {\n return {\n type: EventType.TOOL_CALL_RESULT,\n messageId: `tool-result-${toolCallId}`,\n toolCallId,\n content,\n role: \"tool\",\n ...(error !== undefined ? { isError: true, error } : {}),\n } as AGUIEvent;\n}\n\n/**\n * Adapter for Vercel AI SDK v6 and v7 UIMessage streams.\n *\n * The AI SDK is loaded only when parsing begins so it can remain an optional\n * peer dependency for consumers that use other stream adapters. Its\n * `DefaultChatTransport` performs the native SSE decoding and chunk validation;\n * this adapter only maps validated UIMessage chunks to AG-UI events.\n */\nexport const vercelAIAdapter = (): StreamProtocolAdapter => ({\n async *parse(response): AsyncIterable<AGUIEvent> {\n if (!response.body) throw new Error(\"No response body\");\n\n const chunks = await parseUIMessageStream(response.body);\n const startedTools = new Set<string>();\n const streamedToolArgs = new Set<string>();\n const endedTools = new Set<string>();\n let stepIndex = 0;\n\n // AG-UI step events are lifecycle-only. Normalize each AI SDK model step\n // into one assistant message lifecycle here so downstream consumers do not\n // need provider-specific step handling. Open it lazily to avoid producing\n // empty messages for steps whose only chunks are ignored by this adapter.\n let activeStep:\n | {\n stepName: string;\n messageId?: string;\n messageStarted: boolean;\n // Per-step, so a new step resets it without an explicit assignment.\n // Only ever read while a step message is open (see beginText).\n sawTools: boolean;\n }\n | undefined;\n\n const startStepMessage = (preferredMessageId?: string): AGUIEvent | undefined => {\n if (!activeStep || activeStep.messageStarted) return;\n\n activeStep.messageId ??= preferredMessageId ?? `vercel-ai-message-${stepIndex}`;\n activeStep.messageStarted = true;\n return {\n type: EventType.TEXT_MESSAGE_START,\n messageId: activeStep.messageId,\n role: \"assistant\",\n };\n };\n\n // Single entry point for \"a text chunk arrived\": opens the step's message,\n // or closes it and opens a new one when the text follows tool calls.\n //\n // Text that follows tool calls is a new assistant item: commentary like\n // \"Let me do this\" stays on the tool-bearing message and the answer text\n // after it gets its own message id, so a consumer splitting on\n // TEXT_MESSAGE_START keeps both. Streams without `start-step` already give\n // each text part a distinct id, so only the step-scoped message needs this.\n const beginText = (partId: string): AGUIEvent[] => {\n if (activeStep?.messageStarted && activeStep.sawTools) {\n const previousId = activeStep.messageId!;\n activeStep.messageId = partId;\n activeStep.sawTools = false;\n return [\n { type: EventType.TEXT_MESSAGE_END, messageId: previousId },\n { type: EventType.TEXT_MESSAGE_START, messageId: partId, role: \"assistant\" },\n ];\n }\n\n const event = startStepMessage(partId);\n return event ? [event] : [];\n };\n\n const toolParent = () =>\n activeStep?.messageId ? { parentMessageId: activeStep.messageId } : {};\n\n for await (const chunk of readChunks(chunks)) {\n if (\"providerExecuted\" in chunk && chunk.providerExecuted === true) {\n throw new Error(PROVIDER_EXECUTED_TOOLS_UNSUPPORTED_MESSAGE);\n }\n\n switch (chunk.type) {\n case \"start-step\": {\n const stepName = `vercel-ai-step-${++stepIndex}`;\n activeStep = { stepName, messageStarted: false, sawTools: false };\n yield {\n type: EventType.STEP_STARTED,\n stepName,\n };\n break;\n }\n\n case \"finish-step\": {\n const stepName = activeStep?.stepName ?? `vercel-ai-step-${++stepIndex}`;\n if (activeStep?.messageStarted && activeStep.messageId) {\n yield {\n type: EventType.TEXT_MESSAGE_END,\n messageId: activeStep.messageId,\n };\n }\n yield {\n type: EventType.STEP_FINISHED,\n stepName,\n };\n activeStep = undefined;\n break;\n }\n\n case \"text-start\": {\n for (const event of beginText(chunk.id)) yield event;\n if (!activeStep) {\n yield {\n type: EventType.TEXT_MESSAGE_START,\n messageId: chunk.id,\n role: \"assistant\",\n };\n }\n break;\n }\n\n case \"text-delta\": {\n for (const event of beginText(chunk.id)) yield event;\n yield {\n type: EventType.TEXT_MESSAGE_CONTENT,\n messageId: activeStep?.messageId ?? chunk.id,\n delta: chunk.delta,\n };\n break;\n }\n\n case \"text-end\":\n if (!activeStep) {\n yield {\n type: EventType.TEXT_MESSAGE_END,\n messageId: chunk.id,\n };\n }\n break;\n\n case \"tool-input-start\":\n if (!startedTools.has(chunk.toolCallId)) {\n const event = startStepMessage();\n if (event) yield event;\n startedTools.add(chunk.toolCallId);\n if (activeStep) activeStep.sawTools = true;\n yield {\n type: EventType.TOOL_CALL_START,\n toolCallId: chunk.toolCallId,\n toolCallName: chunk.toolName,\n ...toolParent(),\n };\n }\n break;\n\n case \"tool-input-delta\":\n if (chunk.inputTextDelta) {\n streamedToolArgs.add(chunk.toolCallId);\n yield {\n type: EventType.TOOL_CALL_ARGS,\n toolCallId: chunk.toolCallId,\n delta: chunk.inputTextDelta,\n };\n }\n break;\n\n case \"tool-input-available\":\n case \"tool-input-error\": {\n if (!startedTools.has(chunk.toolCallId)) {\n const event = startStepMessage();\n if (event) yield event;\n startedTools.add(chunk.toolCallId);\n if (activeStep) activeStep.sawTools = true;\n yield {\n type: EventType.TOOL_CALL_START,\n toolCallId: chunk.toolCallId,\n toolCallName: chunk.toolName,\n ...toolParent(),\n };\n }\n\n if (!streamedToolArgs.has(chunk.toolCallId)) {\n streamedToolArgs.add(chunk.toolCallId);\n yield {\n type: EventType.TOOL_CALL_ARGS,\n toolCallId: chunk.toolCallId,\n delta: serialize(chunk.input),\n };\n }\n\n if (!endedTools.has(chunk.toolCallId)) {\n endedTools.add(chunk.toolCallId);\n yield {\n type: EventType.TOOL_CALL_END,\n toolCallId: chunk.toolCallId,\n };\n }\n\n if (chunk.type === \"tool-input-error\") {\n yield toolResult(chunk.toolCallId, chunk.errorText, chunk.errorText);\n }\n break;\n }\n\n case \"tool-output-available\":\n yield toolResult(chunk.toolCallId, serialize(chunk.output));\n break;\n\n case \"tool-output-error\":\n yield toolResult(chunk.toolCallId, chunk.errorText, chunk.errorText);\n break;\n\n case \"tool-output-denied\":\n yield toolResult(\n chunk.toolCallId,\n TOOL_EXECUTION_DENIED_MESSAGE,\n TOOL_EXECUTION_DENIED_MESSAGE,\n );\n break;\n\n case \"error\":\n yield {\n type: EventType.RUN_ERROR,\n message: chunk.errorText,\n };\n return;\n }\n }\n\n if (activeStep?.messageStarted && activeStep.messageId) {\n yield {\n type: EventType.TEXT_MESSAGE_END,\n messageId: activeStep.messageId,\n };\n }\n },\n});\n","import { AssistantMessage, EventType, Message, StreamProtocolAdapter, ToolMessage } from \"../types\";\nimport { agUIAdapter } from \"./adapters\";\n\n/**\n * @inline\n */\ninterface Parameters {\n response: Response;\n /** A function that creates a new message in the thread (assistant or tool). */\n createMessage: (message: Message) => void;\n /** A function that updates an existing message in the thread (matched by id). */\n updateMessage: (message: Message) => void;\n /**\n * Marks a tool call as executing (args closed, awaiting result). Wired to the\n * store's `executingToolCallIds` set so `pairToolActivity` can report the\n * `\"executing\"` status. Optional — defaults to a no-op for standalone use.\n */\n markToolExecuting?: (toolCallId: string) => void;\n /** Clears a tool call from the executing set (result landed or errored). */\n clearToolExecuting?: (toolCallId: string) => void;\n /** The adapter to use for parsing the stream */\n adapter?: StreamProtocolAdapter;\n}\n\n/**\n * @category Utilities\n */\nexport const processStreamedMessage = async ({\n response,\n createMessage,\n updateMessage,\n markToolExecuting = () => {},\n clearToolExecuting = () => {},\n adapter = agUIAdapter(),\n}: Parameters): Promise<AssistantMessage | void> => {\n let currentMessage: AssistantMessage = {\n id: crypto.randomUUID(),\n role: \"assistant\",\n content: \"\",\n toolCalls: [],\n };\n\n let isFirst = true;\n\n // The wire message-item id whose text currently streams into currentMessage.\n let currentTextItemId: string | null = null;\n\n // Tool messages by toolCallId, so repeated TOOL_CALL_RESULTs for the same\n // call UPDATE one message in place instead of duplicating it.\n const toolMessagesByCallId = new Map<string, ToolMessage>();\n\n // Tool calls that have started but not yet received a result. On RUN_ERROR\n // these are surfaced as errored tool messages instead of being left hanging.\n const inFlightToolCallIds = new Set<string>();\n\n let rafId: number | null = null;\n const debouncedUpdate = (msg: AssistantMessage) => {\n if (rafId !== null) cancelAnimationFrame(rafId);\n rafId = requestAnimationFrame(() => {\n updateMessage(msg);\n rafId = null;\n });\n };\n\n /** Flush the open assistant and start a fresh one (interleaved segments). */\n const startNewAssistantSegment = () => {\n if (rafId !== null) {\n cancelAnimationFrame(rafId);\n rafId = null;\n if (!isFirst) updateMessage(currentMessage);\n }\n currentMessage = {\n id: crypto.randomUUID(),\n role: \"assistant\",\n content: \"\",\n toolCalls: [],\n };\n isFirst = true;\n currentTextItemId = null;\n };\n\n const messageHasBody = (msg: AssistantMessage) =>\n (msg.content?.length ?? 0) > 0 || (msg.toolCalls?.length ?? 0) > 0;\n\n /** Publish the open assistant only once it has text or tool calls — never an empty shell. */\n const commitCurrentMessage = () => {\n if (isFirst) {\n if (!messageHasBody(currentMessage)) return;\n createMessage(currentMessage);\n isFirst = false;\n } else {\n debouncedUpdate(currentMessage);\n }\n };\n\n for await (const event of adapter.parse(response)) {\n switch (event.type) {\n // TEXT_MESSAGE_CHUNK and TEXT_MESSAGE_CONTENT are very similar events but TEXT_MESSAGE_CHUNK\n // optionally allows for a role change. Since we don't support role changes in processMessage\n // right now, we treat both the same.\n case EventType.TEXT_MESSAGE_CHUNK:\n case EventType.TEXT_MESSAGE_CONTENT: {\n // Ignore empty deltas — a zero-length content event after tools would\n // otherwise open a blank assistant segment that shadows the real answer\n // (common around parallel tool calls when a new message item is opened).\n if (!event.delta) break;\n // Some adapters (LangGraph / ChatOpenAI Responses) keep one wire\n // messageId for a whole model step even when Responses interleaved\n // several message items. Text after tools means a new segment — same\n // split Responses adapters express via a new TEXT_MESSAGE_START id.\n if ((currentMessage.toolCalls?.length ?? 0) > 0) {\n startNewAssistantSegment();\n }\n currentMessage = {\n ...currentMessage,\n content: (currentMessage.content || \"\") + event.delta,\n };\n break;\n }\n\n case EventType.TOOL_CALL_START:\n inFlightToolCallIds.add(event.toolCallId);\n currentMessage = {\n ...currentMessage,\n toolCalls: [\n ...(currentMessage.toolCalls || []),\n {\n id: event.toolCallId,\n type: \"function\",\n function: {\n name: event.toolCallName,\n arguments: \"\",\n },\n },\n ],\n };\n break;\n\n case EventType.TOOL_CALL_END:\n // Args have finished arriving → the call is now executing (awaiting its\n // result), not \"streaming\". Previously this event was dropped and\n // completion was faked from \"did assistant text start\".\n markToolExecuting(event.toolCallId);\n break;\n\n case EventType.TOOL_CALL_ARGS:\n if (currentMessage.toolCalls) {\n const toolCalls = [...currentMessage.toolCalls];\n const toolCallIndex = toolCalls.findIndex((tc) => tc.id === event.toolCallId);\n if (toolCallIndex !== -1) {\n const currentToolCall = toolCalls[toolCallIndex];\n if (currentToolCall) {\n toolCalls[toolCallIndex] = {\n id: currentToolCall.id,\n type: \"function\",\n function: {\n name: currentToolCall.function.name,\n arguments: currentToolCall.function.arguments + event.delta,\n },\n };\n currentMessage = { ...currentMessage, toolCalls };\n }\n }\n }\n break;\n\n case EventType.TOOL_CALL_CHUNK: {\n // Combined convenience form of START + ARGS (AG-UI). Some servers emit\n // only chunks instead of the explicit START/ARGS/END triad; without\n // this case their tool calls would be silently dropped. Lazily START on\n // the first chunk carrying an id, fill the name if it arrives on a later\n // chunk, and append any `delta` as ARGS. (No END is implied — a\n // chunk-only call stays \"streaming\" until its result lands.)\n const id = event.toolCallId;\n if (!id) break;\n const toolCalls = [...(currentMessage.toolCalls || [])];\n let index = toolCalls.findIndex((tc) => tc.id === id);\n if (index === -1) {\n inFlightToolCallIds.add(id);\n toolCalls.push({\n id,\n type: \"function\",\n function: { name: event.toolCallName ?? \"\", arguments: \"\" },\n });\n index = toolCalls.length - 1;\n }\n const existing = toolCalls[index];\n if (existing) {\n toolCalls[index] = {\n id: existing.id,\n type: \"function\",\n function: {\n name: existing.function.name || event.toolCallName || \"\",\n arguments: existing.function.arguments + (event.delta ?? \"\"),\n },\n };\n currentMessage = { ...currentMessage, toolCalls };\n }\n break;\n }\n\n case EventType.TEXT_MESSAGE_START: {\n // A DIFFERENT item id after content/tool calls have accumulated means\n // the model opened a new output message item — interleaving prose with\n // tool calls (several sections in one run). Split into a fresh assistant\n // message so the live structure matches what reload reconstructs from\n // storage\n const startId = (event as { messageId?: string }).messageId ?? null;\n const hasBody =\n (currentMessage.content?.length ?? 0) > 0 || (currentMessage.toolCalls?.length ?? 0) > 0;\n if (hasBody && startId !== currentTextItemId) {\n startNewAssistantSegment();\n }\n currentTextItemId = startId;\n break;\n }\n\n case EventType.TOOL_CALL_RESULT: {\n // Result landed → no longer executing / in flight.\n clearToolExecuting(event.toolCallId);\n inFlightToolCallIds.delete(event.toolCallId);\n\n // The call this result answers may still be waiting on the debounced\n // assistant update (server-side tools stream their call and result\n // back to back). Publish it first, or the result briefly pairs with no\n // call and renders as a nameless tool — for as long as the frame is\n // deferred, which in a background tab is until it's shown again.\n if (rafId !== null) {\n cancelAnimationFrame(rafId);\n rafId = null;\n updateMessage(currentMessage);\n }\n\n // Surface a failure onto the @ag-ui/core ToolMessage.error field. The\n // TOOL_CALL_RESULT schema is `passthrough`, so adapters may carry an\n // `isError` flag and/or `error` string; map either onto `error` so the\n // selector can emit `status:\"error\"` (the previously-dead error branch\n // in ToolResult lights up). Absent any failure signal it stays a\n // success — no regression vs. today.\n const failed = event as unknown as { isError?: boolean; error?: string };\n const errorText =\n failed.isError === true || (typeof failed.error === \"string\" && failed.error.length > 0)\n ? (failed.error ?? event.content)\n : undefined;\n\n // Upsert the tool message for this toolCallId. First result → create;\n // any subsequent result for the same call → update the same message in\n // place (no duplicates).\n const existing = toolMessagesByCallId.get(event.toolCallId);\n if (existing) {\n const updated: ToolMessage = {\n ...existing,\n content: event.content,\n ...(errorText ? { error: errorText } : {}),\n };\n toolMessagesByCallId.set(event.toolCallId, updated);\n updateMessage(updated);\n } else {\n const toolMessage: ToolMessage = {\n id: crypto.randomUUID(),\n role: \"tool\",\n toolCallId: event.toolCallId,\n content: event.content,\n ...(errorText ? { error: errorText } : {}),\n };\n toolMessagesByCallId.set(event.toolCallId, toolMessage);\n createMessage(toolMessage);\n }\n continue; // skip the trailing isFirst/update logic — this event doesn't touch currentMessage\n }\n\n case EventType.RUN_ERROR: {\n const raw = (event as any).message || (event as any).error || \"Stream error\";\n const errorText = typeof raw === \"string\" ? raw : JSON.stringify(raw);\n\n // RUN_ERROR carries no toolCallId. Clear the executing flag for any\n // tool call still in flight (started, no result yet) so it doesn't spin\n // forever, but do NOT synthesize an empty-content tool message for it —\n // an empty result would blank an in-flight renderer (e.g. an artifact\n // skeleton). A call that already streamed a result was removed from the\n // in-flight set on TOOL_CALL_RESULT, so it keeps its delivered content.\n // The failure surfaces as the thread-level error thrown below.\n for (const toolCallId of inFlightToolCallIds) {\n clearToolExecuting(toolCallId);\n }\n inFlightToolCallIds.clear();\n\n throw new Error(errorText);\n }\n }\n\n commitCurrentMessage();\n }\n\n if (rafId !== null) {\n // flush any update\n cancelAnimationFrame(rafId);\n updateMessage(currentMessage);\n } else if (isFirst && messageHasBody(currentMessage)) {\n // Last event was a no-op (e.g. empty delta) after body landed in memory only.\n createMessage(currentMessage);\n }\n\n return currentMessage;\n};\n","import { ObservabilityLevel } from \"@openuidev/observability\";\nimport { getResponseErrorMessage } from \"../adapters/httpError\";\n\nexport async function buildObservabilityErrorDetail(response: Response) {\n if (response.ok) return {};\n\n try {\n const res = await response.clone().json();\n return {\n error: res?.error,\n ...(!res?.message\n ? { message: await getResponseErrorMessage(response) }\n : { message: res.message }),\n };\n } catch {\n return { message: await getResponseErrorMessage(response) };\n }\n}\n\nexport function levelForStatus(status: number): ObservabilityLevel {\n return status >= 400 ? \"error\" : \"info\";\n}\n","import { observability } from \"@openuidev/observability\";\nimport { createStore } from \"zustand/vanilla\";\nimport { subscribeWithSelector } from \"zustand/middleware\";\nimport { getResponseErrorMessage } from \"../adapters/httpError\";\nimport type { ChatLLM, ChatStorage } from \"../adapters/types\";\nimport { processStreamedMessage } from \"../stream/processStreamedMessage\";\nimport { buildObservabilityErrorDetail, levelForStatus } from \"./observability\";\nimport type { ChatStore, Message, Thread, UserMessage } from \"./types\";\n\nexport interface CreateChatStoreConfig {\n storage: ChatStorage;\n llm: ChatLLM;\n}\n\nconst mergeThreadList = (existing: Thread[], incoming: Thread[]): Thread[] =>\n Array.from(new Map([...existing, ...incoming].map((t) => [t.id, t])).values()).sort(\n (a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime(),\n );\n\n// Takes the ref itself and reads `current` at call time, so the caller\n// (ChatProvider) can refresh `llm` by mutating or replacing `current`.\nexport const createChatStore = (configRef: { current: CreateChatStoreConfig }) => {\n const { storage } = configRef.current;\n const { thread: threadStorage } = storage;\n\n const store = createStore<ChatStore>()(\n subscribeWithSelector((set, get) => ({\n // Thread List State\n threads: [],\n isLoadingThreads: false,\n threadListError: null,\n selectedThreadId: null,\n hasMoreThreads: false,\n _nextCursor: undefined,\n\n // Thread State\n messages: [],\n isRunning: false,\n isLoadingMessages: false,\n threadError: null,\n executingToolCallIds: new Set<string>(),\n _abortController: null,\n\n // ── Thread List Actions ──\n\n loadThreads: () => {\n set({ isLoadingThreads: true, threadListError: null });\n threadStorage\n .listThreads(undefined)\n .then(({ threads = [], nextCursor }) => {\n set({\n threads,\n isLoadingThreads: false,\n _nextCursor: nextCursor,\n hasMoreThreads: nextCursor !== undefined,\n });\n })\n .catch((e) => {\n set({ isLoadingThreads: false, threadListError: e });\n });\n },\n\n loadMoreThreads: () => {\n const cursor = get()._nextCursor;\n if (cursor === undefined) return;\n threadStorage\n .listThreads(cursor)\n .then(({ threads = [], nextCursor }) => {\n set((s) => ({\n threads: mergeThreadList(s.threads, threads),\n _nextCursor: nextCursor,\n hasMoreThreads: nextCursor !== undefined,\n }));\n })\n .catch((e) => {\n set({ threadListError: e });\n });\n },\n\n switchToNewThread: () => {\n get().cancelMessage();\n set({\n selectedThreadId: null,\n messages: [],\n threadError: null,\n executingToolCallIds: new Set<string>(),\n });\n },\n\n createThread: async (firstMessage: UserMessage) => {\n const thread = await threadStorage.createThread(firstMessage);\n set((s) => ({ threads: mergeThreadList(s.threads, [thread]) }));\n return thread;\n },\n\n selectThread: (threadId: string) => {\n // Re-selecting the active thread is a no-op — don't wipe and refetch.\n if (get().selectedThreadId === threadId) return;\n get().cancelMessage();\n set({\n selectedThreadId: threadId,\n messages: [],\n isLoadingMessages: true,\n threadError: null,\n executingToolCallIds: new Set<string>(),\n });\n threadStorage\n .getMessages(threadId)\n .then((messages) => set({ messages, isLoadingMessages: false }))\n .catch((e) => set({ threadError: e, isLoadingMessages: false }));\n },\n\n updateThread: (thread: Thread) => {\n const setPending = (id: string, isPending: boolean) =>\n set((s) => ({ threads: s.threads.map((t) => (t.id === id ? { ...t, isPending } : t)) }));\n setPending(thread.id, true);\n threadStorage\n .updateThread(thread)\n .then((updated) => {\n set((s) => ({\n threads: s.threads.map((t) => (t.id === updated.id ? updated : t)),\n }));\n })\n .catch(() => setPending(thread.id, false));\n },\n\n deleteThread: (threadId: string) => {\n const setPending = (id: string, isPending: boolean) =>\n set((s) => ({ threads: s.threads.map((t) => (t.id === id ? { ...t, isPending } : t)) }));\n setPending(threadId, true);\n threadStorage\n .deleteThread(threadId)\n .then(() => {\n const state = get();\n set({ threads: state.threads.filter((t) => t.id !== threadId) });\n if (state.selectedThreadId === threadId) {\n state.switchToNewThread();\n }\n })\n .catch(() => setPending(threadId, false));\n },\n\n // ── Thread Actions ──\n\n processMessage: async (message) => {\n const state = get();\n if (state.isRunning) return;\n\n const abortController = new AbortController();\n const optimisticMessage: UserMessage = {\n ...message,\n id: crypto.randomUUID(),\n role: \"user\",\n };\n\n set({\n _abortController: abortController,\n isRunning: true,\n threadError: null,\n executingToolCallIds: new Set<string>(),\n });\n set((s) => ({ messages: [...s.messages, optimisticMessage] }));\n\n abortController.signal.addEventListener(\"abort\", () => {\n set({ _abortController: null, isRunning: false });\n });\n\n try {\n let threadId = get().selectedThreadId;\n\n if (!threadId) {\n const created = await get().createThread(optimisticMessage);\n threadId = created.id;\n set({ selectedThreadId: threadId });\n }\n\n const runId = crypto.randomUUID();\n\n observability.info({\n kind: \"LLM:request\",\n threadId,\n runId,\n // message is a reserved keyword for the observability library expecting string\n userMessage: optimisticMessage,\n });\n\n let response: Response | null = null;\n try {\n response = await configRef.current.llm.send({\n threadId,\n messages: get().messages,\n signal: abortController.signal,\n });\n\n observability(levelForStatus(response.status), {\n kind: response.ok ? \"LLM:response\" : \"LLM:error\",\n threadId,\n status: response.status,\n ok: response.ok,\n runId,\n ...(await buildObservabilityErrorDetail(response)),\n });\n\n if (!response.ok) {\n throw new Error(await getResponseErrorMessage(response));\n }\n } catch (e) {\n observability.error({\n kind: \"LLM:error\",\n threadId,\n runId,\n error: e instanceof Error ? e : new Error(String(e)),\n });\n throw e;\n }\n\n await processStreamedMessage({\n response,\n createMessage: (msg) => set((s) => ({ messages: [...s.messages, msg] })),\n updateMessage: (msg) =>\n set((s) => ({\n messages: s.messages.map((m) => (m.id === msg.id ? msg : m)),\n })),\n // A tool's args have closed (TOOL_CALL_END) → it is now executing.\n markToolExecuting: (id) =>\n set((s) =>\n s.executingToolCallIds.has(id)\n ? s\n : { executingToolCallIds: new Set(s.executingToolCallIds).add(id) },\n ),\n // Its result landed (or it errored) → no longer executing.\n clearToolExecuting: (id) =>\n set((s) => {\n if (!s.executingToolCallIds.has(id)) return s;\n const next = new Set(s.executingToolCallIds);\n next.delete(id);\n return { executingToolCallIds: next };\n }),\n adapter: configRef.current.llm.streamProtocol,\n });\n } catch (e) {\n if (!abortController.signal.aborted) {\n set({ threadError: e instanceof Error ? e : new Error(String(e)) });\n }\n } finally {\n // Clear any tool calls still flagged \"executing\" — adapters that emit\n // TOOL_CALL_END without a matching TOOL_CALL_RESULT (e.g. client-side\n // tool calls in the OpenAI adapters) would otherwise leave them stuck\n // in the executing set after the run ends.\n set({\n _abortController: null,\n isRunning: false,\n executingToolCallIds: new Set<string>(),\n });\n }\n },\n\n appendMessages: (...newMessages: Message[]) => {\n set((s) => ({ messages: [...s.messages, ...newMessages] }));\n },\n\n updateMessage: (message: Message) => {\n set((s) => ({\n messages: s.messages.map((m) => (m.id === message.id ? message : m)),\n }));\n },\n\n setMessages: (messages: Message[]) => {\n set({ messages });\n },\n\n deleteMessage: (messageId: string) => {\n set((s) => ({ messages: s.messages.filter((m) => m.id !== messageId) }));\n },\n\n cancelMessage: () => {\n get()._abortController?.abort();\n },\n })),\n );\n\n return store;\n};\n","import { createStore } from \"zustand/vanilla\";\nimport { subscribeWithSelector } from \"zustand/middleware\";\nimport type { DetailedViewStore } from \"./detailedViewTypes\";\n\n/**\n * Creates a Zustand store managing detailed-view state.\n * Instantiated once by `ChatProvider` — consumers should not call this directly.\n *\n * @internal\n */\nexport const createDetailedViewStore = () => {\n return createStore<DetailedViewStore>()(\n subscribeWithSelector((set, get) => ({\n activeDetailedViewId: null,\n\n setActiveDetailedView: (id) => {\n set({ activeDetailedViewId: id });\n },\n\n reset: () => {\n set({ activeDetailedViewId: null });\n },\n\n _detailedViewPanelNode: null,\n _setDetailedViewPanelNode: (node) => {\n if (\n typeof process !== \"undefined\" &&\n process.env?.[\"NODE_ENV\"] !== \"production\" &&\n node &&\n get()._detailedViewPanelNode &&\n get()._detailedViewPanelNode !== node\n ) {\n console.warn(\n \"[OpenUI] Multiple DetailedViewPortalTarget instances detected. \" +\n \"Only one should be mounted at a time.\",\n );\n }\n set({ _detailedViewPanelNode: node });\n },\n })),\n );\n};\n","import { createStore } from \"zustand/vanilla\";\nimport { subscribeWithSelector } from \"zustand/middleware\";\nimport type { ArtifactEntry, ThreadContextStore } from \"./threadContextTypes\";\n\nconst entriesEqual = (a: ArtifactEntry, b: ArtifactEntry) =>\n a.heading === b.heading && a.type === b.type;\n\nconst upsertVersion = (\n registry: Record<string, ArtifactEntry[]>,\n entry: ArtifactEntry,\n): Record<string, ArtifactEntry[]> => {\n const existing = registry[entry.id] ?? [];\n const sameVersionIdx = existing.findIndex((e) => e.version === entry.version);\n\n if (sameVersionIdx !== -1) {\n const current = existing[sameVersionIdx]!;\n if (entriesEqual(current, entry)) return registry;\n const next = existing.slice();\n next[sameVersionIdx] = entry;\n return { ...registry, [entry.id]: next };\n }\n\n // Insert sorted ascending by version.\n const insertIdx = existing.findIndex((e) => e.version > entry.version);\n const next =\n insertIdx === -1\n ? [...existing, entry]\n : [...existing.slice(0, insertIdx), entry, ...existing.slice(insertIdx)];\n return { ...registry, [entry.id]: next };\n};\n\nconst removeVersion = (\n registry: Record<string, ArtifactEntry[]>,\n id: string,\n version: number,\n): Record<string, ArtifactEntry[]> => {\n const existing = registry[id];\n if (!existing) return registry;\n const idx = existing.findIndex((e) => e.version === version);\n if (idx === -1) return registry;\n\n if (existing.length === 1) {\n const { [id]: _removed, ...rest } = registry;\n return rest;\n }\n\n const next = existing.slice();\n next.splice(idx, 1);\n return { ...registry, [id]: next };\n};\n\n/**\n * Creates a Zustand store managing the per-thread artifact registry.\n *\n * Active detailed-view state lives in a separate store\n * (see {@link useDetailedView} / {@link useActiveDetailedView}) — TC tracks\n * what's *attached* to the thread; detailed-view state tracks what's *visible*.\n *\n * Instantiated once by `ChatProvider` — consumers should not call this directly.\n *\n * @internal\n */\nexport const createThreadContextStore = () => {\n return createStore<ThreadContextStore>()(\n subscribeWithSelector((set) => ({\n artifacts: {},\n\n registerArtifact: (entry) => {\n set((s) => ({ artifacts: upsertVersion(s.artifacts, entry) }));\n },\n\n unregisterArtifact: (id, version) => {\n set((s) => ({ artifacts: removeVersion(s.artifacts, id, version) }));\n },\n\n reset: () => {\n set({ artifacts: {} });\n },\n })),\n );\n};\n","import { computed, defineComponent, onMounted, onUpdated, onScopeDispose, provide, watch, type PropType, type VNodeChild } from 'vue'\nimport type { ChatLLM, ChatStorage, ArtifactCategory } from '../adapters/types'\nimport type { ArtifactRendererConfig } from './artifactRendererTypes'\nimport { createDefaultInMemoryStorage } from '../adapters/_defaultStorage'\nimport { useArtifactAutoOpenWatcher } from './artifactAutoOpenWatcher'\nimport { ArtifactCategoriesContext } from './ArtifactCategoriesContext'\nimport { ArtifactRenderersContext, buildArtifactRendererRegistry } from './ArtifactRenderersContext'\nimport { ArtifactStorageContext } from './ArtifactStorageContext'\nimport { ChatContext } from './ChatContext'\nimport { createChatStore } from './createChatStore'\nimport { createDetailedViewStore } from './createDetailedViewStore'\nimport { createThreadContextStore } from './createThreadContextStore'\nimport { DetailedViewContext } from './DetailedViewContext'\nimport { ThreadContextContext } from './ThreadContextContext'\n\nconst EMPTY_CATEGORIES: never[] = []\n\nexport const ChatProvider = defineComponent({\n name: 'OpenUIChatProvider',\n props: {\n llm: { type: Object as PropType<ChatLLM>, required: true },\n storage: Object as PropType<ChatStorage>,\n artifactRenderers: Array as PropType<ReadonlyArray<ArtifactRendererConfig<any>>>,\n artifactCategories: Array as PropType<ArtifactCategory[]>,\n artifactAutoOpen: { type: Boolean, default: true },\n children: null as unknown as PropType<VNodeChild>,\n },\n setup(props, { slots }) {\n const storage = props.storage ?? createDefaultInMemoryStorage()\n const config = { current: { storage, llm: props.llm } }\n watch(() => props.llm, value => { config.current.llm = value }, { flush: 'sync' })\n const chat = createChatStore(config)\n const detail = createDetailedViewStore()\n const thread = createThreadContextStore()\n const registry = buildArtifactRendererRegistry(props.artifactRenderers ?? [])\n const initialRenderers = props.artifactRenderers\n let warned = false\n // A parent updated hook runs after child commits, like the source warning's\n // passive effect. A pre-flush watcher would warn before the child commits.\n onUpdated(() => {\n const renderers = props.artifactRenderers\n if (typeof process !== 'undefined' && process.env.NODE_ENV !== 'production' && !warned && renderers !== initialRenderers) {\n console.warn('[OpenUI] `artifactRenderers` prop changed after ChatProvider mount. The original array is kept; new renderers will not be registered. Memoize the array (useMemo) to avoid this warning.')\n warned = true\n }\n })\n let unsubscribe: (() => void) | undefined\n onMounted(() => {\n unsubscribe = chat.subscribe(state => state.selectedThreadId, () => { detail.getState().reset(); thread.getState().reset() })\n })\n onScopeDispose(() => unsubscribe?.())\n useArtifactAutoOpenWatcher(() => props.artifactAutoOpen ?? true, chat, thread, detail)\n provide(ChatContext, chat)\n provide(DetailedViewContext, detail)\n provide(ThreadContextContext, thread)\n provide(ArtifactRenderersContext, registry)\n provide(ArtifactStorageContext, storage.artifact ?? null)\n provide(ArtifactCategoriesContext, computed(() => props.artifactCategories ?? EMPTY_CATEGORIES))\n return () => slots.default?.() ?? props.children\n },\n})\n","import type { AssistantMessage, Message, ToolMessage, UserMessage } from \"../../types\";\nimport type { MessageFormat } from \"../../types/messageFormat\";\n\n// ── LangGraph / LangChain message types ──────────────────────────\n\n/**\n * LangChain-style message as returned by the LangGraph thread state API.\n * Each message carries a `type` discriminator (`\"human\"`, `\"ai\"`, `\"tool\"`,\n * `\"system\"`) and uses snake_case field names.\n */\ninterface LangChainMessage {\n id?: string;\n type: \"human\" | \"ai\" | \"tool\" | \"system\" | \"developer\" | (string & {});\n content: string | Array<{ type: string; text?: string }>;\n name?: string;\n tool_calls?: Array<{\n id: string;\n name: string;\n args: Record<string, unknown> | string;\n }>;\n tool_call_id?: string;\n}\n\n// ── Outbound (AG-UI → LangGraph) ────────────────────────────────\n\nfunction toLangChainMessage(message: Message): LangChainMessage {\n switch (message.role) {\n case \"user\":\n return { type: \"human\", content: message.content ?? \"\" };\n\n case \"assistant\": {\n const result: LangChainMessage = { type: \"ai\", content: message.content ?? \"\" };\n if (message.toolCalls?.length) {\n result.tool_calls = message.toolCalls.map((tc) => ({\n id: tc.id,\n name: tc.function.name,\n args: safeParseArgs(tc.function.arguments),\n }));\n }\n return result;\n }\n\n case \"tool\":\n return {\n type: \"tool\",\n content: message.content,\n tool_call_id: message.toolCallId,\n };\n\n case \"system\":\n return { type: \"system\", content: message.content };\n\n case \"developer\":\n return { type: \"system\", content: message.content };\n\n default:\n return { type: \"system\", content: \"\" };\n }\n}\n\n// ── Inbound (LangGraph → AG-UI) ────────────────────────────────\n\nfunction fromLangChainMessage(msg: LangChainMessage): Message {\n const id = msg.id ?? crypto.randomUUID();\n\n switch (msg.type) {\n case \"human\":\n return { id, role: \"user\", content: extractContent(msg.content) } satisfies UserMessage;\n\n case \"ai\": {\n const result: AssistantMessage = {\n id,\n role: \"assistant\",\n content: extractContent(msg.content),\n };\n if (msg.tool_calls?.length) {\n result.toolCalls = msg.tool_calls.map((tc) => ({\n id: tc.id,\n type: \"function\" as const,\n function: {\n name: tc.name,\n arguments: typeof tc.args === \"string\" ? tc.args : JSON.stringify(tc.args),\n },\n }));\n }\n return result;\n }\n\n case \"tool\":\n return {\n id,\n role: \"tool\",\n content: extractContent(msg.content),\n toolCallId: msg.tool_call_id ?? \"\",\n } satisfies ToolMessage;\n\n case \"system\":\n case \"developer\":\n return { id, role: \"system\", content: extractContent(msg.content) };\n\n default:\n return { id, role: \"system\", content: extractContent(msg.content) };\n }\n}\n\n// ── Helpers ──────────────────────────────────────────────────────\n\nfunction extractContent(content: string | Array<{ type: string; text?: string }>): string {\n if (typeof content === \"string\") return content;\n return content\n .filter((block) => block.type === \"text\" && block.text)\n .map((block) => block.text!)\n .join(\"\");\n}\n\nfunction safeParseArgs(args: string): Record<string, unknown> | string {\n try {\n return JSON.parse(args) as Record<string, unknown>;\n } catch {\n return args;\n }\n}\n\n// ── MessageFormat implementation ─────────────────────────────────\n\n/**\n * Converts between AG-UI message format and LangGraph's LangChain-style\n * message format.\n *\n * LangGraph uses `type` discriminators (`\"human\"`, `\"ai\"`, `\"tool\"`,\n * `\"system\"`) instead of `role`, and tool call arguments are objects\n * rather than JSON strings.\n *\n * AG-UI → LangGraph (toApi):\n * - Maps `role` to `type` (`\"user\"` → `\"human\"`, `\"assistant\"` → `\"ai\"`)\n * - Converts `toolCalls[].function.arguments` from JSON string to object\n * - Converts `toolCallId` → `tool_call_id`\n *\n * LangGraph → AG-UI (fromApi):\n * - Maps `type` to `role` (`\"human\"` → `\"user\"`, `\"ai\"` → `\"assistant\"`)\n * - Converts tool call `args` object to JSON string\n * - Generates `id` via `crypto.randomUUID()` if not present\n */\nexport const langGraphMessageFormat: MessageFormat = {\n toApi(messages: Message[]): LangChainMessage[] {\n return messages.map(toLangChainMessage);\n },\n\n fromApi(data: unknown): Message[] {\n return (data as LangChainMessage[]).map(fromLangChainMessage);\n },\n};\n\nexport type { LangChainMessage as LangGraphMessageFormat };\n","import type {\n ChatCompletionAssistantMessageParam,\n ChatCompletionMessageParam,\n ChatCompletionToolMessageParam,\n ChatCompletionUserMessageParam,\n} from \"openai/resources/chat/completions\";\nimport type { AssistantMessage, Message, ToolMessage, UserMessage } from \"../../types\";\nimport type { MessageFormat } from \"../../types/messageFormat\";\n\n// ── Outbound (AG-UI → OpenAI Completions) ───────────────────────\n\nfunction toOpenAIUserMessage(message: UserMessage): ChatCompletionUserMessageParam {\n const content = message.content;\n\n if (typeof content === \"string\") {\n return { role: \"user\", content };\n }\n\n const parts: ChatCompletionUserMessageParam[\"content\"] =\n content?.map((part) => {\n if (part.type === \"text\") {\n return { type: \"text\" as const, text: part.text };\n }\n if (part.type === \"binary\") {\n const url = part.url ?? `data:${part.mimeType};base64,${part.data ?? \"\"}`;\n return { type: \"image_url\" as const, image_url: { url } };\n }\n return { type: \"text\" as const, text: \"\" };\n }) ?? [];\n\n return { role: \"user\", content: parts };\n}\n\nfunction toOpenAIAssistantMessage(message: AssistantMessage): ChatCompletionAssistantMessageParam {\n const result: ChatCompletionAssistantMessageParam = {\n role: \"assistant\",\n content: message.content ?? null,\n };\n\n if (message.toolCalls?.length) {\n result.tool_calls = message.toolCalls.map((tc) => ({\n id: tc.id,\n type: \"function\" as const,\n function: {\n name: tc.function.name,\n arguments: tc.function.arguments,\n },\n }));\n }\n\n return result;\n}\n\nfunction toOpenAIToolMessage(message: ToolMessage): ChatCompletionToolMessageParam {\n return {\n role: \"tool\",\n content: message.content,\n tool_call_id: message.toolCallId,\n };\n}\n\nfunction toOpenAI(message: Message): ChatCompletionMessageParam {\n switch (message.role) {\n case \"user\":\n return toOpenAIUserMessage(message);\n case \"assistant\":\n return toOpenAIAssistantMessage(message);\n case \"tool\":\n return toOpenAIToolMessage(message);\n case \"system\":\n return { role: \"system\", content: message.content };\n case \"developer\":\n return { role: \"developer\", content: message.content };\n default:\n // reasoning, activity — map to system as fallback\n return { role: \"system\", content: \"\" };\n }\n}\n\n// ── Inbound (OpenAI Completions → AG-UI) ────────────────────────\n\nfunction fromOpenAIAssistant(msg: ChatCompletionAssistantMessageParam): AssistantMessage {\n const content = typeof msg.content === \"string\" ? msg.content : undefined;\n\n const result: AssistantMessage = {\n id: crypto.randomUUID(),\n role: \"assistant\",\n content,\n };\n\n if (msg.tool_calls?.length) {\n result.toolCalls = msg.tool_calls\n .filter((tc): tc is Extract<typeof tc, { type: \"function\" }> => tc.type === \"function\")\n .map((tc) => ({\n id: tc.id,\n type: \"function\" as const,\n function: {\n name: tc.function.name,\n arguments: tc.function.arguments,\n },\n }));\n }\n\n return result;\n}\n\nfunction fromOpenAIUser(msg: ChatCompletionUserMessageParam): UserMessage {\n if (typeof msg.content === \"string\") {\n return { id: crypto.randomUUID(), role: \"user\", content: msg.content };\n }\n\n const content = msg.content.map((part): { type: \"text\"; text: string } => {\n if (part.type === \"text\") return { type: \"text\", text: part.text };\n return { type: \"text\", text: \"\" };\n });\n\n return { id: crypto.randomUUID(), role: \"user\", content };\n}\n\nfunction fromOpenAITool(msg: ChatCompletionToolMessageParam): ToolMessage {\n const content =\n typeof msg.content === \"string\" ? msg.content : msg.content.map((p) => p.text).join(\"\");\n\n return {\n id: crypto.randomUUID(),\n role: \"tool\",\n content,\n toolCallId: msg.tool_call_id,\n };\n}\n\nfunction fromOpenAI(data: ChatCompletionMessageParam): Message {\n switch (data.role) {\n case \"user\":\n return fromOpenAIUser(data);\n case \"assistant\":\n return fromOpenAIAssistant(data);\n case \"tool\":\n return fromOpenAITool(data);\n case \"system\":\n return {\n id: crypto.randomUUID(),\n role: \"system\",\n content: typeof data.content === \"string\" ? data.content : \"\",\n };\n case \"developer\":\n return {\n id: crypto.randomUUID(),\n role: \"developer\",\n content: typeof data.content === \"string\" ? data.content : \"\",\n };\n default:\n return { id: crypto.randomUUID(), role: \"system\", content: \"\" };\n }\n}\n\n// ── MessageFormat implementation ─────────────────────────────────\n\n/**\n * Converts between AG-UI message format and OpenAI **Chat Completions**\n * message format (`ChatCompletionMessageParam`).\n *\n * This is a 1-to-1 mapping — each AG-UI message becomes exactly one\n * `ChatCompletionMessageParam` and vice versa.\n *\n * AG-UI → OpenAI (toApi):\n * - Strips `id` (OpenAI doesn't use message IDs)\n * - Converts `toolCalls` → `tool_calls`\n * - Converts `toolCallId` → `tool_call_id`\n * - Converts multipart `content` arrays to OpenAI content format\n *\n * OpenAI → AG-UI (fromApi):\n * - Generates `id` via `crypto.randomUUID()`\n * - Converts `tool_calls` → `toolCalls`\n * - Converts `tool_call_id` → `toolCallId`\n */\nexport const openAIMessageFormat: MessageFormat = {\n toApi(messages: Message[]): ChatCompletionMessageParam[] {\n return messages.map(toOpenAI);\n },\n\n fromApi(data: unknown): Message[] {\n return (data as ChatCompletionMessageParam[]).map(fromOpenAI);\n },\n};\n","import type { DynamicToolUIPart, UIMessage } from \"ai\";\nimport type { InputContent, Message, ToolCall, ToolMessage, UserMessage } from \"../../types\";\nimport type { MessageFormat } from \"../../types/messageFormat\";\n\nconst PROVIDER_EXECUTED_TOOLS_UNSUPPORTED_MESSAGE =\n \"Vercel AI SDK provider-executed tools are not supported because AG-UI messages cannot preserve providerExecuted semantics.\";\n\ntype UnknownRecord = Record<string, unknown> & {\n data?: unknown;\n errorText?: unknown;\n filename?: unknown;\n id?: unknown;\n input?: unknown;\n mediaType?: unknown;\n mimeType?: unknown;\n output?: unknown;\n parts?: unknown;\n providerExecuted?: unknown;\n role?: unknown;\n source?: unknown;\n state?: unknown;\n text?: unknown;\n toolCallId?: unknown;\n toolName?: unknown;\n type?: unknown;\n url?: unknown;\n value?: unknown;\n};\n\ntype ValidUIMessage = UnknownRecord & {\n id: string;\n role: \"system\" | \"user\" | \"assistant\";\n parts: unknown[];\n};\n\nfunction isRecord(value: unknown): value is UnknownRecord {\n return value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n\nfunction isProviderExecuted(value: unknown): boolean {\n return isRecord(value) && value.providerExecuted === true;\n}\n\nfunction serialize(value: unknown): string {\n if (typeof value === \"string\") return value;\n\n try {\n return JSON.stringify(value) ?? String(value);\n } catch {\n return String(value);\n }\n}\n\nfunction parseToolInput(value: string): unknown {\n try {\n return JSON.parse(value) as unknown;\n } catch {\n return value;\n }\n}\n\nfunction dataUrl(mediaType: string, data: string): string {\n return `data:${mediaType};base64,${data}`;\n}\n\nfunction mediaTypeForPart(part: UnknownRecord, source: UnknownRecord): string {\n if (typeof source.mimeType === \"string\") return source.mimeType;\n\n switch (part.type) {\n case \"image\":\n return \"image/*\";\n case \"audio\":\n return \"audio/*\";\n case \"video\":\n return \"video/*\";\n default:\n return \"application/octet-stream\";\n }\n}\n\nfunction toUserParts(content: UserMessage[\"content\"]): UIMessage[\"parts\"] {\n if (typeof content === \"string\") {\n return [{ type: \"text\", text: content }];\n }\n\n if (!Array.isArray(content)) return [];\n\n return content.flatMap((part): UIMessage[\"parts\"] => {\n if (!isRecord(part)) return [];\n\n if (part.type === \"text\" && typeof part.text === \"string\") {\n return [{ type: \"text\", text: part.text }];\n }\n\n if (part.type === \"binary\") {\n const mediaType =\n typeof part.mimeType === \"string\" ? part.mimeType : \"application/octet-stream\";\n const url =\n typeof part.url === \"string\"\n ? part.url\n : typeof part.data === \"string\"\n ? dataUrl(mediaType, part.data)\n : undefined;\n\n if (!url) return [];\n\n return [\n {\n type: \"file\",\n mediaType,\n url,\n ...(typeof part.filename === \"string\" ? { filename: part.filename } : {}),\n },\n ];\n }\n\n switch (part.type) {\n case \"image\":\n case \"audio\":\n case \"video\":\n case \"document\": {\n if (!isRecord(part.source) || typeof part.source.value !== \"string\") return [];\n\n const mediaType = mediaTypeForPart(part, part.source);\n const url =\n part.source.type === \"data\"\n ? dataUrl(mediaType, part.source.value)\n : part.source.type === \"url\"\n ? part.source.value\n : undefined;\n\n return url ? [{ type: \"file\", mediaType, url }] : [];\n }\n default:\n return [];\n }\n });\n}\n\nfunction toToolPart(toolCall: ToolCall, result: ToolMessage | undefined): DynamicToolUIPart {\n if (isProviderExecuted(toolCall) || isProviderExecuted(result)) {\n throw new Error(PROVIDER_EXECUTED_TOOLS_UNSUPPORTED_MESSAGE);\n }\n\n const input = parseToolInput(toolCall.function.arguments);\n\n if (result?.error) {\n return {\n type: \"dynamic-tool\",\n toolName: toolCall.function.name,\n toolCallId: toolCall.id,\n state: \"output-error\",\n input,\n errorText: result.error,\n };\n }\n\n if (result) {\n return {\n type: \"dynamic-tool\",\n toolName: toolCall.function.name,\n toolCallId: toolCall.id,\n state: \"output-available\",\n input,\n output: result.content,\n };\n }\n\n return {\n type: \"dynamic-tool\",\n toolName: toolCall.function.name,\n toolCallId: toolCall.id,\n state: \"input-available\",\n input,\n };\n}\n\nfunction toVercelMessages(messages: Message[]): UIMessage[] {\n const toolResults = new Map<string, ToolMessage>();\n\n for (const message of messages) {\n if (message.role === \"tool\") toolResults.set(message.toolCallId, message);\n }\n\n const result: UIMessage[] = [];\n\n for (const message of messages) {\n switch (message.role) {\n case \"user\":\n result.push({ id: message.id, role: \"user\", parts: toUserParts(message.content) });\n break;\n\n case \"assistant\": {\n const parts: UIMessage[\"parts\"] = [];\n\n if (typeof message.content === \"string\" && message.content.length > 0) {\n parts.push({ type: \"text\", text: message.content });\n }\n\n for (const toolCall of message.toolCalls ?? []) {\n parts.push(toToolPart(toolCall, toolResults.get(toolCall.id)));\n }\n\n result.push({ id: message.id, role: \"assistant\", parts });\n break;\n }\n\n case \"system\":\n case \"developer\":\n result.push({\n id: message.id,\n role: \"system\",\n parts: [{ type: \"text\", text: message.content }],\n });\n break;\n\n // Vercel UIMessage has no standalone tool-result, reasoning, or activity role.\n // Tool results were folded into their matching assistant parts above.\n default:\n break;\n }\n }\n\n return result;\n}\n\nfunction validUIMessage(value: unknown): value is ValidUIMessage {\n return (\n isRecord(value) &&\n typeof value.id === \"string\" &&\n (value.role === \"system\" || value.role === \"user\" || value.role === \"assistant\") &&\n Array.isArray(value.parts)\n );\n}\n\nfunction textFromParts(parts: unknown[]): string {\n return parts\n .filter(\n (part): part is UnknownRecord & { type: \"text\"; text: string } =>\n isRecord(part) && part.type === \"text\" && typeof part.text === \"string\",\n )\n .map((part) => part.text)\n .join(\"\");\n}\n\nfunction binaryFromFilePart(part: UnknownRecord): InputContent | undefined {\n if (part.type !== \"file\" || typeof part.mediaType !== \"string\" || typeof part.url !== \"string\") {\n return undefined;\n }\n\n const base64Prefix = `data:${part.mediaType};base64,`;\n const source = part.url.startsWith(base64Prefix)\n ? { data: part.url.slice(base64Prefix.length) }\n : { url: part.url };\n\n return {\n type: \"binary\",\n mimeType: part.mediaType,\n ...source,\n ...(typeof part.filename === \"string\" ? { filename: part.filename } : {}),\n };\n}\n\nfunction fromVercelUser(message: ValidUIMessage): UserMessage {\n const contentParts: InputContent[] = [];\n let hasFile = false;\n\n for (const part of message.parts) {\n if (!isRecord(part)) continue;\n\n if (part.type === \"text\" && typeof part.text === \"string\") {\n contentParts.push({ type: \"text\", text: part.text });\n continue;\n }\n\n const binary = binaryFromFilePart(part);\n if (binary) {\n hasFile = true;\n contentParts.push(binary);\n }\n }\n\n return {\n id: message.id,\n role: \"user\",\n content: hasFile ? contentParts : textFromParts(message.parts),\n };\n}\n\nfunction toolName(part: UnknownRecord): string | undefined {\n if (part.type === \"dynamic-tool\") {\n return typeof part.toolName === \"string\" && part.toolName.length > 0\n ? part.toolName\n : undefined;\n }\n\n if (typeof part.type !== \"string\" || !part.type.startsWith(\"tool-\")) return undefined;\n const name = part.type.slice(\"tool-\".length);\n return name || undefined;\n}\n\nfunction hasOwn(record: UnknownRecord, key: string): boolean {\n return Object.prototype.hasOwnProperty.call(record, key);\n}\n\nfunction toolResultFromPart(part: UnknownRecord): ToolMessage | undefined {\n if (typeof part.toolCallId !== \"string\") return undefined;\n\n if (part.state === \"output-available\" && hasOwn(part, \"output\")) {\n return {\n id: `tool-result-${part.toolCallId}`,\n role: \"tool\",\n toolCallId: part.toolCallId,\n content: serialize(part.output),\n };\n }\n\n if (part.state === \"output-error\" && typeof part.errorText === \"string\") {\n return {\n id: `tool-result-${part.toolCallId}`,\n role: \"tool\",\n toolCallId: part.toolCallId,\n content: part.errorText,\n error: part.errorText,\n };\n }\n\n if (part.state === \"output-denied\") {\n const error = \"Tool execution was denied\";\n return {\n id: `tool-result-${part.toolCallId}`,\n role: \"tool\",\n toolCallId: part.toolCallId,\n content: error,\n error,\n };\n }\n\n return undefined;\n}\n\nfunction appendAssistantSegments(message: ValidUIMessage, result: Message[]): void {\n let segmentIndex = 0;\n let segmentStarted = false;\n let text = \"\";\n let toolCalls: ToolCall[] = [];\n let toolResults: ToolMessage[] = [];\n const hasStepMarkers = message.parts.some((part) => isRecord(part) && part.type === \"step-start\");\n\n const hasBody = () => text.length > 0 || toolCalls.length > 0;\n\n const flush = (force = false) => {\n if (!force && !segmentStarted) return;\n\n segmentIndex += 1;\n result.push({\n id: segmentIndex === 1 ? message.id : `${message.id}-segment-${segmentIndex}`,\n role: \"assistant\",\n ...(text ? { content: text } : {}),\n ...(toolCalls.length ? { toolCalls } : {}),\n });\n result.push(...toolResults);\n\n text = \"\";\n toolCalls = [];\n toolResults = [];\n segmentStarted = false;\n };\n\n for (const value of message.parts) {\n if (!isRecord(value)) continue;\n\n if (value.type === \"step-start\") {\n if (hasBody()) flush();\n continue;\n }\n\n if (value.type === \"text\" && typeof value.text === \"string\") {\n // AI SDK step markers are authoritative. Older/custom UIMessage data may\n // omit them, so retain the previous text-part boundary behavior there.\n // Text after tool calls is always a new item (commentary between calls,\n // then the answer), matching the live adapter.\n if (toolCalls.length > 0 || (!hasStepMarkers && hasBody())) flush();\n segmentStarted = true;\n text += value.text;\n continue;\n }\n\n const name = toolName(value);\n if (!name || typeof value.toolCallId !== \"string\") continue;\n\n if (value.providerExecuted === true) {\n throw new Error(PROVIDER_EXECUTED_TOOLS_UNSUPPORTED_MESSAGE);\n }\n\n segmentStarted = true;\n toolCalls.push({\n id: value.toolCallId,\n type: \"function\",\n function: {\n name,\n arguments: hasOwn(value, \"input\") ? serialize(value.input) : \"\",\n },\n });\n\n const toolResult = toolResultFromPart(value);\n if (toolResult) toolResults.push(toolResult);\n }\n\n // AI SDK permits an assistant UIMessage with no parts. Preserve it as one\n // empty assistant rather than dropping the source message entirely.\n flush(segmentIndex === 0);\n}\n\nfunction fromVercelMessages(data: unknown): Message[] {\n if (!Array.isArray(data)) return [];\n\n const result: Message[] = [];\n\n for (const value of data) {\n if (!validUIMessage(value)) continue;\n const message = value;\n\n if (message.role === \"user\") {\n result.push(fromVercelUser(message));\n continue;\n }\n\n const text = textFromParts(message.parts);\n\n if (message.role === \"system\") {\n result.push({ id: message.id, role: \"system\", content: text });\n continue;\n }\n\n appendAssistantSegments(message, result);\n }\n\n return result;\n}\n\n/**\n * Converts messages between AG-UI and Vercel AI SDK v6 and v7 `UIMessage` format.\n *\n * AG-UI tool-result messages are folded into the matching assistant tool part,\n * because `UIMessage` represents a tool invocation and its result as one part.\n * Outbound tool calls use `dynamic-tool` parts because AG-UI messages do not\n * carry the static tool schema needed to select a `tool-${name}` part. Inbound\n * conversion accepts both dynamic and static tool parts.\n *\n * Vercel `UIMessage` has no developer role, so both AG-UI system and developer\n * messages map to its system role.\n *\n * Provider-executed tools are rejected because the AG-UI message model has no\n * execution-provenance field and therefore cannot preserve their requirement\n * that results remain in the assistant message.\n */\nexport const vercelAIMessageFormat: MessageFormat = {\n toApi(messages: Message[]): UIMessage[] {\n return toVercelMessages(messages);\n },\n\n fromApi(data: unknown): Message[] {\n return fromVercelMessages(data);\n },\n};\n","import { identityMessageFormat, type MessageFormat } from \"../types/messageFormat\";\nimport type { StreamProtocolAdapter } from \"../types/stream\";\nimport type { ChatLLM } from \"./types\";\n\nexport interface FetchLLMOptions {\n /** Endpoint that accepts POST'd messages and returns a streaming Response. */\n url: string;\n /** Stream protocol adapter for parsing the response body (e.g., agUIAdapter, openAIAdapter). */\n streamAdapter: StreamProtocolAdapter;\n /** Wire-format conversion for outgoing messages. Defaults to identity (canonical Message). */\n messageFormat?: MessageFormat;\n /** Extra headers merged into the request. */\n headers?: Record<string, string>;\n /** Override fetch implementation (for tests, custom auth wrappers, etc.). */\n fetch?: typeof fetch;\n /** Extra fields merged into the request body (e.g. `model`) */\n body?: Record<string, unknown>;\n}\n\n/**\n * Generic HTTP-based LLM adapter. POSTs an AG-UI `RunAgentInput`-shaped body\n * (`{ threadId, runId, messages, tools, context }`, messages in the chosen wire\n * format) to `url` and returns the streaming `Response` for downstream processing.\n */\nexport function fetchLLM({\n url,\n streamAdapter,\n messageFormat = identityMessageFormat,\n headers,\n fetch: customFetch,\n body,\n}: FetchLLMOptions): ChatLLM {\n const fetchImpl = customFetch ?? globalThis.fetch.bind(globalThis);\n return {\n send: ({ threadId, messages, signal }) => {\n const runId = crypto.randomUUID();\n return fetchImpl(url, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n ...headers,\n },\n body: JSON.stringify({\n ...body,\n tools: [],\n context: [],\n threadId,\n runId,\n messages: messageFormat.toApi(messages),\n }),\n signal,\n });\n },\n streamProtocol: streamAdapter,\n };\n}\n","import type { Thread, UserMessage } from \"../store/types\";\nimport type { Message } from \"../types/message\";\nimport { identityMessageFormat, type MessageFormat } from \"../types/messageFormat\";\nimport type { ChatStorage } from \"./types\";\n\nexport interface RestStorageOptions {\n /**\n * Base URL for thread endpoints (the old `threadApiUrl`). The factory hits\n * the same conventions the legacy default used:\n * - list: GET {baseUrl}/get (· ?cursor={cursor})\n * - create: POST {baseUrl}/create\n * - get: GET {baseUrl}/get/{threadId}\n * - update: PATCH {baseUrl}/update/{threadId}\n * - delete: DELETE {baseUrl}/delete/{threadId}\n */\n baseUrl: string;\n /** Wire-format conversion. Defaults to identity (canonical Message). */\n messageFormat?: MessageFormat;\n /** Extra headers merged into every request. */\n headers?: Record<string, string>;\n /** Override fetch implementation (for tests, custom auth wrappers, etc.). */\n fetch?: typeof fetch;\n}\n\n/**\n * Generic REST-based thread storage. Reproduces the conventions the removed\n * `threadApiUrl` prop used, so an existing backend keeps working by swapping\n * `threadApiUrl=\"/x\"` for `storage={restStorage({ baseUrl: \"/x\" })}`.\n *\n * Only the `thread` channel is implemented. Pair with an `llm` adapter\n * (e.g. `fetchLLM`).\n */\nexport function restStorage({\n baseUrl,\n messageFormat = identityMessageFormat,\n headers,\n fetch: customFetch,\n}: RestStorageOptions): ChatStorage {\n const fetchImpl = customFetch ?? globalThis.fetch.bind(globalThis);\n\n const request = async (url: string, init?: RequestInit): Promise<Response> => {\n const res = await fetchImpl(url, {\n ...init,\n headers: {\n ...(init?.body ? { \"Content-Type\": \"application/json\" } : {}),\n ...headers,\n ...init?.headers,\n },\n });\n if (!res.ok) {\n throw new Error(\n `restStorage: ${init?.method ?? \"GET\"} ${url} failed: ${res.status} ${res.statusText}`,\n );\n }\n return res;\n };\n\n return {\n thread: {\n async listThreads(cursor?: string) {\n const url = cursor ? `${baseUrl}/get?cursor=${cursor}` : `${baseUrl}/get`;\n const res = await request(url);\n return res.json();\n },\n async createThread(firstMessage: UserMessage): Promise<Thread> {\n const res = await request(`${baseUrl}/create`, {\n method: \"POST\",\n body: JSON.stringify({ messages: messageFormat.toApi([firstMessage]) }),\n });\n return res.json();\n },\n async getMessages(threadId: string): Promise<Message[]> {\n const res = await request(`${baseUrl}/get/${threadId}`);\n const raw: unknown = await res.json();\n return messageFormat.fromApi(raw);\n },\n async updateThread(thread: Thread): Promise<Thread> {\n const res = await request(`${baseUrl}/update/${thread.id}`, {\n method: \"PATCH\",\n body: JSON.stringify(thread),\n });\n return res.json();\n },\n async deleteThread(id: string): Promise<void> {\n await request(`${baseUrl}/delete/${id}`, { method: \"DELETE\" });\n },\n },\n };\n}\n"],"mappings":";;;;;;;AAIA,MAAa,yBAAyB,OAAO,wBAAwB;;;;;;;;;;AAWrE,MAAa,2BAAmD,OAAO,wBAAwB,IAAI;;ACqEnG,MAAM,iBAAiB;;AAEvB,MAAM,qBAAqB;;AAE3B,MAAM,uBAAuB;AAC7B,MAAM,uBAAuB;;AAE7B,MAAM,sBAAsB;;AAE5B,MAAM,iBAAiB,KAAK,KAAK;;AAEjC,MAAM,kBAAkB;AACxB,MAAM,8BAAc,IAAI,IAAY;CAClC;CACA;CACA;CACA;AACF,CAAC;;AAGD,MAAM,UAAU,SAAiD;CAC/D,MAAM,SAAS,UACb,MAAM,QAAQ,KAAK,IAAI,MAAM,QAAQ,SAAyB,OAAO,SAAS,QAAQ,IAAI,CAAC;CAC7F,MAAM,EAAE,OAAO,YAAa,QAAQ,CAAC;CACrC,MAAM,OAAO;EAAE,OAAO,MAAM,KAAK;EAAG,SAAS,MAAM,OAAO;CAAE;CAC5D,OAAO,KAAK,MAAM,SAAS,KAAK,KAAK,QAAQ,SAAS,IAAI,OAAO,KAAA;AACnE;AAEA,MAAM,SAAS,OAAe,IAAI,SAAS,YAAY,WAAW,SAAS,EAAE,CAAC;;AAG9E,MAAM,UAAU,UAAiB,MAAM,SAAS,OAAO,SAAS;;;;;AAMhE,MAAM,SAAS,UACb,MAAM,QAAQ,OAAO,KACrB,MAAM,QAAQ,KAAA,KACd,MAAM,SAAS,OAAO,SAAS;AAEjC,MAAM,eACJ,MACA,SACA,WACyB;CACzB,QAAQ;CACR;CACA;CACA,GAAI,UAAU,KAAA,KAAa,EAAE,MAAM;AACrC;;;;;;;;AASA,IAAa,sBAAb,MAAiC;CAMF;CALZ,0BAAU,IAAI,IAAmB;CACjC,2BAAW,IA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UAAU,OAAO,MAAM;IAC1D,QAAQ;IACR,MAAM,KAAK,UAAU,MAAM;GAC7B,CAAC,EAAA,CACU,KAAK;EAClB;EACA,MAAM,aAAa,IAA2B;GAC5C,MAAM,QAAQ,GAAG,QAAQ,UAAU,MAAM,EAAE,QAAQ,SAAS,CAAC;EAC/D;CACF,EACF;AACF"}
1
+ {"version":3,"file":"index.mjs","names":["extractTextContent","isDev","PROVIDER_EXECUTED_TOOLS_UNSUPPORTED_MESSAGE","serialize"],"sources":["../src/store/ArtifactStorageContext.ts","../src/cloud/artifactStream.ts","../src/cloud/interpreter.ts","../src/cloud/sse.ts","../src/cloud/wire.ts","../src/cloud/artifactStorage.ts","../src/cloud/frontendTokenManager.ts","../src/stream/formats/openai-conversation-message-format.ts","../src/cloud/items.ts","../src/cloud/threadStorage.ts","../src/cloud/openuiCloud.ts","../src/cloud/pollInterval.ts","../src/cloud/OpenUICloudProvider.ts","../src/store/useStore.ts","../src/store/DetailedViewContext.ts","../src/hooks/useActiveDetailedView.ts","../src/store/ThreadContextContext.ts","../src/hooks/useArtifactList.ts","../src/store/ArtifactRenderersContext.ts","../src/hooks/useArtifactRenderer.ts","../src/hooks/useDetailedView.ts","../src/hooks/useDetailedViewPortalTarget.ts","../src/hooks/useMessage.ts","../src/store/ChatContext.ts","../src/hooks/useThread.ts","../src/store/toolActivity.ts","../src/hooks/useToolActivities.ts","../src/store/artifactCategories.ts","../src/store/ArtifactCategoriesContext.ts","../src/store/artifactRendererTypes.ts","../src/store/artifactViewId.ts","../src/adapters/_defaultStorage.ts","../src/store/artifactAutoOpenWatcher.ts","../src/adapters/httpError.ts","../src/types/messageFormat.ts","../src/stream/adapters/_shared/sseLines.ts","../src/stream/adapters/ag-ui.ts","../src/stream/adapters/eve.ts","../src/stream/adapters/langgraph.ts","../src/stream/adapters/openai-completions.ts","../src/stream/adapters/openai-readable-stream.ts","../src/stream/adapters/openai-responses.ts","../src/stream/adapters/vercel-ai-sdk.ts","../src/stream/processStreamedMessage.ts","../src/store/observability.ts","../src/store/createChatStore.ts","../src/store/createDetailedViewStore.ts","../src/store/createThreadContextStore.ts","../src/store/ChatProvider.ts","../src/stream/formats/langgraph-message-format.ts","../src/stream/formats/openai-message-format.ts","../src/stream/formats/vercel-ai-message-format.ts","../src/adapters/fetchLLM.ts","../src/adapters/restStorage.ts"],"sourcesContent":["import { inject, type InjectionKey } from \"vue\";\nimport type { ArtifactStorage } from \"../adapters/types\";\n\n/** @internal Provided by `ChatProvider` from `storage.artifact`. */\nexport const ArtifactStorageContext = Symbol(\n \"ArtifactStorageContext\",\n) as InjectionKey<ArtifactStorage | null>;\n\n/**\n * Returns the configured global {@link ArtifactStorage} channel, or `null`\n * when the storage adapter doesn't provide one.\n *\n * Renderer implementations use this to lazily fetch (`get`) or persist\n * (`update`) artifact content; the artifact browser uses it for `list`.\n *\n * @category Hooks\n */\nexport const useArtifactStorage = (): ArtifactStorage | null =>\n inject(ArtifactStorageContext, null);\n","import { computed, shallowRef, toValue, watch, type ComputedRef, type MaybeRefOrGetter } from \"vue\";\nimport type {\n ArtifactBuildStep,\n ArtifactStorage,\n ArtifactStreamEvent,\n ArtifactSummary,\n} from \"../adapters/types\";\nimport { useArtifactStorage } from \"../store/ArtifactStorageContext\";\n\n/** Why an artifact can't be shown. @category Types */\nexport type ArtifactStreamErrorCode =\n \"not-found\" | \"generation-failed\" | \"network-error\" | \"unauthorized\";\n\n/** @category Types */\nexport interface ArtifactStreamError {\n source: \"artifact\";\n code: ArtifactStreamErrorCode;\n message: string;\n /** The underlying error, for logs. `message` is meant for users. */\n cause?: unknown;\n}\n\n/** An artifact as it streams in. Replaced on every change, never mutated. @category Types */\nexport interface ArtifactStreamSnapshot extends Pick<ArtifactSummary, \"isOwner\" | \"isEditable\"> {\n id: string;\n type?: string;\n title?: string;\n /** The program to render. `null` until the first content arrives. */\n program: string | null;\n /** The stored version `program` is, so a script runs against the one on screen. */\n version?: string;\n isStreaming: boolean;\n /**\n * What a dashboard being built is doing, until it starts writing: the data tools it called\n * and the scripts it's saving. Undefined otherwise.\n */\n step?: ArtifactBuildStep;\n justUpdated: boolean;\n error: ArtifactStreamError | null;\n}\n\n/** Called on every change to an artifact's stream. @internal */\nexport type ArtifactStreamWatcher = (\n id: string,\n before: ArtifactStreamSnapshot,\n after: ArtifactStreamSnapshot,\n) => void;\n\ntype Settled = { program: string; version?: string };\n\ninterface Entry {\n snapshot: ArtifactStreamSnapshot;\n listeners: Set<() => void>;\n controller: AbortController | null;\n started: boolean;\n /** The version being streamed, from its `reference`. */\n version?: string;\n /** A new version streams into `program`, live; the same version again loads into `pending`. */\n target: \"program\" | \"pending\";\n pending: string;\n replace: boolean;\n /** What was on screen before a new version started streaming over it. A failed edit goes back to it. */\n settled: Settled | null;\n reconnects: number;\n versions: Set<string>;\n /** A newer revision was seen while a stream was still running. */\n stale: boolean;\n idleTimer: ReturnType<typeof setTimeout> | null;\n /** A re-read started by `versionMismatch`, and its pending answer. */\n reread: { version: string; answer: Promise<\"rerun\" | \"show\">; settle: Settle } | null;\n rereadAt: number;\n /** The last reference's `tag`: what a poll asks the server to compare. */\n tag?: string;\n /** Each polling renderer's interval. The shortest one wins. */\n pollers: Map<symbol, number>;\n pollTimer: ReturnType<typeof setTimeout> | null;\n /** Polls failed in a row; each one doubles the wait. */\n pollFailures: number;\n /** Turns `justUpdated` off again. */\n justUpdatedTimer: ReturnType<typeof setTimeout> | null;\n}\n\ntype Settle = (answer: \"rerun\" | \"show\") => void;\n\nconst MAX_RECONNECTS = 3;\n/** Refused data calls re-read an artifact at most this often, so they can't loop. */\nconst REREAD_INTERVAL_MS = 10_000;\n/** A connection that stayed open this long was healthy, so its drop doesn't count against `MAX_RECONNECTS`. */\nconst STABLE_CONNECTION_MS = 10_000;\nconst MIN_POLL_INTERVAL_MS = 3_000;\n/** The longest failures stretch the wait between checks, unless the interval itself is longer. */\nconst MAX_POLL_BACKOFF_MS = 5 * 60_000;\n/** The longest `setTimeout` takes: a longer wait would fire at once. */\nconst MAX_TIMEOUT_MS = 2 ** 31 - 1;\n/** How long `justUpdated` stays on. */\nconst JUST_UPDATED_MS = 10_000;\nconst ERROR_CODES = new Set<string>([\n \"not-found\",\n \"generation-failed\",\n \"network-error\",\n \"unauthorized\",\n]);\n\n/** A step's names, or `undefined` for an empty or malformed one. */\nconst stepOf = (data: unknown): ArtifactBuildStep | undefined => {\n const names = (value: unknown) =>\n Array.isArray(value) ? value.filter((name): name is string => typeof name === \"string\") : [];\n const { tools, scripts } = (data ?? {}) as Partial<Record<keyof ArtifactBuildStep, unknown>>;\n const step = { tools: names(tools), scripts: names(scripts) };\n return step.tools.length > 0 || step.scripts.length > 0 ? step : undefined;\n};\n\nconst sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));\n\n/** Deleted, or the user lost access. */\nconst isGone = (entry: Entry) => entry.snapshot.error?.code === \"not-found\";\n\n/**\n * Whether to keep checking: a renderer polls, the server tags what it sends (older\n * servers and storages without `stream` don't), and the user is still signed in.\n */\nconst polls = (entry: Entry) =>\n entry.pollers.size > 0 &&\n entry.tag !== undefined &&\n entry.snapshot.error?.code !== \"unauthorized\";\n\nconst streamError = (\n code: ArtifactStreamErrorCode,\n message: string,\n cause?: unknown,\n): ArtifactStreamError => ({\n source: \"artifact\",\n code,\n message,\n ...(cause !== undefined && { cause }),\n});\n\n/**\n * One stream per artifact, shared by every renderer showing it, so an edit\n * streamed by one renderer updates them all. Reads `storage.stream` when the\n * storage has it, and falls back to `storage.get` otherwise.\n *\n * @internal Exported for tests.\n */\nexport class ArtifactStreamStore {\n private readonly entries = new Map<string, Entry>();\n private readonly watchers = new Set<ArtifactStreamWatcher>();\n /** Artifacts whose poll came due while the tab was hidden. */\n private readonly dueWhileHidden = new Set<string>();\n\n constructor(private readonly storage: ArtifactStorage) {}\n\n /** Calls `watcher` on every change to any artifact's stream. Returns a function that stops it. */\n watch(watcher: ArtifactStreamWatcher): () => void {\n this.watchers.add(watcher);\n return () => this.watchers.delete(watcher);\n }\n\n getSnapshot(id: string): ArtifactStreamSnapshot {\n return this.entry(id).snapshot;\n }\n\n subscribe(id: string, listener: () => void): () => void {\n const entry = this.entry(id);\n entry.listeners.add(listener);\n if (entry.idleTimer) {\n clearTimeout(entry.idleTimer);\n entry.idleTimer = null;\n }\n if (!entry.started) {\n entry.started = true;\n void this.connect(id);\n }\n return () => {\n entry.listeners.delete(listener);\n if (entry.listeners.size > 0 || !entry.controller) return;\n // Deferred, so a StrictMode remount doesn't drop the stream.\n entry.idleTimer = setTimeout(() => {\n entry.idleTimer = null;\n if (entry.listeners.size > 0 || !entry.controller) return;\n entry.controller.abort();\n entry.controller = null;\n entry.started = false;\n }, 0);\n };\n }\n\n poll(id: string, intervalMs: number): () => void {\n const entry = this.entry(id);\n const key = Symbol();\n entry.pollers.set(key, Math.max(intervalMs, MIN_POLL_INTERVAL_MS));\n this.schedulePoll(id);\n return () => {\n entry.pollers.delete(key);\n this.schedulePoll(id);\n };\n }\n\n /** A version not seen before means there's a newer revision to fetch. */\n noteVersion(id: string, version: string | undefined): void {\n if (!version) return;\n const entry = this.entry(id);\n if (entry.versions.has(version)) return;\n const isFirst = entry.versions.size === 0;\n entry.versions.add(version);\n if (isFirst || !entry.started) return;\n // An ended stream can hold its controller a few microtasks longer.\n if (entry.controller && entry.snapshot.isStreaming) entry.stale = true;\n else void this.connect(id);\n }\n\n retry(id: string): void {\n const entry = this.entry(id);\n entry.reconnects = 0;\n entry.started = true;\n void this.connect(id);\n }\n\n /**\n * A data call was refused for `version` (`ARTIFACT_VERSION_MISMATCH`). \"rerun\" if\n * a newer version is on screen or a re-read brings one; else \"show\". Renderers\n * refused together share one re-read.\n */\n versionMismatch(id: string, version: string): Promise<\"rerun\" | \"show\"> {\n const entry = this.entry(id);\n if (version !== entry.snapshot.version) return Promise.resolve(\"rerun\");\n if (entry.reread?.version === version) return entry.reread.answer;\n const now = performance.now();\n if (!entry.started || now - entry.rereadAt < REREAD_INTERVAL_MS) {\n return Promise.resolve(\"show\");\n }\n entry.rereadAt = now;\n let settle!: Settle;\n const answer = new Promise<\"rerun\" | \"show\">((resolve) => (settle = resolve));\n entry.reread = { version, answer, settle };\n this.refresh(id);\n return answer;\n }\n\n /** A read ended: answer a pending re-read. */\n private afterRead(id: string): void {\n const entry = this.entry(id);\n const reread = entry.reread;\n if (!reread || entry.snapshot.isStreaming) return;\n entry.reread = null;\n reread.settle(entry.snapshot.version === reread.version ? \"show\" : \"rerun\");\n }\n\n /** Reads the artifact again, after the running stream if there is one. */\n private refresh(id: string): void {\n const entry = this.entry(id);\n if (!entry.started) return;\n if (entry.controller && entry.snapshot.isStreaming) entry.stale = true;\n else {\n entry.reconnects = 0;\n void this.connect(id);\n }\n }\n\n /** True while `version` is newer than any version recorded: the program on screen is behind. */\n awaits(id: string, version: string | undefined): boolean {\n if (!version) return false;\n const entry = this.entry(id);\n return (\n entry.started &&\n entry.snapshot.program !== null &&\n entry.versions.size > 0 &&\n !entry.versions.has(version)\n );\n }\n\n private entry(id: string): Entry {\n let entry = this.entries.get(id);\n if (!entry) {\n entry = {\n snapshot: { id, program: null, isStreaming: false, justUpdated: false, error: null },\n listeners: new Set(),\n controller: null,\n started: false,\n target: \"program\",\n pending: \"\",\n replace: false,\n settled: null,\n reconnects: 0,\n versions: new Set(),\n stale: false,\n idleTimer: null,\n reread: null,\n rereadAt: -Infinity,\n pollers: new Map(),\n pollTimer: null,\n pollFailures: 0,\n justUpdatedTimer: null,\n };\n this.entries.set(id, entry);\n }\n return entry;\n }\n\n private update(id: string, patch: Partial<ArtifactStreamSnapshot>): void {\n const entry = this.entry(id);\n const before = entry.snapshot;\n entry.snapshot = { ...before, ...patch };\n this.watchers.forEach((watcher) => watcher(id, before, entry.snapshot));\n entry.listeners.forEach((listener) => listener());\n }\n\n /** With `fetchLatest`, a poll: it stays quiet until the server sends something new. */\n private async connect(id: string, fetchLatest?: string): Promise<void> {\n const entry = this.entry(id);\n entry.started = true;\n entry.controller?.abort();\n const controller = new AbortController();\n entry.controller = controller;\n const poll = fetchLatest !== undefined;\n if (!poll) this.update(id, { isStreaming: true, error: null });\n\n const connectedAt = Date.now();\n let finished = false;\n let referenced = false;\n let failure: unknown;\n try {\n if (!this.storage.stream) {\n finished = true;\n await this.load(id);\n return;\n }\n for await (const event of this.storage.stream(id, {\n signal: controller.signal,\n fetchLatest,\n })) {\n if (controller.signal.aborted) return;\n if (event.type === \"end\" || event.type === \"error\" || event.type === \"unchanged\") {\n finished = true;\n this.onEvent(id, event);\n break;\n }\n if (event.type === \"reference\") referenced = true;\n this.onEvent(id, event);\n entry.reconnects = 0;\n }\n } catch (error) {\n if (controller.signal.aborted) return;\n failure = error;\n } finally {\n if (entry.controller === controller) entry.controller = null;\n }\n if (controller.signal.aborted) return;\n // Done, or a poll that failed before anything changed (what's on screen stays): poll again\n // later. Each failure doubles the wait; a 404 is an answer, so a gone artifact keeps the interval.\n if (finished || (poll && !referenced)) {\n entry.pollFailures = finished ? 0 : entry.pollFailures + 1;\n this.schedulePoll(id);\n return;\n }\n\n // The stream dropped before it ended: resume after a backoff, then give up.\n // Proxies cut streams that go quiet, as an edit's does until it's done, so a\n // connection that stayed up a while starts the count again.\n if (Date.now() - connectedAt >= STABLE_CONNECTION_MS) entry.reconnects = 0;\n if (entry.reconnects < MAX_RECONNECTS) {\n entry.reconnects += 1;\n await sleep(500 * 2 ** (entry.reconnects - 1));\n // A new version may have reconnected already.\n if (entry.controller) return;\n if (entry.listeners.size > 0) void this.connect(id);\n else entry.started = false;\n return;\n }\n this.update(id, {\n ...this.endRead(entry),\n isStreaming: false,\n error: streamError(\"network-error\", \"Couldn't reach the artifact's storage.\", failure),\n });\n this.afterRead(id);\n }\n\n /**\n * A read is over: resets it, and returns what was on screen before a new version\n * started streaming over it, if one did. A read that failed goes back to that.\n */\n private endRead(entry: Entry): Settled | null {\n const settled = entry.settled;\n entry.target = \"program\";\n entry.pending = \"\";\n entry.version = undefined;\n entry.settled = null;\n return settled;\n }\n\n /** Turns `justUpdated` on for a while. */\n private markUpdated(id: string): void {\n const entry = this.entry(id);\n if (entry.justUpdatedTimer) clearTimeout(entry.justUpdatedTimer);\n entry.justUpdatedTimer = setTimeout(() => {\n entry.justUpdatedTimer = null;\n this.update(id, { justUpdated: false });\n }, JUST_UPDATED_MS);\n this.update(id, { justUpdated: true });\n }\n\n /** Storages without `stream`: read the stored artifact once. */\n private async load(id: string): Promise<void> {\n try {\n const artifact = await this.storage.get(id);\n this.update(id, {\n type: artifact.type,\n title: artifact.title,\n program: typeof artifact.content === \"string\" ? artifact.content : null,\n isStreaming: false,\n });\n } catch (error) {\n this.update(id, {\n isStreaming: false,\n error: streamError(\n \"not-found\",\n error instanceof Error ? error.message : \"This artifact couldn't be loaded.\",\n error,\n ),\n });\n }\n this.afterRead(id);\n }\n\n /** Sets the next poll, if a renderer polls and the last read went well enough to compare against. */\n private schedulePoll(id: string): void {\n const entry = this.entry(id);\n if (entry.pollTimer) clearTimeout(entry.pollTimer);\n entry.pollTimer = null;\n if (!polls(entry)) return;\n const interval = Math.min(...entry.pollers.values());\n // Each failure doubles the wait, up to 5 minutes. Jitter, so renderers opened together don't poll together.\n const backoff = Math.min(\n interval * 2 ** entry.pollFailures,\n Math.max(interval, MAX_POLL_BACKOFF_MS),\n );\n const wait = backoff * (0.9 + Math.random() * 0.2);\n entry.pollTimer = setTimeout(() => this.pollNow(id), Math.min(wait, MAX_TIMEOUT_MS));\n // Coming back to the tab checks again right away.\n if (entry.pollFailures > 0) this.listenForVisible();\n }\n\n private pollNow(id: string): void {\n const entry = this.entry(id);\n if (entry.pollTimer) clearTimeout(entry.pollTimer);\n entry.pollTimer = null;\n // A read in progress schedules the next poll when it ends.\n if (!polls(entry) || entry.controller) return;\n if (typeof document !== \"undefined\" && document.hidden) {\n this.dueWhileHidden.add(id);\n this.listenForVisible();\n return;\n }\n // Gone, so nothing on screen to compare: a full read, which brings it back if it's shared again.\n void this.connect(id, isGone(entry) ? \"\" : entry.tag);\n }\n\n private listenForVisible(): void {\n if (typeof document !== \"undefined\")\n document.addEventListener(\"visibilitychange\", this.onVisible);\n }\n\n /**\n * The tab is back: run the polls that came due while it was hidden, and check now on\n * artifacts waiting out failures, starting their wait over.\n */\n private readonly onVisible = (): void => {\n if (document.hidden) return;\n document.removeEventListener(\"visibilitychange\", this.onVisible);\n const due = new Set(this.dueWhileHidden);\n this.dueWhileHidden.clear();\n for (const [id, entry] of this.entries) {\n if (entry.pollFailures === 0 || !polls(entry)) continue;\n entry.pollFailures = 0;\n due.add(id);\n }\n due.forEach((id) => this.pollNow(id));\n };\n\n /** Fetches a revision noted while the stream that just ended was running. */\n private catchUp(id: string): void {\n const entry = this.entry(id);\n if (!entry.stale) return;\n entry.stale = false;\n void this.connect(id);\n }\n\n private onEvent(id: string, event: ArtifactStreamEvent): void {\n const entry = this.entry(id);\n const snapshot = entry.snapshot;\n switch (event.type) {\n case \"reference\": {\n const { version, tag, is_owner, is_editable } = event.data ?? {};\n // Seen, so an edit's version noted later counts as newer.\n if (version) entry.versions.add(version);\n entry.tag = tag;\n const shown = snapshot.program;\n const newVersion = version !== snapshot.version;\n // A reconnect into the version being streamed sends it whole again.\n const reconnect = version !== undefined && version === entry.version;\n // A new version streams onto the screen as it's generated: an edit sends its prior\n // program first, then its patch, which the parser merges in. What's on screen stays\n // until its first delta replaces it.\n const overShown = shown !== null && newVersion;\n entry.version = version;\n if (!reconnect) {\n // The same version again (a rename, an access change, a re-read) loads out of sight.\n entry.target = shown === null || newVersion ? \"program\" : \"pending\";\n entry.pending = \"\";\n if (overShown) entry.settled ??= { program: shown, version: snapshot.version };\n }\n entry.replace = reconnect || overShown;\n // The stream resends the build's current step after its reference.\n this.update(id, {\n type: event.data?.type ?? snapshot.type,\n title: event.data?.title ?? snapshot.title,\n isOwner: is_owner ?? snapshot.isOwner,\n isEditable: is_editable ?? snapshot.isEditable,\n // A poll that found only a rename or an access change doesn't show as loading.\n isStreaming: snapshot.isStreaming || newVersion,\n step: undefined,\n error: null,\n ...(entry.target === \"program\" && { version, program: shown ?? \"\" }),\n });\n return;\n }\n case \"unchanged\":\n this.afterRead(id);\n return;\n case \"delta\": {\n const text = event.data?.text;\n if (typeof text !== \"string\") return;\n const replace = entry.replace;\n entry.replace = false;\n if (entry.target === \"pending\") entry.pending = (replace ? \"\" : entry.pending) + text;\n // The first content a build writes ends its step.\n else {\n this.update(id, {\n program: (replace ? \"\" : (snapshot.program ?? \"\")) + text,\n step: undefined,\n });\n }\n return;\n }\n case \"step\": {\n this.update(id, { step: stepOf(event.data) });\n return;\n }\n case \"end\": {\n const swapped =\n entry.target === \"pending\" ? { program: entry.pending, version: entry.version } : {};\n const replaced = this.endRead(entry) !== null;\n this.update(id, { ...swapped, isStreaming: false, step: undefined });\n if (replaced) this.markUpdated(id);\n this.catchUp(id);\n this.afterRead(id);\n return;\n }\n case \"error\": {\n const code = event.data?.code;\n const errorCode =\n code && ERROR_CODES.has(code) ? (code as ArtifactStreamErrorCode) : \"generation-failed\";\n const gone = errorCode === \"not-found\";\n // The next renderer to open it reads it again.\n if (gone) entry.started = false;\n this.update(id, {\n ...this.endRead(entry),\n // Deleted or unshared: nothing of it stays on screen.\n ...(gone && { program: null, version: undefined }),\n isStreaming: false,\n step: undefined,\n error: streamError(\n errorCode,\n event.data?.message ?? \"The artifact couldn't be generated.\",\n ),\n });\n this.catchUp(id);\n this.afterRead(id);\n }\n }\n }\n}\n\nconst stores = new WeakMap<ArtifactStorage, ArtifactStreamStore>();\nconst storeFor = (storage: ArtifactStorage): ArtifactStreamStore => {\n let store = stores.get(storage);\n if (!store) {\n store = new ArtifactStreamStore(storage);\n stores.set(storage, store);\n }\n return store;\n};\n\n/**\n * Tells every renderer showing `id` that `version` was just saved, so they load\n * it now instead of on their next poll.\n *\n * @internal Used by `@openuidev/react-ui/cloud`'s `useArtifactUpdate`.\n */\nexport function noteArtifactVersion(\n storage: ArtifactStorage,\n id: string,\n version: string | undefined,\n): void {\n stores.get(storage)?.noteVersion(id, version);\n}\n\n/**\n * Calls `watcher` on every change to any artifact's stream on `storage`, such as\n * a rename, an access change or a `not-found` a poll picked up. Returns a function\n * that stops it.\n *\n * @internal Used by `@openuidev/react-ui/cloud`'s artifact cache.\n */\nexport function watchArtifactStreams(\n storage: ArtifactStorage,\n watcher: ArtifactStreamWatcher,\n): () => void {\n return storeFor(storage).watch(watcher);\n}\n\n/** @category Types */\nexport interface UseArtifactStreamOptions {\n /** The artifact to show. */\n id: string | null | undefined;\n /** The version from the artifact's tool response. A new one fetches the newer revision. */\n version?: string;\n /** The artifact's saved content, when you keep artifacts in your own storage. Never streams. */\n content?: string;\n pollInterval?: number | false;\n}\n\n/** @category Types */\nexport interface ArtifactStreamState extends Omit<ArtifactStreamSnapshot, \"id\"> {\n /** Reconnects after a `network-error`. Undefined when there's nothing to retry. */\n retry?: () => void;\n /** For a data call refused because the artifact moved on: run the queries again, or show the error. */\n reportVersionMismatch?: (version: string) => Promise<\"rerun\" | \"show\">;\n}\n\nconst IDLE: ArtifactStreamState = {\n program: null,\n isStreaming: false,\n justUpdated: false,\n error: null,\n};\n\n/**\n * Streams an artifact in by id from the configured {@link ArtifactStorage},\n * sharing one stream per artifact across every component that shows it.\n *\n * - While it's generated, `program` grows and `isStreaming` is `true`.\n * - After a reload, it replays everything generated so far, then continues.\n * - A new version streams in live: an edit shows its prior program, then its patch\n * merging in. One that fails goes back to the version before it.\n * - Storages without `stream` are read once with `get`.\n * - With `pollInterval`, it picks up a newer version, a rename or an access\n * change, and the `not-found` error once the artifact is deleted or unshared.\n *\n * @internal Used by the `@openuidev/react-ui/cloud` renderers.\n */\nexport function useArtifactStream(\n options: MaybeRefOrGetter<UseArtifactStreamOptions>,\n): ComputedRef<ArtifactStreamState> {\n const storage = useArtifactStorage();\n const snapshotRef = shallowRef<ArtifactStreamSnapshot | null>(null);\n\n const resolved = computed(() => toValue(options));\n const activeStore = computed(() => {\n const opts = resolved.value;\n const ownContent = opts.content !== undefined;\n return storage && !ownContent && opts.id ? storeFor(storage) : null;\n });\n\n watch(\n [activeStore, () => resolved.value.id],\n ([store, id], _prev, onCleanup) => {\n if (!store || !id) {\n snapshotRef.value = null;\n return;\n }\n snapshotRef.value = store.getSnapshot(id);\n const unsub = store.subscribe(id, () => {\n snapshotRef.value = store.getSnapshot(id);\n });\n onCleanup(unsub);\n },\n { immediate: true },\n );\n\n watch(\n [activeStore, () => resolved.value.id, () => resolved.value.version],\n ([store, id, version]) => {\n if (store && id) store.noteVersion(id, version);\n },\n { immediate: true, flush: \"post\" },\n );\n\n watch(\n [activeStore, () => resolved.value.id, () => resolved.value.pollInterval],\n ([store, id, pollInterval], _prev, onCleanup) => {\n if (!store || !id || !pollInterval) return;\n const stop = store.poll(id, pollInterval);\n onCleanup(stop);\n },\n { immediate: true, flush: \"post\" },\n );\n\n return computed<ArtifactStreamState>(() => {\n const opts = resolved.value;\n const store = activeStore.value;\n const id = opts.id;\n const ownContent = opts.content !== undefined;\n if (ownContent) return { ...IDLE, program: opts.content! };\n\n const snapshot = snapshotRef.value;\n if (!snapshot) {\n if (id && !storage) {\n return {\n ...IDLE,\n error: streamError(\"not-found\", \"No artifact storage is configured.\"),\n };\n }\n return IDLE;\n }\n\n const awaiting = store && id ? store.awaits(id, opts.version) : false;\n const reportVersionMismatch =\n store && id ? (refused: string) => store.versionMismatch(id, refused) : undefined;\n const { id: _id, ...rest } = snapshot;\n const retry =\n snapshot.error?.code === \"network-error\" && store && id ? () => store.retry(id) : undefined;\n return { ...rest, isStreaming: rest.isStreaming || awaiting, retry, reportVersionMismatch };\n });\n}\n","/**\n * The interpreter runs an artifact's data tools on the developer's server.\n * This module bridges `Query()`/`Mutation()` calls from the renderer to it.\n */\n\n/** What the renderer sends your interpreter for each data tool call. @category Types */\nexport interface InterpreterRequest {\n /** The artifact's id. */\n id: string;\n /** The version on screen; OpenUI Cloud refuses a script run when the artifact has moved on. */\n version?: string;\n /** The query or tool to run. */\n name: string;\n arguments: Record<string, unknown>;\n}\n\n/** Your interpreter endpoint: it receives an `InterpreterRequest` as JSON and returns `{ result }`. @category Types */\nexport interface InterpreterConfig {\n url: string;\n /** Headers to send with each request, such as an auth header. */\n headers?: HeadersInit;\n}\n\n/** An async function that runs the request, such as a server action. @category Types */\nexport type InterpreterFunction = (request: InterpreterRequest) => Promise<unknown>;\n\n/** Where an artifact's data tools run. @category Types */\nexport type Interpreter = InterpreterConfig | InterpreterFunction;\n\n/** The shape react-lang's `Renderer` accepts as an MCP-style `toolProvider`. */\nexport interface InterpreterToolProvider {\n callTool(params: { name: string; arguments?: Record<string, unknown> }): Promise<{\n content: Array<{ type: string; text?: string }>;\n structuredContent?: unknown;\n }>;\n}\n\n/** @category Types */\nexport interface InterpreterToolProviderOptions {\n /** Read on every call, so the provider's identity can stay stable. */\n getInterpreter: () => Interpreter | undefined;\n /** The artifact the calls are for. */\n getRequest: () => { id: string | null | undefined; version?: string };\n /** Defaults to the global `fetch`. */\n fetch?: typeof fetch;\n /** Called when a call starts. */\n onStart?: (toolName: string) => void;\n /**\n * Called when a call settles; `message` is `null` on success. On failure, `detail`\n * has the error's `code`, if any, and the artifact `id` and `version` the call ran with.\n */\n onSettle?: (\n toolName: string,\n message: string | null,\n detail?: { code?: string; id: string; version?: string },\n ) => void;\n}\n\nfunction errorMessage(error: unknown): string | undefined {\n if (typeof error === \"string\") return error;\n if (error && typeof error === \"object\" && \"message\" in error) {\n const { message } = error as { message: unknown };\n if (typeof message === \"string\") return message;\n }\n return undefined;\n}\n\nfunction errorCode(error: unknown): string | undefined {\n if (error && typeof error === \"object\" && \"code\" in error) {\n const { code } = error as { code: unknown };\n if (typeof code === \"string\") return code;\n }\n return undefined;\n}\n\nasync function callEndpoint(\n fetchImpl: typeof fetch,\n config: InterpreterConfig,\n request: InterpreterRequest,\n): Promise<unknown> {\n const headers = new Headers(config.headers);\n headers.set(\"Content-Type\", \"application/json\");\n const res = await fetchImpl(config.url, {\n method: \"POST\",\n headers,\n body: JSON.stringify(request),\n });\n let body: { result?: unknown; error?: unknown } | null = null;\n try {\n body = (await res.json()) as { result?: unknown; error?: unknown };\n } catch {\n body = null;\n }\n if (!res.ok || (body?.error !== undefined && body.error !== null)) {\n const message = errorMessage(body?.error) ?? `Interpreter request failed: ${res.status}`;\n throw Object.assign(new Error(message), { code: errorCode(body?.error) });\n }\n return body?.result;\n}\n\n/**\n * A `toolProvider` for react-lang's `Renderer` that sends an artifact's data\n * tool calls to your interpreter, endpoint or function. Results come back as\n * `structuredContent`, so `Renderer` unwraps them the usual way.\n *\n * @internal Used by the `@openuidev/react-ui/cloud` renderers.\n */\nexport function createInterpreterToolProvider(\n options: InterpreterToolProviderOptions,\n): InterpreterToolProvider {\n return {\n async callTool({ name, arguments: args = {} }) {\n const interpreter = options.getInterpreter();\n const { id, version } = options.getRequest();\n if (!interpreter) throw new Error(\"This artifact has no interpreter.\");\n if (!id) throw new Error(\"This artifact has no id yet.\");\n\n const request: InterpreterRequest = {\n id,\n ...(version !== undefined && { version }),\n name,\n arguments: args,\n };\n options.onStart?.(name);\n try {\n const result =\n typeof interpreter === \"function\"\n ? await interpreter(request)\n : await callEndpoint(\n options.fetch ?? globalThis.fetch.bind(globalThis),\n interpreter,\n request,\n );\n options.onSettle?.(name, null);\n return { content: [], structuredContent: result ?? null };\n } catch (error) {\n const code = errorCode(error);\n options.onSettle?.(name, errorMessage(error) ?? \"The data tool failed.\", {\n ...(code !== undefined && { code }),\n id,\n ...(version !== undefined && { version }),\n });\n throw error;\n }\n },\n };\n}\n","/**\n * A minimal server-sent events reader over `fetch`.\n *\n * `EventSource` can't send the frontend-token header, so streams are read from\n * a `fetch` body instead. Handles `id:`, `event:` and multi-line `data:`\n * fields, `:` comments, and both `\\n` and `\\r\\n` line endings.\n */\n\nexport interface SseMessage {\n id?: string;\n event: string;\n data: string;\n}\n\nexport async function* readSse(body: ReadableStream<Uint8Array>): AsyncGenerator<SseMessage> {\n const reader = body.getReader();\n const decoder = new TextDecoder();\n let buffer = \"\";\n let id: string | undefined;\n let event = \"\";\n let data: string[] = [];\n\n const dispatch = (): SseMessage | null => {\n if (data.length === 0 && !event) return null;\n const message: SseMessage = { id, event: event || \"message\", data: data.join(\"\\n\") };\n event = \"\";\n data = [];\n return message;\n };\n\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n buffer += decoder.decode(value, { stream: true });\n\n let newline = buffer.search(/\\r?\\n/);\n while (newline !== -1) {\n const line = buffer.slice(0, newline);\n buffer = buffer.slice(buffer[newline] === \"\\r\" ? newline + 2 : newline + 1);\n\n if (line === \"\") {\n const message = dispatch();\n if (message) yield message;\n } else if (!line.startsWith(\":\")) {\n const colon = line.indexOf(\":\");\n const field = colon === -1 ? line : line.slice(0, colon);\n let value = colon === -1 ? \"\" : line.slice(colon + 1);\n if (value.startsWith(\" \")) value = value.slice(1);\n if (field === \"data\") data.push(value);\n else if (field === \"event\") event = value;\n else if (field === \"id\") id = value;\n }\n newline = buffer.search(/\\r?\\n/);\n }\n }\n const message = dispatch();\n if (message) yield message;\n } finally {\n reader.releaseLock();\n }\n}\n","/**\n * Wire types for the OpenUI Cloud /v1 API, plus the shared list envelope,\n * cursor rule, and request helper. Field-for-field mirrors of the API DTOs.\n */\n\n/** A conversation. `created_at` is unix SECONDS. */\nexport interface CloudConversation {\n id: string;\n object: \"conversation\";\n created_at: number;\n title?: string;\n metadata?: Record<string, unknown>;\n user_id?: string;\n app_id?: string;\n}\n\n/** A conversation item (full Responses item shape). */\nexport interface CloudConversationItem {\n id: string;\n object: \"conversation.item\";\n type: string; // message | function_call | function_call_output | ...\n role?: string;\n status?: string;\n content?: unknown;\n metadata?: Record<string, unknown>;\n created_at: number;\n call_id?: string;\n name?: string;\n arguments?: string;\n output?: unknown;\n}\n\n/** A stored artifact. `content` is the renderer-ready openui-lang program. */\nexport interface CloudArtifact {\n id: string;\n object: \"openui.artifact\";\n conversation_id?: string;\n kind: string; // 'slides' | 'report' | 'dashboard'\n name?: string;\n version?: string; // server bumps via String(Date.now()) when omitted\n content?: string;\n pinned?: boolean; // by the caller\n is_owner?: boolean;\n is_editable?: boolean;\n shares?: CloudArtifactShare[]; // only when is_editable\n created_at: number;\n updated_at?: number;\n}\n\n/** One share on an artifact. `created_at` is unix SECONDS. */\nexport interface CloudArtifactShare {\n object: \"openui.artifact.share\";\n type: \"user\" | \"group\";\n id: string;\n access: \"view\" | \"edit\";\n created_by: string;\n created_at: number;\n}\n\n/** List envelope shared by all paged endpoints. */\nexport interface CloudListEnvelope<T> {\n object: \"list\";\n data: T[];\n has_more: boolean;\n first_id?: string;\n last_id?: string;\n}\n\n/** Forward cursor: pass `last_id` back as `?after=` when there's another page. */\nexport function nextCursorOf(envelope: CloudListEnvelope<unknown>): string | undefined {\n return envelope.has_more && envelope.last_id ? envelope.last_id : undefined;\n}\n\n/**\n * Request helper: prefix baseUrl, set JSON content-type only when sending a\n * body, throw on non-2xx. `fetchImpl` is the token-injecting fetch — auth\n * lives there, never here.\n */\nexport function cloudRequest(fetchImpl: typeof fetch, baseUrl: string) {\n const base = baseUrl.replace(/\\/+$/, \"\");\n return async (path: string, init?: RequestInit): Promise<Response> => {\n const res = await fetchImpl(`${base}${path}`, {\n ...init,\n headers: {\n ...(init?.body ? { \"Content-Type\": \"application/json\" } : {}),\n ...init?.headers,\n },\n });\n if (!res.ok) {\n throw new Error(\n `OpenUI Cloud: ${init?.method ?? \"GET\"} ${path} failed: ${res.status} ${res.statusText}`,\n );\n }\n return res;\n };\n}\n","import type {\n Artifact,\n ArtifactAccess,\n ArtifactListParams,\n ArtifactShare,\n ArtifactShareTarget,\n ArtifactStorage,\n ArtifactStreamEvent,\n ArtifactStreamOptions,\n ArtifactSummary,\n} from \"../adapters/types\";\nimport { readSse } from \"./sse\";\nimport {\n cloudRequest,\n nextCursorOf,\n type CloudArtifact,\n type CloudArtifactShare,\n type CloudListEnvelope,\n} from \"./wire\";\n\nconst STREAM_EVENT_TYPES = new Set([\"reference\", \"delta\", \"step\", \"end\", \"error\"]);\n\nfunction parseJson(data: string): unknown {\n try {\n return JSON.parse(data);\n } catch {\n return null;\n }\n}\n\nexport interface CloudArtifactStorageOptions {\n /** OpenUI Cloud API origin, e.g. \"http://localhost:3102\". */\n baseUrl: string;\n /** The token-injecting fetch from createFctFetch. */\n fetch: typeof fetch;\n /** Default page size when the caller passes no limit. */\n pageLimit?: number;\n /**\n * Dashboards show each query's last result while it reloads; the results are\n * kept in OpenUI Cloud for 24 hours, per user. `false` turns this off. Default true.\n */\n cacheQueryResults?: boolean;\n}\n\nfunction toSummary(artifact: CloudArtifact): ArtifactSummary {\n return {\n id: artifact.id,\n title: artifact.name ?? artifact.id,\n type: artifact.kind,\n threadId: artifact.conversation_id ?? \"\",\n updatedAt: (artifact.updated_at ?? artifact.created_at) * 1000,\n ...(artifact.pinned !== undefined && { pinned: artifact.pinned }),\n ...(artifact.is_owner !== undefined && { isOwner: artifact.is_owner }),\n ...(artifact.is_editable !== undefined && { isEditable: artifact.is_editable }),\n ...(artifact.shares !== undefined && { shares: artifact.shares.map(toShare) }),\n ...(artifact.version !== undefined && { version: artifact.version }),\n };\n}\n\nfunction toShare(share: CloudArtifactShare): ArtifactShare {\n return {\n type: share.type,\n id: share.id,\n access: share.access,\n createdBy: share.created_by,\n createdAt: share.created_at * 1000,\n };\n}\n\nexport function cloudArtifactStorage({\n baseUrl,\n fetch: fetchImpl,\n pageLimit = 100,\n cacheQueryResults = true,\n}: CloudArtifactStorageOptions): ArtifactStorage {\n const request = cloudRequest(fetchImpl, baseUrl);\n const base = baseUrl.replace(/\\/+$/, \"\");\n\n return {\n /** GET /v1/artifacts?[name=][kind=…]&limit[&after=]. Omitting the\n * conversation scope lists across conversations, token-scoped to the user. */\n async list(params?: ArtifactListParams) {\n const query = new URLSearchParams();\n if (params?.name !== undefined && params.name !== \"\") query.set(\"name\", params.name);\n for (const type of params?.type ?? []) query.append(\"kind\", type);\n if (params?.pinned !== undefined) query.set(\"pinned\", String(params.pinned));\n if (params?.isOwner !== undefined) query.set(\"is_owner\", String(params.isOwner));\n if (params?.order !== undefined) query.set(\"order\", params.order);\n if (params?.cursor !== undefined) query.set(\"after\", params.cursor);\n query.set(\"limit\", String(params?.limit ?? pageLimit));\n const res = await request(`/v1/artifacts?${query.toString()}`);\n const envelope = (await res.json()) as CloudListEnvelope<CloudArtifact>;\n return {\n artifacts: envelope.data.map(toSummary),\n nextCursor: nextCursorOf(envelope),\n };\n },\n\n /** GET /v1/artifacts/:id → the stored openui-lang program (bare program;\n * the renderer's parser sniffs the `root = …` root). */\n async get(id: string): Promise<Artifact> {\n const res = await request(`/v1/artifacts/${encodeURIComponent(id)}`);\n const artifact = (await res.json()) as CloudArtifact;\n return { ...toSummary(artifact), content: artifact.content };\n },\n\n /** POST /v1/artifacts/:id {content?, name?}. New content (the edited inner program) is a\n * new version, which the server bumps; a title alone renames it. */\n async update(patch: {\n id: string;\n content?: unknown;\n title?: string;\n }): Promise<ArtifactSummary> {\n const body = {\n ...(patch.content !== undefined && {\n content:\n typeof patch.content === \"string\" ? patch.content : JSON.stringify(patch.content),\n }),\n ...(patch.title !== undefined && { name: patch.title }),\n };\n const res = await request(`/v1/artifacts/${encodeURIComponent(patch.id)}`, {\n method: \"POST\",\n body: JSON.stringify(body),\n });\n return toSummary((await res.json()) as CloudArtifact);\n },\n\n /** POST /v1/artifacts/:id/pin. */\n async pin(id: string): Promise<ArtifactSummary> {\n const res = await request(`/v1/artifacts/${encodeURIComponent(id)}/pin`, { method: \"POST\" });\n return toSummary((await res.json()) as CloudArtifact);\n },\n\n /** POST /v1/artifacts/:id/unpin. */\n async unpin(id: string): Promise<ArtifactSummary> {\n const res = await request(`/v1/artifacts/${encodeURIComponent(id)}/unpin`, {\n method: \"POST\",\n });\n return toSummary((await res.json()) as CloudArtifact);\n },\n\n /** DELETE /v1/artifacts/:id. */\n async delete(id: string): Promise<void> {\n await request(`/v1/artifacts/${encodeURIComponent(id)}`, { method: \"DELETE\" });\n },\n\n /** POST /v1/artifacts/:id/share {type, id, access}. Sends only those fields. */\n async share(\n id: string,\n share: ArtifactShareTarget & { access: ArtifactAccess },\n ): Promise<ArtifactSummary> {\n const res = await request(`/v1/artifacts/${encodeURIComponent(id)}/share`, {\n method: \"POST\",\n body: JSON.stringify({ type: share.type, id: share.id, access: share.access }),\n });\n return toSummary((await res.json()) as CloudArtifact);\n },\n\n /** POST /v1/artifacts/:id/unshare {type, id}. Sends only those fields. */\n async unshare(id: string, target: ArtifactShareTarget): Promise<ArtifactSummary> {\n const res = await request(`/v1/artifacts/${encodeURIComponent(id)}/unshare`, {\n method: \"POST\",\n body: JSON.stringify({ type: target.type, id: target.id }),\n });\n return toSummary((await res.json()) as CloudArtifact);\n },\n\n ...(cacheQueryResults && {\n /** GET /v1/artifacts/:id/query-results → the saved entries by key. */\n async getQueryResults(id: string): Promise<Record<string, unknown>> {\n const res = await request(`/v1/artifacts/${encodeURIComponent(id)}/query-results`);\n return ((await res.json()) as { results?: Record<string, unknown> }).results ?? {};\n },\n\n /** PUT /v1/artifacts/:id/query-results {key, value}. Not awaited; a failure is dropped. */\n putQueryResult(id: string, entry: { key: string; value: unknown }): void {\n request(`/v1/artifacts/${encodeURIComponent(id)}/query-results`, {\n method: \"PUT\",\n body: JSON.stringify(entry),\n }).catch(() => {});\n },\n }),\n\n /** GET /v1/artifacts/:id/stream[?fetch_latest=] (SSE). Replays a finished artifact\n * the same way; every connection starts from the whole program. 304: unchanged. */\n async *stream(\n id: string,\n options?: ArtifactStreamOptions,\n ): AsyncGenerator<ArtifactStreamEvent> {\n const query = options?.fetchLatest\n ? `?${new URLSearchParams({ fetch_latest: options.fetchLatest }).toString()}`\n : \"\";\n const res = await fetchImpl(`${base}/v1/artifacts/${encodeURIComponent(id)}/stream${query}`, {\n headers: { Accept: \"text/event-stream\" },\n signal: options?.signal,\n });\n if (res.status === 304) {\n yield { type: \"unchanged\" };\n return;\n }\n if (res.status === 404) {\n yield {\n type: \"error\",\n data: { code: \"not-found\", message: \"This artifact was deleted, or you can't see it.\" },\n };\n return;\n }\n // A 401 already got a fresh token (createFctFetch); retrying won't change either.\n if (res.status === 401 || res.status === 403) {\n yield {\n type: \"error\",\n data: {\n code: \"unauthorized\",\n message: \"Your session expired, or you can't see this artifact.\",\n },\n };\n return;\n }\n if (!res.ok || !res.body) {\n throw new Error(`OpenUI Cloud: stream ${id} failed: ${res.status} ${res.statusText}`);\n }\n for await (const message of readSse(res.body)) {\n if (!STREAM_EVENT_TYPES.has(message.event)) continue;\n yield {\n type: message.event,\n data: parseJson(message.data),\n } as ArtifactStreamEvent;\n }\n },\n };\n}\n","/**\n * Frontend session-token (fct_) lifecycle for the browser plane.\n *\n * - The token rides ONLY the `x-thesys-frontend-token` header; `Authorization`\n * on /v1/* always means the master key (server-side).\n * - Minting happens on YOUR backend (here, the /api/frontend-token proxy),\n * which calls the cloud mint endpoint with the master key and decides the\n * end-user identity server-side. The browser sends no body and never names\n * its own user.\n * - Mint response: { token: 'fct_…', expires_at: <unix seconds> }, TTL ~15 min.\n *\n * A fetch override (not static headers) is used so the token can refresh\n * mid-session — the chat provider captures the storage object once at mount.\n */\n\nexport const FRONTEND_TOKEN_HEADER = \"x-thesys-frontend-token\";\n\nexport interface MintFrontendTokenResponse {\n token: string;\n expires_at: number; // unix seconds\n}\n\nexport interface FrontendTokenManagerOptions {\n /** Your backend mint endpoint, e.g. \"/api/frontend-token\". */\n mintUrl: string;\n /** Override for tests / SSR. Defaults to globalThis.fetch. */\n fetch?: typeof fetch;\n /** Refresh this many seconds before expiry. Default 60. */\n refreshSkewSeconds?: number;\n}\n\nexport interface FrontendTokenManager {\n /** A token valid for at least refreshSkewSeconds (single-flight mint). */\n getToken(): Promise<string>;\n /** Drop the cached token. Pass the token that 401'd so a concurrent refresh\n * is not discarded. */\n invalidate(staleToken?: string): void;\n}\n\nexport function createFrontendTokenManager({\n mintUrl,\n fetch: customFetch,\n refreshSkewSeconds = 60,\n}: FrontendTokenManagerOptions): FrontendTokenManager {\n const fetchImpl = customFetch ?? globalThis.fetch.bind(globalThis);\n\n let token: string | null = null;\n let expiresAt = 0; // unix seconds\n let inflight: Promise<string> | null = null;\n\n const mint = async (): Promise<string> => {\n const res = await fetchImpl(mintUrl, { method: \"POST\" });\n if (!res.ok) {\n throw new Error(`frontend-token mint failed: ${res.status} ${res.statusText}`);\n }\n const body = (await res.json()) as MintFrontendTokenResponse;\n token = body.token;\n expiresAt = body.expires_at;\n return body.token;\n };\n\n return {\n async getToken(): Promise<string> {\n const nowSeconds = Date.now() / 1000;\n if (token !== null && nowSeconds < expiresAt - refreshSkewSeconds) return token;\n // Single-flight: callers during a refresh await the same mint.\n if (inflight === null) {\n inflight = mint().finally(() => {\n inflight = null;\n });\n }\n return inflight;\n },\n\n invalidate(staleToken?: string): void {\n if (staleToken === undefined || staleToken === token) {\n token = null;\n expiresAt = 0;\n }\n },\n };\n}\n\n/** Where a frontend token comes from: your mint endpoint's URL, or a function\n * returning a fresh token (you own caching). */\nexport type FrontendTokenSource = string | (() => Promise<string>);\n\n/** Normalize a token source into a FrontendTokenManager. */\nexport function toFrontendTokenManager(\n source: FrontendTokenSource,\n options: Omit<FrontendTokenManagerOptions, \"mintUrl\"> = {},\n): FrontendTokenManager {\n if (typeof source === \"string\") {\n return createFrontendTokenManager({ ...options, mintUrl: source });\n }\n let current: string | null = null;\n return {\n async getToken(): Promise<string> {\n current = await source();\n return current;\n },\n invalidate(staleToken?: string): void {\n if (staleToken === undefined || staleToken === current) current = null;\n },\n };\n}\n\n/**\n * Wrap a base fetch so every request carries a fresh token, with one reactive\n * retry on 401. The request is re-sent with the same init — pass re-readable\n * (string) bodies only.\n */\nexport function createFctFetch(\n tokens: FrontendTokenManager,\n baseFetch?: typeof fetch,\n): typeof fetch {\n const fetchImpl = baseFetch ?? globalThis.fetch.bind(globalThis);\n\n return async (input: RequestInfo | URL, init?: RequestInit): Promise<Response> => {\n const token = await tokens.getToken();\n const headers = new Headers(init?.headers);\n headers.set(FRONTEND_TOKEN_HEADER, token);\n\n let res = await fetchImpl(input, { ...init, headers });\n\n if (res.status === 401) {\n tokens.invalidate(token);\n const freshToken = await tokens.getToken();\n const retryHeaders = new Headers(init?.headers);\n retryHeaders.set(FRONTEND_TOKEN_HEADER, freshToken);\n res = await fetchImpl(input, { ...init, headers: retryHeaders });\n }\n\n return res;\n };\n}\n","import type { Message as ConversationMessage } from \"openai/resources/conversations/conversations\";\nimport type { ConversationItem } from \"openai/resources/conversations/items\";\nimport type {\n EasyInputMessage,\n ResponseFunctionToolCall,\n ResponseFunctionToolCallOutputItem,\n ResponseInputItem,\n ResponseInputMessageContentList,\n} from \"openai/resources/responses/responses\";\nimport type { AssistantMessage, Message, ToolMessage, UserMessage } from \"../../types\";\nimport type { MessageFormat } from \"../../types/messageFormat\";\n\n// ── Outbound (AG-UI → OpenAI Responses/Conversations input) ─────\n\n/**\n * Both the Responses API and the Conversations API accept\n * `ResponseInputItem[]` as input, so a single outbound conversion\n * works for both.\n *\n * Tool calls are *sibling items* of the assistant message, not nested\n * inside it. We flatten each AG-UI assistant message into:\n * 1. An `EasyInputMessage` with `role: \"assistant\"` (text part)\n * 2. One `ResponseFunctionToolCall` per tool call\n *\n * Tool result messages become `FunctionCallOutput` items.\n */\nfunction toItems(message: Message): ResponseInputItem[] {\n switch (message.role) {\n case \"user\":\n return [toInputMessage(message)];\n\n case \"assistant\": {\n const items: ResponseInputItem[] = [];\n\n if (message.content) {\n items.push({\n role: \"assistant\",\n content: message.content,\n type: \"message\",\n } satisfies EasyInputMessage);\n }\n\n if (message.toolCalls?.length) {\n for (const tc of message.toolCalls) {\n items.push({\n type: \"function_call\",\n call_id: tc.id,\n name: tc.function.name,\n arguments: tc.function.arguments,\n } satisfies ResponseFunctionToolCall);\n }\n }\n\n return items;\n }\n\n case \"tool\":\n return [\n {\n type: \"function_call_output\",\n call_id: message.toolCallId,\n output: message.content,\n } as ResponseInputItem,\n ];\n\n case \"system\":\n return [\n { role: \"system\", content: message.content, type: \"message\" } satisfies EasyInputMessage,\n ];\n\n case \"developer\":\n return [\n { role: \"developer\", content: message.content, type: \"message\" } satisfies EasyInputMessage,\n ];\n\n default:\n return [];\n }\n}\n\nfunction toInputMessage(message: UserMessage): EasyInputMessage {\n const content = message.content;\n\n if (typeof content === \"string\") {\n return { role: \"user\", content, type: \"message\" };\n }\n\n const parts: ResponseInputMessageContentList =\n content?.map((part) => {\n if (part.type === \"text\") {\n return { type: \"input_text\" as const, text: part.text };\n }\n if (part.type === \"binary\") {\n const url = part.url ?? `data:${part.mimeType};base64,${part.data ?? \"\"}`;\n return { type: \"input_image\" as const, image_url: url, detail: \"auto\" as const };\n }\n return { type: \"input_text\" as const, text: \"\" };\n }) ?? [];\n\n return { role: \"user\", content: parts, type: \"message\" };\n}\n\n// ── Inbound (OpenAI Conversations/Responses → AG-UI) ────────────\n\n/**\n * Converts `ConversationItem[]` (from the Conversations API) or\n * `ResponseItem[]` (from the Responses API) into AG-UI `Message[]`.\n *\n * Both APIs return items as a flat list with `type` discriminator:\n * - `\"message\"` → user / assistant / system / developer / tool message\n * - `\"function_call\"` → tool call (grouped into the preceding assistant)\n * - `\"function_call_output\"` → tool result\n *\n * The Conversations API `Message` type is a superset that also handles\n * `reasoning_text`, `summary_text`, and `text` content parts, as well\n * as additional roles like `tool` and `critic`.\n */\nfunction fromItems(items: ConversationItem[]): Message[] {\n const messages: Message[] = [];\n let currentAssistant: AssistantMessage | null = null;\n // Tool outputs for the in-progress assistant turn. BUFFERED rather than\n // pushed immediately so that an assistant turn with MULTIPLE tool calls\n // (e.g. thesys_get_artifact_description THEN thesys_generate_artifact)\n // reconstructs as ONE assistant message + its tool messages — matching the\n // live stream shape — instead of one assistant message PER tool call. The\n // latter renders a duplicate \"Behind the scenes\" group for every call on\n // reload, because each function_call_output used to flush the assistant.\n let pendingToolMsgs: ToolMessage[] = [];\n\n // Emit the in-progress assistant turn: the assistant message first, then its\n // buffered tool results (the renderer pairs tool messages that immediately\n // follow their assistant message).\n const flushAssistant = () => {\n if (currentAssistant) {\n messages.push(currentAssistant);\n currentAssistant = null;\n }\n if (pendingToolMsgs.length > 0) {\n messages.push(...pendingToolMsgs);\n pendingToolMsgs = [];\n }\n };\n\n for (const item of items) {\n switch (item.type) {\n case \"message\": {\n // A non-tool message ends the current assistant turn.\n flushAssistant();\n\n const msg = item as ConversationMessage;\n\n if (msg.role === \"assistant\") {\n currentAssistant = {\n id: msg.id,\n role: \"assistant\",\n content: extractTextContent(msg) || undefined,\n };\n } else if (msg.role === \"tool\") {\n // Conversations API can have tool messages with type: \"message\"\n messages.push({\n id: msg.id,\n role: \"tool\",\n content: extractTextContent(msg),\n toolCallId: \"\",\n } as ToolMessage);\n } else if (msg.role === \"user\") {\n messages.push(fromUserMessage(msg));\n } else {\n // system / developer / unknown / critic / discriminator\n const role = msg.role === \"developer\" ? \"developer\" : \"system\";\n messages.push({\n id: msg.id,\n role,\n content: extractTextContent(msg),\n } as Message);\n }\n break;\n }\n\n case \"function_call\": {\n const tc = item as { id?: string; call_id: string; name: string; arguments: string };\n\n if (!currentAssistant) {\n currentAssistant = { id: crypto.randomUUID(), role: \"assistant\" };\n }\n\n currentAssistant = {\n ...currentAssistant,\n toolCalls: [\n ...(currentAssistant.toolCalls ?? []),\n {\n id: tc.call_id,\n type: \"function\" as const,\n function: { name: tc.name, arguments: tc.arguments },\n },\n ],\n };\n break;\n }\n\n case \"function_call_output\": {\n // Buffer alongside the current assistant — do NOT flush here, so\n // sibling tool calls in the same turn stay on one assistant message.\n const output = item as ResponseFunctionToolCallOutputItem;\n pendingToolMsgs.push({\n id: output.id,\n role: \"tool\",\n content:\n typeof output.output === \"string\" ? output.output : JSON.stringify(output.output),\n toolCallId: output.call_id,\n } as ToolMessage);\n break;\n }\n\n case \"mcp_call\": {\n if (!currentAssistant) {\n currentAssistant = { id: crypto.randomUUID(), role: \"assistant\" };\n }\n\n currentAssistant = {\n ...currentAssistant,\n toolCalls: [\n ...(currentAssistant.toolCalls ?? []),\n {\n id: item.id,\n type: \"function\" as const,\n function: { name: item.name, arguments: item.arguments },\n },\n ],\n };\n\n const errorText =\n typeof item.error === \"string\" && item.error.length > 0 ? item.error : undefined;\n pendingToolMsgs.push({\n id: `${item.id}-output`,\n role: \"tool\",\n content: item.output ?? \"\",\n toolCallId: item.id,\n ...(errorText ? { error: errorText } : {}),\n } as ToolMessage);\n break;\n }\n\n default:\n // file_search, web_search, computer_call, reasoning, etc. — skip\n break;\n }\n }\n\n flushAssistant();\n\n return messages;\n}\n\n/**\n * Extract text content from a Conversations API `Message`.\n *\n * Handles the full content union:\n * - `output_text` (assistant output)\n * - `input_text` (user/system/developer input)\n * - `text` (generic text)\n * - `summary_text`, `reasoning_text` (appended)\n * - `refusal` (mapped to text)\n */\nfunction extractTextContent(msg: ConversationMessage): string {\n return msg.content\n .map((part) => {\n switch (part.type) {\n case \"output_text\":\n return part.text;\n case \"input_text\":\n return part.text;\n case \"text\":\n return part.text;\n case \"summary_text\":\n return part.text;\n case \"reasoning_text\":\n return part.text;\n case \"refusal\":\n return `[Refusal]: ${part.refusal}`;\n default:\n return \"\";\n }\n })\n .filter(Boolean)\n .join(\"\");\n}\n\nfunction fromUserMessage(msg: ConversationMessage): UserMessage {\n // Check if content has images/files — if so, use multipart\n const hasMedia = msg.content.some(\n (part) => part.type === \"input_image\" || part.type === \"input_file\",\n );\n\n if (!hasMedia) {\n return { id: msg.id, role: \"user\", content: extractTextContent(msg) };\n }\n\n const parts = msg.content.map(\n (part): { type: \"text\"; text: string } | { type: \"binary\"; url: string; mimeType: string } => {\n if (part.type === \"input_text\" || part.type === \"text\") {\n return { type: \"text\", text: part.text };\n }\n if (part.type === \"input_image\" && part.image_url) {\n return { type: \"binary\", url: part.image_url, mimeType: \"image/*\" };\n }\n return { type: \"text\", text: \"\" };\n },\n );\n\n return { id: msg.id, role: \"user\", content: parts };\n}\n\n// ── MessageFormat implementation ─────────────────────────────────\n\n/**\n * Converts between AG-UI message format and OpenAI's item-based format,\n * compatible with both the **Responses API** and **Conversations API**.\n *\n * AG-UI → OpenAI (toApi):\n * - Returns `ResponseInputItem[]` — works for both `responses.create({ input })`\n * and `conversations.items.create({ items })`\n * - Flattens assistant messages: text → `EasyInputMessage`, tool calls → `ResponseFunctionToolCall`\n *\n * OpenAI → AG-UI (fromApi):\n * - Accepts `ConversationItem[]` (or `ResponseItem[]`, which is a subset)\n * - Groups adjacent assistant messages + function_calls into `AssistantMessage`\n * - Handles Conversations-specific content types (`reasoning_text`, `summary_text`, etc.)\n */\nexport const openAIConversationMessageFormat: MessageFormat = {\n toApi(messages: Message[]): ResponseInputItem[] {\n return messages.flatMap(toItems);\n },\n\n fromApi(data: unknown): Message[] {\n return fromItems(data as ConversationItem[]);\n },\n};\n","import { openAIConversationMessageFormat } from \"../stream/formats/openai-conversation-message-format\";\nimport type { Message } from \"../types/message\";\nimport type { CloudConversationItem } from \"./wire\";\n\n/**\n * Convert /v1 conversation items to AG-UI Message[]. Each item is normalized\n * into the OpenAI ConversationItem shape that openAIConversationMessageFormat\n * .fromApi expects, then delegated — the grouping logic (function_call →\n * assistant toolCalls, function_call_output → ToolMessage) stays in the SDK.\n *\n * Normalizations:\n * - message content: assistant outputs arrive as part arrays; user inputs\n * arrive as a plain string → wrap strings as a single text part.\n * - function_call / function_call_output: a malformed row (missing the\n * top-level call_id/name/output) is skipped so it can't crash fromApi.\n * - other item types are skipped.\n */\nfunction normalizeItem(item: CloudConversationItem): Record<string, unknown> | null {\n switch (item.type) {\n case \"message\": {\n const content = item.content;\n const parts = Array.isArray(content)\n ? content\n : [\n {\n type: item.role === \"assistant\" ? \"output_text\" : \"input_text\",\n text: typeof content === \"string\" ? content : \"\",\n },\n ];\n return {\n id: item.id,\n type: \"message\",\n role: item.role ?? \"user\",\n status: item.status ?? \"completed\",\n content: parts,\n };\n }\n\n case \"function_call\": {\n if (typeof item.call_id !== \"string\" || typeof item.name !== \"string\") return null;\n return {\n id: item.id,\n type: \"function_call\",\n call_id: item.call_id,\n name: item.name,\n arguments:\n typeof item.arguments === \"string\"\n ? item.arguments\n : JSON.stringify(item.arguments ?? {}),\n };\n }\n\n case \"function_call_output\": {\n if (typeof item.call_id !== \"string\" || item.output === undefined) return null;\n return {\n id: item.id,\n type: \"function_call_output\",\n call_id: item.call_id,\n output: item.output,\n };\n }\n\n default:\n return null;\n }\n}\n\nexport function cloudItemsToMessages(items: CloudConversationItem[]): Message[] {\n const normalized = items\n .map(normalizeItem)\n .filter((i): i is Record<string, unknown> => i !== null);\n return openAIConversationMessageFormat.fromApi(normalized);\n}\n","import type { ThreadStorage } from \"../adapters/types\";\nimport type { Thread } from \"../store/types\";\nimport type { Message, UserMessage } from \"../types/message\";\nimport { cloudItemsToMessages } from \"./items\";\nimport {\n cloudRequest,\n nextCursorOf,\n type CloudConversation,\n type CloudConversationItem,\n type CloudListEnvelope,\n} from \"./wire\";\n\nexport interface CloudThreadStorageOptions {\n /** OpenUI Cloud API origin, e.g. \"http://localhost:3102\". */\n baseUrl: string;\n /** The token-injecting fetch from createFctFetch. */\n fetch: typeof fetch;\n /** Page size for list/items calls. */\n pageLimit?: number;\n}\n\n/** Hard stop for the items pagination loop. */\nconst MAX_ITEM_PAGES = 50;\n\nfunction toThread(conversation: CloudConversation): Thread {\n return {\n id: conversation.id,\n title: conversation.title ?? \"New conversation\",\n createdAt: conversation.created_at * 1000, // unix seconds → ms\n };\n}\n\n/** Client-side title from the first user message (the API does not auto-title). */\nexport function deriveTitle(firstMessage: UserMessage): string {\n const content = firstMessage.content;\n let text = \"\";\n if (typeof content === \"string\") {\n text = content;\n } else if (Array.isArray(content)) {\n for (const part of content) {\n if (part.type === \"text\" && typeof part.text === \"string\" && part.text.trim() !== \"\") {\n text = part.text;\n break;\n }\n }\n }\n text = text.trim();\n return (text === \"\" ? \"New conversation\" : text).slice(0, 60);\n}\n\nexport function cloudThreadStorage({\n baseUrl,\n fetch: fetchImpl,\n pageLimit = 100,\n}: CloudThreadStorageOptions): ThreadStorage {\n const request = cloudRequest(fetchImpl, baseUrl);\n\n return {\n /** GET /v1/conversations?limit[&after]. Newest-first. */\n async listThreads(cursor?: string) {\n const query = new URLSearchParams({ limit: String(pageLimit) });\n if (cursor !== undefined) query.set(\"after\", cursor);\n const res = await request(`/v1/conversations?${query.toString()}`);\n const envelope = (await res.json()) as CloudListEnvelope<CloudConversation>;\n return {\n threads: envelope.data.map(toThread),\n nextCursor: nextCursorOf(envelope),\n };\n },\n\n /** POST /v1/conversations {title}. No messages and no user_id — the user is\n * bound from the token; the first message arrives later on the generation\n * plane (conversation linkage). */\n async createThread(firstMessage: UserMessage): Promise<Thread> {\n const res = await request(`/v1/conversations`, {\n method: \"POST\",\n body: JSON.stringify({ title: deriveTitle(firstMessage) }),\n });\n return toThread((await res.json()) as CloudConversation);\n },\n\n /** GET /v1/conversations/:id/items?order=asc, paged, then mapped to Messages. */\n async getMessages(threadId: string): Promise<Message[]> {\n const items: CloudConversationItem[] = [];\n let after: string | undefined;\n for (let page = 0; page < MAX_ITEM_PAGES; page++) {\n const query = new URLSearchParams({\n order: \"asc\",\n limit: String(pageLimit),\n });\n if (after !== undefined) query.set(\"after\", after);\n const res = await request(\n `/v1/conversations/${encodeURIComponent(threadId)}/items?${query.toString()}`,\n );\n const envelope = (await res.json()) as CloudListEnvelope<CloudConversationItem>;\n items.push(...envelope.data);\n after = nextCursorOf(envelope);\n if (after === undefined) break;\n }\n return cloudItemsToMessages(items);\n },\n\n /** POST /v1/conversations/:id {title}. */\n async updateThread(thread: Thread): Promise<Thread> {\n const res = await request(`/v1/conversations/${encodeURIComponent(thread.id)}`, {\n method: \"POST\",\n body: JSON.stringify({ title: thread.title }),\n });\n return toThread((await res.json()) as CloudConversation);\n },\n\n /** DELETE /v1/conversations/:id (soft delete). */\n async deleteThread(id: string): Promise<void> {\n await request(`/v1/conversations/${encodeURIComponent(id)}`, {\n method: \"DELETE\",\n });\n },\n };\n}\n","import { computed, toValue, type MaybeRefOrGetter, type ComputedRef } from \"vue\";\nimport type { ChatStorage } from \"../adapters/types\";\n\nimport { cloudArtifactStorage } from \"./artifactStorage\";\nimport {\n createFctFetch,\n toFrontendTokenManager,\n type FrontendTokenSource,\n} from \"./frontendTokenManager\";\nimport { cloudThreadStorage } from \"./threadStorage\";\n\n/** Which storage surfaces useOpenuiCloudStorage wires. */\nexport interface OpenuiCloudFeatures {\n /** Stored-artifact reads + edits. Default true. */\n artifact?: boolean;\n}\n\nexport interface OpenuiCloudOptions {\n /**\n * The OpenUI Cloud API origin. Defaults to \"https://api.thesys.dev\" (the\n * storage layer appends `/v1/...`). Set this to e.g. \"http://localhost:3102\"\n * to run against a local stack. The browser calls this directly with the\n * fct_ token — there is no same-origin proxy in between.\n */\n apiBaseUrl?: string;\n /**\n * Where the short-lived fct_ session token comes from — either a URL of your\n * backend mint endpoint (POST → { token, expires_at }, cached + refreshed\n * here) or a function returning a fresh token (you own caching). The token\n * rides the `x-thesys-frontend-token` header on every /v1 call. The frontend\n * token is minted server-side; the master key never reaches the browser.\n */\n token: FrontendTokenSource;\n /** Which storage surfaces to wire. Omit to enable all. */\n features?: OpenuiCloudFeatures;\n /**\n * Dashboards show each query's last result while it reloads; the results are\n * kept in OpenUI Cloud for 24 hours, per user. `false` turns this off. Default true.\n */\n cacheQueryResults?: boolean;\n /** fetch override (tests / SSR). Defaults to globalThis.fetch. */\n fetch?: typeof fetch;\n /** Refresh the cached token this many seconds before expiry (URL form). Default 60. */\n refreshSkewSeconds?: number;\n}\n\n/** OpenUI Cloud API origin used when `apiBaseUrl` is omitted. The storage\n * layer appends `/v1/...` to it. */\nconst DEFAULT_API_BASE_URL = \"https://api.thesys.dev\";\n\n/**\n * One-call browser wiring for OpenUI Cloud, as a hook: a memoised `ChatStorage`\n * backed by the /v1 API, authenticated per-request with an fct_ session token.\n * Pass it straight to `<AgentInterface storage={…} />`.\n *\n * As a hook the storage (and its fct_ token manager) is created on mount and\n * re-created only when its options change. Tokens are minted lazily on the first\n * storage request. ChatProvider captures storage at mount; remount the provider\n * when switching users or storage configurations.\n *\n * This is the READ/EDIT plane (browser → /v1/* with the fct_ token). Generation\n * is the separate ChatLLM plane (browser → your backend → /v1/embed/responses\n * with the master key).\n */\nexport function useOpenuiCloudStorage(\n options: MaybeRefOrGetter<OpenuiCloudOptions>,\n): ComputedRef<ChatStorage> {\n let previous: readonly unknown[] | undefined;\n let storage: ChatStorage;\n return computed(() => {\n const current = toValue(options);\n // Match frozen React useMemo dependencies exactly: only artifact is\n // normalized; omitted origin/skew are distinct from explicit defaults.\n const dependencies = [\n current.apiBaseUrl,\n current.token,\n current.fetch,\n current.refreshSkewSeconds,\n current.cacheQueryResults,\n current.features?.artifact ?? true,\n ];\n if (!previous || dependencies.some((value, index) => !Object.is(value, previous![index]))) {\n storage = createCloudStorage(current);\n previous = dependencies;\n }\n return storage;\n });\n}\n\n/** The actual storage wiring — a pure factory with no Vue, memoised by the\n * composable above. */\nfunction createCloudStorage(options: OpenuiCloudOptions): ChatStorage {\n const tokens = toFrontendTokenManager(options.token, {\n fetch: options.fetch,\n refreshSkewSeconds: options.refreshSkewSeconds,\n });\n const fctFetch = createFctFetch(tokens, options.fetch);\n const artifactOn = options.features?.artifact ?? true;\n const baseUrl = options.apiBaseUrl ?? DEFAULT_API_BASE_URL;\n\n const storage: ChatStorage = {\n thread: cloudThreadStorage({ baseUrl, fetch: fctFetch }),\n };\n if (artifactOn) {\n storage.artifact = cloudArtifactStorage({\n baseUrl,\n fetch: fctFetch,\n cacheQueryResults: options.cacheQueryResults,\n });\n }\n return storage;\n}\n","import { inject, toValue, type InjectionKey, type MaybeRefOrGetter } from \"vue\";\n\n/** @internal Set by `OpenUICloudProvider`'s `pollInterval`. */\nexport const ArtifactPollIntervalContext = Symbol(\"ArtifactPollIntervalContext\") as InjectionKey<\n MaybeRefOrGetter<number | false | undefined>\n>;\n\n/**\n * How often open artifacts check for changes, as set on `OpenUICloudProvider`.\n * Undefined when it doesn't say.\n */\nexport const useArtifactPollInterval = (): number | false | undefined =>\n toValue(inject(ArtifactPollIntervalContext, undefined));\n","import { computed, defineComponent, provide, type PropType } from \"vue\";\nimport { ArtifactStorageContext } from \"../store/ArtifactStorageContext\";\nimport type { FrontendTokenSource } from \"./frontendTokenManager\";\nimport { useOpenuiCloudStorage, type OpenuiCloudOptions } from \"./openuiCloud\";\nimport { ArtifactPollIntervalContext } from \"./pollInterval\";\n\n/** @category Types */\nexport interface OpenUICloudProviderProps extends Omit<OpenuiCloudOptions, \"features\"> {\n /**\n * How often every open artifact checks for a newer version, a rename or an\n * access change, in ms (at least 3s), unless its renderer sets its own.\n * `false`: never. Default 30s.\n */\n pollInterval?: number | false;\n}\n\nexport const OpenUICloudProvider = defineComponent({\n name: \"OpenUICloudProvider\",\n props: {\n apiBaseUrl: { type: String as PropType<string | undefined>, default: undefined },\n token: {\n type: [String, Function] as PropType<FrontendTokenSource>,\n required: true as const,\n },\n cacheQueryResults: { type: Boolean as PropType<boolean | undefined>, default: undefined },\n fetch: { type: Function as PropType<typeof fetch | undefined>, default: undefined },\n refreshSkewSeconds: { type: Number as PropType<number | undefined>, default: undefined },\n pollInterval: {\n type: [Number, Boolean] as PropType<number | false | undefined>,\n default: undefined,\n },\n },\n setup(props, { slots }) {\n const stableReadToken = () => {\n const current = props.token;\n return typeof current === \"string\" ? Promise.resolve(current) : current();\n };\n const storage = useOpenuiCloudStorage(() => ({\n apiBaseUrl: props.apiBaseUrl,\n token: typeof props.token === \"string\" ? props.token : stableReadToken,\n cacheQueryResults: props.cacheQueryResults,\n fetch: props.fetch,\n refreshSkewSeconds: props.refreshSkewSeconds,\n }));\n\n const artifactStorage = computed(() => storage.value.artifact ?? null);\n provide(ArtifactStorageContext, artifactStorage.value);\n provide(ArtifactPollIntervalContext, () => props.pollInterval);\n\n return () => slots.default?.() ?? null;\n },\n});\n","import {\n computed,\n getCurrentInstance,\n getCurrentScope,\n inject,\n onScopeDispose,\n shallowRef,\n ssrContextKey,\n watchEffect,\n type ComputedRef,\n} from \"vue\";\nimport type { StoreApi } from \"zustand/vanilla\";\n\n/** Vue binding for the pinned Zustand vanilla store; the owner scope owns cleanup. */\nexport function useStore<S, T>(store: StoreApi<S>, selector: (state: S) => T): ComputedRef<T> {\n if (!getCurrentScope())\n throw new Error(\"useStore must be used within a Vue setup or effect scope\");\n // Server scopes are not unmounted. Like useSyncExternalStore, SSR reads a\n // snapshot without installing a listener; use only Vue's public SSR key.\n if (getCurrentInstance() && inject(ssrContextKey, null) !== null) {\n return computed(() => selector(store.getInitialState()));\n }\n const snapshot = shallowRef(store.getState());\n const selected = shallowRef<T>();\n // Eager selection is necessary on Vue 3.3: a lazy computed invalidates its\n // consumers even when its next value is identical. Track external ref/getter\n // dependencies too (e.g. a changing detailed-view ID).\n watchEffect(\n () => {\n selected.value = selector(snapshot.value);\n },\n { flush: \"sync\" },\n );\n const unsubscribe = store.subscribe((state) => {\n snapshot.value = state;\n });\n snapshot.value = store.getState();\n onScopeDispose(unsubscribe);\n return computed(() => selected.value as T);\n}\n\n/** Per-consumer useShallow equivalent for the default thread slices only. */\nexport function shallowSelector<S, T extends object>(selector: (state: S) => T): (state: S) => T {\n let previous: T | undefined;\n return (state) => {\n const next = selector(state);\n const keys = Object.keys(next) as Array<keyof T>;\n if (\n previous &&\n keys.length === Object.keys(previous).length &&\n keys.every(\n (key) =>\n Object.prototype.hasOwnProperty.call(previous, key) &&\n Object.is(previous![key], next[key]),\n )\n )\n return previous;\n previous = next;\n return next;\n };\n}\n","import { inject, type InjectionKey } from \"vue\";\nimport type { StoreApi } from \"zustand/vanilla\";\nimport type { DetailedViewStore } from \"./detailedViewTypes\";\n\n/** @internal React context holding the detailed-view Zustand store. Provided by `ChatProvider`. */\nexport const DetailedViewContext = Symbol(\n \"DetailedViewContext\",\n) as InjectionKey<StoreApi<DetailedViewStore> | null>;\n\n/**\n * Returns the raw detailed-view Zustand store for advanced use cases.\n *\n * Prefer {@link useDetailedView} or {@link useActiveDetailedView} for most cases —\n * this hook is an escape hatch when you need direct store access.\n *\n * @category Hooks\n * @returns The Zustand `StoreApi<DetailedViewStore>` instance\n * @throws Error if called outside a `<ChatProvider>`\n */\nexport const useDetailedViewStore = (): StoreApi<DetailedViewStore> => {\n const store = inject(DetailedViewContext, null);\n if (!store) {\n throw new Error(\"useDetailedViewStore must be used within a <ChatProvider>\");\n }\n return store;\n};\n","import { computed } from \"vue\";\nimport { useStore } from \"../store/useStore\";\nimport { useDetailedViewStore } from \"../store/DetailedViewContext\";\nexport function useActiveDetailedView() {\n const store = useDetailedViewStore();\n const activeDetailedViewId = useStore(store, (state) => state.activeDetailedViewId);\n const isDetailedViewActive = computed(() => activeDetailedViewId.value !== null);\n const closeDetailedView = () => {\n if (store.getState().activeDetailedViewId !== null)\n store.getState().setActiveDetailedView(null);\n };\n return { activeDetailedViewId, isDetailedViewActive, closeDetailedView };\n}\n","import { inject, type InjectionKey } from \"vue\";\nimport type { StoreApi } from \"zustand/vanilla\";\nimport type { ThreadContextStore } from \"./threadContextTypes\";\n\n/** @internal React context holding the ThreadContext Zustand store. Provided by `ChatProvider`. */\nexport const ThreadContextContext = Symbol(\n \"ThreadContextContext\",\n) as InjectionKey<StoreApi<ThreadContextStore> | null>;\n\n/**\n * Returns the raw ThreadContext Zustand store for advanced use cases.\n *\n * Prefer {@link useDetailedView}, {@link useActiveDetailedView}, {@link useAppList},\n * or {@link useArtifactList} for most cases — this hook is an escape hatch when you\n * need direct store access.\n *\n * @category Hooks\n * @returns The Zustand `StoreApi<ThreadContextStore>` instance\n * @throws Error if called outside a `<ChatProvider>`\n */\nexport const useThreadContextStore = (): StoreApi<ThreadContextStore> => {\n const store = inject(ThreadContextContext, null);\n if (!store) {\n throw new Error(\"useThreadContextStore must be used within a <ChatProvider>\");\n }\n return store;\n};\n","import { computed, toValue, type MaybeRefOrGetter } from \"vue\";\nimport { useStore } from \"../store/useStore\";\nimport { useThreadContextStore } from \"../store/ThreadContextContext\";\nimport type { ArtifactEntry } from \"../store/threadContextTypes\";\nexport interface ArtifactListFilter {\n type?: string[];\n}\nexport function useArtifactList(filter?: MaybeRefOrGetter<ArtifactListFilter | undefined>) {\n const store = useThreadContextStore();\n const artifacts = useStore(store, (state) => state.artifacts);\n let previous:\n | {\n artifacts: Record<string, ArtifactEntry[]>;\n typeKey: string | undefined;\n value: Record<string, ArtifactEntry[]>;\n }\n | undefined;\n return computed(() => {\n const typeKey = toValue(filter)?.type?.join(\" \");\n const current = artifacts.value;\n if (previous && previous.artifacts === current && previous.typeKey === typeKey)\n return previous.value;\n if (typeKey === undefined) {\n previous = { artifacts: current, typeKey, value: current };\n return current;\n }\n const allowed = new Set(typeKey.split(\" \"));\n const result: Record<string, ArtifactEntry[]> = {};\n for (const [id, versions] of Object.entries(current)) {\n const latest = versions[versions.length - 1];\n if (latest && allowed.has(latest.type)) result[id] = versions;\n }\n previous = { artifacts: current, typeKey, value: result };\n return result;\n });\n}\n","import { inject, type InjectionKey } from \"vue\";\nimport type { ArtifactRendererConfig } from \"./artifactRendererTypes\";\n\n/**\n * Pre-built lookup structure for artifact-renderer matching.\n *\n * Built once at `ChatProvider` mount from the user-supplied `artifactRenderers`\n * array. Subsequent prop changes are ignored (with a dev-mode warning) so\n * renderer registration stays stable for the lifetime of the provider.\n *\n * @internal\n */\nexport type ArtifactRendererRegistry = {\n /** toolName → renderer. A renderer with several toolNames appears once per name. */\n byToolName: Map<string, ArtifactRendererConfig<unknown>>;\n /** artifact type → renderer. Used by the artifact browser to render stored artifacts. */\n byType: Map<string, ArtifactRendererConfig<unknown>>;\n};\n\nconst isDev = () => typeof process !== \"undefined\" && process.env?.[\"NODE_ENV\"] !== \"production\";\n\n/**\n * Builds an {@link ArtifactRendererRegistry} from a list of configs.\n *\n * First-wins on duplicate `toolName` or `type`: subsequent registrations are\n * ignored with a dev-mode warning so the user can reorder their array\n * (custom renderers should come *before* SDK defaults).\n *\n * @internal\n */\nexport function buildArtifactRendererRegistry(\n configs: ReadonlyArray<ArtifactRendererConfig<any>>,\n): ArtifactRendererRegistry {\n const byToolName = new Map<string, ArtifactRendererConfig<unknown>>();\n const byType = new Map<string, ArtifactRendererConfig<unknown>>();\n\n for (const config of configs) {\n const toolNames = Array.isArray(config.toolName) ? config.toolName : [config.toolName];\n for (const name of toolNames) {\n if (byToolName.has(name)) {\n if (isDev()) {\n console.warn(\n `[OpenUI] Artifact renderer for toolName \"${name}\" was ignored ` +\n `(already registered earlier in the array).`,\n );\n }\n continue;\n }\n byToolName.set(name, config);\n }\n\n if (byType.has(config.type)) {\n if (isDev()) {\n console.warn(\n `[OpenUI] Artifact renderer for type \"${config.type}\" was ignored for type-based ` +\n `lookup (already registered earlier in the array).`,\n );\n }\n continue;\n }\n byType.set(config.type, config);\n }\n\n return { byToolName, byType };\n}\n\n/** Resolves the renderer matching a tool name, or `null`. @internal */\nexport function lookupArtifactRenderer(\n registry: ArtifactRendererRegistry,\n toolName: string,\n): ArtifactRendererConfig<unknown> | null {\n return registry.byToolName.get(toolName) ?? null;\n}\n\n/** Resolves the renderer matching an artifact type, or `null`. @internal */\nexport function lookupArtifactRendererByType(\n registry: ArtifactRendererRegistry,\n type: string,\n): ArtifactRendererConfig<unknown> | null {\n return registry.byType.get(type) ?? null;\n}\n\n/** @internal React context holding the renderer registry. Provided by `ChatProvider`. */\nexport const ArtifactRenderersContext = Symbol(\n \"ArtifactRenderersContext\",\n) as InjectionKey<ArtifactRendererRegistry | null>;\n\n/**\n * Returns the raw artifact-renderer registry for advanced use cases.\n *\n * Prefer {@link useArtifactRenderer} for resolving a specific tool name —\n * this hook is an escape hatch for custom dispatching.\n *\n * Returns `null` if no `artifactRenderers` were provided to the `<ChatProvider>` —\n * this is not an error since renderers are optional.\n *\n * @category Hooks\n */\nexport const useArtifactRendererRegistry = (): ArtifactRendererRegistry | null => {\n return inject(ArtifactRenderersContext, null);\n};\n","import { computed, toValue, type MaybeRefOrGetter } from \"vue\";\nimport {\n lookupArtifactRenderer,\n useArtifactRendererRegistry,\n} from \"../store/ArtifactRenderersContext\";\nexport function useArtifactRenderer(toolName: MaybeRefOrGetter<string>) {\n const registry = useArtifactRendererRegistry();\n return computed(() => (registry ? lookupArtifactRenderer(registry, toValue(toolName)) : null));\n}\n","import { toValue, type MaybeRefOrGetter } from \"vue\";\nimport { useStore } from \"../store/useStore\";\nimport { useDetailedViewStore } from \"../store/DetailedViewContext\";\nexport function useDetailedView(viewId: MaybeRefOrGetter<string>) {\n const store = useDetailedViewStore();\n const isActive = useStore(store, (state) => state.activeDetailedViewId === toValue(viewId));\n const open = () => store.getState().setActiveDetailedView(toValue(viewId));\n const close = () => {\n if (store.getState().activeDetailedViewId === toValue(viewId))\n store.getState().setActiveDetailedView(null);\n };\n const toggle = () => {\n const id = toValue(viewId);\n store\n .getState()\n .setActiveDetailedView(store.getState().activeDetailedViewId === id ? null : id);\n };\n return { isActive, open, close, toggle };\n}\n","import { useStore } from \"../store/useStore\";\nimport { useDetailedViewStore } from \"../store/DetailedViewContext\";\nexport function useDetailedViewPortalTarget() {\n const store = useDetailedViewStore();\n const node = useStore(store, (state) => state._detailedViewPanelNode);\n return {\n node,\n setNode: (node: HTMLElement | null) => store.getState()._setDetailedViewPanelNode(node),\n };\n}\n","import { defineComponent, inject, provide, type InjectionKey, type PropType } from \"vue\";\nimport type { Message } from \"../types\";\nexport const MessageContext = Symbol(\"MessageContext\") as InjectionKey<{\n readonly message: Message;\n}>;\nexport function useMessage() {\n const context = inject(MessageContext, null);\n if (!context) throw new Error(\"useMessage must be used within a MessageProvider\");\n return context;\n}\nexport const MessageProvider = defineComponent({\n name: \"OpenUIMessageProvider\",\n props: { message: { type: Object as PropType<Message>, required: true } },\n setup(props, { slots }) {\n provide(MessageContext, {\n get message() {\n return props.message;\n },\n });\n return () => slots.default?.();\n },\n});\n","import { inject, type InjectionKey } from \"vue\";\nimport type { StoreApi } from \"zustand/vanilla\";\nimport type { ChatStore } from \"./types\";\n\nexport const ChatContext = Symbol(\"ChatContext\") as InjectionKey<StoreApi<ChatStore> | null>;\n\nexport const useChatStore = (): StoreApi<ChatStore> => {\n const store = inject(ChatContext, null);\n if (!store) {\n throw new Error(\"useChatStore must be used within a <ChatProvider>\");\n }\n return store;\n};\n","import { shallowSelector, useStore } from \"../store/useStore\";\nimport type { ComputedRef } from \"vue\";\nimport { useChatStore } from \"../store/ChatContext\";\nimport type {\n ChatStore,\n ThreadActions,\n ThreadListActions,\n ThreadListState,\n ThreadState,\n} from \"../store/types\";\n\ntype ThreadSlice = ThreadState & ThreadActions;\ntype ThreadListSlice = ThreadListState & ThreadListActions;\n\nconst threadSelector = (s: ChatStore): ThreadSlice => ({\n messages: s.messages,\n isRunning: s.isRunning,\n isLoadingMessages: s.isLoadingMessages,\n threadError: s.threadError,\n executingToolCallIds: s.executingToolCallIds,\n processMessage: s.processMessage,\n appendMessages: s.appendMessages,\n updateMessage: s.updateMessage,\n setMessages: s.setMessages,\n deleteMessage: s.deleteMessage,\n cancelMessage: s.cancelMessage,\n});\n\nconst threadListSelector = (s: ChatStore): ThreadListSlice => ({\n threads: s.threads,\n isLoadingThreads: s.isLoadingThreads,\n threadListError: s.threadListError,\n selectedThreadId: s.selectedThreadId,\n hasMoreThreads: s.hasMoreThreads,\n loadThreads: s.loadThreads,\n loadMoreThreads: s.loadMoreThreads,\n switchToNewThread: s.switchToNewThread,\n createThread: s.createThread,\n selectThread: s.selectThread,\n updateThread: s.updateThread,\n deleteThread: s.deleteThread,\n});\n\nexport function useThread(): ComputedRef<ThreadSlice>;\nexport function useThread<T>(selector: (state: ThreadSlice) => T): ComputedRef<T>;\nexport function useThread<T>(selector?: (state: ThreadSlice) => T) {\n const store = useChatStore();\n if (selector) {\n return useStore(store, (s) => selector(threadSelector(s)));\n }\n return useStore(store, shallowSelector(threadSelector));\n}\n\nexport function useThreadList(): ComputedRef<ThreadListSlice>;\nexport function useThreadList<T>(selector: (state: ThreadListSlice) => T): ComputedRef<T>;\nexport function useThreadList<T>(selector?: (state: ThreadListSlice) => T) {\n const store = useChatStore();\n if (selector) {\n return useStore(store, (s) => selector(threadListSelector(s)));\n }\n return useStore(store, shallowSelector(threadListSelector));\n}\n","import type { AssistantMessage, Message, ToolCall, ToolMessage } from \"../types\";\n\n/**\n * Real per-call lifecycle of a tool invocation.\n *\n * Derived from AG-UI stream events (never faked from `!!content`):\n * - `streaming` — arguments are still arriving (`TOOL_CALL_ARGS` deltas).\n * - `executing` — arguments closed (`TOOL_CALL_END` seen), awaiting a result.\n * - `complete` — a `TOOL_CALL_RESULT` landed without an error.\n * - `error` — a `TOOL_CALL_RESULT`/`RUN_ERROR` carried a failure.\n *\n * @category Types\n */\nexport type ToolCallStatus = \"streaming\" | \"executing\" | \"complete\" | \"error\";\n\n/**\n * Single source of truth for one tool call + its (optional) result, used by the\n * UI layer instead of reading raw `ToolCall`/`ToolMessage` separately.\n *\n * Discriminated by `status` so impossible states are unrepresentable: the view\n * literally cannot read `result`/`errorText` in a state where they don't exist,\n * nor render an error as a success.\n *\n * - `streaming` → args still arriving; `input` is `Partial<T>`, no result.\n * - `executing` → args closed; `input` is `T`, awaiting result.\n * - `complete` → result landed OK; `input` is `T`, `result` is a string.\n * - `error` → result landed with a failure; `errorText` present.\n *\n * `input` is {@link partialJSONParse}'d **once** by the selector — never a raw\n * string for the consumer to parse.\n *\n * @category Types\n */\nexport type ToolActivity<T = unknown> =\n | {\n status: \"streaming\";\n id: string;\n toolName: string;\n toolCall: ToolCall;\n toolMessage: null;\n input: Partial<T>;\n result?: undefined;\n isError: false;\n errorText?: undefined;\n statusMessage?: string;\n }\n | {\n status: \"executing\";\n id: string;\n toolName: string;\n toolCall: ToolCall;\n toolMessage: null;\n input: T;\n result?: undefined;\n isError: false;\n errorText?: undefined;\n statusMessage?: string;\n }\n | {\n status: \"complete\";\n id: string;\n toolName: string;\n toolCall: ToolCall;\n toolMessage: ToolMessage;\n input: T;\n result: string;\n isError: false;\n errorText?: undefined;\n statusMessage?: string;\n }\n | {\n status: \"error\";\n id: string;\n toolName: string;\n toolCall: ToolCall;\n toolMessage: ToolMessage;\n input: T;\n result: string;\n isError: true;\n errorText?: string;\n statusMessage?: string;\n };\n\nconst isDev = () => typeof process !== \"undefined\" && process.env?.[\"NODE_ENV\"] !== \"production\";\n\n/**\n * Closes dangling brackets/quotes for a partial (mid-stream) JSON string so it\n * can be parsed for a best-effort snapshot. Conservative: only trims a trailing\n * object key that is provably awaiting a value (signalled by a trailing colon),\n * leaving complete array/values intact.\n */\nfunction balanceOpenJSON(raw: string): string {\n const closers: string[] = [];\n let inString = false;\n let escaped = false;\n\n for (let i = 0; i < raw.length; i++) {\n const ch = raw[i];\n if (inString) {\n if (escaped) escaped = false;\n else if (ch === \"\\\\\") escaped = true;\n else if (ch === '\"') inString = false;\n continue;\n }\n if (ch === '\"') inString = true;\n else if (ch === \"{\") closers.push(\"}\");\n else if (ch === \"[\") closers.push(\"]\");\n else if (ch === \"}\" || ch === \"]\") closers.pop();\n }\n\n let out = raw;\n if (inString) {\n // Mid-string: drop a dangling escape, then close the string literal.\n if (escaped) out = out.slice(0, -1);\n out += '\"';\n }\n\n // Drop a dangling object key with no value yet (`… \"key\":`). The colon is the\n // reliable \"awaiting value\" signal — a trailing string WITHOUT a colon may be\n // a complete array element/value, so leave it. Then drop any exposed comma.\n out = out.replace(/(?:,\\s*)?\"(?:[^\"\\\\]|\\\\.)*\"\\s*:\\s*$/, \"\");\n out = out.replace(/,\\s*$/, \"\");\n\n for (let i = closers.length - 1; i >= 0; i--) out += closers[i];\n return out;\n}\n\n/**\n * Tolerant single-pass JSON parse for streamed tool arguments. Tries a straight\n * parse, then a bracket-balanced parse for partial input. **Never throws** —\n * returns `{}` when nothing parseable can be recovered.\n *\n * @category Utilities\n */\nexport function partialJSONParse(raw: string): unknown {\n if (!raw) return {};\n try {\n return JSON.parse(raw);\n } catch {\n /* fall through to the balanced attempt */\n }\n try {\n return JSON.parse(balanceOpenJSON(raw));\n } catch {\n return {};\n }\n}\n\nlet warnedTitle = false;\n\n/**\n * Maps the deprecated `_title` tool-arg key onto a typed `statusMessage` for one\n * minor release (with a one-time dev warning). Prefer a renderer-owned typed\n * field going forward.\n */\nfunction readStatusMessage(input: unknown): string | undefined {\n if (input && typeof input === \"object\" && \"_title\" in input) {\n const value = (input as Record<string, unknown>)[\"_title\"];\n if (typeof value === \"string\") {\n if (isDev() && !warnedTitle) {\n warnedTitle = true;\n console.warn(\n \"[OpenUI] The `_title` tool-arg key is deprecated and will be removed; \" +\n \"the renderer now exposes a typed `statusMessage` on ToolActivity instead.\",\n );\n }\n return value;\n }\n }\n return undefined;\n}\n\n/**\n * Pairs every tool call on an assistant message with its result message **by\n * `toolCallId`** (id-keyed, no positional `break`), producing a typed\n * {@link ToolActivity} per call. Turn-safe even when tool messages trail or\n * interleave with other messages.\n *\n * @param message The assistant message owning the tool calls.\n * @param allMessages The full thread message list (scanned for tool results).\n * @param executingIds Tool-call ids whose args have closed but whose result\n * hasn't landed (the store's `executingToolCallIds`).\n *\n * @category Utilities\n */\nexport function pairToolActivity(\n message: AssistantMessage,\n allMessages: ReadonlyArray<Message>,\n executingIds: ReadonlySet<string> = new Set(),\n): ToolActivity[] {\n const byCallId = new Map<string, ToolMessage>();\n // Every tool-call id owned by ANY assistant message — used to detect orphan\n // tool results (a `role:\"tool\"` message whose call exists nowhere).\n const ownedCallIds = new Set<string>();\n for (const m of allMessages) {\n if (m.role === \"tool\") {\n const tm = m as ToolMessage;\n if (tm.toolCallId) byCallId.set(tm.toolCallId, tm);\n } else if (m.role === \"assistant\") {\n for (const tc of (m as AssistantMessage).toolCalls ?? []) ownedCallIds.add(tc.id);\n }\n }\n\n const activities = (message.toolCalls ?? []).map((toolCall): ToolActivity => {\n const toolMessage = byCallId.get(toolCall.id) ?? null;\n const input = partialJSONParse(toolCall.function.arguments) as Record<string, unknown>;\n const statusMessage = readStatusMessage(input);\n const base = {\n id: toolCall.id,\n toolName: toolCall.function.name,\n toolCall,\n statusMessage,\n };\n\n if (toolMessage) {\n return toolMessage.error\n ? {\n ...base,\n status: \"error\",\n toolMessage,\n input: input as never,\n result: toolMessage.content,\n isError: true,\n errorText: toolMessage.error,\n }\n : {\n ...base,\n status: \"complete\",\n toolMessage,\n input: input as never,\n result: toolMessage.content,\n isError: false,\n };\n }\n\n return executingIds.has(toolCall.id)\n ? {\n ...base,\n status: \"executing\",\n toolMessage: null,\n input: input as never,\n isError: false,\n }\n : {\n ...base,\n status: \"streaming\",\n toolMessage: null,\n input: input as Partial<unknown>,\n isError: false,\n };\n });\n\n // Orphan tool results: tool messages that trail THIS assistant message but\n // belong to no tool call anywhere. Previously these still rendered (as a\n // generic result chip); pairing by id alone would drop them. Attribute each\n // to the assistant message it positionally trails so it renders exactly once.\n const msgIndex = allMessages.findIndex((m) => m.id === message.id);\n if (msgIndex !== -1) {\n for (let i = msgIndex + 1; i < allMessages.length; i++) {\n const m = allMessages[i];\n if (!m || m.role !== \"tool\") break;\n const tm = m as ToolMessage;\n if (!tm.toolCallId || ownedCallIds.has(tm.toolCallId)) continue;\n const orphanCall: ToolCall = {\n id: tm.toolCallId,\n type: \"function\",\n function: { name: \"\", arguments: \"\" },\n };\n // Key by the (unique) tool-message id, not the toolCallId — two orphan\n // results can share a toolCallId in persisted history and would otherwise\n // collide on the React key.\n const base = { id: tm.id, toolName: \"\", toolCall: orphanCall };\n activities.push(\n tm.error\n ? {\n ...base,\n status: \"error\",\n toolMessage: tm,\n input: {} as never,\n result: tm.content,\n isError: true,\n errorText: tm.error,\n }\n : {\n ...base,\n status: \"complete\",\n toolMessage: tm,\n input: {} as never,\n result: tm.content,\n isError: false,\n },\n );\n }\n }\n\n return activities;\n}\n","import { computed, toValue, type MaybeRefOrGetter } from \"vue\";\nimport { pairToolActivity, type ToolActivity } from \"../store/toolActivity\";\nimport type { AssistantMessage, Message, ToolMessage } from \"../types\";\nimport { useThread } from \"./useThread\";\nexport function useToolActivities(\n message: MaybeRefOrGetter<AssistantMessage>,\n allMessages: MaybeRefOrGetter<Message[]>,\n) {\n const executingIds = useThread((state) => state.executingToolCallIds);\n let previous:\n | { id: string; args: string; result: string; executing: Set<string>; value: ToolActivity[] }\n | undefined;\n return computed(() => {\n const current = toValue(message);\n const messages = toValue(allMessages);\n const args = (current.toolCalls ?? [])\n .map((tool) => `${tool.id}:${tool.function.arguments.length}`)\n .join(\"|\");\n const result = messages\n .filter((item): item is ToolMessage => item.role === \"tool\")\n .map((item) => `${item.toolCallId}:${item.content?.length ?? 0}:${item.error ? 1 : 0}`)\n .join(\"|\");\n const executing = executingIds.value;\n // Preserve the original React memo invalidation contract, including its\n // length-based keys; do not silently change same-length update behavior.\n if (\n previous &&\n previous.id === current.id &&\n previous.args === args &&\n previous.result === result &&\n previous.executing === executing\n )\n return previous.value;\n previous = {\n id: current.id,\n args,\n result,\n executing,\n value: pairToolActivity(current, messages, executing),\n };\n return previous.value;\n });\n}\n","import type { VNodeChild } from \"vue\";\n\nimport type { ArtifactCategory } from \"../adapters/types\";\nimport type { ArtifactRendererConfig } from \"./artifactRendererTypes\";\n\n/**\n * One named artifact category and the renderers that belong to it. Passed to\n * {@link defineArtifactCategories}.\n *\n * @category Types\n */\nexport interface ArtifactCategoryGroup {\n /** Display label and key for the category, e.g. `\"Reports\"`. */\n name: string;\n /**\n * Renderers in this category. Each renderer's `type` populates the category's\n * filter, and the renderers themselves are collected into `artifactRenderers`.\n */\n renderers: ArtifactRendererConfig<any>[];\n /** Sidebar nav icon for the category. Omit to fall back to the default. */\n icon?: VNodeChild;\n}\n\n/**\n * Wraps the manual `artifactRenderers` + `artifactCategories` wiring: declare\n * each category once with its renderers, and get both props back, ready to\n * spread onto `<AgentInterface>`.\n *\n * - `artifactRenderers` is every group's renderers, in order, de-duplicated by\n * identity (a renderer listed in two groups registers once).\n * - `artifactCategories` is one {@link ArtifactCategory} per group, its\n * `filter.type` collected from the group's renderer `type`s (de-duplicated).\n *\n * @category Functions\n *\n * @example\n * ```tsx\n * const artifacts = defineArtifactCategories([\n * { name: \"Reports\", renderers: [reportRenderer], icon: <ReportIcon /> },\n * { name: \"Dashboards\", renderers: [dashboardRenderer], icon: <AppIcon /> },\n * ]);\n *\n * <AgentInterface llm={llm} {...artifacts} />;\n * ```\n */\nexport function defineArtifactCategories(groups: ArtifactCategoryGroup[]): {\n artifactRenderers: ArtifactRendererConfig<any>[];\n artifactCategories: ArtifactCategory[];\n} {\n const artifactRenderers: ArtifactRendererConfig<any>[] = [];\n const seenRenderers = new Set<ArtifactRendererConfig<any>>();\n\n const artifactCategories = groups.map((group): ArtifactCategory => {\n const type: string[] = [];\n const seenTypes = new Set<string>();\n\n for (const renderer of group.renderers) {\n if (!seenRenderers.has(renderer)) {\n seenRenderers.add(renderer);\n artifactRenderers.push(renderer);\n }\n if (!seenTypes.has(renderer.type)) {\n seenTypes.add(renderer.type);\n type.push(renderer.type);\n }\n }\n\n return { name: group.name, filter: { type }, icon: group.icon };\n });\n\n return { artifactRenderers, artifactCategories };\n}\n","import { computed, inject, type ComputedRef, type InjectionKey } from \"vue\";\nimport type { ArtifactCategory } from \"../adapters/types\";\nexport const ArtifactCategoriesContext = Symbol(\"ArtifactCategoriesContext\") as InjectionKey<\n ComputedRef<ArtifactCategory[]>\n>;\nexport const useArtifactCategories = () =>\n inject(\n ArtifactCategoriesContext,\n computed(() => []),\n );\n","import type { VNodeChild } from \"vue\";\n\n/**\n * Controls passed to a renderer's `preview` and `actual` render functions.\n *\n * @category Types\n */\nexport interface ArtifactRendererControls {\n /** Whether this renderer's detailed view is the currently active one. */\n isActive: boolean;\n /**\n * `true` while the tool call is still streaming — i.e. its arguments are\n * arriving incrementally and no tool result has been paired in yet. Becomes\n * `false` once the tool result message lands and the renderer is invoked\n * with the full `response`. Always `false` for storage-opened artifacts.\n *\n * The same component instance is reused across the streaming → completed\n * transition, so renderers can rely on this flag to swap UI states (e.g.\n * show a skeleton or \"streaming…\" badge during partial args, then the final\n * view) without remounting.\n */\n isStreaming: boolean;\n /** Activates this renderer's detailed view. */\n open: () => void;\n /** Closes this renderer's detailed view if currently active. */\n close: () => void;\n /** Toggles this renderer's detailed view. */\n toggle: () => void;\n}\n\n/**\n * Result of a renderer's `parser`.\n *\n * - Returning `null` from `parser` skips rendering this tool call entirely.\n * - `meta: null` renders preview/actual but skips ThreadContext registration —\n * a common pattern while `ctx.isStreaming` is `true` so the entry only\n * appears in the registry once the tool result has arrived.\n *\n * @category Types\n */\nexport interface ParsedArtifact<Props> {\n props: Props;\n // `type`, when a parser provides it, is the artifact's REAL kind. It lets the\n // ThreadContext registration label/resolve the artifact by its own kind even\n // when a single tool-owning renderer matched the tool name (e.g. one renderer\n // owns the generate/edit tools but emits both presentations and reports).\n // Optional: parsers that don't set it fall back to the matched renderer's type.\n meta: { id: string; version: number; heading: string; type?: string } | null;\n}\n\n/**\n * Configuration for a single artifact renderer, returned by {@link defineArtifactRenderer}.\n *\n * Renderers are matched against tool calls by `toolName` (one or many literal\n * strings) and against stored artifacts by `type`. When a match fires, `parser`\n * converts the raw envelope into typed `Props` + an optional ThreadContext\n * `meta` entry, and `preview` / `actual` render the inline chat preview and\n * the full view respectively.\n *\n * @category Types\n */\nexport interface ArtifactRendererConfig<Props = unknown> {\n /**\n * Artifact type this renderer handles, e.g. `\"th_presentation\"`.\n * Links the renderer to {@link ArtifactCategory} filters and to stored\n * artifacts (`ArtifactSummary.type`) for thread-independent rendering.\n */\n type: string;\n /**\n * Tool name(s) to match. Literal strings only; first registration wins on\n * duplicates. An array registers the same renderer for several tools.\n */\n toolName: string | string[];\n /**\n * Converts the raw envelope into `{ props, meta }`.\n *\n * Tool-call path: receives `{ args, response }` exactly as the backend\n * emitted them — the SDK does not pre-parse JSON. Called on every update,\n * including during streaming, so implementations must tolerate:\n * - `args` as a *partial* JSON string (the LLM is still emitting it), and\n * - `response` as `null` (the tool result hasn't arrived yet — see\n * {@link ArtifactRendererControls.isStreaming}).\n *\n * Storage path (artifact browser): receives `{ args: undefined, response: artifact.content }` —\n * stored `content` must therefore have the same shape as the tool-call response.\n *\n * Return `null` to skip rendering. Return `meta: null` to render without\n * registering in the ThreadContext (entry hidden from workspace lists).\n * `meta.id` should be stable across re-runs of the same logical entry —\n * when `(id, version)` changes, the registry entry is re-registered.\n */\n parser: (\n raw: { args: unknown; response: unknown; id?: string },\n ctx: { isStreaming: boolean },\n ) => ParsedArtifact<Props> | null;\n /** Renders the inline preview shown in the chat message. */\n preview: (props: Props, controls: ArtifactRendererControls) => VNodeChild;\n /** Renders the full artifact view (side panel in-thread, full page in the artifact browser). */\n actual: (props: Props, controls: ArtifactRendererControls) => VNodeChild;\n /**\n * `false`: the side panel draws no header (title and close) around `actual`, for a renderer\n * that brings its own and closes with `controls.close`. Defaults to `true`.\n */\n panelHeader?: boolean;\n /**\n * Icon for this artifact type, used by the artifact nav for the category this\n * type belongs to. A platform-neutral node (a web element or a React Native\n * element). When a category groups several types, the nav uses the first\n * member type's icon; if none is set the UI falls back to a generic default.\n */\n icon?: VNodeChild;\n /**\n * Human-readable display label for this artifact type, shown as the type\n * metadata on artifact browser cards and workspace items (e.g. `\"Report\"`).\n * When omitted, the UI prettifies the `type` id (never shows the raw id).\n * Mirrors `icon` — declared via `defineArtifactRenderer({ label })`.\n */\n label?: string;\n}\n\n/**\n * Identity helper that returns its argument while preserving `Props` inference.\n *\n * Without this, users would have to write `const r: ArtifactRendererConfig<MyProps> = {...}`\n * to get type checking. With it, `defineArtifactRenderer({...})` infers `Props`\n * from `parser`'s return type.\n *\n * @category Functions\n *\n * @example\n * ```ts\n * const presentationRenderer = defineArtifactRenderer({\n * type: \"th_presentation\",\n * toolName: [\"presentation:create\", \"presentation:edit\"],\n * parser: ({ response }) => {\n * const slides = response as { id: string; slides: Slide[] } | null;\n * if (!slides) return null;\n * return {\n * props: slides,\n * meta: { id: slides.id, version: 1, heading: `Presentation ${slides.id}` },\n * };\n * },\n * preview: (props, controls) => <PresentationCard onOpen={controls.open} />,\n * actual: (props) => <SlideDeck slides={props.slides} />,\n * });\n * ```\n */\nexport function defineArtifactRenderer<Props>(\n config: ArtifactRendererConfig<Props>,\n): ArtifactRendererConfig<Props> {\n return config;\n}\n","/**\n * Builds the detailed-view id for an artifact version. This is the contract\n * between everything that opens artifact panels (auto-open watcher, workspace\n * rail) and the renderer that registers them — always build/read the id\n * through these helpers, never hand-roll the string.\n */\nexport function artifactViewId(id: string, version: number): string {\n return `${id}:${version}`;\n}\n\n/**\n * Splits a detailed-view id back into artifact id + version. Returns null\n * when the string isn't an artifact view id (e.g. a useId fallback).\n */\nexport function parseArtifactViewId(viewId: string): { id: string; version: number } | null {\n const sep = viewId.lastIndexOf(\":\");\n if (sep <= 0) return null;\n const versionPart = viewId.slice(sep + 1);\n if (!/^\\d+$/.test(versionPart)) return null;\n return { id: viewId.slice(0, sep), version: Number(versionPart) };\n}\n","import type { Thread } from \"../store/types\";\nimport type { Message, UserMessage } from \"../types/message\";\nimport type { ChatStorage } from \"./types\";\n\n/**\n * Internal default storage — in-memory, no persistence across reload.\n * Used by `<ChatProvider>` when no `storage` prop is provided. Not exported\n * from the package; callers who want explicit in-memory behavior should\n * construct their own adapter object.\n */\nexport function createDefaultInMemoryStorage(): ChatStorage {\n let threads: Thread[] = [];\n const messagesByThread = new Map<string, Message[]>();\n\n return {\n thread: {\n async listThreads() {\n return { threads };\n },\n async createThread(firstMessage: UserMessage) {\n const thread: Thread = {\n id: crypto.randomUUID(),\n title:\n typeof firstMessage.content === \"string\"\n ? firstMessage.content.slice(0, 40) || \"New thread\"\n : \"New thread\",\n createdAt: new Date().toISOString(),\n };\n threads = [thread, ...threads];\n messagesByThread.set(thread.id, [\n { ...firstMessage, id: firstMessage.id ?? crypto.randomUUID() },\n ]);\n return thread;\n },\n async getMessages(threadId: string) {\n return messagesByThread.get(threadId) ?? [];\n },\n async updateThread(thread: Thread) {\n threads = threads.map((t) => (t.id === thread.id ? thread : t));\n return thread;\n },\n async deleteThread(id: string) {\n threads = threads.filter((t) => t.id !== id);\n messagesByThread.delete(id);\n },\n },\n };\n}\n","import { onMounted, onUpdated, onScopeDispose, toValue, type MaybeRefOrGetter } from \"vue\";\nimport { artifactViewId } from \"./artifactViewId\";\nimport type { createChatStore } from \"./createChatStore\";\nimport type { createDetailedViewStore } from \"./createDetailedViewStore\";\nimport type { createThreadContextStore } from \"./createThreadContextStore\";\nimport type { ArtifactEntry } from \"./threadContextTypes\";\n\n/**\n * One pass over every artifact registered in the thread. Each artifact\n * version (`id:version`) gets a single chance to auto-open — recorded in\n * `claimedIds` the first time we see it, whether or not it opens — so an\n * edit's new version qualifies again. Returns true when a panel opened.\n */\nexport function evaluateRegisteredArtifacts(\n artifacts: Record<string, ArtifactEntry[]>, // all artifacts in the thread context: id → versions, ascending\n mayOpen: boolean, // \"is opening allowed right now\" — streaming and nothing opened yet this stream\n claimedIds: Set<string>, // \"id:version\" keys that already used their chance (cleared per thread)\n detailedViewStore: ReturnType<typeof createDetailedViewStore>,\n): boolean {\n let opened = false;\n // artifacts = {\n // \"report-abc\": [ {id:\"report-abc\", version:1, …}, {id:\"report-abc\", version:2, …} ],\n // \"deck-xyz\": [ {id:\"deck-xyz\", version:1, …} ],\n // }\n // artifactsWithVersions = [\n // [ {id:\"report-abc\", version:1, …}, {id:\"report-abc\", version:2, …} ],\n // [ {id:\"deck-xyz\", version:1, …} ],\n // ]\n const artifactsWithVersions = Object.values(artifacts);\n for (let i = 0; i < artifactsWithVersions.length; i++) {\n const versions = artifactsWithVersions[i];\n // versions = [ {id:\"report-abc\", version:1, …}, {id:\"report-abc\", version:2, …} ]\n // no list at this index (can't happen; strict TS guard)\n if (!versions) continue;\n // versions are sorted ascending, so the last entry is the newest one\n // latest = {id:\"report-abc\", version:2, …}\n const latest = versions[versions.length - 1];\n // no versions at all (can't happen in practice; keeps strict TS happy)\n if (!latest) continue;\n // claim keyed by id:version so an EDIT (new version, same id) gets a\n // fresh chance to open, while re-registrations of the same version are\n // ignored (a user's close sticks)\n const key = artifactViewId(latest.id, latest.version);\n if (claimedIds.has(key)) continue;\n claimedIds.add(key);\n // allowed to open right now? and only one open per pass\n if (!mayOpen || opened) continue;\n // takes over the panel even if it is already open: a new stream's first\n // artifact (or a streaming edit) re-points an open panel to itself\n detailedViewStore.getState().setActiveDetailedView(key);\n opened = true;\n }\n return opened;\n}\n\n/**\n * Runs inside ChatProvider: re-evaluates whenever an artifact registers in\n * the thread context, opening at most one artifact per stream.\n */\nexport function useArtifactAutoOpenWatcher(\n artifactAutoOpen: MaybeRefOrGetter<boolean>,\n chatStore: ReturnType<typeof createChatStore>,\n threadContextStore: ReturnType<typeof createThreadContextStore>,\n detailedViewStore: ReturnType<typeof createDetailedViewStore>,\n): void {\n // \"did this stream already auto-open something\" — re-armed on each new stream\n const openedThisRunRef = { current: false };\n // id:version keys that used their one auto-open chance — cleared on thread switch\n const claimedIdsRef = { current: new Set<string>() };\n\n let enabled: boolean | undefined;\n let cleanup: (() => void) | undefined;\n // This hook is internal to ChatProvider. Its input is a Provider prop,\n // so reconcile after the Provider commits, not in a post-flush watcher:\n // post watchers can precede child mounted/updated hooks. React's previous\n // passive effect remains installed through the child's layout commit.\n const reconcile = () => {\n const nextEnabled = toValue(artifactAutoOpen);\n if (nextEnabled === enabled) return;\n cleanup?.();\n cleanup = undefined;\n enabled = nextEnabled;\n if (!enabled) return;\n const unsubscribeThread = chatStore.subscribe(\n (s) => s.selectedThreadId,\n () => {\n claimedIdsRef.current.clear();\n openedThisRunRef.current = false;\n },\n );\n const unsubscribeRun = chatStore.subscribe(\n (s) => s.isRunning,\n (isRunning) => {\n if (isRunning) openedThisRunRef.current = false;\n },\n );\n const unsubscribeArtifacts = threadContextStore.subscribe(\n (s) => s.artifacts,\n (artifacts) => {\n const mayOpen = chatStore.getState().isRunning && !openedThisRunRef.current;\n if (\n evaluateRegisteredArtifacts(artifacts, mayOpen, claimedIdsRef.current, detailedViewStore)\n ) {\n openedThisRunRef.current = true;\n }\n },\n // also evaluate artifacts that registered before this watcher mounted\n { fireImmediately: true },\n );\n cleanup = () => {\n unsubscribeThread();\n unsubscribeRun();\n unsubscribeArtifacts();\n };\n };\n onMounted(reconcile);\n onUpdated(reconcile);\n onScopeDispose(() => cleanup?.());\n}\n","export async function getResponseErrorMessage(response: Response): Promise<string> {\n try {\n const data = (await response.clone().json()) as {\n error?: { message?: unknown } | string;\n message?: unknown;\n };\n const message =\n typeof data.error === \"string\"\n ? data.error\n : typeof data.error?.message === \"string\"\n ? data.error.message\n : typeof data.message === \"string\"\n ? data.message\n : null;\n\n if (message?.trim()) return message;\n } catch {\n // Fall through to the status-based message.\n }\n\n return `Request failed: ${response.status} ${response.statusText}`.trim();\n}\n","import type { Message } from \"./message\";\n\n/**\n * Converts messages between AG-UI format (used internally) and the\n * format your backend / storage layer expects.\n *\n * Both methods operate on **arrays** so that formats where a single\n * AG-UI message maps to multiple backend items (e.g. OpenAI Responses\n * API) work seamlessly alongside 1-to-1 formats (e.g. Completions).\n *\n * @example\n * // Identity (default) — no conversion\n * const identity: MessageFormat = {\n * toApi: (messages) => messages,\n * fromApi: (data) => data as Message[],\n * };\n */\nexport interface MessageFormat {\n /** Convert AG-UI messages to the format your backend expects (outbound). */\n toApi(messages: Message[]): unknown;\n /** Convert messages from your backend/storage format to AG-UI (inbound). */\n fromApi(data: unknown): Message[];\n}\n\n/**\n * Default identity message format — no conversion.\n * Messages are sent and received as-is in AG-UI format.\n */\nexport const identityMessageFormat: MessageFormat = {\n toApi: (messages) => messages,\n fromApi: (data) => data as Message[],\n};\n","/**\n * Shared line iterator for streamed HTTP responses.\n *\n * Buffers the leftover partial line between network chunks so an SSE event (or\n * NDJSON record) split across two `reader.read()` results is reassembled rather\n * than silently dropped. The reference implementation lived in\n * `openai-readable-stream.ts`; this extracts it so `ag-ui.ts` and\n * `openai-completions.ts` share the same correct buffering.\n *\n * Yields each complete line verbatim (caller strips any `data: ` SSE prefix);\n * blank lines are skipped. The trailing buffered line is flushed on stream end.\n *\n * @internal\n */\nexport async function* sseLineIterator(response: Response): AsyncGenerator<string> {\n const reader = response.body?.getReader();\n if (!reader) throw new Error(\"No response body\");\n\n const decoder = new TextDecoder();\n let buffer = \"\";\n\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split(\"\\n\");\n // Keep the straddling partial line (everything after the last \"\\n\") for the\n // next chunk; it may be completed by the bytes that follow.\n buffer = lines.pop() ?? \"\";\n\n for (const line of lines) {\n if (line.trim()) yield line;\n }\n }\n\n // Flush the tail — a stream that ends without a trailing newline still has a\n // complete final line sitting in the buffer.\n if (buffer.trim()) yield buffer;\n}\n","import { AGUIEvent, StreamProtocolAdapter } from \"../../types\";\nimport { sseLineIterator } from \"./_shared/sseLines\";\n\nexport const agUIAdapter = (): StreamProtocolAdapter => ({\n async *parse(response: Response): AsyncIterable<AGUIEvent> {\n for await (const line of sseLineIterator(response)) {\n if (!line.startsWith(\"data: \")) continue;\n const data = line.slice(6).trim();\n if (!data || data === \"[DONE]\") continue;\n\n try {\n const event = JSON.parse(data);\n yield event as AGUIEvent;\n } catch (e) {\n console.error(\"Failed to parse SSE event\", e);\n }\n }\n },\n});\n","import type { HandleMessageStreamEvent } from \"eve/client\";\nimport { AGUIEvent, EventType, StreamProtocolAdapter } from \"../../types\";\nimport { sseLineIterator } from \"./_shared/sseLines\";\n\nexport type {\n InputOption as EveInputOption,\n InputRequest as EveInputRequest,\n HandleMessageStreamEvent as EveStreamEvent,\n} from \"eve/client\";\n\n/**\n * Options for the Eve adapter.\n */\nexport interface EveAdapterOptions {\n /** Called with every raw Eve event before translation (including unmapped types). */\n onEvent?: (event: HandleMessageStreamEvent) => void;\n}\n\nexport const EVE_INPUT_REQUESTED_EVENT = \"eve.input.requested\";\n\nconst TURN_BOUNDARY_TYPES = new Set([\"session.completed\", \"session.failed\", \"session.waiting\"]);\n\n/**\n * Adapter for Eve session streams (`GET /eve/v1/session/:id/stream`).\n *\n * Eve emits newline-delimited JSON harness events. The adapter handles\n * `actions.requested`, `action.result`, `message.appended`, `message.completed`,\n * `input.requested`, `turn.failed`, and `session.failed` and maps tool calls,\n * assistant text, input prompts, and failures to AG-UI events. Parsing stops at\n * turn boundaries (`session.completed`, `session.waiting`, `session.failed`).\n * Pass `onEvent` for unmapped events such as `session.started`.\n */\nexport const eveAdapter = (options: EveAdapterOptions = {}): StreamProtocolAdapter => ({\n async *parse(response: Response): AsyncIterable<AGUIEvent> {\n const messageId = crypto.randomUUID();\n const streamedSteps = new Set<number>();\n let started = false;\n\n const start = (): AGUIEvent[] => {\n if (started) return [];\n started = true;\n return [{ type: EventType.TEXT_MESSAGE_START, messageId, role: \"assistant\" }];\n };\n\n for await (const line of sseLineIterator(response)) {\n let event: HandleMessageStreamEvent;\n try {\n event = JSON.parse(line) as HandleMessageStreamEvent;\n } catch (e) {\n console.error(\"Failed to parse Eve stream event\", e);\n continue;\n }\n options.onEvent?.(event);\n\n if (event.type === \"actions.requested\") {\n for (const action of event.data.actions) {\n if (action.kind !== \"tool-call\") continue;\n yield* start();\n yield {\n type: EventType.TOOL_CALL_START,\n toolCallId: action.callId,\n toolCallName: action.toolName,\n parentMessageId: messageId,\n };\n const args = JSON.stringify(action.input ?? {});\n if (args && args !== \"{}\") {\n yield { type: EventType.TOOL_CALL_ARGS, toolCallId: action.callId, delta: args };\n }\n yield { type: EventType.TOOL_CALL_END, toolCallId: action.callId };\n }\n } else if (event.type === \"action.result\") {\n const { result, status, error } = event.data;\n if (result.kind !== \"tool-result\") continue;\n const content =\n status === \"completed\"\n ? typeof result.output === \"string\"\n ? result.output\n : JSON.stringify(result.output ?? null)\n : JSON.stringify({ error: error?.message ?? `tool ${status}` });\n yield {\n type: EventType.TOOL_CALL_RESULT,\n messageId: crypto.randomUUID(),\n toolCallId: result.callId,\n content,\n role: \"tool\",\n };\n } else if (event.type === \"message.appended\") {\n const { messageDelta, stepIndex } = event.data;\n if (!messageDelta) continue;\n streamedSteps.add(stepIndex);\n yield* start();\n yield { type: EventType.TEXT_MESSAGE_CONTENT, messageId, delta: messageDelta };\n } else if (event.type === \"message.completed\") {\n const { message, stepIndex } = event.data;\n if (!message || streamedSteps.has(stepIndex)) continue;\n yield* start();\n yield { type: EventType.TEXT_MESSAGE_CONTENT, messageId, delta: message };\n } else if (event.type === \"input.requested\") {\n yield {\n type: EventType.CUSTOM,\n name: EVE_INPUT_REQUESTED_EVENT,\n value: event.data.requests,\n };\n } else if (event.type === \"turn.failed\" || event.type === \"session.failed\") {\n yield { type: EventType.RUN_ERROR, message: event.data.message };\n }\n\n if (TURN_BOUNDARY_TYPES.has(event.type)) break;\n }\n\n if (started) yield { type: EventType.TEXT_MESSAGE_END, messageId };\n },\n});\n","import { AGUIEvent, EventType, StreamProtocolAdapter } from \"../../types\";\n\ntype LangGraphContent = string | Array<{ type: string; text?: string }>;\n\n/** LangGraph AI message (or chunk) received in `messages` stream mode. */\ninterface LangGraphAIMessage {\n id?: string;\n type: \"ai\" | \"AIMessageChunk\" | \"AIMessage\";\n content: LangGraphContent;\n tool_calls?: Array<{\n id: string;\n name: string;\n args: Record<string, unknown> | string;\n }>;\n tool_call_chunks?: Array<{\n id?: string;\n name?: string;\n args?: string;\n index?: number;\n }>;\n}\n\n/** LangGraph tool result (or chunk) received between model invocations. */\ninterface LangGraphToolMessage {\n id?: string;\n type: \"tool\" | \"ToolMessage\" | \"ToolMessageChunk\";\n content: LangGraphContent;\n tool_call_id: string;\n status?: \"success\" | \"error\";\n}\n\ntype LangGraphMessage = LangGraphAIMessage | LangGraphToolMessage;\n\n/**\n * Metadata attached to each message tuple in the `messages` stream mode.\n */\ninterface LangGraphMessageMetadata {\n langgraph_node?: string;\n langgraph_step?: number;\n langgraph_triggers?: string[];\n langgraph_checkpoint_ns?: string;\n tags?: string[];\n ls_model_name?: string;\n}\n\n/**\n * Options for the LangGraph adapter.\n */\nexport interface LangGraphAdapterOptions {\n /**\n * Called when a LangGraph interrupt is encountered in an `updates` event.\n * The interrupt payload is the value of the `__interrupt__` key.\n */\n onInterrupt?: (interrupt: unknown) => void;\n}\n\n/**\n * Adapter for LangGraph streaming responses.\n *\n * LangGraph uses named SSE events (`event: <type>\\ndata: <json>\\n\\n`)\n * rather than the `data:`-only format used by OpenAI. The adapter handles\n * the `messages`, `metadata`, `updates`, and `error` event types and maps\n * model steps and tool results to ordered AG-UI events.\n *\n * Usage:\n * ```tsx\n * <ChatProvider\n * apiUrl=\"/api/langgraph\"\n * streamProtocol={langGraphAdapter()}\n * />\n * ```\n */\nexport const langGraphAdapter = (options?: LangGraphAdapterOptions): StreamProtocolAdapter => ({\n async *parse(response: Response): AsyncIterable<AGUIEvent> {\n const reader = response.body?.getReader();\n if (!reader) throw new Error(\"No response body\");\n\n const decoder = new TextDecoder();\n let fallbackMessageId = crypto.randomUUID();\n let currentMessageId: string | null = null;\n let currentGraphStep: number | undefined;\n const toolCallIdsByIndex = new Map<number, string>();\n const startedToolCallIds = new Set<string>();\n const openToolCallIds = new Set<string>();\n const toolCallArgsSeen = new Set<string>();\n // Every id already spent on an assistant segment, so a repeated wire id can\n // be given a distinct one (see the segment-opening branch below).\n const usedMessageIds = new Set<string>();\n let duplicateMessageIds = 0;\n let messageStarted = false;\n let sawToolsOnCurrentMessage = false;\n let buffer = \"\";\n\n while (true) {\n const { done, value } = await reader.read();\n\n // Accumulate across reads: an SSE event block (e.g. a multi-KB artifact\n // function_call_arguments payload) can span several network reads. Hold the\n // trailing partial block until the next read; on done, flush what remains\n // (the old early `if (done) break` dropped the final un-terminated block).\n buffer += done ? decoder.decode() : decoder.decode(value, { stream: true });\n\n // SSE events are separated by double newlines; keep the last (possibly\n // incomplete) block in the buffer until more arrives.\n const blocks = buffer.split(\"\\n\\n\");\n buffer = done ? \"\" : (blocks.pop() ?? \"\");\n\n for (const block of blocks) {\n const trimmed = block.trim();\n if (!trimmed) continue;\n\n const { event, data } = parseSSEBlock(trimmed);\n if (!data) continue;\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(data);\n } catch (e) {\n console.error(\"Failed to parse LangGraph SSE data\", e);\n continue;\n }\n\n switch (event) {\n case \"metadata\": {\n // Metadata event signals the run has started.\n // Payload: { run_id: string, thread_id: string }\n // We don't emit RUN_STARTED because processStreamedMessage\n // doesn't handle it — it's informational only.\n break;\n }\n\n case \"messages\": {\n // Payload is a tuple: [message_chunk, metadata]\n // or just a message object depending on the stream version.\n const tuple = parsed as [LangGraphMessage, LangGraphMessageMetadata] | LangGraphMessage;\n const msg = Array.isArray(tuple) ? tuple[0] : tuple;\n const metadata = Array.isArray(tuple) ? tuple[1] : undefined;\n\n if (isToolMessage(msg)) {\n // A ToolMessage marks the end of the model step that requested\n // the tool. Close both the call and assistant segment before\n // emitting its result so live history remains ai → tool → ai.\n if (openToolCallIds.delete(msg.tool_call_id)) {\n yield {\n type: EventType.TOOL_CALL_END,\n toolCallId: msg.tool_call_id,\n };\n }\n if (messageStarted && currentMessageId) {\n yield {\n type: EventType.TEXT_MESSAGE_END,\n messageId: currentMessageId,\n };\n }\n messageStarted = false;\n currentMessageId = null;\n sawToolsOnCurrentMessage = false;\n currentGraphStep = undefined;\n fallbackMessageId = crypto.randomUUID();\n toolCallIdsByIndex.clear();\n\n const content = serializeToolContent(msg.content);\n yield {\n type: EventType.TOOL_CALL_RESULT,\n messageId: msg.id ?? `tool-result-${msg.tool_call_id}`,\n toolCallId: msg.tool_call_id,\n content,\n role: \"tool\",\n ...(msg.status === \"error\" ? { isError: true, error: content } : {}),\n } as AGUIEvent;\n break;\n }\n\n if (!isAIMessage(msg)) break;\n\n const graphStep = metadata?.langgraph_step;\n const graphStepChanged =\n graphStep !== undefined &&\n currentGraphStep !== undefined &&\n graphStep !== currentGraphStep;\n let nextMessageId =\n msg.id ??\n (graphStep === undefined ? fallbackMessageId : `langgraph-step-${graphStep}`);\n\n const textContent = extractTextContent(msg.content);\n // Text after tool calls is a new assistant item so commentary like\n // \"Let me do this\" stays on the tool-bearing message and the answer\n // text after it is not concatenated onto the same message.\n const splitAfterTools = !!textContent && sawToolsOnCurrentMessage && messageStarted;\n\n const isNewModelStep =\n !messageStarted ||\n nextMessageId !== currentMessageId ||\n graphStepChanged ||\n splitAfterTools;\n\n // LangGraph repeats a wire id across segment boundaries — both when\n // the graph step advances and after a tool call — so an id already\n // spent on a closed segment needs a fresh one for consumers to keep\n // both. Only when opening a segment: mid-message chunks must keep\n // streaming into currentMessageId.\n if (isNewModelStep && usedMessageIds.has(nextMessageId)) {\n nextMessageId = `${nextMessageId}#${++duplicateMessageIds}`;\n }\n\n if (isNewModelStep) {\n if (messageStarted && currentMessageId) {\n yield {\n type: EventType.TEXT_MESSAGE_END,\n messageId: currentMessageId,\n };\n }\n currentMessageId = nextMessageId;\n usedMessageIds.add(nextMessageId);\n currentGraphStep = graphStep;\n sawToolsOnCurrentMessage = false;\n toolCallIdsByIndex.clear();\n yield {\n type: EventType.TEXT_MESSAGE_START,\n messageId: currentMessageId,\n role: \"assistant\",\n };\n messageStarted = true;\n }\n\n if (textContent) {\n yield {\n type: EventType.TEXT_MESSAGE_CONTENT,\n messageId: currentMessageId!,\n delta: textContent,\n };\n }\n\n // Handle streaming tool call chunks (partial arguments)\n if (msg.tool_call_chunks) {\n for (const chunk of msg.tool_call_chunks) {\n const index = chunk.index ?? 0;\n\n if (chunk.id) toolCallIdsByIndex.set(index, chunk.id);\n const toolCallId = chunk.id ?? toolCallIdsByIndex.get(index);\n\n if (toolCallId && !startedToolCallIds.has(toolCallId)) {\n startedToolCallIds.add(toolCallId);\n openToolCallIds.add(toolCallId);\n sawToolsOnCurrentMessage = true;\n yield {\n type: EventType.TOOL_CALL_START,\n toolCallId,\n toolCallName: chunk.name || \"\",\n };\n }\n\n if (chunk.args && toolCallId) {\n toolCallArgsSeen.add(toolCallId);\n yield {\n type: EventType.TOOL_CALL_ARGS,\n toolCallId,\n delta: chunk.args,\n };\n }\n }\n }\n\n // Handle complete tool calls only for non-streaming messages.\n // LangChain chunks can also carry a provisional tool_calls\n // projection (often with args: {}). tool_call_chunks is the\n // authoritative source whenever that field is present.\n if (msg.tool_call_chunks === undefined && msg.tool_calls && msg.tool_calls.length > 0) {\n for (let i = 0; i < msg.tool_calls.length; i++) {\n const tc = msg.tool_calls[i];\n if (!tc) continue;\n\n const toolCallId = tc.id || crypto.randomUUID();\n\n if (!startedToolCallIds.has(toolCallId)) {\n startedToolCallIds.add(toolCallId);\n openToolCallIds.add(toolCallId);\n sawToolsOnCurrentMessage = true;\n yield {\n type: EventType.TOOL_CALL_START,\n toolCallId,\n toolCallName: tc.name,\n };\n }\n\n if (!toolCallArgsSeen.has(toolCallId)) {\n const argsStr = typeof tc.args === \"string\" ? tc.args : JSON.stringify(tc.args);\n toolCallArgsSeen.add(toolCallId);\n yield {\n type: EventType.TOOL_CALL_ARGS,\n toolCallId,\n delta: argsStr,\n };\n }\n\n if (openToolCallIds.delete(toolCallId)) {\n yield {\n type: EventType.TOOL_CALL_END,\n toolCallId,\n };\n }\n }\n }\n\n break;\n }\n\n case \"updates\": {\n // Payload: { [node_name]: node_output }\n // Check for interrupts\n const updates = parsed as Record<string, unknown>;\n if (\"__interrupt__\" in updates && options?.onInterrupt) {\n options.onInterrupt(updates[\"__interrupt__\"]);\n }\n break;\n }\n\n case \"error\": {\n // Payload: { error: string, message: string }\n const err = parsed as { error?: string; message?: string };\n yield {\n type: EventType.RUN_ERROR,\n message: err.message || err.error || \"Unknown error\",\n code: err.error ?? undefined,\n };\n break;\n }\n\n case \"end\": {\n // Stream has ended — close out any open message/tool calls.\n if (messageStarted) {\n // End any open streaming tool calls\n for (const toolCallId of openToolCallIds) {\n yield {\n type: EventType.TOOL_CALL_END,\n toolCallId,\n };\n }\n openToolCallIds.clear();\n\n yield {\n type: EventType.TEXT_MESSAGE_END,\n messageId: currentMessageId!,\n };\n messageStarted = false; // Prevent duplicate end in fallback\n }\n break;\n }\n\n // Intentionally unhandled: values, debug, tasks, checkpoints, custom\n default:\n break;\n }\n }\n\n if (done) break;\n }\n\n // If stream ended without an explicit \"end\" event, close out.\n if (messageStarted) {\n for (const toolCallId of openToolCallIds) {\n yield {\n type: EventType.TOOL_CALL_END,\n toolCallId,\n };\n }\n openToolCallIds.clear();\n yield {\n type: EventType.TEXT_MESSAGE_END,\n messageId: currentMessageId!,\n };\n }\n },\n});\n\n/**\n * Parse an SSE block into its event name and data payload.\n *\n * LangGraph SSE format:\n * ```\n * event: messages\n * data: [{\"content\": \"Hello\", ...}, {\"langgraph_node\": \"agent\"}]\n * ```\n */\nfunction parseSSEBlock(block: string): { event: string; data: string } {\n let event = \"\";\n const dataLines: string[] = [];\n\n for (const line of block.split(\"\\n\")) {\n if (line.startsWith(\"event:\")) {\n event = line.slice(6).trim();\n } else if (line.startsWith(\"data:\")) {\n dataLines.push(line.slice(5).trim());\n }\n // Ignore id:, retry:, and comment lines\n }\n\n return { event, data: dataLines.join(\"\\n\") };\n}\n\n/**\n * Extract text content from a LangGraph message content field.\n * Content can be a plain string or an array of typed content blocks.\n */\nfunction extractTextContent(content: string | Array<{ type: string; text?: string }>): string {\n if (typeof content === \"string\") return content;\n\n return content\n .filter((block) => block.type === \"text\" && block.text)\n .map((block) => block.text!)\n .join(\"\");\n}\n\nfunction serializeToolContent(content: LangGraphContent): string {\n return typeof content === \"string\" ? content : JSON.stringify(content);\n}\n\nfunction isAIMessage(message: LangGraphMessage): message is LangGraphAIMessage {\n return message.type === \"ai\" || message.type === \"AIMessage\" || message.type === \"AIMessageChunk\";\n}\n\nfunction isToolMessage(message: LangGraphMessage): message is LangGraphToolMessage {\n return (\n message.type === \"tool\" || message.type === \"ToolMessage\" || message.type === \"ToolMessageChunk\"\n );\n}\n","import type { ChatCompletionChunk } from \"openai/resources/chat/completions\";\nimport { AGUIEvent, EventType, StreamProtocolAdapter } from \"../../types\";\nimport { sseLineIterator } from \"./_shared/sseLines\";\n\nexport const openAIAdapter = (): StreamProtocolAdapter => ({\n async *parse(response: Response): AsyncIterable<AGUIEvent> {\n const messageId = crypto.randomUUID();\n const toolCallIds: Record<number, string> = {};\n let messageStarted = false;\n\n for await (const line of sseLineIterator(response)) {\n if (!line.startsWith(\"data: \")) continue;\n const data = line.slice(6).trim();\n if (!data || data === \"[DONE]\") continue;\n\n try {\n const json = JSON.parse(data) as ChatCompletionChunk;\n const choice = json.choices?.[0];\n const delta = choice?.delta;\n\n if (!delta) continue;\n\n // Emit TEXT_MESSAGE_START on first meaningful delta\n if (!messageStarted && (delta.content || delta.role)) {\n yield {\n type: EventType.TEXT_MESSAGE_START,\n messageId,\n role: \"assistant\",\n };\n messageStarted = true;\n }\n\n if (delta.content) {\n yield {\n type: EventType.TEXT_MESSAGE_CONTENT,\n messageId,\n delta: delta.content,\n };\n }\n\n if (delta.tool_calls) {\n for (const toolCall of delta.tool_calls) {\n const index = toolCall.index;\n\n if (toolCall.id) {\n toolCallIds[index] = toolCall.id;\n yield {\n type: EventType.TOOL_CALL_START,\n toolCallId: toolCall.id,\n toolCallName: toolCall.function?.name || \"\",\n };\n }\n\n if (toolCall.function?.arguments) {\n const toolCallId = toolCallIds[index];\n if (toolCallId) {\n yield {\n type: EventType.TOOL_CALL_ARGS,\n toolCallId,\n delta: toolCall.function.arguments,\n };\n }\n }\n }\n }\n\n // Emit end events based on finish_reason\n if (choice?.finish_reason === \"stop\") {\n yield {\n type: EventType.TEXT_MESSAGE_END,\n messageId,\n };\n } else if (choice?.finish_reason === \"tool_calls\") {\n for (const toolCallId of Object.values(toolCallIds)) {\n yield {\n type: EventType.TOOL_CALL_END,\n toolCallId,\n };\n }\n }\n } catch (e) {\n console.error(\"Failed to parse OpenAI SSE event\", e);\n }\n }\n },\n});\n","import type { ChatCompletionChunk } from \"openai/resources/chat/completions\";\nimport { AGUIEvent, EventType, StreamProtocolAdapter } from \"../../types\";\nimport { sseLineIterator } from \"./_shared/sseLines\";\n\n/**\n * Adapter for streams produced by the OpenAI SDK's `Stream.toReadableStream()`.\n * That method emits NDJSON (one JSON object per line, no `data: ` SSE prefix),\n * which differs from the raw SSE format that `openAIAdapter` expects.\n */\nexport const openAIReadableStreamAdapter = (): StreamProtocolAdapter => ({\n async *parse(response: Response): AsyncIterable<AGUIEvent> {\n const messageId = crypto.randomUUID();\n const toolCallIds: Record<number, string> = {};\n let messageStarted = false;\n\n for await (const line of sseLineIterator(response)) {\n const data = line.trim();\n if (!data) continue;\n\n try {\n const json = JSON.parse(data) as ChatCompletionChunk;\n const choice = json.choices?.[0];\n const delta = choice?.delta;\n\n if (!delta) continue;\n\n if (!messageStarted && (delta.content || delta.role)) {\n yield {\n type: EventType.TEXT_MESSAGE_START,\n messageId,\n role: \"assistant\",\n };\n messageStarted = true;\n }\n\n if (delta.content) {\n yield {\n type: EventType.TEXT_MESSAGE_CONTENT,\n messageId,\n delta: delta.content,\n };\n }\n\n if (delta.tool_calls) {\n for (const toolCall of delta.tool_calls) {\n const index = toolCall.index;\n\n if (toolCall.id) {\n toolCallIds[index] = toolCall.id;\n yield {\n type: EventType.TOOL_CALL_START,\n toolCallId: toolCall.id,\n toolCallName: toolCall.function?.name || \"\",\n };\n }\n\n if (toolCall.function?.arguments) {\n const toolCallId = toolCallIds[index];\n if (toolCallId) {\n yield {\n type: EventType.TOOL_CALL_ARGS,\n toolCallId,\n delta: toolCall.function.arguments,\n };\n }\n }\n }\n }\n\n if (choice?.finish_reason === \"stop\") {\n yield {\n type: EventType.TEXT_MESSAGE_END,\n messageId,\n };\n } else if (choice?.finish_reason === \"tool_calls\") {\n for (const toolCallId of Object.values(toolCallIds)) {\n yield {\n type: EventType.TOOL_CALL_END,\n toolCallId,\n };\n }\n }\n } catch (e) {\n console.error(\"Failed to parse OpenAI NDJSON chunk\", e);\n }\n }\n },\n});\n","import type {\n ResponseFunctionToolCallOutputItem,\n ResponseStreamEvent,\n} from \"openai/resources/responses/responses\";\nimport { AGUIEvent, EventType, StreamProtocolAdapter } from \"../../types\";\n\n/** A tool result's `output` as a string (JSON-encoded if structured, \"\" if absent). */\nconst stringifyOutput = (output: unknown): string =>\n typeof output === \"string\" ? output : output != null ? JSON.stringify(output) : \"\";\n\nexport const openAIResponsesAdapter = (): StreamProtocolAdapter => ({\n async *parse(response: Response): AsyncIterable<AGUIEvent> {\n const reader = response.body?.getReader();\n if (!reader) throw new Error(\"No response body\");\n\n const decoder = new TextDecoder();\n // Map item_id → call_id so TOOL_CALL_ARGS can reference the correct toolCallId\n const itemIdToCallId: Record<string, string> = {};\n // The text output-item currently streaming.\n let textItemId: string | null = null;\n\n let buffer = \"\";\n while (true) {\n const { done, value } = await reader.read();\n // Accumulate across reads: a single SSE `data:` line (e.g. a multi-KB\n // artifact function_call_output payload) can span several network\n // chunks. Splitting each chunk independently tears that line in two and\n // drops it on JSON.parse. Hold the trailing partial line until the next\n // read; on done, flush whatever remains.\n buffer += done ? decoder.decode() : decoder.decode(value, { stream: true });\n const lines = buffer.split(\"\\n\");\n buffer = done ? \"\" : (lines.pop() ?? \"\");\n\n for (const line of lines) {\n if (!line.startsWith(\"data: \")) continue;\n const data = line.slice(6).trim();\n if (!data || data === \"[DONE]\") continue;\n\n try {\n const event = JSON.parse(data) as ResponseStreamEvent;\n\n switch (event.type) {\n case \"response.output_item.added\": {\n // OpenAI's Conversations API surfaces function_call_output as an\n // output item even though the SDK's ResponseOutputItem union does\n // not declare it. Widen the type so we can branch on it below.\n const item = event.item as typeof event.item | ResponseFunctionToolCallOutputItem;\n if (item.type === \"message\" && item.role === \"assistant\") {\n textItemId = item.id;\n yield {\n type: EventType.TEXT_MESSAGE_START,\n messageId: item.id,\n role: \"assistant\",\n };\n } else if (item.type === \"function_call\") {\n // Store the mapping so we can resolve it in arguments.delta\n itemIdToCallId[item.id ?? item.call_id] = item.call_id;\n yield {\n type: EventType.TOOL_CALL_START,\n toolCallId: item.call_id,\n toolCallName: item.name,\n };\n } else if (item.type === \"function_call_output\") {\n yield {\n type: EventType.TOOL_CALL_RESULT,\n messageId: item.id,\n toolCallId: item.call_id,\n content: stringifyOutput(item.output),\n };\n } else if (item.type === \"web_search_call\") {\n yield {\n type: EventType.TOOL_CALL_START,\n toolCallId: item.id,\n toolCallName: \"web_search\",\n };\n } else if (item.type === \"mcp_call\") {\n yield {\n type: EventType.TOOL_CALL_START,\n toolCallId: item.id,\n toolCallName: item.name,\n };\n } else if (item.type === \"mcp_list_tools\") {\n yield {\n type: EventType.TOOL_CALL_START,\n toolCallId: item.id,\n toolCallName: \"mcp_list_tools\",\n };\n yield {\n type: EventType.TOOL_CALL_ARGS,\n toolCallId: item.id,\n delta: JSON.stringify({ server_label: item.server_label }),\n };\n yield {\n type: EventType.TOOL_CALL_END,\n toolCallId: item.id,\n };\n }\n break;\n }\n\n case \"response.output_text.delta\":\n // A delta for a not-yet-seen item id opens its message — covers\n // backends that switch item id on the delta without a preceding\n // `output_item.added` (idempotent when that event did fire).\n if (event.item_id !== textItemId) {\n textItemId = event.item_id;\n yield {\n type: EventType.TEXT_MESSAGE_START,\n messageId: event.item_id,\n role: \"assistant\",\n };\n }\n yield {\n type: EventType.TEXT_MESSAGE_CONTENT,\n messageId: event.item_id,\n delta: event.delta,\n };\n break;\n\n case \"response.output_text.done\":\n yield {\n type: EventType.TEXT_MESSAGE_END,\n messageId: event.item_id,\n };\n break;\n\n case \"response.function_call_arguments.delta\": {\n const callId = itemIdToCallId[event.item_id] ?? event.item_id;\n yield {\n type: EventType.TOOL_CALL_ARGS,\n toolCallId: callId,\n delta: event.delta,\n };\n break;\n }\n\n case \"response.function_call_arguments.done\": {\n const callId = itemIdToCallId[event.item_id] ?? event.item_id;\n yield {\n type: EventType.TOOL_CALL_END,\n toolCallId: callId,\n };\n break;\n }\n\n case \"response.mcp_call_arguments.delta\":\n yield {\n type: EventType.TOOL_CALL_ARGS,\n toolCallId: event.item_id,\n delta: event.delta,\n };\n break;\n\n case \"response.mcp_call_arguments.done\":\n yield {\n type: EventType.TOOL_CALL_END,\n toolCallId: event.item_id,\n };\n break;\n\n case \"response.output_item.done\": {\n // Server-executed tools deliver their result on the done item —\n // there's no function_call_output for them: mcp_call carries\n // output/error, web_search carries output/action. Every other item\n // type closes via its own event (function_call →\n // function_call_arguments.done, message → output_text.done).\n if (event.item.type === \"mcp_call\") {\n const mcp = event.item;\n const errorText =\n typeof mcp.error === \"string\" && mcp.error.length > 0 ? mcp.error : undefined;\n yield {\n type: EventType.TOOL_CALL_RESULT,\n messageId: mcp.id,\n toolCallId: mcp.id,\n content: stringifyOutput(mcp.output),\n ...(errorText ? { isError: true, error: errorText } : {}),\n };\n break;\n }\n\n if (event.item.type === \"mcp_list_tools\") {\n const list = event.item;\n // Summarize to names only\n const toolNames = list.tools.map((t) => t.name);\n const listError =\n typeof list.error === \"string\" && list.error.length > 0 ? list.error : undefined;\n yield {\n type: EventType.TOOL_CALL_RESULT,\n messageId: list.id,\n toolCallId: list.id,\n content: JSON.stringify({\n server_label: list.server_label,\n tool_count: toolNames.length,\n tools: toolNames,\n }),\n ...(listError ? { isError: true, error: listError } : {}),\n };\n break;\n }\n\n const item = event.item as {\n type?: string;\n id?: string;\n status?: string;\n output?: unknown;\n error?: unknown;\n action?: unknown;\n };\n if (item.type !== \"web_search_call\") break;\n\n const toolCallId = item.id ?? \"web_search_call\";\n\n // web_search streams no argument deltas — its query lives in\n // `action`. Surface it as the tool-call args so the card shows the\n // query live, matching a reload's persisted function_call args.\n if (item.action && typeof item.action === \"object\") {\n yield {\n type: EventType.TOOL_CALL_ARGS,\n toolCallId,\n delta: JSON.stringify(item.action),\n };\n }\n\n const content = stringifyOutput(item.output);\n yield {\n type: EventType.TOOL_CALL_RESULT,\n messageId: toolCallId,\n toolCallId,\n content,\n };\n break;\n }\n\n case \"error\":\n yield {\n type: EventType.RUN_ERROR,\n message: event.message,\n code: event.code ?? undefined,\n };\n break;\n\n case \"response.failed\":\n yield {\n type: EventType.RUN_ERROR,\n message: event.response?.error?.message ?? \"Response failed\",\n code: event.response?.error?.code ?? undefined,\n };\n break;\n\n // Intentionally unhandled — these are lifecycle/metadata events:\n // response.created, response.in_progress, response.completed,\n // response.content_part.added, response.content_part.done,\n // web_search's *.in_progress/searching/completed status events,\n // response.mcp_call.in_progress/.completed/.failed and\n // response.mcp_list_tools.* (the respective output_item.added/.done\n // handling above covers all three), and the mcp_approval_request\n // output item (HITL approval flow — no tray), etc.\n default:\n break;\n }\n } catch (e) {\n console.error(\"Failed to parse OpenAI Responses SSE event\", e);\n }\n }\n if (done) break;\n }\n },\n});\n","import type { UIMessage, UIMessageChunk } from \"ai\";\nimport { AGUIEvent, EventType, StreamProtocolAdapter } from \"../../types\";\n\nconst MISSING_AI_SDK_MESSAGE =\n 'vercelAIAdapter requires the optional peer dependency \"ai\" (Vercel AI SDK v6 or v7).';\nconst PROVIDER_EXECUTED_TOOLS_UNSUPPORTED_MESSAGE =\n \"Vercel AI SDK provider-executed tools are not supported because AG-UI messages cannot preserve providerExecuted semantics.\";\nconst TOOL_EXECUTION_DENIED_MESSAGE = \"Tool execution was denied\";\n\nfunction serialize(value: unknown): string {\n if (typeof value === \"string\") return value;\n return JSON.stringify(value) ?? String(value);\n}\n\nasync function parseUIMessageStream(\n body: ReadableStream<Uint8Array>,\n): Promise<ReadableStream<UIMessageChunk>> {\n let DefaultChatTransport: typeof import(\"ai\").DefaultChatTransport;\n\n try {\n ({ DefaultChatTransport } = await import(\"ai\"));\n } catch (cause) {\n throw new Error(MISSING_AI_SDK_MESSAGE, { cause });\n }\n\n // Some bundlers replace a missing optional peer with an empty module rather\n // than rejecting the dynamic import. Keep that path on the same actionable\n // error instead of failing later with \"Class extends undefined\".\n if (typeof DefaultChatTransport !== \"function\") {\n throw new Error(MISSING_AI_SDK_MESSAGE);\n }\n\n class UIMessageStreamParser extends DefaultChatTransport<UIMessage> {\n parseBody(stream: ReadableStream<Uint8Array>): ReadableStream<UIMessageChunk> {\n return this.processResponseStream(stream);\n }\n }\n\n return new UIMessageStreamParser().parseBody(body);\n}\n\nasync function* readChunks(stream: ReadableStream<UIMessageChunk>): AsyncIterable<UIMessageChunk> {\n const reader = stream.getReader();\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) return;\n yield value;\n }\n } finally {\n reader.releaseLock();\n }\n}\n\nfunction toolResult(toolCallId: string, content: string, error?: string): AGUIEvent {\n return {\n type: EventType.TOOL_CALL_RESULT,\n messageId: `tool-result-${toolCallId}`,\n toolCallId,\n content,\n role: \"tool\",\n ...(error !== undefined ? { isError: true, error } : {}),\n } as AGUIEvent;\n}\n\n/**\n * Adapter for Vercel AI SDK v6 and v7 UIMessage streams.\n *\n * The AI SDK is loaded only when parsing begins so it can remain an optional\n * peer dependency for consumers that use other stream adapters. Its\n * `DefaultChatTransport` performs the native SSE decoding and chunk validation;\n * this adapter only maps validated UIMessage chunks to AG-UI events.\n */\nexport const vercelAIAdapter = (): StreamProtocolAdapter => ({\n async *parse(response): AsyncIterable<AGUIEvent> {\n if (!response.body) throw new Error(\"No response body\");\n\n const chunks = await parseUIMessageStream(response.body);\n const startedTools = new Set<string>();\n const streamedToolArgs = new Set<string>();\n const endedTools = new Set<string>();\n let stepIndex = 0;\n\n // AG-UI step events are lifecycle-only. Normalize each AI SDK model step\n // into one assistant message lifecycle here so downstream consumers do not\n // need provider-specific step handling. Open it lazily to avoid producing\n // empty messages for steps whose only chunks are ignored by this adapter.\n let activeStep:\n | {\n stepName: string;\n messageId?: string;\n messageStarted: boolean;\n // Per-step, so a new step resets it without an explicit assignment.\n // Only ever read while a step message is open (see beginText).\n sawTools: boolean;\n }\n | undefined;\n\n const startStepMessage = (preferredMessageId?: string): AGUIEvent | undefined => {\n if (!activeStep || activeStep.messageStarted) return;\n\n activeStep.messageId ??= preferredMessageId ?? `vercel-ai-message-${stepIndex}`;\n activeStep.messageStarted = true;\n return {\n type: EventType.TEXT_MESSAGE_START,\n messageId: activeStep.messageId,\n role: \"assistant\",\n };\n };\n\n // Single entry point for \"a text chunk arrived\": opens the step's message,\n // or closes it and opens a new one when the text follows tool calls.\n //\n // Text that follows tool calls is a new assistant item: commentary like\n // \"Let me do this\" stays on the tool-bearing message and the answer text\n // after it gets its own message id, so a consumer splitting on\n // TEXT_MESSAGE_START keeps both. Streams without `start-step` already give\n // each text part a distinct id, so only the step-scoped message needs this.\n const beginText = (partId: string): AGUIEvent[] => {\n if (activeStep?.messageStarted && activeStep.sawTools) {\n const previousId = activeStep.messageId!;\n activeStep.messageId = partId;\n activeStep.sawTools = false;\n return [\n { type: EventType.TEXT_MESSAGE_END, messageId: previousId },\n { type: EventType.TEXT_MESSAGE_START, messageId: partId, role: \"assistant\" },\n ];\n }\n\n const event = startStepMessage(partId);\n return event ? [event] : [];\n };\n\n const toolParent = () =>\n activeStep?.messageId ? { parentMessageId: activeStep.messageId } : {};\n\n for await (const chunk of readChunks(chunks)) {\n if (\"providerExecuted\" in chunk && chunk.providerExecuted === true) {\n throw new Error(PROVIDER_EXECUTED_TOOLS_UNSUPPORTED_MESSAGE);\n }\n\n switch (chunk.type) {\n case \"start-step\": {\n const stepName = `vercel-ai-step-${++stepIndex}`;\n activeStep = { stepName, messageStarted: false, sawTools: false };\n yield {\n type: EventType.STEP_STARTED,\n stepName,\n };\n break;\n }\n\n case \"finish-step\": {\n const stepName = activeStep?.stepName ?? `vercel-ai-step-${++stepIndex}`;\n if (activeStep?.messageStarted && activeStep.messageId) {\n yield {\n type: EventType.TEXT_MESSAGE_END,\n messageId: activeStep.messageId,\n };\n }\n yield {\n type: EventType.STEP_FINISHED,\n stepName,\n };\n activeStep = undefined;\n break;\n }\n\n case \"text-start\": {\n for (const event of beginText(chunk.id)) yield event;\n if (!activeStep) {\n yield {\n type: EventType.TEXT_MESSAGE_START,\n messageId: chunk.id,\n role: \"assistant\",\n };\n }\n break;\n }\n\n case \"text-delta\": {\n for (const event of beginText(chunk.id)) yield event;\n yield {\n type: EventType.TEXT_MESSAGE_CONTENT,\n messageId: activeStep?.messageId ?? chunk.id,\n delta: chunk.delta,\n };\n break;\n }\n\n case \"text-end\":\n if (!activeStep) {\n yield {\n type: EventType.TEXT_MESSAGE_END,\n messageId: chunk.id,\n };\n }\n break;\n\n case \"tool-input-start\":\n if (!startedTools.has(chunk.toolCallId)) {\n const event = startStepMessage();\n if (event) yield event;\n startedTools.add(chunk.toolCallId);\n if (activeStep) activeStep.sawTools = true;\n yield {\n type: EventType.TOOL_CALL_START,\n toolCallId: chunk.toolCallId,\n toolCallName: chunk.toolName,\n ...toolParent(),\n };\n }\n break;\n\n case \"tool-input-delta\":\n if (chunk.inputTextDelta) {\n streamedToolArgs.add(chunk.toolCallId);\n yield {\n type: EventType.TOOL_CALL_ARGS,\n toolCallId: chunk.toolCallId,\n delta: chunk.inputTextDelta,\n };\n }\n break;\n\n case \"tool-input-available\":\n case \"tool-input-error\": {\n if (!startedTools.has(chunk.toolCallId)) {\n const event = startStepMessage();\n if (event) yield event;\n startedTools.add(chunk.toolCallId);\n if (activeStep) activeStep.sawTools = true;\n yield {\n type: EventType.TOOL_CALL_START,\n toolCallId: chunk.toolCallId,\n toolCallName: chunk.toolName,\n ...toolParent(),\n };\n }\n\n if (!streamedToolArgs.has(chunk.toolCallId)) {\n streamedToolArgs.add(chunk.toolCallId);\n yield {\n type: EventType.TOOL_CALL_ARGS,\n toolCallId: chunk.toolCallId,\n delta: serialize(chunk.input),\n };\n }\n\n if (!endedTools.has(chunk.toolCallId)) {\n endedTools.add(chunk.toolCallId);\n yield {\n type: EventType.TOOL_CALL_END,\n toolCallId: chunk.toolCallId,\n };\n }\n\n if (chunk.type === \"tool-input-error\") {\n yield toolResult(chunk.toolCallId, chunk.errorText, chunk.errorText);\n }\n break;\n }\n\n case \"tool-output-available\":\n yield toolResult(chunk.toolCallId, serialize(chunk.output));\n break;\n\n case \"tool-output-error\":\n yield toolResult(chunk.toolCallId, chunk.errorText, chunk.errorText);\n break;\n\n case \"tool-output-denied\":\n yield toolResult(\n chunk.toolCallId,\n TOOL_EXECUTION_DENIED_MESSAGE,\n TOOL_EXECUTION_DENIED_MESSAGE,\n );\n break;\n\n case \"error\":\n yield {\n type: EventType.RUN_ERROR,\n message: chunk.errorText,\n };\n return;\n }\n }\n\n if (activeStep?.messageStarted && activeStep.messageId) {\n yield {\n type: EventType.TEXT_MESSAGE_END,\n messageId: activeStep.messageId,\n };\n }\n },\n});\n","import { AssistantMessage, EventType, Message, StreamProtocolAdapter, ToolMessage } from \"../types\";\nimport { agUIAdapter } from \"./adapters\";\n\n/**\n * @inline\n */\ninterface Parameters {\n response: Response;\n /** A function that creates a new message in the thread (assistant or tool). */\n createMessage: (message: Message) => void;\n /** A function that updates an existing message in the thread (matched by id). */\n updateMessage: (message: Message) => void;\n /**\n * Marks a tool call as executing (args closed, awaiting result). Wired to the\n * store's `executingToolCallIds` set so `pairToolActivity` can report the\n * `\"executing\"` status. Optional — defaults to a no-op for standalone use.\n */\n markToolExecuting?: (toolCallId: string) => void;\n /** Clears a tool call from the executing set (result landed or errored). */\n clearToolExecuting?: (toolCallId: string) => void;\n /** The adapter to use for parsing the stream */\n adapter?: StreamProtocolAdapter;\n}\n\n/**\n * @category Utilities\n */\nexport const processStreamedMessage = async ({\n response,\n createMessage,\n updateMessage,\n markToolExecuting = () => {},\n clearToolExecuting = () => {},\n adapter = agUIAdapter(),\n}: Parameters): Promise<AssistantMessage | void> => {\n let currentMessage: AssistantMessage = {\n id: crypto.randomUUID(),\n role: \"assistant\",\n content: \"\",\n toolCalls: [],\n };\n\n let isFirst = true;\n\n // The wire message-item id whose text currently streams into currentMessage.\n let currentTextItemId: string | null = null;\n\n // Tool messages by toolCallId, so repeated TOOL_CALL_RESULTs for the same\n // call UPDATE one message in place instead of duplicating it.\n const toolMessagesByCallId = new Map<string, ToolMessage>();\n\n // Tool calls that have started but not yet received a result. On RUN_ERROR\n // these are surfaced as errored tool messages instead of being left hanging.\n const inFlightToolCallIds = new Set<string>();\n\n let rafId: number | null = null;\n const debouncedUpdate = (msg: AssistantMessage) => {\n if (rafId !== null) cancelAnimationFrame(rafId);\n rafId = requestAnimationFrame(() => {\n updateMessage(msg);\n rafId = null;\n });\n };\n\n /** Flush the open assistant and start a fresh one (interleaved segments). */\n const startNewAssistantSegment = () => {\n if (rafId !== null) {\n cancelAnimationFrame(rafId);\n rafId = null;\n if (!isFirst) updateMessage(currentMessage);\n }\n currentMessage = {\n id: crypto.randomUUID(),\n role: \"assistant\",\n content: \"\",\n toolCalls: [],\n };\n isFirst = true;\n currentTextItemId = null;\n };\n\n const messageHasBody = (msg: AssistantMessage) =>\n (msg.content?.length ?? 0) > 0 || (msg.toolCalls?.length ?? 0) > 0;\n\n /** Publish the open assistant only once it has text or tool calls — never an empty shell. */\n const commitCurrentMessage = () => {\n if (isFirst) {\n if (!messageHasBody(currentMessage)) return;\n createMessage(currentMessage);\n isFirst = false;\n } else {\n debouncedUpdate(currentMessage);\n }\n };\n\n for await (const event of adapter.parse(response)) {\n switch (event.type) {\n // TEXT_MESSAGE_CHUNK and TEXT_MESSAGE_CONTENT are very similar events but TEXT_MESSAGE_CHUNK\n // optionally allows for a role change. Since we don't support role changes in processMessage\n // right now, we treat both the same.\n case EventType.TEXT_MESSAGE_CHUNK:\n case EventType.TEXT_MESSAGE_CONTENT: {\n // Ignore empty deltas — a zero-length content event after tools would\n // otherwise open a blank assistant segment that shadows the real answer\n // (common around parallel tool calls when a new message item is opened).\n if (!event.delta) break;\n // Some adapters (LangGraph / ChatOpenAI Responses) keep one wire\n // messageId for a whole model step even when Responses interleaved\n // several message items. Text after tools means a new segment — same\n // split Responses adapters express via a new TEXT_MESSAGE_START id.\n if ((currentMessage.toolCalls?.length ?? 0) > 0) {\n startNewAssistantSegment();\n }\n currentMessage = {\n ...currentMessage,\n content: (currentMessage.content || \"\") + event.delta,\n };\n break;\n }\n\n case EventType.TOOL_CALL_START:\n inFlightToolCallIds.add(event.toolCallId);\n currentMessage = {\n ...currentMessage,\n toolCalls: [\n ...(currentMessage.toolCalls || []),\n {\n id: event.toolCallId,\n type: \"function\",\n function: {\n name: event.toolCallName,\n arguments: \"\",\n },\n },\n ],\n };\n break;\n\n case EventType.TOOL_CALL_END:\n // Args have finished arriving → the call is now executing (awaiting its\n // result), not \"streaming\". Previously this event was dropped and\n // completion was faked from \"did assistant text start\".\n markToolExecuting(event.toolCallId);\n break;\n\n case EventType.TOOL_CALL_ARGS:\n if (currentMessage.toolCalls) {\n const toolCalls = [...currentMessage.toolCalls];\n const toolCallIndex = toolCalls.findIndex((tc) => tc.id === event.toolCallId);\n if (toolCallIndex !== -1) {\n const currentToolCall = toolCalls[toolCallIndex];\n if (currentToolCall) {\n toolCalls[toolCallIndex] = {\n id: currentToolCall.id,\n type: \"function\",\n function: {\n name: currentToolCall.function.name,\n arguments: currentToolCall.function.arguments + event.delta,\n },\n };\n currentMessage = { ...currentMessage, toolCalls };\n }\n }\n }\n break;\n\n case EventType.TOOL_CALL_CHUNK: {\n // Combined convenience form of START + ARGS (AG-UI). Some servers emit\n // only chunks instead of the explicit START/ARGS/END triad; without\n // this case their tool calls would be silently dropped. Lazily START on\n // the first chunk carrying an id, fill the name if it arrives on a later\n // chunk, and append any `delta` as ARGS. (No END is implied — a\n // chunk-only call stays \"streaming\" until its result lands.)\n const id = event.toolCallId;\n if (!id) break;\n const toolCalls = [...(currentMessage.toolCalls || [])];\n let index = toolCalls.findIndex((tc) => tc.id === id);\n if (index === -1) {\n inFlightToolCallIds.add(id);\n toolCalls.push({\n id,\n type: \"function\",\n function: { name: event.toolCallName ?? \"\", arguments: \"\" },\n });\n index = toolCalls.length - 1;\n }\n const existing = toolCalls[index];\n if (existing) {\n toolCalls[index] = {\n id: existing.id,\n type: \"function\",\n function: {\n name: existing.function.name || event.toolCallName || \"\",\n arguments: existing.function.arguments + (event.delta ?? \"\"),\n },\n };\n currentMessage = { ...currentMessage, toolCalls };\n }\n break;\n }\n\n case EventType.TEXT_MESSAGE_START: {\n // A DIFFERENT item id after content/tool calls have accumulated means\n // the model opened a new output message item — interleaving prose with\n // tool calls (several sections in one run). Split into a fresh assistant\n // message so the live structure matches what reload reconstructs from\n // storage\n const startId = (event as { messageId?: string }).messageId ?? null;\n const hasBody =\n (currentMessage.content?.length ?? 0) > 0 || (currentMessage.toolCalls?.length ?? 0) > 0;\n if (hasBody && startId !== currentTextItemId) {\n startNewAssistantSegment();\n }\n currentTextItemId = startId;\n break;\n }\n\n case EventType.TOOL_CALL_RESULT: {\n // Result landed → no longer executing / in flight.\n clearToolExecuting(event.toolCallId);\n inFlightToolCallIds.delete(event.toolCallId);\n\n // The call this result answers may still be waiting on the debounced\n // assistant update (server-side tools stream their call and result\n // back to back). Publish it first, or the result briefly pairs with no\n // call and renders as a nameless tool — for as long as the frame is\n // deferred, which in a background tab is until it's shown again.\n if (rafId !== null) {\n cancelAnimationFrame(rafId);\n rafId = null;\n updateMessage(currentMessage);\n }\n\n // Surface a failure onto the @ag-ui/core ToolMessage.error field. The\n // TOOL_CALL_RESULT schema is `passthrough`, so adapters may carry an\n // `isError` flag and/or `error` string; map either onto `error` so the\n // selector can emit `status:\"error\"` (the previously-dead error branch\n // in ToolResult lights up). Absent any failure signal it stays a\n // success — no regression vs. today.\n const failed = event as unknown as { isError?: boolean; error?: string };\n const errorText =\n failed.isError === true || (typeof failed.error === \"string\" && failed.error.length > 0)\n ? (failed.error ?? event.content)\n : undefined;\n\n // Upsert the tool message for this toolCallId. First result → create;\n // any subsequent result for the same call → update the same message in\n // place (no duplicates).\n const existing = toolMessagesByCallId.get(event.toolCallId);\n if (existing) {\n const updated: ToolMessage = {\n ...existing,\n content: event.content,\n ...(errorText ? { error: errorText } : {}),\n };\n toolMessagesByCallId.set(event.toolCallId, updated);\n updateMessage(updated);\n } else {\n const toolMessage: ToolMessage = {\n id: crypto.randomUUID(),\n role: \"tool\",\n toolCallId: event.toolCallId,\n content: event.content,\n ...(errorText ? { error: errorText } : {}),\n };\n toolMessagesByCallId.set(event.toolCallId, toolMessage);\n createMessage(toolMessage);\n }\n continue; // skip the trailing isFirst/update logic — this event doesn't touch currentMessage\n }\n\n case EventType.RUN_ERROR: {\n const raw = (event as any).message || (event as any).error || \"Stream error\";\n const errorText = typeof raw === \"string\" ? raw : JSON.stringify(raw);\n\n // RUN_ERROR carries no toolCallId. Clear the executing flag for any\n // tool call still in flight (started, no result yet) so it doesn't spin\n // forever, but do NOT synthesize an empty-content tool message for it —\n // an empty result would blank an in-flight renderer (e.g. an artifact\n // skeleton). A call that already streamed a result was removed from the\n // in-flight set on TOOL_CALL_RESULT, so it keeps its delivered content.\n // The failure surfaces as the thread-level error thrown below.\n for (const toolCallId of inFlightToolCallIds) {\n clearToolExecuting(toolCallId);\n }\n inFlightToolCallIds.clear();\n\n throw new Error(errorText);\n }\n }\n\n commitCurrentMessage();\n }\n\n if (rafId !== null) {\n // flush any update\n cancelAnimationFrame(rafId);\n updateMessage(currentMessage);\n } else if (isFirst && messageHasBody(currentMessage)) {\n // Last event was a no-op (e.g. empty delta) after body landed in memory only.\n createMessage(currentMessage);\n }\n\n return currentMessage;\n};\n","import { ObservabilityLevel } from \"@openuidev/observability\";\nimport { getResponseErrorMessage } from \"../adapters/httpError\";\n\nexport async function buildObservabilityErrorDetail(response: Response) {\n if (response.ok) return {};\n\n try {\n const res = await response.clone().json();\n return {\n error: res?.error,\n ...(!res?.message\n ? { message: await getResponseErrorMessage(response) }\n : { message: res.message }),\n };\n } catch {\n return { message: await getResponseErrorMessage(response) };\n }\n}\n\nexport function levelForStatus(status: number): ObservabilityLevel {\n return status >= 400 ? \"error\" : \"info\";\n}\n","import { observability } from \"@openuidev/observability\";\nimport { createStore } from \"zustand/vanilla\";\nimport { subscribeWithSelector } from \"zustand/middleware\";\nimport { getResponseErrorMessage } from \"../adapters/httpError\";\nimport type { ChatLLM, ChatStorage } from \"../adapters/types\";\nimport { processStreamedMessage } from \"../stream/processStreamedMessage\";\nimport { buildObservabilityErrorDetail, levelForStatus } from \"./observability\";\nimport type { ChatStore, Message, Thread, UserMessage } from \"./types\";\n\nexport interface CreateChatStoreConfig {\n storage: ChatStorage;\n llm: ChatLLM;\n}\n\nconst mergeThreadList = (existing: Thread[], incoming: Thread[]): Thread[] =>\n Array.from(new Map([...existing, ...incoming].map((t) => [t.id, t])).values()).sort(\n (a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime(),\n );\n\n// Takes the ref itself and reads `current` at call time, so the caller\n// (ChatProvider) can refresh `llm` by mutating or replacing `current`.\nexport const createChatStore = (configRef: { current: CreateChatStoreConfig }) => {\n const { storage } = configRef.current;\n const { thread: threadStorage } = storage;\n\n const store = createStore<ChatStore>()(\n subscribeWithSelector((set, get) => ({\n // Thread List State\n threads: [],\n isLoadingThreads: false,\n threadListError: null,\n selectedThreadId: null,\n hasMoreThreads: false,\n _nextCursor: undefined,\n\n // Thread State\n messages: [],\n isRunning: false,\n isLoadingMessages: false,\n threadError: null,\n executingToolCallIds: new Set<string>(),\n _abortController: null,\n\n // ── Thread List Actions ──\n\n loadThreads: () => {\n set({ isLoadingThreads: true, threadListError: null });\n threadStorage\n .listThreads(undefined)\n .then(({ threads = [], nextCursor }) => {\n set({\n threads,\n isLoadingThreads: false,\n _nextCursor: nextCursor,\n hasMoreThreads: nextCursor !== undefined,\n });\n })\n .catch((e) => {\n set({ isLoadingThreads: false, threadListError: e });\n });\n },\n\n loadMoreThreads: () => {\n const cursor = get()._nextCursor;\n if (cursor === undefined) return;\n threadStorage\n .listThreads(cursor)\n .then(({ threads = [], nextCursor }) => {\n set((s) => ({\n threads: mergeThreadList(s.threads, threads),\n _nextCursor: nextCursor,\n hasMoreThreads: nextCursor !== undefined,\n }));\n })\n .catch((e) => {\n set({ threadListError: e });\n });\n },\n\n switchToNewThread: () => {\n get().cancelMessage();\n set({\n selectedThreadId: null,\n messages: [],\n threadError: null,\n executingToolCallIds: new Set<string>(),\n });\n },\n\n createThread: async (firstMessage: UserMessage) => {\n const thread = await threadStorage.createThread(firstMessage);\n set((s) => ({ threads: mergeThreadList(s.threads, [thread]) }));\n return thread;\n },\n\n selectThread: (threadId: string) => {\n // Re-selecting the active thread is a no-op — don't wipe and refetch.\n if (get().selectedThreadId === threadId) return;\n get().cancelMessage();\n set({\n selectedThreadId: threadId,\n messages: [],\n isLoadingMessages: true,\n threadError: null,\n executingToolCallIds: new Set<string>(),\n });\n threadStorage\n .getMessages(threadId)\n .then((messages) => set({ messages, isLoadingMessages: false }))\n .catch((e) => set({ threadError: e, isLoadingMessages: false }));\n },\n\n updateThread: (thread: Thread) => {\n const setPending = (id: string, isPending: boolean) =>\n set((s) => ({ threads: s.threads.map((t) => (t.id === id ? { ...t, isPending } : t)) }));\n setPending(thread.id, true);\n threadStorage\n .updateThread(thread)\n .then((updated) => {\n set((s) => ({\n threads: s.threads.map((t) => (t.id === updated.id ? updated : t)),\n }));\n })\n .catch(() => setPending(thread.id, false));\n },\n\n deleteThread: (threadId: string) => {\n const setPending = (id: string, isPending: boolean) =>\n set((s) => ({ threads: s.threads.map((t) => (t.id === id ? { ...t, isPending } : t)) }));\n setPending(threadId, true);\n threadStorage\n .deleteThread(threadId)\n .then(() => {\n const state = get();\n set({ threads: state.threads.filter((t) => t.id !== threadId) });\n if (state.selectedThreadId === threadId) {\n state.switchToNewThread();\n }\n })\n .catch(() => setPending(threadId, false));\n },\n\n // ── Thread Actions ──\n\n processMessage: async (message) => {\n const state = get();\n if (state.isRunning) return;\n\n const abortController = new AbortController();\n const optimisticMessage: UserMessage = {\n ...message,\n id: crypto.randomUUID(),\n role: \"user\",\n };\n\n set({\n _abortController: abortController,\n isRunning: true,\n threadError: null,\n executingToolCallIds: new Set<string>(),\n });\n set((s) => ({ messages: [...s.messages, optimisticMessage] }));\n\n abortController.signal.addEventListener(\"abort\", () => {\n set({ _abortController: null, isRunning: false });\n });\n\n try {\n let threadId = get().selectedThreadId;\n\n if (!threadId) {\n const created = await get().createThread(optimisticMessage);\n threadId = created.id;\n set({ selectedThreadId: threadId });\n }\n\n const runId = crypto.randomUUID();\n\n observability.info({\n kind: \"LLM:request\",\n threadId,\n runId,\n // message is a reserved keyword for the observability library expecting string\n userMessage: optimisticMessage,\n });\n\n let response: Response | null = null;\n try {\n response = await configRef.current.llm.send({\n threadId,\n messages: get().messages,\n signal: abortController.signal,\n });\n\n observability(levelForStatus(response.status), {\n kind: response.ok ? \"LLM:response\" : \"LLM:error\",\n threadId,\n status: response.status,\n ok: response.ok,\n runId,\n ...(await buildObservabilityErrorDetail(response)),\n });\n\n if (!response.ok) {\n throw new Error(await getResponseErrorMessage(response));\n }\n } catch (e) {\n observability.error({\n kind: \"LLM:error\",\n threadId,\n runId,\n error: e instanceof Error ? e : new Error(String(e)),\n });\n throw e;\n }\n\n await processStreamedMessage({\n response,\n createMessage: (msg) => set((s) => ({ messages: [...s.messages, msg] })),\n updateMessage: (msg) =>\n set((s) => ({\n messages: s.messages.map((m) => (m.id === msg.id ? msg : m)),\n })),\n // A tool's args have closed (TOOL_CALL_END) → it is now executing.\n markToolExecuting: (id) =>\n set((s) =>\n s.executingToolCallIds.has(id)\n ? s\n : { executingToolCallIds: new Set(s.executingToolCallIds).add(id) },\n ),\n // Its result landed (or it errored) → no longer executing.\n clearToolExecuting: (id) =>\n set((s) => {\n if (!s.executingToolCallIds.has(id)) return s;\n const next = new Set(s.executingToolCallIds);\n next.delete(id);\n return { executingToolCallIds: next };\n }),\n adapter: configRef.current.llm.streamProtocol,\n });\n } catch (e) {\n if (!abortController.signal.aborted) {\n set({ threadError: e instanceof Error ? e : new Error(String(e)) });\n }\n } finally {\n // Clear any tool calls still flagged \"executing\" — adapters that emit\n // TOOL_CALL_END without a matching TOOL_CALL_RESULT (e.g. client-side\n // tool calls in the OpenAI adapters) would otherwise leave them stuck\n // in the executing set after the run ends.\n set({\n _abortController: null,\n isRunning: false,\n executingToolCallIds: new Set<string>(),\n });\n }\n },\n\n appendMessages: (...newMessages: Message[]) => {\n set((s) => ({ messages: [...s.messages, ...newMessages] }));\n },\n\n updateMessage: (message: Message) => {\n set((s) => ({\n messages: s.messages.map((m) => (m.id === message.id ? message : m)),\n }));\n },\n\n setMessages: (messages: Message[]) => {\n set({ messages });\n },\n\n deleteMessage: (messageId: string) => {\n set((s) => ({ messages: s.messages.filter((m) => m.id !== messageId) }));\n },\n\n cancelMessage: () => {\n get()._abortController?.abort();\n },\n })),\n );\n\n return store;\n};\n","import { createStore } from \"zustand/vanilla\";\nimport { subscribeWithSelector } from \"zustand/middleware\";\nimport type { DetailedViewStore } from \"./detailedViewTypes\";\n\n/**\n * Creates a Zustand store managing detailed-view state.\n * Instantiated once by `ChatProvider` — consumers should not call this directly.\n *\n * @internal\n */\nexport const createDetailedViewStore = () => {\n return createStore<DetailedViewStore>()(\n subscribeWithSelector((set, get) => ({\n activeDetailedViewId: null,\n\n setActiveDetailedView: (id) => {\n set({ activeDetailedViewId: id });\n },\n\n reset: () => {\n set({ activeDetailedViewId: null });\n },\n\n _detailedViewPanelNode: null,\n _setDetailedViewPanelNode: (node) => {\n if (\n typeof process !== \"undefined\" &&\n process.env?.[\"NODE_ENV\"] !== \"production\" &&\n node &&\n get()._detailedViewPanelNode &&\n get()._detailedViewPanelNode !== node\n ) {\n console.warn(\n \"[OpenUI] Multiple DetailedViewPortalTarget instances detected. \" +\n \"Only one should be mounted at a time.\",\n );\n }\n set({ _detailedViewPanelNode: node });\n },\n })),\n );\n};\n","import { createStore } from \"zustand/vanilla\";\nimport { subscribeWithSelector } from \"zustand/middleware\";\nimport type { ArtifactEntry, ThreadContextStore } from \"./threadContextTypes\";\n\nconst entriesEqual = (a: ArtifactEntry, b: ArtifactEntry) =>\n a.heading === b.heading && a.type === b.type;\n\nconst upsertVersion = (\n registry: Record<string, ArtifactEntry[]>,\n entry: ArtifactEntry,\n): Record<string, ArtifactEntry[]> => {\n const existing = registry[entry.id] ?? [];\n const sameVersionIdx = existing.findIndex((e) => e.version === entry.version);\n\n if (sameVersionIdx !== -1) {\n const current = existing[sameVersionIdx]!;\n if (entriesEqual(current, entry)) return registry;\n const next = existing.slice();\n next[sameVersionIdx] = entry;\n return { ...registry, [entry.id]: next };\n }\n\n // Insert sorted ascending by version.\n const insertIdx = existing.findIndex((e) => e.version > entry.version);\n const next =\n insertIdx === -1\n ? [...existing, entry]\n : [...existing.slice(0, insertIdx), entry, ...existing.slice(insertIdx)];\n return { ...registry, [entry.id]: next };\n};\n\nconst removeVersion = (\n registry: Record<string, ArtifactEntry[]>,\n id: string,\n version: number,\n): Record<string, ArtifactEntry[]> => {\n const existing = registry[id];\n if (!existing) return registry;\n const idx = existing.findIndex((e) => e.version === version);\n if (idx === -1) return registry;\n\n if (existing.length === 1) {\n const { [id]: _removed, ...rest } = registry;\n return rest;\n }\n\n const next = existing.slice();\n next.splice(idx, 1);\n return { ...registry, [id]: next };\n};\n\n/**\n * Creates a Zustand store managing the per-thread artifact registry.\n *\n * Active detailed-view state lives in a separate store\n * (see {@link useDetailedView} / {@link useActiveDetailedView}) — TC tracks\n * what's *attached* to the thread; detailed-view state tracks what's *visible*.\n *\n * Instantiated once by `ChatProvider` — consumers should not call this directly.\n *\n * @internal\n */\nexport const createThreadContextStore = () => {\n return createStore<ThreadContextStore>()(\n subscribeWithSelector((set) => ({\n artifacts: {},\n\n registerArtifact: (entry) => {\n set((s) => ({ artifacts: upsertVersion(s.artifacts, entry) }));\n },\n\n unregisterArtifact: (id, version) => {\n set((s) => ({ artifacts: removeVersion(s.artifacts, id, version) }));\n },\n\n reset: () => {\n set({ artifacts: {} });\n },\n })),\n );\n};\n","import {\n computed,\n defineComponent,\n onMounted,\n onUpdated,\n onScopeDispose,\n provide,\n watch,\n type PropType,\n type VNodeChild,\n} from \"vue\";\nimport type { ChatLLM, ChatStorage, ArtifactCategory } from \"../adapters/types\";\nimport type { ArtifactRendererConfig } from \"./artifactRendererTypes\";\nimport { createDefaultInMemoryStorage } from \"../adapters/_defaultStorage\";\nimport { useArtifactAutoOpenWatcher } from \"./artifactAutoOpenWatcher\";\nimport { ArtifactCategoriesContext } from \"./ArtifactCategoriesContext\";\nimport {\n ArtifactRenderersContext,\n buildArtifactRendererRegistry,\n} from \"./ArtifactRenderersContext\";\nimport { ArtifactStorageContext } from \"./ArtifactStorageContext\";\nimport { ChatContext } from \"./ChatContext\";\nimport { createChatStore } from \"./createChatStore\";\nimport { createDetailedViewStore } from \"./createDetailedViewStore\";\nimport { createThreadContextStore } from \"./createThreadContextStore\";\nimport { DetailedViewContext } from \"./DetailedViewContext\";\nimport { ThreadContextContext } from \"./ThreadContextContext\";\n\nconst EMPTY_CATEGORIES: never[] = [];\n\nexport const ChatProvider = defineComponent({\n name: \"OpenUIChatProvider\",\n props: {\n llm: { type: Object as PropType<ChatLLM>, required: true },\n storage: Object as PropType<ChatStorage>,\n artifactRenderers: Array as PropType<ReadonlyArray<ArtifactRendererConfig<any>>>,\n artifactCategories: Array as PropType<ArtifactCategory[]>,\n artifactAutoOpen: { type: Boolean, default: true },\n children: null as unknown as PropType<VNodeChild>,\n },\n setup(props, { slots }) {\n const storage = props.storage ?? createDefaultInMemoryStorage();\n const config = { current: { storage, llm: props.llm } };\n watch(\n () => props.llm,\n (value) => {\n config.current.llm = value;\n },\n { flush: \"sync\" },\n );\n const chat = createChatStore(config);\n const detail = createDetailedViewStore();\n const thread = createThreadContextStore();\n const registry = buildArtifactRendererRegistry(props.artifactRenderers ?? []);\n const initialRenderers = props.artifactRenderers;\n let warned = false;\n // A parent updated hook runs after child commits, like the source warning's\n // passive effect. A pre-flush watcher would warn before the child commits.\n onUpdated(() => {\n const renderers = props.artifactRenderers;\n if (\n typeof process !== \"undefined\" &&\n process.env.NODE_ENV !== \"production\" &&\n !warned &&\n renderers !== initialRenderers\n ) {\n console.warn(\n \"[OpenUI] `artifactRenderers` prop changed after ChatProvider mount. The original array is kept; new renderers will not be registered. Memoize the array (useMemo) to avoid this warning.\",\n );\n warned = true;\n }\n });\n let unsubscribe: (() => void) | undefined;\n onMounted(() => {\n unsubscribe = chat.subscribe(\n (state) => state.selectedThreadId,\n () => {\n detail.getState().reset();\n thread.getState().reset();\n },\n );\n });\n onScopeDispose(() => unsubscribe?.());\n useArtifactAutoOpenWatcher(() => props.artifactAutoOpen ?? true, chat, thread, detail);\n provide(ChatContext, chat);\n provide(DetailedViewContext, detail);\n provide(ThreadContextContext, thread);\n provide(ArtifactRenderersContext, registry);\n provide(ArtifactStorageContext, storage.artifact ?? null);\n provide(\n ArtifactCategoriesContext,\n computed(() => props.artifactCategories ?? EMPTY_CATEGORIES),\n );\n return () => slots.default?.() ?? props.children;\n },\n});\n","import type { AssistantMessage, Message, ToolMessage, UserMessage } from \"../../types\";\nimport type { MessageFormat } from \"../../types/messageFormat\";\n\n// ── LangGraph / LangChain message types ──────────────────────────\n\n/**\n * LangChain-style message as returned by the LangGraph thread state API.\n * Each message carries a `type` discriminator (`\"human\"`, `\"ai\"`, `\"tool\"`,\n * `\"system\"`) and uses snake_case field names.\n */\ninterface LangChainMessage {\n id?: string;\n type: \"human\" | \"ai\" | \"tool\" | \"system\" | \"developer\" | (string & {});\n content: string | Array<{ type: string; text?: string }>;\n name?: string;\n tool_calls?: Array<{\n id: string;\n name: string;\n args: Record<string, unknown> | string;\n }>;\n tool_call_id?: string;\n}\n\n// ── Outbound (AG-UI → LangGraph) ────────────────────────────────\n\nfunction toLangChainMessage(message: Message): LangChainMessage {\n switch (message.role) {\n case \"user\":\n return { type: \"human\", content: message.content ?? \"\" };\n\n case \"assistant\": {\n const result: LangChainMessage = { type: \"ai\", content: message.content ?? \"\" };\n if (message.toolCalls?.length) {\n result.tool_calls = message.toolCalls.map((tc) => ({\n id: tc.id,\n name: tc.function.name,\n args: safeParseArgs(tc.function.arguments),\n }));\n }\n return result;\n }\n\n case \"tool\":\n return {\n type: \"tool\",\n content: message.content,\n tool_call_id: message.toolCallId,\n };\n\n case \"system\":\n return { type: \"system\", content: message.content };\n\n case \"developer\":\n return { type: \"system\", content: message.content };\n\n default:\n return { type: \"system\", content: \"\" };\n }\n}\n\n// ── Inbound (LangGraph → AG-UI) ────────────────────────────────\n\nfunction fromLangChainMessage(msg: LangChainMessage): Message {\n const id = msg.id ?? crypto.randomUUID();\n\n switch (msg.type) {\n case \"human\":\n return { id, role: \"user\", content: extractContent(msg.content) } satisfies UserMessage;\n\n case \"ai\": {\n const result: AssistantMessage = {\n id,\n role: \"assistant\",\n content: extractContent(msg.content),\n };\n if (msg.tool_calls?.length) {\n result.toolCalls = msg.tool_calls.map((tc) => ({\n id: tc.id,\n type: \"function\" as const,\n function: {\n name: tc.name,\n arguments: typeof tc.args === \"string\" ? tc.args : JSON.stringify(tc.args),\n },\n }));\n }\n return result;\n }\n\n case \"tool\":\n return {\n id,\n role: \"tool\",\n content: extractContent(msg.content),\n toolCallId: msg.tool_call_id ?? \"\",\n } satisfies ToolMessage;\n\n case \"system\":\n case \"developer\":\n return { id, role: \"system\", content: extractContent(msg.content) };\n\n default:\n return { id, role: \"system\", content: extractContent(msg.content) };\n }\n}\n\n// ── Helpers ──────────────────────────────────────────────────────\n\nfunction extractContent(content: string | Array<{ type: string; text?: string }>): string {\n if (typeof content === \"string\") return content;\n return content\n .filter((block) => block.type === \"text\" && block.text)\n .map((block) => block.text!)\n .join(\"\");\n}\n\nfunction safeParseArgs(args: string): Record<string, unknown> | string {\n try {\n return JSON.parse(args) as Record<string, unknown>;\n } catch {\n return args;\n }\n}\n\n// ── MessageFormat implementation ─────────────────────────────────\n\n/**\n * Converts between AG-UI message format and LangGraph's LangChain-style\n * message format.\n *\n * LangGraph uses `type` discriminators (`\"human\"`, `\"ai\"`, `\"tool\"`,\n * `\"system\"`) instead of `role`, and tool call arguments are objects\n * rather than JSON strings.\n *\n * AG-UI → LangGraph (toApi):\n * - Maps `role` to `type` (`\"user\"` → `\"human\"`, `\"assistant\"` → `\"ai\"`)\n * - Converts `toolCalls[].function.arguments` from JSON string to object\n * - Converts `toolCallId` → `tool_call_id`\n *\n * LangGraph → AG-UI (fromApi):\n * - Maps `type` to `role` (`\"human\"` → `\"user\"`, `\"ai\"` → `\"assistant\"`)\n * - Converts tool call `args` object to JSON string\n * - Generates `id` via `crypto.randomUUID()` if not present\n */\nexport const langGraphMessageFormat: MessageFormat = {\n toApi(messages: Message[]): LangChainMessage[] {\n return messages.map(toLangChainMessage);\n },\n\n fromApi(data: unknown): Message[] {\n return (data as LangChainMessage[]).map(fromLangChainMessage);\n },\n};\n\nexport type { LangChainMessage as LangGraphMessageFormat };\n","import type {\n ChatCompletionAssistantMessageParam,\n ChatCompletionMessageParam,\n ChatCompletionToolMessageParam,\n ChatCompletionUserMessageParam,\n} from \"openai/resources/chat/completions\";\nimport type { AssistantMessage, Message, ToolMessage, UserMessage } from \"../../types\";\nimport type { MessageFormat } from \"../../types/messageFormat\";\n\n// ── Outbound (AG-UI → OpenAI Completions) ───────────────────────\n\nfunction toOpenAIUserMessage(message: UserMessage): ChatCompletionUserMessageParam {\n const content = message.content;\n\n if (typeof content === \"string\") {\n return { role: \"user\", content };\n }\n\n const parts: ChatCompletionUserMessageParam[\"content\"] =\n content?.map((part) => {\n if (part.type === \"text\") {\n return { type: \"text\" as const, text: part.text };\n }\n if (part.type === \"binary\") {\n const url = part.url ?? `data:${part.mimeType};base64,${part.data ?? \"\"}`;\n return { type: \"image_url\" as const, image_url: { url } };\n }\n return { type: \"text\" as const, text: \"\" };\n }) ?? [];\n\n return { role: \"user\", content: parts };\n}\n\nfunction toOpenAIAssistantMessage(message: AssistantMessage): ChatCompletionAssistantMessageParam {\n const result: ChatCompletionAssistantMessageParam = {\n role: \"assistant\",\n content: message.content ?? null,\n };\n\n if (message.toolCalls?.length) {\n result.tool_calls = message.toolCalls.map((tc) => ({\n id: tc.id,\n type: \"function\" as const,\n function: {\n name: tc.function.name,\n arguments: tc.function.arguments,\n },\n }));\n }\n\n return result;\n}\n\nfunction toOpenAIToolMessage(message: ToolMessage): ChatCompletionToolMessageParam {\n return {\n role: \"tool\",\n content: message.content,\n tool_call_id: message.toolCallId,\n };\n}\n\nfunction toOpenAI(message: Message): ChatCompletionMessageParam {\n switch (message.role) {\n case \"user\":\n return toOpenAIUserMessage(message);\n case \"assistant\":\n return toOpenAIAssistantMessage(message);\n case \"tool\":\n return toOpenAIToolMessage(message);\n case \"system\":\n return { role: \"system\", content: message.content };\n case \"developer\":\n return { role: \"developer\", content: message.content };\n default:\n // reasoning, activity — map to system as fallback\n return { role: \"system\", content: \"\" };\n }\n}\n\n// ── Inbound (OpenAI Completions → AG-UI) ────────────────────────\n\nfunction fromOpenAIAssistant(msg: ChatCompletionAssistantMessageParam): AssistantMessage {\n const content = typeof msg.content === \"string\" ? msg.content : undefined;\n\n const result: AssistantMessage = {\n id: crypto.randomUUID(),\n role: \"assistant\",\n content,\n };\n\n if (msg.tool_calls?.length) {\n result.toolCalls = msg.tool_calls\n .filter((tc): tc is Extract<typeof tc, { type: \"function\" }> => tc.type === \"function\")\n .map((tc) => ({\n id: tc.id,\n type: \"function\" as const,\n function: {\n name: tc.function.name,\n arguments: tc.function.arguments,\n },\n }));\n }\n\n return result;\n}\n\nfunction fromOpenAIUser(msg: ChatCompletionUserMessageParam): UserMessage {\n if (typeof msg.content === \"string\") {\n return { id: crypto.randomUUID(), role: \"user\", content: msg.content };\n }\n\n const content = msg.content.map((part): { type: \"text\"; text: string } => {\n if (part.type === \"text\") return { type: \"text\", text: part.text };\n return { type: \"text\", text: \"\" };\n });\n\n return { id: crypto.randomUUID(), role: \"user\", content };\n}\n\nfunction fromOpenAITool(msg: ChatCompletionToolMessageParam): ToolMessage {\n const content =\n typeof msg.content === \"string\" ? msg.content : msg.content.map((p) => p.text).join(\"\");\n\n return {\n id: crypto.randomUUID(),\n role: \"tool\",\n content,\n toolCallId: msg.tool_call_id,\n };\n}\n\nfunction fromOpenAI(data: ChatCompletionMessageParam): Message {\n switch (data.role) {\n case \"user\":\n return fromOpenAIUser(data);\n case \"assistant\":\n return fromOpenAIAssistant(data);\n case \"tool\":\n return fromOpenAITool(data);\n case \"system\":\n return {\n id: crypto.randomUUID(),\n role: \"system\",\n content: typeof data.content === \"string\" ? data.content : \"\",\n };\n case \"developer\":\n return {\n id: crypto.randomUUID(),\n role: \"developer\",\n content: typeof data.content === \"string\" ? data.content : \"\",\n };\n default:\n return { id: crypto.randomUUID(), role: \"system\", content: \"\" };\n }\n}\n\n// ── MessageFormat implementation ─────────────────────────────────\n\n/**\n * Converts between AG-UI message format and OpenAI **Chat Completions**\n * message format (`ChatCompletionMessageParam`).\n *\n * This is a 1-to-1 mapping — each AG-UI message becomes exactly one\n * `ChatCompletionMessageParam` and vice versa.\n *\n * AG-UI → OpenAI (toApi):\n * - Strips `id` (OpenAI doesn't use message IDs)\n * - Converts `toolCalls` → `tool_calls`\n * - Converts `toolCallId` → `tool_call_id`\n * - Converts multipart `content` arrays to OpenAI content format\n *\n * OpenAI → AG-UI (fromApi):\n * - Generates `id` via `crypto.randomUUID()`\n * - Converts `tool_calls` → `toolCalls`\n * - Converts `tool_call_id` → `toolCallId`\n */\nexport const openAIMessageFormat: MessageFormat = {\n toApi(messages: Message[]): ChatCompletionMessageParam[] {\n return messages.map(toOpenAI);\n },\n\n fromApi(data: unknown): Message[] {\n return (data as ChatCompletionMessageParam[]).map(fromOpenAI);\n },\n};\n","import type { DynamicToolUIPart, UIMessage } from \"ai\";\nimport type { InputContent, Message, ToolCall, ToolMessage, UserMessage } from \"../../types\";\nimport type { MessageFormat } from \"../../types/messageFormat\";\n\nconst PROVIDER_EXECUTED_TOOLS_UNSUPPORTED_MESSAGE =\n \"Vercel AI SDK provider-executed tools are not supported because AG-UI messages cannot preserve providerExecuted semantics.\";\n\ntype UnknownRecord = Record<string, unknown> & {\n data?: unknown;\n errorText?: unknown;\n filename?: unknown;\n id?: unknown;\n input?: unknown;\n mediaType?: unknown;\n mimeType?: unknown;\n output?: unknown;\n parts?: unknown;\n providerExecuted?: unknown;\n role?: unknown;\n source?: unknown;\n state?: unknown;\n text?: unknown;\n toolCallId?: unknown;\n toolName?: unknown;\n type?: unknown;\n url?: unknown;\n value?: unknown;\n};\n\ntype ValidUIMessage = UnknownRecord & {\n id: string;\n role: \"system\" | \"user\" | \"assistant\";\n parts: unknown[];\n};\n\nfunction isRecord(value: unknown): value is UnknownRecord {\n return value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n\nfunction isProviderExecuted(value: unknown): boolean {\n return isRecord(value) && value.providerExecuted === true;\n}\n\nfunction serialize(value: unknown): string {\n if (typeof value === \"string\") return value;\n\n try {\n return JSON.stringify(value) ?? String(value);\n } catch {\n return String(value);\n }\n}\n\nfunction parseToolInput(value: string): unknown {\n try {\n return JSON.parse(value) as unknown;\n } catch {\n return value;\n }\n}\n\nfunction dataUrl(mediaType: string, data: string): string {\n return `data:${mediaType};base64,${data}`;\n}\n\nfunction mediaTypeForPart(part: UnknownRecord, source: UnknownRecord): string {\n if (typeof source.mimeType === \"string\") return source.mimeType;\n\n switch (part.type) {\n case \"image\":\n return \"image/*\";\n case \"audio\":\n return \"audio/*\";\n case \"video\":\n return \"video/*\";\n default:\n return \"application/octet-stream\";\n }\n}\n\nfunction toUserParts(content: UserMessage[\"content\"]): UIMessage[\"parts\"] {\n if (typeof content === \"string\") {\n return [{ type: \"text\", text: content }];\n }\n\n if (!Array.isArray(content)) return [];\n\n return content.flatMap((part): UIMessage[\"parts\"] => {\n if (!isRecord(part)) return [];\n\n if (part.type === \"text\" && typeof part.text === \"string\") {\n return [{ type: \"text\", text: part.text }];\n }\n\n if (part.type === \"binary\") {\n const mediaType =\n typeof part.mimeType === \"string\" ? part.mimeType : \"application/octet-stream\";\n const url =\n typeof part.url === \"string\"\n ? part.url\n : typeof part.data === \"string\"\n ? dataUrl(mediaType, part.data)\n : undefined;\n\n if (!url) return [];\n\n return [\n {\n type: \"file\",\n mediaType,\n url,\n ...(typeof part.filename === \"string\" ? { filename: part.filename } : {}),\n },\n ];\n }\n\n switch (part.type) {\n case \"image\":\n case \"audio\":\n case \"video\":\n case \"document\": {\n if (!isRecord(part.source) || typeof part.source.value !== \"string\") return [];\n\n const mediaType = mediaTypeForPart(part, part.source);\n const url =\n part.source.type === \"data\"\n ? dataUrl(mediaType, part.source.value)\n : part.source.type === \"url\"\n ? part.source.value\n : undefined;\n\n return url ? [{ type: \"file\", mediaType, url }] : [];\n }\n default:\n return [];\n }\n });\n}\n\nfunction toToolPart(toolCall: ToolCall, result: ToolMessage | undefined): DynamicToolUIPart {\n if (isProviderExecuted(toolCall) || isProviderExecuted(result)) {\n throw new Error(PROVIDER_EXECUTED_TOOLS_UNSUPPORTED_MESSAGE);\n }\n\n const input = parseToolInput(toolCall.function.arguments);\n\n if (result?.error) {\n return {\n type: \"dynamic-tool\",\n toolName: toolCall.function.name,\n toolCallId: toolCall.id,\n state: \"output-error\",\n input,\n errorText: result.error,\n };\n }\n\n if (result) {\n return {\n type: \"dynamic-tool\",\n toolName: toolCall.function.name,\n toolCallId: toolCall.id,\n state: \"output-available\",\n input,\n output: result.content,\n };\n }\n\n return {\n type: \"dynamic-tool\",\n toolName: toolCall.function.name,\n toolCallId: toolCall.id,\n state: \"input-available\",\n input,\n };\n}\n\nfunction toVercelMessages(messages: Message[]): UIMessage[] {\n const toolResults = new Map<string, ToolMessage>();\n\n for (const message of messages) {\n if (message.role === \"tool\") toolResults.set(message.toolCallId, message);\n }\n\n const result: UIMessage[] = [];\n\n for (const message of messages) {\n switch (message.role) {\n case \"user\":\n result.push({ id: message.id, role: \"user\", parts: toUserParts(message.content) });\n break;\n\n case \"assistant\": {\n const parts: UIMessage[\"parts\"] = [];\n\n if (typeof message.content === \"string\" && message.content.length > 0) {\n parts.push({ type: \"text\", text: message.content });\n }\n\n for (const toolCall of message.toolCalls ?? []) {\n parts.push(toToolPart(toolCall, toolResults.get(toolCall.id)));\n }\n\n result.push({ id: message.id, role: \"assistant\", parts });\n break;\n }\n\n case \"system\":\n case \"developer\":\n result.push({\n id: message.id,\n role: \"system\",\n parts: [{ type: \"text\", text: message.content }],\n });\n break;\n\n // Vercel UIMessage has no standalone tool-result, reasoning, or activity role.\n // Tool results were folded into their matching assistant parts above.\n default:\n break;\n }\n }\n\n return result;\n}\n\nfunction validUIMessage(value: unknown): value is ValidUIMessage {\n return (\n isRecord(value) &&\n typeof value.id === \"string\" &&\n (value.role === \"system\" || value.role === \"user\" || value.role === \"assistant\") &&\n Array.isArray(value.parts)\n );\n}\n\nfunction textFromParts(parts: unknown[]): string {\n return parts\n .filter(\n (part): part is UnknownRecord & { type: \"text\"; text: string } =>\n isRecord(part) && part.type === \"text\" && typeof part.text === \"string\",\n )\n .map((part) => part.text)\n .join(\"\");\n}\n\nfunction binaryFromFilePart(part: UnknownRecord): InputContent | undefined {\n if (part.type !== \"file\" || typeof part.mediaType !== \"string\" || typeof part.url !== \"string\") {\n return undefined;\n }\n\n const base64Prefix = `data:${part.mediaType};base64,`;\n const source = part.url.startsWith(base64Prefix)\n ? { data: part.url.slice(base64Prefix.length) }\n : { url: part.url };\n\n return {\n type: \"binary\",\n mimeType: part.mediaType,\n ...source,\n ...(typeof part.filename === \"string\" ? { filename: part.filename } : {}),\n };\n}\n\nfunction fromVercelUser(message: ValidUIMessage): UserMessage {\n const contentParts: InputContent[] = [];\n let hasFile = false;\n\n for (const part of message.parts) {\n if (!isRecord(part)) continue;\n\n if (part.type === \"text\" && typeof part.text === \"string\") {\n contentParts.push({ type: \"text\", text: part.text });\n continue;\n }\n\n const binary = binaryFromFilePart(part);\n if (binary) {\n hasFile = true;\n contentParts.push(binary);\n }\n }\n\n return {\n id: message.id,\n role: \"user\",\n content: hasFile ? contentParts : textFromParts(message.parts),\n };\n}\n\nfunction toolName(part: UnknownRecord): string | undefined {\n if (part.type === \"dynamic-tool\") {\n return typeof part.toolName === \"string\" && part.toolName.length > 0\n ? part.toolName\n : undefined;\n }\n\n if (typeof part.type !== \"string\" || !part.type.startsWith(\"tool-\")) return undefined;\n const name = part.type.slice(\"tool-\".length);\n return name || undefined;\n}\n\nfunction hasOwn(record: UnknownRecord, key: string): boolean {\n return Object.prototype.hasOwnProperty.call(record, key);\n}\n\nfunction toolResultFromPart(part: UnknownRecord): ToolMessage | undefined {\n if (typeof part.toolCallId !== \"string\") return undefined;\n\n if (part.state === \"output-available\" && hasOwn(part, \"output\")) {\n return {\n id: `tool-result-${part.toolCallId}`,\n role: \"tool\",\n toolCallId: part.toolCallId,\n content: serialize(part.output),\n };\n }\n\n if (part.state === \"output-error\" && typeof part.errorText === \"string\") {\n return {\n id: `tool-result-${part.toolCallId}`,\n role: \"tool\",\n toolCallId: part.toolCallId,\n content: part.errorText,\n error: part.errorText,\n };\n }\n\n if (part.state === \"output-denied\") {\n const error = \"Tool execution was denied\";\n return {\n id: `tool-result-${part.toolCallId}`,\n role: \"tool\",\n toolCallId: part.toolCallId,\n content: error,\n error,\n };\n }\n\n return undefined;\n}\n\nfunction appendAssistantSegments(message: ValidUIMessage, result: Message[]): void {\n let segmentIndex = 0;\n let segmentStarted = false;\n let text = \"\";\n let toolCalls: ToolCall[] = [];\n let toolResults: ToolMessage[] = [];\n const hasStepMarkers = message.parts.some((part) => isRecord(part) && part.type === \"step-start\");\n\n const hasBody = () => text.length > 0 || toolCalls.length > 0;\n\n const flush = (force = false) => {\n if (!force && !segmentStarted) return;\n\n segmentIndex += 1;\n result.push({\n id: segmentIndex === 1 ? message.id : `${message.id}-segment-${segmentIndex}`,\n role: \"assistant\",\n ...(text ? { content: text } : {}),\n ...(toolCalls.length ? { toolCalls } : {}),\n });\n result.push(...toolResults);\n\n text = \"\";\n toolCalls = [];\n toolResults = [];\n segmentStarted = false;\n };\n\n for (const value of message.parts) {\n if (!isRecord(value)) continue;\n\n if (value.type === \"step-start\") {\n if (hasBody()) flush();\n continue;\n }\n\n if (value.type === \"text\" && typeof value.text === \"string\") {\n // AI SDK step markers are authoritative. Older/custom UIMessage data may\n // omit them, so retain the previous text-part boundary behavior there.\n // Text after tool calls is always a new item (commentary between calls,\n // then the answer), matching the live adapter.\n if (toolCalls.length > 0 || (!hasStepMarkers && hasBody())) flush();\n segmentStarted = true;\n text += value.text;\n continue;\n }\n\n const name = toolName(value);\n if (!name || typeof value.toolCallId !== \"string\") continue;\n\n if (value.providerExecuted === true) {\n throw new Error(PROVIDER_EXECUTED_TOOLS_UNSUPPORTED_MESSAGE);\n }\n\n segmentStarted = true;\n toolCalls.push({\n id: value.toolCallId,\n type: \"function\",\n function: {\n name,\n arguments: hasOwn(value, \"input\") ? serialize(value.input) : \"\",\n },\n });\n\n const toolResult = toolResultFromPart(value);\n if (toolResult) toolResults.push(toolResult);\n }\n\n // AI SDK permits an assistant UIMessage with no parts. Preserve it as one\n // empty assistant rather than dropping the source message entirely.\n flush(segmentIndex === 0);\n}\n\nfunction fromVercelMessages(data: unknown): Message[] {\n if (!Array.isArray(data)) return [];\n\n const result: Message[] = [];\n\n for (const value of data) {\n if (!validUIMessage(value)) continue;\n const message = value;\n\n if (message.role === \"user\") {\n result.push(fromVercelUser(message));\n continue;\n }\n\n const text = textFromParts(message.parts);\n\n if (message.role === \"system\") {\n result.push({ id: message.id, role: \"system\", content: text });\n continue;\n }\n\n appendAssistantSegments(message, result);\n }\n\n return result;\n}\n\n/**\n * Converts messages between AG-UI and Vercel AI SDK v6 and v7 `UIMessage` format.\n *\n * AG-UI tool-result messages are folded into the matching assistant tool part,\n * because `UIMessage` represents a tool invocation and its result as one part.\n * Outbound tool calls use `dynamic-tool` parts because AG-UI messages do not\n * carry the static tool schema needed to select a `tool-${name}` part. Inbound\n * conversion accepts both dynamic and static tool parts.\n *\n * Vercel `UIMessage` has no developer role, so both AG-UI system and developer\n * messages map to its system role.\n *\n * Provider-executed tools are rejected because the AG-UI message model has no\n * execution-provenance field and therefore cannot preserve their requirement\n * that results remain in the assistant message.\n */\nexport const vercelAIMessageFormat: MessageFormat = {\n toApi(messages: Message[]): UIMessage[] {\n return toVercelMessages(messages);\n },\n\n fromApi(data: unknown): Message[] {\n return fromVercelMessages(data);\n },\n};\n","import { identityMessageFormat, type MessageFormat } from \"../types/messageFormat\";\nimport type { StreamProtocolAdapter } from \"../types/stream\";\nimport type { ChatLLM } from \"./types\";\n\nexport interface FetchLLMOptions {\n /** Endpoint that accepts POST'd messages and returns a streaming Response. */\n url: string;\n /** Stream protocol adapter for parsing the response body (e.g., agUIAdapter, openAIAdapter). */\n streamAdapter: StreamProtocolAdapter;\n /** Wire-format conversion for outgoing messages. Defaults to identity (canonical Message). */\n messageFormat?: MessageFormat;\n /** Extra headers merged into the request. */\n headers?: Record<string, string>;\n /** Override fetch implementation (for tests, custom auth wrappers, etc.). */\n fetch?: typeof fetch;\n /** Extra fields merged into the request body (e.g. `model`) */\n body?: Record<string, unknown>;\n}\n\n/**\n * Generic HTTP-based LLM adapter. POSTs an AG-UI `RunAgentInput`-shaped body\n * (`{ threadId, runId, messages, tools, context }`, messages in the chosen wire\n * format) to `url` and returns the streaming `Response` for downstream processing.\n */\nexport function fetchLLM({\n url,\n streamAdapter,\n messageFormat = identityMessageFormat,\n headers,\n fetch: customFetch,\n body,\n}: FetchLLMOptions): ChatLLM {\n const fetchImpl = customFetch ?? globalThis.fetch.bind(globalThis);\n return {\n send: ({ threadId, messages, signal }) => {\n const runId = crypto.randomUUID();\n return fetchImpl(url, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n ...headers,\n },\n body: JSON.stringify({\n ...body,\n tools: [],\n context: [],\n threadId,\n runId,\n messages: messageFormat.toApi(messages),\n }),\n signal,\n });\n },\n streamProtocol: streamAdapter,\n };\n}\n","import type { Thread, UserMessage } from \"../store/types\";\nimport type { Message } from \"../types/message\";\nimport { identityMessageFormat, type MessageFormat } from \"../types/messageFormat\";\nimport type { ChatStorage } from \"./types\";\n\nexport interface RestStorageOptions {\n /**\n * Base URL for thread endpoints (the old `threadApiUrl`). The factory hits\n * the same conventions the legacy default used:\n * - list: GET {baseUrl}/get (· ?cursor={cursor})\n * - create: POST {baseUrl}/create\n * - get: GET {baseUrl}/get/{threadId}\n * - update: PATCH {baseUrl}/update/{threadId}\n * - delete: DELETE {baseUrl}/delete/{threadId}\n */\n baseUrl: string;\n /** Wire-format conversion. Defaults to identity (canonical Message). */\n messageFormat?: MessageFormat;\n /** Extra headers merged into every request. */\n headers?: Record<string, string>;\n /** Override fetch implementation (for tests, custom auth wrappers, etc.). */\n fetch?: typeof fetch;\n}\n\n/**\n * Generic REST-based thread storage. Reproduces the conventions the removed\n * `threadApiUrl` prop used, so an existing backend keeps working by swapping\n * `threadApiUrl=\"/x\"` for `storage={restStorage({ baseUrl: \"/x\" })}`.\n *\n * Only the `thread` channel is implemented. Pair with an `llm` adapter\n * (e.g. `fetchLLM`).\n */\nexport function restStorage({\n baseUrl,\n messageFormat = identityMessageFormat,\n headers,\n fetch: customFetch,\n}: RestStorageOptions): ChatStorage {\n const fetchImpl = customFetch ?? globalThis.fetch.bind(globalThis);\n\n const request = async (url: string, init?: RequestInit): Promise<Response> => {\n const res = await fetchImpl(url, {\n ...init,\n headers: {\n ...(init?.body ? { \"Content-Type\": \"application/json\" } : {}),\n ...headers,\n ...init?.headers,\n },\n });\n if (!res.ok) {\n throw new Error(\n `restStorage: ${init?.method ?? \"GET\"} ${url} failed: ${res.status} ${res.statusText}`,\n );\n }\n return res;\n };\n\n return {\n thread: {\n async listThreads(cursor?: string) {\n const url = cursor ? `${baseUrl}/get?cursor=${cursor}` : `${baseUrl}/get`;\n const res = await request(url);\n return res.json();\n },\n async createThread(firstMessage: UserMessage): Promise<Thread> {\n const res = await request(`${baseUrl}/create`, {\n method: \"POST\",\n body: JSON.stringify({ messages: messageFormat.toApi([firstMessage]) }),\n });\n return res.json();\n },\n async getMessages(threadId: string): Promise<Message[]> {\n const res = await request(`${baseUrl}/get/${threadId}`);\n const raw: unknown = await res.json();\n return messageFormat.fromApi(raw);\n },\n async updateThread(thread: Thread): Promise<Thread> {\n const res = await request(`${baseUrl}/update/${thread.id}`, {\n method: \"PATCH\",\n body: JSON.stringify(thread),\n });\n return res.json();\n },\n async deleteThread(id: string): Promise<void> {\n await request(`${baseUrl}/delete/${id}`, { method: \"DELETE\" });\n },\n },\n };\n}\n"],"mappings":";;;;;;;AAIA,MAAa,yBAAyB,OACpC,wBACF;;;;;;;;;;AAWA,MAAa,2BACX,OAAO,wBAAwB,IAAI;;ACkErC,MAAM,iBAAiB;;AAEvB,MAAM,qBAAqB;;AAE3B,MAAM,uBAAuB;AAC7B,MAAM,uBAAuB;;AAE7B,MAAM,sBAAsB;;AAE5B,MAAM,iBAAiB,KAAK,KAAK;;AAEjC,MAAM,kBAAkB;AACxB,MAAM,8BAAc,IAAI,IAAY;CAClC;CACA;CACA;CACA;AACF,CAAC;;AAGD,MAAM,UAAU,SAAiD;CAC/D,MAAM,SAAS,UACb,MAAM,QAAQ,KAAK,IAAI,MAAM,QAAQ,SAAyB,OA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