@fencyai/react 0.1.110 → 0.1.111

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.js CHANGED
@@ -1,212 +1,47 @@
1
- import { createAgentTask as q, createFileDownloadLink as G, AgentTaskProgressItemType as O, createStream as V } from "@fencyai/js";
2
- import { createContext as X, useContext as Y, useState as T, useEffect as x, useMemo as B, useCallback as D, useRef as F } from "react";
3
- import { jsxs as I, jsx as g } from "react/jsx-runtime";
4
- import { motion as C, useInView as J, AnimatePresence as _ } from "motion/react";
1
+ import { createAgentTask as X, createFileDownloadLink as V, AgentTaskProgressItemType as O, createStream as Y } from "@fencyai/js";
2
+ import { createContext as J, useContext as Q, useState as v, useRef as E, useEffect as T, useCallback as M, useMemo as H } from "react";
3
+ import { jsxs as x, jsx as f } from "react/jsx-runtime";
4
+ import { motion as P, useInView as Z, AnimatePresence as B } from "motion/react";
5
5
  import W from "react-markdown";
6
6
  import { Prism as j } from "react-syntax-highlighter";
7
7
  import L from "remark-gfm";
8
- import './assets/index.css';const $ = X(
8
+ import './assets/index.css';const $ = J(
9
9
  void 0
10
10
  );
11
- function R() {
12
- const e = Y($);
11
+ function F() {
12
+ const e = Q($);
13
13
  if (e === void 0)
14
14
  throw new Error("useFencyContext must be used within a FencyProvider");
15
15
  return e;
16
16
  }
17
- async function Q(e, t) {
18
- const o = e.getReader();
19
- let i;
20
- for (; !(i = await o.read()).done; )
21
- t(i.value);
22
- }
23
- function Z(e) {
24
- let t, o, i, s = !1;
25
- return function(u) {
26
- t === void 0 ? (t = u, o = 0, i = -1) : t = ee(t, u);
27
- const a = t.length;
28
- let n = 0;
29
- for (; o < a; ) {
30
- s && (t[o] === 10 && (n = ++o), s = !1);
31
- let d = -1;
32
- for (; o < a && d === -1; ++o)
33
- switch (t[o]) {
34
- case 58:
35
- i === -1 && (i = o - n);
36
- break;
37
- case 13:
38
- s = !0;
39
- case 10:
40
- d = o;
41
- break;
42
- }
43
- if (d === -1)
44
- break;
45
- e(t.subarray(n, d), i), n = o, i = -1;
46
- }
47
- n === a ? t = void 0 : n !== 0 && (t = t.subarray(n), o -= n);
48
- };
49
- }
50
- function p(e, t, o) {
51
- let i = z();
52
- const s = new TextDecoder();
53
- return function(u, a) {
54
- if (u.length === 0)
55
- o == null || o(i), i = z();
56
- else if (a > 0) {
57
- const n = s.decode(u.subarray(0, a)), d = a + (u[a + 1] === 32 ? 2 : 1), l = s.decode(u.subarray(d));
58
- switch (n) {
59
- case "data":
60
- i.data = i.data ? i.data + `
61
- ` + l : l;
62
- break;
63
- case "event":
64
- i.event = l;
65
- break;
66
- case "id":
67
- e(i.id = l);
68
- break;
69
- case "retry":
70
- const c = parseInt(l, 10);
71
- isNaN(c) || t(i.retry = c);
72
- break;
73
- }
74
- }
75
- };
76
- }
77
- function ee(e, t) {
78
- const o = new Uint8Array(e.length + t.length);
79
- return o.set(e), o.set(t, e.length), o;
80
- }
81
- function z() {
82
- return {
83
- data: "",
84
- event: "",
85
- id: "",
86
- retry: void 0
87
- };
88
- }
89
- var te = function(e, t) {
90
- var o = {};
91
- for (var i in e) Object.prototype.hasOwnProperty.call(e, i) && t.indexOf(i) < 0 && (o[i] = e[i]);
92
- if (e != null && typeof Object.getOwnPropertySymbols == "function")
93
- for (var s = 0, i = Object.getOwnPropertySymbols(e); s < i.length; s++)
94
- t.indexOf(i[s]) < 0 && Object.prototype.propertyIsEnumerable.call(e, i[s]) && (o[i[s]] = e[i[s]]);
95
- return o;
96
- };
97
- const U = "text/event-stream", ne = 1e3, H = "last-event-id";
98
- function re(e, t) {
99
- var { signal: o, headers: i, onopen: s, onmessage: m, onclose: u, onerror: a, openWhenHidden: n, fetch: d } = t, l = te(t, ["signal", "headers", "onopen", "onmessage", "onclose", "onerror", "openWhenHidden", "fetch"]);
100
- return new Promise((c, r) => {
101
- const f = Object.assign({}, i);
102
- f.accept || (f.accept = U);
103
- let h;
104
- function b() {
105
- h.abort(), document.hidden || A();
106
- }
107
- n || document.addEventListener("visibilitychange", b);
108
- let w = ne, y = 0;
109
- function k() {
110
- document.removeEventListener("visibilitychange", b), window.clearTimeout(y), h.abort();
111
- }
112
- o == null || o.addEventListener("abort", () => {
113
- k(), c();
114
- });
115
- const v = d ?? window.fetch, E = s ?? oe;
116
- async function A() {
117
- var P;
118
- h = new AbortController();
119
- try {
120
- const N = await v(e, Object.assign(Object.assign({}, l), { headers: f, signal: h.signal }));
121
- await E(N), await Q(N.body, Z(p((S) => {
122
- S ? f[H] = S : delete f[H];
123
- }, (S) => {
124
- w = S;
125
- }, m))), u == null || u(), k(), c();
126
- } catch (N) {
127
- if (!h.signal.aborted)
128
- try {
129
- const S = (P = a == null ? void 0 : a(N)) !== null && P !== void 0 ? P : w;
130
- window.clearTimeout(y), y = window.setTimeout(A, S);
131
- } catch (S) {
132
- k(), r(S);
133
- }
134
- }
135
- }
136
- A();
137
- });
138
- }
139
- function oe(e) {
140
- const t = e.headers.get("content-type");
141
- if (!(t != null && t.startsWith(U)))
142
- throw new Error(`Expected content-type to be ${U}, Actual: ${t}`);
143
- }
144
- function ae(e) {
145
- const [t, o] = T(null);
146
- return x(() => {
147
- if (!t)
148
- return;
149
- const i = new AbortController();
150
- return re(t, {
151
- headers: e == null ? void 0 : e.headers,
152
- signal: i.signal,
153
- async onopen(s) {
154
- if (!s.ok && s.status >= 400 && s.status < 500 && s.status !== 429)
155
- throw new Error(`Client error ${s.status}`);
156
- },
157
- onmessage(s) {
158
- s.data && (e == null || e.onMessage({
159
- url: t,
160
- data: ie(s.data)
161
- }));
162
- },
163
- onerror(s) {
164
- throw console.error("EventSource error:", s), e == null || e.onError(t), o(null), s;
165
- },
166
- onclose() {
167
- }
168
- }), () => {
169
- i.abort();
170
- };
171
- }, [t, e == null ? void 0 : e.headers]), {
172
- setSourceUrl: o,
173
- sourceUrl: t
174
- };
175
- }
176
- function ie(e) {
177
- const t = atob(e), o = new Uint8Array(t.length);
178
- for (let i = 0; i < t.length; i++)
179
- o[i] = t.charCodeAt(i);
180
- return new TextDecoder("utf-8").decode(o);
181
- }
182
- const se = (e) => {
17
+ const p = (e) => {
183
18
  try {
184
19
  const t = JSON.parse(e);
185
- return ce(t);
20
+ return ee(t);
186
21
  } catch (t) {
187
22
  return console.error("Error parsing message:", t), null;
188
23
  }
189
- }, ce = (e) => {
24
+ }, ee = (e) => {
190
25
  if (!(typeof e == "object" && e !== null && "type" in e && "streamId" in e && "timestamp" in e))
191
26
  return null;
192
27
  switch (e.type) {
193
28
  case "StreamTimeout":
194
- return le(e);
29
+ return te(e);
195
30
  case "StreamNotFound":
196
- return de(e);
31
+ return ne(e);
197
32
  case "AgentTaskProgressItemUpdated":
198
- return ue(e);
33
+ return re(e);
199
34
  }
200
35
  return null;
201
- }, le = (e) => ({
36
+ }, te = (e) => ({
202
37
  type: "StreamTimeout",
203
38
  streamId: e.streamId,
204
39
  timestamp: e.timestamp
205
- }), de = (e) => ({
40
+ }), ne = (e) => ({
206
41
  type: "StreamNotFound",
207
42
  streamId: e.streamId,
208
43
  timestamp: e.timestamp
209
- }), ue = (e) => ({
44
+ }), re = (e) => ({
210
45
  type: "AgentTaskProgressItemUpdated",
211
46
  streamId: e.streamId,
212
47
  agentTaskId: e.agentTaskId,
@@ -216,196 +51,201 @@ const se = (e) => {
216
51
  createdAt: e.createdAt,
217
52
  response: e.response,
218
53
  progressItemType: e.progressItemType
219
- }), me = (e) => {
220
- const t = R(), [o, i] = T(null), [s, m] = T(null), [u, a] = T(null), n = B(() => {
221
- if (s)
222
- return {
223
- "X-Fency-Publishable-Key": t.fency.publishableKey,
224
- "X-Fency-Stream-Token": s
225
- };
226
- }, [s, t.fency.publishableKey]), d = ae({
227
- headers: n,
228
- onError: (c) => {
229
- var r;
230
- console.error("Stream error:", c), (r = e == null ? void 0 : e.onStreamError) == null || r.call(e, {
231
- streamId: c,
232
- error: {
233
- code: "UnknownError",
234
- message: "Unknown error in useStream"
235
- }
236
- });
237
- },
238
- onMessage: (c) => {
239
- var f, h, b, w, y, k, v, E, A, P;
240
- const r = se(c.data);
241
- if (!r)
242
- return !1;
243
- switch (r.type) {
244
- case "NewChatCompletionStreamChunk":
245
- return (f = e == null ? void 0 : e.onNewChatCompletionStreamChunk) == null || f.call(e, r), !0;
246
- case "ChatCompletionStreamCompleted":
247
- return (h = e == null ? void 0 : e.onChatCompletionStreamCompleted) == null || h.call(e, r), !0;
248
- case "StreamTimeout":
249
- return (b = e == null ? void 0 : e.onStreamTimeout) == null || b.call(e, r), !0;
250
- case "StreamNotFound":
251
- return (w = e == null ? void 0 : e.onStreamNotFound) == null || w.call(e, r), !0;
252
- case "FileUploadCompleted":
253
- return (y = e == null ? void 0 : e.onFileUploadCompleted) == null || y.call(e, r), !0;
254
- case "FileTextContentReady":
255
- return (k = e == null ? void 0 : e.onFileTextContentReady) == null || k.call(e, r), !0;
256
- case "WebsiteHtmlContentReady":
257
- return (v = e == null ? void 0 : e.onWebsiteHtmlContentReady) == null || v.call(e, r), !0;
258
- case "WebsiteTextContentReady":
259
- return (E = e == null ? void 0 : e.onWebsiteTextContentReady) == null || E.call(e, r), !0;
260
- case "FileSearchIndexReady":
261
- return (A = e == null ? void 0 : e.onFileSearchIndexReady) == null || A.call(e, r), !0;
262
- case "AgentTaskProgressItemUpdated":
263
- return (P = e == null ? void 0 : e.onAgentTaskProgressItemUpdated) == null || P.call(e, r), !0;
54
+ }), oe = (e) => {
55
+ const t = F(), [n, o] = v(null), a = E(`subscriber-${Math.random().toString(36).substr(2, 9)}`);
56
+ return T(() => {
57
+ if (!t.eventManager) return;
58
+ const l = {
59
+ onMessage: (r, i) => {
60
+ var s, c, m, b, h, k, y, w, I, C;
61
+ const d = p(r);
62
+ if (d)
63
+ switch (d.type) {
64
+ case "NewChatCompletionStreamChunk":
65
+ (s = e == null ? void 0 : e.onNewChatCompletionStreamChunk) == null || s.call(e, d);
66
+ break;
67
+ case "ChatCompletionStreamCompleted":
68
+ (c = e == null ? void 0 : e.onChatCompletionStreamCompleted) == null || c.call(e, d);
69
+ break;
70
+ case "StreamTimeout":
71
+ (m = e == null ? void 0 : e.onStreamTimeout) == null || m.call(e, d);
72
+ break;
73
+ case "StreamNotFound":
74
+ (b = e == null ? void 0 : e.onStreamNotFound) == null || b.call(e, d);
75
+ break;
76
+ case "FileUploadCompleted":
77
+ (h = e == null ? void 0 : e.onFileUploadCompleted) == null || h.call(e, d);
78
+ break;
79
+ case "FileTextContentReady":
80
+ (k = e == null ? void 0 : e.onFileTextContentReady) == null || k.call(e, d);
81
+ break;
82
+ case "WebsiteHtmlContentReady":
83
+ (y = e == null ? void 0 : e.onWebsiteHtmlContentReady) == null || y.call(e, d);
84
+ break;
85
+ case "WebsiteTextContentReady":
86
+ (w = e == null ? void 0 : e.onWebsiteTextContentReady) == null || w.call(e, d);
87
+ break;
88
+ case "FileSearchIndexReady":
89
+ (I = e == null ? void 0 : e.onFileSearchIndexReady) == null || I.call(e, d);
90
+ break;
91
+ case "AgentTaskProgressItemUpdated":
92
+ (C = e == null ? void 0 : e.onAgentTaskProgressItemUpdated) == null || C.call(e, d);
93
+ break;
94
+ }
95
+ },
96
+ onError: (r) => {
97
+ var i;
98
+ (i = e == null ? void 0 : e.onStreamError) == null || i.call(e, {
99
+ streamId: r,
100
+ error: {
101
+ code: "UnknownError",
102
+ message: "Unknown error in useStream"
103
+ }
104
+ });
264
105
  }
265
- }
266
- });
267
- return x(() => {
268
- u && s && o && (d.setSourceUrl(u), a(null));
269
- }, [u, s, o]), {
106
+ };
107
+ return t.eventManager.subscribe(
108
+ a.current,
109
+ l
110
+ );
111
+ }, [t.eventManager, e]), {
270
112
  createStream: async () => {
271
113
  try {
272
- const c = await t.getOrCreateStream(e.fetchTokens, 3e4);
273
- i(c), m(c.token);
274
- const r = `${t.fency.baseUrl}/sse/streams/${c.id}`;
275
- return a(r), {
114
+ const l = await t.getOrCreateStream(e.fetchTokens, 3e4);
115
+ return o(l), {
276
116
  type: "success",
277
- stream: c
117
+ stream: l
278
118
  };
279
- } catch (c) {
119
+ } catch (l) {
280
120
  return {
281
121
  type: "error",
282
122
  error: {
283
123
  code: "UnknownError",
284
- message: c instanceof Error ? c.message : "Failed to create stream"
124
+ message: l instanceof Error ? l.message : "Failed to create stream"
285
125
  }
286
126
  };
287
127
  }
288
128
  },
289
- stream: o
129
+ stream: n
290
130
  };
291
- }, Ce = (e) => {
292
- const t = R(), [o, i] = T([]), { createStream: s } = me({
131
+ }, Ee = (e) => {
132
+ const t = F(), [n, o] = v([]), a = E(/* @__PURE__ */ new Set()), { createStream: g } = oe({
293
133
  fetchTokens: e.fetchCreateStreamTokens,
294
- onAgentTaskProgressItemUpdated: (a) => {
295
- var n;
296
- (n = e.onAgentTaskProgressItemUpdated) == null || n.call(e, a), i((d) => {
297
- const l = d.find(
298
- (r) => r.streamId === a.streamId
134
+ onAgentTaskProgressItemUpdated: (r) => {
135
+ var i;
136
+ a.current.has(r.agentTaskId) && ((i = e.onAgentTaskProgressItemUpdated) == null || i.call(e, r), o((d) => {
137
+ const s = d.find(
138
+ (m) => m.streamId === r.streamId
299
139
  );
300
- return l ? l.progressItems.map(
301
- (r) => r.progressItemId
302
- ).includes(a.progressItemId) ? [
303
- ...d.filter((r) => r.streamId !== a.streamId),
140
+ return s ? s.progressItems.map(
141
+ (m) => m.progressItemId
142
+ ).includes(r.progressItemId) ? [
143
+ ...d.filter((m) => m.streamId !== r.streamId),
304
144
  {
305
- ...l,
306
- progressItems: l.progressItems.map(
307
- (r) => r.progressItemId === a.progressItemId ? a : r
145
+ ...s,
146
+ progressItems: s.progressItems.map(
147
+ (m) => m.progressItemId === r.progressItemId ? r : m
308
148
  )
309
149
  }
310
150
  ] : [
311
151
  ...d.filter(
312
- (r) => r.streamId !== a.streamId
152
+ (m) => m.streamId !== r.streamId
313
153
  ),
314
154
  {
315
- ...l,
155
+ ...s,
316
156
  progressItems: [
317
- ...l.progressItems,
318
- a
157
+ ...s.progressItems,
158
+ r
319
159
  ]
320
160
  }
321
161
  ] : d;
322
- });
162
+ }));
323
163
  },
324
- onStreamError: (a) => {
325
- var n;
326
- (n = e == null ? void 0 : e.onStreamError) == null || n.call(e, a), i((d) => {
327
- const l = d.find((c) => c.streamId === a.streamId);
328
- return l ? [
329
- ...d.filter((c) => c.streamId !== a.streamId),
164
+ onStreamError: (r) => {
165
+ var i;
166
+ (i = e == null ? void 0 : e.onStreamError) == null || i.call(e, r), o((d) => {
167
+ const s = d.find((c) => c.streamId === r.streamId);
168
+ return s ? [
169
+ ...d.filter((c) => c.streamId !== r.streamId),
330
170
  {
331
- ...l,
171
+ ...s,
332
172
  loading: !1,
333
- error: a.error
173
+ error: r.error
334
174
  }
335
175
  ] : d;
336
176
  });
337
177
  },
338
- onStreamNotFound: (a) => {
339
- var n;
340
- (n = e == null ? void 0 : e.onStreamNotFound) == null || n.call(e, a);
178
+ onStreamNotFound: (r) => {
179
+ var i;
180
+ (i = e == null ? void 0 : e.onStreamNotFound) == null || i.call(e, r);
341
181
  },
342
- onStreamTimeout: (a) => {
343
- var n;
344
- (n = e == null ? void 0 : e.onStreamTimeout) == null || n.call(e, a);
182
+ onStreamTimeout: (r) => {
183
+ var i;
184
+ (i = e == null ? void 0 : e.onStreamTimeout) == null || i.call(e, r);
345
185
  }
346
- }), m = D(
347
- async (a) => {
348
- const n = await s();
349
- if (n.type === "success") {
350
- i([
351
- ...o,
186
+ }), l = M(
187
+ async (r) => {
188
+ const i = await g();
189
+ if (i.type === "success") {
190
+ o([
191
+ ...n,
352
192
  {
353
- streamId: n.stream.id,
193
+ streamId: i.stream.id,
354
194
  triggeredAt: (/* @__PURE__ */ new Date()).toISOString(),
355
195
  data: null,
356
196
  error: null,
357
- prompt: a,
197
+ prompt: r,
358
198
  progressItems: [],
359
199
  loading: !0,
360
200
  doneStreaming: !1
361
201
  }
362
202
  ]);
363
- const { clientToken: d } = await e.fetchClientToken(), l = await q({
203
+ const { clientToken: d } = await e.fetchClientToken(), s = await X({
364
204
  pk: t.fency.publishableKey,
365
205
  baseUrl: t.fency.baseUrl,
366
206
  clientToken: d,
367
- streamToken: n.stream.token,
207
+ streamToken: i.stream.token,
368
208
  request: {
369
- streamId: n.stream.id,
370
- queryText: a.queryText,
371
- jsonSchema: a.jsonSchema,
372
- todos: a.todos
209
+ streamId: i.stream.id,
210
+ queryText: r.queryText,
211
+ jsonSchema: r.jsonSchema,
212
+ todos: r.todos
373
213
  }
374
214
  });
375
- if (l.type === "success" && l.agentTask)
376
- return i((c) => [
215
+ if (s.type === "success" && s.agentTask)
216
+ return a.current.add(s.agentTask.id), o((c) => [
377
217
  ...c.filter(
378
- (r) => r.streamId !== n.stream.id
218
+ (m) => m.streamId !== i.stream.id
379
219
  ),
380
220
  {
381
- streamId: n.stream.id,
221
+ streamId: i.stream.id,
382
222
  triggeredAt: (/* @__PURE__ */ new Date()).toISOString(),
383
223
  data: {
384
- id: l.agentTask.id,
385
- createdAt: l.agentTask.createdAt,
386
- streamId: n.stream.id
224
+ id: s.agentTask.id,
225
+ createdAt: s.agentTask.createdAt,
226
+ streamId: i.stream.id
387
227
  },
388
228
  error: null,
389
- prompt: a,
229
+ prompt: r,
390
230
  progressItems: [],
391
231
  doneStreaming: !1,
392
232
  loading: !0
393
233
  }
394
234
  ]), {
395
235
  type: "success",
396
- streamId: n.stream.id,
397
- agentTaskId: l.agentTask.id
236
+ streamId: i.stream.id,
237
+ agentTaskId: s.agentTask.id
398
238
  };
399
- if (l.type === "error")
400
- return i((c) => [
239
+ if (s.type === "error")
240
+ return o((c) => [
401
241
  ...c.filter(
402
- (r) => r.streamId !== n.stream.id
242
+ (m) => m.streamId !== i.stream.id
403
243
  ),
404
244
  {
405
245
  triggeredAt: (/* @__PURE__ */ new Date()).toISOString(),
406
- streamId: n.stream.id,
407
- prompt: a,
408
- error: l.error,
246
+ streamId: i.stream.id,
247
+ prompt: r,
248
+ error: s.error,
409
249
  progressItems: [],
410
250
  loading: !1,
411
251
  doneStreaming: !1,
@@ -413,22 +253,22 @@ const se = (e) => {
413
253
  }
414
254
  ]), {
415
255
  type: "error",
416
- error: l.error
256
+ error: s.error
417
257
  };
418
258
  {
419
259
  const c = {
420
260
  message: "No response received",
421
261
  code: "UnknownError"
422
262
  };
423
- return i((r) => [
424
- ...r.filter(
425
- (f) => f.streamId !== n.stream.id
263
+ return o((m) => [
264
+ ...m.filter(
265
+ (b) => b.streamId !== i.stream.id
426
266
  ),
427
267
  {
428
268
  triggeredAt: (/* @__PURE__ */ new Date()).toISOString(),
429
- streamId: n.stream.id,
269
+ streamId: i.stream.id,
430
270
  error: c,
431
- prompt: a,
271
+ prompt: r,
432
272
  progressItems: [],
433
273
  loading: !1,
434
274
  doneStreaming: !1,
@@ -440,35 +280,202 @@ const se = (e) => {
440
280
  };
441
281
  }
442
282
  } else
443
- return console.error(n.error), n;
283
+ return console.error(i.error), i;
444
284
  },
445
- [t, o, s]
446
- ), u = B(() => o.sort((a, n) => new Date(n.triggeredAt).getTime() - new Date(a.triggeredAt).getTime())[0], [o]);
447
- return {
448
- agentTasks: o,
449
- createAgentTask: m,
285
+ [t, n, g]
286
+ ), u = H(() => n.sort((r, i) => new Date(i.triggeredAt).getTime() - new Date(r.triggeredAt).getTime())[0], [n]);
287
+ return T(() => () => {
288
+ a.current.clear();
289
+ }, []), {
290
+ agentTasks: n,
291
+ createAgentTask: l,
450
292
  latest: u
451
293
  };
452
294
  };
453
- function Ae(e, t) {
454
- const [o, i] = T(
295
+ async function ae(e, t) {
296
+ const n = e.getReader();
297
+ let o;
298
+ for (; !(o = await n.read()).done; )
299
+ t(o.value);
300
+ }
301
+ function ie(e) {
302
+ let t, n, o, a = !1;
303
+ return function(l) {
304
+ t === void 0 ? (t = l, n = 0, o = -1) : t = ce(t, l);
305
+ const u = t.length;
306
+ let r = 0;
307
+ for (; n < u; ) {
308
+ a && (t[n] === 10 && (r = ++n), a = !1);
309
+ let i = -1;
310
+ for (; n < u && i === -1; ++n)
311
+ switch (t[n]) {
312
+ case 58:
313
+ o === -1 && (o = n - r);
314
+ break;
315
+ case 13:
316
+ a = !0;
317
+ case 10:
318
+ i = n;
319
+ break;
320
+ }
321
+ if (i === -1)
322
+ break;
323
+ e(t.subarray(r, i), o), r = n, o = -1;
324
+ }
325
+ r === u ? t = void 0 : r !== 0 && (t = t.subarray(r), n -= r);
326
+ };
327
+ }
328
+ function se(e, t, n) {
329
+ let o = _();
330
+ const a = new TextDecoder();
331
+ return function(l, u) {
332
+ if (l.length === 0)
333
+ n == null || n(o), o = _();
334
+ else if (u > 0) {
335
+ const r = a.decode(l.subarray(0, u)), i = u + (l[u + 1] === 32 ? 2 : 1), d = a.decode(l.subarray(i));
336
+ switch (r) {
337
+ case "data":
338
+ o.data = o.data ? o.data + `
339
+ ` + d : d;
340
+ break;
341
+ case "event":
342
+ o.event = d;
343
+ break;
344
+ case "id":
345
+ e(o.id = d);
346
+ break;
347
+ case "retry":
348
+ const s = parseInt(d, 10);
349
+ isNaN(s) || t(o.retry = s);
350
+ break;
351
+ }
352
+ }
353
+ };
354
+ }
355
+ function ce(e, t) {
356
+ const n = new Uint8Array(e.length + t.length);
357
+ return n.set(e), n.set(t, e.length), n;
358
+ }
359
+ function _() {
360
+ return {
361
+ data: "",
362
+ event: "",
363
+ id: "",
364
+ retry: void 0
365
+ };
366
+ }
367
+ var le = function(e, t) {
368
+ var n = {};
369
+ for (var o in e) Object.prototype.hasOwnProperty.call(e, o) && t.indexOf(o) < 0 && (n[o] = e[o]);
370
+ if (e != null && typeof Object.getOwnPropertySymbols == "function")
371
+ for (var a = 0, o = Object.getOwnPropertySymbols(e); a < o.length; a++)
372
+ t.indexOf(o[a]) < 0 && Object.prototype.propertyIsEnumerable.call(e, o[a]) && (n[o[a]] = e[o[a]]);
373
+ return n;
374
+ };
375
+ const U = "text/event-stream", de = 1e3, z = "last-event-id";
376
+ function q(e, t) {
377
+ var { signal: n, headers: o, onopen: a, onmessage: g, onclose: l, onerror: u, openWhenHidden: r, fetch: i } = t, d = le(t, ["signal", "headers", "onopen", "onmessage", "onclose", "onerror", "openWhenHidden", "fetch"]);
378
+ return new Promise((s, c) => {
379
+ const m = Object.assign({}, o);
380
+ m.accept || (m.accept = U);
381
+ let b;
382
+ function h() {
383
+ b.abort(), document.hidden || A();
384
+ }
385
+ r || document.addEventListener("visibilitychange", h);
386
+ let k = de, y = 0;
387
+ function w() {
388
+ document.removeEventListener("visibilitychange", h), window.clearTimeout(y), b.abort();
389
+ }
390
+ n == null || n.addEventListener("abort", () => {
391
+ w(), s();
392
+ });
393
+ const I = i ?? window.fetch, C = a ?? ue;
394
+ async function A() {
395
+ var R;
396
+ b = new AbortController();
397
+ try {
398
+ const N = await I(e, Object.assign(Object.assign({}, d), { headers: m, signal: b.signal }));
399
+ await C(N), await ae(N.body, ie(se((S) => {
400
+ S ? m[z] = S : delete m[z];
401
+ }, (S) => {
402
+ k = S;
403
+ }, g))), l == null || l(), w(), s();
404
+ } catch (N) {
405
+ if (!b.signal.aborted)
406
+ try {
407
+ const S = (R = u == null ? void 0 : u(N)) !== null && R !== void 0 ? R : k;
408
+ window.clearTimeout(y), y = window.setTimeout(A, S);
409
+ } catch (S) {
410
+ w(), c(S);
411
+ }
412
+ }
413
+ }
414
+ A();
415
+ });
416
+ }
417
+ function ue(e) {
418
+ const t = e.headers.get("content-type");
419
+ if (!(t != null && t.startsWith(U)))
420
+ throw new Error(`Expected content-type to be ${U}, Actual: ${t}`);
421
+ }
422
+ function xe(e) {
423
+ const [t, n] = v(null);
424
+ return T(() => {
425
+ if (!t)
426
+ return;
427
+ const o = new AbortController();
428
+ return q(t, {
429
+ headers: e == null ? void 0 : e.headers,
430
+ signal: o.signal,
431
+ async onopen(a) {
432
+ if (!a.ok && a.status >= 400 && a.status < 500 && a.status !== 429)
433
+ throw new Error(`Client error ${a.status}`);
434
+ },
435
+ onmessage(a) {
436
+ a.data && (e == null || e.onMessage({
437
+ url: t,
438
+ data: G(a.data)
439
+ }));
440
+ },
441
+ onerror(a) {
442
+ throw console.error("EventSource error:", a), e == null || e.onError(t), n(null), a;
443
+ },
444
+ onclose() {
445
+ }
446
+ }), () => {
447
+ o.abort();
448
+ };
449
+ }, [t, e == null ? void 0 : e.headers]), {
450
+ setSourceUrl: n,
451
+ sourceUrl: t
452
+ };
453
+ }
454
+ function G(e) {
455
+ const t = atob(e), n = new Uint8Array(t.length);
456
+ for (let o = 0; o < t.length; o++)
457
+ n[o] = t.charCodeAt(o);
458
+ return new TextDecoder("utf-8").decode(n);
459
+ }
460
+ function Pe(e, t) {
461
+ const [n, o] = v(
455
462
  null
456
- ), [s, m] = T(
463
+ ), [a, g] = v(
457
464
  null
458
- ), u = R(), a = async (c) => {
459
- const r = await c.fetchTokens(), { fetchTokens: f, nextPageToken: h, previousPageToken: b, ...w } = c, y = await e({
460
- pk: u.fency.publishableKey,
461
- clientToken: r.clientToken,
462
- streamToken: r.streamToken,
465
+ ), l = F(), u = async (s) => {
466
+ const c = await s.fetchTokens(), { fetchTokens: m, nextPageToken: b, previousPageToken: h, ...k } = s, y = await e({
467
+ pk: l.fency.publishableKey,
468
+ clientToken: c.clientToken,
469
+ streamToken: c.streamToken,
463
470
  request: {
464
- ...w,
471
+ ...k,
465
472
  limit: (t == null ? void 0 : t.pageSize) ?? 50,
466
473
  pagination: {
467
- nextPageToken: h,
468
- previousPageToken: b
474
+ nextPageToken: b,
475
+ previousPageToken: h
469
476
  }
470
477
  },
471
- baseUrl: u.fency.baseUrl
478
+ baseUrl: l.fency.baseUrl
472
479
  });
473
480
  return y.type === "success" && y.items && y.pagination ? {
474
481
  type: "success",
@@ -487,16 +494,16 @@ function Ae(e, t) {
487
494
  };
488
495
  };
489
496
  return {
490
- fetchFirstPage: async (c) => {
491
- const r = await a({
492
- ...c,
497
+ fetchFirstPage: async (s) => {
498
+ const c = await u({
499
+ ...s,
493
500
  nextPageToken: void 0,
494
501
  previousPageToken: void 0
495
502
  });
496
- return r.type === "success" && (m(r.page), i(c)), r;
503
+ return c.type === "success" && (g(c.page), o(s)), c;
497
504
  },
498
- fetchNextPage: async (c) => {
499
- if (s == null)
505
+ fetchNextPage: async (s) => {
506
+ if (a == null)
500
507
  return {
501
508
  type: "error",
502
509
  error: {
@@ -504,7 +511,7 @@ function Ae(e, t) {
504
511
  message: "No current page"
505
512
  }
506
513
  };
507
- if (s.pagination.nextPageToken == null)
514
+ if (a.pagination.nextPageToken == null)
508
515
  return {
509
516
  type: "error",
510
517
  error: {
@@ -512,15 +519,15 @@ function Ae(e, t) {
512
519
  message: "No next page"
513
520
  }
514
521
  };
515
- const r = await a({
516
- ...c,
517
- nextPageToken: s.pagination.nextPageToken,
522
+ const c = await u({
523
+ ...s,
524
+ nextPageToken: a.pagination.nextPageToken,
518
525
  previousPageToken: void 0
519
526
  });
520
- return r.type === "success" && (m(r.page), i(c)), r;
527
+ return c.type === "success" && (g(c.page), o(s)), c;
521
528
  },
522
- fetchPreviousPage: async (c) => {
523
- if (s == null)
529
+ fetchPreviousPage: async (s) => {
530
+ if (a == null)
524
531
  return {
525
532
  type: "error",
526
533
  error: {
@@ -528,7 +535,7 @@ function Ae(e, t) {
528
535
  message: "No current page"
529
536
  }
530
537
  };
531
- if (s.pagination.previousPageToken == null)
538
+ if (a.pagination.previousPageToken == null)
532
539
  return {
533
540
  type: "error",
534
541
  error: {
@@ -536,21 +543,21 @@ function Ae(e, t) {
536
543
  message: "No previous page"
537
544
  }
538
545
  };
539
- const r = await a({
540
- ...c,
546
+ const c = await u({
547
+ ...s,
541
548
  nextPageToken: void 0,
542
- previousPageToken: s.pagination.previousPageToken
549
+ previousPageToken: a.pagination.previousPageToken
543
550
  });
544
- return r.type === "success" && (m(r.page), i(c)), r;
551
+ return c.type === "success" && (g(c.page), o(s)), c;
545
552
  },
546
- refetchCurrentPage: async () => o == null ? {
553
+ refetchCurrentPage: async () => n == null ? {
547
554
  type: "error",
548
555
  error: {
549
556
  code: "NO_CURRENT_PAGE",
550
557
  message: "No current page, please call fetchFirstPage first."
551
558
  }
552
- } : a(o),
553
- currentPage: s
559
+ } : u(n),
560
+ currentPage: a
554
561
  };
555
562
  }
556
563
  const K = {
@@ -704,83 +711,83 @@ const K = {
704
711
  italic: {
705
712
  fontStyle: "italic"
706
713
  }
707
- }, ge = ({
714
+ }, me = ({
708
715
  markdown: e,
709
716
  streamToken: t,
710
- fetchClientToken: o,
711
- durationSeconds: i
717
+ fetchClientToken: n,
718
+ durationSeconds: o
712
719
  }) => {
713
- const { fency: s } = R(), m = D(
714
- async (u) => {
720
+ const { fency: a } = F(), g = M(
721
+ async (l) => {
715
722
  try {
716
- const { clientToken: a } = await o(), n = await G({
717
- pk: s.publishableKey,
718
- baseUrl: s.baseUrl,
719
- clientToken: a,
723
+ const { clientToken: u } = await n(), r = await V({
724
+ pk: a.publishableKey,
725
+ baseUrl: a.baseUrl,
726
+ clientToken: u,
720
727
  streamToken: t,
721
728
  request: {
722
- fileId: u
729
+ fileId: l
723
730
  }
724
731
  });
725
- n.type === "success" && window.open(n.downloadLink, "_blank");
726
- } catch (a) {
727
- console.error("Failed to download file:", a);
732
+ r.type === "success" && window.open(r.downloadLink, "_blank");
733
+ } catch (u) {
734
+ console.error("Failed to download file:", u);
728
735
  }
729
736
  },
730
- [s, t, o]
737
+ [a, t, n]
731
738
  );
732
- return /* @__PURE__ */ I(
739
+ return /* @__PURE__ */ x(
733
740
  "div",
734
741
  {
735
742
  style: {
736
743
  padding: "16px"
737
744
  },
738
745
  children: [
739
- /* @__PURE__ */ g(
740
- C.div,
746
+ /* @__PURE__ */ f(
747
+ P.div,
741
748
  {
742
749
  className: "fency-markdown-body-raw",
743
750
  initial: { opacity: 0, y: -10 },
744
751
  animate: { opacity: 1, y: 0 },
745
752
  transition: { duration: 0.3, delay: 0 },
746
- children: /* @__PURE__ */ g(
753
+ children: /* @__PURE__ */ f(
747
754
  W,
748
755
  {
749
756
  remarkPlugins: [L],
750
757
  components: {
751
- code(u) {
752
- const { children: a, className: n, node: d, ref: l, ...c } = u, r = /language-(\w+)/.exec(n || "");
753
- return r ? /* @__PURE__ */ g(
758
+ code(l) {
759
+ const { children: u, className: r, node: i, ref: d, ...s } = l, c = /language-(\w+)/.exec(r || "");
760
+ return c ? /* @__PURE__ */ f(
754
761
  j,
755
762
  {
756
- ...c,
763
+ ...s,
757
764
  PreTag: "div",
758
- children: String(a).replace(
765
+ children: String(u).replace(
759
766
  /\n$/,
760
767
  ""
761
768
  ),
762
- language: r[1],
769
+ language: c[1],
763
770
  style: K
764
771
  }
765
- ) : /* @__PURE__ */ g("code", { ...c, className: n, children: String(a) });
772
+ ) : /* @__PURE__ */ f("code", { ...s, className: r, children: String(u) });
766
773
  },
767
- a(u) {
768
- const { children: a, href: n, ...d } = u;
769
- return /* @__PURE__ */ g(
774
+ a(l) {
775
+ const { children: u, href: r, ...i } = l;
776
+ return /* @__PURE__ */ f(
770
777
  "a",
771
778
  {
772
- ...d,
773
- href: n,
774
- onClick: (l) => {
775
- if (!n) return;
776
- const c = n.match(/\/files\/(fil_[a-zA-Z0-9]+)\/download/);
777
- if (c) {
778
- l.preventDefault();
779
- const r = c[1];
780
- m(r);
779
+ ...i,
780
+ href: r,
781
+ onClick: (d) => {
782
+ if (!r) return;
783
+ const s = r.match(/\/files\/(fil_[a-zA-Z0-9]+)\/download/);
784
+ if (s) {
785
+ d.preventDefault();
786
+ const c = s[1];
787
+ g(c);
781
788
  }
782
789
  },
783
- children: a
790
+ children: u
784
791
  }
785
792
  );
786
793
  }
@@ -790,7 +797,7 @@ const K = {
790
797
  )
791
798
  }
792
799
  ),
793
- i !== void 0 && /* @__PURE__ */ I(
800
+ o !== void 0 && /* @__PURE__ */ x(
794
801
  "div",
795
802
  {
796
803
  style: {
@@ -801,7 +808,7 @@ const K = {
801
808
  },
802
809
  children: [
803
810
  "Thought for ",
804
- i,
811
+ o,
805
812
  " seconds"
806
813
  ]
807
814
  }
@@ -810,27 +817,27 @@ const K = {
810
817
  }
811
818
  );
812
819
  };
813
- function M({
820
+ function D({
814
821
  text: e,
815
822
  duration: t = 2,
816
- delay: o = 0,
817
- repeat: i = !0,
818
- repeatDelay: s = 0.5,
819
- className: m,
820
- startOnView: u = !1,
821
- once: a = !1,
822
- inViewMargin: n,
823
- spread: d = 2,
824
- color: l = "#999",
825
- shimmerColor: c = "#000",
826
- direction: r = "fromBottom"
823
+ delay: n = 0,
824
+ repeat: o = !0,
825
+ repeatDelay: a = 0.5,
826
+ className: g,
827
+ startOnView: l = !1,
828
+ once: u = !1,
829
+ inViewMargin: r,
830
+ spread: i = 2,
831
+ color: d = "#999",
832
+ shimmerColor: s = "#000",
833
+ direction: c = "fromBottom"
827
834
  }) {
828
- const f = F(null), h = J(f, { once: a, margin: n }), b = B(() => e.length * d, [e, d]), w = !u || h, y = r === "fromBottom" ? "100% center" : "-100% center", k = r === "fromBottom" ? "0% center" : "200% center";
829
- return /* @__PURE__ */ g(
830
- C.span,
835
+ const m = E(null), b = Z(m, { once: u, margin: r }), h = H(() => e.length * i, [e, i]), k = !l || b, y = c === "fromBottom" ? "100% center" : "-100% center", w = c === "fromBottom" ? "0% center" : "200% center";
836
+ return /* @__PURE__ */ f(
837
+ P.span,
831
838
  {
832
- ref: f,
833
- className: m,
839
+ ref: m,
840
+ className: g,
834
841
  style: {
835
842
  position: "relative",
836
843
  display: "inline-block",
@@ -840,9 +847,9 @@ function M({
840
847
  color: "transparent",
841
848
  WebkitTextFillColor: "transparent",
842
849
  backgroundRepeat: "no-repeat, padding-box",
843
- "--spread": `${b}px`,
844
- "--base-color": l,
845
- "--shimmer-color": c,
850
+ "--spread": `${h}px`,
851
+ "--base-color": d,
852
+ "--shimmer-color": s,
846
853
  "--shimmer-bg": "linear-gradient(90deg, transparent calc(50% - var(--spread)), var(--shimmer-color), transparent calc(50% + var(--spread)))",
847
854
  backgroundImage: "var(--shimmer-bg), linear-gradient(var(--base-color), var(--base-color))"
848
855
  },
@@ -850,41 +857,41 @@ function M({
850
857
  backgroundPosition: y,
851
858
  opacity: 0
852
859
  },
853
- animate: w ? {
854
- backgroundPosition: k,
860
+ animate: k ? {
861
+ backgroundPosition: w,
855
862
  opacity: 1
856
863
  } : {},
857
864
  transition: {
858
865
  backgroundPosition: {
859
- repeat: i ? 1 / 0 : 0,
866
+ repeat: o ? 1 / 0 : 0,
860
867
  duration: t,
861
- delay: o,
862
- repeatDelay: s,
868
+ delay: n,
869
+ repeatDelay: a,
863
870
  ease: "linear"
864
871
  },
865
872
  opacity: {
866
873
  duration: 0.3,
867
- delay: o
874
+ delay: n
868
875
  }
869
876
  },
870
877
  children: e
871
878
  }
872
879
  );
873
880
  }
874
- const fe = ({
881
+ const ge = ({
875
882
  title: e,
876
883
  completed: t,
877
- isLatest: o = !1,
878
- durationSeconds: i
879
- }) => /* @__PURE__ */ I(
884
+ isLatest: n = !1,
885
+ durationSeconds: o
886
+ }) => /* @__PURE__ */ x(
880
887
  "div",
881
888
  {
882
889
  style: {
883
890
  padding: "16px"
884
891
  },
885
892
  children: [
886
- /* @__PURE__ */ g(
887
- C.div,
893
+ /* @__PURE__ */ f(
894
+ P.div,
888
895
  {
889
896
  style: {
890
897
  display: "flex",
@@ -895,8 +902,8 @@ const fe = ({
895
902
  initial: { opacity: 0, y: -10 },
896
903
  animate: { opacity: 1, y: 0 },
897
904
  transition: { duration: 0.3, delay: 0 },
898
- children: o && !i ? /* @__PURE__ */ g(
899
- M,
905
+ children: n && !o ? /* @__PURE__ */ f(
906
+ D,
900
907
  {
901
908
  text: e,
902
909
  duration: 2.5,
@@ -904,10 +911,10 @@ const fe = ({
904
911
  color: "#999",
905
912
  shimmerColor: "#000"
906
913
  }
907
- ) : /* @__PURE__ */ g("span", { style: { color: "#666" }, children: e })
914
+ ) : /* @__PURE__ */ f("span", { style: { color: "#666" }, children: e })
908
915
  }
909
916
  ),
910
- i !== void 0 && /* @__PURE__ */ I(
917
+ o !== void 0 && /* @__PURE__ */ x(
911
918
  "div",
912
919
  {
913
920
  style: {
@@ -918,44 +925,44 @@ const fe = ({
918
925
  },
919
926
  children: [
920
927
  "Thought for ",
921
- i,
928
+ o,
922
929
  " seconds"
923
930
  ]
924
931
  }
925
932
  ),
926
- /* @__PURE__ */ g("style", { children: `
933
+ /* @__PURE__ */ f("style", { children: `
927
934
  @keyframes spin {
928
935
  to { transform: rotate(360deg); }
929
936
  }
930
937
  ` })
931
938
  ]
932
939
  }
933
- ), ye = ({
940
+ ), fe = ({
934
941
  title: e,
935
942
  markdown: t,
936
- completed: o,
937
- isLatest: i = !1,
938
- durationSeconds: s
943
+ completed: n,
944
+ isLatest: o = !1,
945
+ durationSeconds: a
939
946
  }) => {
940
- const m = F(null);
941
- return x(() => {
942
- m.current && !o && (m.current.scrollTop = m.current.scrollHeight);
943
- }, [t, o]), /* @__PURE__ */ I(
947
+ const g = E(null);
948
+ return T(() => {
949
+ g.current && !n && (g.current.scrollTop = g.current.scrollHeight);
950
+ }, [t, n]), /* @__PURE__ */ x(
944
951
  "div",
945
952
  {
946
953
  style: {
947
954
  padding: "16px"
948
955
  },
949
956
  children: [
950
- /* @__PURE__ */ g(
951
- C.h3,
957
+ /* @__PURE__ */ f(
958
+ P.h3,
952
959
  {
953
960
  style: { marginBottom: "10px", color: "#666" },
954
961
  initial: { opacity: 0, y: -10 },
955
962
  animate: { opacity: 1, y: 0 },
956
963
  transition: { duration: 0.3, delay: 0 },
957
- children: i && !s ? /* @__PURE__ */ g(
958
- M,
964
+ children: o && !a ? /* @__PURE__ */ f(
965
+ D,
959
966
  {
960
967
  text: e,
961
968
  duration: 2.5,
@@ -966,10 +973,10 @@ const fe = ({
966
973
  ) : e
967
974
  }
968
975
  ),
969
- /* @__PURE__ */ g(
970
- C.div,
976
+ /* @__PURE__ */ f(
977
+ P.div,
971
978
  {
972
- ref: m,
979
+ ref: g,
973
980
  style: {
974
981
  maxHeight: "100px",
975
982
  overflowY: "auto",
@@ -982,34 +989,34 @@ const fe = ({
982
989
  initial: { opacity: 0, y: -10 },
983
990
  animate: { opacity: 0.5, y: 0 },
984
991
  transition: { duration: 0.3, delay: 0.1 },
985
- children: /* @__PURE__ */ g("div", { className: "fency-markdown-body-raw", children: /* @__PURE__ */ g(
992
+ children: /* @__PURE__ */ f("div", { className: "fency-markdown-body-raw", children: /* @__PURE__ */ f(
986
993
  W,
987
994
  {
988
995
  remarkPlugins: [L],
989
996
  components: {
990
- code(u) {
997
+ code(l) {
991
998
  const {
992
- children: a,
993
- className: n,
994
- node: d,
995
- ref: l,
996
- ...c
997
- } = u, r = /language-(\w+)/.exec(
998
- n || ""
999
+ children: u,
1000
+ className: r,
1001
+ node: i,
1002
+ ref: d,
1003
+ ...s
1004
+ } = l, c = /language-(\w+)/.exec(
1005
+ r || ""
999
1006
  );
1000
- return r ? /* @__PURE__ */ g(
1007
+ return c ? /* @__PURE__ */ f(
1001
1008
  j,
1002
1009
  {
1003
- ...c,
1010
+ ...s,
1004
1011
  PreTag: "div",
1005
- children: String(a).replace(
1012
+ children: String(u).replace(
1006
1013
  /\n$/,
1007
1014
  ""
1008
1015
  ),
1009
- language: r[1],
1016
+ language: c[1],
1010
1017
  style: K
1011
1018
  }
1012
- ) : /* @__PURE__ */ g("code", { ...c, className: n, children: String(a) });
1019
+ ) : /* @__PURE__ */ f("code", { ...s, className: r, children: String(u) });
1013
1020
  }
1014
1021
  },
1015
1022
  children: t
@@ -1017,7 +1024,7 @@ const fe = ({
1017
1024
  ) })
1018
1025
  }
1019
1026
  ),
1020
- s !== void 0 && /* @__PURE__ */ I(
1027
+ a !== void 0 && /* @__PURE__ */ x(
1021
1028
  "div",
1022
1029
  {
1023
1030
  style: {
@@ -1028,7 +1035,7 @@ const fe = ({
1028
1035
  },
1029
1036
  children: [
1030
1037
  "Thought for ",
1031
- s,
1038
+ a,
1032
1039
  " seconds"
1033
1040
  ]
1034
1041
  }
@@ -1036,11 +1043,11 @@ const fe = ({
1036
1043
  ]
1037
1044
  }
1038
1045
  );
1039
- }, he = ({ message: e, isLatest: t = !1, streamToken: o, fetchClientToken: i }) => {
1040
- const s = e.state || "complete";
1041
- if (s === O.EXECUTION)
1042
- return /* @__PURE__ */ g(
1043
- fe,
1046
+ }, he = ({ message: e, isLatest: t = !1, streamToken: n, fetchClientToken: o }) => {
1047
+ const a = e.state || "complete";
1048
+ if (a === O.EXECUTION)
1049
+ return /* @__PURE__ */ f(
1050
+ ge,
1044
1051
  {
1045
1052
  title: e.title,
1046
1053
  completed: e.completed,
@@ -1048,9 +1055,9 @@ const fe = ({
1048
1055
  durationSeconds: e.durationSeconds
1049
1056
  }
1050
1057
  );
1051
- if (s === O.REASONING)
1052
- return /* @__PURE__ */ g(
1053
- ye,
1058
+ if (a === O.REASONING)
1059
+ return /* @__PURE__ */ f(
1060
+ fe,
1054
1061
  {
1055
1062
  title: e.title,
1056
1063
  markdown: e.markdown,
@@ -1059,86 +1066,86 @@ const fe = ({
1059
1066
  durationSeconds: e.durationSeconds
1060
1067
  }
1061
1068
  );
1062
- if (s === O.FINAL_RESPONSE)
1063
- return /* @__PURE__ */ g(
1064
- ge,
1069
+ if (a === O.FINAL_RESPONSE)
1070
+ return /* @__PURE__ */ f(
1071
+ me,
1065
1072
  {
1066
1073
  markdown: e.markdown,
1067
- streamToken: o,
1068
- fetchClientToken: i,
1074
+ streamToken: n,
1075
+ fetchClientToken: o,
1069
1076
  durationSeconds: e.durationSeconds
1070
1077
  }
1071
1078
  );
1072
- throw new Error(`Unknown state: ${s}`);
1073
- }, Pe = ({
1079
+ throw new Error(`Unknown state: ${a}`);
1080
+ }, Ne = ({
1074
1081
  agentTask: e,
1075
1082
  mode: t = "verbose",
1076
- placeholderMessage: o = "Processing your request",
1077
- streamToken: i,
1078
- fetchClientToken: s
1083
+ placeholderMessage: n = "Processing your request",
1084
+ streamToken: o,
1085
+ fetchClientToken: a
1079
1086
  }) => {
1080
- const [m, u] = T([]), a = F(null);
1081
- if (x(() => {
1082
- const n = e.progressItems.map((r, f) => {
1083
- let h;
1084
- const b = e.progressItems[f + 1];
1085
- if (b != null && b.createdAt) {
1086
- const y = new Date(r.createdAt).getTime(), k = new Date(b.createdAt).getTime();
1087
- h = Math.round((k - y) / 1e3);
1087
+ const [g, l] = v([]), u = E(null);
1088
+ if (T(() => {
1089
+ const r = e.progressItems.map((c, m) => {
1090
+ let b;
1091
+ const h = e.progressItems[m + 1];
1092
+ if (h != null && h.createdAt) {
1093
+ const y = new Date(c.createdAt).getTime(), w = new Date(h.createdAt).getTime();
1094
+ b = Math.round((w - y) / 1e3);
1088
1095
  }
1089
- const w = b != null;
1096
+ const k = h != null;
1090
1097
  return {
1091
- id: r.progressItemId,
1092
- title: r.title,
1093
- markdown: r.response || "",
1094
- state: r.progressItemType,
1095
- completed: w,
1096
- startedAt: r.createdAt,
1097
- durationSeconds: h
1098
+ id: c.progressItemId,
1099
+ title: c.title,
1100
+ markdown: c.response || "",
1101
+ state: c.progressItemType,
1102
+ completed: k,
1103
+ startedAt: c.createdAt,
1104
+ durationSeconds: b
1098
1105
  };
1099
1106
  });
1100
- let d;
1101
- const l = e.progressItems[0];
1102
- if (l != null && l.createdAt) {
1103
- const r = new Date(e.triggeredAt).getTime(), f = new Date(l.createdAt).getTime();
1104
- d = Math.round((f - r) / 1e3);
1107
+ let i;
1108
+ const d = e.progressItems[0];
1109
+ if (d != null && d.createdAt) {
1110
+ const c = new Date(e.triggeredAt).getTime(), m = new Date(d.createdAt).getTime();
1111
+ i = Math.round((m - c) / 1e3);
1105
1112
  }
1106
- const c = {
1113
+ const s = {
1107
1114
  id: "placeholder",
1108
- title: o,
1115
+ title: n,
1109
1116
  markdown: "",
1110
1117
  state: O.EXECUTION,
1111
- completed: l != null,
1112
- durationSeconds: d
1118
+ completed: d != null,
1119
+ durationSeconds: i
1113
1120
  };
1114
- u([c, ...n]);
1115
- }, [e, o]), x(() => {
1116
- t === "verbose" && a.current && (a.current.scrollTop = a.current.scrollHeight);
1117
- }, [m, t]), t === "simple") {
1118
- const n = m[m.length - 1];
1119
- if (!n)
1121
+ l([s, ...r]);
1122
+ }, [e, n]), T(() => {
1123
+ t === "verbose" && u.current && (u.current.scrollTop = u.current.scrollHeight);
1124
+ }, [g, t]), t === "simple") {
1125
+ const r = g[g.length - 1];
1126
+ if (!r)
1120
1127
  return null;
1121
- const d = n.completed;
1122
- return /* @__PURE__ */ g("div", { className: "simple-mode-container", children: /* @__PURE__ */ g(_, { mode: "wait", children: /* @__PURE__ */ g(
1123
- C.div,
1128
+ const i = r.completed;
1129
+ return /* @__PURE__ */ f("div", { className: "simple-mode-container", children: /* @__PURE__ */ f(B, { mode: "wait", children: /* @__PURE__ */ f(
1130
+ P.div,
1124
1131
  {
1125
1132
  initial: { opacity: 0, y: 10 },
1126
1133
  animate: { opacity: 1, y: 0 },
1127
1134
  exit: { opacity: 0, y: -10 },
1128
1135
  transition: { duration: 0.3 },
1129
- children: d ? /* @__PURE__ */ g(
1136
+ children: i ? /* @__PURE__ */ f(
1130
1137
  "div",
1131
1138
  {
1132
1139
  className: "simple-mode-title",
1133
1140
  style: {
1134
1141
  color: "#666"
1135
1142
  },
1136
- children: n.title
1143
+ children: r.title
1137
1144
  }
1138
- ) : /* @__PURE__ */ g(
1139
- M,
1145
+ ) : /* @__PURE__ */ f(
1146
+ D,
1140
1147
  {
1141
- text: n.title,
1148
+ text: r.title,
1142
1149
  className: "simple-mode-title",
1143
1150
  duration: 2.5,
1144
1151
  repeat: !0,
@@ -1147,111 +1154,198 @@ const fe = ({
1147
1154
  }
1148
1155
  )
1149
1156
  },
1150
- n.id
1157
+ r.id
1151
1158
  ) }) });
1152
1159
  }
1153
- return /* @__PURE__ */ g(
1160
+ return /* @__PURE__ */ f(
1154
1161
  "div",
1155
1162
  {
1156
- ref: a,
1163
+ ref: u,
1157
1164
  style: {
1158
1165
  flex: 1,
1159
1166
  overflowY: "auto",
1160
1167
  minHeight: 0
1161
1168
  // Important for flex scroll
1162
1169
  },
1163
- children: /* @__PURE__ */ g(_, { children: m.length > 0 && m.map((n, d) => /* @__PURE__ */ g(
1164
- C.div,
1170
+ children: /* @__PURE__ */ f(B, { children: g.length > 0 && g.map((r, i) => /* @__PURE__ */ f(
1171
+ P.div,
1165
1172
  {
1166
1173
  initial: { opacity: 0, y: -20 },
1167
1174
  animate: { opacity: 1, y: 0 },
1168
1175
  transition: {
1169
1176
  duration: 0.4,
1170
- delay: d * 0.1,
1177
+ delay: i * 0.1,
1171
1178
  // Stagger effect
1172
1179
  ease: "easeOut"
1173
1180
  },
1174
- children: /* @__PURE__ */ g(
1181
+ children: /* @__PURE__ */ f(
1175
1182
  he,
1176
1183
  {
1177
- message: n,
1178
- isLatest: d === m.length - 1,
1179
- streamToken: i,
1180
- fetchClientToken: s
1184
+ message: r,
1185
+ isLatest: i === g.length - 1,
1186
+ streamToken: o,
1187
+ fetchClientToken: a
1181
1188
  }
1182
1189
  )
1183
1190
  },
1184
- n.id
1191
+ r.id
1185
1192
  )) })
1186
1193
  }
1187
1194
  );
1188
1195
  };
1189
- function xe({ fency: e, children: t }) {
1190
- const [o, i] = T(
1196
+ class ye {
1197
+ constructor(t) {
1198
+ this.eventSources = /* @__PURE__ */ new Map(), this.subscribers = /* @__PURE__ */ new Map(), this.fency = t;
1199
+ }
1200
+ /**
1201
+ * Called by FencyProvider when activeStreams changes.
1202
+ * Creates new connections and removes old ones.
1203
+ */
1204
+ updateStreams(t) {
1205
+ t.forEach((o) => {
1206
+ const a = o.stream.id;
1207
+ this.eventSources.has(a) || this.connectStream(o);
1208
+ });
1209
+ const n = new Set(t.map((o) => o.stream.id));
1210
+ this.eventSources.forEach((o, a) => {
1211
+ n.has(a) || (o.abort(), this.eventSources.delete(a));
1212
+ });
1213
+ }
1214
+ connectStream(t) {
1215
+ const n = t.stream.id, o = new AbortController();
1216
+ this.eventSources.set(n, o);
1217
+ const a = `${this.fency.baseUrl}/sse/streams/${n}`, g = {
1218
+ "X-Fency-Publishable-Key": this.fency.publishableKey,
1219
+ "X-Fency-Stream-Token": t.stream.token
1220
+ };
1221
+ q(a, {
1222
+ headers: g,
1223
+ signal: o.signal,
1224
+ async onopen(l) {
1225
+ if (!l.ok && l.status >= 400 && l.status < 500 && l.status !== 429)
1226
+ throw new Error(`Client error ${l.status}`);
1227
+ },
1228
+ onmessage: (l) => {
1229
+ if (l.data) {
1230
+ const u = G(l.data);
1231
+ this.broadcast(u, n);
1232
+ }
1233
+ },
1234
+ onerror: (l) => {
1235
+ throw console.error("EventSource error for stream", n, ":", l), this.broadcastError(n), l;
1236
+ },
1237
+ onclose() {
1238
+ }
1239
+ });
1240
+ }
1241
+ /**
1242
+ * Subscribe to events from all active streams.
1243
+ * Returns an unsubscribe function.
1244
+ */
1245
+ subscribe(t, n) {
1246
+ return this.subscribers.set(t, n), () => {
1247
+ this.subscribers.delete(t);
1248
+ };
1249
+ }
1250
+ broadcast(t, n) {
1251
+ this.subscribers.forEach((o) => {
1252
+ o.onMessage(t, n);
1253
+ });
1254
+ }
1255
+ broadcastError(t) {
1256
+ this.subscribers.forEach((n) => {
1257
+ n.onError(t);
1258
+ });
1259
+ }
1260
+ /**
1261
+ * Cleanup all connections and subscriptions
1262
+ */
1263
+ cleanup() {
1264
+ this.eventSources.forEach((t) => t.abort()), this.eventSources.clear(), this.subscribers.clear();
1265
+ }
1266
+ }
1267
+ const be = 12e4, we = (e) => {
1268
+ const t = Date.now();
1269
+ return e.filter((n) => t - n.createdAt < be);
1270
+ };
1271
+ function Re({ fency: e, children: t }) {
1272
+ const [n, o] = v(
1191
1273
  null
1192
- ), [s, m] = T(!0), [u, a] = T(null), [n, d] = T(null), l = F(null);
1193
- x(() => {
1194
- e.then((f) => {
1195
- i(f), m(!1);
1196
- }).catch((f) => {
1197
- a(f), m(!1);
1274
+ ), [a, g] = v(!0), [l, u] = v(null), [r, i] = v([]), d = E(null), s = E(null);
1275
+ T(() => {
1276
+ e.then((h) => {
1277
+ o(h), g(!1);
1278
+ }).catch((h) => {
1279
+ u(h), g(!1);
1198
1280
  });
1199
- }, [e]);
1200
- const c = D(
1201
- async (f, h = 3e4) => {
1202
- if (l.current)
1203
- return l.current;
1204
- const b = Date.now();
1205
- if (n && b - n.createdAt < h)
1206
- return n.stream;
1207
- const w = (async () => {
1208
- if (!o)
1281
+ }, [e]), T(() => {
1282
+ n && !s.current && (s.current = new ye(n));
1283
+ }, [n]), T(() => {
1284
+ s.current && s.current.updateStreams(r);
1285
+ }, [r]), T(() => () => {
1286
+ var h;
1287
+ (h = s.current) == null || h.cleanup();
1288
+ }, []);
1289
+ const c = M(
1290
+ async (h, k = 3e4) => {
1291
+ if (d.current)
1292
+ return d.current;
1293
+ const y = Date.now(), w = r.length > 0 ? r[r.length - 1] : null;
1294
+ if (w && y - w.createdAt < k)
1295
+ return w.stream;
1296
+ const I = (async () => {
1297
+ if (!n)
1209
1298
  throw new Error("Fency instance not initialized");
1210
- const y = await f(), k = await V({
1211
- pk: o.publishableKey,
1212
- baseUrl: o.baseUrl,
1213
- clientToken: (y == null ? void 0 : y.clientToken) ?? ""
1299
+ const C = await h(), A = await Y({
1300
+ pk: n.publishableKey,
1301
+ baseUrl: n.baseUrl,
1302
+ clientToken: (C == null ? void 0 : C.clientToken) ?? ""
1214
1303
  });
1215
- if (k.type === "success") {
1216
- const v = {
1217
- stream: k.stream,
1304
+ if (A.type === "success") {
1305
+ const R = {
1306
+ stream: A.stream,
1218
1307
  createdAt: Date.now()
1219
1308
  };
1220
- return d(v), l.current = null, k.stream;
1309
+ return i((N) => {
1310
+ const S = [...N, R];
1311
+ return we(S);
1312
+ }), d.current = null, A.stream;
1221
1313
  } else
1222
- throw l.current = null, new Error("Failed to create stream");
1314
+ throw d.current = null, new Error("Failed to create stream");
1223
1315
  })();
1224
- return l.current = w, w;
1316
+ return d.current = I, I;
1225
1317
  },
1226
- [o, n]
1318
+ [n, r]
1227
1319
  );
1228
- if (u)
1229
- return /* @__PURE__ */ I("div", { children: [
1320
+ if (l)
1321
+ return /* @__PURE__ */ x("div", { children: [
1230
1322
  "Fency error: ",
1231
- u.message
1323
+ l.message
1232
1324
  ] });
1233
- if (!o)
1325
+ if (!n)
1234
1326
  return null;
1235
- const r = {
1236
- fency: o,
1237
- loading: s,
1238
- error: u,
1239
- activeStream: n,
1327
+ const m = r.length > 0 ? r[r.length - 1] : null, b = {
1328
+ fency: n,
1329
+ loading: a,
1330
+ error: l,
1331
+ activeStreams: r,
1332
+ latestStream: m,
1333
+ eventManager: s.current,
1240
1334
  getOrCreateStream: c
1241
1335
  };
1242
- return /* @__PURE__ */ g($.Provider, { value: r, children: t });
1336
+ return /* @__PURE__ */ f($.Provider, { value: b, children: t });
1243
1337
  }
1244
1338
  export {
1245
- Pe as AgentTaskProgress,
1339
+ Ne as AgentTaskProgress,
1246
1340
  he as ChatResponse,
1247
- ge as ChatResponseComplete,
1248
- fe as ChatResponseLoading,
1249
- ye as ChatResponseThinking,
1250
- xe as FencyProvider,
1251
- M as ShimmeringText,
1252
- Ce as useAgentTasks,
1253
- R as useFencyContext,
1254
- ae as useFencyEventSource,
1255
- Ae as usePaginatedQuery,
1256
- me as useStream
1341
+ me as ChatResponseComplete,
1342
+ ge as ChatResponseLoading,
1343
+ fe as ChatResponseThinking,
1344
+ Re as FencyProvider,
1345
+ D as ShimmeringText,
1346
+ Ee as useAgentTasks,
1347
+ F as useFencyContext,
1348
+ xe as useFencyEventSource,
1349
+ Pe as usePaginatedQuery,
1350
+ oe as useStream
1257
1351
  };