@wodecorp/openui-vue-headless 0.1.3 → 0.1.5

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