@zenera/chat-widget 0.1.4 → 0.1.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/README.md +53 -8
  2. package/dist/catalog-BYJPdVB0.js +358 -0
  3. package/dist/index-Dw5Lv6cs.js +3151 -0
  4. package/dist/index.js +22 -14
  5. package/dist/shadow-CEK6vAGQ.js +4 -0
  6. package/dist/styles.css +1 -1
  7. package/dist/types/packages/chat-widget/src/index.d.ts +4 -2
  8. package/dist/types/packages/chat-widget/src/interceptors.d.ts +50 -0
  9. package/dist/types/packages/chat-widget/src/reducer.d.ts +14 -0
  10. package/dist/types/packages/chat-widget/src/transport.d.ts +37 -4
  11. package/dist/types/packages/chat-widget/src/ui/ChatThreadView.d.ts +22 -2
  12. package/dist/types/packages/chat-widget/src/ui/ZeneraChat.d.ts +8 -2
  13. package/dist/types/packages/chat-widget/src/ui/internal/composerDraft.d.ts +1 -1
  14. package/dist/types/packages/chat-widget/src/useAttachments.d.ts +32 -0
  15. package/dist/types/packages/chat-widget/src/useChatThread.d.ts +3 -2
  16. package/dist/types/packages/chat-widget/src/widget.d.ts +8 -2
  17. package/dist/types/shared/components/A2uiSurface.d.ts +3 -0
  18. package/dist/types/shared/components/a2ui/Chart.d.ts +2 -0
  19. package/dist/types/shared/components/a2ui/ChartView.d.ts +3 -0
  20. package/dist/types/shared/components/a2ui/DataTable.d.ts +2 -0
  21. package/dist/types/shared/components/a2ui/Notice.d.ts +6 -0
  22. package/dist/types/shared/components/a2ui/catalog.d.ts +2 -0
  23. package/dist/types/shared/components/a2ui/catalogApi.d.ts +16 -0
  24. package/dist/types/shared/components/a2ui/chartData.d.ts +8 -0
  25. package/dist/types/shared/components/a2ui/tableData.d.ts +21 -0
  26. package/dist/types/shared/components/a2ui/useChartPayload.d.ts +9 -0
  27. package/dist/types/shared/lib/a2ui.d.ts +22 -0
  28. package/dist/types/shared/lib/a2uiData.d.ts +2 -0
  29. package/dist/types/shared/lib/a2uiFeed.d.ts +40 -0
  30. package/dist/types/shared/lib/promptHistory.d.ts +1 -1
  31. package/dist/ui.js +15 -2822
  32. package/dist/useThreadList-BbWSgDw_.js +899 -0
  33. package/dist/widget/chat-widget.iife.js +6179 -88
  34. package/package.json +7 -9
  35. package/dist/shadow-BRAwePHz.js +0 -4
  36. package/dist/useThreadList-Pg29akQ4.js +0 -576
@@ -0,0 +1,899 @@
1
+ var ce = Object.defineProperty;
2
+ var de = (e, t, n) => t in e ? ce(e, t, { enumerable: !0, configurable: !0, writable: !0, value: n }) : e[t] = n;
3
+ var F = (e, t, n) => de(e, typeof t != "symbol" ? t + "" : t, n);
4
+ import { useState as x, useRef as L, useCallback as O, useEffect as G, useMemo as ne } from "react";
5
+ import { EventType as C } from "@ag-ui/core";
6
+ const V = { items: [], status: "loading" };
7
+ function J(e) {
8
+ return typeof e == "string" ? e : Array.isArray(e) ? e.filter((t) => t && typeof t == "object" && "text" in t).map((t) => String(t.text)).join(`
9
+ `) : "";
10
+ }
11
+ const le = /* @__PURE__ */ new Set(["image", "audio", "video", "document"]);
12
+ function re(e) {
13
+ if (!Array.isArray(e)) return;
14
+ const t = e.flatMap((n) => {
15
+ var s, i, c, l, y;
16
+ const r = n;
17
+ if (!r || typeof r.type != "string" || !le.has(r.type)) return [];
18
+ const o = typeof ((s = r.source) == null ? void 0 : s.value) == "string" ? r.source.value : "", a = ((i = r.source) == null ? void 0 : i.type) === "url" && o ? o : void 0;
19
+ return [
20
+ {
21
+ name: typeof ((c = r.metadata) == null ? void 0 : c.name) == "string" ? r.metadata.name : (a == null ? void 0 : a.split("/").at(-1)) ?? "file",
22
+ ...typeof ((l = r.metadata) == null ? void 0 : l.size) == "number" && { size: r.metadata.size },
23
+ ...typeof ((y = r.source) == null ? void 0 : y.mimeType) == "string" && { mimeType: r.source.mimeType },
24
+ ...a && { path: a }
25
+ }
26
+ ];
27
+ });
28
+ return t.length ? t : void 0;
29
+ }
30
+ function se(e, t, n) {
31
+ const r = re(t);
32
+ return {
33
+ kind: "user",
34
+ id: e,
35
+ text: J(t),
36
+ ...n && { runId: n },
37
+ ...r && { attachments: r }
38
+ };
39
+ }
40
+ function fe(e) {
41
+ const t = [];
42
+ for (const n of e)
43
+ if (n.role === "user")
44
+ t.push(se(n.id, n.content));
45
+ else if (n.role === "assistant") {
46
+ n.content && t.push({ kind: "assistant", id: n.id, text: n.content, agent: n.name });
47
+ for (const r of n.toolCalls ?? [])
48
+ t.push({
49
+ kind: "tool",
50
+ id: r.id,
51
+ name: r.function.name,
52
+ args: r.function.arguments
53
+ });
54
+ } else if (n.role === "tool") {
55
+ const r = J(n.content), o = t.findIndex((a) => a.kind === "tool" && a.id === n.toolCallId);
56
+ o >= 0 && (t[o] = {
57
+ ...t[o],
58
+ result: r,
59
+ isError: !!n.error
60
+ });
61
+ }
62
+ return t;
63
+ }
64
+ function X(e, t) {
65
+ let n = { items: fe(e), status: "idle" };
66
+ for (const r of t) n = oe(n, r);
67
+ return { items: n.items, status: "idle", interrupts: n.interrupts };
68
+ }
69
+ function xe(e, t) {
70
+ return X(e, t).items;
71
+ }
72
+ function me(e) {
73
+ const t = e;
74
+ return (t == null ? void 0 : t.type) !== "interrupt" || !Array.isArray(t.interrupts) ? [] : t.interrupts.flatMap((n) => {
75
+ const r = n;
76
+ return !r || typeof r.id != "string" || typeof r.reason != "string" ? [] : [
77
+ {
78
+ id: r.id,
79
+ reason: r.reason,
80
+ ...typeof r.message == "string" ? { message: r.message } : {},
81
+ ...typeof r.toolCallId == "string" ? { toolCallId: r.toolCallId } : {},
82
+ ...r.metadata && typeof r.metadata == "object" ? { metadata: r.metadata } : {}
83
+ }
84
+ ];
85
+ });
86
+ }
87
+ function pe(e, t) {
88
+ var r;
89
+ if (!((r = e.interrupts) != null && r.length)) return e.items;
90
+ const n = /* @__PURE__ */ new Map();
91
+ if (Array.isArray(t))
92
+ for (const o of t)
93
+ typeof (o == null ? void 0 : o.interruptId) == "string" && (o.status === "resolved" || o.status === "cancelled") && n.set(o.interruptId, o.status);
94
+ return e.items.map(
95
+ (o) => o.kind === "tool" && o.interrupt && !o.interrupt.ended ? {
96
+ ...o,
97
+ interrupt: {
98
+ ...o.interrupt,
99
+ ended: n.get(o.interrupt.id) ?? "superseded"
100
+ }
101
+ } : o
102
+ );
103
+ }
104
+ function B(e, t, n, r) {
105
+ const o = e.items.findIndex((u) => u.id === t && u.kind === n);
106
+ if (o < 0) return e;
107
+ const a = e.items.slice();
108
+ return a[o] = r(a[o]), { ...e, items: a };
109
+ }
110
+ function oe(e, t) {
111
+ var r, o, a, u;
112
+ const n = "subagentRunId" in t && typeof t.subagentRunId == "string" ? t.subagentRunId : void 0;
113
+ switch (t.type) {
114
+ case C.RUN_STARTED: {
115
+ const s = (r = t.input) == null ? void 0 : r.messages.at(-1), i = pe(e, (o = t.input) == null ? void 0 : o.resume), c = (s == null ? void 0 : s.role) !== "user" ? i : i.some((l) => l.id === s.id) ? i.map((l) => {
116
+ if (l.kind !== "user" || l.id !== s.id) return l;
117
+ const y = re(s.content);
118
+ return {
119
+ ...l,
120
+ runId: l.runId ?? t.runId,
121
+ ...y && { attachments: y }
122
+ };
123
+ }) : [...i, se(s.id, s.content, t.runId)];
124
+ return {
125
+ ...e,
126
+ items: c,
127
+ status: "running",
128
+ runId: t.runId,
129
+ error: void 0,
130
+ waking: void 0,
131
+ interrupts: void 0
132
+ };
133
+ }
134
+ case C.CUSTOM: {
135
+ if (t.name !== "zenera.project") return e;
136
+ const s = (a = t.value) == null ? void 0 : a.podStatus;
137
+ return { ...e, waking: s === "running" ? void 0 : s };
138
+ }
139
+ case C.SUBAGENT_STARTED:
140
+ return t.name ? { ...e, branches: { ...e.branches, [t.subagentRunId]: t.name } } : e;
141
+ case C.TEXT_MESSAGE_START: {
142
+ const s = n ? (u = e.branches) == null ? void 0 : u[n] : void 0;
143
+ return {
144
+ ...e,
145
+ items: [
146
+ ...e.items,
147
+ {
148
+ kind: "assistant",
149
+ id: t.messageId,
150
+ text: "",
151
+ agent: t.name,
152
+ subagent: n,
153
+ ...s ? { branch: s } : {}
154
+ }
155
+ ]
156
+ };
157
+ }
158
+ case C.TEXT_MESSAGE_CONTENT:
159
+ return B(e, t.messageId, "assistant", (s) => ({
160
+ ...s,
161
+ text: s.text + t.delta
162
+ }));
163
+ case C.REASONING_MESSAGE_START:
164
+ return {
165
+ ...e,
166
+ items: [...e.items, { kind: "reasoning", id: t.messageId, text: "", subagent: n }]
167
+ };
168
+ case C.REASONING_MESSAGE_CONTENT:
169
+ return B(e, t.messageId, "reasoning", (s) => ({
170
+ ...s,
171
+ text: s.text + t.delta
172
+ }));
173
+ case C.TOOL_CALL_START:
174
+ return {
175
+ ...e,
176
+ items: [
177
+ ...e.items,
178
+ { kind: "tool", id: t.toolCallId, name: t.toolCallName, args: "", subagent: n }
179
+ ]
180
+ };
181
+ case C.TOOL_CALL_ARGS:
182
+ return B(e, t.toolCallId, "tool", (s) => ({ ...s, args: s.args + t.delta }));
183
+ case C.TOOL_CALL_RESULT:
184
+ return B(e, t.toolCallId, "tool", (s) => {
185
+ var i;
186
+ return {
187
+ ...s,
188
+ result: J(t.content),
189
+ isError: ((i = t.metadata) == null ? void 0 : i.isError) === !0
190
+ };
191
+ });
192
+ case C.RUN_FINISHED: {
193
+ const s = me(t.outcome), i = new Map(s.map((c) => [c.toolCallId, c]));
194
+ return {
195
+ ...e,
196
+ items: s.length ? e.items.map(
197
+ (c) => c.kind === "tool" && i.has(c.id) ? { ...c, interrupt: i.get(c.id) } : c
198
+ ) : e.items,
199
+ status: "idle",
200
+ runId: void 0,
201
+ waking: void 0,
202
+ interrupts: s.length ? s : void 0
203
+ };
204
+ }
205
+ case C.RUN_ERROR:
206
+ return {
207
+ ...e,
208
+ items: t.code === "cancelled" ? e.items : [
209
+ ...e.items,
210
+ {
211
+ kind: "error",
212
+ id: `error-${e.runId ?? e.items.length}`,
213
+ text: t.message
214
+ }
215
+ ],
216
+ status: "idle",
217
+ runId: void 0,
218
+ waking: void 0
219
+ };
220
+ default:
221
+ return e;
222
+ }
223
+ }
224
+ class U extends Error {
225
+ constructor(n, r) {
226
+ super(typeof r.error == "string" ? r.error : `HTTP ${n}`);
227
+ F(this, "status");
228
+ F(this, "body");
229
+ this.status = n, this.body = r;
230
+ }
231
+ }
232
+ const W = 100 * 1024 * 1024, Y = 20, ye = "zenera", he = 3;
233
+ async function K(e, t) {
234
+ if (!e.body) return;
235
+ const n = e.body.pipeThrough(new TextDecoderStream()).getReader();
236
+ let r = "";
237
+ for (; ; ) {
238
+ const { done: o, value: a } = await n.read();
239
+ if (o) break;
240
+ r += a.replace(/\r\n/g, `
241
+ `);
242
+ for (let u = r.indexOf(`
243
+
244
+ `); u >= 0; u = r.indexOf(`
245
+
246
+ `)) {
247
+ const s = r.slice(0, u);
248
+ r = r.slice(u + 2);
249
+ const i = s.split(`
250
+ `).filter((c) => c.startsWith("data:")).map((c) => c.slice(5).trimStart()).join(`
251
+ `);
252
+ i && t(JSON.parse(i));
253
+ }
254
+ }
255
+ }
256
+ function ge(e) {
257
+ const t = e.split("/")[0];
258
+ return t === "image" || t === "audio" || t === "video" ? t : "document";
259
+ }
260
+ function we(e, t = []) {
261
+ return t.length ? [
262
+ ...e ? [{ type: "text", text: e }] : [],
263
+ ...t.map((n) => ({
264
+ type: ge(n.mimeType),
265
+ source: { type: "file", value: n.id, provider: ye },
266
+ metadata: { name: n.name, size: n.size }
267
+ }))
268
+ ] : e;
269
+ }
270
+ function ve(e, t, n, r, o, a) {
271
+ return typeof XMLHttpRequest > "u" ? e(t, { method: "POST", headers: r, body: n, signal: a }).then(async (u) => (o == null || o(n.size, n.size), {
272
+ status: u.status,
273
+ body: await u.json().catch(() => ({})),
274
+ retryAfter: u.headers.get("Retry-After")
275
+ })) : new Promise((u, s) => {
276
+ const i = new XMLHttpRequest();
277
+ if (i.open("POST", t), r.forEach((c, l) => i.setRequestHeader(l, c)), i.upload.onprogress = (c) => o == null ? void 0 : o(c.loaded, c.lengthComputable ? c.total : n.size), i.onload = () => {
278
+ let c = {};
279
+ try {
280
+ c = JSON.parse(i.responseText);
281
+ } catch {
282
+ }
283
+ u({ status: i.status, body: c, retryAfter: i.getResponseHeader("Retry-After") });
284
+ }, i.onerror = () => s(new Error("the upload failed: the connection was lost")), i.onabort = () => s(new DOMException("the upload was cancelled", "AbortError")), a == null || a.addEventListener("abort", () => i.abort(), { once: !0 }), a != null && a.aborted) {
285
+ i.abort();
286
+ return;
287
+ }
288
+ i.send(n);
289
+ });
290
+ }
291
+ const Te = (e, t) => new Promise((n, r) => {
292
+ const o = setTimeout(n, e);
293
+ t == null || t.addEventListener(
294
+ "abort",
295
+ () => {
296
+ clearTimeout(o), r(new DOMException("the upload was cancelled", "AbortError"));
297
+ },
298
+ { once: !0 }
299
+ );
300
+ });
301
+ function ie(e, t, n, r = {}) {
302
+ const o = (s) => `${e}/${encodeURIComponent(s)}`, a = async (s, i = {}) => {
303
+ const c = typeof n == "function" ? await n() : n, l = new Headers(c);
304
+ return new Headers(i.headers).forEach((y, m) => l.set(m, y)), (t ?? fetch)(s, { ...i, headers: l });
305
+ }, u = async (s, i) => {
306
+ const c = await a(s, i), l = await c.json().catch(() => ({}));
307
+ if (!c.ok) throw new U(c.status, l);
308
+ return l;
309
+ };
310
+ return {
311
+ listThreads: async () => {
312
+ const s = await u(e);
313
+ return r.threads ? { threads: r.threads(s) } : s;
314
+ },
315
+ createThread: r.create ?? ((s) => u(e, {
316
+ method: "POST",
317
+ headers: { "Content-Type": "application/json" },
318
+ body: JSON.stringify(s ? { title: s } : {})
319
+ })),
320
+ loadThread: (s) => u(o(s)),
321
+ deleteThread: (s) => u(o(s), { method: "DELETE" }),
322
+ cancel: (s, i) => u(`${o(s)}/runs/${encodeURIComponent(i)}/cancel`, {
323
+ method: "POST"
324
+ }),
325
+ ...r.interrupts !== void 0 && {
326
+ interrupt: (s) => u(`${r.interrupts}/${encodeURIComponent(s)}`),
327
+ cancelInterrupt: (s) => u(`${r.interrupts}/${encodeURIComponent(s)}/cancel`, {
328
+ method: "POST"
329
+ })
330
+ },
331
+ async follow(s, i, c, l) {
332
+ const y = await a(
333
+ `${o(s)}/runs/${encodeURIComponent(i)}/events`,
334
+ {
335
+ headers: { Accept: "text/event-stream" },
336
+ signal: l
337
+ }
338
+ );
339
+ if (!y.ok)
340
+ throw new U(y.status, await y.json().catch(() => ({})));
341
+ await K(y, c);
342
+ },
343
+ async run(s, i, c, l) {
344
+ const y = {
345
+ threadId: s,
346
+ runId: i.runId,
347
+ messages: [
348
+ {
349
+ id: i.messageId,
350
+ role: "user",
351
+ content: we(i.text, i.files)
352
+ }
353
+ ],
354
+ tools: [],
355
+ context: [],
356
+ forwardedProps: {}
357
+ }, m = await a(`${o(s)}/runs`, {
358
+ method: "POST",
359
+ headers: { "Content-Type": "application/json", Accept: "text/event-stream" },
360
+ body: JSON.stringify(y),
361
+ signal: l
362
+ });
363
+ if (!m.ok)
364
+ throw new U(m.status, await m.json().catch(() => ({})));
365
+ await K(m, c);
366
+ },
367
+ ...r.uploadHeaders && {
368
+ async upload(s, i, { onProgress: c, signal: l } = {}) {
369
+ const y = i.name || "file", m = new URLSearchParams({ name: y, type: i.type || "" }), I = `${o(s)}/uploads?${m}`;
370
+ for (let N = 0; ; N++) {
371
+ const E = new Headers(await r.uploadHeaders("POST", I));
372
+ E.set("Content-Type", "application/octet-stream");
373
+ const v = await ve(
374
+ t ?? fetch,
375
+ I,
376
+ i,
377
+ E,
378
+ c,
379
+ l
380
+ );
381
+ if (v.status >= 200 && v.status < 300)
382
+ return v.body;
383
+ if (v.status === 503 && N < he) {
384
+ const M = Number(v.retryAfter);
385
+ await Te(
386
+ Math.min(Number.isFinite(M) && M > 0 ? M : 2, 10) * 1e3,
387
+ l
388
+ );
389
+ continue;
390
+ }
391
+ throw new U(v.status, v.body);
392
+ }
393
+ },
394
+ removeUpload: async (s, i) => {
395
+ const c = await a(
396
+ `${o(s)}/uploads/${encodeURIComponent(i)}`,
397
+ { method: "DELETE" }
398
+ );
399
+ if (!c.ok && c.status !== 404)
400
+ throw new U(c.status, await c.json().catch(() => ({})));
401
+ }
402
+ }
403
+ };
404
+ }
405
+ function be(e, { baseUrl: t = "", collection: n = "chats", fetch: r, headers: o } = {}) {
406
+ const a = `${t}/api/projects/${encodeURIComponent(e)}`;
407
+ return ie(`${a}/${n}`, r, o, {
408
+ interrupts: `${a}/interrupts`,
409
+ // The builder chat takes no files.
410
+ ...n !== "meta-chat" && {
411
+ uploadHeaders: async () => typeof o == "function" ? await o() : o ?? {}
412
+ }
413
+ });
414
+ }
415
+ function Ee({
416
+ baseUrl: e,
417
+ token: t,
418
+ fetch: n
419
+ }) {
420
+ const r = async (a, u) => {
421
+ const s = new URL(u, "http://runtime.invalid");
422
+ return `Bearer ${(typeof t == "string" ? t : await t({
423
+ method: a.toUpperCase(),
424
+ path: s.pathname + s.search
425
+ })).trim()}`;
426
+ }, o = async (a, u) => {
427
+ const s = typeof a == "string" ? a : a instanceof URL ? a.href : a.url, i = new Headers(u == null ? void 0 : u.headers);
428
+ return i.set("Authorization", await r((u == null ? void 0 : u.method) ?? "GET", s)), (n ?? fetch)(a, { ...u, headers: i });
429
+ };
430
+ return ie(`${e.replace(/\/+$/, "")}/api/sessions`, o, void 0, {
431
+ uploadHeaders: async (a, u) => ({ Authorization: await r(a, u) }),
432
+ threads: (a) => (a.sessions ?? []).map((u) => ({
433
+ id: u.id,
434
+ projectId: "",
435
+ title: !u.title.trim() || u.title.trim() === u.id ? "New chat" : u.title,
436
+ createdAt: u.createdAt,
437
+ updatedAt: u.updatedAt
438
+ })),
439
+ create: async (a) => {
440
+ const u = (/* @__PURE__ */ new Date()).toISOString();
441
+ return {
442
+ thread: {
443
+ id: crypto.randomUUID(),
444
+ projectId: "",
445
+ title: a ?? "New chat",
446
+ createdAt: u,
447
+ updatedAt: u
448
+ }
449
+ };
450
+ }
451
+ });
452
+ }
453
+ const Se = (e, t) => e.name === t.name && e.size === t.size && e.lastModified === t.lastModified, Ie = (e) => `${Math.round(e / (1024 * 1024))} MB`;
454
+ function Me(e, t, n) {
455
+ const r = !!(e != null && e.upload), [o, a] = x([]), [u, s] = x(null), i = L(/* @__PURE__ */ new Map()), c = L(null), l = L(null), y = O(() => {
456
+ var g;
457
+ for (const w of i.current.values()) (g = w.controller) == null || g.abort();
458
+ i.current.clear(), c.current = null, a([]), s(null);
459
+ }, []);
460
+ G(() => {
461
+ c.current && c.current !== t && y();
462
+ }, [t, y]), G(() => y, [y]);
463
+ const m = (g, w) => a((b) => b.map((S) => S.key === g ? { ...S, ...w } : S)), I = O(
464
+ async (g) => {
465
+ var S;
466
+ const w = i.current.get(g);
467
+ if (!w || !(e != null && e.upload)) return;
468
+ (S = w.controller) == null || S.abort();
469
+ const b = new AbortController();
470
+ w.controller = b, m(g, { status: "uploading", sent: 0, error: void 0 });
471
+ try {
472
+ let d = t ?? c.current;
473
+ if (!d) {
474
+ if (!n) throw new Error("open a chat first");
475
+ l.current ?? (l.current = n().finally(() => l.current = null)), d = await l.current;
476
+ }
477
+ c.current = d;
478
+ const f = await e.upload(d, w.file, {
479
+ signal: b.signal,
480
+ onProgress: (p) => m(g, { sent: p })
481
+ });
482
+ if (b.signal.aborted || !i.current.has(g)) return;
483
+ m(g, { status: "done", sent: f.size, upload: f });
484
+ } catch (d) {
485
+ if (b.signal.aborted) return;
486
+ m(g, { status: "error", error: d.message || "upload failed" });
487
+ }
488
+ },
489
+ [e, t, n]
490
+ ), N = O(
491
+ (g) => {
492
+ if (!(e != null && e.upload)) return;
493
+ const w = [...i.current.values()].map((d) => d.file), b = [], S = [];
494
+ for (const d of g)
495
+ if (!w.some((f) => Se(f, d))) {
496
+ if (w.length + b.length >= Y) {
497
+ S.push(`a message carries at most ${Y} files`);
498
+ break;
499
+ }
500
+ if (d.size > W) {
501
+ S.push(`${d.name} is larger than ${Ie(W)}`);
502
+ continue;
503
+ }
504
+ b.push({ key: crypto.randomUUID(), file: d });
505
+ }
506
+ if (s(S.length ? S.join("; ") : null), !!b.length) {
507
+ for (const { key: d, file: f } of b) i.current.set(d, { file: f });
508
+ a((d) => [
509
+ ...d,
510
+ ...b.map(({ key: f, file: p }) => ({
511
+ key: f,
512
+ name: p.name || "file",
513
+ size: p.size,
514
+ mimeType: p.type || "application/octet-stream",
515
+ status: "uploading",
516
+ sent: 0
517
+ }))
518
+ ]);
519
+ for (const { key: d } of b) I(d);
520
+ }
521
+ },
522
+ [e, I]
523
+ ), E = L(o);
524
+ E.current = o;
525
+ const v = O(
526
+ (g) => {
527
+ var b, S, d;
528
+ (S = (b = i.current.get(g)) == null ? void 0 : b.controller) == null || S.abort(), i.current.delete(g);
529
+ const w = E.current.find((f) => f.key === g);
530
+ w != null && w.upload && c.current && ((d = e == null ? void 0 : e.removeUpload) == null || d.call(e, c.current, w.upload.id).catch(() => {
531
+ })), s(null), a((f) => f.filter((p) => p.key !== g));
532
+ },
533
+ [e]
534
+ ), M = O((g) => void I(g), [I]), j = O(() => {
535
+ const g = o.flatMap((w) => w.status === "done" && w.upload ? [w.upload] : []);
536
+ return i.current.clear(), a([]), s(null), g;
537
+ }, [o]);
538
+ return {
539
+ supported: r,
540
+ files: o,
541
+ notice: u,
542
+ ready: o.every((g) => g.status === "done"),
543
+ add: N,
544
+ remove: v,
545
+ retry: M,
546
+ take: j
547
+ };
548
+ }
549
+ async function Re(e, t) {
550
+ let n = t.text;
551
+ for (const r of e ?? [])
552
+ r.outgoing && (n = await r.outgoing({ ...t, text: n }));
553
+ return n;
554
+ }
555
+ function Q(e, t) {
556
+ let n = t;
557
+ for (const r of [...e ?? []].reverse())
558
+ r.display && (n = r.display(n));
559
+ return n;
560
+ }
561
+ function Ae(e, t) {
562
+ return typeof t == "string" ? Q(e, t) : Array.isArray(t) ? t.flatMap((n) => {
563
+ if ((n == null ? void 0 : n.type) !== "text" || typeof n.text != "string") return [n];
564
+ const r = Q(e, n.text);
565
+ return r ? [{ ...n, text: r }] : [];
566
+ }) : t;
567
+ }
568
+ function ae(e, t) {
569
+ return t.map(
570
+ (n) => n.role === "user" ? { ...n, content: Ae(e, n.content) } : n
571
+ );
572
+ }
573
+ function q(e, t) {
574
+ var n;
575
+ return t.type !== C.RUN_STARTED || !((n = t.input) != null && n.messages) ? t : {
576
+ ...t,
577
+ input: { ...t.input, messages: ae(e, t.input.messages) }
578
+ };
579
+ }
580
+ function _e(e, t) {
581
+ const n = () => typeof t == "function" ? t() : t, r = Object.create(e);
582
+ return r.loadThread = async (o) => {
583
+ const a = await e.loadThread(o), u = n();
584
+ return {
585
+ ...a,
586
+ messages: ae(u, a.messages ?? []),
587
+ events: (a.events ?? []).map((s) => q(u, s))
588
+ };
589
+ }, r.follow = (o, a, u, s) => e.follow(o, a, (i) => u(q(n(), i)), s), r.run = async (o, a, u, s) => {
590
+ const i = n(), c = await Re(i, {
591
+ text: a.text,
592
+ threadId: o,
593
+ files: a.files ?? []
594
+ });
595
+ return e.run(
596
+ o,
597
+ { ...a, text: c },
598
+ (l) => u(q(i, l)),
599
+ s
600
+ );
601
+ }, r;
602
+ }
603
+ function ke(e, { tag: t = "app_context", withFilesOnly: n = !1 } = {}) {
604
+ const r = `<${t}>`, o = `</${t}>`, a = (u) => u.split(o).join("").split(r).join("");
605
+ return {
606
+ async outgoing({ text: u }) {
607
+ if (!u && !n) return u;
608
+ const s = Object.entries(typeof e == "function" ? await e() : e).filter(([, c]) => c != null && String(c) !== "").map(([c, l]) => `${a(c)} = ${a(String(l))}`);
609
+ if (!s.length) return u;
610
+ const i = `${r}
611
+ ${s.join(`
612
+ `)}
613
+ ${o}`;
614
+ return u ? `${u}
615
+
616
+ ${i}` : i;
617
+ },
618
+ display(u) {
619
+ const s = u.trimEnd();
620
+ if (!s.endsWith(o)) return u;
621
+ const i = s.lastIndexOf(`${r}
622
+ `);
623
+ return i < 0 ? u : i === 0 ? "" : s.slice(i - 2, i) !== `
624
+
625
+ ` ? u : s.slice(0, i - 2);
626
+ }
627
+ };
628
+ }
629
+ const Z = 5e3, ee = [1e3, 2e3, 5e3, 1e4, 3e4], Ce = 3e3;
630
+ function te(e, t) {
631
+ return new Promise((n) => {
632
+ const r = () => {
633
+ document.visibilityState === "visible" && o();
634
+ }, o = () => {
635
+ clearTimeout(a), window.removeEventListener("online", o), document.removeEventListener("visibilitychange", r), t.removeEventListener("abort", o), n();
636
+ }, a = setTimeout(o, e);
637
+ window.addEventListener("online", o), document.addEventListener("visibilitychange", r), t.addEventListener("abort", o);
638
+ });
639
+ }
640
+ function Ue(e, { baseUrl: t, collection: n, fetch: r, headers: o } = {}) {
641
+ return ne(
642
+ () => e ? be(e, { baseUrl: t, collection: n, fetch: r, headers: o }) : null,
643
+ [e, t, n, r, o]
644
+ );
645
+ }
646
+ function Ne({
647
+ baseUrl: e,
648
+ token: t,
649
+ fetch: n
650
+ }) {
651
+ return ne(
652
+ () => Ee({ baseUrl: e, token: t, fetch: n }),
653
+ [e, t, n]
654
+ );
655
+ }
656
+ function je(e, t) {
657
+ const [n, r] = x(V), [o, a] = x(null), [u, s] = x(!1), [i, c] = x({}), l = L(() => {
658
+ }), y = L(/* @__PURE__ */ new Set()), m = L(null), I = L(0), N = L([]);
659
+ N.current = n.items;
660
+ const E = L(void 0);
661
+ E.current = n.runId;
662
+ const v = O(
663
+ async (d, f, p, T, $) => {
664
+ var D;
665
+ (D = m.current) == null || D.abort();
666
+ const h = new AbortController();
667
+ m.current = h;
668
+ let R = !1;
669
+ for (let A = 0; !h.signal.aborted && !R; A++) {
670
+ let z = A > 0 || !$;
671
+ const _ = (k) => {
672
+ (k.type === C.RUN_FINISHED || k.type === C.RUN_ERROR) && (R = !0);
673
+ const H = z;
674
+ z = !1, r((P) => oe(H ? { ...P, items: T } : P, k)), s(!1), a(null);
675
+ };
676
+ try {
677
+ await (z ? d.follow(f, p, _, h.signal) : $(_, h.signal));
678
+ } catch (k) {
679
+ if (h.signal.aborted) break;
680
+ if (k instanceof U && k.status === 503) {
681
+ a(String(k.body.podStatus ?? "starting")), await te(Z, h.signal);
682
+ continue;
683
+ }
684
+ if (k instanceof U) {
685
+ const H = k.status === 404 ? await d.loadThread(f).catch(() => null) : null, P = H ? X(H.messages, H.events) : null;
686
+ r((ue) => ({
687
+ ...ue,
688
+ ...P ? { items: P.items, interrupts: P.interrupts } : {},
689
+ status: "idle",
690
+ runId: void 0,
691
+ waking: void 0,
692
+ error: H ? void 0 : k.message
693
+ }));
694
+ break;
695
+ }
696
+ }
697
+ if (R || h.signal.aborted) break;
698
+ s(!0), await te(ee[Math.min(A, ee.length - 1)], h.signal);
699
+ }
700
+ m.current === h && (m.current = null, s(!1));
701
+ },
702
+ []
703
+ ), M = O(
704
+ (d, f, p) => {
705
+ const T = X(p.messages, p.events);
706
+ p.running ? (r({
707
+ items: T.items,
708
+ status: "running",
709
+ runId: p.running.runId
710
+ }), v(d, f, p.running.runId, T.items)) : r(T);
711
+ },
712
+ [v]
713
+ );
714
+ G(() => {
715
+ var $;
716
+ if (($ = m.current) == null || $.abort(), m.current = null, a(null), s(!1), !e || !t) {
717
+ r({ items: [], status: "idle" });
718
+ return;
719
+ }
720
+ r(V), c({}), y.current = /* @__PURE__ */ new Set();
721
+ let d = !1, f;
722
+ const p = I.current, T = async () => {
723
+ try {
724
+ const h = await e.loadThread(t);
725
+ if (d || m.current || I.current !== p) return;
726
+ a(null), M(e, t, h);
727
+ } catch (h) {
728
+ if (d) return;
729
+ if (h instanceof U && h.status === 503) {
730
+ a(String(h.body.podStatus ?? "starting")), f = setTimeout(T, Z);
731
+ return;
732
+ }
733
+ r({ items: [], status: "idle", error: h.message });
734
+ }
735
+ };
736
+ return T(), () => {
737
+ var h;
738
+ d = !0, clearTimeout(f), (h = m.current) == null || h.abort();
739
+ };
740
+ }, [e, t, v, M]);
741
+ const j = n.status === "idle" ? n.interrupts : void 0;
742
+ G(() => {
743
+ const d = e == null ? void 0 : e.interrupt;
744
+ if (!e || !t || !(j != null && j.length) || !d) return;
745
+ let f = !1, p = !1, T;
746
+ const $ = /* @__PURE__ */ new Set(), h = async () => {
747
+ if (f || p) return;
748
+ p = !0, clearTimeout(T);
749
+ try {
750
+ for (const A of j) {
751
+ if ($.has(A.id) || y.current.has(A.id)) continue;
752
+ let z;
753
+ try {
754
+ z = await d(A.id);
755
+ } catch (_) {
756
+ _ instanceof U && _.status === 404 && $.add(A.id);
757
+ continue;
758
+ }
759
+ if (f) return;
760
+ if (c((_) => ({ ..._, [A.id]: z })), z.status !== "pending" && z.resumeState !== "queued") {
761
+ y.current.add(A.id);
762
+ const _ = await e.loadThread(t).catch(() => null);
763
+ if (f || m.current) return;
764
+ if (_) {
765
+ M(e, t, _);
766
+ return;
767
+ }
768
+ }
769
+ }
770
+ } finally {
771
+ p = !1;
772
+ }
773
+ const D = j.filter((A) => !$.has(A.id) && !y.current.has(A.id));
774
+ !f && D.length && (T = setTimeout(h, Ce));
775
+ }, R = () => {
776
+ document.visibilityState === "visible" && h();
777
+ };
778
+ return l.current = () => void h(), h(), window.addEventListener("focus", R), document.addEventListener("visibilitychange", R), () => {
779
+ f = !0, clearTimeout(T), l.current = () => {
780
+ }, window.removeEventListener("focus", R), document.removeEventListener("visibilitychange", R);
781
+ };
782
+ }, [e, t, j, M]);
783
+ const g = O(
784
+ async (d) => {
785
+ if (!(e != null && e.cancelInterrupt)) return;
786
+ const f = await e.cancelInterrupt(d);
787
+ c((p) => ({ ...p, [d]: f })), l.current();
788
+ },
789
+ [e]
790
+ ), w = O(() => l.current(), []), b = O(
791
+ async (d, f = []) => {
792
+ const p = d.trim();
793
+ if (!e || !t || !p && !f.length || m.current) return;
794
+ I.current++;
795
+ const T = crypto.randomUUID(), $ = N.current, h = f.map(({ name: R, size: D, mimeType: A }) => ({ name: R, size: D, mimeType: A }));
796
+ r((R) => ({
797
+ ...R,
798
+ items: [
799
+ ...R.items,
800
+ {
801
+ kind: "user",
802
+ id: T,
803
+ text: p,
804
+ runId: T,
805
+ ...h.length && { attachments: h }
806
+ }
807
+ ],
808
+ status: "running",
809
+ runId: T,
810
+ error: void 0
811
+ })), await v(
812
+ e,
813
+ t,
814
+ T,
815
+ $,
816
+ (R, D) => e.run(
817
+ t,
818
+ { runId: T, messageId: T, text: p, files: f },
819
+ R,
820
+ D
821
+ )
822
+ );
823
+ },
824
+ [e, t, v]
825
+ ), S = O(() => {
826
+ !e || !t || !E.current || e.cancel(t, E.current).catch((d) => {
827
+ var f;
828
+ d instanceof U && d.status === 404 ? ((f = m.current) == null || f.abort(), r((p) => ({ ...p, status: "idle", runId: void 0, waking: void 0 }))) : r((p) => ({ ...p, error: `Could not stop: ${d.message}` }));
829
+ });
830
+ }, [e, t]);
831
+ return {
832
+ ...n,
833
+ starting: o ?? n.waking ?? null,
834
+ reconnecting: u,
835
+ send: b,
836
+ cancel: S,
837
+ interruptInfo: i,
838
+ cancelInterrupt: g,
839
+ refreshInterrupts: w
840
+ };
841
+ }
842
+ function De(e, t) {
843
+ const [n, r] = x([]), [o, a] = x(!1), [u, s] = x(null), [i, c] = x(!1), [l, y] = x(0), m = L(0);
844
+ G(() => {
845
+ r([]), s(null);
846
+ }, [e]), G(() => {
847
+ const E = ++m.current;
848
+ if (!e) {
849
+ a(!1);
850
+ return;
851
+ }
852
+ return a(!0), e.listThreads().then(({ threads: v }) => {
853
+ E === m.current && (r(v), s(null));
854
+ }).catch((v) => {
855
+ E === m.current && s(v instanceof Error ? v.message : "Could not load the chats");
856
+ }).finally(() => {
857
+ E === m.current && a(!1);
858
+ }), () => {
859
+ m.current++;
860
+ };
861
+ }, [e, t, l]);
862
+ const I = O(() => y((E) => E + 1), []), N = O(
863
+ async (E) => {
864
+ if (e) {
865
+ c(!0);
866
+ try {
867
+ await e.deleteThread(E);
868
+ } finally {
869
+ c(!1), I();
870
+ }
871
+ }
872
+ },
873
+ [e, I]
874
+ );
875
+ return { threads: n, loading: o, error: u, removing: i, refresh: I, remove: N };
876
+ }
877
+ export {
878
+ U as C,
879
+ Y as M,
880
+ W as a,
881
+ ke as b,
882
+ re as c,
883
+ be as d,
884
+ Ee as e,
885
+ Q as f,
886
+ V as g,
887
+ xe as h,
888
+ fe as i,
889
+ X as j,
890
+ oe as k,
891
+ je as l,
892
+ we as m,
893
+ Ue as n,
894
+ Ne as o,
895
+ De as p,
896
+ K as r,
897
+ Me as u,
898
+ _e as w
899
+ };