@wodecorp/openui-vue-headless 0.1.4 → 0.1.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,4333 +1,8 @@
1
- import { computed, defineComponent, getCurrentInstance, getCurrentScope, inject, onMounted, onScopeDispose, onUpdated, provide, shallowRef, ssrContextKey, toValue, watch, watchEffect } from "vue";
2
- import { observability } from "@openuidev/observability";
3
- import { createStore } from "zustand/vanilla";
4
- import { subscribeWithSelector } from "zustand/middleware";
5
- import { EventType } from "@ag-ui/core";
6
- // src/store/ArtifactStorageContext.ts
7
- /** @internal Provided by `ChatProvider` from `storage.artifact`. */
8
- const ArtifactStorageContext = Symbol("ArtifactStorageContext");
9
- /**
10
- * Returns the configured global {@link ArtifactStorage} channel, or `null`
11
- * when the storage adapter doesn't provide one.
12
- *
13
- * Renderer implementations use this to lazily fetch (`get`) or persist
14
- * (`update`) artifact content; the artifact browser uses it for `list`.
15
- *
16
- * @category Hooks
17
- */
18
- const useArtifactStorage = () => inject(ArtifactStorageContext, null);
19
- // src/cloud/artifactStream.ts
20
- const MAX_RECONNECTS = 3;
21
- /** Refused data calls re-read an artifact at most this often, so they can't loop. */
22
- const REREAD_INTERVAL_MS = 1e4;
23
- /** A connection that stayed open this long was healthy, so its drop doesn't count against `MAX_RECONNECTS`. */
24
- const STABLE_CONNECTION_MS = 1e4;
25
- const MIN_POLL_INTERVAL_MS = 3e3;
26
- /** The longest failures stretch the wait between checks, unless the interval itself is longer. */
27
- const MAX_POLL_BACKOFF_MS = 3e5;
28
- /** The longest `setTimeout` takes: a longer wait would fire at once. */
29
- const MAX_TIMEOUT_MS = 2 ** 31 - 1;
30
- /** How long `justUpdated` stays on. */
31
- const JUST_UPDATED_MS = 1e4;
32
- const ERROR_CODES = /* @__PURE__ */ new Set([
33
- "not-found",
34
- "generation-failed",
35
- "network-error",
36
- "unauthorized"
37
- ]);
38
- /** A step's names, or `undefined` for an empty or malformed one. */
39
- const stepOf = (data) => {
40
- const names = (value) => Array.isArray(value) ? value.filter((name) => typeof name === "string") : [];
41
- const { tools, scripts } = data ?? {};
42
- const step = {
43
- tools: names(tools),
44
- scripts: names(scripts)
45
- };
46
- return step.tools.length > 0 || step.scripts.length > 0 ? step : void 0;
47
- };
48
- const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
49
- /** Deleted, or the user lost access. */
50
- const isGone = (entry) => entry.snapshot.error?.code === "not-found";
51
- /**
52
- * Whether to keep checking: a renderer polls, the server tags what it sends (older
53
- * servers and storages without `stream` don't), and the user is still signed in.
54
- */
55
- const polls = (entry) => entry.pollers.size > 0 && entry.tag !== void 0 && entry.snapshot.error?.code !== "unauthorized";
56
- const streamError = (code, message, cause) => ({
57
- source: "artifact",
58
- code,
59
- message,
60
- ...cause !== void 0 && { cause }
61
- });
62
- /**
63
- * One stream per artifact, shared by every renderer showing it, so an edit
64
- * streamed by one renderer updates them all. Reads `storage.stream` when the
65
- * storage has it, and falls back to `storage.get` otherwise.
66
- *
67
- * @internal Exported for tests.
68
- */
69
- var ArtifactStreamStore = class {
70
- storage;
71
- entries = /* @__PURE__ */ new Map();
72
- watchers = /* @__PURE__ */ new Set();
73
- /** Artifacts whose poll came due while the tab was hidden. */
74
- dueWhileHidden = /* @__PURE__ */ new Set();
75
- constructor(storage) {
76
- this.storage = storage;
77
- }
78
- /** Calls `watcher` on every change to any artifact's stream. Returns a function that stops it. */
79
- watch(watcher) {
80
- this.watchers.add(watcher);
81
- return () => this.watchers.delete(watcher);
82
- }
83
- getSnapshot(id) {
84
- return this.entry(id).snapshot;
85
- }
86
- subscribe(id, listener) {
87
- const entry = this.entry(id);
88
- entry.listeners.add(listener);
89
- if (entry.idleTimer) {
90
- clearTimeout(entry.idleTimer);
91
- entry.idleTimer = null;
92
- }
93
- if (!entry.started) {
94
- entry.started = true;
95
- this.connect(id);
96
- }
97
- return () => {
98
- entry.listeners.delete(listener);
99
- if (entry.listeners.size > 0 || !entry.controller) return;
100
- entry.idleTimer = setTimeout(() => {
101
- entry.idleTimer = null;
102
- if (entry.listeners.size > 0 || !entry.controller) return;
103
- entry.controller.abort();
104
- entry.controller = null;
105
- entry.started = false;
106
- }, 0);
107
- };
108
- }
109
- poll(id, intervalMs) {
110
- const entry = this.entry(id);
111
- const key = Symbol();
112
- entry.pollers.set(key, Math.max(intervalMs, MIN_POLL_INTERVAL_MS));
113
- this.schedulePoll(id);
114
- return () => {
115
- entry.pollers.delete(key);
116
- this.schedulePoll(id);
117
- };
118
- }
119
- /** A version not seen before means there's a newer revision to fetch. */
120
- noteVersion(id, version) {
121
- if (!version) return;
122
- const entry = this.entry(id);
123
- if (entry.versions.has(version)) return;
124
- const isFirst = entry.versions.size === 0;
125
- entry.versions.add(version);
126
- if (isFirst || !entry.started) return;
127
- if (entry.controller && entry.snapshot.isStreaming) entry.stale = true;
128
- else this.connect(id);
129
- }
130
- retry(id) {
131
- const entry = this.entry(id);
132
- entry.reconnects = 0;
133
- entry.started = true;
134
- this.connect(id);
135
- }
136
- /**
137
- * A data call was refused for `version` (`ARTIFACT_VERSION_MISMATCH`). "rerun" if
138
- * a newer version is on screen or a re-read brings one; else "show". Renderers
139
- * refused together share one re-read.
140
- */
141
- versionMismatch(id, version) {
142
- const entry = this.entry(id);
143
- if (version !== entry.snapshot.version) return Promise.resolve("rerun");
144
- if (entry.reread?.version === version) return entry.reread.answer;
145
- const now = performance.now();
146
- if (!entry.started || now - entry.rereadAt < REREAD_INTERVAL_MS) return Promise.resolve("show");
147
- entry.rereadAt = now;
148
- let settle;
149
- const answer = new Promise((resolve) => settle = resolve);
150
- entry.reread = {
151
- version,
152
- answer,
153
- settle
154
- };
155
- this.refresh(id);
156
- return answer;
157
- }
158
- /** A read ended: answer a pending re-read. */
159
- afterRead(id) {
160
- const entry = this.entry(id);
161
- const reread = entry.reread;
162
- if (!reread || entry.snapshot.isStreaming) return;
163
- entry.reread = null;
164
- reread.settle(entry.snapshot.version === reread.version ? "show" : "rerun");
165
- }
166
- /** Reads the artifact again, after the running stream if there is one. */
167
- refresh(id) {
168
- const entry = this.entry(id);
169
- if (!entry.started) return;
170
- if (entry.controller && entry.snapshot.isStreaming) entry.stale = true;
171
- else {
172
- entry.reconnects = 0;
173
- this.connect(id);
174
- }
175
- }
176
- /** True while `version` is newer than any version recorded: the program on screen is behind. */
177
- awaits(id, version) {
178
- if (!version) return false;
179
- const entry = this.entry(id);
180
- return entry.started && entry.snapshot.program !== null && entry.versions.size > 0 && !entry.versions.has(version);
181
- }
182
- entry(id) {
183
- let entry = this.entries.get(id);
184
- if (!entry) {
185
- entry = {
186
- snapshot: {
187
- id,
188
- program: null,
189
- isStreaming: false,
190
- justUpdated: false,
191
- error: null
192
- },
193
- listeners: /* @__PURE__ */ new Set(),
194
- controller: null,
195
- started: false,
196
- target: "program",
197
- pending: "",
198
- replace: false,
199
- settled: null,
200
- reconnects: 0,
201
- versions: /* @__PURE__ */ new Set(),
202
- stale: false,
203
- idleTimer: null,
204
- reread: null,
205
- rereadAt: -1e400,
206
- pollers: /* @__PURE__ */ new Map(),
207
- pollTimer: null,
208
- pollFailures: 0,
209
- justUpdatedTimer: null
210
- };
211
- this.entries.set(id, entry);
212
- }
213
- return entry;
214
- }
215
- update(id, patch) {
216
- const entry = this.entry(id);
217
- const before = entry.snapshot;
218
- entry.snapshot = {
219
- ...before,
220
- ...patch
221
- };
222
- this.watchers.forEach((watcher) => watcher(id, before, entry.snapshot));
223
- entry.listeners.forEach((listener) => listener());
224
- }
225
- /** With `fetchLatest`, a poll: it stays quiet until the server sends something new. */
226
- async connect(id, fetchLatest) {
227
- const entry = this.entry(id);
228
- entry.started = true;
229
- entry.controller?.abort();
230
- const controller = new AbortController();
231
- entry.controller = controller;
232
- const poll = fetchLatest !== void 0;
233
- if (!poll) this.update(id, {
234
- isStreaming: true,
235
- error: null
236
- });
237
- const connectedAt = Date.now();
238
- let finished = false;
239
- let referenced = false;
240
- let failure;
241
- try {
242
- if (!this.storage.stream) {
243
- finished = true;
244
- await this.load(id);
245
- return;
246
- }
247
- for await (const event of this.storage.stream(id, {
248
- signal: controller.signal,
249
- fetchLatest
250
- })) {
251
- if (controller.signal.aborted) return;
252
- if (event.type === "end" || event.type === "error" || event.type === "unchanged") {
253
- finished = true;
254
- this.onEvent(id, event);
255
- break;
256
- }
257
- if (event.type === "reference") referenced = true;
258
- this.onEvent(id, event);
259
- entry.reconnects = 0;
260
- }
261
- } catch (error) {
262
- if (controller.signal.aborted) return;
263
- failure = error;
264
- } finally {
265
- if (entry.controller === controller) entry.controller = null;
266
- }
267
- if (controller.signal.aborted) return;
268
- if (finished || poll && !referenced) {
269
- entry.pollFailures = finished ? 0 : entry.pollFailures + 1;
270
- this.schedulePoll(id);
271
- return;
272
- }
273
- if (Date.now() - connectedAt >= STABLE_CONNECTION_MS) entry.reconnects = 0;
274
- if (entry.reconnects < MAX_RECONNECTS) {
275
- entry.reconnects += 1;
276
- await sleep(500 * 2 ** (entry.reconnects - 1));
277
- if (entry.controller) return;
278
- if (entry.listeners.size > 0) this.connect(id);
279
- else entry.started = false;
280
- return;
281
- }
282
- this.update(id, {
283
- ...this.endRead(entry),
284
- isStreaming: false,
285
- error: streamError("network-error", "Couldn't reach the artifact's storage.", failure)
286
- });
287
- this.afterRead(id);
288
- }
289
- /**
290
- * A read is over: resets it, and returns what was on screen before a new version
291
- * started streaming over it, if one did. A read that failed goes back to that.
292
- */
293
- endRead(entry) {
294
- const settled = entry.settled;
295
- entry.target = "program";
296
- entry.pending = "";
297
- entry.version = void 0;
298
- entry.settled = null;
299
- return settled;
300
- }
301
- /** Turns `justUpdated` on for a while. */
302
- markUpdated(id) {
303
- const entry = this.entry(id);
304
- if (entry.justUpdatedTimer) clearTimeout(entry.justUpdatedTimer);
305
- entry.justUpdatedTimer = setTimeout(() => {
306
- entry.justUpdatedTimer = null;
307
- this.update(id, { justUpdated: false });
308
- }, JUST_UPDATED_MS);
309
- this.update(id, { justUpdated: true });
310
- }
311
- /** Storages without `stream`: read the stored artifact once. */
312
- async load(id) {
313
- try {
314
- const artifact = await this.storage.get(id);
315
- this.update(id, {
316
- type: artifact.type,
317
- title: artifact.title,
318
- program: typeof artifact.content === "string" ? artifact.content : null,
319
- isStreaming: false
320
- });
321
- } catch (error) {
322
- this.update(id, {
323
- isStreaming: false,
324
- error: streamError("not-found", error instanceof Error ? error.message : "This artifact couldn't be loaded.", error)
325
- });
326
- }
327
- this.afterRead(id);
328
- }
329
- /** Sets the next poll, if a renderer polls and the last read went well enough to compare against. */
330
- schedulePoll(id) {
331
- const entry = this.entry(id);
332
- if (entry.pollTimer) clearTimeout(entry.pollTimer);
333
- entry.pollTimer = null;
334
- if (!polls(entry)) return;
335
- const interval = Math.min(...entry.pollers.values());
336
- const wait = Math.min(interval * 2 ** entry.pollFailures, Math.max(interval, MAX_POLL_BACKOFF_MS)) * (.9 + Math.random() * .2);
337
- entry.pollTimer = setTimeout(() => this.pollNow(id), Math.min(wait, MAX_TIMEOUT_MS));
338
- if (entry.pollFailures > 0) this.listenForVisible();
339
- }
340
- pollNow(id) {
341
- const entry = this.entry(id);
342
- if (entry.pollTimer) clearTimeout(entry.pollTimer);
343
- entry.pollTimer = null;
344
- if (!polls(entry) || entry.controller) return;
345
- if (typeof document !== "undefined" && document.hidden) {
346
- this.dueWhileHidden.add(id);
347
- this.listenForVisible();
348
- return;
349
- }
350
- this.connect(id, isGone(entry) ? "" : entry.tag);
351
- }
352
- listenForVisible() {
353
- if (typeof document !== "undefined") document.addEventListener("visibilitychange", this.onVisible);
354
- }
355
- /**
356
- * The tab is back: run the polls that came due while it was hidden, and check now on
357
- * artifacts waiting out failures, starting their wait over.
358
- */
359
- onVisible = () => {
360
- if (document.hidden) return;
361
- document.removeEventListener("visibilitychange", this.onVisible);
362
- const due = new Set(this.dueWhileHidden);
363
- this.dueWhileHidden.clear();
364
- for (const [id, entry] of this.entries) {
365
- if (entry.pollFailures === 0 || !polls(entry)) continue;
366
- entry.pollFailures = 0;
367
- due.add(id);
368
- }
369
- due.forEach((id) => this.pollNow(id));
370
- };
371
- /** Fetches a revision noted while the stream that just ended was running. */
372
- catchUp(id) {
373
- const entry = this.entry(id);
374
- if (!entry.stale) return;
375
- entry.stale = false;
376
- this.connect(id);
377
- }
378
- onEvent(id, event) {
379
- const entry = this.entry(id);
380
- const snapshot = entry.snapshot;
381
- switch (event.type) {
382
- case "reference": {
383
- const { version, tag, is_owner, is_editable } = event.data ?? {};
384
- if (version) entry.versions.add(version);
385
- entry.tag = tag;
386
- const shown = snapshot.program;
387
- const newVersion = version !== snapshot.version;
388
- const reconnect = version !== void 0 && version === entry.version;
389
- const overShown = shown !== null && newVersion;
390
- entry.version = version;
391
- if (!reconnect) {
392
- entry.target = shown === null || newVersion ? "program" : "pending";
393
- entry.pending = "";
394
- if (overShown) entry.settled ??= {
395
- program: shown,
396
- version: snapshot.version
397
- };
398
- }
399
- entry.replace = reconnect || overShown;
400
- this.update(id, {
401
- type: event.data?.type ?? snapshot.type,
402
- title: event.data?.title ?? snapshot.title,
403
- isOwner: is_owner ?? snapshot.isOwner,
404
- isEditable: is_editable ?? snapshot.isEditable,
405
- isStreaming: snapshot.isStreaming || newVersion,
406
- step: void 0,
407
- error: null,
408
- ...entry.target === "program" && {
409
- version,
410
- program: shown ?? ""
411
- }
412
- });
413
- return;
414
- }
415
- case "unchanged":
416
- this.afterRead(id);
417
- return;
418
- case "delta": {
419
- const text = event.data?.text;
420
- if (typeof text !== "string") return;
421
- const replace = entry.replace;
422
- entry.replace = false;
423
- if (entry.target === "pending") entry.pending = (replace ? "" : entry.pending) + text;
424
- else this.update(id, {
425
- program: (replace ? "" : snapshot.program ?? "") + text,
426
- step: void 0
427
- });
428
- return;
429
- }
430
- case "step":
431
- this.update(id, { step: stepOf(event.data) });
432
- return;
433
- case "end": {
434
- const swapped = entry.target === "pending" ? {
435
- program: entry.pending,
436
- version: entry.version
437
- } : {};
438
- const replaced = this.endRead(entry) !== null;
439
- this.update(id, {
440
- ...swapped,
441
- isStreaming: false,
442
- step: void 0
443
- });
444
- if (replaced) this.markUpdated(id);
445
- this.catchUp(id);
446
- this.afterRead(id);
447
- return;
448
- }
449
- case "error": {
450
- const code = event.data?.code;
451
- const errorCode = code && ERROR_CODES.has(code) ? code : "generation-failed";
452
- const gone = errorCode === "not-found";
453
- if (gone) entry.started = false;
454
- this.update(id, {
455
- ...this.endRead(entry),
456
- ...gone && {
457
- program: null,
458
- version: void 0
459
- },
460
- isStreaming: false,
461
- step: void 0,
462
- error: streamError(errorCode, event.data?.message ?? "The artifact couldn't be generated.")
463
- });
464
- this.catchUp(id);
465
- this.afterRead(id);
466
- }
467
- }
468
- }
469
- };
470
- const stores = /* @__PURE__ */ new WeakMap();
471
- const storeFor = (storage) => {
472
- let store = stores.get(storage);
473
- if (!store) {
474
- store = new ArtifactStreamStore(storage);
475
- stores.set(storage, store);
476
- }
477
- return store;
478
- };
479
- /**
480
- * Tells every renderer showing `id` that `version` was just saved, so they load
481
- * it now instead of on their next poll.
482
- *
483
- * @internal Used by `@openuidev/react-ui/cloud`'s `useArtifactUpdate`.
484
- */
485
- function noteArtifactVersion(storage, id, version) {
486
- stores.get(storage)?.noteVersion(id, version);
487
- }
488
- /**
489
- * Calls `watcher` on every change to any artifact's stream on `storage`, such as
490
- * a rename, an access change or a `not-found` a poll picked up. Returns a function
491
- * that stops it.
492
- *
493
- * @internal Used by `@openuidev/react-ui/cloud`'s artifact cache.
494
- */
495
- function watchArtifactStreams(storage, watcher) {
496
- return storeFor(storage).watch(watcher);
497
- }
498
- const IDLE = {
499
- program: null,
500
- isStreaming: false,
501
- justUpdated: false,
502
- error: null
503
- };
504
- /**
505
- * Streams an artifact in by id from the configured {@link ArtifactStorage},
506
- * sharing one stream per artifact across every component that shows it.
507
- *
508
- * - While it's generated, `program` grows and `isStreaming` is `true`.
509
- * - After a reload, it replays everything generated so far, then continues.
510
- * - A new version streams in live: an edit shows its prior program, then its patch
511
- * merging in. One that fails goes back to the version before it.
512
- * - Storages without `stream` are read once with `get`.
513
- * - With `pollInterval`, it picks up a newer version, a rename or an access
514
- * change, and the `not-found` error once the artifact is deleted or unshared.
515
- *
516
- * @internal Used by the `@openuidev/react-ui/cloud` renderers.
517
- */
518
- function useArtifactStream(options) {
519
- const storage = useArtifactStorage();
520
- const snapshotRef = shallowRef(null);
521
- const resolved = computed(() => toValue(options));
522
- const activeStore = computed(() => {
523
- const opts = resolved.value;
524
- const ownContent = opts.content !== void 0;
525
- return storage && !ownContent && opts.id ? storeFor(storage) : null;
526
- });
527
- watch([activeStore, () => resolved.value.id], ([store, id], _prev, onCleanup) => {
528
- if (!store || !id) {
529
- snapshotRef.value = null;
530
- return;
531
- }
532
- snapshotRef.value = store.getSnapshot(id);
533
- onCleanup(store.subscribe(id, () => {
534
- snapshotRef.value = store.getSnapshot(id);
535
- }));
536
- }, { immediate: true });
537
- watch([
538
- activeStore,
539
- () => resolved.value.id,
540
- () => resolved.value.version
541
- ], ([store, id, version]) => {
542
- if (store && id) store.noteVersion(id, version);
543
- }, {
544
- immediate: true,
545
- flush: "post"
546
- });
547
- watch([
548
- activeStore,
549
- () => resolved.value.id,
550
- () => resolved.value.pollInterval
551
- ], ([store, id, pollInterval], _prev, onCleanup) => {
552
- if (!store || !id || !pollInterval) return;
553
- onCleanup(store.poll(id, pollInterval));
554
- }, {
555
- immediate: true,
556
- flush: "post"
557
- });
558
- return computed(() => {
559
- const opts = resolved.value;
560
- const store = activeStore.value;
561
- const id = opts.id;
562
- if (opts.content !== void 0) return {
563
- ...IDLE,
564
- program: opts.content
565
- };
566
- const snapshot = snapshotRef.value;
567
- if (!snapshot) {
568
- if (id && !storage) return {
569
- ...IDLE,
570
- error: streamError("not-found", "No artifact storage is configured.")
571
- };
572
- return IDLE;
573
- }
574
- const awaiting = store && id ? store.awaits(id, opts.version) : false;
575
- const reportVersionMismatch = store && id ? (refused) => store.versionMismatch(id, refused) : void 0;
576
- const { id: _id, ...rest } = snapshot;
577
- const retry = snapshot.error?.code === "network-error" && store && id ? () => store.retry(id) : void 0;
578
- return {
579
- ...rest,
580
- isStreaming: rest.isStreaming || awaiting,
581
- retry,
582
- reportVersionMismatch
583
- };
584
- });
585
- }
586
- // src/cloud/interpreter.ts
587
- function errorMessage(error) {
588
- if (typeof error === "string") return error;
589
- if (error && typeof error === "object" && "message" in error) {
590
- const { message } = error;
591
- if (typeof message === "string") return message;
592
- }
593
- }
594
- function errorCode(error) {
595
- if (error && typeof error === "object" && "code" in error) {
596
- const { code } = error;
597
- if (typeof code === "string") return code;
598
- }
599
- }
600
- async function callEndpoint(fetchImpl, config, request) {
601
- const headers = new Headers(config.headers);
602
- headers.set("Content-Type", "application/json");
603
- const res = await fetchImpl(config.url, {
604
- method: "POST",
605
- headers,
606
- body: JSON.stringify(request)
607
- });
608
- let body = null;
609
- try {
610
- body = await res.json();
611
- } catch {
612
- body = null;
613
- }
614
- if (!res.ok || body?.error !== void 0 && body.error !== null) {
615
- const message = errorMessage(body?.error) ?? `Interpreter request failed: ${res.status}`;
616
- throw Object.assign(new Error(message), { code: errorCode(body?.error) });
617
- }
618
- return body?.result;
619
- }
620
- /**
621
- * A `toolProvider` for react-lang's `Renderer` that sends an artifact's data
622
- * tool calls to your interpreter, endpoint or function. Results come back as
623
- * `structuredContent`, so `Renderer` unwraps them the usual way.
624
- *
625
- * @internal Used by the `@openuidev/react-ui/cloud` renderers.
626
- */
627
- function createInterpreterToolProvider(options) {
628
- return { async callTool({ name, arguments: args = {} }) {
629
- const interpreter = options.getInterpreter();
630
- const { id, version } = options.getRequest();
631
- if (!interpreter) throw new Error("This artifact has no interpreter.");
632
- if (!id) throw new Error("This artifact has no id yet.");
633
- const request = {
634
- id,
635
- ...version !== void 0 && { version },
636
- name,
637
- arguments: args
638
- };
639
- options.onStart?.(name);
640
- try {
641
- const result = typeof interpreter === "function" ? await interpreter(request) : await callEndpoint(options.fetch ?? globalThis.fetch.bind(globalThis), interpreter, request);
642
- options.onSettle?.(name, null);
643
- return {
644
- content: [],
645
- structuredContent: result ?? null
646
- };
647
- } catch (error) {
648
- const code = errorCode(error);
649
- options.onSettle?.(name, errorMessage(error) ?? "The data tool failed.", {
650
- ...code !== void 0 && { code },
651
- id,
652
- ...version !== void 0 && { version }
653
- });
654
- throw error;
655
- }
656
- } };
657
- }
658
- // src/cloud/sse.ts
659
- async function* readSse(body) {
660
- const reader = body.getReader();
661
- const decoder = new TextDecoder();
662
- let buffer = "";
663
- let id;
664
- let event = "";
665
- let data = [];
666
- const dispatch = () => {
667
- if (data.length === 0 && !event) return null;
668
- const message = {
669
- id,
670
- event: event || "message",
671
- data: data.join("\n")
672
- };
673
- event = "";
674
- data = [];
675
- return message;
676
- };
677
- try {
678
- for (;;) {
679
- const { done, value } = await reader.read();
680
- if (done) break;
681
- buffer += decoder.decode(value, { stream: true });
682
- let newline = buffer.search(/\r?\n/);
683
- while (newline !== -1) {
684
- const line = buffer.slice(0, newline);
685
- buffer = buffer.slice(buffer[newline] === "\r" ? newline + 2 : newline + 1);
686
- if (line === "") {
687
- const message = dispatch();
688
- if (message) yield message;
689
- } else if (!line.startsWith(":")) {
690
- const colon = line.indexOf(":");
691
- const field = colon === -1 ? line : line.slice(0, colon);
692
- let value = colon === -1 ? "" : line.slice(colon + 1);
693
- if (value.startsWith(" ")) value = value.slice(1);
694
- if (field === "data") data.push(value);
695
- else if (field === "event") event = value;
696
- else if (field === "id") id = value;
697
- }
698
- newline = buffer.search(/\r?\n/);
699
- }
700
- }
701
- const message = dispatch();
702
- if (message) yield message;
703
- } finally {
704
- reader.releaseLock();
705
- }
706
- }
707
- // src/cloud/wire.ts
708
- /** Forward cursor: pass `last_id` back as `?after=` when there's another page. */
709
- function nextCursorOf(envelope) {
710
- return envelope.has_more && envelope.last_id ? envelope.last_id : void 0;
711
- }
712
- /**
713
- * Request helper: prefix baseUrl, set JSON content-type only when sending a
714
- * body, throw on non-2xx. `fetchImpl` is the token-injecting fetch — auth
715
- * lives there, never here.
716
- */
717
- function cloudRequest(fetchImpl, baseUrl) {
718
- const base = baseUrl.replace(/\/+$/, "");
719
- return async (path, init) => {
720
- const res = await fetchImpl(`${base}${path}`, {
721
- ...init,
722
- headers: {
723
- ...init?.body ? { "Content-Type": "application/json" } : {},
724
- ...init?.headers
725
- }
726
- });
727
- if (!res.ok) throw new Error(`OpenUI Cloud: ${init?.method ?? "GET"} ${path} failed: ${res.status} ${res.statusText}`);
728
- return res;
729
- };
730
- }
731
- // src/cloud/artifactStorage.ts
732
- const STREAM_EVENT_TYPES = /* @__PURE__ */ new Set([
733
- "reference",
734
- "delta",
735
- "step",
736
- "end",
737
- "error"
738
- ]);
739
- function parseJson(data) {
740
- try {
741
- return JSON.parse(data);
742
- } catch {
743
- return null;
744
- }
745
- }
746
- function toSummary(artifact) {
747
- return {
748
- id: artifact.id,
749
- title: artifact.name ?? artifact.id,
750
- type: artifact.kind,
751
- threadId: artifact.conversation_id ?? "",
752
- updatedAt: (artifact.updated_at ?? artifact.created_at) * 1e3,
753
- ...artifact.pinned !== void 0 && { pinned: artifact.pinned },
754
- ...artifact.is_owner !== void 0 && { isOwner: artifact.is_owner },
755
- ...artifact.is_editable !== void 0 && { isEditable: artifact.is_editable },
756
- ...artifact.shares !== void 0 && { shares: artifact.shares.map(toShare) },
757
- ...artifact.version !== void 0 && { version: artifact.version }
758
- };
759
- }
760
- function toShare(share) {
761
- return {
762
- type: share.type,
763
- id: share.id,
764
- access: share.access,
765
- createdBy: share.created_by,
766
- createdAt: share.created_at * 1e3
767
- };
768
- }
769
- function cloudArtifactStorage({ baseUrl, fetch: fetchImpl, pageLimit = 100, cacheQueryResults = true }) {
770
- const request = cloudRequest(fetchImpl, baseUrl);
771
- const base = baseUrl.replace(/\/+$/, "");
772
- return {
773
- /** GET /v1/artifacts?[name=][kind=…]&limit[&after=]. Omitting the
774
- * conversation scope lists across conversations, token-scoped to the user. */
775
- async list(params) {
776
- const query = new URLSearchParams();
777
- if (params?.name !== void 0 && params.name !== "") query.set("name", params.name);
778
- for (const type of params?.type ?? []) query.append("kind", type);
779
- if (params?.pinned !== void 0) query.set("pinned", String(params.pinned));
780
- if (params?.isOwner !== void 0) query.set("is_owner", String(params.isOwner));
781
- if (params?.order !== void 0) query.set("order", params.order);
782
- if (params?.cursor !== void 0) query.set("after", params.cursor);
783
- query.set("limit", String(params?.limit ?? pageLimit));
784
- const envelope = await (await request(`/v1/artifacts?${query.toString()}`)).json();
785
- return {
786
- artifacts: envelope.data.map(toSummary),
787
- nextCursor: nextCursorOf(envelope)
788
- };
789
- },
790
- /** GET /v1/artifacts/:id → the stored openui-lang program (bare program;
791
- * the renderer's parser sniffs the `root = …` root). */
792
- async get(id) {
793
- const artifact = await (await request(`/v1/artifacts/${encodeURIComponent(id)}`)).json();
794
- return {
795
- ...toSummary(artifact),
796
- content: artifact.content
797
- };
798
- },
799
- /** POST /v1/artifacts/:id {content?, name?}. New content (the edited inner program) is a
800
- * new version, which the server bumps; a title alone renames it. */
801
- async update(patch) {
802
- const body = {
803
- ...patch.content !== void 0 && { content: typeof patch.content === "string" ? patch.content : JSON.stringify(patch.content) },
804
- ...patch.title !== void 0 && { name: patch.title }
805
- };
806
- return toSummary(await (await request(`/v1/artifacts/${encodeURIComponent(patch.id)}`, {
807
- method: "POST",
808
- body: JSON.stringify(body)
809
- })).json());
810
- },
811
- /** POST /v1/artifacts/:id/pin. */
812
- async pin(id) {
813
- return toSummary(await (await request(`/v1/artifacts/${encodeURIComponent(id)}/pin`, { method: "POST" })).json());
814
- },
815
- /** POST /v1/artifacts/:id/unpin. */
816
- async unpin(id) {
817
- return toSummary(await (await request(`/v1/artifacts/${encodeURIComponent(id)}/unpin`, { method: "POST" })).json());
818
- },
819
- /** DELETE /v1/artifacts/:id. */
820
- async delete(id) {
821
- await request(`/v1/artifacts/${encodeURIComponent(id)}`, { method: "DELETE" });
822
- },
823
- /** POST /v1/artifacts/:id/share {type, id, access}. Sends only those fields. */
824
- async share(id, share) {
825
- return toSummary(await (await request(`/v1/artifacts/${encodeURIComponent(id)}/share`, {
826
- method: "POST",
827
- body: JSON.stringify({
828
- type: share.type,
829
- id: share.id,
830
- access: share.access
831
- })
832
- })).json());
833
- },
834
- /** POST /v1/artifacts/:id/unshare {type, id}. Sends only those fields. */
835
- async unshare(id, target) {
836
- return toSummary(await (await request(`/v1/artifacts/${encodeURIComponent(id)}/unshare`, {
837
- method: "POST",
838
- body: JSON.stringify({
839
- type: target.type,
840
- id: target.id
841
- })
842
- })).json());
843
- },
844
- ...cacheQueryResults && {
845
- /** GET /v1/artifacts/:id/query-results → the saved entries by key. */
846
- async getQueryResults(id) {
847
- return (await (await request(`/v1/artifacts/${encodeURIComponent(id)}/query-results`)).json()).results ?? {};
848
- },
849
- /** PUT /v1/artifacts/:id/query-results {key, value}. Not awaited; a failure is dropped. */
850
- putQueryResult(id, entry) {
851
- request(`/v1/artifacts/${encodeURIComponent(id)}/query-results`, {
852
- method: "PUT",
853
- body: JSON.stringify(entry)
854
- }).catch(() => {});
855
- }
856
- },
857
- /** GET /v1/artifacts/:id/stream[?fetch_latest=] (SSE). Replays a finished artifact
858
- * the same way; every connection starts from the whole program. 304: unchanged. */
859
- async *stream(id, options) {
860
- const query = options?.fetchLatest ? `?${new URLSearchParams({ fetch_latest: options.fetchLatest }).toString()}` : "";
861
- const res = await fetchImpl(`${base}/v1/artifacts/${encodeURIComponent(id)}/stream${query}`, {
862
- headers: { Accept: "text/event-stream" },
863
- signal: options?.signal
864
- });
865
- if (res.status === 304) {
866
- yield { type: "unchanged" };
867
- return;
868
- }
869
- if (res.status === 404) {
870
- yield {
871
- type: "error",
872
- data: {
873
- code: "not-found",
874
- message: "This artifact was deleted, or you can't see it."
875
- }
876
- };
877
- return;
878
- }
879
- if (res.status === 401 || res.status === 403) {
880
- yield {
881
- type: "error",
882
- data: {
883
- code: "unauthorized",
884
- message: "Your session expired, or you can't see this artifact."
885
- }
886
- };
887
- return;
888
- }
889
- if (!res.ok || !res.body) throw new Error(`OpenUI Cloud: stream ${id} failed: ${res.status} ${res.statusText}`);
890
- for await (const message of readSse(res.body)) {
891
- if (!STREAM_EVENT_TYPES.has(message.event)) continue;
892
- yield {
893
- type: message.event,
894
- data: parseJson(message.data)
895
- };
896
- }
897
- }
898
- };
899
- }
900
- // src/cloud/frontendTokenManager.ts
901
- /**
902
- * Frontend session-token (fct_) lifecycle for the browser plane.
903
- *
904
- * - The token rides ONLY the `x-thesys-frontend-token` header; `Authorization`
905
- * on /v1/* always means the master key (server-side).
906
- * - Minting happens on YOUR backend (here, the /api/frontend-token proxy),
907
- * which calls the cloud mint endpoint with the master key and decides the
908
- * end-user identity server-side. The browser sends no body and never names
909
- * its own user.
910
- * - Mint response: { token: 'fct_…', expires_at: <unix seconds> }, TTL ~15 min.
911
- *
912
- * A fetch override (not static headers) is used so the token can refresh
913
- * mid-session — the chat provider captures the storage object once at mount.
914
- */
915
- const FRONTEND_TOKEN_HEADER = "x-thesys-frontend-token";
916
- function createFrontendTokenManager({ mintUrl, fetch: customFetch, refreshSkewSeconds = 60 }) {
917
- const fetchImpl = customFetch ?? globalThis.fetch.bind(globalThis);
918
- let token = null;
919
- let expiresAt = 0;
920
- let inflight = null;
921
- const mint = async () => {
922
- const res = await fetchImpl(mintUrl, { method: "POST" });
923
- if (!res.ok) throw new Error(`frontend-token mint failed: ${res.status} ${res.statusText}`);
924
- const body = await res.json();
925
- token = body.token;
926
- expiresAt = body.expires_at;
927
- return body.token;
928
- };
929
- return {
930
- async getToken() {
931
- const nowSeconds = Date.now() / 1e3;
932
- if (token !== null && nowSeconds < expiresAt - refreshSkewSeconds) return token;
933
- if (inflight === null) inflight = mint().finally(() => {
934
- inflight = null;
935
- });
936
- return inflight;
937
- },
938
- invalidate(staleToken) {
939
- if (staleToken === void 0 || staleToken === token) {
940
- token = null;
941
- expiresAt = 0;
942
- }
943
- }
944
- };
945
- }
946
- /** Normalize a token source into a FrontendTokenManager. */
947
- function toFrontendTokenManager(source, options = {}) {
948
- if (typeof source === "string") return createFrontendTokenManager({
949
- ...options,
950
- mintUrl: source
951
- });
952
- let current = null;
953
- return {
954
- async getToken() {
955
- current = await source();
956
- return current;
957
- },
958
- invalidate(staleToken) {
959
- if (staleToken === void 0 || staleToken === current) current = null;
960
- }
961
- };
962
- }
963
- /**
964
- * Wrap a base fetch so every request carries a fresh token, with one reactive
965
- * retry on 401. The request is re-sent with the same init — pass re-readable
966
- * (string) bodies only.
967
- */
968
- function createFctFetch(tokens, baseFetch) {
969
- const fetchImpl = baseFetch ?? globalThis.fetch.bind(globalThis);
970
- return async (input, init) => {
971
- const token = await tokens.getToken();
972
- const headers = new Headers(init?.headers);
973
- headers.set(FRONTEND_TOKEN_HEADER, token);
974
- let res = await fetchImpl(input, {
975
- ...init,
976
- headers
977
- });
978
- if (res.status === 401) {
979
- tokens.invalidate(token);
980
- const freshToken = await tokens.getToken();
981
- const retryHeaders = new Headers(init?.headers);
982
- retryHeaders.set(FRONTEND_TOKEN_HEADER, freshToken);
983
- res = await fetchImpl(input, {
984
- ...init,
985
- headers: retryHeaders
986
- });
987
- }
988
- return res;
989
- };
990
- }
991
- // src/stream/formats/openai-conversation-message-format.ts
992
- /**
993
- * Both the Responses API and the Conversations API accept
994
- * `ResponseInputItem[]` as input, so a single outbound conversion
995
- * works for both.
996
- *
997
- * Tool calls are *sibling items* of the assistant message, not nested
998
- * inside it. We flatten each AG-UI assistant message into:
999
- * 1. An `EasyInputMessage` with `role: "assistant"` (text part)
1000
- * 2. One `ResponseFunctionToolCall` per tool call
1001
- *
1002
- * Tool result messages become `FunctionCallOutput` items.
1003
- */
1004
- function toItems(message) {
1005
- switch (message.role) {
1006
- case "user": return [toInputMessage(message)];
1007
- case "assistant": {
1008
- const items = [];
1009
- if (message.content) items.push({
1010
- role: "assistant",
1011
- content: message.content,
1012
- type: "message"
1013
- });
1014
- if (message.toolCalls?.length) for (const tc of message.toolCalls) items.push({
1015
- type: "function_call",
1016
- call_id: tc.id,
1017
- name: tc.function.name,
1018
- arguments: tc.function.arguments
1019
- });
1020
- return items;
1021
- }
1022
- case "tool": return [{
1023
- type: "function_call_output",
1024
- call_id: message.toolCallId,
1025
- output: message.content
1026
- }];
1027
- case "system": return [{
1028
- role: "system",
1029
- content: message.content,
1030
- type: "message"
1031
- }];
1032
- case "developer": return [{
1033
- role: "developer",
1034
- content: message.content,
1035
- type: "message"
1036
- }];
1037
- default: return [];
1038
- }
1039
- }
1040
- function toInputMessage(message) {
1041
- const content = message.content;
1042
- if (typeof content === "string") return {
1043
- role: "user",
1044
- content,
1045
- type: "message"
1046
- };
1047
- return {
1048
- role: "user",
1049
- content: content?.map((part) => {
1050
- if (part.type === "text") return {
1051
- type: "input_text",
1052
- text: part.text
1053
- };
1054
- if (part.type === "binary") return {
1055
- type: "input_image",
1056
- image_url: part.url ?? `data:${part.mimeType};base64,${part.data ?? ""}`,
1057
- detail: "auto"
1058
- };
1059
- return {
1060
- type: "input_text",
1061
- text: ""
1062
- };
1063
- }) ?? [],
1064
- type: "message"
1065
- };
1066
- }
1067
- /**
1068
- * Converts `ConversationItem[]` (from the Conversations API) or
1069
- * `ResponseItem[]` (from the Responses API) into AG-UI `Message[]`.
1070
- *
1071
- * Both APIs return items as a flat list with `type` discriminator:
1072
- * - `"message"` → user / assistant / system / developer / tool message
1073
- * - `"function_call"` → tool call (grouped into the preceding assistant)
1074
- * - `"function_call_output"` → tool result
1075
- *
1076
- * The Conversations API `Message` type is a superset that also handles
1077
- * `reasoning_text`, `summary_text`, and `text` content parts, as well
1078
- * as additional roles like `tool` and `critic`.
1079
- */
1080
- function fromItems(items) {
1081
- const messages = [];
1082
- let currentAssistant = null;
1083
- let pendingToolMsgs = [];
1084
- const flushAssistant = () => {
1085
- if (currentAssistant) {
1086
- messages.push(currentAssistant);
1087
- currentAssistant = null;
1088
- }
1089
- if (pendingToolMsgs.length > 0) {
1090
- messages.push(...pendingToolMsgs);
1091
- pendingToolMsgs = [];
1092
- }
1093
- };
1094
- for (const item of items) switch (item.type) {
1095
- case "message": {
1096
- flushAssistant();
1097
- const msg = item;
1098
- if (msg.role === "assistant") currentAssistant = {
1099
- id: msg.id,
1100
- role: "assistant",
1101
- content: extractTextContent$1(msg) || void 0
1102
- };
1103
- else if (msg.role === "tool") messages.push({
1104
- id: msg.id,
1105
- role: "tool",
1106
- content: extractTextContent$1(msg),
1107
- toolCallId: ""
1108
- });
1109
- else if (msg.role === "user") messages.push(fromUserMessage(msg));
1110
- else {
1111
- const role = msg.role === "developer" ? "developer" : "system";
1112
- messages.push({
1113
- id: msg.id,
1114
- role,
1115
- content: extractTextContent$1(msg)
1116
- });
1117
- }
1118
- break;
1119
- }
1120
- case "function_call": {
1121
- const tc = item;
1122
- if (!currentAssistant) currentAssistant = {
1123
- id: crypto.randomUUID(),
1124
- role: "assistant"
1125
- };
1126
- currentAssistant = {
1127
- ...currentAssistant,
1128
- toolCalls: [...currentAssistant.toolCalls ?? [], {
1129
- id: tc.call_id,
1130
- type: "function",
1131
- function: {
1132
- name: tc.name,
1133
- arguments: tc.arguments
1134
- }
1135
- }]
1136
- };
1137
- break;
1138
- }
1139
- case "function_call_output": {
1140
- const output = item;
1141
- pendingToolMsgs.push({
1142
- id: output.id,
1143
- role: "tool",
1144
- content: typeof output.output === "string" ? output.output : JSON.stringify(output.output),
1145
- toolCallId: output.call_id
1146
- });
1147
- break;
1148
- }
1149
- case "mcp_call": {
1150
- if (!currentAssistant) currentAssistant = {
1151
- id: crypto.randomUUID(),
1152
- role: "assistant"
1153
- };
1154
- currentAssistant = {
1155
- ...currentAssistant,
1156
- toolCalls: [...currentAssistant.toolCalls ?? [], {
1157
- id: item.id,
1158
- type: "function",
1159
- function: {
1160
- name: item.name,
1161
- arguments: item.arguments
1162
- }
1163
- }]
1164
- };
1165
- const errorText = typeof item.error === "string" && item.error.length > 0 ? item.error : void 0;
1166
- pendingToolMsgs.push({
1167
- id: `${item.id}-output`,
1168
- role: "tool",
1169
- content: item.output ?? "",
1170
- toolCallId: item.id,
1171
- ...errorText ? { error: errorText } : {}
1172
- });
1173
- break;
1174
- }
1175
- }
1176
- flushAssistant();
1177
- return messages;
1178
- }
1179
- /**
1180
- * Extract text content from a Conversations API `Message`.
1181
- *
1182
- * Handles the full content union:
1183
- * - `output_text` (assistant output)
1184
- * - `input_text` (user/system/developer input)
1185
- * - `text` (generic text)
1186
- * - `summary_text`, `reasoning_text` (appended)
1187
- * - `refusal` (mapped to text)
1188
- */
1189
- function extractTextContent$1(msg) {
1190
- return msg.content.map((part) => {
1191
- switch (part.type) {
1192
- case "output_text": return part.text;
1193
- case "input_text": return part.text;
1194
- case "text": return part.text;
1195
- case "summary_text": return part.text;
1196
- case "reasoning_text": return part.text;
1197
- case "refusal": return `[Refusal]: ${part.refusal}`;
1198
- default: return "";
1199
- }
1200
- }).filter(Boolean).join("");
1201
- }
1202
- function fromUserMessage(msg) {
1203
- if (!msg.content.some((part) => part.type === "input_image" || part.type === "input_file")) return {
1204
- id: msg.id,
1205
- role: "user",
1206
- content: extractTextContent$1(msg)
1207
- };
1208
- const parts = msg.content.map((part) => {
1209
- if (part.type === "input_text" || part.type === "text") return {
1210
- type: "text",
1211
- text: part.text
1212
- };
1213
- if (part.type === "input_image" && part.image_url) return {
1214
- type: "binary",
1215
- url: part.image_url,
1216
- mimeType: "image/*"
1217
- };
1218
- return {
1219
- type: "text",
1220
- text: ""
1221
- };
1222
- });
1223
- return {
1224
- id: msg.id,
1225
- role: "user",
1226
- content: parts
1227
- };
1228
- }
1229
- /**
1230
- * Converts between AG-UI message format and OpenAI's item-based format,
1231
- * compatible with both the **Responses API** and **Conversations API**.
1232
- *
1233
- * AG-UI → OpenAI (toApi):
1234
- * - Returns `ResponseInputItem[]` — works for both `responses.create({ input })`
1235
- * and `conversations.items.create({ items })`
1236
- * - Flattens assistant messages: text → `EasyInputMessage`, tool calls → `ResponseFunctionToolCall`
1237
- *
1238
- * OpenAI → AG-UI (fromApi):
1239
- * - Accepts `ConversationItem[]` (or `ResponseItem[]`, which is a subset)
1240
- * - Groups adjacent assistant messages + function_calls into `AssistantMessage`
1241
- * - Handles Conversations-specific content types (`reasoning_text`, `summary_text`, etc.)
1242
- */
1243
- const openAIConversationMessageFormat = {
1244
- toApi(messages) {
1245
- return messages.flatMap(toItems);
1246
- },
1247
- fromApi(data) {
1248
- return fromItems(data);
1249
- }
1250
- };
1251
- // src/cloud/items.ts
1252
- /**
1253
- * Convert /v1 conversation items to AG-UI Message[]. Each item is normalized
1254
- * into the OpenAI ConversationItem shape that openAIConversationMessageFormat
1255
- * .fromApi expects, then delegated — the grouping logic (function_call →
1256
- * assistant toolCalls, function_call_output → ToolMessage) stays in the SDK.
1257
- *
1258
- * Normalizations:
1259
- * - message content: assistant outputs arrive as part arrays; user inputs
1260
- * arrive as a plain string → wrap strings as a single text part.
1261
- * - function_call / function_call_output: a malformed row (missing the
1262
- * top-level call_id/name/output) is skipped so it can't crash fromApi.
1263
- * - other item types are skipped.
1264
- */
1265
- function normalizeItem(item) {
1266
- switch (item.type) {
1267
- case "message": {
1268
- const content = item.content;
1269
- const parts = Array.isArray(content) ? content : [{
1270
- type: item.role === "assistant" ? "output_text" : "input_text",
1271
- text: typeof content === "string" ? content : ""
1272
- }];
1273
- return {
1274
- id: item.id,
1275
- type: "message",
1276
- role: item.role ?? "user",
1277
- status: item.status ?? "completed",
1278
- content: parts
1279
- };
1280
- }
1281
- case "function_call":
1282
- if (typeof item.call_id !== "string" || typeof item.name !== "string") return null;
1283
- return {
1284
- id: item.id,
1285
- type: "function_call",
1286
- call_id: item.call_id,
1287
- name: item.name,
1288
- arguments: typeof item.arguments === "string" ? item.arguments : JSON.stringify(item.arguments ?? {})
1289
- };
1290
- case "function_call_output":
1291
- if (typeof item.call_id !== "string" || item.output === void 0) return null;
1292
- return {
1293
- id: item.id,
1294
- type: "function_call_output",
1295
- call_id: item.call_id,
1296
- output: item.output
1297
- };
1298
- default: return null;
1299
- }
1300
- }
1301
- function cloudItemsToMessages(items) {
1302
- const normalized = items.map(normalizeItem).filter((i) => i !== null);
1303
- return openAIConversationMessageFormat.fromApi(normalized);
1304
- }
1305
- // src/cloud/threadStorage.ts
1306
- /** Hard stop for the items pagination loop. */
1307
- const MAX_ITEM_PAGES = 50;
1308
- function toThread(conversation) {
1309
- return {
1310
- id: conversation.id,
1311
- title: conversation.title ?? "New conversation",
1312
- createdAt: conversation.created_at * 1e3
1313
- };
1314
- }
1315
- /** Client-side title from the first user message (the API does not auto-title). */
1316
- function deriveTitle(firstMessage) {
1317
- const content = firstMessage.content;
1318
- let text = "";
1319
- if (typeof content === "string") text = content;
1320
- else if (Array.isArray(content)) {
1321
- for (const part of content) if (part.type === "text" && typeof part.text === "string" && part.text.trim() !== "") {
1322
- text = part.text;
1323
- break;
1324
- }
1325
- }
1326
- text = text.trim();
1327
- return (text === "" ? "New conversation" : text).slice(0, 60);
1328
- }
1329
- function cloudThreadStorage({ baseUrl, fetch: fetchImpl, pageLimit = 100 }) {
1330
- const request = cloudRequest(fetchImpl, baseUrl);
1331
- return {
1332
- /** GET /v1/conversations?limit[&after]. Newest-first. */
1333
- async listThreads(cursor) {
1334
- const query = new URLSearchParams({ limit: String(pageLimit) });
1335
- if (cursor !== void 0) query.set("after", cursor);
1336
- const envelope = await (await request(`/v1/conversations?${query.toString()}`)).json();
1337
- return {
1338
- threads: envelope.data.map(toThread),
1339
- nextCursor: nextCursorOf(envelope)
1340
- };
1341
- },
1342
- /** POST /v1/conversations {title}. No messages and no user_id — the user is
1343
- * bound from the token; the first message arrives later on the generation
1344
- * plane (conversation linkage). */
1345
- async createThread(firstMessage) {
1346
- return toThread(await (await request(`/v1/conversations`, {
1347
- method: "POST",
1348
- body: JSON.stringify({ title: deriveTitle(firstMessage) })
1349
- })).json());
1350
- },
1351
- /** GET /v1/conversations/:id/items?order=asc, paged, then mapped to Messages. */
1352
- async getMessages(threadId) {
1353
- const items = [];
1354
- let after;
1355
- for (let page = 0; page < MAX_ITEM_PAGES; page++) {
1356
- const query = new URLSearchParams({
1357
- order: "asc",
1358
- limit: String(pageLimit)
1359
- });
1360
- if (after !== void 0) query.set("after", after);
1361
- const envelope = await (await request(`/v1/conversations/${encodeURIComponent(threadId)}/items?${query.toString()}`)).json();
1362
- items.push(...envelope.data);
1363
- after = nextCursorOf(envelope);
1364
- if (after === void 0) break;
1365
- }
1366
- return cloudItemsToMessages(items);
1367
- },
1368
- /** POST /v1/conversations/:id {title}. */
1369
- async updateThread(thread) {
1370
- return toThread(await (await request(`/v1/conversations/${encodeURIComponent(thread.id)}`, {
1371
- method: "POST",
1372
- body: JSON.stringify({ title: thread.title })
1373
- })).json());
1374
- },
1375
- /** DELETE /v1/conversations/:id (soft delete). */
1376
- async deleteThread(id) {
1377
- await request(`/v1/conversations/${encodeURIComponent(id)}`, { method: "DELETE" });
1378
- }
1379
- };
1380
- }
1381
- // src/cloud/openuiCloud.ts
1382
- /** OpenUI Cloud API origin used when `apiBaseUrl` is omitted. The storage
1383
- * layer appends `/v1/...` to it. */
1384
- const DEFAULT_API_BASE_URL = "https://api.thesys.dev";
1385
- /**
1386
- * One-call browser wiring for OpenUI Cloud, as a hook: a memoised `ChatStorage`
1387
- * backed by the /v1 API, authenticated per-request with an fct_ session token.
1388
- * Pass it straight to `<AgentInterface storage={…} />`.
1389
- *
1390
- * As a hook the storage (and its fct_ token manager) is created on mount and
1391
- * re-created only when its options change. Tokens are minted lazily on the first
1392
- * storage request. ChatProvider captures storage at mount; remount the provider
1393
- * when switching users or storage configurations.
1394
- *
1395
- * This is the READ/EDIT plane (browser → /v1/* with the fct_ token). Generation
1396
- * is the separate ChatLLM plane (browser → your backend → /v1/embed/responses
1397
- * with the master key).
1398
- */
1399
- function useOpenuiCloudStorage(options) {
1400
- let previous;
1401
- let storage;
1402
- return computed(() => {
1403
- const current = toValue(options);
1404
- const dependencies = [
1405
- current.apiBaseUrl,
1406
- current.token,
1407
- current.fetch,
1408
- current.refreshSkewSeconds,
1409
- current.cacheQueryResults,
1410
- current.features?.artifact ?? true
1411
- ];
1412
- if (!previous || dependencies.some((value, index) => !Object.is(value, previous[index]))) {
1413
- storage = createCloudStorage(current);
1414
- previous = dependencies;
1415
- }
1416
- return storage;
1417
- });
1418
- }
1419
- /** The actual storage wiring — a pure factory with no Vue, memoised by the
1420
- * composable above. */
1421
- function createCloudStorage(options) {
1422
- const fctFetch = createFctFetch(toFrontendTokenManager(options.token, {
1423
- fetch: options.fetch,
1424
- refreshSkewSeconds: options.refreshSkewSeconds
1425
- }), options.fetch);
1426
- const artifactOn = options.features?.artifact ?? true;
1427
- const baseUrl = options.apiBaseUrl ?? DEFAULT_API_BASE_URL;
1428
- const storage = { thread: cloudThreadStorage({
1429
- baseUrl,
1430
- fetch: fctFetch
1431
- }) };
1432
- if (artifactOn) storage.artifact = cloudArtifactStorage({
1433
- baseUrl,
1434
- fetch: fctFetch,
1435
- cacheQueryResults: options.cacheQueryResults
1436
- });
1437
- return storage;
1438
- }
1439
- // src/cloud/pollInterval.ts
1440
- /** @internal Set by `OpenUICloudProvider`'s `pollInterval`. */
1441
- const ArtifactPollIntervalContext = Symbol("ArtifactPollIntervalContext");
1442
- /**
1443
- * How often open artifacts check for changes, as set on `OpenUICloudProvider`.
1444
- * Undefined when it doesn't say.
1445
- */
1446
- const useArtifactPollInterval = () => toValue(inject(ArtifactPollIntervalContext, void 0));
1447
- // src/cloud/OpenUICloudProvider.ts
1448
- const OpenUICloudProvider = defineComponent({
1449
- name: "OpenUICloudProvider",
1450
- props: {
1451
- apiBaseUrl: {
1452
- type: String,
1453
- default: void 0
1454
- },
1455
- token: {
1456
- type: [String, Function],
1457
- required: true
1458
- },
1459
- cacheQueryResults: {
1460
- type: Boolean,
1461
- default: void 0
1462
- },
1463
- fetch: {
1464
- type: Function,
1465
- default: void 0
1466
- },
1467
- refreshSkewSeconds: {
1468
- type: Number,
1469
- default: void 0
1470
- },
1471
- pollInterval: {
1472
- type: [Number, Boolean],
1473
- default: void 0
1474
- }
1475
- },
1476
- setup(props, { slots }) {
1477
- const stableReadToken = () => {
1478
- const current = props.token;
1479
- return typeof current === "string" ? Promise.resolve(current) : current();
1480
- };
1481
- const storage = useOpenuiCloudStorage(() => ({
1482
- apiBaseUrl: props.apiBaseUrl,
1483
- token: typeof props.token === "string" ? props.token : stableReadToken,
1484
- cacheQueryResults: props.cacheQueryResults,
1485
- fetch: props.fetch,
1486
- refreshSkewSeconds: props.refreshSkewSeconds
1487
- }));
1488
- const artifactStorage = computed(() => storage.value.artifact ?? null);
1489
- provide(ArtifactStorageContext, artifactStorage.value);
1490
- provide(ArtifactPollIntervalContext, () => props.pollInterval);
1491
- return () => slots.default?.() ?? null;
1492
- }
1493
- });
1494
- // src/store/useStore.ts
1495
- /** Vue binding for the pinned Zustand vanilla store; the owner scope owns cleanup. */
1496
- function useStore(store, selector) {
1497
- if (!getCurrentScope()) throw new Error("useStore must be used within a Vue setup or effect scope");
1498
- if (getCurrentInstance() && inject(ssrContextKey, null) !== null) return computed(() => selector(store.getInitialState()));
1499
- const snapshot = shallowRef(store.getState());
1500
- const selected = shallowRef();
1501
- watchEffect(() => {
1502
- selected.value = selector(snapshot.value);
1503
- }, { flush: "sync" });
1504
- const unsubscribe = store.subscribe((state) => {
1505
- snapshot.value = state;
1506
- });
1507
- snapshot.value = store.getState();
1508
- onScopeDispose(unsubscribe);
1509
- return computed(() => selected.value);
1510
- }
1511
- /** Per-consumer useShallow equivalent for the default thread slices only. */
1512
- function shallowSelector(selector) {
1513
- let previous;
1514
- return (state) => {
1515
- const next = selector(state);
1516
- const keys = Object.keys(next);
1517
- 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;
1518
- previous = next;
1519
- return next;
1520
- };
1521
- }
1522
- // src/store/DetailedViewContext.ts
1523
- /** @internal React context holding the detailed-view Zustand store. Provided by `ChatProvider`. */
1524
- const DetailedViewContext = Symbol("DetailedViewContext");
1525
- /**
1526
- * Returns the raw detailed-view Zustand store for advanced use cases.
1527
- *
1528
- * Prefer {@link useDetailedView} or {@link useActiveDetailedView} for most cases —
1529
- * this hook is an escape hatch when you need direct store access.
1530
- *
1531
- * @category Hooks
1532
- * @returns The Zustand `StoreApi<DetailedViewStore>` instance
1533
- * @throws Error if called outside a `<ChatProvider>`
1534
- */
1535
- const useDetailedViewStore = () => {
1536
- const store = inject(DetailedViewContext, null);
1537
- if (!store) throw new Error("useDetailedViewStore must be used within a <ChatProvider>");
1538
- return store;
1539
- };
1540
- // src/hooks/useActiveDetailedView.ts
1541
- function useActiveDetailedView() {
1542
- const store = useDetailedViewStore();
1543
- const activeDetailedViewId = useStore(store, (state) => state.activeDetailedViewId);
1544
- const isDetailedViewActive = computed(() => activeDetailedViewId.value !== null);
1545
- const closeDetailedView = () => {
1546
- if (store.getState().activeDetailedViewId !== null) store.getState().setActiveDetailedView(null);
1547
- };
1548
- return {
1549
- activeDetailedViewId,
1550
- isDetailedViewActive,
1551
- closeDetailedView
1552
- };
1553
- }
1554
- // src/store/ThreadContextContext.ts
1555
- /** @internal React context holding the ThreadContext Zustand store. Provided by `ChatProvider`. */
1556
- const ThreadContextContext = Symbol("ThreadContextContext");
1557
- /**
1558
- * Returns the raw ThreadContext Zustand store for advanced use cases.
1559
- *
1560
- * Prefer {@link useDetailedView}, {@link useActiveDetailedView}, {@link useAppList},
1561
- * or {@link useArtifactList} for most cases — this hook is an escape hatch when you
1562
- * need direct store access.
1563
- *
1564
- * @category Hooks
1565
- * @returns The Zustand `StoreApi<ThreadContextStore>` instance
1566
- * @throws Error if called outside a `<ChatProvider>`
1567
- */
1568
- const useThreadContextStore = () => {
1569
- const store = inject(ThreadContextContext, null);
1570
- if (!store) throw new Error("useThreadContextStore must be used within a <ChatProvider>");
1571
- return store;
1572
- };
1573
- // src/hooks/useArtifactList.ts
1574
- function useArtifactList(filter) {
1575
- const artifacts = useStore(useThreadContextStore(), (state) => state.artifacts);
1576
- let previous;
1577
- return computed(() => {
1578
- const typeKey = toValue(filter)?.type?.join(" ");
1579
- const current = artifacts.value;
1580
- if (previous && previous.artifacts === current && previous.typeKey === typeKey) return previous.value;
1581
- if (typeKey === void 0) {
1582
- previous = {
1583
- artifacts: current,
1584
- typeKey,
1585
- value: current
1586
- };
1587
- return current;
1588
- }
1589
- const allowed = new Set(typeKey.split(" "));
1590
- const result = {};
1591
- for (const [id, versions] of Object.entries(current)) {
1592
- const latest = versions[versions.length - 1];
1593
- if (latest && allowed.has(latest.type)) result[id] = versions;
1594
- }
1595
- previous = {
1596
- artifacts: current,
1597
- typeKey,
1598
- value: result
1599
- };
1600
- return result;
1601
- });
1602
- }
1603
- // src/store/ArtifactRenderersContext.ts
1604
- const isDev$1 = () => typeof process !== "undefined" && process.env?.["NODE_ENV"] !== "production";
1605
- /**
1606
- * Builds an {@link ArtifactRendererRegistry} from a list of configs.
1607
- *
1608
- * First-wins on duplicate `toolName` or `type`: subsequent registrations are
1609
- * ignored with a dev-mode warning so the user can reorder their array
1610
- * (custom renderers should come *before* SDK defaults).
1611
- *
1612
- * @internal
1613
- */
1614
- function buildArtifactRendererRegistry(configs) {
1615
- const byToolName = /* @__PURE__ */ new Map();
1616
- const byType = /* @__PURE__ */ new Map();
1617
- for (const config of configs) {
1618
- const toolNames = Array.isArray(config.toolName) ? config.toolName : [config.toolName];
1619
- for (const name of toolNames) {
1620
- if (byToolName.has(name)) {
1621
- if (isDev$1()) console.warn(`[OpenUI] Artifact renderer for toolName "${name}" was ignored (already registered earlier in the array).`);
1622
- continue;
1623
- }
1624
- byToolName.set(name, config);
1625
- }
1626
- if (byType.has(config.type)) {
1627
- if (isDev$1()) console.warn(`[OpenUI] Artifact renderer for type "${config.type}" was ignored for type-based lookup (already registered earlier in the array).`);
1628
- continue;
1629
- }
1630
- byType.set(config.type, config);
1631
- }
1632
- return {
1633
- byToolName,
1634
- byType
1635
- };
1636
- }
1637
- /** Resolves the renderer matching a tool name, or `null`. @internal */
1638
- function lookupArtifactRenderer(registry, toolName) {
1639
- return registry.byToolName.get(toolName) ?? null;
1640
- }
1641
- /** Resolves the renderer matching an artifact type, or `null`. @internal */
1642
- function lookupArtifactRendererByType(registry, type) {
1643
- return registry.byType.get(type) ?? null;
1644
- }
1645
- /** @internal React context holding the renderer registry. Provided by `ChatProvider`. */
1646
- const ArtifactRenderersContext = Symbol("ArtifactRenderersContext");
1647
- /**
1648
- * Returns the raw artifact-renderer registry for advanced use cases.
1649
- *
1650
- * Prefer {@link useArtifactRenderer} for resolving a specific tool name —
1651
- * this hook is an escape hatch for custom dispatching.
1652
- *
1653
- * Returns `null` if no `artifactRenderers` were provided to the `<ChatProvider>` —
1654
- * this is not an error since renderers are optional.
1655
- *
1656
- * @category Hooks
1657
- */
1658
- const useArtifactRendererRegistry = () => {
1659
- return inject(ArtifactRenderersContext, null);
1660
- };
1661
- // src/hooks/useArtifactRenderer.ts
1662
- function useArtifactRenderer(toolName) {
1663
- const registry = useArtifactRendererRegistry();
1664
- return computed(() => registry ? lookupArtifactRenderer(registry, toValue(toolName)) : null);
1665
- }
1666
- // src/hooks/useDetailedView.ts
1667
- function useDetailedView(viewId) {
1668
- const store = useDetailedViewStore();
1669
- const isActive = useStore(store, (state) => state.activeDetailedViewId === toValue(viewId));
1670
- const open = () => store.getState().setActiveDetailedView(toValue(viewId));
1671
- const close = () => {
1672
- if (store.getState().activeDetailedViewId === toValue(viewId)) store.getState().setActiveDetailedView(null);
1673
- };
1674
- const toggle = () => {
1675
- const id = toValue(viewId);
1676
- store.getState().setActiveDetailedView(store.getState().activeDetailedViewId === id ? null : id);
1677
- };
1678
- return {
1679
- isActive,
1680
- open,
1681
- close,
1682
- toggle
1683
- };
1684
- }
1685
- // src/hooks/useDetailedViewPortalTarget.ts
1686
- function useDetailedViewPortalTarget() {
1687
- const store = useDetailedViewStore();
1688
- return {
1689
- node: useStore(store, (state) => state._detailedViewPanelNode),
1690
- setNode: (node) => store.getState()._setDetailedViewPanelNode(node)
1691
- };
1692
- }
1693
- // src/hooks/useMessage.ts
1694
- const MessageContext = Symbol("MessageContext");
1695
- function useMessage() {
1696
- const context = inject(MessageContext, null);
1697
- if (!context) throw new Error("useMessage must be used within a MessageProvider");
1698
- return context;
1699
- }
1700
- const MessageProvider = defineComponent({
1701
- name: "OpenUIMessageProvider",
1702
- props: { message: {
1703
- type: Object,
1704
- required: true
1705
- } },
1706
- setup(props, { slots }) {
1707
- provide(MessageContext, { get message() {
1708
- return props.message;
1709
- } });
1710
- return () => slots.default?.();
1711
- }
1712
- });
1713
- // src/store/ChatContext.ts
1714
- const ChatContext = Symbol("ChatContext");
1715
- const useChatStore = () => {
1716
- const store = inject(ChatContext, null);
1717
- if (!store) throw new Error("useChatStore must be used within a <ChatProvider>");
1718
- return store;
1719
- };
1720
- // src/hooks/useThread.ts
1721
- const threadSelector = (s) => ({
1722
- messages: s.messages,
1723
- isRunning: s.isRunning,
1724
- isLoadingMessages: s.isLoadingMessages,
1725
- threadError: s.threadError,
1726
- executingToolCallIds: s.executingToolCallIds,
1727
- processMessage: s.processMessage,
1728
- appendMessages: s.appendMessages,
1729
- updateMessage: s.updateMessage,
1730
- setMessages: s.setMessages,
1731
- deleteMessage: s.deleteMessage,
1732
- cancelMessage: s.cancelMessage
1733
- });
1734
- const threadListSelector = (s) => ({
1735
- threads: s.threads,
1736
- isLoadingThreads: s.isLoadingThreads,
1737
- threadListError: s.threadListError,
1738
- selectedThreadId: s.selectedThreadId,
1739
- hasMoreThreads: s.hasMoreThreads,
1740
- loadThreads: s.loadThreads,
1741
- loadMoreThreads: s.loadMoreThreads,
1742
- switchToNewThread: s.switchToNewThread,
1743
- createThread: s.createThread,
1744
- selectThread: s.selectThread,
1745
- updateThread: s.updateThread,
1746
- deleteThread: s.deleteThread
1747
- });
1748
- function useThread(selector) {
1749
- const store = useChatStore();
1750
- if (selector) return useStore(store, (s) => selector(threadSelector(s)));
1751
- return useStore(store, shallowSelector(threadSelector));
1752
- }
1753
- function useThreadList(selector) {
1754
- const store = useChatStore();
1755
- if (selector) return useStore(store, (s) => selector(threadListSelector(s)));
1756
- return useStore(store, shallowSelector(threadListSelector));
1757
- }
1758
- // src/store/toolActivity.ts
1759
- const isDev = () => typeof process !== "undefined" && process.env?.["NODE_ENV"] !== "production";
1760
- /**
1761
- * Closes dangling brackets/quotes for a partial (mid-stream) JSON string so it
1762
- * can be parsed for a best-effort snapshot. Conservative: only trims a trailing
1763
- * object key that is provably awaiting a value (signalled by a trailing colon),
1764
- * leaving complete array/values intact.
1765
- */
1766
- function balanceOpenJSON(raw) {
1767
- const closers = [];
1768
- let inString = false;
1769
- let escaped = false;
1770
- for (let i = 0; i < raw.length; i++) {
1771
- const ch = raw[i];
1772
- if (inString) {
1773
- if (escaped) escaped = false;
1774
- else if (ch === "\\") escaped = true;
1775
- else if (ch === "\"") inString = false;
1776
- continue;
1777
- }
1778
- if (ch === "\"") inString = true;
1779
- else if (ch === "{") closers.push("}");
1780
- else if (ch === "[") closers.push("]");
1781
- else if (ch === "}" || ch === "]") closers.pop();
1782
- }
1783
- let out = raw;
1784
- if (inString) {
1785
- if (escaped) out = out.slice(0, -1);
1786
- out += "\"";
1787
- }
1788
- out = out.replace(/(?:,\s*)?"(?:[^"\\]|\\.)*"\s*:\s*$/, "");
1789
- out = out.replace(/,\s*$/, "");
1790
- for (let i = closers.length - 1; i >= 0; i--) out += closers[i];
1791
- return out;
1792
- }
1793
- /**
1794
- * Tolerant single-pass JSON parse for streamed tool arguments. Tries a straight
1795
- * parse, then a bracket-balanced parse for partial input. **Never throws** —
1796
- * returns `{}` when nothing parseable can be recovered.
1797
- *
1798
- * @category Utilities
1799
- */
1800
- function partialJSONParse(raw) {
1801
- if (!raw) return {};
1802
- try {
1803
- return JSON.parse(raw);
1804
- } catch {}
1805
- try {
1806
- return JSON.parse(balanceOpenJSON(raw));
1807
- } catch {
1808
- return {};
1809
- }
1810
- }
1811
- let warnedTitle = false;
1812
- /**
1813
- * Maps the deprecated `_title` tool-arg key onto a typed `statusMessage` for one
1814
- * minor release (with a one-time dev warning). Prefer a renderer-owned typed
1815
- * field going forward.
1816
- */
1817
- function readStatusMessage(input) {
1818
- if (input && typeof input === "object" && "_title" in input) {
1819
- const value = input["_title"];
1820
- if (typeof value === "string") {
1821
- if (isDev() && !warnedTitle) {
1822
- warnedTitle = true;
1823
- console.warn("[OpenUI] The `_title` tool-arg key is deprecated and will be removed; the renderer now exposes a typed `statusMessage` on ToolActivity instead.");
1824
- }
1825
- return value;
1826
- }
1827
- }
1828
- }
1829
- /**
1830
- * Pairs every tool call on an assistant message with its result message **by
1831
- * `toolCallId`** (id-keyed, no positional `break`), producing a typed
1832
- * {@link ToolActivity} per call. Turn-safe even when tool messages trail or
1833
- * interleave with other messages.
1834
- *
1835
- * @param message The assistant message owning the tool calls.
1836
- * @param allMessages The full thread message list (scanned for tool results).
1837
- * @param executingIds Tool-call ids whose args have closed but whose result
1838
- * hasn't landed (the store's `executingToolCallIds`).
1839
- *
1840
- * @category Utilities
1841
- */
1842
- function pairToolActivity(message, allMessages, executingIds = /* @__PURE__ */ new Set()) {
1843
- const byCallId = /* @__PURE__ */ new Map();
1844
- const ownedCallIds = /* @__PURE__ */ new Set();
1845
- for (const m of allMessages) if (m.role === "tool") {
1846
- const tm = m;
1847
- if (tm.toolCallId) byCallId.set(tm.toolCallId, tm);
1848
- } else if (m.role === "assistant") for (const tc of m.toolCalls ?? []) ownedCallIds.add(tc.id);
1849
- const activities = (message.toolCalls ?? []).map((toolCall) => {
1850
- const toolMessage = byCallId.get(toolCall.id) ?? null;
1851
- const input = partialJSONParse(toolCall.function.arguments);
1852
- const statusMessage = readStatusMessage(input);
1853
- const base = {
1854
- id: toolCall.id,
1855
- toolName: toolCall.function.name,
1856
- toolCall,
1857
- statusMessage
1858
- };
1859
- if (toolMessage) return toolMessage.error ? {
1860
- ...base,
1861
- status: "error",
1862
- toolMessage,
1863
- input,
1864
- result: toolMessage.content,
1865
- isError: true,
1866
- errorText: toolMessage.error
1867
- } : {
1868
- ...base,
1869
- status: "complete",
1870
- toolMessage,
1871
- input,
1872
- result: toolMessage.content,
1873
- isError: false
1874
- };
1875
- return executingIds.has(toolCall.id) ? {
1876
- ...base,
1877
- status: "executing",
1878
- toolMessage: null,
1879
- input,
1880
- isError: false
1881
- } : {
1882
- ...base,
1883
- status: "streaming",
1884
- toolMessage: null,
1885
- input,
1886
- isError: false
1887
- };
1888
- });
1889
- const msgIndex = allMessages.findIndex((m) => m.id === message.id);
1890
- if (msgIndex !== -1) for (let i = msgIndex + 1; i < allMessages.length; i++) {
1891
- const m = allMessages[i];
1892
- if (!m || m.role !== "tool") break;
1893
- const tm = m;
1894
- if (!tm.toolCallId || ownedCallIds.has(tm.toolCallId)) continue;
1895
- const orphanCall = {
1896
- id: tm.toolCallId,
1897
- type: "function",
1898
- function: {
1899
- name: "",
1900
- arguments: ""
1901
- }
1902
- };
1903
- const base = {
1904
- id: tm.id,
1905
- toolName: "",
1906
- toolCall: orphanCall
1907
- };
1908
- activities.push(tm.error ? {
1909
- ...base,
1910
- status: "error",
1911
- toolMessage: tm,
1912
- input: {},
1913
- result: tm.content,
1914
- isError: true,
1915
- errorText: tm.error
1916
- } : {
1917
- ...base,
1918
- status: "complete",
1919
- toolMessage: tm,
1920
- input: {},
1921
- result: tm.content,
1922
- isError: false
1923
- });
1924
- }
1925
- return activities;
1926
- }
1927
- // src/hooks/useToolActivities.ts
1928
- function useToolActivities(message, allMessages) {
1929
- const executingIds = useThread((state) => state.executingToolCallIds);
1930
- let previous;
1931
- return computed(() => {
1932
- const current = toValue(message);
1933
- const messages = toValue(allMessages);
1934
- const args = (current.toolCalls ?? []).map((tool) => `${tool.id}:${tool.function.arguments.length}`).join("|");
1935
- const result = messages.filter((item) => item.role === "tool").map((item) => `${item.toolCallId}:${item.content?.length ?? 0}:${item.error ? 1 : 0}`).join("|");
1936
- const executing = executingIds.value;
1937
- if (previous && previous.id === current.id && previous.args === args && previous.result === result && previous.executing === executing) return previous.value;
1938
- previous = {
1939
- id: current.id,
1940
- args,
1941
- result,
1942
- executing,
1943
- value: pairToolActivity(current, messages, executing)
1944
- };
1945
- return previous.value;
1946
- });
1947
- }
1948
- // src/store/artifactCategories.ts
1949
- /**
1950
- * Wraps the manual `artifactRenderers` + `artifactCategories` wiring: declare
1951
- * each category once with its renderers, and get both props back, ready to
1952
- * spread onto `<AgentInterface>`.
1953
- *
1954
- * - `artifactRenderers` is every group's renderers, in order, de-duplicated by
1955
- * identity (a renderer listed in two groups registers once).
1956
- * - `artifactCategories` is one {@link ArtifactCategory} per group, its
1957
- * `filter.type` collected from the group's renderer `type`s (de-duplicated).
1958
- *
1959
- * @category Functions
1960
- *
1961
- * @example
1962
- * ```tsx
1963
- * const artifacts = defineArtifactCategories([
1964
- * { name: "Reports", renderers: [reportRenderer], icon: <ReportIcon /> },
1965
- * { name: "Dashboards", renderers: [dashboardRenderer], icon: <AppIcon /> },
1966
- * ]);
1967
- *
1968
- * <AgentInterface llm={llm} {...artifacts} />;
1969
- * ```
1970
- */
1971
- function defineArtifactCategories(groups) {
1972
- const artifactRenderers = [];
1973
- const seenRenderers = /* @__PURE__ */ new Set();
1974
- return {
1975
- artifactRenderers,
1976
- artifactCategories: groups.map((group) => {
1977
- const type = [];
1978
- const seenTypes = /* @__PURE__ */ new Set();
1979
- for (const renderer of group.renderers) {
1980
- if (!seenRenderers.has(renderer)) {
1981
- seenRenderers.add(renderer);
1982
- artifactRenderers.push(renderer);
1983
- }
1984
- if (!seenTypes.has(renderer.type)) {
1985
- seenTypes.add(renderer.type);
1986
- type.push(renderer.type);
1987
- }
1988
- }
1989
- return {
1990
- name: group.name,
1991
- filter: { type },
1992
- icon: group.icon
1993
- };
1994
- })
1995
- };
1996
- }
1997
- // src/store/ArtifactCategoriesContext.ts
1998
- const ArtifactCategoriesContext = Symbol("ArtifactCategoriesContext");
1999
- const useArtifactCategories = () => inject(ArtifactCategoriesContext, computed(() => []));
2000
- // src/store/artifactRendererTypes.ts
2001
- /**
2002
- * Identity helper that returns its argument while preserving `Props` inference.
2003
- *
2004
- * Without this, users would have to write `const r: ArtifactRendererConfig<MyProps> = {...}`
2005
- * to get type checking. With it, `defineArtifactRenderer({...})` infers `Props`
2006
- * from `parser`'s return type.
2007
- *
2008
- * @category Functions
2009
- *
2010
- * @example
2011
- * ```ts
2012
- * const presentationRenderer = defineArtifactRenderer({
2013
- * type: "th_presentation",
2014
- * toolName: ["presentation:create", "presentation:edit"],
2015
- * parser: ({ response }) => {
2016
- * const slides = response as { id: string; slides: Slide[] } | null;
2017
- * if (!slides) return null;
2018
- * return {
2019
- * props: slides,
2020
- * meta: { id: slides.id, version: 1, heading: `Presentation ${slides.id}` },
2021
- * };
2022
- * },
2023
- * preview: (props, controls) => <PresentationCard onOpen={controls.open} />,
2024
- * actual: (props) => <SlideDeck slides={props.slides} />,
2025
- * });
2026
- * ```
2027
- */
2028
- function defineArtifactRenderer(config) {
2029
- return config;
2030
- }
2031
- // src/store/artifactViewId.ts
2032
- /**
2033
- * Builds the detailed-view id for an artifact version. This is the contract
2034
- * between everything that opens artifact panels (auto-open watcher, workspace
2035
- * rail) and the renderer that registers them — always build/read the id
2036
- * through these helpers, never hand-roll the string.
2037
- */
2038
- function artifactViewId(id, version) {
2039
- return `${id}:${version}`;
2040
- }
2041
- /**
2042
- * Splits a detailed-view id back into artifact id + version. Returns null
2043
- * when the string isn't an artifact view id (e.g. a useId fallback).
2044
- */
2045
- function parseArtifactViewId(viewId) {
2046
- const sep = viewId.lastIndexOf(":");
2047
- if (sep <= 0) return null;
2048
- const versionPart = viewId.slice(sep + 1);
2049
- if (!/^\d+$/.test(versionPart)) return null;
2050
- return {
2051
- id: viewId.slice(0, sep),
2052
- version: Number(versionPart)
2053
- };
2054
- }
2055
- // src/adapters/_defaultStorage.ts
2056
- /**
2057
- * Internal default storage — in-memory, no persistence across reload.
2058
- * Used by `<ChatProvider>` when no `storage` prop is provided. Not exported
2059
- * from the package; callers who want explicit in-memory behavior should
2060
- * construct their own adapter object.
2061
- */
2062
- function createDefaultInMemoryStorage() {
2063
- let threads = [];
2064
- const messagesByThread = /* @__PURE__ */ new Map();
2065
- return { thread: {
2066
- async listThreads() {
2067
- return { threads };
2068
- },
2069
- async createThread(firstMessage) {
2070
- const thread = {
2071
- id: crypto.randomUUID(),
2072
- title: typeof firstMessage.content === "string" ? firstMessage.content.slice(0, 40) || "New thread" : "New thread",
2073
- createdAt: (/* @__PURE__ */ new Date()).toISOString()
2074
- };
2075
- threads = [thread, ...threads];
2076
- messagesByThread.set(thread.id, [{
2077
- ...firstMessage,
2078
- id: firstMessage.id ?? crypto.randomUUID()
2079
- }]);
2080
- return thread;
2081
- },
2082
- async getMessages(threadId) {
2083
- return messagesByThread.get(threadId) ?? [];
2084
- },
2085
- async updateThread(thread) {
2086
- threads = threads.map((t) => t.id === thread.id ? thread : t);
2087
- return thread;
2088
- },
2089
- async deleteThread(id) {
2090
- threads = threads.filter((t) => t.id !== id);
2091
- messagesByThread.delete(id);
2092
- }
2093
- } };
2094
- }
2095
- // src/store/artifactAutoOpenWatcher.ts
2096
- /**
2097
- * One pass over every artifact registered in the thread. Each artifact
2098
- * version (`id:version`) gets a single chance to auto-open — recorded in
2099
- * `claimedIds` the first time we see it, whether or not it opens — so an
2100
- * edit's new version qualifies again. Returns true when a panel opened.
2101
- */
2102
- function evaluateRegisteredArtifacts(artifacts, mayOpen, claimedIds, detailedViewStore) {
2103
- let opened = false;
2104
- const artifactsWithVersions = Object.values(artifacts);
2105
- for (let i = 0; i < artifactsWithVersions.length; i++) {
2106
- const versions = artifactsWithVersions[i];
2107
- if (!versions) continue;
2108
- const latest = versions[versions.length - 1];
2109
- if (!latest) continue;
2110
- const key = artifactViewId(latest.id, latest.version);
2111
- if (claimedIds.has(key)) continue;
2112
- claimedIds.add(key);
2113
- if (!mayOpen || opened) continue;
2114
- detailedViewStore.getState().setActiveDetailedView(key);
2115
- opened = true;
2116
- }
2117
- return opened;
2118
- }
2119
- /**
2120
- * Runs inside ChatProvider: re-evaluates whenever an artifact registers in
2121
- * the thread context, opening at most one artifact per stream.
2122
- */
2123
- function useArtifactAutoOpenWatcher(artifactAutoOpen, chatStore, threadContextStore, detailedViewStore) {
2124
- const openedThisRunRef = { current: false };
2125
- const claimedIdsRef = { current: /* @__PURE__ */ new Set() };
2126
- let enabled;
2127
- let cleanup;
2128
- const reconcile = () => {
2129
- const nextEnabled = toValue(artifactAutoOpen);
2130
- if (nextEnabled === enabled) return;
2131
- cleanup?.();
2132
- cleanup = void 0;
2133
- enabled = nextEnabled;
2134
- if (!enabled) return;
2135
- const unsubscribeThread = chatStore.subscribe((s) => s.selectedThreadId, () => {
2136
- claimedIdsRef.current.clear();
2137
- openedThisRunRef.current = false;
2138
- });
2139
- const unsubscribeRun = chatStore.subscribe((s) => s.isRunning, (isRunning) => {
2140
- if (isRunning) openedThisRunRef.current = false;
2141
- });
2142
- const unsubscribeArtifacts = threadContextStore.subscribe((s) => s.artifacts, (artifacts) => {
2143
- if (evaluateRegisteredArtifacts(artifacts, chatStore.getState().isRunning && !openedThisRunRef.current, claimedIdsRef.current, detailedViewStore)) openedThisRunRef.current = true;
2144
- }, { fireImmediately: true });
2145
- cleanup = () => {
2146
- unsubscribeThread();
2147
- unsubscribeRun();
2148
- unsubscribeArtifacts();
2149
- };
2150
- };
2151
- onMounted(reconcile);
2152
- onUpdated(reconcile);
2153
- onScopeDispose(() => cleanup?.());
2154
- }
2155
- // src/adapters/httpError.ts
2156
- async function getResponseErrorMessage(response) {
2157
- try {
2158
- const data = await response.clone().json();
2159
- const message = typeof data.error === "string" ? data.error : typeof data.error?.message === "string" ? data.error.message : typeof data.message === "string" ? data.message : null;
2160
- if (message?.trim()) return message;
2161
- } catch {}
2162
- return `Request failed: ${response.status} ${response.statusText}`.trim();
2163
- }
2164
- // src/types/messageFormat.ts
2165
- /**
2166
- * Default identity message format — no conversion.
2167
- * Messages are sent and received as-is in AG-UI format.
2168
- */
2169
- const identityMessageFormat = {
2170
- toApi: (messages) => messages,
2171
- fromApi: (data) => data
2172
- };
2173
- // src/stream/adapters/_shared/sseLines.ts
2174
- /**
2175
- * Shared line iterator for streamed HTTP responses.
2176
- *
2177
- * Buffers the leftover partial line between network chunks so an SSE event (or
2178
- * NDJSON record) split across two `reader.read()` results is reassembled rather
2179
- * than silently dropped. The reference implementation lived in
2180
- * `openai-readable-stream.ts`; this extracts it so `ag-ui.ts` and
2181
- * `openai-completions.ts` share the same correct buffering.
2182
- *
2183
- * Yields each complete line verbatim (caller strips any `data: ` SSE prefix);
2184
- * blank lines are skipped. The trailing buffered line is flushed on stream end.
2185
- *
2186
- * @internal
2187
- */
2188
- async function* sseLineIterator(response) {
2189
- const reader = response.body?.getReader();
2190
- if (!reader) throw new Error("No response body");
2191
- const decoder = new TextDecoder();
2192
- let buffer = "";
2193
- while (true) {
2194
- const { done, value } = await reader.read();
2195
- if (done) break;
2196
- buffer += decoder.decode(value, { stream: true });
2197
- const lines = buffer.split("\n");
2198
- buffer = lines.pop() ?? "";
2199
- for (const line of lines) if (line.trim()) yield line;
2200
- }
2201
- if (buffer.trim()) yield buffer;
2202
- }
2203
- // src/stream/adapters/ag-ui.ts
2204
- const agUIAdapter = () => ({ async *parse(response) {
2205
- for await (const line of sseLineIterator(response)) {
2206
- if (!line.startsWith("data: ")) continue;
2207
- const data = line.slice(6).trim();
2208
- if (!data || data === "[DONE]") continue;
2209
- try {
2210
- yield JSON.parse(data);
2211
- } catch (e) {
2212
- console.error("Failed to parse SSE event", e);
2213
- }
2214
- }
2215
- } });
2216
- // src/stream/adapters/eve.ts
2217
- const EVE_INPUT_REQUESTED_EVENT = "eve.input.requested";
2218
- const TURN_BOUNDARY_TYPES = /* @__PURE__ */ new Set([
2219
- "session.completed",
2220
- "session.failed",
2221
- "session.waiting"
2222
- ]);
2223
- /**
2224
- * Adapter for Eve session streams (`GET /eve/v1/session/:id/stream`).
2225
- *
2226
- * Eve emits newline-delimited JSON harness events. The adapter handles
2227
- * `actions.requested`, `action.result`, `message.appended`, `message.completed`,
2228
- * `input.requested`, `turn.failed`, and `session.failed` and maps tool calls,
2229
- * assistant text, input prompts, and failures to AG-UI events. Parsing stops at
2230
- * turn boundaries (`session.completed`, `session.waiting`, `session.failed`).
2231
- * Pass `onEvent` for unmapped events such as `session.started`.
2232
- */
2233
- const eveAdapter = (options = {}) => ({ async *parse(response) {
2234
- const messageId = crypto.randomUUID();
2235
- const streamedSteps = /* @__PURE__ */ new Set();
2236
- let started = false;
2237
- const start = () => {
2238
- if (started) return [];
2239
- started = true;
2240
- return [{
2241
- type: EventType.TEXT_MESSAGE_START,
2242
- messageId,
2243
- role: "assistant"
2244
- }];
2245
- };
2246
- for await (const line of sseLineIterator(response)) {
2247
- let event;
2248
- try {
2249
- event = JSON.parse(line);
2250
- } catch (e) {
2251
- console.error("Failed to parse Eve stream event", e);
2252
- continue;
2253
- }
2254
- options.onEvent?.(event);
2255
- if (event.type === "actions.requested") for (const action of event.data.actions) {
2256
- if (action.kind !== "tool-call") continue;
2257
- yield* start();
2258
- yield {
2259
- type: EventType.TOOL_CALL_START,
2260
- toolCallId: action.callId,
2261
- toolCallName: action.toolName,
2262
- parentMessageId: messageId
2263
- };
2264
- const args = JSON.stringify(action.input ?? {});
2265
- if (args && args !== "{}") yield {
2266
- type: EventType.TOOL_CALL_ARGS,
2267
- toolCallId: action.callId,
2268
- delta: args
2269
- };
2270
- yield {
2271
- type: EventType.TOOL_CALL_END,
2272
- toolCallId: action.callId
2273
- };
2274
- }
2275
- else if (event.type === "action.result") {
2276
- const { result, status, error } = event.data;
2277
- if (result.kind !== "tool-result") continue;
2278
- const content = status === "completed" ? typeof result.output === "string" ? result.output : JSON.stringify(result.output ?? null) : JSON.stringify({ error: error?.message ?? `tool ${status}` });
2279
- yield {
2280
- type: EventType.TOOL_CALL_RESULT,
2281
- messageId: crypto.randomUUID(),
2282
- toolCallId: result.callId,
2283
- content,
2284
- role: "tool"
2285
- };
2286
- } else if (event.type === "message.appended") {
2287
- const { messageDelta, stepIndex } = event.data;
2288
- if (!messageDelta) continue;
2289
- streamedSteps.add(stepIndex);
2290
- yield* start();
2291
- yield {
2292
- type: EventType.TEXT_MESSAGE_CONTENT,
2293
- messageId,
2294
- delta: messageDelta
2295
- };
2296
- } else if (event.type === "message.completed") {
2297
- const { message, stepIndex } = event.data;
2298
- if (!message || streamedSteps.has(stepIndex)) continue;
2299
- yield* start();
2300
- yield {
2301
- type: EventType.TEXT_MESSAGE_CONTENT,
2302
- messageId,
2303
- delta: message
2304
- };
2305
- } else if (event.type === "input.requested") yield {
2306
- type: EventType.CUSTOM,
2307
- name: EVE_INPUT_REQUESTED_EVENT,
2308
- value: event.data.requests
2309
- };
2310
- else if (event.type === "turn.failed" || event.type === "session.failed") yield {
2311
- type: EventType.RUN_ERROR,
2312
- message: event.data.message
2313
- };
2314
- if (TURN_BOUNDARY_TYPES.has(event.type)) break;
2315
- }
2316
- if (started) yield {
2317
- type: EventType.TEXT_MESSAGE_END,
2318
- messageId
2319
- };
2320
- } });
2321
- // src/stream/adapters/langgraph.ts
2322
- /**
2323
- * Adapter for LangGraph streaming responses.
2324
- *
2325
- * LangGraph uses named SSE events (`event: <type>\ndata: <json>\n\n`)
2326
- * rather than the `data:`-only format used by OpenAI. The adapter handles
2327
- * the `messages`, `metadata`, `updates`, and `error` event types and maps
2328
- * model steps and tool results to ordered AG-UI events.
2329
- *
2330
- * Usage:
2331
- * ```tsx
2332
- * <ChatProvider
2333
- * apiUrl="/api/langgraph"
2334
- * streamProtocol={langGraphAdapter()}
2335
- * />
2336
- * ```
2337
- */
2338
- const langGraphAdapter = (options) => ({ async *parse(response) {
2339
- const reader = response.body?.getReader();
2340
- if (!reader) throw new Error("No response body");
2341
- const decoder = new TextDecoder();
2342
- let fallbackMessageId = crypto.randomUUID();
2343
- let currentMessageId = null;
2344
- let currentGraphStep;
2345
- const toolCallIdsByIndex = /* @__PURE__ */ new Map();
2346
- const startedToolCallIds = /* @__PURE__ */ new Set();
2347
- const openToolCallIds = /* @__PURE__ */ new Set();
2348
- const toolCallArgsSeen = /* @__PURE__ */ new Set();
2349
- const usedMessageIds = /* @__PURE__ */ new Set();
2350
- let duplicateMessageIds = 0;
2351
- let messageStarted = false;
2352
- let sawToolsOnCurrentMessage = false;
2353
- let buffer = "";
2354
- while (true) {
2355
- const { done, value } = await reader.read();
2356
- buffer += done ? decoder.decode() : decoder.decode(value, { stream: true });
2357
- const blocks = buffer.split("\n\n");
2358
- buffer = done ? "" : blocks.pop() ?? "";
2359
- for (const block of blocks) {
2360
- const trimmed = block.trim();
2361
- if (!trimmed) continue;
2362
- const { event, data } = parseSSEBlock(trimmed);
2363
- if (!data) continue;
2364
- let parsed;
2365
- try {
2366
- parsed = JSON.parse(data);
2367
- } catch (e) {
2368
- console.error("Failed to parse LangGraph SSE data", e);
2369
- continue;
2370
- }
2371
- switch (event) {
2372
- case "metadata": break;
2373
- case "messages": {
2374
- const tuple = parsed;
2375
- const msg = Array.isArray(tuple) ? tuple[0] : tuple;
2376
- const metadata = Array.isArray(tuple) ? tuple[1] : void 0;
2377
- if (isToolMessage(msg)) {
2378
- if (openToolCallIds.delete(msg.tool_call_id)) yield {
2379
- type: EventType.TOOL_CALL_END,
2380
- toolCallId: msg.tool_call_id
2381
- };
2382
- if (messageStarted && currentMessageId) yield {
2383
- type: EventType.TEXT_MESSAGE_END,
2384
- messageId: currentMessageId
2385
- };
2386
- messageStarted = false;
2387
- currentMessageId = null;
2388
- sawToolsOnCurrentMessage = false;
2389
- currentGraphStep = void 0;
2390
- fallbackMessageId = crypto.randomUUID();
2391
- toolCallIdsByIndex.clear();
2392
- const content = serializeToolContent(msg.content);
2393
- yield {
2394
- type: EventType.TOOL_CALL_RESULT,
2395
- messageId: msg.id ?? `tool-result-${msg.tool_call_id}`,
2396
- toolCallId: msg.tool_call_id,
2397
- content,
2398
- role: "tool",
2399
- ...msg.status === "error" ? {
2400
- isError: true,
2401
- error: content
2402
- } : {}
2403
- };
2404
- break;
2405
- }
2406
- if (!isAIMessage(msg)) break;
2407
- const graphStep = metadata?.langgraph_step;
2408
- const graphStepChanged = graphStep !== void 0 && currentGraphStep !== void 0 && graphStep !== currentGraphStep;
2409
- let nextMessageId = msg.id ?? (graphStep === void 0 ? fallbackMessageId : `langgraph-step-${graphStep}`);
2410
- const textContent = extractTextContent(msg.content);
2411
- const isNewModelStep = !messageStarted || nextMessageId !== currentMessageId || graphStepChanged || !!textContent && sawToolsOnCurrentMessage && messageStarted;
2412
- if (isNewModelStep && usedMessageIds.has(nextMessageId)) nextMessageId = `${nextMessageId}#${++duplicateMessageIds}`;
2413
- if (isNewModelStep) {
2414
- if (messageStarted && currentMessageId) yield {
2415
- type: EventType.TEXT_MESSAGE_END,
2416
- messageId: currentMessageId
2417
- };
2418
- currentMessageId = nextMessageId;
2419
- usedMessageIds.add(nextMessageId);
2420
- currentGraphStep = graphStep;
2421
- sawToolsOnCurrentMessage = false;
2422
- toolCallIdsByIndex.clear();
2423
- yield {
2424
- type: EventType.TEXT_MESSAGE_START,
2425
- messageId: currentMessageId,
2426
- role: "assistant"
2427
- };
2428
- messageStarted = true;
2429
- }
2430
- if (textContent) yield {
2431
- type: EventType.TEXT_MESSAGE_CONTENT,
2432
- messageId: currentMessageId,
2433
- delta: textContent
2434
- };
2435
- if (msg.tool_call_chunks) for (const chunk of msg.tool_call_chunks) {
2436
- const index = chunk.index ?? 0;
2437
- if (chunk.id) toolCallIdsByIndex.set(index, chunk.id);
2438
- const toolCallId = chunk.id ?? toolCallIdsByIndex.get(index);
2439
- if (toolCallId && !startedToolCallIds.has(toolCallId)) {
2440
- startedToolCallIds.add(toolCallId);
2441
- openToolCallIds.add(toolCallId);
2442
- sawToolsOnCurrentMessage = true;
2443
- yield {
2444
- type: EventType.TOOL_CALL_START,
2445
- toolCallId,
2446
- toolCallName: chunk.name || ""
2447
- };
2448
- }
2449
- if (chunk.args && toolCallId) {
2450
- toolCallArgsSeen.add(toolCallId);
2451
- yield {
2452
- type: EventType.TOOL_CALL_ARGS,
2453
- toolCallId,
2454
- delta: chunk.args
2455
- };
2456
- }
2457
- }
2458
- if (msg.tool_call_chunks === void 0 && msg.tool_calls && msg.tool_calls.length > 0) for (let i = 0; i < msg.tool_calls.length; i++) {
2459
- const tc = msg.tool_calls[i];
2460
- if (!tc) continue;
2461
- const toolCallId = tc.id || crypto.randomUUID();
2462
- if (!startedToolCallIds.has(toolCallId)) {
2463
- startedToolCallIds.add(toolCallId);
2464
- openToolCallIds.add(toolCallId);
2465
- sawToolsOnCurrentMessage = true;
2466
- yield {
2467
- type: EventType.TOOL_CALL_START,
2468
- toolCallId,
2469
- toolCallName: tc.name
2470
- };
2471
- }
2472
- if (!toolCallArgsSeen.has(toolCallId)) {
2473
- const argsStr = typeof tc.args === "string" ? tc.args : JSON.stringify(tc.args);
2474
- toolCallArgsSeen.add(toolCallId);
2475
- yield {
2476
- type: EventType.TOOL_CALL_ARGS,
2477
- toolCallId,
2478
- delta: argsStr
2479
- };
2480
- }
2481
- if (openToolCallIds.delete(toolCallId)) yield {
2482
- type: EventType.TOOL_CALL_END,
2483
- toolCallId
2484
- };
2485
- }
2486
- break;
2487
- }
2488
- case "updates": {
2489
- const updates = parsed;
2490
- if ("__interrupt__" in updates && options?.onInterrupt) options.onInterrupt(updates["__interrupt__"]);
2491
- break;
2492
- }
2493
- case "error": {
2494
- const err = parsed;
2495
- yield {
2496
- type: EventType.RUN_ERROR,
2497
- message: err.message || err.error || "Unknown error",
2498
- code: err.error ?? void 0
2499
- };
2500
- break;
2501
- }
2502
- case "end": if (messageStarted) {
2503
- for (const toolCallId of openToolCallIds) yield {
2504
- type: EventType.TOOL_CALL_END,
2505
- toolCallId
2506
- };
2507
- openToolCallIds.clear();
2508
- yield {
2509
- type: EventType.TEXT_MESSAGE_END,
2510
- messageId: currentMessageId
2511
- };
2512
- messageStarted = false;
2513
- }
2514
- }
2515
- }
2516
- if (done) break;
2517
- }
2518
- if (messageStarted) {
2519
- for (const toolCallId of openToolCallIds) yield {
2520
- type: EventType.TOOL_CALL_END,
2521
- toolCallId
2522
- };
2523
- openToolCallIds.clear();
2524
- yield {
2525
- type: EventType.TEXT_MESSAGE_END,
2526
- messageId: currentMessageId
2527
- };
2528
- }
2529
- } });
2530
- /**
2531
- * Parse an SSE block into its event name and data payload.
2532
- *
2533
- * LangGraph SSE format:
2534
- * ```
2535
- * event: messages
2536
- * data: [{"content": "Hello", ...}, {"langgraph_node": "agent"}]
2537
- * ```
2538
- */
2539
- function parseSSEBlock(block) {
2540
- let event = "";
2541
- const dataLines = [];
2542
- for (const line of block.split("\n")) if (line.startsWith("event:")) event = line.slice(6).trim();
2543
- else if (line.startsWith("data:")) dataLines.push(line.slice(5).trim());
2544
- return {
2545
- event,
2546
- data: dataLines.join("\n")
2547
- };
2548
- }
2549
- /**
2550
- * Extract text content from a LangGraph message content field.
2551
- * Content can be a plain string or an array of typed content blocks.
2552
- */
2553
- function extractTextContent(content) {
2554
- if (typeof content === "string") return content;
2555
- return content.filter((block) => block.type === "text" && block.text).map((block) => block.text).join("");
2556
- }
2557
- function serializeToolContent(content) {
2558
- return typeof content === "string" ? content : JSON.stringify(content);
2559
- }
2560
- function isAIMessage(message) {
2561
- return message.type === "ai" || message.type === "AIMessage" || message.type === "AIMessageChunk";
2562
- }
2563
- function isToolMessage(message) {
2564
- return message.type === "tool" || message.type === "ToolMessage" || message.type === "ToolMessageChunk";
2565
- }
2566
- // src/stream/adapters/openai-completions.ts
2567
- const openAIAdapter = () => ({ async *parse(response) {
2568
- const messageId = crypto.randomUUID();
2569
- const toolCallIds = {};
2570
- let messageStarted = false;
2571
- for await (const line of sseLineIterator(response)) {
2572
- if (!line.startsWith("data: ")) continue;
2573
- const data = line.slice(6).trim();
2574
- if (!data || data === "[DONE]") continue;
2575
- try {
2576
- const choice = JSON.parse(data).choices?.[0];
2577
- const delta = choice?.delta;
2578
- if (!delta) continue;
2579
- if (!messageStarted && (delta.content || delta.role)) {
2580
- yield {
2581
- type: EventType.TEXT_MESSAGE_START,
2582
- messageId,
2583
- role: "assistant"
2584
- };
2585
- messageStarted = true;
2586
- }
2587
- if (delta.content) yield {
2588
- type: EventType.TEXT_MESSAGE_CONTENT,
2589
- messageId,
2590
- delta: delta.content
2591
- };
2592
- if (delta.tool_calls) for (const toolCall of delta.tool_calls) {
2593
- const index = toolCall.index;
2594
- if (toolCall.id) {
2595
- toolCallIds[index] = toolCall.id;
2596
- yield {
2597
- type: EventType.TOOL_CALL_START,
2598
- toolCallId: toolCall.id,
2599
- toolCallName: toolCall.function?.name || ""
2600
- };
2601
- }
2602
- if (toolCall.function?.arguments) {
2603
- const toolCallId = toolCallIds[index];
2604
- if (toolCallId) yield {
2605
- type: EventType.TOOL_CALL_ARGS,
2606
- toolCallId,
2607
- delta: toolCall.function.arguments
2608
- };
2609
- }
2610
- }
2611
- if (choice?.finish_reason === "stop") yield {
2612
- type: EventType.TEXT_MESSAGE_END,
2613
- messageId
2614
- };
2615
- else if (choice?.finish_reason === "tool_calls") for (const toolCallId of Object.values(toolCallIds)) yield {
2616
- type: EventType.TOOL_CALL_END,
2617
- toolCallId
2618
- };
2619
- } catch (e) {
2620
- console.error("Failed to parse OpenAI SSE event", e);
2621
- }
2622
- }
2623
- } });
2624
- // src/stream/adapters/openai-readable-stream.ts
2625
- /**
2626
- * Adapter for streams produced by the OpenAI SDK's `Stream.toReadableStream()`.
2627
- * That method emits NDJSON (one JSON object per line, no `data: ` SSE prefix),
2628
- * which differs from the raw SSE format that `openAIAdapter` expects.
2629
- */
2630
- const openAIReadableStreamAdapter = () => ({ async *parse(response) {
2631
- const messageId = crypto.randomUUID();
2632
- const toolCallIds = {};
2633
- let messageStarted = false;
2634
- for await (const line of sseLineIterator(response)) {
2635
- const data = line.trim();
2636
- if (!data) continue;
2637
- try {
2638
- const choice = JSON.parse(data).choices?.[0];
2639
- const delta = choice?.delta;
2640
- if (!delta) continue;
2641
- if (!messageStarted && (delta.content || delta.role)) {
2642
- yield {
2643
- type: EventType.TEXT_MESSAGE_START,
2644
- messageId,
2645
- role: "assistant"
2646
- };
2647
- messageStarted = true;
2648
- }
2649
- if (delta.content) yield {
2650
- type: EventType.TEXT_MESSAGE_CONTENT,
2651
- messageId,
2652
- delta: delta.content
2653
- };
2654
- if (delta.tool_calls) for (const toolCall of delta.tool_calls) {
2655
- const index = toolCall.index;
2656
- if (toolCall.id) {
2657
- toolCallIds[index] = toolCall.id;
2658
- yield {
2659
- type: EventType.TOOL_CALL_START,
2660
- toolCallId: toolCall.id,
2661
- toolCallName: toolCall.function?.name || ""
2662
- };
2663
- }
2664
- if (toolCall.function?.arguments) {
2665
- const toolCallId = toolCallIds[index];
2666
- if (toolCallId) yield {
2667
- type: EventType.TOOL_CALL_ARGS,
2668
- toolCallId,
2669
- delta: toolCall.function.arguments
2670
- };
2671
- }
2672
- }
2673
- if (choice?.finish_reason === "stop") yield {
2674
- type: EventType.TEXT_MESSAGE_END,
2675
- messageId
2676
- };
2677
- else if (choice?.finish_reason === "tool_calls") for (const toolCallId of Object.values(toolCallIds)) yield {
2678
- type: EventType.TOOL_CALL_END,
2679
- toolCallId
2680
- };
2681
- } catch (e) {
2682
- console.error("Failed to parse OpenAI NDJSON chunk", e);
2683
- }
2684
- }
2685
- } });
2686
- // src/stream/adapters/openai-responses.ts
2687
- /** A tool result's `output` as a string (JSON-encoded if structured, "" if absent). */
2688
- const stringifyOutput = (output) => typeof output === "string" ? output : output != null ? JSON.stringify(output) : "";
2689
- const openAIResponsesAdapter = () => ({ async *parse(response) {
2690
- const reader = response.body?.getReader();
2691
- if (!reader) throw new Error("No response body");
2692
- const decoder = new TextDecoder();
2693
- const itemIdToCallId = {};
2694
- let textItemId = null;
2695
- let buffer = "";
2696
- while (true) {
2697
- const { done, value } = await reader.read();
2698
- buffer += done ? decoder.decode() : decoder.decode(value, { stream: true });
2699
- const lines = buffer.split("\n");
2700
- buffer = done ? "" : lines.pop() ?? "";
2701
- for (const line of lines) {
2702
- if (!line.startsWith("data: ")) continue;
2703
- const data = line.slice(6).trim();
2704
- if (!data || data === "[DONE]") continue;
2705
- try {
2706
- const event = JSON.parse(data);
2707
- switch (event.type) {
2708
- case "response.output_item.added": {
2709
- const item = event.item;
2710
- if (item.type === "message" && item.role === "assistant") {
2711
- textItemId = item.id;
2712
- yield {
2713
- type: EventType.TEXT_MESSAGE_START,
2714
- messageId: item.id,
2715
- role: "assistant"
2716
- };
2717
- } else if (item.type === "function_call") {
2718
- itemIdToCallId[item.id ?? item.call_id] = item.call_id;
2719
- yield {
2720
- type: EventType.TOOL_CALL_START,
2721
- toolCallId: item.call_id,
2722
- toolCallName: item.name
2723
- };
2724
- } else if (item.type === "function_call_output") yield {
2725
- type: EventType.TOOL_CALL_RESULT,
2726
- messageId: item.id,
2727
- toolCallId: item.call_id,
2728
- content: stringifyOutput(item.output)
2729
- };
2730
- else if (item.type === "web_search_call") yield {
2731
- type: EventType.TOOL_CALL_START,
2732
- toolCallId: item.id,
2733
- toolCallName: "web_search"
2734
- };
2735
- else if (item.type === "mcp_call") yield {
2736
- type: EventType.TOOL_CALL_START,
2737
- toolCallId: item.id,
2738
- toolCallName: item.name
2739
- };
2740
- else if (item.type === "mcp_list_tools") {
2741
- yield {
2742
- type: EventType.TOOL_CALL_START,
2743
- toolCallId: item.id,
2744
- toolCallName: "mcp_list_tools"
2745
- };
2746
- yield {
2747
- type: EventType.TOOL_CALL_ARGS,
2748
- toolCallId: item.id,
2749
- delta: JSON.stringify({ server_label: item.server_label })
2750
- };
2751
- yield {
2752
- type: EventType.TOOL_CALL_END,
2753
- toolCallId: item.id
2754
- };
2755
- }
2756
- break;
2757
- }
2758
- case "response.output_text.delta":
2759
- if (event.item_id !== textItemId) {
2760
- textItemId = event.item_id;
2761
- yield {
2762
- type: EventType.TEXT_MESSAGE_START,
2763
- messageId: event.item_id,
2764
- role: "assistant"
2765
- };
2766
- }
2767
- yield {
2768
- type: EventType.TEXT_MESSAGE_CONTENT,
2769
- messageId: event.item_id,
2770
- delta: event.delta
2771
- };
2772
- break;
2773
- case "response.output_text.done":
2774
- yield {
2775
- type: EventType.TEXT_MESSAGE_END,
2776
- messageId: event.item_id
2777
- };
2778
- break;
2779
- case "response.function_call_arguments.delta": {
2780
- const callId = itemIdToCallId[event.item_id] ?? event.item_id;
2781
- yield {
2782
- type: EventType.TOOL_CALL_ARGS,
2783
- toolCallId: callId,
2784
- delta: event.delta
2785
- };
2786
- break;
2787
- }
2788
- case "response.function_call_arguments.done": {
2789
- const callId = itemIdToCallId[event.item_id] ?? event.item_id;
2790
- yield {
2791
- type: EventType.TOOL_CALL_END,
2792
- toolCallId: callId
2793
- };
2794
- break;
2795
- }
2796
- case "response.mcp_call_arguments.delta":
2797
- yield {
2798
- type: EventType.TOOL_CALL_ARGS,
2799
- toolCallId: event.item_id,
2800
- delta: event.delta
2801
- };
2802
- break;
2803
- case "response.mcp_call_arguments.done":
2804
- yield {
2805
- type: EventType.TOOL_CALL_END,
2806
- toolCallId: event.item_id
2807
- };
2808
- break;
2809
- case "response.output_item.done": {
2810
- if (event.item.type === "mcp_call") {
2811
- const mcp = event.item;
2812
- const errorText = typeof mcp.error === "string" && mcp.error.length > 0 ? mcp.error : void 0;
2813
- yield {
2814
- type: EventType.TOOL_CALL_RESULT,
2815
- messageId: mcp.id,
2816
- toolCallId: mcp.id,
2817
- content: stringifyOutput(mcp.output),
2818
- ...errorText ? {
2819
- isError: true,
2820
- error: errorText
2821
- } : {}
2822
- };
2823
- break;
2824
- }
2825
- if (event.item.type === "mcp_list_tools") {
2826
- const list = event.item;
2827
- const toolNames = list.tools.map((t) => t.name);
2828
- const listError = typeof list.error === "string" && list.error.length > 0 ? list.error : void 0;
2829
- yield {
2830
- type: EventType.TOOL_CALL_RESULT,
2831
- messageId: list.id,
2832
- toolCallId: list.id,
2833
- content: JSON.stringify({
2834
- server_label: list.server_label,
2835
- tool_count: toolNames.length,
2836
- tools: toolNames
2837
- }),
2838
- ...listError ? {
2839
- isError: true,
2840
- error: listError
2841
- } : {}
2842
- };
2843
- break;
2844
- }
2845
- const item = event.item;
2846
- if (item.type !== "web_search_call") break;
2847
- const toolCallId = item.id ?? "web_search_call";
2848
- if (item.action && typeof item.action === "object") yield {
2849
- type: EventType.TOOL_CALL_ARGS,
2850
- toolCallId,
2851
- delta: JSON.stringify(item.action)
2852
- };
2853
- const content = stringifyOutput(item.output);
2854
- yield {
2855
- type: EventType.TOOL_CALL_RESULT,
2856
- messageId: toolCallId,
2857
- toolCallId,
2858
- content
2859
- };
2860
- break;
2861
- }
2862
- case "error":
2863
- yield {
2864
- type: EventType.RUN_ERROR,
2865
- message: event.message,
2866
- code: event.code ?? void 0
2867
- };
2868
- break;
2869
- case "response.failed": yield {
2870
- type: EventType.RUN_ERROR,
2871
- message: event.response?.error?.message ?? "Response failed",
2872
- code: event.response?.error?.code ?? void 0
2873
- };
2874
- }
2875
- } catch (e) {
2876
- console.error("Failed to parse OpenAI Responses SSE event", e);
2877
- }
2878
- }
2879
- if (done) break;
2880
- }
2881
- } });
2882
- // src/stream/adapters/vercel-ai-sdk.ts
2883
- const MISSING_AI_SDK_MESSAGE = "vercelAIAdapter requires the optional peer dependency \"ai\" (Vercel AI SDK v6 or v7).";
2884
- const PROVIDER_EXECUTED_TOOLS_UNSUPPORTED_MESSAGE$1 = "Vercel AI SDK provider-executed tools are not supported because AG-UI messages cannot preserve providerExecuted semantics.";
2885
- const TOOL_EXECUTION_DENIED_MESSAGE = "Tool execution was denied";
2886
- function serialize$1(value) {
2887
- if (typeof value === "string") return value;
2888
- return JSON.stringify(value) ?? String(value);
2889
- }
2890
- async function parseUIMessageStream(body) {
2891
- let DefaultChatTransport;
2892
- try {
2893
- ({DefaultChatTransport} = await import("ai"));
2894
- } catch (cause) {
2895
- throw new Error(MISSING_AI_SDK_MESSAGE, { cause });
2896
- }
2897
- if (typeof DefaultChatTransport !== "function") throw new Error(MISSING_AI_SDK_MESSAGE);
2898
- class UIMessageStreamParser extends DefaultChatTransport {
2899
- parseBody(stream) {
2900
- return this.processResponseStream(stream);
2901
- }
2902
- }
2903
- return new UIMessageStreamParser().parseBody(body);
2904
- }
2905
- async function* readChunks(stream) {
2906
- const reader = stream.getReader();
2907
- try {
2908
- for (;;) {
2909
- const { done, value } = await reader.read();
2910
- if (done) return;
2911
- yield value;
2912
- }
2913
- } finally {
2914
- reader.releaseLock();
2915
- }
2916
- }
2917
- function toolResult(toolCallId, content, error) {
2918
- return {
2919
- type: EventType.TOOL_CALL_RESULT,
2920
- messageId: `tool-result-${toolCallId}`,
2921
- toolCallId,
2922
- content,
2923
- role: "tool",
2924
- ...error !== void 0 ? {
2925
- isError: true,
2926
- error
2927
- } : {}
2928
- };
2929
- }
2930
- /**
2931
- * Adapter for Vercel AI SDK v6 and v7 UIMessage streams.
2932
- *
2933
- * The AI SDK is loaded only when parsing begins so it can remain an optional
2934
- * peer dependency for consumers that use other stream adapters. Its
2935
- * `DefaultChatTransport` performs the native SSE decoding and chunk validation;
2936
- * this adapter only maps validated UIMessage chunks to AG-UI events.
2937
- */
2938
- const vercelAIAdapter = () => ({ async *parse(response) {
2939
- if (!response.body) throw new Error("No response body");
2940
- const chunks = await parseUIMessageStream(response.body);
2941
- const startedTools = /* @__PURE__ */ new Set();
2942
- const streamedToolArgs = /* @__PURE__ */ new Set();
2943
- const endedTools = /* @__PURE__ */ new Set();
2944
- let stepIndex = 0;
2945
- let activeStep;
2946
- const startStepMessage = (preferredMessageId) => {
2947
- if (!activeStep || activeStep.messageStarted) return;
2948
- activeStep.messageId ??= preferredMessageId ?? `vercel-ai-message-${stepIndex}`;
2949
- activeStep.messageStarted = true;
2950
- return {
2951
- type: EventType.TEXT_MESSAGE_START,
2952
- messageId: activeStep.messageId,
2953
- role: "assistant"
2954
- };
2955
- };
2956
- const beginText = (partId) => {
2957
- if (activeStep?.messageStarted && activeStep.sawTools) {
2958
- const previousId = activeStep.messageId;
2959
- activeStep.messageId = partId;
2960
- activeStep.sawTools = false;
2961
- return [{
2962
- type: EventType.TEXT_MESSAGE_END,
2963
- messageId: previousId
2964
- }, {
2965
- type: EventType.TEXT_MESSAGE_START,
2966
- messageId: partId,
2967
- role: "assistant"
2968
- }];
2969
- }
2970
- const event = startStepMessage(partId);
2971
- return event ? [event] : [];
2972
- };
2973
- const toolParent = () => activeStep?.messageId ? { parentMessageId: activeStep.messageId } : {};
2974
- for await (const chunk of readChunks(chunks)) {
2975
- if ("providerExecuted" in chunk && chunk.providerExecuted === true) throw new Error(PROVIDER_EXECUTED_TOOLS_UNSUPPORTED_MESSAGE$1);
2976
- switch (chunk.type) {
2977
- case "start-step": {
2978
- const stepName = `vercel-ai-step-${++stepIndex}`;
2979
- activeStep = {
2980
- stepName,
2981
- messageStarted: false,
2982
- sawTools: false
2983
- };
2984
- yield {
2985
- type: EventType.STEP_STARTED,
2986
- stepName
2987
- };
2988
- break;
2989
- }
2990
- case "finish-step": {
2991
- const stepName = activeStep?.stepName ?? `vercel-ai-step-${++stepIndex}`;
2992
- if (activeStep?.messageStarted && activeStep.messageId) yield {
2993
- type: EventType.TEXT_MESSAGE_END,
2994
- messageId: activeStep.messageId
2995
- };
2996
- yield {
2997
- type: EventType.STEP_FINISHED,
2998
- stepName
2999
- };
3000
- activeStep = void 0;
3001
- break;
3002
- }
3003
- case "text-start":
3004
- for (const event of beginText(chunk.id)) yield event;
3005
- if (!activeStep) yield {
3006
- type: EventType.TEXT_MESSAGE_START,
3007
- messageId: chunk.id,
3008
- role: "assistant"
3009
- };
3010
- break;
3011
- case "text-delta":
3012
- for (const event of beginText(chunk.id)) yield event;
3013
- yield {
3014
- type: EventType.TEXT_MESSAGE_CONTENT,
3015
- messageId: activeStep?.messageId ?? chunk.id,
3016
- delta: chunk.delta
3017
- };
3018
- break;
3019
- case "text-end":
3020
- if (!activeStep) yield {
3021
- type: EventType.TEXT_MESSAGE_END,
3022
- messageId: chunk.id
3023
- };
3024
- break;
3025
- case "tool-input-start":
3026
- if (!startedTools.has(chunk.toolCallId)) {
3027
- const event = startStepMessage();
3028
- if (event) yield event;
3029
- startedTools.add(chunk.toolCallId);
3030
- if (activeStep) activeStep.sawTools = true;
3031
- yield {
3032
- type: EventType.TOOL_CALL_START,
3033
- toolCallId: chunk.toolCallId,
3034
- toolCallName: chunk.toolName,
3035
- ...toolParent()
3036
- };
3037
- }
3038
- break;
3039
- case "tool-input-delta":
3040
- if (chunk.inputTextDelta) {
3041
- streamedToolArgs.add(chunk.toolCallId);
3042
- yield {
3043
- type: EventType.TOOL_CALL_ARGS,
3044
- toolCallId: chunk.toolCallId,
3045
- delta: chunk.inputTextDelta
3046
- };
3047
- }
3048
- break;
3049
- case "tool-input-available":
3050
- case "tool-input-error":
3051
- if (!startedTools.has(chunk.toolCallId)) {
3052
- const event = startStepMessage();
3053
- if (event) yield event;
3054
- startedTools.add(chunk.toolCallId);
3055
- if (activeStep) activeStep.sawTools = true;
3056
- yield {
3057
- type: EventType.TOOL_CALL_START,
3058
- toolCallId: chunk.toolCallId,
3059
- toolCallName: chunk.toolName,
3060
- ...toolParent()
3061
- };
3062
- }
3063
- if (!streamedToolArgs.has(chunk.toolCallId)) {
3064
- streamedToolArgs.add(chunk.toolCallId);
3065
- yield {
3066
- type: EventType.TOOL_CALL_ARGS,
3067
- toolCallId: chunk.toolCallId,
3068
- delta: serialize$1(chunk.input)
3069
- };
3070
- }
3071
- if (!endedTools.has(chunk.toolCallId)) {
3072
- endedTools.add(chunk.toolCallId);
3073
- yield {
3074
- type: EventType.TOOL_CALL_END,
3075
- toolCallId: chunk.toolCallId
3076
- };
3077
- }
3078
- if (chunk.type === "tool-input-error") yield toolResult(chunk.toolCallId, chunk.errorText, chunk.errorText);
3079
- break;
3080
- case "tool-output-available":
3081
- yield toolResult(chunk.toolCallId, serialize$1(chunk.output));
3082
- break;
3083
- case "tool-output-error":
3084
- yield toolResult(chunk.toolCallId, chunk.errorText, chunk.errorText);
3085
- break;
3086
- case "tool-output-denied":
3087
- yield toolResult(chunk.toolCallId, TOOL_EXECUTION_DENIED_MESSAGE, TOOL_EXECUTION_DENIED_MESSAGE);
3088
- break;
3089
- case "error":
3090
- yield {
3091
- type: EventType.RUN_ERROR,
3092
- message: chunk.errorText
3093
- };
3094
- return;
3095
- }
3096
- }
3097
- if (activeStep?.messageStarted && activeStep.messageId) yield {
3098
- type: EventType.TEXT_MESSAGE_END,
3099
- messageId: activeStep.messageId
3100
- };
3101
- } });
3102
- // src/stream/processStreamedMessage.ts
3103
- /**
3104
- * @category Utilities
3105
- */
3106
- const processStreamedMessage = async ({ response, createMessage, updateMessage, markToolExecuting = () => {}, clearToolExecuting = () => {}, adapter = agUIAdapter() }) => {
3107
- let currentMessage = {
3108
- id: crypto.randomUUID(),
3109
- role: "assistant",
3110
- content: "",
3111
- toolCalls: []
3112
- };
3113
- let isFirst = true;
3114
- let currentTextItemId = null;
3115
- const toolMessagesByCallId = /* @__PURE__ */ new Map();
3116
- const inFlightToolCallIds = /* @__PURE__ */ new Set();
3117
- let rafId = null;
3118
- const debouncedUpdate = (msg) => {
3119
- if (rafId !== null) cancelAnimationFrame(rafId);
3120
- rafId = requestAnimationFrame(() => {
3121
- updateMessage(msg);
3122
- rafId = null;
3123
- });
3124
- };
3125
- /** Flush the open assistant and start a fresh one (interleaved segments). */
3126
- const startNewAssistantSegment = () => {
3127
- if (rafId !== null) {
3128
- cancelAnimationFrame(rafId);
3129
- rafId = null;
3130
- if (!isFirst) updateMessage(currentMessage);
3131
- }
3132
- currentMessage = {
3133
- id: crypto.randomUUID(),
3134
- role: "assistant",
3135
- content: "",
3136
- toolCalls: []
3137
- };
3138
- isFirst = true;
3139
- currentTextItemId = null;
3140
- };
3141
- const messageHasBody = (msg) => (msg.content?.length ?? 0) > 0 || (msg.toolCalls?.length ?? 0) > 0;
3142
- /** Publish the open assistant only once it has text or tool calls — never an empty shell. */
3143
- const commitCurrentMessage = () => {
3144
- if (isFirst) {
3145
- if (!messageHasBody(currentMessage)) return;
3146
- createMessage(currentMessage);
3147
- isFirst = false;
3148
- } else debouncedUpdate(currentMessage);
3149
- };
3150
- for await (const event of adapter.parse(response)) {
3151
- switch (event.type) {
3152
- case EventType.TEXT_MESSAGE_CHUNK:
3153
- case EventType.TEXT_MESSAGE_CONTENT:
3154
- if (!event.delta) break;
3155
- if ((currentMessage.toolCalls?.length ?? 0) > 0) startNewAssistantSegment();
3156
- currentMessage = {
3157
- ...currentMessage,
3158
- content: (currentMessage.content || "") + event.delta
3159
- };
3160
- break;
3161
- case EventType.TOOL_CALL_START:
3162
- inFlightToolCallIds.add(event.toolCallId);
3163
- currentMessage = {
3164
- ...currentMessage,
3165
- toolCalls: [...currentMessage.toolCalls || [], {
3166
- id: event.toolCallId,
3167
- type: "function",
3168
- function: {
3169
- name: event.toolCallName,
3170
- arguments: ""
3171
- }
3172
- }]
3173
- };
3174
- break;
3175
- case EventType.TOOL_CALL_END:
3176
- markToolExecuting(event.toolCallId);
3177
- break;
3178
- case EventType.TOOL_CALL_ARGS:
3179
- if (currentMessage.toolCalls) {
3180
- const toolCalls = [...currentMessage.toolCalls];
3181
- const toolCallIndex = toolCalls.findIndex((tc) => tc.id === event.toolCallId);
3182
- if (toolCallIndex !== -1) {
3183
- const currentToolCall = toolCalls[toolCallIndex];
3184
- if (currentToolCall) {
3185
- toolCalls[toolCallIndex] = {
3186
- id: currentToolCall.id,
3187
- type: "function",
3188
- function: {
3189
- name: currentToolCall.function.name,
3190
- arguments: currentToolCall.function.arguments + event.delta
3191
- }
3192
- };
3193
- currentMessage = {
3194
- ...currentMessage,
3195
- toolCalls
3196
- };
3197
- }
3198
- }
3199
- }
3200
- break;
3201
- case EventType.TOOL_CALL_CHUNK: {
3202
- const id = event.toolCallId;
3203
- if (!id) break;
3204
- const toolCalls = [...currentMessage.toolCalls || []];
3205
- let index = toolCalls.findIndex((tc) => tc.id === id);
3206
- if (index === -1) {
3207
- inFlightToolCallIds.add(id);
3208
- toolCalls.push({
3209
- id,
3210
- type: "function",
3211
- function: {
3212
- name: event.toolCallName ?? "",
3213
- arguments: ""
3214
- }
3215
- });
3216
- index = toolCalls.length - 1;
3217
- }
3218
- const existing = toolCalls[index];
3219
- if (existing) {
3220
- toolCalls[index] = {
3221
- id: existing.id,
3222
- type: "function",
3223
- function: {
3224
- name: existing.function.name || event.toolCallName || "",
3225
- arguments: existing.function.arguments + (event.delta ?? "")
3226
- }
3227
- };
3228
- currentMessage = {
3229
- ...currentMessage,
3230
- toolCalls
3231
- };
3232
- }
3233
- break;
3234
- }
3235
- case EventType.TEXT_MESSAGE_START: {
3236
- const startId = event.messageId ?? null;
3237
- if (((currentMessage.content?.length ?? 0) > 0 || (currentMessage.toolCalls?.length ?? 0) > 0) && startId !== currentTextItemId) startNewAssistantSegment();
3238
- currentTextItemId = startId;
3239
- break;
3240
- }
3241
- case EventType.TOOL_CALL_RESULT: {
3242
- clearToolExecuting(event.toolCallId);
3243
- inFlightToolCallIds.delete(event.toolCallId);
3244
- if (rafId !== null) {
3245
- cancelAnimationFrame(rafId);
3246
- rafId = null;
3247
- updateMessage(currentMessage);
3248
- }
3249
- const failed = event;
3250
- const errorText = failed.isError === true || typeof failed.error === "string" && failed.error.length > 0 ? failed.error ?? event.content : void 0;
3251
- const existing = toolMessagesByCallId.get(event.toolCallId);
3252
- if (existing) {
3253
- const updated = {
3254
- ...existing,
3255
- content: event.content,
3256
- ...errorText ? { error: errorText } : {}
3257
- };
3258
- toolMessagesByCallId.set(event.toolCallId, updated);
3259
- updateMessage(updated);
3260
- } else {
3261
- const toolMessage = {
3262
- id: crypto.randomUUID(),
3263
- role: "tool",
3264
- toolCallId: event.toolCallId,
3265
- content: event.content,
3266
- ...errorText ? { error: errorText } : {}
3267
- };
3268
- toolMessagesByCallId.set(event.toolCallId, toolMessage);
3269
- createMessage(toolMessage);
3270
- }
3271
- continue;
3272
- }
3273
- case EventType.RUN_ERROR: {
3274
- const raw = event.message || event.error || "Stream error";
3275
- const errorText = typeof raw === "string" ? raw : JSON.stringify(raw);
3276
- for (const toolCallId of inFlightToolCallIds) clearToolExecuting(toolCallId);
3277
- inFlightToolCallIds.clear();
3278
- throw new Error(errorText);
3279
- }
3280
- }
3281
- commitCurrentMessage();
3282
- }
3283
- if (rafId !== null) {
3284
- cancelAnimationFrame(rafId);
3285
- updateMessage(currentMessage);
3286
- } else if (isFirst && messageHasBody(currentMessage)) createMessage(currentMessage);
3287
- return currentMessage;
3288
- };
3289
- // src/store/observability.ts
3290
- async function buildObservabilityErrorDetail(response) {
3291
- if (response.ok) return {};
3292
- try {
3293
- const res = await response.clone().json();
3294
- return {
3295
- error: res?.error,
3296
- ...!res?.message ? { message: await getResponseErrorMessage(response) } : { message: res.message }
3297
- };
3298
- } catch {
3299
- return { message: await getResponseErrorMessage(response) };
3300
- }
3301
- }
3302
- function levelForStatus(status) {
3303
- return status >= 400 ? "error" : "info";
3304
- }
3305
- // src/store/createChatStore.ts
3306
- const mergeThreadList = (existing, incoming) => Array.from(new Map([...existing, ...incoming].map((t) => [t.id, t])).values()).sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime());
3307
- const createChatStore = (configRef) => {
3308
- const { storage } = configRef.current;
3309
- const { thread: threadStorage } = storage;
3310
- return createStore()(subscribeWithSelector((set, get) => ({
3311
- threads: [],
3312
- isLoadingThreads: false,
3313
- threadListError: null,
3314
- selectedThreadId: null,
3315
- hasMoreThreads: false,
3316
- _nextCursor: void 0,
3317
- messages: [],
3318
- isRunning: false,
3319
- isLoadingMessages: false,
3320
- threadError: null,
3321
- executingToolCallIds: /* @__PURE__ */ new Set(),
3322
- _abortController: null,
3323
- loadThreads: () => {
3324
- set({
3325
- isLoadingThreads: true,
3326
- threadListError: null
3327
- });
3328
- threadStorage.listThreads(void 0).then(({ threads = [], nextCursor }) => {
3329
- set({
3330
- threads,
3331
- isLoadingThreads: false,
3332
- _nextCursor: nextCursor,
3333
- hasMoreThreads: nextCursor !== void 0
3334
- });
3335
- }).catch((e) => {
3336
- set({
3337
- isLoadingThreads: false,
3338
- threadListError: e
3339
- });
3340
- });
3341
- },
3342
- loadMoreThreads: () => {
3343
- const cursor = get()._nextCursor;
3344
- if (cursor === void 0) return;
3345
- threadStorage.listThreads(cursor).then(({ threads = [], nextCursor }) => {
3346
- set((s) => ({
3347
- threads: mergeThreadList(s.threads, threads),
3348
- _nextCursor: nextCursor,
3349
- hasMoreThreads: nextCursor !== void 0
3350
- }));
3351
- }).catch((e) => {
3352
- set({ threadListError: e });
3353
- });
3354
- },
3355
- switchToNewThread: () => {
3356
- get().cancelMessage();
3357
- set({
3358
- selectedThreadId: null,
3359
- messages: [],
3360
- threadError: null,
3361
- executingToolCallIds: /* @__PURE__ */ new Set()
3362
- });
3363
- },
3364
- createThread: async (firstMessage) => {
3365
- const thread = await threadStorage.createThread(firstMessage);
3366
- set((s) => ({ threads: mergeThreadList(s.threads, [thread]) }));
3367
- return thread;
3368
- },
3369
- selectThread: (threadId) => {
3370
- if (get().selectedThreadId === threadId) return;
3371
- get().cancelMessage();
3372
- set({
3373
- selectedThreadId: threadId,
3374
- messages: [],
3375
- isLoadingMessages: true,
3376
- threadError: null,
3377
- executingToolCallIds: /* @__PURE__ */ new Set()
3378
- });
3379
- threadStorage.getMessages(threadId).then((messages) => set({
3380
- messages,
3381
- isLoadingMessages: false
3382
- })).catch((e) => set({
3383
- threadError: e,
3384
- isLoadingMessages: false
3385
- }));
3386
- },
3387
- updateThread: (thread) => {
3388
- const setPending = (id, isPending) => set((s) => ({ threads: s.threads.map((t) => t.id === id ? {
3389
- ...t,
3390
- isPending
3391
- } : t) }));
3392
- setPending(thread.id, true);
3393
- threadStorage.updateThread(thread).then((updated) => {
3394
- set((s) => ({ threads: s.threads.map((t) => t.id === updated.id ? updated : t) }));
3395
- }).catch(() => setPending(thread.id, false));
3396
- },
3397
- deleteThread: (threadId) => {
3398
- const setPending = (id, isPending) => set((s) => ({ threads: s.threads.map((t) => t.id === id ? {
3399
- ...t,
3400
- isPending
3401
- } : t) }));
3402
- setPending(threadId, true);
3403
- threadStorage.deleteThread(threadId).then(() => {
3404
- const state = get();
3405
- set({ threads: state.threads.filter((t) => t.id !== threadId) });
3406
- if (state.selectedThreadId === threadId) state.switchToNewThread();
3407
- }).catch(() => setPending(threadId, false));
3408
- },
3409
- processMessage: async (message) => {
3410
- if (get().isRunning) return;
3411
- const abortController = new AbortController();
3412
- const optimisticMessage = {
3413
- ...message,
3414
- id: crypto.randomUUID(),
3415
- role: "user"
3416
- };
3417
- set({
3418
- _abortController: abortController,
3419
- isRunning: true,
3420
- threadError: null,
3421
- executingToolCallIds: /* @__PURE__ */ new Set()
3422
- });
3423
- set((s) => ({ messages: [...s.messages, optimisticMessage] }));
3424
- abortController.signal.addEventListener("abort", () => {
3425
- set({
3426
- _abortController: null,
3427
- isRunning: false
3428
- });
3429
- });
3430
- try {
3431
- let threadId = get().selectedThreadId;
3432
- if (!threadId) {
3433
- threadId = (await get().createThread(optimisticMessage)).id;
3434
- set({ selectedThreadId: threadId });
3435
- }
3436
- const runId = crypto.randomUUID();
3437
- observability.info({
3438
- kind: "LLM:request",
3439
- threadId,
3440
- runId,
3441
- userMessage: optimisticMessage
3442
- });
3443
- let response = null;
3444
- try {
3445
- response = await configRef.current.llm.send({
3446
- threadId,
3447
- messages: get().messages,
3448
- signal: abortController.signal
3449
- });
3450
- observability(levelForStatus(response.status), {
3451
- kind: response.ok ? "LLM:response" : "LLM:error",
3452
- threadId,
3453
- status: response.status,
3454
- ok: response.ok,
3455
- runId,
3456
- ...await buildObservabilityErrorDetail(response)
3457
- });
3458
- if (!response.ok) throw new Error(await getResponseErrorMessage(response));
3459
- } catch (e) {
3460
- observability.error({
3461
- kind: "LLM:error",
3462
- threadId,
3463
- runId,
3464
- error: e instanceof Error ? e : new Error(String(e))
3465
- });
3466
- throw e;
3467
- }
3468
- await processStreamedMessage({
3469
- response,
3470
- createMessage: (msg) => set((s) => ({ messages: [...s.messages, msg] })),
3471
- updateMessage: (msg) => set((s) => ({ messages: s.messages.map((m) => m.id === msg.id ? msg : m) })),
3472
- markToolExecuting: (id) => set((s) => s.executingToolCallIds.has(id) ? s : { executingToolCallIds: new Set(s.executingToolCallIds).add(id) }),
3473
- clearToolExecuting: (id) => set((s) => {
3474
- if (!s.executingToolCallIds.has(id)) return s;
3475
- const next = new Set(s.executingToolCallIds);
3476
- next.delete(id);
3477
- return { executingToolCallIds: next };
3478
- }),
3479
- adapter: configRef.current.llm.streamProtocol
3480
- });
3481
- } catch (e) {
3482
- if (!abortController.signal.aborted) set({ threadError: e instanceof Error ? e : new Error(String(e)) });
3483
- } finally {
3484
- set({
3485
- _abortController: null,
3486
- isRunning: false,
3487
- executingToolCallIds: /* @__PURE__ */ new Set()
3488
- });
3489
- }
3490
- },
3491
- appendMessages: (...newMessages) => {
3492
- set((s) => ({ messages: [...s.messages, ...newMessages] }));
3493
- },
3494
- updateMessage: (message) => {
3495
- set((s) => ({ messages: s.messages.map((m) => m.id === message.id ? message : m) }));
3496
- },
3497
- setMessages: (messages) => {
3498
- set({ messages });
3499
- },
3500
- deleteMessage: (messageId) => {
3501
- set((s) => ({ messages: s.messages.filter((m) => m.id !== messageId) }));
3502
- },
3503
- cancelMessage: () => {
3504
- get()._abortController?.abort();
3505
- }
3506
- })));
3507
- };
3508
- // src/store/createDetailedViewStore.ts
3509
- /**
3510
- * Creates a Zustand store managing detailed-view state.
3511
- * Instantiated once by `ChatProvider` — consumers should not call this directly.
3512
- *
3513
- * @internal
3514
- */
3515
- const createDetailedViewStore = () => {
3516
- return createStore()(subscribeWithSelector((set, get) => ({
3517
- activeDetailedViewId: null,
3518
- setActiveDetailedView: (id) => {
3519
- set({ activeDetailedViewId: id });
3520
- },
3521
- reset: () => {
3522
- set({ activeDetailedViewId: null });
3523
- },
3524
- _detailedViewPanelNode: null,
3525
- _setDetailedViewPanelNode: (node) => {
3526
- if (typeof process !== "undefined" && process.env?.["NODE_ENV"] !== "production" && node && get()._detailedViewPanelNode && get()._detailedViewPanelNode !== node) console.warn("[OpenUI] Multiple DetailedViewPortalTarget instances detected. Only one should be mounted at a time.");
3527
- set({ _detailedViewPanelNode: node });
3528
- }
3529
- })));
3530
- };
3531
- // src/store/createThreadContextStore.ts
3532
- const entriesEqual = (a, b) => a.heading === b.heading && a.type === b.type;
3533
- const upsertVersion = (registry, entry) => {
3534
- const existing = registry[entry.id] ?? [];
3535
- const sameVersionIdx = existing.findIndex((e) => e.version === entry.version);
3536
- if (sameVersionIdx !== -1) {
3537
- const current = existing[sameVersionIdx];
3538
- if (entriesEqual(current, entry)) return registry;
3539
- const next = existing.slice();
3540
- next[sameVersionIdx] = entry;
3541
- return {
3542
- ...registry,
3543
- [entry.id]: next
3544
- };
3545
- }
3546
- const insertIdx = existing.findIndex((e) => e.version > entry.version);
3547
- const next = insertIdx === -1 ? [...existing, entry] : [
3548
- ...existing.slice(0, insertIdx),
3549
- entry,
3550
- ...existing.slice(insertIdx)
3551
- ];
3552
- return {
3553
- ...registry,
3554
- [entry.id]: next
3555
- };
3556
- };
3557
- const removeVersion = (registry, id, version) => {
3558
- const existing = registry[id];
3559
- if (!existing) return registry;
3560
- const idx = existing.findIndex((e) => e.version === version);
3561
- if (idx === -1) return registry;
3562
- if (existing.length === 1) {
3563
- const { [id]: _removed, ...rest } = registry;
3564
- return rest;
3565
- }
3566
- const next = existing.slice();
3567
- next.splice(idx, 1);
3568
- return {
3569
- ...registry,
3570
- [id]: next
3571
- };
3572
- };
3573
- /**
3574
- * Creates a Zustand store managing the per-thread artifact registry.
3575
- *
3576
- * Active detailed-view state lives in a separate store
3577
- * (see {@link useDetailedView} / {@link useActiveDetailedView}) — TC tracks
3578
- * what's *attached* to the thread; detailed-view state tracks what's *visible*.
3579
- *
3580
- * Instantiated once by `ChatProvider` — consumers should not call this directly.
3581
- *
3582
- * @internal
3583
- */
3584
- const createThreadContextStore = () => {
3585
- return createStore()(subscribeWithSelector((set) => ({
3586
- artifacts: {},
3587
- registerArtifact: (entry) => {
3588
- set((s) => ({ artifacts: upsertVersion(s.artifacts, entry) }));
3589
- },
3590
- unregisterArtifact: (id, version) => {
3591
- set((s) => ({ artifacts: removeVersion(s.artifacts, id, version) }));
3592
- },
3593
- reset: () => {
3594
- set({ artifacts: {} });
3595
- }
3596
- })));
3597
- };
3598
- // src/store/ChatProvider.ts
3599
- const EMPTY_CATEGORIES = [];
3600
- const ChatProvider = defineComponent({
3601
- name: "OpenUIChatProvider",
3602
- props: {
3603
- llm: {
3604
- type: Object,
3605
- required: true
3606
- },
3607
- storage: Object,
3608
- artifactRenderers: Array,
3609
- artifactCategories: Array,
3610
- artifactAutoOpen: {
3611
- type: Boolean,
3612
- default: true
3613
- },
3614
- children: null
3615
- },
3616
- setup(props, { slots }) {
3617
- const storage = props.storage ?? createDefaultInMemoryStorage();
3618
- const config = { current: {
3619
- storage,
3620
- llm: props.llm
3621
- } };
3622
- watch(() => props.llm, (value) => {
3623
- config.current.llm = value;
3624
- }, { flush: "sync" });
3625
- const chat = createChatStore(config);
3626
- const detail = createDetailedViewStore();
3627
- const thread = createThreadContextStore();
3628
- const registry = buildArtifactRendererRegistry(props.artifactRenderers ?? []);
3629
- const initialRenderers = props.artifactRenderers;
3630
- let warned = false;
3631
- onUpdated(() => {
3632
- const renderers = props.artifactRenderers;
3633
- if (typeof process !== "undefined" && process.env.NODE_ENV !== "production" && !warned && renderers !== initialRenderers) {
3634
- 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.");
3635
- warned = true;
3636
- }
3637
- });
3638
- let unsubscribe;
3639
- onMounted(() => {
3640
- unsubscribe = chat.subscribe((state) => state.selectedThreadId, () => {
3641
- detail.getState().reset();
3642
- thread.getState().reset();
3643
- });
3644
- });
3645
- onScopeDispose(() => unsubscribe?.());
3646
- useArtifactAutoOpenWatcher(() => props.artifactAutoOpen ?? true, chat, thread, detail);
3647
- provide(ChatContext, chat);
3648
- provide(DetailedViewContext, detail);
3649
- provide(ThreadContextContext, thread);
3650
- provide(ArtifactRenderersContext, registry);
3651
- provide(ArtifactStorageContext, storage.artifact ?? null);
3652
- provide(ArtifactCategoriesContext, computed(() => props.artifactCategories ?? EMPTY_CATEGORIES));
3653
- return () => slots.default?.() ?? props.children;
3654
- }
3655
- });
3656
- // src/stream/formats/langgraph-message-format.ts
3657
- function toLangChainMessage(message) {
3658
- switch (message.role) {
3659
- case "user": return {
3660
- type: "human",
3661
- content: message.content ?? ""
3662
- };
3663
- case "assistant": {
3664
- const result = {
3665
- type: "ai",
3666
- content: message.content ?? ""
3667
- };
3668
- if (message.toolCalls?.length) result.tool_calls = message.toolCalls.map((tc) => ({
3669
- id: tc.id,
3670
- name: tc.function.name,
3671
- args: safeParseArgs(tc.function.arguments)
3672
- }));
3673
- return result;
3674
- }
3675
- case "tool": return {
3676
- type: "tool",
3677
- content: message.content,
3678
- tool_call_id: message.toolCallId
3679
- };
3680
- case "system": return {
3681
- type: "system",
3682
- content: message.content
3683
- };
3684
- case "developer": return {
3685
- type: "system",
3686
- content: message.content
3687
- };
3688
- default: return {
3689
- type: "system",
3690
- content: ""
3691
- };
3692
- }
3693
- }
3694
- function fromLangChainMessage(msg) {
3695
- const id = msg.id ?? crypto.randomUUID();
3696
- switch (msg.type) {
3697
- case "human": return {
3698
- id,
3699
- role: "user",
3700
- content: extractContent(msg.content)
3701
- };
3702
- case "ai": {
3703
- const result = {
3704
- id,
3705
- role: "assistant",
3706
- content: extractContent(msg.content)
3707
- };
3708
- if (msg.tool_calls?.length) result.toolCalls = msg.tool_calls.map((tc) => ({
3709
- id: tc.id,
3710
- type: "function",
3711
- function: {
3712
- name: tc.name,
3713
- arguments: typeof tc.args === "string" ? tc.args : JSON.stringify(tc.args)
3714
- }
3715
- }));
3716
- return result;
3717
- }
3718
- case "tool": return {
3719
- id,
3720
- role: "tool",
3721
- content: extractContent(msg.content),
3722
- toolCallId: msg.tool_call_id ?? ""
3723
- };
3724
- case "system":
3725
- case "developer": return {
3726
- id,
3727
- role: "system",
3728
- content: extractContent(msg.content)
3729
- };
3730
- default: return {
3731
- id,
3732
- role: "system",
3733
- content: extractContent(msg.content)
3734
- };
3735
- }
3736
- }
3737
- function extractContent(content) {
3738
- if (typeof content === "string") return content;
3739
- return content.filter((block) => block.type === "text" && block.text).map((block) => block.text).join("");
3740
- }
3741
- function safeParseArgs(args) {
3742
- try {
3743
- return JSON.parse(args);
3744
- } catch {
3745
- return args;
3746
- }
3747
- }
3748
- /**
3749
- * Converts between AG-UI message format and LangGraph's LangChain-style
3750
- * message format.
3751
- *
3752
- * LangGraph uses `type` discriminators (`"human"`, `"ai"`, `"tool"`,
3753
- * `"system"`) instead of `role`, and tool call arguments are objects
3754
- * rather than JSON strings.
3755
- *
3756
- * AG-UI → LangGraph (toApi):
3757
- * - Maps `role` to `type` (`"user"` → `"human"`, `"assistant"` → `"ai"`)
3758
- * - Converts `toolCalls[].function.arguments` from JSON string to object
3759
- * - Converts `toolCallId` → `tool_call_id`
3760
- *
3761
- * LangGraph → AG-UI (fromApi):
3762
- * - Maps `type` to `role` (`"human"` → `"user"`, `"ai"` → `"assistant"`)
3763
- * - Converts tool call `args` object to JSON string
3764
- * - Generates `id` via `crypto.randomUUID()` if not present
3765
- */
3766
- const langGraphMessageFormat = {
3767
- toApi(messages) {
3768
- return messages.map(toLangChainMessage);
3769
- },
3770
- fromApi(data) {
3771
- return data.map(fromLangChainMessage);
3772
- }
3773
- };
3774
- // src/stream/formats/openai-message-format.ts
3775
- function toOpenAIUserMessage(message) {
3776
- const content = message.content;
3777
- if (typeof content === "string") return {
3778
- role: "user",
3779
- content
3780
- };
3781
- return {
3782
- role: "user",
3783
- content: content?.map((part) => {
3784
- if (part.type === "text") return {
3785
- type: "text",
3786
- text: part.text
3787
- };
3788
- if (part.type === "binary") return {
3789
- type: "image_url",
3790
- image_url: { url: part.url ?? `data:${part.mimeType};base64,${part.data ?? ""}` }
3791
- };
3792
- return {
3793
- type: "text",
3794
- text: ""
3795
- };
3796
- }) ?? []
3797
- };
3798
- }
3799
- function toOpenAIAssistantMessage(message) {
3800
- const result = {
3801
- role: "assistant",
3802
- content: message.content ?? null
3803
- };
3804
- if (message.toolCalls?.length) result.tool_calls = message.toolCalls.map((tc) => ({
3805
- id: tc.id,
3806
- type: "function",
3807
- function: {
3808
- name: tc.function.name,
3809
- arguments: tc.function.arguments
3810
- }
3811
- }));
3812
- return result;
3813
- }
3814
- function toOpenAIToolMessage(message) {
3815
- return {
3816
- role: "tool",
3817
- content: message.content,
3818
- tool_call_id: message.toolCallId
3819
- };
3820
- }
3821
- function toOpenAI(message) {
3822
- switch (message.role) {
3823
- case "user": return toOpenAIUserMessage(message);
3824
- case "assistant": return toOpenAIAssistantMessage(message);
3825
- case "tool": return toOpenAIToolMessage(message);
3826
- case "system": return {
3827
- role: "system",
3828
- content: message.content
3829
- };
3830
- case "developer": return {
3831
- role: "developer",
3832
- content: message.content
3833
- };
3834
- default: return {
3835
- role: "system",
3836
- content: ""
3837
- };
3838
- }
3839
- }
3840
- function fromOpenAIAssistant(msg) {
3841
- const content = typeof msg.content === "string" ? msg.content : void 0;
3842
- const result = {
3843
- id: crypto.randomUUID(),
3844
- role: "assistant",
3845
- content
3846
- };
3847
- if (msg.tool_calls?.length) result.toolCalls = msg.tool_calls.filter((tc) => tc.type === "function").map((tc) => ({
3848
- id: tc.id,
3849
- type: "function",
3850
- function: {
3851
- name: tc.function.name,
3852
- arguments: tc.function.arguments
3853
- }
3854
- }));
3855
- return result;
3856
- }
3857
- function fromOpenAIUser(msg) {
3858
- if (typeof msg.content === "string") return {
3859
- id: crypto.randomUUID(),
3860
- role: "user",
3861
- content: msg.content
3862
- };
3863
- const content = msg.content.map((part) => {
3864
- if (part.type === "text") return {
3865
- type: "text",
3866
- text: part.text
3867
- };
3868
- return {
3869
- type: "text",
3870
- text: ""
3871
- };
3872
- });
3873
- return {
3874
- id: crypto.randomUUID(),
3875
- role: "user",
3876
- content
3877
- };
3878
- }
3879
- function fromOpenAITool(msg) {
3880
- const content = typeof msg.content === "string" ? msg.content : msg.content.map((p) => p.text).join("");
3881
- return {
3882
- id: crypto.randomUUID(),
3883
- role: "tool",
3884
- content,
3885
- toolCallId: msg.tool_call_id
3886
- };
3887
- }
3888
- function fromOpenAI(data) {
3889
- switch (data.role) {
3890
- case "user": return fromOpenAIUser(data);
3891
- case "assistant": return fromOpenAIAssistant(data);
3892
- case "tool": return fromOpenAITool(data);
3893
- case "system": return {
3894
- id: crypto.randomUUID(),
3895
- role: "system",
3896
- content: typeof data.content === "string" ? data.content : ""
3897
- };
3898
- case "developer": return {
3899
- id: crypto.randomUUID(),
3900
- role: "developer",
3901
- content: typeof data.content === "string" ? data.content : ""
3902
- };
3903
- default: return {
3904
- id: crypto.randomUUID(),
3905
- role: "system",
3906
- content: ""
3907
- };
3908
- }
3909
- }
3910
- /**
3911
- * Converts between AG-UI message format and OpenAI **Chat Completions**
3912
- * message format (`ChatCompletionMessageParam`).
3913
- *
3914
- * This is a 1-to-1 mapping — each AG-UI message becomes exactly one
3915
- * `ChatCompletionMessageParam` and vice versa.
3916
- *
3917
- * AG-UI → OpenAI (toApi):
3918
- * - Strips `id` (OpenAI doesn't use message IDs)
3919
- * - Converts `toolCalls` → `tool_calls`
3920
- * - Converts `toolCallId` → `tool_call_id`
3921
- * - Converts multipart `content` arrays to OpenAI content format
3922
- *
3923
- * OpenAI → AG-UI (fromApi):
3924
- * - Generates `id` via `crypto.randomUUID()`
3925
- * - Converts `tool_calls` → `toolCalls`
3926
- * - Converts `tool_call_id` → `toolCallId`
3927
- */
3928
- const openAIMessageFormat = {
3929
- toApi(messages) {
3930
- return messages.map(toOpenAI);
3931
- },
3932
- fromApi(data) {
3933
- return data.map(fromOpenAI);
3934
- }
3935
- };
3936
- // src/stream/formats/vercel-ai-message-format.ts
3937
- const PROVIDER_EXECUTED_TOOLS_UNSUPPORTED_MESSAGE = "Vercel AI SDK provider-executed tools are not supported because AG-UI messages cannot preserve providerExecuted semantics.";
3938
- function isRecord(value) {
3939
- return value !== null && typeof value === "object" && !Array.isArray(value);
3940
- }
3941
- function isProviderExecuted(value) {
3942
- return isRecord(value) && value.providerExecuted === true;
3943
- }
3944
- function serialize(value) {
3945
- if (typeof value === "string") return value;
3946
- try {
3947
- return JSON.stringify(value) ?? String(value);
3948
- } catch {
3949
- return String(value);
3950
- }
3951
- }
3952
- function parseToolInput(value) {
3953
- try {
3954
- return JSON.parse(value);
3955
- } catch {
3956
- return value;
3957
- }
3958
- }
3959
- function dataUrl(mediaType, data) {
3960
- return `data:${mediaType};base64,${data}`;
3961
- }
3962
- function mediaTypeForPart(part, source) {
3963
- if (typeof source.mimeType === "string") return source.mimeType;
3964
- switch (part.type) {
3965
- case "image": return "image/*";
3966
- case "audio": return "audio/*";
3967
- case "video": return "video/*";
3968
- default: return "application/octet-stream";
3969
- }
3970
- }
3971
- function toUserParts(content) {
3972
- if (typeof content === "string") return [{
3973
- type: "text",
3974
- text: content
3975
- }];
3976
- if (!Array.isArray(content)) return [];
3977
- return content.flatMap((part) => {
3978
- if (!isRecord(part)) return [];
3979
- if (part.type === "text" && typeof part.text === "string") return [{
3980
- type: "text",
3981
- text: part.text
3982
- }];
3983
- if (part.type === "binary") {
3984
- const mediaType = typeof part.mimeType === "string" ? part.mimeType : "application/octet-stream";
3985
- const url = typeof part.url === "string" ? part.url : typeof part.data === "string" ? dataUrl(mediaType, part.data) : void 0;
3986
- if (!url) return [];
3987
- return [{
3988
- type: "file",
3989
- mediaType,
3990
- url,
3991
- ...typeof part.filename === "string" ? { filename: part.filename } : {}
3992
- }];
3993
- }
3994
- switch (part.type) {
3995
- case "image":
3996
- case "audio":
3997
- case "video":
3998
- case "document": {
3999
- if (!isRecord(part.source) || typeof part.source.value !== "string") return [];
4000
- const mediaType = mediaTypeForPart(part, part.source);
4001
- const url = part.source.type === "data" ? dataUrl(mediaType, part.source.value) : part.source.type === "url" ? part.source.value : void 0;
4002
- return url ? [{
4003
- type: "file",
4004
- mediaType,
4005
- url
4006
- }] : [];
4007
- }
4008
- default: return [];
4009
- }
4010
- });
4011
- }
4012
- function toToolPart(toolCall, result) {
4013
- if (isProviderExecuted(toolCall) || isProviderExecuted(result)) throw new Error(PROVIDER_EXECUTED_TOOLS_UNSUPPORTED_MESSAGE);
4014
- const input = parseToolInput(toolCall.function.arguments);
4015
- if (result?.error) return {
4016
- type: "dynamic-tool",
4017
- toolName: toolCall.function.name,
4018
- toolCallId: toolCall.id,
4019
- state: "output-error",
4020
- input,
4021
- errorText: result.error
4022
- };
4023
- if (result) return {
4024
- type: "dynamic-tool",
4025
- toolName: toolCall.function.name,
4026
- toolCallId: toolCall.id,
4027
- state: "output-available",
4028
- input,
4029
- output: result.content
4030
- };
4031
- return {
4032
- type: "dynamic-tool",
4033
- toolName: toolCall.function.name,
4034
- toolCallId: toolCall.id,
4035
- state: "input-available",
4036
- input
4037
- };
4038
- }
4039
- function toVercelMessages(messages) {
4040
- const toolResults = /* @__PURE__ */ new Map();
4041
- for (const message of messages) if (message.role === "tool") toolResults.set(message.toolCallId, message);
4042
- const result = [];
4043
- for (const message of messages) switch (message.role) {
4044
- case "user":
4045
- result.push({
4046
- id: message.id,
4047
- role: "user",
4048
- parts: toUserParts(message.content)
4049
- });
4050
- break;
4051
- case "assistant": {
4052
- const parts = [];
4053
- if (typeof message.content === "string" && message.content.length > 0) parts.push({
4054
- type: "text",
4055
- text: message.content
4056
- });
4057
- for (const toolCall of message.toolCalls ?? []) parts.push(toToolPart(toolCall, toolResults.get(toolCall.id)));
4058
- result.push({
4059
- id: message.id,
4060
- role: "assistant",
4061
- parts
4062
- });
4063
- break;
4064
- }
4065
- case "system":
4066
- case "developer": result.push({
4067
- id: message.id,
4068
- role: "system",
4069
- parts: [{
4070
- type: "text",
4071
- text: message.content
4072
- }]
4073
- });
4074
- }
4075
- return result;
4076
- }
4077
- function validUIMessage(value) {
4078
- return isRecord(value) && typeof value.id === "string" && (value.role === "system" || value.role === "user" || value.role === "assistant") && Array.isArray(value.parts);
4079
- }
4080
- function textFromParts(parts) {
4081
- return parts.filter((part) => isRecord(part) && part.type === "text" && typeof part.text === "string").map((part) => part.text).join("");
4082
- }
4083
- function binaryFromFilePart(part) {
4084
- if (part.type !== "file" || typeof part.mediaType !== "string" || typeof part.url !== "string") return;
4085
- const base64Prefix = `data:${part.mediaType};base64,`;
4086
- const source = part.url.startsWith(base64Prefix) ? { data: part.url.slice(base64Prefix.length) } : { url: part.url };
4087
- return {
4088
- type: "binary",
4089
- mimeType: part.mediaType,
4090
- ...source,
4091
- ...typeof part.filename === "string" ? { filename: part.filename } : {}
4092
- };
4093
- }
4094
- function fromVercelUser(message) {
4095
- const contentParts = [];
4096
- let hasFile = false;
4097
- for (const part of message.parts) {
4098
- if (!isRecord(part)) continue;
4099
- if (part.type === "text" && typeof part.text === "string") {
4100
- contentParts.push({
4101
- type: "text",
4102
- text: part.text
4103
- });
4104
- continue;
4105
- }
4106
- const binary = binaryFromFilePart(part);
4107
- if (binary) {
4108
- hasFile = true;
4109
- contentParts.push(binary);
4110
- }
4111
- }
4112
- return {
4113
- id: message.id,
4114
- role: "user",
4115
- content: hasFile ? contentParts : textFromParts(message.parts)
4116
- };
4117
- }
4118
- function toolName(part) {
4119
- if (part.type === "dynamic-tool") return typeof part.toolName === "string" && part.toolName.length > 0 ? part.toolName : void 0;
4120
- if (typeof part.type !== "string" || !part.type.startsWith("tool-")) return void 0;
4121
- return part.type.slice(5) || void 0;
4122
- }
4123
- function hasOwn(record, key) {
4124
- return Object.prototype.hasOwnProperty.call(record, key);
4125
- }
4126
- function toolResultFromPart(part) {
4127
- if (typeof part.toolCallId !== "string") return void 0;
4128
- if (part.state === "output-available" && hasOwn(part, "output")) return {
4129
- id: `tool-result-${part.toolCallId}`,
4130
- role: "tool",
4131
- toolCallId: part.toolCallId,
4132
- content: serialize(part.output)
4133
- };
4134
- if (part.state === "output-error" && typeof part.errorText === "string") return {
4135
- id: `tool-result-${part.toolCallId}`,
4136
- role: "tool",
4137
- toolCallId: part.toolCallId,
4138
- content: part.errorText,
4139
- error: part.errorText
4140
- };
4141
- if (part.state === "output-denied") {
4142
- const error = "Tool execution was denied";
4143
- return {
4144
- id: `tool-result-${part.toolCallId}`,
4145
- role: "tool",
4146
- toolCallId: part.toolCallId,
4147
- content: error,
4148
- error
4149
- };
4150
- }
4151
- }
4152
- function appendAssistantSegments(message, result) {
4153
- let segmentIndex = 0;
4154
- let segmentStarted = false;
4155
- let text = "";
4156
- let toolCalls = [];
4157
- let toolResults = [];
4158
- const hasStepMarkers = message.parts.some((part) => isRecord(part) && part.type === "step-start");
4159
- const hasBody = () => text.length > 0 || toolCalls.length > 0;
4160
- const flush = (force = false) => {
4161
- if (!force && !segmentStarted) return;
4162
- segmentIndex += 1;
4163
- result.push({
4164
- id: segmentIndex === 1 ? message.id : `${message.id}-segment-${segmentIndex}`,
4165
- role: "assistant",
4166
- ...text ? { content: text } : {},
4167
- ...toolCalls.length ? { toolCalls } : {}
4168
- });
4169
- result.push(...toolResults);
4170
- text = "";
4171
- toolCalls = [];
4172
- toolResults = [];
4173
- segmentStarted = false;
4174
- };
4175
- for (const value of message.parts) {
4176
- if (!isRecord(value)) continue;
4177
- if (value.type === "step-start") {
4178
- if (hasBody()) flush();
4179
- continue;
4180
- }
4181
- if (value.type === "text" && typeof value.text === "string") {
4182
- if (toolCalls.length > 0 || !hasStepMarkers && hasBody()) flush();
4183
- segmentStarted = true;
4184
- text += value.text;
4185
- continue;
4186
- }
4187
- const name = toolName(value);
4188
- if (!name || typeof value.toolCallId !== "string") continue;
4189
- if (value.providerExecuted === true) throw new Error(PROVIDER_EXECUTED_TOOLS_UNSUPPORTED_MESSAGE);
4190
- segmentStarted = true;
4191
- toolCalls.push({
4192
- id: value.toolCallId,
4193
- type: "function",
4194
- function: {
4195
- name,
4196
- arguments: hasOwn(value, "input") ? serialize(value.input) : ""
4197
- }
4198
- });
4199
- const toolResult = toolResultFromPart(value);
4200
- if (toolResult) toolResults.push(toolResult);
4201
- }
4202
- flush(segmentIndex === 0);
4203
- }
4204
- function fromVercelMessages(data) {
4205
- if (!Array.isArray(data)) return [];
4206
- const result = [];
4207
- for (const value of data) {
4208
- if (!validUIMessage(value)) continue;
4209
- const message = value;
4210
- if (message.role === "user") {
4211
- result.push(fromVercelUser(message));
4212
- continue;
4213
- }
4214
- const text = textFromParts(message.parts);
4215
- if (message.role === "system") {
4216
- result.push({
4217
- id: message.id,
4218
- role: "system",
4219
- content: text
4220
- });
4221
- continue;
4222
- }
4223
- appendAssistantSegments(message, result);
4224
- }
4225
- return result;
4226
- }
4227
- /**
4228
- * Converts messages between AG-UI and Vercel AI SDK v6 and v7 `UIMessage` format.
4229
- *
4230
- * AG-UI tool-result messages are folded into the matching assistant tool part,
4231
- * because `UIMessage` represents a tool invocation and its result as one part.
4232
- * Outbound tool calls use `dynamic-tool` parts because AG-UI messages do not
4233
- * carry the static tool schema needed to select a `tool-${name}` part. Inbound
4234
- * conversion accepts both dynamic and static tool parts.
4235
- *
4236
- * Vercel `UIMessage` has no developer role, so both AG-UI system and developer
4237
- * messages map to its system role.
4238
- *
4239
- * Provider-executed tools are rejected because the AG-UI message model has no
4240
- * execution-provenance field and therefore cannot preserve their requirement
4241
- * that results remain in the assistant message.
4242
- */
4243
- const vercelAIMessageFormat = {
4244
- toApi(messages) {
4245
- return toVercelMessages(messages);
4246
- },
4247
- fromApi(data) {
4248
- return fromVercelMessages(data);
4249
- }
4250
- };
4251
- // src/adapters/fetchLLM.ts
4252
- /**
4253
- * Generic HTTP-based LLM adapter. POSTs an AG-UI `RunAgentInput`-shaped body
4254
- * (`{ threadId, runId, messages, tools, context }`, messages in the chosen wire
4255
- * format) to `url` and returns the streaming `Response` for downstream processing.
4256
- */
4257
- function fetchLLM({ url, streamAdapter, messageFormat = identityMessageFormat, headers, fetch: customFetch, body }) {
4258
- const fetchImpl = customFetch ?? globalThis.fetch.bind(globalThis);
4259
- return {
4260
- send: ({ threadId, messages, signal }) => {
4261
- const runId = crypto.randomUUID();
4262
- return fetchImpl(url, {
4263
- method: "POST",
4264
- headers: {
4265
- "Content-Type": "application/json",
4266
- ...headers
4267
- },
4268
- body: JSON.stringify({
4269
- ...body,
4270
- tools: [],
4271
- context: [],
4272
- threadId,
4273
- runId,
4274
- messages: messageFormat.toApi(messages)
4275
- }),
4276
- signal
4277
- });
4278
- },
4279
- streamProtocol: streamAdapter
4280
- };
4281
- }
4282
- // src/adapters/restStorage.ts
4283
- /**
4284
- * Generic REST-based thread storage. Reproduces the conventions the removed
4285
- * `threadApiUrl` prop used, so an existing backend keeps working by swapping
4286
- * `threadApiUrl="/x"` for `storage={restStorage({ baseUrl: "/x" })}`.
4287
- *
4288
- * Only the `thread` channel is implemented. Pair with an `llm` adapter
4289
- * (e.g. `fetchLLM`).
4290
- */
4291
- function restStorage({ baseUrl, messageFormat = identityMessageFormat, headers, fetch: customFetch }) {
4292
- const fetchImpl = customFetch ?? globalThis.fetch.bind(globalThis);
4293
- const request = async (url, init) => {
4294
- const res = await fetchImpl(url, {
4295
- ...init,
4296
- headers: {
4297
- ...init?.body ? { "Content-Type": "application/json" } : {},
4298
- ...headers,
4299
- ...init?.headers
4300
- }
4301
- });
4302
- if (!res.ok) throw new Error(`restStorage: ${init?.method ?? "GET"} ${url} failed: ${res.status} ${res.statusText}`);
4303
- return res;
4304
- };
4305
- return { thread: {
4306
- async listThreads(cursor) {
4307
- const url = cursor ? `${baseUrl}/get?cursor=${cursor}` : `${baseUrl}/get`;
4308
- return (await request(url)).json();
4309
- },
4310
- async createThread(firstMessage) {
4311
- return (await request(`${baseUrl}/create`, {
4312
- method: "POST",
4313
- body: JSON.stringify({ messages: messageFormat.toApi([firstMessage]) })
4314
- })).json();
4315
- },
4316
- async getMessages(threadId) {
4317
- const raw = await (await request(`${baseUrl}/get/${threadId}`)).json();
4318
- return messageFormat.fromApi(raw);
4319
- },
4320
- async updateThread(thread) {
4321
- return (await request(`${baseUrl}/update/${thread.id}`, {
4322
- method: "PATCH",
4323
- body: JSON.stringify(thread)
4324
- })).json();
4325
- },
4326
- async deleteThread(id) {
4327
- await request(`${baseUrl}/delete/${id}`, { method: "DELETE" });
4328
- }
4329
- } };
4330
- }
4331
- export { ArtifactPollIntervalContext, ArtifactRenderersContext, ArtifactStorageContext, ArtifactStreamStore, ChatProvider, DetailedViewContext, EVE_INPUT_REQUESTED_EVENT, EventType, MessageContext, MessageProvider, OpenUICloudProvider, ThreadContextContext, agUIAdapter, artifactViewId, createInterpreterToolProvider, defineArtifactCategories, defineArtifactRenderer, eveAdapter, fetchLLM, getResponseErrorMessage, identityMessageFormat, langGraphAdapter, langGraphMessageFormat, lookupArtifactRenderer, lookupArtifactRendererByType, noteArtifactVersion, openAIAdapter, openAIConversationMessageFormat, openAIMessageFormat, openAIReadableStreamAdapter, openAIResponsesAdapter, pairToolActivity, parseArtifactViewId, partialJSONParse, processStreamedMessage, restStorage, useActiveDetailedView, useArtifactCategories, useArtifactList, useArtifactPollInterval, useArtifactRenderer, useArtifactRendererRegistry, useArtifactStorage, useArtifactStream, useDetailedView, useDetailedViewPortalTarget, useDetailedViewStore, useMessage, useOpenuiCloudStorage, useThread, useThreadContextStore, useThreadList, useToolActivities, vercelAIAdapter, vercelAIMessageFormat, watchArtifactStreams };
1
+ import{computed as e,defineComponent as t,getCurrentInstance as n,getCurrentScope as r,inject as i,onMounted as a,onScopeDispose as o,onUpdated as s,provide as c,shallowRef as l,ssrContextKey as u,toValue as d,watch as f,watchEffect as p}from"vue";import{observability as m}from"@openuidev/observability";import{createStore as h}from"zustand/vanilla";import{subscribeWithSelector as g}from"zustand/middleware";import{EventType as _}from"@ag-ui/core";const v=Symbol(`ArtifactStorageContext`),y=()=>i(v,null),b=2**31-1,ee=/* @__PURE__ */ new Set([`not-found`,`generation-failed`,`network-error`,`unauthorized`]),te=e=>{let t=e=>Array.isArray(e)?e.filter(e=>typeof e==`string`):[],{tools:n,scripts:r}=e??{},i={tools:t(n),scripts:t(r)};return i.tools.length>0||i.scripts.length>0?i:void 0},ne=e=>new Promise(t=>setTimeout(t,e)),re=e=>e.snapshot.error?.code===`not-found`,x=e=>e.pollers.size>0&&e.tag!==void 0&&e.snapshot.error?.code!==`unauthorized`,S=(e,t,n)=>({source:`artifact`,code:e,message:t,...n!==void 0&&{cause:n}});var ie=class{storage;entries=/* @__PURE__ */ new Map;watchers=/* @__PURE__ */ new Set;dueWhileHidden=/* @__PURE__ */ new Set;constructor(e){this.storage=e}watch(e){return this.watchers.add(e),()=>this.watchers.delete(e)}getSnapshot(e){return this.entry(e).snapshot}subscribe(e,t){let n=this.entry(e);return n.listeners.add(t),n.idleTimer&&=(clearTimeout(n.idleTimer),null),n.started||(n.started=!0,this.connect(e)),()=>{n.listeners.delete(t),n.listeners.size>0||!n.controller||(n.idleTimer=setTimeout(()=>{n.idleTimer=null,n.listeners.size>0||!n.controller||(n.controller.abort(),n.controller=null,n.started=!1)},0))}}poll(e,t){let n=this.entry(e),r=Symbol();return n.pollers.set(r,Math.max(t,3e3)),this.schedulePoll(e),()=>{n.pollers.delete(r),this.schedulePoll(e)}}noteVersion(e,t){if(!t)return;let n=this.entry(e);if(n.versions.has(t))return;let r=n.versions.size===0;n.versions.add(t),!r&&n.started&&(n.controller&&n.snapshot.isStreaming?n.stale=!0:this.connect(e))}retry(e){let t=this.entry(e);t.reconnects=0,t.started=!0,this.connect(e)}versionMismatch(e,t){let n=this.entry(e);if(t!==n.snapshot.version)return Promise.resolve(`rerun`);if(n.reread?.version===t)return n.reread.answer;let r=performance.now();if(!n.started||r-n.rereadAt<1e4)return Promise.resolve(`show`);n.rereadAt=r;let i,a=new Promise(e=>i=e);return n.reread={version:t,answer:a,settle:i},this.refresh(e),a}afterRead(e){let t=this.entry(e),n=t.reread;n&&!t.snapshot.isStreaming&&(t.reread=null,n.settle(t.snapshot.version===n.version?`show`:`rerun`))}refresh(e){let t=this.entry(e);t.started&&(t.controller&&t.snapshot.isStreaming?t.stale=!0:(t.reconnects=0,this.connect(e)))}awaits(e,t){if(!t)return!1;let n=this.entry(e);return n.started&&n.snapshot.program!==null&&n.versions.size>0&&!n.versions.has(t)}entry(e){let t=this.entries.get(e);return t||(t={snapshot:{id:e,program:null,isStreaming:!1,justUpdated:!1,error:null},listeners:/* @__PURE__ */ new Set,controller:null,started:!1,target:`program`,pending:``,replace:!1,settled:null,reconnects:0,versions:/* @__PURE__ */ new Set,stale:!1,idleTimer:null,reread:null,rereadAt:-1/0,pollers:/* @__PURE__ */ new Map,pollTimer:null,pollFailures:0,justUpdatedTimer:null},this.entries.set(e,t)),t}update(e,t){let n=this.entry(e),r=n.snapshot;n.snapshot={...r,...t},this.watchers.forEach(t=>t(e,r,n.snapshot)),n.listeners.forEach(e=>e())}async connect(e,t){let n=this.entry(e);n.started=!0,n.controller?.abort();let r=new AbortController;n.controller=r;let i=t!==void 0;i||this.update(e,{isStreaming:!0,error:null});let a=Date.now(),o=!1,s=!1,c;try{if(!this.storage.stream){o=!0,await this.load(e);return}for await(let i of this.storage.stream(e,{signal:r.signal,fetchLatest:t})){if(r.signal.aborted)return;if(i.type===`end`||i.type===`error`||i.type===`unchanged`){o=!0,this.onEvent(e,i);break}i.type===`reference`&&(s=!0),this.onEvent(e,i),n.reconnects=0}}catch(e){if(r.signal.aborted)return;c=e}finally{n.controller===r&&(n.controller=null)}if(!r.signal.aborted){if(o||i&&!s)n.pollFailures=o?0:n.pollFailures+1,this.schedulePoll(e);else if(Date.now()-a>=1e4&&(n.reconnects=0),n.reconnects<3){if(n.reconnects+=1,await ne(500*2**(n.reconnects-1)),n.controller)return;n.listeners.size>0?this.connect(e):n.started=!1}else this.update(e,{...this.endRead(n),isStreaming:!1,error:S(`network-error`,`Couldn't reach the artifact's storage.`,c)}),this.afterRead(e)}}endRead(e){let t=e.settled;return e.target=`program`,e.pending=``,e.version=void 0,e.settled=null,t}markUpdated(e){let t=this.entry(e);t.justUpdatedTimer&&clearTimeout(t.justUpdatedTimer),t.justUpdatedTimer=setTimeout(()=>{t.justUpdatedTimer=null,this.update(e,{justUpdated:!1})},1e4),this.update(e,{justUpdated:!0})}async load(e){try{let t=await this.storage.get(e);this.update(e,{type:t.type,title:t.title,program:typeof t.content==`string`?t.content:null,isStreaming:!1})}catch(t){this.update(e,{isStreaming:!1,error:S(`not-found`,t instanceof Error?t.message:`This artifact couldn't be loaded.`,t)})}this.afterRead(e)}schedulePoll(e){let t=this.entry(e);if(t.pollTimer&&clearTimeout(t.pollTimer),t.pollTimer=null,!x(t))return;let n=Math.min(...t.pollers.values()),r=Math.min(n*2**t.pollFailures,Math.max(n,3e5))*(.9+Math.random()*.2);t.pollTimer=setTimeout(()=>this.pollNow(e),Math.min(r,b)),t.pollFailures>0&&this.listenForVisible()}pollNow(e){let t=this.entry(e);t.pollTimer&&clearTimeout(t.pollTimer),t.pollTimer=null,x(t)&&!t.controller&&(typeof document<`u`&&document.hidden?(this.dueWhileHidden.add(e),this.listenForVisible()):this.connect(e,re(t)?``:t.tag))}listenForVisible(){typeof document<`u`&&document.addEventListener(`visibilitychange`,this.onVisible)}onVisible=()=>{if(document.hidden)return;document.removeEventListener(`visibilitychange`,this.onVisible);let e=new Set(this.dueWhileHidden);this.dueWhileHidden.clear();for(let[t,n]of this.entries)n.pollFailures!==0&&x(n)&&(n.pollFailures=0,e.add(t));e.forEach(e=>this.pollNow(e))};catchUp(e){let t=this.entry(e);t.stale&&(t.stale=!1,this.connect(e))}onEvent(e,t){let n=this.entry(e),r=n.snapshot;switch(t.type){case`reference`:{let{version:i,tag:a,is_owner:o,is_editable:s}=t.data??{};i&&n.versions.add(i),n.tag=a;let c=r.program,l=i!==r.version,u=i!==void 0&&i===n.version,d=c!==null&&l;n.version=i,u||(n.target=c===null||l?`program`:`pending`,n.pending=``,d&&(n.settled??={program:c,version:r.version})),n.replace=u||d,this.update(e,{type:t.data?.type??r.type,title:t.data?.title??r.title,isOwner:o??r.isOwner,isEditable:s??r.isEditable,isStreaming:r.isStreaming||l,step:void 0,error:null,...n.target===`program`&&{version:i,program:c??``}});return}case`unchanged`:this.afterRead(e);return;case`delta`:{let i=t.data?.text;if(typeof i!=`string`)return;let a=n.replace;n.replace=!1,n.target===`pending`?n.pending=(a?``:n.pending)+i:this.update(e,{program:(a?``:r.program??``)+i,step:void 0});return}case`step`:this.update(e,{step:te(t.data)});return;case`end`:{let t=n.target===`pending`?{program:n.pending,version:n.version}:{},r=this.endRead(n)!==null;this.update(e,{...t,isStreaming:!1,step:void 0}),r&&this.markUpdated(e),this.catchUp(e),this.afterRead(e);return}case`error`:{let r=t.data?.code,i=r&&ee.has(r)?r:`generation-failed`,a=i===`not-found`;a&&(n.started=!1),this.update(e,{...this.endRead(n),...a&&{program:null,version:void 0},isStreaming:!1,step:void 0,error:S(i,t.data?.message??`The artifact couldn't be generated.`)}),this.catchUp(e),this.afterRead(e)}}}};const C=/* @__PURE__ */ new WeakMap,w=e=>{let t=C.get(e);return t||(t=new ie(e),C.set(e,t)),t};function ae(e,t,n){C.get(e)?.noteVersion(t,n)}function oe(e,t){return w(e).watch(t)}const T={program:null,isStreaming:!1,justUpdated:!1,error:null};function se(t){let n=y(),r=l(null),i=e(()=>d(t)),a=e(()=>{let e=i.value,t=e.content!==void 0;return n&&!t&&e.id?w(n):null});return f([a,()=>i.value.id],([e,t],n,i)=>{!e||!t?r.value=null:(r.value=e.getSnapshot(t),i(e.subscribe(t,()=>{r.value=e.getSnapshot(t)})))},{immediate:!0}),f([a,()=>i.value.id,()=>i.value.version],([e,t,n])=>{e&&t&&e.noteVersion(t,n)},{immediate:!0,flush:`post`}),f([a,()=>i.value.id,()=>i.value.pollInterval],([e,t,n],r,i)=>{e&&t&&n&&i(e.poll(t,n))},{immediate:!0,flush:`post`}),e(()=>{let e=i.value,t=a.value,o=e.id;if(e.content!==void 0)return{...T,program:e.content};let s=r.value;if(!s)return o&&!n?{...T,error:S(`not-found`,`No artifact storage is configured.`)}:T;let c=t&&o?t.awaits(o,e.version):!1,l=t&&o?e=>t.versionMismatch(o,e):void 0,{id:u,...d}=s,f=s.error?.code===`network-error`&&t&&o?()=>t.retry(o):void 0;return{...d,isStreaming:d.isStreaming||c,retry:f,reportVersionMismatch:l}})}function ce(e){if(typeof e==`string`)return e;if(e&&typeof e==`object`&&`message`in e){let{message:t}=e;if(typeof t==`string`)return t}}function E(e){if(e&&typeof e==`object`&&`code`in e){let{code:t}=e;if(typeof t==`string`)return t}}async function le(e,t,n){let r=new Headers(t.headers);r.set(`Content-Type`,`application/json`);let i=await e(t.url,{method:`POST`,headers:r,body:JSON.stringify(n)}),a=null;try{a=await i.json()}catch{a=null}if(!i.ok||a?.error!==void 0&&a.error!==null){let e=ce(a?.error)??`Interpreter request failed: ${i.status}`;throw Object.assign(Error(e),{code:E(a?.error)})}return a?.result}function ue(e){return{async callTool({name:t,arguments:n={}}){let r=e.getInterpreter(),{id:i,version:a}=e.getRequest();if(!r)throw Error(`This artifact has no interpreter.`);if(!i)throw Error(`This artifact has no id yet.`);let o={id:i,...a!==void 0&&{version:a},name:t,arguments:n};e.onStart?.(t);try{let n=typeof r==`function`?await r(o):await le(e.fetch??globalThis.fetch.bind(globalThis),r,o);return e.onSettle?.(t,null),{content:[],structuredContent:n??null}}catch(n){let r=E(n);throw e.onSettle?.(t,ce(n)??`The data tool failed.`,{...r!==void 0&&{code:r},id:i,...a!==void 0&&{version:a}}),n}}}}async function*de(e){let t=e.getReader(),n=new TextDecoder,r=``,i,a=``,o=[],s=()=>{if(o.length===0&&!a)return null;let e={id:i,event:a||`message`,data:o.join(`
2
+ `)};return a=``,o=[],e};try{for(;;){let{done:e,value:c}=await t.read();if(e)break;r+=n.decode(c,{stream:!0});let l=r.search(/\r?\n/);for(;l!==-1;){let e=r.slice(0,l);if(r=r.slice(r[l]===`\r`?l+2:l+1),e===``){let e=s();e&&(yield e)}else if(!e.startsWith(`:`)){let t=e.indexOf(`:`),n=t===-1?e:e.slice(0,t),r=t===-1?``:e.slice(t+1);r.startsWith(` `)&&(r=r.slice(1)),n===`data`?o.push(r):n===`event`?a=r:n===`id`&&(i=r)}l=r.search(/\r?\n/)}}let e=s();e&&(yield e)}finally{t.releaseLock()}}function D(e){return e.has_more&&e.last_id?e.last_id:void 0}function fe(e,t){let n=t.replace(/\/+$/,``);return async(t,r)=>{let i=await e(`${n}${t}`,{...r,headers:{...r?.body?{"Content-Type":`application/json`}:{},...r?.headers}});if(!i.ok)throw Error(`OpenUI Cloud: ${r?.method??`GET`} ${t} failed: ${i.status} ${i.statusText}`);return i}}const pe=/* @__PURE__ */ new Set([`reference`,`delta`,`step`,`end`,`error`]);function me(e){try{return JSON.parse(e)}catch{return null}}function O(e){return{id:e.id,title:e.name??e.id,type:e.kind,threadId:e.conversation_id??``,updatedAt:(e.updated_at??e.created_at)*1e3,...e.pinned!==void 0&&{pinned:e.pinned},...e.is_owner!==void 0&&{isOwner:e.is_owner},...e.is_editable!==void 0&&{isEditable:e.is_editable},...e.shares!==void 0&&{shares:e.shares.map(he)},...e.version!==void 0&&{version:e.version}}}function he(e){return{type:e.type,id:e.id,access:e.access,createdBy:e.created_by,createdAt:e.created_at*1e3}}function ge({baseUrl:e,fetch:t,pageLimit:n=100,cacheQueryResults:r=!0}){let i=fe(t,e),a=e.replace(/\/+$/,``);return{async list(e){let t=new URLSearchParams;e?.name!==void 0&&e.name!==``&&t.set(`name`,e.name);for(let n of e?.type??[])t.append(`kind`,n);e?.pinned!==void 0&&t.set(`pinned`,String(e.pinned)),e?.isOwner!==void 0&&t.set(`is_owner`,String(e.isOwner)),e?.order!==void 0&&t.set(`order`,e.order),e?.cursor!==void 0&&t.set(`after`,e.cursor),t.set(`limit`,String(e?.limit??n));let r=await(await i(`/v1/artifacts?${t.toString()}`)).json();return{artifacts:r.data.map(O),nextCursor:D(r)}},async get(e){let t=await(await i(`/v1/artifacts/${encodeURIComponent(e)}`)).json();return{...O(t),content:t.content}},async update(e){let t={...e.content!==void 0&&{content:typeof e.content==`string`?e.content:JSON.stringify(e.content)},...e.title!==void 0&&{name:e.title}};return O(await(await i(`/v1/artifacts/${encodeURIComponent(e.id)}`,{method:`POST`,body:JSON.stringify(t)})).json())},async pin(e){return O(await(await i(`/v1/artifacts/${encodeURIComponent(e)}/pin`,{method:`POST`})).json())},async unpin(e){return O(await(await i(`/v1/artifacts/${encodeURIComponent(e)}/unpin`,{method:`POST`})).json())},async delete(e){await i(`/v1/artifacts/${encodeURIComponent(e)}`,{method:`DELETE`})},async share(e,t){return O(await(await i(`/v1/artifacts/${encodeURIComponent(e)}/share`,{method:`POST`,body:JSON.stringify({type:t.type,id:t.id,access:t.access})})).json())},async unshare(e,t){return O(await(await i(`/v1/artifacts/${encodeURIComponent(e)}/unshare`,{method:`POST`,body:JSON.stringify({type:t.type,id:t.id})})).json())},...r&&{async getQueryResults(e){return(await(await i(`/v1/artifacts/${encodeURIComponent(e)}/query-results`)).json()).results??{}},putQueryResult(e,t){i(`/v1/artifacts/${encodeURIComponent(e)}/query-results`,{method:`PUT`,body:JSON.stringify(t)}).catch(()=>{})}},async*stream(e,n){let r=n?.fetchLatest?`?${new URLSearchParams({fetch_latest:n.fetchLatest}).toString()}`:``,i=await t(`${a}/v1/artifacts/${encodeURIComponent(e)}/stream${r}`,{headers:{Accept:`text/event-stream`},signal:n?.signal});if(i.status===304)yield{type:`unchanged`};else if(i.status===404)yield{type:`error`,data:{code:`not-found`,message:`This artifact was deleted, or you can't see it.`}};else if(i.status===401||i.status===403)yield{type:`error`,data:{code:`unauthorized`,message:`Your session expired, or you can't see this artifact.`}};else{if(!i.ok||!i.body)throw Error(`OpenUI Cloud: stream ${e} failed: ${i.status} ${i.statusText}`);for await(let e of de(i.body))pe.has(e.event)&&(yield{type:e.event,data:me(e.data)})}}}}const _e=`x-thesys-frontend-token`;function ve({mintUrl:e,fetch:t,refreshSkewSeconds:n=60}){let r=t??globalThis.fetch.bind(globalThis),i=null,a=0,o=null,s=async()=>{let t=await r(e,{method:`POST`});if(!t.ok)throw Error(`frontend-token mint failed: ${t.status} ${t.statusText}`);let n=await t.json();return i=n.token,a=n.expires_at,n.token};return{async getToken(){let e=Date.now()/1e3;return i!==null&&e<a-n?i:(o===null&&(o=s().finally(()=>{o=null})),o)},invalidate(e){(e===void 0||e===i)&&(i=null,a=0)}}}function ye(e,t={}){if(typeof e==`string`)return ve({...t,mintUrl:e});let n=null;return{async getToken(){return n=await e(),n},invalidate(e){(e===void 0||e===n)&&(n=null)}}}function be(e,t){let n=t??globalThis.fetch.bind(globalThis);return async(t,r)=>{let i=await e.getToken(),a=new Headers(r?.headers);a.set(_e,i);let o=await n(t,{...r,headers:a});if(o.status===401){e.invalidate(i);let a=await e.getToken(),s=new Headers(r?.headers);s.set(_e,a),o=await n(t,{...r,headers:s})}return o}}function xe(e){switch(e.role){case`user`:return[Se(e)];case`assistant`:{let t=[];if(e.content&&t.push({role:`assistant`,content:e.content,type:`message`}),e.toolCalls?.length)for(let n of e.toolCalls)t.push({type:`function_call`,call_id:n.id,name:n.function.name,arguments:n.function.arguments});return t}case`tool`:return[{type:`function_call_output`,call_id:e.toolCallId,output:e.content}];case`system`:return[{role:`system`,content:e.content,type:`message`}];case`developer`:return[{role:`developer`,content:e.content,type:`message`}];default:return[]}}function Se(e){let t=e.content;return typeof t==`string`?{role:`user`,content:t,type:`message`}:{role:`user`,content:t?.map(e=>e.type===`text`?{type:`input_text`,text:e.text}:e.type===`binary`?{type:`input_image`,image_url:e.url??`data:${e.mimeType};base64,${e.data??``}`,detail:`auto`}:{type:`input_text`,text:``})??[],type:`message`}}function Ce(e){let t=[],n=null,r=[],i=()=>{n&&=(t.push(n),null),r.length>0&&(t.push(...r),r=[])};for(let a of e)switch(a.type){case`message`:{i();let e=a;if(e.role===`assistant`)n={id:e.id,role:`assistant`,content:k(e)||void 0};else if(e.role===`tool`)t.push({id:e.id,role:`tool`,content:k(e),toolCallId:``});else if(e.role===`user`)t.push(we(e));else{let n=e.role===`developer`?`developer`:`system`;t.push({id:e.id,role:n,content:k(e)})}break}case`function_call`:{let e=a;n||={id:crypto.randomUUID(),role:`assistant`},n={...n,toolCalls:[...n.toolCalls??[],{id:e.call_id,type:`function`,function:{name:e.name,arguments:e.arguments}}]};break}case`function_call_output`:{let e=a;r.push({id:e.id,role:`tool`,content:typeof e.output==`string`?e.output:JSON.stringify(e.output),toolCallId:e.call_id});break}case`mcp_call`:{n||={id:crypto.randomUUID(),role:`assistant`},n={...n,toolCalls:[...n.toolCalls??[],{id:a.id,type:`function`,function:{name:a.name,arguments:a.arguments}}]};let e=typeof a.error==`string`&&a.error.length>0?a.error:void 0;r.push({id:`${a.id}-output`,role:`tool`,content:a.output??``,toolCallId:a.id,...e?{error:e}:{}});break}}return i(),t}function k(e){return e.content.map(e=>{switch(e.type){case`output_text`:case`input_text`:case`text`:case`summary_text`:case`reasoning_text`:return e.text;case`refusal`:return`[Refusal]: ${e.refusal}`;default:return``}}).filter(Boolean).join(``)}function we(e){if(!e.content.some(e=>e.type===`input_image`||e.type===`input_file`))return{id:e.id,role:`user`,content:k(e)};let t=e.content.map(e=>e.type===`input_text`||e.type===`text`?{type:`text`,text:e.text}:e.type===`input_image`&&e.image_url?{type:`binary`,url:e.image_url,mimeType:`image/*`}:{type:`text`,text:``});return{id:e.id,role:`user`,content:t}}const Te={toApi(e){return e.flatMap(xe)},fromApi(e){return Ce(e)}};function Ee(e){switch(e.type){case`message`:{let t=e.content,n=Array.isArray(t)?t:[{type:e.role===`assistant`?`output_text`:`input_text`,text:typeof t==`string`?t:``}];return{id:e.id,type:`message`,role:e.role??`user`,status:e.status??`completed`,content:n}}case`function_call`:return typeof e.call_id!=`string`||typeof e.name!=`string`?null:{id:e.id,type:`function_call`,call_id:e.call_id,name:e.name,arguments:typeof e.arguments==`string`?e.arguments:JSON.stringify(e.arguments??{})};case`function_call_output`:return typeof e.call_id!=`string`||e.output===void 0?null:{id:e.id,type:`function_call_output`,call_id:e.call_id,output:e.output};default:return null}}function De(e){let t=e.map(Ee).filter(e=>e!==null);return Te.fromApi(t)}function A(e){return{id:e.id,title:e.title??`New conversation`,createdAt:e.created_at*1e3}}function Oe(e){let t=e.content,n=``;if(typeof t==`string`)n=t;else if(Array.isArray(t)){for(let e of t)if(e.type===`text`&&typeof e.text==`string`&&e.text.trim()!==``){n=e.text;break}}return n=n.trim(),(n===``?`New conversation`:n).slice(0,60)}function ke({baseUrl:e,fetch:t,pageLimit:n=100}){let r=fe(t,e);return{async listThreads(e){let t=new URLSearchParams({limit:String(n)});e!==void 0&&t.set(`after`,e);let i=await(await r(`/v1/conversations?${t.toString()}`)).json();return{threads:i.data.map(A),nextCursor:D(i)}},async createThread(e){return A(await(await r(`/v1/conversations`,{method:`POST`,body:JSON.stringify({title:Oe(e)})})).json())},async getMessages(e){let t=[],i;for(let a=0;a<50;a++){let a=new URLSearchParams({order:`asc`,limit:String(n)});i!==void 0&&a.set(`after`,i);let o=await(await r(`/v1/conversations/${encodeURIComponent(e)}/items?${a.toString()}`)).json();if(t.push(...o.data),i=D(o),i===void 0)break}return De(t)},async updateThread(e){return A(await(await r(`/v1/conversations/${encodeURIComponent(e.id)}`,{method:`POST`,body:JSON.stringify({title:e.title})})).json())},async deleteThread(e){await r(`/v1/conversations/${encodeURIComponent(e)}`,{method:`DELETE`})}}}function j(t){let n,r;return e(()=>{let e=d(t),i=[e.apiBaseUrl,e.token,e.fetch,e.refreshSkewSeconds,e.cacheQueryResults,e.features?.artifact??!0];return(!n||i.some((e,t)=>!Object.is(e,n[t])))&&(r=Ae(e),n=i),r})}function Ae(e){let t=be(ye(e.token,{fetch:e.fetch,refreshSkewSeconds:e.refreshSkewSeconds}),e.fetch),n=e.features?.artifact??!0,r=e.apiBaseUrl??`https://api.thesys.dev`,i={thread:ke({baseUrl:r,fetch:t})};return n&&(i.artifact=ge({baseUrl:r,fetch:t,cacheQueryResults:e.cacheQueryResults})),i}const M=Symbol(`ArtifactPollIntervalContext`),je=()=>d(i(M,void 0)),Me=t({name:`OpenUICloudProvider`,props:{apiBaseUrl:{type:String,default:void 0},token:{type:[String,Function],required:!0},cacheQueryResults:{type:Boolean,default:void 0},fetch:{type:Function,default:void 0},refreshSkewSeconds:{type:Number,default:void 0},pollInterval:{type:[Number,Boolean],default:void 0}},setup(t,{slots:n}){let r=()=>{let e=t.token;return typeof e==`string`?Promise.resolve(e):e()},i=j(()=>({apiBaseUrl:t.apiBaseUrl,token:typeof t.token==`string`?t.token:r,cacheQueryResults:t.cacheQueryResults,fetch:t.fetch,refreshSkewSeconds:t.refreshSkewSeconds})),a=e(()=>i.value.artifact??null);return c(v,a.value),c(M,()=>t.pollInterval),()=>n.default?.()??null}});function N(t,a){if(!r())throw Error(`useStore must be used within a Vue setup or effect scope`);if(n()&&i(u,null)!==null)return e(()=>a(t.getInitialState()));let s=l(t.getState()),c=l();p(()=>{c.value=a(s.value)},{flush:`sync`});let d=t.subscribe(e=>{s.value=e});return s.value=t.getState(),o(d),e(()=>c.value)}function Ne(e){let t;return n=>{let r=e(n),i=Object.keys(r);return t&&i.length===Object.keys(t).length&&i.every(e=>Object.prototype.hasOwnProperty.call(t,e)&&Object.is(t[e],r[e]))?t:(t=r,r)}}const P=Symbol(`DetailedViewContext`),F=()=>{let e=i(P,null);if(!e)throw Error(`useDetailedViewStore must be used within a <ChatProvider>`);return e};function Pe(){let t=F(),n=N(t,e=>e.activeDetailedViewId);return{activeDetailedViewId:n,isDetailedViewActive:e(()=>n.value!==null),closeDetailedView:()=>{t.getState().activeDetailedViewId!==null&&t.getState().setActiveDetailedView(null)}}}const I=Symbol(`ThreadContextContext`),Fe=()=>{let e=i(I,null);if(!e)throw Error(`useThreadContextStore must be used within a <ChatProvider>`);return e};function Ie(t){let n=N(Fe(),e=>e.artifacts),r;return e(()=>{let e=d(t)?.type?.join(` `),i=n.value;if(r&&r.artifacts===i&&r.typeKey===e)return r.value;if(e===void 0)return r={artifacts:i,typeKey:e,value:i},i;let a=new Set(e.split(` `)),o={};for(let[e,t]of Object.entries(i)){let n=t[t.length-1];n&&a.has(n.type)&&(o[e]=t)}return r={artifacts:i,typeKey:e,value:o},o})}const Le=()=>typeof process<`u`&&process.env?.NODE_ENV!==`production`;function Re(e){let t=/* @__PURE__ */ new Map,n=/* @__PURE__ */ new Map;for(let r of e){let e=Array.isArray(r.toolName)?r.toolName:[r.toolName];for(let n of e)t.has(n)?Le()&&console.warn(`[OpenUI] Artifact renderer for toolName "${n}" was ignored (already registered earlier in the array).`):t.set(n,r);n.has(r.type)?Le()&&console.warn(`[OpenUI] Artifact renderer for type "${r.type}" was ignored for type-based lookup (already registered earlier in the array).`):n.set(r.type,r)}return{byToolName:t,byType:n}}function ze(e,t){return e.byToolName.get(t)??null}function Be(e,t){return e.byType.get(t)??null}const L=Symbol(`ArtifactRenderersContext`),R=()=>i(L,null);function Ve(t){let n=R();return e(()=>n?ze(n,d(t)):null)}function He(e){let t=F();return{isActive:N(t,t=>t.activeDetailedViewId===d(e)),open:()=>t.getState().setActiveDetailedView(d(e)),close:()=>{t.getState().activeDetailedViewId===d(e)&&t.getState().setActiveDetailedView(null)},toggle:()=>{let n=d(e);t.getState().setActiveDetailedView(t.getState().activeDetailedViewId===n?null:n)}}}function Ue(){let e=F();return{node:N(e,e=>e._detailedViewPanelNode),setNode:t=>e.getState()._setDetailedViewPanelNode(t)}}const z=Symbol(`MessageContext`);function We(){let e=i(z,null);if(!e)throw Error(`useMessage must be used within a MessageProvider`);return e}const Ge=t({name:`OpenUIMessageProvider`,props:{message:{type:Object,required:!0}},setup(e,{slots:t}){return c(z,{get message(){return e.message}}),()=>t.default?.()}}),B=Symbol(`ChatContext`),V=()=>{let e=i(B,null);if(!e)throw Error(`useChatStore must be used within a <ChatProvider>`);return e},H=e=>({messages:e.messages,isRunning:e.isRunning,isLoadingMessages:e.isLoadingMessages,threadError:e.threadError,executingToolCallIds:e.executingToolCallIds,processMessage:e.processMessage,appendMessages:e.appendMessages,updateMessage:e.updateMessage,setMessages:e.setMessages,deleteMessage:e.deleteMessage,cancelMessage:e.cancelMessage}),U=e=>({threads:e.threads,isLoadingThreads:e.isLoadingThreads,threadListError:e.threadListError,selectedThreadId:e.selectedThreadId,hasMoreThreads:e.hasMoreThreads,loadThreads:e.loadThreads,loadMoreThreads:e.loadMoreThreads,switchToNewThread:e.switchToNewThread,createThread:e.createThread,selectThread:e.selectThread,updateThread:e.updateThread,deleteThread:e.deleteThread});function W(e){let t=V();return e?N(t,t=>e(H(t))):N(t,Ne(H))}function Ke(e){let t=V();return e?N(t,t=>e(U(t))):N(t,Ne(U))}const qe=()=>typeof process<`u`&&process.env?.NODE_ENV!==`production`;function Je(e){let t=[],n=!1,r=!1;for(let i=0;i<e.length;i++){let a=e[i];n?r?r=!1:a===`\\`?r=!0:a===`"`&&(n=!1):a===`"`?n=!0:a===`{`?t.push(`}`):a===`[`?t.push(`]`):(a===`}`||a===`]`)&&t.pop()}let i=e;n&&(r&&(i=i.slice(0,-1)),i+=`"`),i=i.replace(/(?:,\s*)?"(?:[^"\\]|\\.)*"\s*:\s*$/,``),i=i.replace(/,\s*$/,``);for(let e=t.length-1;e>=0;e--)i+=t[e];return i}function G(e){if(!e)return{};try{return JSON.parse(e)}catch{}try{return JSON.parse(Je(e))}catch{return{}}}let K=!1;function Ye(e){if(e&&typeof e==`object`&&`_title`in e){let t=e._title;if(typeof t==`string`)return qe()&&!K&&(K=!0,console.warn("[OpenUI] The `_title` tool-arg key is deprecated and will be removed; the renderer now exposes a typed `statusMessage` on ToolActivity instead.")),t}}function Xe(e,t,n=/* @__PURE__ */ new Set){let r=/* @__PURE__ */ new Map,i=/* @__PURE__ */ new Set;for(let e of t)if(e.role===`tool`){let t=e;t.toolCallId&&r.set(t.toolCallId,t)}else if(e.role===`assistant`)for(let t of e.toolCalls??[])i.add(t.id);let a=(e.toolCalls??[]).map(e=>{let t=r.get(e.id)??null,i=G(e.function.arguments),a=Ye(i),o={id:e.id,toolName:e.function.name,toolCall:e,statusMessage:a};return t?t.error?{...o,status:`error`,toolMessage:t,input:i,result:t.content,isError:!0,errorText:t.error}:{...o,status:`complete`,toolMessage:t,input:i,result:t.content,isError:!1}:n.has(e.id)?{...o,status:`executing`,toolMessage:null,input:i,isError:!1}:{...o,status:`streaming`,toolMessage:null,input:i,isError:!1}}),o=t.findIndex(t=>t.id===e.id);if(o!==-1)for(let e=o+1;e<t.length;e++){let n=t[e];if(!n||n.role!==`tool`)break;let r=n;if(!r.toolCallId||i.has(r.toolCallId))continue;let o={id:r.toolCallId,type:`function`,function:{name:``,arguments:``}},s={id:r.id,toolName:``,toolCall:o};a.push(r.error?{...s,status:`error`,toolMessage:r,input:{},result:r.content,isError:!0,errorText:r.error}:{...s,status:`complete`,toolMessage:r,input:{},result:r.content,isError:!1})}return a}function Ze(t,n){let r=W(e=>e.executingToolCallIds),i;return e(()=>{let e=d(t),a=d(n),o=(e.toolCalls??[]).map(e=>`${e.id}:${e.function.arguments.length}`).join(`|`),s=a.filter(e=>e.role===`tool`).map(e=>`${e.toolCallId}:${e.content?.length??0}:${+!!e.error}`).join(`|`),c=r.value;return i&&i.id===e.id&&i.args===o&&i.result===s&&i.executing===c||(i={id:e.id,args:o,result:s,executing:c,value:Xe(e,a,c)}),i.value})}function Qe(e){let t=[],n=/* @__PURE__ */ new Set;return{artifactRenderers:t,artifactCategories:e.map(e=>{let r=[],i=/* @__PURE__ */ new Set;for(let a of e.renderers)n.has(a)||(n.add(a),t.push(a)),i.has(a.type)||(i.add(a.type),r.push(a.type));return{name:e.name,filter:{type:r},icon:e.icon}})}}const $e=Symbol(`ArtifactCategoriesContext`),et=()=>i($e,e(()=>[]));function tt(e){return e}function nt(e,t){return`${e}:${t}`}function rt(e){let t=e.lastIndexOf(`:`);if(t<=0)return null;let n=e.slice(t+1);return/^\d+$/.test(n)?{id:e.slice(0,t),version:Number(n)}:null}function it(){let e=[],t=/* @__PURE__ */ new Map;return{thread:{async listThreads(){return{threads:e}},async createThread(n){let r={id:crypto.randomUUID(),title:typeof n.content==`string`&&n.content.slice(0,40)||`New thread`,createdAt:(/* @__PURE__ */ new Date()).toISOString()};return e=[r,...e],t.set(r.id,[{...n,id:n.id??crypto.randomUUID()}]),r},async getMessages(e){return t.get(e)??[]},async updateThread(t){return e=e.map(e=>e.id===t.id?t:e),t},async deleteThread(n){e=e.filter(e=>e.id!==n),t.delete(n)}}}}function at(e,t,n,r){let i=!1,a=Object.values(e);for(let e=0;e<a.length;e++){let o=a[e];if(!o)continue;let s=o[o.length-1];if(!s)continue;let c=nt(s.id,s.version);n.has(c)||(n.add(c),t&&!i&&(r.getState().setActiveDetailedView(c),i=!0))}return i}function ot(e,t,n,r){let i={current:!1},c={current:/* @__PURE__ */ new Set},l,u,f=()=>{let a=d(e);if(a===l||(u?.(),u=void 0,l=a,!l))return;let o=t.subscribe(e=>e.selectedThreadId,()=>{c.current.clear(),i.current=!1}),s=t.subscribe(e=>e.isRunning,e=>{e&&(i.current=!1)}),f=n.subscribe(e=>e.artifacts,e=>{at(e,t.getState().isRunning&&!i.current,c.current,r)&&(i.current=!0)},{fireImmediately:!0});u=()=>{o(),s(),f()}};a(f),s(f),o(()=>u?.())}async function q(e){try{let t=await e.clone().json(),n=typeof t.error==`string`?t.error:typeof t.error?.message==`string`?t.error.message:typeof t.message==`string`?t.message:null;if(n?.trim())return n}catch{}return`Request failed: ${e.status} ${e.statusText}`.trim()}const J={toApi:e=>e,fromApi:e=>e};async function*Y(e){let t=e.body?.getReader();if(!t)throw Error(`No response body`);let n=new TextDecoder,r=``;for(;;){let{done:e,value:i}=await t.read();if(e)break;r+=n.decode(i,{stream:!0});let a=r.split(`
3
+ `);r=a.pop()??``;for(let e of a)e.trim()&&(yield e)}r.trim()&&(yield r)}const st=()=>({async*parse(e){for await(let t of Y(e)){if(!t.startsWith(`data: `))continue;let e=t.slice(6).trim();if(e&&e!==`[DONE]`)try{yield JSON.parse(e)}catch(e){console.error(`Failed to parse SSE event`,e)}}}}),ct=`eve.input.requested`,lt=/* @__PURE__ */ new Set([`session.completed`,`session.failed`,`session.waiting`]),ut=(e={})=>({async*parse(t){let n=crypto.randomUUID(),r=/* @__PURE__ */ new Set,i=!1,a=()=>i?[]:(i=!0,[{type:_.TEXT_MESSAGE_START,messageId:n,role:`assistant`}]);for await(let i of Y(t)){let t;try{t=JSON.parse(i)}catch(e){console.error(`Failed to parse Eve stream event`,e);continue}if(e.onEvent?.(t),t.type===`actions.requested`)for(let e of t.data.actions){if(e.kind!==`tool-call`)continue;yield*a(),yield{type:_.TOOL_CALL_START,toolCallId:e.callId,toolCallName:e.toolName,parentMessageId:n};let t=JSON.stringify(e.input??{});t&&t!==`{}`&&(yield{type:_.TOOL_CALL_ARGS,toolCallId:e.callId,delta:t}),yield{type:_.TOOL_CALL_END,toolCallId:e.callId}}else if(t.type===`action.result`){let{result:e,status:n,error:r}=t.data;if(e.kind!==`tool-result`)continue;let i=n===`completed`?typeof e.output==`string`?e.output:JSON.stringify(e.output??null):JSON.stringify({error:r?.message??`tool ${n}`});yield{type:_.TOOL_CALL_RESULT,messageId:crypto.randomUUID(),toolCallId:e.callId,content:i,role:`tool`}}else if(t.type===`message.appended`){let{messageDelta:e,stepIndex:i}=t.data;if(!e)continue;r.add(i),yield*a(),yield{type:_.TEXT_MESSAGE_CONTENT,messageId:n,delta:e}}else if(t.type===`message.completed`){let{message:e,stepIndex:i}=t.data;if(!e||r.has(i))continue;yield*a(),yield{type:_.TEXT_MESSAGE_CONTENT,messageId:n,delta:e}}else t.type===`input.requested`?yield{type:_.CUSTOM,name:ct,value:t.data.requests}:(t.type===`turn.failed`||t.type===`session.failed`)&&(yield{type:_.RUN_ERROR,message:t.data.message});if(lt.has(t.type))break}i&&(yield{type:_.TEXT_MESSAGE_END,messageId:n})}}),dt=e=>({async*parse(t){let n=t.body?.getReader();if(!n)throw Error(`No response body`);let r=new TextDecoder,i=crypto.randomUUID(),a=null,o,s=/* @__PURE__ */ new Map,c=/* @__PURE__ */ new Set,l=/* @__PURE__ */ new Set,u=/* @__PURE__ */ new Set,d=/* @__PURE__ */ new Set,f=0,p=!1,m=!1,h=``;for(;;){let{done:t,value:g}=await n.read();h+=t?r.decode():r.decode(g,{stream:!0});let v=h.split(`
4332
4
 
4333
- //# sourceMappingURL=index.mjs.map
5
+ `);h=t?``:v.pop()??``;for(let t of v){let n=t.trim();if(!n)continue;let{event:r,data:h}=ft(n);if(!h)continue;let g;try{g=JSON.parse(h)}catch(e){console.error(`Failed to parse LangGraph SSE data`,e);continue}switch(r){case`metadata`:break;case`messages`:{let e=g,t=Array.isArray(e)?e[0]:e,n=Array.isArray(e)?e[1]:void 0;if(gt(t)){l.delete(t.tool_call_id)&&(yield{type:_.TOOL_CALL_END,toolCallId:t.tool_call_id}),p&&a&&(yield{type:_.TEXT_MESSAGE_END,messageId:a}),p=!1,a=null,m=!1,o=void 0,i=crypto.randomUUID(),s.clear();let e=mt(t.content);yield{type:_.TOOL_CALL_RESULT,messageId:t.id??`tool-result-${t.tool_call_id}`,toolCallId:t.tool_call_id,content:e,role:`tool`,...t.status===`error`?{isError:!0,error:e}:{}};break}if(!ht(t))break;let r=n?.langgraph_step,h=r!==void 0&&o!==void 0&&r!==o,v=t.id??(r===void 0?i:`langgraph-step-${r}`),y=pt(t.content),b=!p||v!==a||h||!!y&&m&&p;if(b&&d.has(v)&&(v=`${v}#${++f}`),b&&(p&&a&&(yield{type:_.TEXT_MESSAGE_END,messageId:a}),a=v,d.add(v),o=r,m=!1,s.clear(),yield{type:_.TEXT_MESSAGE_START,messageId:a,role:`assistant`},p=!0),y&&(yield{type:_.TEXT_MESSAGE_CONTENT,messageId:a,delta:y}),t.tool_call_chunks)for(let e of t.tool_call_chunks){let t=e.index??0;e.id&&s.set(t,e.id);let n=e.id??s.get(t);n&&!c.has(n)&&(c.add(n),l.add(n),m=!0,yield{type:_.TOOL_CALL_START,toolCallId:n,toolCallName:e.name||``}),e.args&&n&&(u.add(n),yield{type:_.TOOL_CALL_ARGS,toolCallId:n,delta:e.args})}if(t.tool_call_chunks===void 0&&t.tool_calls&&t.tool_calls.length>0)for(let e=0;e<t.tool_calls.length;e++){let n=t.tool_calls[e];if(!n)continue;let r=n.id||crypto.randomUUID();if(c.has(r)||(c.add(r),l.add(r),m=!0,yield{type:_.TOOL_CALL_START,toolCallId:r,toolCallName:n.name}),!u.has(r)){let e=typeof n.args==`string`?n.args:JSON.stringify(n.args);u.add(r),yield{type:_.TOOL_CALL_ARGS,toolCallId:r,delta:e}}l.delete(r)&&(yield{type:_.TOOL_CALL_END,toolCallId:r})}break}case`updates`:{let t=g;`__interrupt__`in t&&e?.onInterrupt&&e.onInterrupt(t.__interrupt__);break}case`error`:{let e=g;yield{type:_.RUN_ERROR,message:e.message||e.error||`Unknown error`,code:e.error??void 0};break}case`end`:if(p){for(let e of l)yield{type:_.TOOL_CALL_END,toolCallId:e};l.clear(),yield{type:_.TEXT_MESSAGE_END,messageId:a},p=!1}}}if(t)break}if(p){for(let e of l)yield{type:_.TOOL_CALL_END,toolCallId:e};l.clear(),yield{type:_.TEXT_MESSAGE_END,messageId:a}}}});function ft(e){let t=``,n=[];for(let r of e.split(`
6
+ `))r.startsWith(`event:`)?t=r.slice(6).trim():r.startsWith(`data:`)&&n.push(r.slice(5).trim());return{event:t,data:n.join(`
7
+ `)}}function pt(e){return typeof e==`string`?e:e.filter(e=>e.type===`text`&&e.text).map(e=>e.text).join(``)}function mt(e){return typeof e==`string`?e:JSON.stringify(e)}function ht(e){return e.type===`ai`||e.type===`AIMessage`||e.type===`AIMessageChunk`}function gt(e){return e.type===`tool`||e.type===`ToolMessage`||e.type===`ToolMessageChunk`}const _t=()=>({async*parse(e){let t=crypto.randomUUID(),n={},r=!1;for await(let i of Y(e)){if(!i.startsWith(`data: `))continue;let e=i.slice(6).trim();if(e&&e!==`[DONE]`)try{let i=JSON.parse(e).choices?.[0],a=i?.delta;if(!a)continue;if(!r&&(a.content||a.role)&&(yield{type:_.TEXT_MESSAGE_START,messageId:t,role:`assistant`},r=!0),a.content&&(yield{type:_.TEXT_MESSAGE_CONTENT,messageId:t,delta:a.content}),a.tool_calls)for(let e of a.tool_calls){let t=e.index;if(e.id&&(n[t]=e.id,yield{type:_.TOOL_CALL_START,toolCallId:e.id,toolCallName:e.function?.name||``}),e.function?.arguments){let r=n[t];r&&(yield{type:_.TOOL_CALL_ARGS,toolCallId:r,delta:e.function.arguments})}}if(i?.finish_reason===`stop`)yield{type:_.TEXT_MESSAGE_END,messageId:t};else if(i?.finish_reason===`tool_calls`)for(let e of Object.values(n))yield{type:_.TOOL_CALL_END,toolCallId:e}}catch(e){console.error(`Failed to parse OpenAI SSE event`,e)}}}}),vt=()=>({async*parse(e){let t=crypto.randomUUID(),n={},r=!1;for await(let i of Y(e)){let e=i.trim();if(e)try{let i=JSON.parse(e).choices?.[0],a=i?.delta;if(!a)continue;if(!r&&(a.content||a.role)&&(yield{type:_.TEXT_MESSAGE_START,messageId:t,role:`assistant`},r=!0),a.content&&(yield{type:_.TEXT_MESSAGE_CONTENT,messageId:t,delta:a.content}),a.tool_calls)for(let e of a.tool_calls){let t=e.index;if(e.id&&(n[t]=e.id,yield{type:_.TOOL_CALL_START,toolCallId:e.id,toolCallName:e.function?.name||``}),e.function?.arguments){let r=n[t];r&&(yield{type:_.TOOL_CALL_ARGS,toolCallId:r,delta:e.function.arguments})}}if(i?.finish_reason===`stop`)yield{type:_.TEXT_MESSAGE_END,messageId:t};else if(i?.finish_reason===`tool_calls`)for(let e of Object.values(n))yield{type:_.TOOL_CALL_END,toolCallId:e}}catch(e){console.error(`Failed to parse OpenAI NDJSON chunk`,e)}}}}),X=e=>typeof e==`string`?e:e==null?``:JSON.stringify(e),yt=()=>({async*parse(e){let t=e.body?.getReader();if(!t)throw Error(`No response body`);let n=new TextDecoder,r={},i=null,a=``;for(;;){let{done:e,value:o}=await t.read();a+=e?n.decode():n.decode(o,{stream:!0});let s=a.split(`
8
+ `);a=e?``:s.pop()??``;for(let e of s){if(!e.startsWith(`data: `))continue;let t=e.slice(6).trim();if(t&&t!==`[DONE]`)try{let e=JSON.parse(t);switch(e.type){case`response.output_item.added`:{let t=e.item;t.type===`message`&&t.role===`assistant`?(i=t.id,yield{type:_.TEXT_MESSAGE_START,messageId:t.id,role:`assistant`}):t.type===`function_call`?(r[t.id??t.call_id]=t.call_id,yield{type:_.TOOL_CALL_START,toolCallId:t.call_id,toolCallName:t.name}):t.type===`function_call_output`?yield{type:_.TOOL_CALL_RESULT,messageId:t.id,toolCallId:t.call_id,content:X(t.output)}:t.type===`web_search_call`?yield{type:_.TOOL_CALL_START,toolCallId:t.id,toolCallName:`web_search`}:t.type===`mcp_call`?yield{type:_.TOOL_CALL_START,toolCallId:t.id,toolCallName:t.name}:t.type===`mcp_list_tools`&&(yield{type:_.TOOL_CALL_START,toolCallId:t.id,toolCallName:`mcp_list_tools`},yield{type:_.TOOL_CALL_ARGS,toolCallId:t.id,delta:JSON.stringify({server_label:t.server_label})},yield{type:_.TOOL_CALL_END,toolCallId:t.id});break}case`response.output_text.delta`:e.item_id!==i&&(i=e.item_id,yield{type:_.TEXT_MESSAGE_START,messageId:e.item_id,role:`assistant`}),yield{type:_.TEXT_MESSAGE_CONTENT,messageId:e.item_id,delta:e.delta};break;case`response.output_text.done`:yield{type:_.TEXT_MESSAGE_END,messageId:e.item_id};break;case`response.function_call_arguments.delta`:{let t=r[e.item_id]??e.item_id;yield{type:_.TOOL_CALL_ARGS,toolCallId:t,delta:e.delta};break}case`response.function_call_arguments.done`:{let t=r[e.item_id]??e.item_id;yield{type:_.TOOL_CALL_END,toolCallId:t};break}case`response.mcp_call_arguments.delta`:yield{type:_.TOOL_CALL_ARGS,toolCallId:e.item_id,delta:e.delta};break;case`response.mcp_call_arguments.done`:yield{type:_.TOOL_CALL_END,toolCallId:e.item_id};break;case`response.output_item.done`:{if(e.item.type===`mcp_call`){let t=e.item,n=typeof t.error==`string`&&t.error.length>0?t.error:void 0;yield{type:_.TOOL_CALL_RESULT,messageId:t.id,toolCallId:t.id,content:X(t.output),...n?{isError:!0,error:n}:{}};break}if(e.item.type===`mcp_list_tools`){let t=e.item,n=t.tools.map(e=>e.name),r=typeof t.error==`string`&&t.error.length>0?t.error:void 0;yield{type:_.TOOL_CALL_RESULT,messageId:t.id,toolCallId:t.id,content:JSON.stringify({server_label:t.server_label,tool_count:n.length,tools:n}),...r?{isError:!0,error:r}:{}};break}let t=e.item;if(t.type!==`web_search_call`)break;let n=t.id??`web_search_call`;t.action&&typeof t.action==`object`&&(yield{type:_.TOOL_CALL_ARGS,toolCallId:n,delta:JSON.stringify(t.action)});let r=X(t.output);yield{type:_.TOOL_CALL_RESULT,messageId:n,toolCallId:n,content:r};break}case`error`:yield{type:_.RUN_ERROR,message:e.message,code:e.code??void 0};break;case`response.failed`:yield{type:_.RUN_ERROR,message:e.response?.error?.message??`Response failed`,code:e.response?.error?.code??void 0}}}catch(e){console.error(`Failed to parse OpenAI Responses SSE event`,e)}}if(e)break}}}),bt=`vercelAIAdapter requires the optional peer dependency "ai" (Vercel AI SDK v6 or v7).`,xt=`Tool execution was denied`;function St(e){return typeof e==`string`?e:JSON.stringify(e)??String(e)}async function Ct(e){let t;try{({DefaultChatTransport:t}=await import(`ai`))}catch(e){throw Error(bt,{cause:e})}if(typeof t!=`function`)throw Error(bt);class n extends t{parseBody(e){return this.processResponseStream(e)}}return new n().parseBody(e)}async function*wt(e){let t=e.getReader();try{for(;;){let{done:e,value:n}=await t.read();if(e)return;yield n}}finally{t.releaseLock()}}function Z(e,t,n){return{type:_.TOOL_CALL_RESULT,messageId:`tool-result-${e}`,toolCallId:e,content:t,role:`tool`,...n===void 0?{}:{isError:!0,error:n}}}const Tt=()=>({async*parse(e){if(!e.body)throw Error(`No response body`);let t=await Ct(e.body),n=/* @__PURE__ */ new Set,r=/* @__PURE__ */ new Set,i=/* @__PURE__ */ new Set,a=0,o,s=e=>{if(o&&!o.messageStarted)return o.messageId??=e??`vercel-ai-message-${a}`,o.messageStarted=!0,{type:_.TEXT_MESSAGE_START,messageId:o.messageId,role:`assistant`}},c=e=>{if(o?.messageStarted&&o.sawTools){let t=o.messageId;return o.messageId=e,o.sawTools=!1,[{type:_.TEXT_MESSAGE_END,messageId:t},{type:_.TEXT_MESSAGE_START,messageId:e,role:`assistant`}]}let t=s(e);return t?[t]:[]},l=()=>o?.messageId?{parentMessageId:o.messageId}:{};for await(let e of wt(t)){if(`providerExecuted`in e&&e.providerExecuted===!0)throw Error(`Vercel AI SDK provider-executed tools are not supported because AG-UI messages cannot preserve providerExecuted semantics.`);switch(e.type){case`start-step`:{let e=`vercel-ai-step-${++a}`;o={stepName:e,messageStarted:!1,sawTools:!1},yield{type:_.STEP_STARTED,stepName:e};break}case`finish-step`:{let e=o?.stepName??`vercel-ai-step-${++a}`;o?.messageStarted&&o.messageId&&(yield{type:_.TEXT_MESSAGE_END,messageId:o.messageId}),yield{type:_.STEP_FINISHED,stepName:e},o=void 0;break}case`text-start`:for(let t of c(e.id))yield t;o||(yield{type:_.TEXT_MESSAGE_START,messageId:e.id,role:`assistant`});break;case`text-delta`:for(let t of c(e.id))yield t;yield{type:_.TEXT_MESSAGE_CONTENT,messageId:o?.messageId??e.id,delta:e.delta};break;case`text-end`:o||(yield{type:_.TEXT_MESSAGE_END,messageId:e.id});break;case`tool-input-start`:if(!n.has(e.toolCallId)){let t=s();t&&(yield t),n.add(e.toolCallId),o&&(o.sawTools=!0),yield{type:_.TOOL_CALL_START,toolCallId:e.toolCallId,toolCallName:e.toolName,...l()}}break;case`tool-input-delta`:e.inputTextDelta&&(r.add(e.toolCallId),yield{type:_.TOOL_CALL_ARGS,toolCallId:e.toolCallId,delta:e.inputTextDelta});break;case`tool-input-available`:case`tool-input-error`:if(!n.has(e.toolCallId)){let t=s();t&&(yield t),n.add(e.toolCallId),o&&(o.sawTools=!0),yield{type:_.TOOL_CALL_START,toolCallId:e.toolCallId,toolCallName:e.toolName,...l()}}r.has(e.toolCallId)||(r.add(e.toolCallId),yield{type:_.TOOL_CALL_ARGS,toolCallId:e.toolCallId,delta:St(e.input)}),i.has(e.toolCallId)||(i.add(e.toolCallId),yield{type:_.TOOL_CALL_END,toolCallId:e.toolCallId}),e.type===`tool-input-error`&&(yield Z(e.toolCallId,e.errorText,e.errorText));break;case`tool-output-available`:yield Z(e.toolCallId,St(e.output));break;case`tool-output-error`:yield Z(e.toolCallId,e.errorText,e.errorText);break;case`tool-output-denied`:yield Z(e.toolCallId,xt,xt);break;case`error`:yield{type:_.RUN_ERROR,message:e.errorText};return}}o?.messageStarted&&o.messageId&&(yield{type:_.TEXT_MESSAGE_END,messageId:o.messageId})}}),Et=async({response:e,createMessage:t,updateMessage:n,markToolExecuting:r=()=>{},clearToolExecuting:i=()=>{},adapter:a=st()})=>{let o={id:crypto.randomUUID(),role:`assistant`,content:``,toolCalls:[]},s=!0,c=null,l=/* @__PURE__ */ new Map,u=/* @__PURE__ */ new Set,d=null,f=e=>{d!==null&&cancelAnimationFrame(d),d=requestAnimationFrame(()=>{n(e),d=null})},p=()=>{d!==null&&(cancelAnimationFrame(d),d=null,s||n(o)),o={id:crypto.randomUUID(),role:`assistant`,content:``,toolCalls:[]},s=!0,c=null},m=e=>(e.content?.length??0)>0||(e.toolCalls?.length??0)>0,h=()=>{if(s){if(!m(o))return;t(o),s=!1}else f(o)};for await(let s of a.parse(e)){switch(s.type){case _.TEXT_MESSAGE_CHUNK:case _.TEXT_MESSAGE_CONTENT:if(!s.delta)break;(o.toolCalls?.length??0)>0&&p(),o={...o,content:(o.content||``)+s.delta};break;case _.TOOL_CALL_START:u.add(s.toolCallId),o={...o,toolCalls:[...o.toolCalls||[],{id:s.toolCallId,type:`function`,function:{name:s.toolCallName,arguments:``}}]};break;case _.TOOL_CALL_END:r(s.toolCallId);break;case _.TOOL_CALL_ARGS:if(o.toolCalls){let e=[...o.toolCalls],t=e.findIndex(e=>e.id===s.toolCallId);if(t!==-1){let n=e[t];n&&(e[t]={id:n.id,type:`function`,function:{name:n.function.name,arguments:n.function.arguments+s.delta}},o={...o,toolCalls:e})}}break;case _.TOOL_CALL_CHUNK:{let e=s.toolCallId;if(!e)break;let t=[...o.toolCalls||[]],n=t.findIndex(t=>t.id===e);n===-1&&(u.add(e),t.push({id:e,type:`function`,function:{name:s.toolCallName??``,arguments:``}}),n=t.length-1);let r=t[n];r&&(t[n]={id:r.id,type:`function`,function:{name:r.function.name||s.toolCallName||``,arguments:r.function.arguments+(s.delta??``)}},o={...o,toolCalls:t});break}case _.TEXT_MESSAGE_START:{let e=s.messageId??null;((o.content?.length??0)>0||(o.toolCalls?.length??0)>0)&&e!==c&&p(),c=e;break}case _.TOOL_CALL_RESULT:{i(s.toolCallId),u.delete(s.toolCallId),d!==null&&(cancelAnimationFrame(d),d=null,n(o));let e=s,r=e.isError===!0||typeof e.error==`string`&&e.error.length>0?e.error??s.content:void 0,a=l.get(s.toolCallId);if(a){let e={...a,content:s.content,...r?{error:r}:{}};l.set(s.toolCallId,e),n(e)}else{let e={id:crypto.randomUUID(),role:`tool`,toolCallId:s.toolCallId,content:s.content,...r?{error:r}:{}};l.set(s.toolCallId,e),t(e)}continue}case _.RUN_ERROR:{let e=s.message||s.error||`Stream error`,t=typeof e==`string`?e:JSON.stringify(e);for(let e of u)i(e);throw u.clear(),Error(t)}}h()}return d===null?s&&m(o)&&t(o):(cancelAnimationFrame(d),n(o)),o};async function Dt(e){if(e.ok)return{};try{let t=await e.clone().json();return{error:t?.error,...t?.message?{message:t.message}:{message:await q(e)}}}catch{return{message:await q(e)}}}function Ot(e){return e>=400?`error`:`info`}const kt=(e,t)=>Array.from(new Map([...e,...t].map(e=>[e.id,e])).values()).sort((e,t)=>new Date(t.createdAt).getTime()-new Date(e.createdAt).getTime()),At=e=>{let{storage:t}=e.current,{thread:n}=t;return h()(g((t,r)=>({threads:[],isLoadingThreads:!1,threadListError:null,selectedThreadId:null,hasMoreThreads:!1,_nextCursor:void 0,messages:[],isRunning:!1,isLoadingMessages:!1,threadError:null,executingToolCallIds:/* @__PURE__ */ new Set,_abortController:null,loadThreads:()=>{t({isLoadingThreads:!0,threadListError:null}),n.listThreads(void 0).then(({threads:e=[],nextCursor:n})=>{t({threads:e,isLoadingThreads:!1,_nextCursor:n,hasMoreThreads:n!==void 0})}).catch(e=>{t({isLoadingThreads:!1,threadListError:e})})},loadMoreThreads:()=>{let e=r()._nextCursor;e!==void 0&&n.listThreads(e).then(({threads:e=[],nextCursor:n})=>{t(t=>({threads:kt(t.threads,e),_nextCursor:n,hasMoreThreads:n!==void 0}))}).catch(e=>{t({threadListError:e})})},switchToNewThread:()=>{r().cancelMessage(),t({selectedThreadId:null,messages:[],threadError:null,executingToolCallIds:/* @__PURE__ */ new Set})},createThread:async e=>{let r=await n.createThread(e);return t(e=>({threads:kt(e.threads,[r])})),r},selectThread:e=>{r().selectedThreadId!==e&&(r().cancelMessage(),t({selectedThreadId:e,messages:[],isLoadingMessages:!0,threadError:null,executingToolCallIds:/* @__PURE__ */ new Set}),n.getMessages(e).then(e=>t({messages:e,isLoadingMessages:!1})).catch(e=>t({threadError:e,isLoadingMessages:!1})))},updateThread:e=>{let r=(e,n)=>t(t=>({threads:t.threads.map(t=>t.id===e?{...t,isPending:n}:t)}));r(e.id,!0),n.updateThread(e).then(e=>{t(t=>({threads:t.threads.map(t=>t.id===e.id?e:t)}))}).catch(()=>r(e.id,!1))},deleteThread:e=>{let i=(e,n)=>t(t=>({threads:t.threads.map(t=>t.id===e?{...t,isPending:n}:t)}));i(e,!0),n.deleteThread(e).then(()=>{let n=r();t({threads:n.threads.filter(t=>t.id!==e)}),n.selectedThreadId===e&&n.switchToNewThread()}).catch(()=>i(e,!1))},processMessage:async n=>{if(r().isRunning)return;let i=new AbortController,a={...n,id:crypto.randomUUID(),role:`user`};t({_abortController:i,isRunning:!0,threadError:null,executingToolCallIds:/* @__PURE__ */ new Set}),t(e=>({messages:[...e.messages,a]})),i.signal.addEventListener(`abort`,()=>{t({_abortController:null,isRunning:!1})});try{let n=r().selectedThreadId;n||(n=(await r().createThread(a)).id,t({selectedThreadId:n}));let o=crypto.randomUUID();m.info({kind:`LLM:request`,threadId:n,runId:o,userMessage:a});let s=null;try{if(s=await e.current.llm.send({threadId:n,messages:r().messages,signal:i.signal}),m(Ot(s.status),{kind:s.ok?`LLM:response`:`LLM:error`,threadId:n,status:s.status,ok:s.ok,runId:o,...await Dt(s)}),!s.ok)throw Error(await q(s))}catch(e){throw m.error({kind:`LLM:error`,threadId:n,runId:o,error:e instanceof Error?e:Error(String(e))}),e}await Et({response:s,createMessage:e=>t(t=>({messages:[...t.messages,e]})),updateMessage:e=>t(t=>({messages:t.messages.map(t=>t.id===e.id?e:t)})),markToolExecuting:e=>t(t=>t.executingToolCallIds.has(e)?t:{executingToolCallIds:new Set(t.executingToolCallIds).add(e)}),clearToolExecuting:e=>t(t=>{if(!t.executingToolCallIds.has(e))return t;let n=new Set(t.executingToolCallIds);return n.delete(e),{executingToolCallIds:n}}),adapter:e.current.llm.streamProtocol})}catch(e){i.signal.aborted||t({threadError:e instanceof Error?e:Error(String(e))})}finally{t({_abortController:null,isRunning:!1,executingToolCallIds:/* @__PURE__ */ new Set})}},appendMessages:(...e)=>{t(t=>({messages:[...t.messages,...e]}))},updateMessage:e=>{t(t=>({messages:t.messages.map(t=>t.id===e.id?e:t)}))},setMessages:e=>{t({messages:e})},deleteMessage:e=>{t(t=>({messages:t.messages.filter(t=>t.id!==e)}))},cancelMessage:()=>{r()._abortController?.abort()}})))},jt=()=>h()(g((e,t)=>({activeDetailedViewId:null,setActiveDetailedView:t=>{e({activeDetailedViewId:t})},reset:()=>{e({activeDetailedViewId:null})},_detailedViewPanelNode:null,_setDetailedViewPanelNode:n=>{typeof process<`u`&&process.env?.NODE_ENV!==`production`&&n&&t()._detailedViewPanelNode&&t()._detailedViewPanelNode!==n&&console.warn(`[OpenUI] Multiple DetailedViewPortalTarget instances detected. Only one should be mounted at a time.`),e({_detailedViewPanelNode:n})}}))),Mt=(e,t)=>e.heading===t.heading&&e.type===t.type,Nt=(e,t)=>{let n=e[t.id]??[],r=n.findIndex(e=>e.version===t.version);if(r!==-1){let i=n[r];if(Mt(i,t))return e;let a=n.slice();return a[r]=t,{...e,[t.id]:a}}let i=n.findIndex(e=>e.version>t.version),a=i===-1?[...n,t]:[...n.slice(0,i),t,...n.slice(i)];return{...e,[t.id]:a}},Pt=(e,t,n)=>{let r=e[t];if(!r)return e;let i=r.findIndex(e=>e.version===n);if(i===-1)return e;if(r.length===1){let{[t]:n,...r}=e;return r}let a=r.slice();return a.splice(i,1),{...e,[t]:a}},Ft=()=>h()(g(e=>({artifacts:{},registerArtifact:t=>{e(e=>({artifacts:Nt(e.artifacts,t)}))},unregisterArtifact:(t,n)=>{e(e=>({artifacts:Pt(e.artifacts,t,n)}))},reset:()=>{e({artifacts:{}})}}))),It=[],Lt=t({name:`OpenUIChatProvider`,props:{llm:{type:Object,required:!0},storage:Object,artifactRenderers:Array,artifactCategories:Array,artifactAutoOpen:{type:Boolean,default:!0},children:null},setup(t,{slots:n}){let r=t.storage??it(),i={current:{storage:r,llm:t.llm}};f(()=>t.llm,e=>{i.current.llm=e},{flush:`sync`});let l=At(i),u=jt(),d=Ft(),p=Re(t.artifactRenderers??[]),m=t.artifactRenderers,h=!1;s(()=>{let e=t.artifactRenderers;typeof process<`u`&&process.env.NODE_ENV!==`production`&&!h&&e!==m&&(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."),h=!0)});let g;return a(()=>{g=l.subscribe(e=>e.selectedThreadId,()=>{u.getState().reset(),d.getState().reset()})}),o(()=>g?.()),ot(()=>t.artifactAutoOpen??!0,l,d,u),c(B,l),c(P,u),c(I,d),c(L,p),c(v,r.artifact??null),c($e,e(()=>t.artifactCategories??It)),()=>n.default?.()??t.children}});function Rt(e){switch(e.role){case`user`:return{type:`human`,content:e.content??``};case`assistant`:{let t={type:`ai`,content:e.content??``};return e.toolCalls?.length&&(t.tool_calls=e.toolCalls.map(e=>({id:e.id,name:e.function.name,args:Bt(e.function.arguments)}))),t}case`tool`:return{type:`tool`,content:e.content,tool_call_id:e.toolCallId};case`system`:case`developer`:return{type:`system`,content:e.content};default:return{type:`system`,content:``}}}function zt(e){let t=e.id??crypto.randomUUID();switch(e.type){case`human`:return{id:t,role:`user`,content:Q(e.content)};case`ai`:{let n={id:t,role:`assistant`,content:Q(e.content)};return e.tool_calls?.length&&(n.toolCalls=e.tool_calls.map(e=>({id:e.id,type:`function`,function:{name:e.name,arguments:typeof e.args==`string`?e.args:JSON.stringify(e.args)}}))),n}case`tool`:return{id:t,role:`tool`,content:Q(e.content),toolCallId:e.tool_call_id??``};default:return{id:t,role:`system`,content:Q(e.content)}}}function Q(e){return typeof e==`string`?e:e.filter(e=>e.type===`text`&&e.text).map(e=>e.text).join(``)}function Bt(e){try{return JSON.parse(e)}catch{return e}}const Vt={toApi(e){return e.map(Rt)},fromApi(e){return e.map(zt)}};function Ht(e){let t=e.content;return typeof t==`string`?{role:`user`,content:t}:{role:`user`,content:t?.map(e=>e.type===`text`?{type:`text`,text:e.text}:e.type===`binary`?{type:`image_url`,image_url:{url:e.url??`data:${e.mimeType};base64,${e.data??``}`}}:{type:`text`,text:``})??[]}}function Ut(e){let t={role:`assistant`,content:e.content??null};return e.toolCalls?.length&&(t.tool_calls=e.toolCalls.map(e=>({id:e.id,type:`function`,function:{name:e.function.name,arguments:e.function.arguments}}))),t}function Wt(e){return{role:`tool`,content:e.content,tool_call_id:e.toolCallId}}function Gt(e){switch(e.role){case`user`:return Ht(e);case`assistant`:return Ut(e);case`tool`:return Wt(e);case`system`:return{role:`system`,content:e.content};case`developer`:return{role:`developer`,content:e.content};default:return{role:`system`,content:``}}}function Kt(e){let t=typeof e.content==`string`?e.content:void 0,n={id:crypto.randomUUID(),role:`assistant`,content:t};return e.tool_calls?.length&&(n.toolCalls=e.tool_calls.filter(e=>e.type===`function`).map(e=>({id:e.id,type:`function`,function:{name:e.function.name,arguments:e.function.arguments}}))),n}function qt(e){if(typeof e.content==`string`)return{id:crypto.randomUUID(),role:`user`,content:e.content};let t=e.content.map(e=>e.type===`text`?{type:`text`,text:e.text}:{type:`text`,text:``});return{id:crypto.randomUUID(),role:`user`,content:t}}function Jt(e){let t=typeof e.content==`string`?e.content:e.content.map(e=>e.text).join(``);return{id:crypto.randomUUID(),role:`tool`,content:t,toolCallId:e.tool_call_id}}function Yt(e){switch(e.role){case`user`:return qt(e);case`assistant`:return Kt(e);case`tool`:return Jt(e);case`system`:return{id:crypto.randomUUID(),role:`system`,content:typeof e.content==`string`?e.content:``};case`developer`:return{id:crypto.randomUUID(),role:`developer`,content:typeof e.content==`string`?e.content:``};default:return{id:crypto.randomUUID(),role:`system`,content:``}}}const Xt={toApi(e){return e.map(Gt)},fromApi(e){return e.map(Yt)}},Zt=`Vercel AI SDK provider-executed tools are not supported because AG-UI messages cannot preserve providerExecuted semantics.`;function $(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Qt(e){return $(e)&&e.providerExecuted===!0}function $t(e){if(typeof e==`string`)return e;try{return JSON.stringify(e)??String(e)}catch{return String(e)}}function en(e){try{return JSON.parse(e)}catch{return e}}function tn(e,t){return`data:${e};base64,${t}`}function nn(e,t){if(typeof t.mimeType==`string`)return t.mimeType;switch(e.type){case`image`:return`image/*`;case`audio`:return`audio/*`;case`video`:return`video/*`;default:return`application/octet-stream`}}function rn(e){return typeof e==`string`?[{type:`text`,text:e}]:Array.isArray(e)?e.flatMap(e=>{if(!$(e))return[];if(e.type===`text`&&typeof e.text==`string`)return[{type:`text`,text:e.text}];if(e.type===`binary`){let t=typeof e.mimeType==`string`?e.mimeType:`application/octet-stream`,n=typeof e.url==`string`?e.url:typeof e.data==`string`?tn(t,e.data):void 0;return n?[{type:`file`,mediaType:t,url:n,...typeof e.filename==`string`?{filename:e.filename}:{}}]:[]}switch(e.type){case`image`:case`audio`:case`video`:case`document`:{if(!$(e.source)||typeof e.source.value!=`string`)return[];let t=nn(e,e.source),n=e.source.type===`data`?tn(t,e.source.value):e.source.type===`url`?e.source.value:void 0;return n?[{type:`file`,mediaType:t,url:n}]:[]}default:return[]}}):[]}function an(e,t){if(Qt(e)||Qt(t))throw Error(Zt);let n=en(e.function.arguments);return t?.error?{type:`dynamic-tool`,toolName:e.function.name,toolCallId:e.id,state:`output-error`,input:n,errorText:t.error}:t?{type:`dynamic-tool`,toolName:e.function.name,toolCallId:e.id,state:`output-available`,input:n,output:t.content}:{type:`dynamic-tool`,toolName:e.function.name,toolCallId:e.id,state:`input-available`,input:n}}function on(e){let t=/* @__PURE__ */ new Map;for(let n of e)n.role===`tool`&&t.set(n.toolCallId,n);let n=[];for(let r of e)switch(r.role){case`user`:n.push({id:r.id,role:`user`,parts:rn(r.content)});break;case`assistant`:{let e=[];typeof r.content==`string`&&r.content.length>0&&e.push({type:`text`,text:r.content});for(let n of r.toolCalls??[])e.push(an(n,t.get(n.id)));n.push({id:r.id,role:`assistant`,parts:e});break}case`system`:case`developer`:n.push({id:r.id,role:`system`,parts:[{type:`text`,text:r.content}]})}return n}function sn(e){return $(e)&&typeof e.id==`string`&&(e.role===`system`||e.role===`user`||e.role===`assistant`)&&Array.isArray(e.parts)}function cn(e){return e.filter(e=>$(e)&&e.type===`text`&&typeof e.text==`string`).map(e=>e.text).join(``)}function ln(e){if(e.type!==`file`||typeof e.mediaType!=`string`||typeof e.url!=`string`)return;let t=`data:${e.mediaType};base64,`,n=e.url.startsWith(t)?{data:e.url.slice(t.length)}:{url:e.url};return{type:`binary`,mimeType:e.mediaType,...n,...typeof e.filename==`string`?{filename:e.filename}:{}}}function un(e){let t=[],n=!1;for(let r of e.parts){if(!$(r))continue;if(r.type===`text`&&typeof r.text==`string`){t.push({type:`text`,text:r.text});continue}let e=ln(r);e&&(n=!0,t.push(e))}return{id:e.id,role:`user`,content:n?t:cn(e.parts)}}function dn(e){if(e.type===`dynamic-tool`)return typeof e.toolName==`string`&&e.toolName.length>0?e.toolName:void 0;if(typeof e.type==`string`&&e.type.startsWith(`tool-`))return e.type.slice(5)||void 0}function fn(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function pn(e){if(typeof e.toolCallId==`string`){if(e.state===`output-available`&&fn(e,`output`))return{id:`tool-result-${e.toolCallId}`,role:`tool`,toolCallId:e.toolCallId,content:$t(e.output)};if(e.state===`output-error`&&typeof e.errorText==`string`)return{id:`tool-result-${e.toolCallId}`,role:`tool`,toolCallId:e.toolCallId,content:e.errorText,error:e.errorText};if(e.state===`output-denied`){let t=`Tool execution was denied`;return{id:`tool-result-${e.toolCallId}`,role:`tool`,toolCallId:e.toolCallId,content:t,error:t}}}}function mn(e,t){let n=0,r=!1,i=``,a=[],o=[],s=e.parts.some(e=>$(e)&&e.type===`step-start`),c=()=>i.length>0||a.length>0,l=(s=!1)=>{(s||r)&&(n+=1,t.push({id:n===1?e.id:`${e.id}-segment-${n}`,role:`assistant`,...i?{content:i}:{},...a.length?{toolCalls:a}:{}}),t.push(...o),i=``,a=[],o=[],r=!1)};for(let t of e.parts){if(!$(t))continue;if(t.type===`step-start`){c()&&l();continue}if(t.type===`text`&&typeof t.text==`string`){(a.length>0||!s&&c())&&l(),r=!0,i+=t.text;continue}let e=dn(t);if(!e||typeof t.toolCallId!=`string`)continue;if(t.providerExecuted===!0)throw Error(Zt);r=!0,a.push({id:t.toolCallId,type:`function`,function:{name:e,arguments:fn(t,`input`)?$t(t.input):``}});let n=pn(t);n&&o.push(n)}l(n===0)}function hn(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(!sn(n))continue;let e=n;if(e.role===`user`){t.push(un(e));continue}let r=cn(e.parts);e.role===`system`?t.push({id:e.id,role:`system`,content:r}):mn(e,t)}return t}const gn={toApi(e){return on(e)},fromApi(e){return hn(e)}};function _n({url:e,streamAdapter:t,messageFormat:n=J,headers:r,fetch:i,body:a}){let o=i??globalThis.fetch.bind(globalThis);return{send:({threadId:t,messages:i,signal:s})=>{let c=crypto.randomUUID();return o(e,{method:`POST`,headers:{"Content-Type":`application/json`,...r},body:JSON.stringify({...a,tools:[],context:[],threadId:t,runId:c,messages:n.toApi(i)}),signal:s})},streamProtocol:t}}function vn({baseUrl:e,messageFormat:t=J,headers:n,fetch:r}){let i=r??globalThis.fetch.bind(globalThis),a=async(e,t)=>{let r=await i(e,{...t,headers:{...t?.body?{"Content-Type":`application/json`}:{},...n,...t?.headers}});if(!r.ok)throw Error(`restStorage: ${t?.method??`GET`} ${e} failed: ${r.status} ${r.statusText}`);return r};return{thread:{async listThreads(t){let n=t?`${e}/get?cursor=${t}`:`${e}/get`;return(await a(n)).json()},async createThread(n){return(await a(`${e}/create`,{method:`POST`,body:JSON.stringify({messages:t.toApi([n])})})).json()},async getMessages(n){let r=await(await a(`${e}/get/${n}`)).json();return t.fromApi(r)},async updateThread(t){return(await a(`${e}/update/${t.id}`,{method:`PATCH`,body:JSON.stringify(t)})).json()},async deleteThread(t){await a(`${e}/delete/${t}`,{method:`DELETE`})}}}}export{M as ArtifactPollIntervalContext,L as ArtifactRenderersContext,v as ArtifactStorageContext,ie as ArtifactStreamStore,Lt as ChatProvider,P as DetailedViewContext,ct as EVE_INPUT_REQUESTED_EVENT,_ as EventType,z as MessageContext,Ge as MessageProvider,Me as OpenUICloudProvider,I as ThreadContextContext,st as agUIAdapter,nt as artifactViewId,ue as createInterpreterToolProvider,Qe as defineArtifactCategories,tt as defineArtifactRenderer,ut as eveAdapter,_n as fetchLLM,q as getResponseErrorMessage,J as identityMessageFormat,dt as langGraphAdapter,Vt as langGraphMessageFormat,ze as lookupArtifactRenderer,Be as lookupArtifactRendererByType,ae as noteArtifactVersion,_t as openAIAdapter,Te as openAIConversationMessageFormat,Xt as openAIMessageFormat,vt as openAIReadableStreamAdapter,yt as openAIResponsesAdapter,Xe as pairToolActivity,rt as parseArtifactViewId,G as partialJSONParse,Et as processStreamedMessage,vn as restStorage,Pe as useActiveDetailedView,et as useArtifactCategories,Ie as useArtifactList,je as useArtifactPollInterval,Ve as useArtifactRenderer,R as useArtifactRendererRegistry,y as useArtifactStorage,se as useArtifactStream,He as useDetailedView,Ue as useDetailedViewPortalTarget,F as useDetailedViewStore,We as useMessage,j as useOpenuiCloudStorage,W as useThread,Fe as useThreadContextStore,Ke as useThreadList,Ze as useToolActivities,Tt as vercelAIAdapter,gn as vercelAIMessageFormat,oe as watchArtifactStreams};