ai 0.0.0-85f9a635-20240518005312 → 0.0.0-9477ebb9-20250403064906

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 (70) hide show
  1. package/CHANGELOG.md +3521 -0
  2. package/README.md +112 -22
  3. package/dist/index.d.mts +3697 -1642
  4. package/dist/index.d.ts +3697 -1642
  5. package/dist/index.js +7201 -2942
  6. package/dist/index.js.map +1 -1
  7. package/dist/index.mjs +7249 -2963
  8. package/dist/index.mjs.map +1 -1
  9. package/mcp-stdio/create-child-process.test.ts +92 -0
  10. package/mcp-stdio/create-child-process.ts +21 -0
  11. package/mcp-stdio/dist/index.d.mts +169 -0
  12. package/mcp-stdio/dist/index.d.ts +169 -0
  13. package/mcp-stdio/dist/index.js +352 -0
  14. package/mcp-stdio/dist/index.js.map +1 -0
  15. package/mcp-stdio/dist/index.mjs +337 -0
  16. package/mcp-stdio/dist/index.mjs.map +1 -0
  17. package/mcp-stdio/get-environment.ts +43 -0
  18. package/mcp-stdio/index.ts +4 -0
  19. package/mcp-stdio/mcp-stdio-transport.test.ts +262 -0
  20. package/mcp-stdio/mcp-stdio-transport.ts +157 -0
  21. package/package.json +46 -103
  22. package/react/dist/index.d.mts +10 -557
  23. package/react/dist/index.d.ts +10 -574
  24. package/react/dist/index.js +6 -1397
  25. package/react/dist/index.js.map +1 -1
  26. package/react/dist/index.mjs +10 -1384
  27. package/react/dist/index.mjs.map +1 -1
  28. package/rsc/dist/index.d.ts +432 -199
  29. package/rsc/dist/rsc-server.d.mts +431 -199
  30. package/rsc/dist/rsc-server.mjs +1599 -1357
  31. package/rsc/dist/rsc-server.mjs.map +1 -1
  32. package/rsc/dist/rsc-shared.d.mts +30 -23
  33. package/rsc/dist/rsc-shared.mjs +70 -108
  34. package/rsc/dist/rsc-shared.mjs.map +1 -1
  35. package/test/dist/index.d.mts +65 -0
  36. package/test/dist/index.d.ts +65 -0
  37. package/test/dist/index.js +121 -0
  38. package/test/dist/index.js.map +1 -0
  39. package/test/dist/index.mjs +94 -0
  40. package/test/dist/index.mjs.map +1 -0
  41. package/prompts/dist/index.d.mts +0 -324
  42. package/prompts/dist/index.d.ts +0 -324
  43. package/prompts/dist/index.js +0 -178
  44. package/prompts/dist/index.js.map +0 -1
  45. package/prompts/dist/index.mjs +0 -146
  46. package/prompts/dist/index.mjs.map +0 -1
  47. package/react/dist/index.server.d.mts +0 -17
  48. package/react/dist/index.server.d.ts +0 -17
  49. package/react/dist/index.server.js +0 -50
  50. package/react/dist/index.server.js.map +0 -1
  51. package/react/dist/index.server.mjs +0 -23
  52. package/react/dist/index.server.mjs.map +0 -1
  53. package/solid/dist/index.d.mts +0 -408
  54. package/solid/dist/index.d.ts +0 -408
  55. package/solid/dist/index.js +0 -1072
  56. package/solid/dist/index.js.map +0 -1
  57. package/solid/dist/index.mjs +0 -1044
  58. package/solid/dist/index.mjs.map +0 -1
  59. package/svelte/dist/index.d.mts +0 -484
  60. package/svelte/dist/index.d.ts +0 -484
  61. package/svelte/dist/index.js +0 -1778
  62. package/svelte/dist/index.js.map +0 -1
  63. package/svelte/dist/index.mjs +0 -1749
  64. package/svelte/dist/index.mjs.map +0 -1
  65. package/vue/dist/index.d.mts +0 -402
  66. package/vue/dist/index.d.ts +0 -402
  67. package/vue/dist/index.js +0 -1072
  68. package/vue/dist/index.js.map +0 -1
  69. package/vue/dist/index.mjs +0 -1034
  70. package/vue/dist/index.mjs.map +0 -1
@@ -1,1778 +0,0 @@
1
- "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, { get: all[name], enumerable: true });
9
- };
10
- var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
17
- };
18
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
-
20
- // svelte/index.ts
21
- var svelte_exports = {};
22
- __export(svelte_exports, {
23
- useAssistant: () => useAssistant,
24
- useChat: () => useChat,
25
- useCompletion: () => useCompletion
26
- });
27
- module.exports = __toCommonJS(svelte_exports);
28
-
29
- // ../../node_modules/.pnpm/swrev@4.0.0/node_modules/swrev/dist/swrev.mjs
30
- var P = Object.defineProperty;
31
- var F = (r, e, t) => e in r ? P(r, e, { enumerable: true, configurable: true, writable: true, value: t }) : r[e] = t;
32
- var h = (r, e, t) => (F(r, typeof e != "symbol" ? e + "" : e, t), t);
33
- var I = class {
34
- constructor() {
35
- h(this, "listeners", /* @__PURE__ */ new Map());
36
- }
37
- /**
38
- * Subscribes a given listener.
39
- */
40
- subscribe(e, t) {
41
- this.listeners.has(e) || this.listeners.set(e, []), !this.listeners.get(e).includes(t) && this.listeners.get(e).push(t);
42
- }
43
- /**
44
- * Unsubscribes the given listener.
45
- */
46
- unsubscribe(e, t) {
47
- this.listeners.has(e) && this.listeners.get(e).includes(t) && (this.listeners.get(e).splice(this.listeners.get(e).indexOf(t), 1), this.listeners.get(e).length === 0 && this.listeners.delete(e));
48
- }
49
- /**
50
- * Emits an event to all active listeners.
51
- */
52
- emit(e, t) {
53
- this.listeners.has(e) && this.listeners.get(e).forEach((s) => s(t));
54
- }
55
- };
56
- var L = {
57
- broadcast: false
58
- };
59
- var S = {
60
- broadcast: false
61
- };
62
- var O = class {
63
- /**
64
- * Creates the cache item given the data and expiration at.
65
- */
66
- constructor({ data: e, expiresAt: t = null }) {
67
- h(this, "data");
68
- h(this, "expiresAt");
69
- this.data = e, this.expiresAt = t;
70
- }
71
- /**
72
- * Determines if the current cache item is still being resolved.
73
- * This returns true if data is a promise, or false if type `D`.
74
- */
75
- isResolving() {
76
- return this.data instanceof Promise;
77
- }
78
- /**
79
- * Determines if the given cache item has expired.
80
- */
81
- hasExpired() {
82
- return this.expiresAt === null || this.expiresAt < /* @__PURE__ */ new Date();
83
- }
84
- /**
85
- * Set the expiration time of the given cache item relative to now.
86
- */
87
- expiresIn(e) {
88
- return this.expiresAt = /* @__PURE__ */ new Date(), this.expiresAt.setMilliseconds(this.expiresAt.getMilliseconds() + e), this;
89
- }
90
- };
91
- var q = class {
92
- constructor() {
93
- h(this, "elements", /* @__PURE__ */ new Map());
94
- h(this, "event", new I());
95
- }
96
- /**
97
- * Resolves the promise and replaces the Promise to the resolved data.
98
- * It also broadcasts the value change if needed or deletes the key if
99
- * the value resolves to undefined or null.
100
- */
101
- resolve(e, t) {
102
- Promise.resolve(t.data).then((s) => {
103
- if (s == null)
104
- return this.remove(e);
105
- t.data = s, this.broadcast(e, s);
106
- });
107
- }
108
- /**
109
- * Gets an element from the cache.
110
- *
111
- * It is assumed the item always exist when
112
- * you get it. Use the has method to check
113
- * for the existence of it.
114
- */
115
- get(e) {
116
- return this.elements.get(e);
117
- }
118
- /**
119
- * Sets an element to the cache.
120
- */
121
- set(e, t) {
122
- this.elements.set(e, t), this.resolve(e, t);
123
- }
124
- /**
125
- * Removes an key-value pair from the cache.
126
- */
127
- remove(e, t) {
128
- const { broadcast: s } = { ...L, ...t };
129
- s && this.broadcast(e, void 0), this.elements.delete(e);
130
- }
131
- /**
132
- * Removes all the key-value pairs from the cache.
133
- */
134
- clear(e) {
135
- const { broadcast: t } = { ...S, ...e };
136
- if (t)
137
- for (const s of this.elements.keys())
138
- this.broadcast(s, void 0);
139
- this.elements.clear();
140
- }
141
- /**
142
- * Determines if the given key exists
143
- * in the cache.
144
- */
145
- has(e) {
146
- return this.elements.has(e);
147
- }
148
- /**
149
- * Subscribes the callback to the given key.
150
- */
151
- subscribe(e, t) {
152
- this.event.subscribe(e, t);
153
- }
154
- /**
155
- * Unsubscribes to the given key events.
156
- */
157
- unsubscribe(e, t) {
158
- this.event.unsubscribe(e, t);
159
- }
160
- /**
161
- * Broadcasts a value change on all subscribed instances.
162
- */
163
- broadcast(e, t) {
164
- this.event.emit(e, t);
165
- }
166
- };
167
- var x = {
168
- cache: new q(),
169
- errors: new I(),
170
- fetcher: async (r) => {
171
- const e = await fetch(r);
172
- if (!e.ok)
173
- throw Error("Not a 2XX response.");
174
- return e.json();
175
- },
176
- fallbackData: void 0,
177
- loadInitialCache: true,
178
- revalidateOnStart: true,
179
- dedupingInterval: 2e3,
180
- revalidateOnFocus: true,
181
- focusThrottleInterval: 5e3,
182
- revalidateOnReconnect: true,
183
- reconnectWhen: (r, { enabled: e }) => e && typeof window < "u" ? (window.addEventListener("online", r), () => window.removeEventListener("online", r)) : () => {
184
- },
185
- focusWhen: (r, { enabled: e, throttleInterval: t }) => {
186
- if (e && typeof window < "u") {
187
- let s = null;
188
- const i = () => {
189
- const a = Date.now();
190
- (s === null || a - s > t) && (s = a, r());
191
- };
192
- return window.addEventListener("focus", i), () => window.removeEventListener("focus", i);
193
- }
194
- return () => {
195
- };
196
- },
197
- revalidateFunction: void 0
198
- };
199
- var E = {
200
- ...x,
201
- force: false
202
- };
203
- var T = {
204
- revalidate: true,
205
- revalidateOptions: { ...E },
206
- revalidateFunction: void 0
207
- };
208
- var X = {
209
- broadcast: false
210
- };
211
- var H = class {
212
- /**
213
- * Creates a new instance of SWR.
214
- */
215
- constructor(e) {
216
- h(this, "options");
217
- this.options = { ...x, ...e };
218
- }
219
- /**
220
- * Gets the cache of the SWR.
221
- */
222
- get cache() {
223
- return this.options.cache;
224
- }
225
- /**
226
- * Gets the cache of the SWR.
227
- */
228
- get errors() {
229
- return this.options.errors;
230
- }
231
- /**
232
- * Requests the data using the provided fetcher.
233
- */
234
- async requestData(e, t) {
235
- return await Promise.resolve(t(e)).catch((s) => {
236
- throw this.errors.emit(e, s), s;
237
- });
238
- }
239
- /**
240
- * Resolves the given to a SWRKey or undefined.
241
- */
242
- resolveKey(e) {
243
- if (typeof e == "function")
244
- try {
245
- return e();
246
- } catch (e2) {
247
- return;
248
- }
249
- return e;
250
- }
251
- /**
252
- * Clear the specified keys from the cache. If no keys
253
- * are specified, it clears all the cache keys.
254
- */
255
- clear(e, t) {
256
- const s = { ...X, ...t };
257
- if (e == null)
258
- return this.cache.clear(s);
259
- if (!Array.isArray(e))
260
- return this.cache.remove(e, s);
261
- for (const i of e)
262
- this.cache.remove(i, s);
263
- }
264
- /**
265
- * Revalidates the key and mutates the cache if needed.
266
- */
267
- async revalidate(e, t) {
268
- if (!e)
269
- throw new Error("[Revalidate] Key issue: ${key}");
270
- const { fetcher: s, dedupingInterval: i } = this.options, { force: a, fetcher: o, dedupingInterval: n } = {
271
- ...E,
272
- fetcher: s,
273
- dedupingInterval: i,
274
- ...t
275
- };
276
- if (a || !this.cache.has(e) || this.cache.has(e) && this.cache.get(e).hasExpired()) {
277
- const c2 = this.requestData(e, o), l = c2.catch(() => {
278
- });
279
- return this.cache.set(e, new O({ data: l }).expiresIn(n)), await c2;
280
- }
281
- return this.getWait(e);
282
- }
283
- /**
284
- * Mutates the data of a given key with a new value.
285
- * This is used to replace the cache contents of the
286
- * given key manually.
287
- */
288
- async mutate(e, t, s) {
289
- var _a;
290
- if (!e)
291
- throw new Error("[Mutate] Key issue: ${key}");
292
- const {
293
- revalidate: i,
294
- revalidateOptions: a,
295
- revalidateFunction: o
296
- } = {
297
- ...T,
298
- ...s
299
- };
300
- let n;
301
- if (typeof t == "function") {
302
- let c2;
303
- if (this.cache.has(e)) {
304
- const l = this.cache.get(e);
305
- l.isResolving() || (c2 = l.data);
306
- }
307
- n = t(c2);
308
- } else
309
- n = t;
310
- return this.cache.set(e, new O({ data: n })), i ? await ((_a = o == null ? void 0 : o(e, a)) != null ? _a : this.revalidate(e, a)) : n;
311
- }
312
- /**
313
- * Gets the data of the given key. Keep in mind
314
- * this data will be stale and revalidate in the background
315
- * unless specified otherwise.
316
- */
317
- subscribeData(e, t) {
318
- if (e) {
319
- const s = (i) => t(i);
320
- return this.cache.subscribe(e, s), () => this.cache.unsubscribe(e, s);
321
- }
322
- return () => {
323
- };
324
- }
325
- /**
326
- * Subscribes to errors on the given key.
327
- */
328
- subscribeErrors(e, t) {
329
- if (e) {
330
- const s = (i) => t(i);
331
- return this.errors.subscribe(e, s), () => this.errors.unsubscribe(e, s);
332
- }
333
- return () => {
334
- };
335
- }
336
- /**
337
- * Gets the current cached data of the given key.
338
- * This does not trigger any revalidation nor mutation
339
- * of the data.
340
- * - If the data has never been validated
341
- * (there is no cache) it will return undefined.
342
- * - If the item is pending to resolve (there is a request
343
- * pending to resolve) it will return undefined.
344
- */
345
- get(e) {
346
- if (e && this.cache.has(e)) {
347
- const t = this.cache.get(e);
348
- if (!t.isResolving())
349
- return t.data;
350
- }
351
- }
352
- /**
353
- * Gets an element from the cache. The difference
354
- * with the get is that this method returns a promise
355
- * that will resolve the the value. If there's no item
356
- * in the cache, it will wait for it before resolving.
357
- */
358
- getWait(e) {
359
- return new Promise((t, s) => {
360
- const i = this.subscribeData(e, (n) => {
361
- if (i(), n !== void 0)
362
- return t(n);
363
- }), a = this.subscribeErrors(e, (n) => {
364
- if (a(), n !== void 0)
365
- return s(n);
366
- }), o = this.get(e);
367
- if (o !== void 0)
368
- return t(o);
369
- });
370
- }
371
- /**
372
- * Use a SWR value given the key and
373
- * subscribe to future changes.
374
- */
375
- subscribe(e, t, s, i) {
376
- const {
377
- fetcher: a,
378
- fallbackData: o,
379
- loadInitialCache: n,
380
- revalidateOnStart: c2,
381
- dedupingInterval: l,
382
- revalidateOnFocus: A2,
383
- focusThrottleInterval: C,
384
- revalidateOnReconnect: R,
385
- reconnectWhen: W2,
386
- focusWhen: D2,
387
- revalidateFunction: d
388
- } = {
389
- // Current instance options
390
- // (includes default options)
391
- ...this.options,
392
- // Current call options.
393
- ...i
394
- }, K2 = (m) => {
395
- var _a;
396
- return (_a = d == null ? void 0 : d(this.resolveKey(e), m)) != null ? _a : this.revalidate(this.resolveKey(e), m);
397
- }, f = () => K2({ fetcher: a, dedupingInterval: l }), u = n ? this.get(this.resolveKey(e)) : o != null ? o : void 0, g = c2 ? f() : Promise.resolve(void 0), M = u ? Promise.resolve(u) : g;
398
- u && (t == null || t(u));
399
- const v2 = t ? this.subscribeData(this.resolveKey(e), t) : void 0, b = s ? this.subscribeErrors(this.resolveKey(e), s) : void 0, p2 = D2(f, {
400
- throttleInterval: C,
401
- enabled: A2
402
- }), w2 = W2(f, {
403
- enabled: R
404
- });
405
- return { unsubscribe: () => {
406
- v2 == null || v2(), b == null || b(), p2 == null || p2(), w2 == null || w2();
407
- }, dataPromise: M, revalidatePromise: g };
408
- }
409
- };
410
-
411
- // ../../node_modules/.pnpm/sswr@2.0.0_svelte@4.2.3/node_modules/sswr/dist/sswr.mjs
412
- var import_svelte = require("svelte");
413
- function p() {
414
- }
415
- function D(t) {
416
- return t();
417
- }
418
- function q2(t) {
419
- t.forEach(D);
420
- }
421
- function x2(t) {
422
- return typeof t == "function";
423
- }
424
- function K(t, e) {
425
- return t != t ? e == e : t !== e || t && typeof t == "object" || typeof t == "function";
426
- }
427
- function z(t, ...e) {
428
- if (t == null) {
429
- for (const r of e)
430
- r(void 0);
431
- return p;
432
- }
433
- const n = t.subscribe(...e);
434
- return n.unsubscribe ? () => n.unsubscribe() : n;
435
- }
436
- var v = [];
437
- function A(t, e) {
438
- return {
439
- subscribe: y(t, e).subscribe
440
- };
441
- }
442
- function y(t, e = p) {
443
- let n;
444
- const r = /* @__PURE__ */ new Set();
445
- function i(u) {
446
- if (K(t, u) && (t = u, n)) {
447
- const f = !v.length;
448
- for (const s of r)
449
- s[1](), v.push(s, t);
450
- if (f) {
451
- for (let s = 0; s < v.length; s += 2)
452
- v[s][0](v[s + 1]);
453
- v.length = 0;
454
- }
455
- }
456
- }
457
- function a(u) {
458
- i(u(t));
459
- }
460
- function d(u, f = p) {
461
- const s = [u, f];
462
- return r.add(s), r.size === 1 && (n = e(i, a) || p), u(t), () => {
463
- r.delete(s), r.size === 0 && n && (n(), n = null);
464
- };
465
- }
466
- return { set: i, update: a, subscribe: d };
467
- }
468
- function S2(t, e, n) {
469
- const r = !Array.isArray(t), i = r ? [t] : t;
470
- if (!i.every(Boolean))
471
- throw new Error("derived() expects stores as input, got a falsy value");
472
- const a = e.length < 2;
473
- return A(n, (d, u) => {
474
- let f = false;
475
- const s = [];
476
- let h2 = 0, o = p;
477
- const l = () => {
478
- if (h2)
479
- return;
480
- o();
481
- const b = e(r ? s[0] : s, d, u);
482
- a ? d(b) : o = x2(b) ? b : p;
483
- }, g = i.map(
484
- (b, m) => z(
485
- b,
486
- (R) => {
487
- s[m] = R, h2 &= ~(1 << m), f && l();
488
- },
489
- () => {
490
- h2 |= 1 << m;
491
- }
492
- )
493
- );
494
- return f = true, l(), function() {
495
- q2(g), o(), f = false;
496
- };
497
- });
498
- }
499
- var O2 = class extends H {
500
- /**
501
- * Svelte specific use of SWR.
502
- */
503
- useSWR(e, n) {
504
- let r;
505
- const i = y(void 0, () => () => r == null ? void 0 : r()), a = y(void 0, () => () => r == null ? void 0 : r());
506
- (0, import_svelte.beforeUpdate)(() => {
507
- const o = (g) => {
508
- a.set(void 0), i.set(g);
509
- }, l = (g) => a.set(g);
510
- r || (r = this.subscribe(e, o, l, {
511
- loadInitialCache: true,
512
- ...n
513
- }).unsubscribe);
514
- }), (0, import_svelte.onDestroy)(() => r == null ? void 0 : r());
515
- const d = (o, l) => this.mutate(this.resolveKey(e), o, {
516
- revalidateOptions: n,
517
- ...l
518
- }), u = (o) => this.revalidate(this.resolveKey(e), { ...n, ...o }), f = (o) => this.clear(this.resolveKey(e), o), s = S2([i, a], ([o, l]) => o === void 0 && l === void 0), h2 = S2([i, a], ([o, l]) => o !== void 0 && l === void 0);
519
- return { data: i, error: a, mutate: d, revalidate: u, clear: f, isLoading: s, isValid: h2 };
520
- }
521
- };
522
- var W = (t) => new O2(t);
523
- var c = W();
524
- var F2 = (t, e) => c.useSWR(t, e);
525
-
526
- // svelte/use-chat.ts
527
- var import_store = require("svelte/store");
528
-
529
- // shared/generate-id.ts
530
- var import_non_secure = require("nanoid/non-secure");
531
- var generateId = (0, import_non_secure.customAlphabet)(
532
- "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
533
- 7
534
- );
535
-
536
- // shared/stream-parts.ts
537
- var textStreamPart = {
538
- code: "0",
539
- name: "text",
540
- parse: (value) => {
541
- if (typeof value !== "string") {
542
- throw new Error('"text" parts expect a string value.');
543
- }
544
- return { type: "text", value };
545
- }
546
- };
547
- var functionCallStreamPart = {
548
- code: "1",
549
- name: "function_call",
550
- parse: (value) => {
551
- if (value == null || typeof value !== "object" || !("function_call" in value) || typeof value.function_call !== "object" || value.function_call == null || !("name" in value.function_call) || !("arguments" in value.function_call) || typeof value.function_call.name !== "string" || typeof value.function_call.arguments !== "string") {
552
- throw new Error(
553
- '"function_call" parts expect an object with a "function_call" property.'
554
- );
555
- }
556
- return {
557
- type: "function_call",
558
- value
559
- };
560
- }
561
- };
562
- var dataStreamPart = {
563
- code: "2",
564
- name: "data",
565
- parse: (value) => {
566
- if (!Array.isArray(value)) {
567
- throw new Error('"data" parts expect an array value.');
568
- }
569
- return { type: "data", value };
570
- }
571
- };
572
- var errorStreamPart = {
573
- code: "3",
574
- name: "error",
575
- parse: (value) => {
576
- if (typeof value !== "string") {
577
- throw new Error('"error" parts expect a string value.');
578
- }
579
- return { type: "error", value };
580
- }
581
- };
582
- var assistantMessageStreamPart = {
583
- code: "4",
584
- name: "assistant_message",
585
- parse: (value) => {
586
- if (value == null || typeof value !== "object" || !("id" in value) || !("role" in value) || !("content" in value) || typeof value.id !== "string" || typeof value.role !== "string" || value.role !== "assistant" || !Array.isArray(value.content) || !value.content.every(
587
- (item) => item != null && typeof item === "object" && "type" in item && item.type === "text" && "text" in item && item.text != null && typeof item.text === "object" && "value" in item.text && typeof item.text.value === "string"
588
- )) {
589
- throw new Error(
590
- '"assistant_message" parts expect an object with an "id", "role", and "content" property.'
591
- );
592
- }
593
- return {
594
- type: "assistant_message",
595
- value
596
- };
597
- }
598
- };
599
- var assistantControlDataStreamPart = {
600
- code: "5",
601
- name: "assistant_control_data",
602
- parse: (value) => {
603
- if (value == null || typeof value !== "object" || !("threadId" in value) || !("messageId" in value) || typeof value.threadId !== "string" || typeof value.messageId !== "string") {
604
- throw new Error(
605
- '"assistant_control_data" parts expect an object with a "threadId" and "messageId" property.'
606
- );
607
- }
608
- return {
609
- type: "assistant_control_data",
610
- value: {
611
- threadId: value.threadId,
612
- messageId: value.messageId
613
- }
614
- };
615
- }
616
- };
617
- var dataMessageStreamPart = {
618
- code: "6",
619
- name: "data_message",
620
- parse: (value) => {
621
- if (value == null || typeof value !== "object" || !("role" in value) || !("data" in value) || typeof value.role !== "string" || value.role !== "data") {
622
- throw new Error(
623
- '"data_message" parts expect an object with a "role" and "data" property.'
624
- );
625
- }
626
- return {
627
- type: "data_message",
628
- value
629
- };
630
- }
631
- };
632
- var toolCallsStreamPart = {
633
- code: "7",
634
- name: "tool_calls",
635
- parse: (value) => {
636
- if (value == null || typeof value !== "object" || !("tool_calls" in value) || typeof value.tool_calls !== "object" || value.tool_calls == null || !Array.isArray(value.tool_calls) || value.tool_calls.some(
637
- (tc) => tc == null || typeof tc !== "object" || !("id" in tc) || typeof tc.id !== "string" || !("type" in tc) || typeof tc.type !== "string" || !("function" in tc) || tc.function == null || typeof tc.function !== "object" || !("arguments" in tc.function) || typeof tc.function.name !== "string" || typeof tc.function.arguments !== "string"
638
- )) {
639
- throw new Error(
640
- '"tool_calls" parts expect an object with a ToolCallPayload.'
641
- );
642
- }
643
- return {
644
- type: "tool_calls",
645
- value
646
- };
647
- }
648
- };
649
- var messageAnnotationsStreamPart = {
650
- code: "8",
651
- name: "message_annotations",
652
- parse: (value) => {
653
- if (!Array.isArray(value)) {
654
- throw new Error('"message_annotations" parts expect an array value.');
655
- }
656
- return { type: "message_annotations", value };
657
- }
658
- };
659
- var toolCallStreamPart = {
660
- code: "9",
661
- name: "tool_call",
662
- parse: (value) => {
663
- if (value == null || typeof value !== "object" || !("toolCallId" in value) || typeof value.toolCallId !== "string" || !("toolName" in value) || typeof value.toolName !== "string" || !("args" in value) || typeof value.args !== "object") {
664
- throw new Error(
665
- '"tool_call" parts expect an object with a "toolCallId", "toolName", and "args" property.'
666
- );
667
- }
668
- return {
669
- type: "tool_call",
670
- value
671
- };
672
- }
673
- };
674
- var toolResultStreamPart = {
675
- code: "a",
676
- name: "tool_result",
677
- parse: (value) => {
678
- if (value == null || typeof value !== "object" || !("toolCallId" in value) || typeof value.toolCallId !== "string" || !("toolName" in value) || typeof value.toolName !== "string" || !("args" in value) || typeof value.args !== "object" || !("result" in value)) {
679
- throw new Error(
680
- '"tool_result" parts expect an object with a "toolCallId", "toolName", "args", and "result" property.'
681
- );
682
- }
683
- return {
684
- type: "tool_result",
685
- value
686
- };
687
- }
688
- };
689
- var streamParts = [
690
- textStreamPart,
691
- functionCallStreamPart,
692
- dataStreamPart,
693
- errorStreamPart,
694
- assistantMessageStreamPart,
695
- assistantControlDataStreamPart,
696
- dataMessageStreamPart,
697
- toolCallsStreamPart,
698
- messageAnnotationsStreamPart,
699
- toolCallStreamPart,
700
- toolResultStreamPart
701
- ];
702
- var streamPartsByCode = {
703
- [textStreamPart.code]: textStreamPart,
704
- [functionCallStreamPart.code]: functionCallStreamPart,
705
- [dataStreamPart.code]: dataStreamPart,
706
- [errorStreamPart.code]: errorStreamPart,
707
- [assistantMessageStreamPart.code]: assistantMessageStreamPart,
708
- [assistantControlDataStreamPart.code]: assistantControlDataStreamPart,
709
- [dataMessageStreamPart.code]: dataMessageStreamPart,
710
- [toolCallsStreamPart.code]: toolCallsStreamPart,
711
- [messageAnnotationsStreamPart.code]: messageAnnotationsStreamPart,
712
- [toolCallStreamPart.code]: toolCallStreamPart,
713
- [toolResultStreamPart.code]: toolResultStreamPart
714
- };
715
- var StreamStringPrefixes = {
716
- [textStreamPart.name]: textStreamPart.code,
717
- [functionCallStreamPart.name]: functionCallStreamPart.code,
718
- [dataStreamPart.name]: dataStreamPart.code,
719
- [errorStreamPart.name]: errorStreamPart.code,
720
- [assistantMessageStreamPart.name]: assistantMessageStreamPart.code,
721
- [assistantControlDataStreamPart.name]: assistantControlDataStreamPart.code,
722
- [dataMessageStreamPart.name]: dataMessageStreamPart.code,
723
- [toolCallsStreamPart.name]: toolCallsStreamPart.code,
724
- [messageAnnotationsStreamPart.name]: messageAnnotationsStreamPart.code,
725
- [toolCallStreamPart.name]: toolCallStreamPart.code,
726
- [toolResultStreamPart.name]: toolResultStreamPart.code
727
- };
728
- var validCodes = streamParts.map((part) => part.code);
729
- var parseStreamPart = (line) => {
730
- const firstSeparatorIndex = line.indexOf(":");
731
- if (firstSeparatorIndex === -1) {
732
- throw new Error("Failed to parse stream string. No separator found.");
733
- }
734
- const prefix = line.slice(0, firstSeparatorIndex);
735
- if (!validCodes.includes(prefix)) {
736
- throw new Error(`Failed to parse stream string. Invalid code ${prefix}.`);
737
- }
738
- const code = prefix;
739
- const textValue = line.slice(firstSeparatorIndex + 1);
740
- const jsonValue = JSON.parse(textValue);
741
- return streamPartsByCode[code].parse(jsonValue);
742
- };
743
-
744
- // shared/read-data-stream.ts
745
- var NEWLINE = "\n".charCodeAt(0);
746
- function concatChunks(chunks, totalLength) {
747
- const concatenatedChunks = new Uint8Array(totalLength);
748
- let offset = 0;
749
- for (const chunk of chunks) {
750
- concatenatedChunks.set(chunk, offset);
751
- offset += chunk.length;
752
- }
753
- chunks.length = 0;
754
- return concatenatedChunks;
755
- }
756
- async function* readDataStream(reader, {
757
- isAborted
758
- } = {}) {
759
- const decoder = new TextDecoder();
760
- const chunks = [];
761
- let totalLength = 0;
762
- while (true) {
763
- const { value } = await reader.read();
764
- if (value) {
765
- chunks.push(value);
766
- totalLength += value.length;
767
- if (value[value.length - 1] !== NEWLINE) {
768
- continue;
769
- }
770
- }
771
- if (chunks.length === 0) {
772
- break;
773
- }
774
- const concatenatedChunks = concatChunks(chunks, totalLength);
775
- totalLength = 0;
776
- const streamParts2 = decoder.decode(concatenatedChunks, { stream: true }).split("\n").filter((line) => line !== "").map(parseStreamPart);
777
- for (const streamPart of streamParts2) {
778
- yield streamPart;
779
- }
780
- if (isAborted == null ? void 0 : isAborted()) {
781
- reader.cancel();
782
- break;
783
- }
784
- }
785
- }
786
-
787
- // shared/parse-complex-response.ts
788
- function assignAnnotationsToMessage(message, annotations) {
789
- if (!message || !annotations || !annotations.length)
790
- return message;
791
- return { ...message, annotations: [...annotations] };
792
- }
793
- async function parseComplexResponse({
794
- reader,
795
- abortControllerRef,
796
- update,
797
- onFinish,
798
- generateId: generateId2 = generateId,
799
- getCurrentDate = () => /* @__PURE__ */ new Date()
800
- }) {
801
- const createdAt = getCurrentDate();
802
- const prefixMap = {
803
- data: []
804
- };
805
- let message_annotations = void 0;
806
- for await (const { type, value } of readDataStream(reader, {
807
- isAborted: () => (abortControllerRef == null ? void 0 : abortControllerRef.current) === null
808
- })) {
809
- if (type === "text") {
810
- if (prefixMap["text"]) {
811
- prefixMap["text"] = {
812
- ...prefixMap["text"],
813
- content: (prefixMap["text"].content || "") + value
814
- };
815
- } else {
816
- prefixMap["text"] = {
817
- id: generateId2(),
818
- role: "assistant",
819
- content: value,
820
- createdAt
821
- };
822
- }
823
- }
824
- if (type === "tool_call") {
825
- if (prefixMap.text == null) {
826
- prefixMap.text = {
827
- id: generateId2(),
828
- role: "assistant",
829
- content: "",
830
- createdAt
831
- };
832
- }
833
- if (prefixMap.text.toolInvocations == null) {
834
- prefixMap.text.toolInvocations = [];
835
- }
836
- prefixMap.text.toolInvocations.push(value);
837
- } else if (type === "tool_result") {
838
- if (prefixMap.text == null) {
839
- prefixMap.text = {
840
- id: generateId2(),
841
- role: "assistant",
842
- content: "",
843
- createdAt
844
- };
845
- }
846
- if (prefixMap.text.toolInvocations == null) {
847
- prefixMap.text.toolInvocations = [];
848
- }
849
- const toolInvocationIndex = prefixMap.text.toolInvocations.findIndex(
850
- (invocation) => invocation.toolCallId === value.toolCallId
851
- );
852
- if (toolInvocationIndex !== -1) {
853
- prefixMap.text.toolInvocations[toolInvocationIndex] = value;
854
- } else {
855
- prefixMap.text.toolInvocations.push(value);
856
- }
857
- }
858
- let functionCallMessage = null;
859
- if (type === "function_call") {
860
- prefixMap["function_call"] = {
861
- id: generateId2(),
862
- role: "assistant",
863
- content: "",
864
- function_call: value.function_call,
865
- name: value.function_call.name,
866
- createdAt
867
- };
868
- functionCallMessage = prefixMap["function_call"];
869
- }
870
- let toolCallMessage = null;
871
- if (type === "tool_calls") {
872
- prefixMap["tool_calls"] = {
873
- id: generateId2(),
874
- role: "assistant",
875
- content: "",
876
- tool_calls: value.tool_calls,
877
- createdAt
878
- };
879
- toolCallMessage = prefixMap["tool_calls"];
880
- }
881
- if (type === "data") {
882
- prefixMap["data"].push(...value);
883
- }
884
- let responseMessage = prefixMap["text"];
885
- if (type === "message_annotations") {
886
- if (!message_annotations) {
887
- message_annotations = [...value];
888
- } else {
889
- message_annotations.push(...value);
890
- }
891
- functionCallMessage = assignAnnotationsToMessage(
892
- prefixMap["function_call"],
893
- message_annotations
894
- );
895
- toolCallMessage = assignAnnotationsToMessage(
896
- prefixMap["tool_calls"],
897
- message_annotations
898
- );
899
- responseMessage = assignAnnotationsToMessage(
900
- prefixMap["text"],
901
- message_annotations
902
- );
903
- }
904
- if (message_annotations == null ? void 0 : message_annotations.length) {
905
- const messagePrefixKeys = [
906
- "text",
907
- "function_call",
908
- "tool_calls"
909
- ];
910
- messagePrefixKeys.forEach((key) => {
911
- if (prefixMap[key]) {
912
- prefixMap[key].annotations = [...message_annotations];
913
- }
914
- });
915
- }
916
- const merged = [functionCallMessage, toolCallMessage, responseMessage].filter(Boolean).map((message) => ({
917
- ...assignAnnotationsToMessage(message, message_annotations)
918
- }));
919
- update(merged, [...prefixMap["data"]]);
920
- }
921
- onFinish == null ? void 0 : onFinish(prefixMap);
922
- return {
923
- messages: [
924
- prefixMap.text,
925
- prefixMap.function_call,
926
- prefixMap.tool_calls
927
- ].filter(Boolean),
928
- data: prefixMap.data
929
- };
930
- }
931
-
932
- // shared/utils.ts
933
- function createChunkDecoder(complex) {
934
- const decoder = new TextDecoder();
935
- if (!complex) {
936
- return function(chunk) {
937
- if (!chunk)
938
- return "";
939
- return decoder.decode(chunk, { stream: true });
940
- };
941
- }
942
- return function(chunk) {
943
- const decoded = decoder.decode(chunk, { stream: true }).split("\n").filter((line) => line !== "");
944
- return decoded.map(parseStreamPart).filter(Boolean);
945
- };
946
- }
947
-
948
- // shared/call-chat-api.ts
949
- async function callChatApi({
950
- api,
951
- messages,
952
- body,
953
- streamMode = "stream-data",
954
- credentials,
955
- headers,
956
- abortController,
957
- restoreMessagesOnFailure,
958
- onResponse,
959
- onUpdate,
960
- onFinish,
961
- generateId: generateId2
962
- }) {
963
- var _a;
964
- const response = await fetch(api, {
965
- method: "POST",
966
- body: JSON.stringify({
967
- messages,
968
- ...body
969
- }),
970
- headers: {
971
- "Content-Type": "application/json",
972
- ...headers
973
- },
974
- signal: (_a = abortController == null ? void 0 : abortController()) == null ? void 0 : _a.signal,
975
- credentials
976
- }).catch((err) => {
977
- restoreMessagesOnFailure();
978
- throw err;
979
- });
980
- if (onResponse) {
981
- try {
982
- await onResponse(response);
983
- } catch (err) {
984
- throw err;
985
- }
986
- }
987
- if (!response.ok) {
988
- restoreMessagesOnFailure();
989
- throw new Error(
990
- await response.text() || "Failed to fetch the chat response."
991
- );
992
- }
993
- if (!response.body) {
994
- throw new Error("The response body is empty.");
995
- }
996
- const reader = response.body.getReader();
997
- switch (streamMode) {
998
- case "text": {
999
- const decoder = createChunkDecoder();
1000
- const resultMessage = {
1001
- id: generateId2(),
1002
- createdAt: /* @__PURE__ */ new Date(),
1003
- role: "assistant",
1004
- content: ""
1005
- };
1006
- while (true) {
1007
- const { done, value } = await reader.read();
1008
- if (done) {
1009
- break;
1010
- }
1011
- resultMessage.content += decoder(value);
1012
- resultMessage.id = generateId2();
1013
- onUpdate([{ ...resultMessage }], []);
1014
- if ((abortController == null ? void 0 : abortController()) === null) {
1015
- reader.cancel();
1016
- break;
1017
- }
1018
- }
1019
- onFinish == null ? void 0 : onFinish(resultMessage);
1020
- return {
1021
- messages: [resultMessage],
1022
- data: []
1023
- };
1024
- }
1025
- case "stream-data": {
1026
- return await parseComplexResponse({
1027
- reader,
1028
- abortControllerRef: abortController != null ? { current: abortController() } : void 0,
1029
- update: onUpdate,
1030
- onFinish(prefixMap) {
1031
- if (onFinish && prefixMap.text != null) {
1032
- onFinish(prefixMap.text);
1033
- }
1034
- },
1035
- generateId: generateId2
1036
- });
1037
- }
1038
- default: {
1039
- const exhaustiveCheck = streamMode;
1040
- throw new Error(`Unknown stream mode: ${exhaustiveCheck}`);
1041
- }
1042
- }
1043
- }
1044
-
1045
- // shared/process-chat-stream.ts
1046
- async function processChatStream({
1047
- getStreamedResponse: getStreamedResponse2,
1048
- experimental_onFunctionCall,
1049
- experimental_onToolCall,
1050
- updateChatRequest,
1051
- getCurrentMessages
1052
- }) {
1053
- while (true) {
1054
- const messagesAndDataOrJustMessage = await getStreamedResponse2();
1055
- if ("messages" in messagesAndDataOrJustMessage) {
1056
- let hasFollowingResponse = false;
1057
- for (const message of messagesAndDataOrJustMessage.messages) {
1058
- if ((message.function_call === void 0 || typeof message.function_call === "string") && (message.tool_calls === void 0 || typeof message.tool_calls === "string")) {
1059
- continue;
1060
- }
1061
- hasFollowingResponse = true;
1062
- if (experimental_onFunctionCall) {
1063
- const functionCall = message.function_call;
1064
- if (typeof functionCall !== "object") {
1065
- console.warn(
1066
- "experimental_onFunctionCall should not be defined when using tools"
1067
- );
1068
- continue;
1069
- }
1070
- const functionCallResponse = await experimental_onFunctionCall(
1071
- getCurrentMessages(),
1072
- functionCall
1073
- );
1074
- if (functionCallResponse === void 0) {
1075
- hasFollowingResponse = false;
1076
- break;
1077
- }
1078
- updateChatRequest(functionCallResponse);
1079
- }
1080
- if (experimental_onToolCall) {
1081
- const toolCalls = message.tool_calls;
1082
- if (!Array.isArray(toolCalls) || toolCalls.some((toolCall) => typeof toolCall !== "object")) {
1083
- console.warn(
1084
- "experimental_onToolCall should not be defined when using tools"
1085
- );
1086
- continue;
1087
- }
1088
- const toolCallResponse = await experimental_onToolCall(getCurrentMessages(), toolCalls);
1089
- if (toolCallResponse === void 0) {
1090
- hasFollowingResponse = false;
1091
- break;
1092
- }
1093
- updateChatRequest(toolCallResponse);
1094
- }
1095
- }
1096
- if (!hasFollowingResponse) {
1097
- break;
1098
- }
1099
- } else {
1100
- let fixFunctionCallArguments2 = function(response) {
1101
- for (const message of response.messages) {
1102
- if (message.tool_calls !== void 0) {
1103
- for (const toolCall of message.tool_calls) {
1104
- if (typeof toolCall === "object") {
1105
- if (toolCall.function.arguments && typeof toolCall.function.arguments !== "string") {
1106
- toolCall.function.arguments = JSON.stringify(
1107
- toolCall.function.arguments
1108
- );
1109
- }
1110
- }
1111
- }
1112
- }
1113
- if (message.function_call !== void 0) {
1114
- if (typeof message.function_call === "object") {
1115
- if (message.function_call.arguments && typeof message.function_call.arguments !== "string") {
1116
- message.function_call.arguments = JSON.stringify(
1117
- message.function_call.arguments
1118
- );
1119
- }
1120
- }
1121
- }
1122
- }
1123
- };
1124
- var fixFunctionCallArguments = fixFunctionCallArguments2;
1125
- const streamedResponseMessage = messagesAndDataOrJustMessage;
1126
- if ((streamedResponseMessage.function_call === void 0 || typeof streamedResponseMessage.function_call === "string") && (streamedResponseMessage.tool_calls === void 0 || typeof streamedResponseMessage.tool_calls === "string")) {
1127
- break;
1128
- }
1129
- if (experimental_onFunctionCall) {
1130
- const functionCall = streamedResponseMessage.function_call;
1131
- if (!(typeof functionCall === "object")) {
1132
- console.warn(
1133
- "experimental_onFunctionCall should not be defined when using tools"
1134
- );
1135
- continue;
1136
- }
1137
- const functionCallResponse = await experimental_onFunctionCall(getCurrentMessages(), functionCall);
1138
- if (functionCallResponse === void 0)
1139
- break;
1140
- fixFunctionCallArguments2(functionCallResponse);
1141
- updateChatRequest(functionCallResponse);
1142
- }
1143
- if (experimental_onToolCall) {
1144
- const toolCalls = streamedResponseMessage.tool_calls;
1145
- if (!(typeof toolCalls === "object")) {
1146
- console.warn(
1147
- "experimental_onToolCall should not be defined when using functions"
1148
- );
1149
- continue;
1150
- }
1151
- const toolCallResponse = await experimental_onToolCall(getCurrentMessages(), toolCalls);
1152
- if (toolCallResponse === void 0)
1153
- break;
1154
- fixFunctionCallArguments2(toolCallResponse);
1155
- updateChatRequest(toolCallResponse);
1156
- }
1157
- }
1158
- }
1159
- }
1160
-
1161
- // svelte/use-chat.ts
1162
- var getStreamedResponse = async (api, chatRequest, mutate, mutateStreamData, existingData, extraMetadata, previousMessages, abortControllerRef, generateId2, streamMode, onFinish, onResponse, sendExtraMessageFields) => {
1163
- var _a, _b;
1164
- mutate(chatRequest.messages);
1165
- const constructedMessagesPayload = sendExtraMessageFields ? chatRequest.messages : chatRequest.messages.map(
1166
- ({ role, content, name, function_call, tool_calls, tool_call_id }) => ({
1167
- role,
1168
- content,
1169
- tool_call_id,
1170
- ...name !== void 0 && { name },
1171
- ...function_call !== void 0 && {
1172
- function_call
1173
- },
1174
- ...tool_calls !== void 0 && {
1175
- tool_calls
1176
- }
1177
- })
1178
- );
1179
- return await callChatApi({
1180
- api,
1181
- messages: constructedMessagesPayload,
1182
- body: {
1183
- ...extraMetadata.body,
1184
- ...(_a = chatRequest.options) == null ? void 0 : _a.body,
1185
- ...chatRequest.functions !== void 0 && {
1186
- functions: chatRequest.functions
1187
- },
1188
- ...chatRequest.function_call !== void 0 && {
1189
- function_call: chatRequest.function_call
1190
- },
1191
- ...chatRequest.tools !== void 0 && {
1192
- tools: chatRequest.tools
1193
- },
1194
- ...chatRequest.tool_choice !== void 0 && {
1195
- tool_choice: chatRequest.tool_choice
1196
- }
1197
- },
1198
- streamMode,
1199
- credentials: extraMetadata.credentials,
1200
- headers: {
1201
- ...extraMetadata.headers,
1202
- ...(_b = chatRequest.options) == null ? void 0 : _b.headers
1203
- },
1204
- abortController: () => abortControllerRef,
1205
- restoreMessagesOnFailure() {
1206
- mutate(previousMessages);
1207
- },
1208
- onResponse,
1209
- onUpdate(merged, data) {
1210
- mutate([...chatRequest.messages, ...merged]);
1211
- mutateStreamData([...existingData || [], ...data || []]);
1212
- },
1213
- onFinish,
1214
- generateId: generateId2
1215
- });
1216
- };
1217
- var uniqueId = 0;
1218
- var store = {};
1219
- function useChat({
1220
- api = "/api/chat",
1221
- id,
1222
- initialMessages = [],
1223
- initialInput = "",
1224
- sendExtraMessageFields,
1225
- experimental_onFunctionCall,
1226
- experimental_onToolCall,
1227
- streamMode,
1228
- onResponse,
1229
- onFinish,
1230
- onError,
1231
- credentials,
1232
- headers,
1233
- body,
1234
- generateId: generateId2 = generateId
1235
- } = {}) {
1236
- const chatId = id || `chat-${uniqueId++}`;
1237
- const key = `${api}|${chatId}`;
1238
- const {
1239
- data,
1240
- mutate: originalMutate,
1241
- isLoading: isSWRLoading
1242
- } = F2(key, {
1243
- fetcher: () => store[key] || initialMessages,
1244
- fallbackData: initialMessages
1245
- });
1246
- const streamData = (0, import_store.writable)(void 0);
1247
- const loading = (0, import_store.writable)(false);
1248
- data.set(initialMessages);
1249
- const mutate = (data2) => {
1250
- store[key] = data2;
1251
- return originalMutate(data2);
1252
- };
1253
- const messages = data;
1254
- let abortController = null;
1255
- const extraMetadata = {
1256
- credentials,
1257
- headers,
1258
- body
1259
- };
1260
- const error = (0, import_store.writable)(void 0);
1261
- async function triggerRequest(chatRequest) {
1262
- try {
1263
- error.set(void 0);
1264
- loading.set(true);
1265
- abortController = new AbortController();
1266
- await processChatStream({
1267
- getStreamedResponse: () => getStreamedResponse(
1268
- api,
1269
- chatRequest,
1270
- mutate,
1271
- (data2) => {
1272
- streamData.set(data2);
1273
- },
1274
- (0, import_store.get)(streamData),
1275
- extraMetadata,
1276
- (0, import_store.get)(messages),
1277
- abortController,
1278
- generateId2,
1279
- streamMode,
1280
- onFinish,
1281
- onResponse,
1282
- sendExtraMessageFields
1283
- ),
1284
- experimental_onFunctionCall,
1285
- experimental_onToolCall,
1286
- updateChatRequest: (chatRequestParam) => {
1287
- chatRequest = chatRequestParam;
1288
- },
1289
- getCurrentMessages: () => (0, import_store.get)(messages)
1290
- });
1291
- abortController = null;
1292
- return null;
1293
- } catch (err) {
1294
- if (err.name === "AbortError") {
1295
- abortController = null;
1296
- return null;
1297
- }
1298
- if (onError && err instanceof Error) {
1299
- onError(err);
1300
- }
1301
- error.set(err);
1302
- } finally {
1303
- loading.set(false);
1304
- }
1305
- }
1306
- const append = async (message, {
1307
- options,
1308
- functions,
1309
- function_call,
1310
- tools,
1311
- tool_choice
1312
- } = {}) => {
1313
- if (!message.id) {
1314
- message.id = generateId2();
1315
- }
1316
- const chatRequest = {
1317
- messages: (0, import_store.get)(messages).concat(message),
1318
- options,
1319
- ...functions !== void 0 && { functions },
1320
- ...function_call !== void 0 && { function_call },
1321
- ...tools !== void 0 && { tools },
1322
- ...tool_choice !== void 0 && { tool_choice }
1323
- };
1324
- return triggerRequest(chatRequest);
1325
- };
1326
- const reload = async ({
1327
- options,
1328
- functions,
1329
- function_call,
1330
- tools,
1331
- tool_choice
1332
- } = {}) => {
1333
- const messagesSnapshot = (0, import_store.get)(messages);
1334
- if (messagesSnapshot.length === 0)
1335
- return null;
1336
- const lastMessage = messagesSnapshot.at(-1);
1337
- if ((lastMessage == null ? void 0 : lastMessage.role) === "assistant") {
1338
- const chatRequest2 = {
1339
- messages: messagesSnapshot.slice(0, -1),
1340
- options,
1341
- ...functions !== void 0 && { functions },
1342
- ...function_call !== void 0 && { function_call },
1343
- ...tools !== void 0 && { tools },
1344
- ...tool_choice !== void 0 && { tool_choice }
1345
- };
1346
- return triggerRequest(chatRequest2);
1347
- }
1348
- const chatRequest = {
1349
- messages: messagesSnapshot,
1350
- options,
1351
- ...functions !== void 0 && { functions },
1352
- ...function_call !== void 0 && { function_call },
1353
- ...tools !== void 0 && { tools },
1354
- ...tool_choice !== void 0 && { tool_choice }
1355
- };
1356
- return triggerRequest(chatRequest);
1357
- };
1358
- const stop = () => {
1359
- if (abortController) {
1360
- abortController.abort();
1361
- abortController = null;
1362
- }
1363
- };
1364
- const setMessages = (messages2) => {
1365
- mutate(messages2);
1366
- };
1367
- const input = (0, import_store.writable)(initialInput);
1368
- const handleSubmit = (e, options = {}) => {
1369
- e.preventDefault();
1370
- const inputValue = (0, import_store.get)(input);
1371
- if (!inputValue)
1372
- return;
1373
- append(
1374
- {
1375
- content: inputValue,
1376
- role: "user",
1377
- createdAt: /* @__PURE__ */ new Date()
1378
- },
1379
- options
1380
- );
1381
- input.set("");
1382
- };
1383
- const isLoading = (0, import_store.derived)(
1384
- [isSWRLoading, loading],
1385
- ([$isSWRLoading, $loading]) => {
1386
- return $isSWRLoading || $loading;
1387
- }
1388
- );
1389
- return {
1390
- messages,
1391
- error,
1392
- append,
1393
- reload,
1394
- stop,
1395
- setMessages,
1396
- input,
1397
- handleSubmit,
1398
- isLoading,
1399
- data: streamData
1400
- };
1401
- }
1402
-
1403
- // svelte/use-completion.ts
1404
- var import_store2 = require("svelte/store");
1405
-
1406
- // shared/call-completion-api.ts
1407
- async function callCompletionApi({
1408
- api,
1409
- prompt,
1410
- credentials,
1411
- headers,
1412
- body,
1413
- streamMode = "stream-data",
1414
- setCompletion,
1415
- setLoading,
1416
- setError,
1417
- setAbortController,
1418
- onResponse,
1419
- onFinish,
1420
- onError,
1421
- onData
1422
- }) {
1423
- try {
1424
- setLoading(true);
1425
- setError(void 0);
1426
- const abortController = new AbortController();
1427
- setAbortController(abortController);
1428
- setCompletion("");
1429
- const res = await fetch(api, {
1430
- method: "POST",
1431
- body: JSON.stringify({
1432
- prompt,
1433
- ...body
1434
- }),
1435
- credentials,
1436
- headers: {
1437
- "Content-Type": "application/json",
1438
- ...headers
1439
- },
1440
- signal: abortController.signal
1441
- }).catch((err) => {
1442
- throw err;
1443
- });
1444
- if (onResponse) {
1445
- try {
1446
- await onResponse(res);
1447
- } catch (err) {
1448
- throw err;
1449
- }
1450
- }
1451
- if (!res.ok) {
1452
- throw new Error(
1453
- await res.text() || "Failed to fetch the chat response."
1454
- );
1455
- }
1456
- if (!res.body) {
1457
- throw new Error("The response body is empty.");
1458
- }
1459
- let result = "";
1460
- const reader = res.body.getReader();
1461
- switch (streamMode) {
1462
- case "text": {
1463
- const decoder = createChunkDecoder();
1464
- while (true) {
1465
- const { done, value } = await reader.read();
1466
- if (done) {
1467
- break;
1468
- }
1469
- result += decoder(value);
1470
- setCompletion(result);
1471
- if (abortController === null) {
1472
- reader.cancel();
1473
- break;
1474
- }
1475
- }
1476
- break;
1477
- }
1478
- case "stream-data": {
1479
- for await (const { type, value } of readDataStream(reader, {
1480
- isAborted: () => abortController === null
1481
- })) {
1482
- switch (type) {
1483
- case "text": {
1484
- result += value;
1485
- setCompletion(result);
1486
- break;
1487
- }
1488
- case "data": {
1489
- onData == null ? void 0 : onData(value);
1490
- break;
1491
- }
1492
- }
1493
- }
1494
- break;
1495
- }
1496
- default: {
1497
- const exhaustiveCheck = streamMode;
1498
- throw new Error(`Unknown stream mode: ${exhaustiveCheck}`);
1499
- }
1500
- }
1501
- if (onFinish) {
1502
- onFinish(prompt, result);
1503
- }
1504
- setAbortController(null);
1505
- return result;
1506
- } catch (err) {
1507
- if (err.name === "AbortError") {
1508
- setAbortController(null);
1509
- return null;
1510
- }
1511
- if (err instanceof Error) {
1512
- if (onError) {
1513
- onError(err);
1514
- }
1515
- }
1516
- setError(err);
1517
- } finally {
1518
- setLoading(false);
1519
- }
1520
- }
1521
-
1522
- // svelte/use-completion.ts
1523
- var uniqueId2 = 0;
1524
- var store2 = {};
1525
- function useCompletion({
1526
- api = "/api/completion",
1527
- id,
1528
- initialCompletion = "",
1529
- initialInput = "",
1530
- credentials,
1531
- headers,
1532
- body,
1533
- streamMode,
1534
- onResponse,
1535
- onFinish,
1536
- onError
1537
- } = {}) {
1538
- const completionId = id || `completion-${uniqueId2++}`;
1539
- const key = `${api}|${completionId}`;
1540
- const {
1541
- data,
1542
- mutate: originalMutate,
1543
- isLoading: isSWRLoading
1544
- } = F2(key, {
1545
- fetcher: () => store2[key] || initialCompletion,
1546
- fallbackData: initialCompletion
1547
- });
1548
- const streamData = (0, import_store2.writable)(void 0);
1549
- const loading = (0, import_store2.writable)(false);
1550
- data.set(initialCompletion);
1551
- const mutate = (data2) => {
1552
- store2[key] = data2;
1553
- return originalMutate(data2);
1554
- };
1555
- const completion = data;
1556
- const error = (0, import_store2.writable)(void 0);
1557
- let abortController = null;
1558
- const complete = async (prompt, options) => {
1559
- const existingData = (0, import_store2.get)(streamData);
1560
- return callCompletionApi({
1561
- api,
1562
- prompt,
1563
- credentials,
1564
- headers: {
1565
- ...headers,
1566
- ...options == null ? void 0 : options.headers
1567
- },
1568
- body: {
1569
- ...body,
1570
- ...options == null ? void 0 : options.body
1571
- },
1572
- streamMode,
1573
- setCompletion: mutate,
1574
- setLoading: (loadingState) => loading.set(loadingState),
1575
- setError: (err) => error.set(err),
1576
- setAbortController: (controller) => {
1577
- abortController = controller;
1578
- },
1579
- onResponse,
1580
- onFinish,
1581
- onError,
1582
- onData(data2) {
1583
- streamData.set([...existingData || [], ...data2 || []]);
1584
- }
1585
- });
1586
- };
1587
- const stop = () => {
1588
- if (abortController) {
1589
- abortController.abort();
1590
- abortController = null;
1591
- }
1592
- };
1593
- const setCompletion = (completion2) => {
1594
- mutate(completion2);
1595
- };
1596
- const input = (0, import_store2.writable)(initialInput);
1597
- const handleSubmit = (e) => {
1598
- e.preventDefault();
1599
- const inputValue = (0, import_store2.get)(input);
1600
- if (!inputValue)
1601
- return;
1602
- return complete(inputValue);
1603
- };
1604
- const isLoading = (0, import_store2.derived)(
1605
- [isSWRLoading, loading],
1606
- ([$isSWRLoading, $loading]) => {
1607
- return $isSWRLoading || $loading;
1608
- }
1609
- );
1610
- return {
1611
- completion,
1612
- complete,
1613
- error,
1614
- stop,
1615
- setCompletion,
1616
- input,
1617
- handleSubmit,
1618
- isLoading,
1619
- data: streamData
1620
- };
1621
- }
1622
-
1623
- // svelte/use-assistant.ts
1624
- var import_provider_utils = require("@ai-sdk/provider-utils");
1625
- var import_store3 = require("svelte/store");
1626
- var uniqueId3 = 0;
1627
- var store3 = {};
1628
- function useAssistant({
1629
- api,
1630
- threadId: threadIdParam,
1631
- credentials,
1632
- headers,
1633
- body,
1634
- onError
1635
- }) {
1636
- const threadIdStore = (0, import_store3.writable)(threadIdParam);
1637
- const key = `${api}|${threadIdParam != null ? threadIdParam : `completion-${uniqueId3++}`}`;
1638
- const messages = (0, import_store3.writable)(store3[key] || []);
1639
- const input = (0, import_store3.writable)("");
1640
- const status = (0, import_store3.writable)("awaiting_message");
1641
- const error = (0, import_store3.writable)(void 0);
1642
- let abortController = null;
1643
- const mutateMessages = (newMessages) => {
1644
- store3[key] = newMessages;
1645
- messages.set(newMessages);
1646
- };
1647
- async function append(message, requestOptions) {
1648
- var _a, _b, _c, _d;
1649
- status.set("in_progress");
1650
- abortController = new AbortController();
1651
- mutateMessages([
1652
- ...(0, import_store3.get)(messages),
1653
- { ...message, id: (_a = message.id) != null ? _a : generateId() }
1654
- ]);
1655
- input.set("");
1656
- try {
1657
- const result = await fetch(api, {
1658
- method: "POST",
1659
- credentials,
1660
- signal: abortController.signal,
1661
- headers: { "Content-Type": "application/json", ...headers },
1662
- body: JSON.stringify({
1663
- ...body,
1664
- // always use user-provided threadId when available:
1665
- threadId: (_b = threadIdParam != null ? threadIdParam : (0, import_store3.get)(threadIdStore)) != null ? _b : null,
1666
- message: message.content,
1667
- // optional request data:
1668
- data: requestOptions == null ? void 0 : requestOptions.data
1669
- })
1670
- });
1671
- if (result.body == null) {
1672
- throw new Error("The response body is empty.");
1673
- }
1674
- for await (const { type, value } of readDataStream(
1675
- result.body.getReader()
1676
- )) {
1677
- switch (type) {
1678
- case "assistant_message": {
1679
- mutateMessages([
1680
- ...(0, import_store3.get)(messages),
1681
- {
1682
- id: value.id,
1683
- role: value.role,
1684
- content: value.content[0].text.value
1685
- }
1686
- ]);
1687
- break;
1688
- }
1689
- case "text": {
1690
- mutateMessages(
1691
- (0, import_store3.get)(messages).map((msg, index, array) => {
1692
- if (index === array.length - 1) {
1693
- return { ...msg, content: msg.content + value };
1694
- }
1695
- return msg;
1696
- })
1697
- );
1698
- break;
1699
- }
1700
- case "data_message": {
1701
- mutateMessages([
1702
- ...(0, import_store3.get)(messages),
1703
- {
1704
- id: (_c = value.id) != null ? _c : generateId(),
1705
- role: "data",
1706
- content: "",
1707
- data: value.data
1708
- }
1709
- ]);
1710
- break;
1711
- }
1712
- case "assistant_control_data": {
1713
- threadIdStore.set(value.threadId);
1714
- mutateMessages(
1715
- (0, import_store3.get)(messages).map((msg, index, array) => {
1716
- if (index === array.length - 1) {
1717
- return { ...msg, id: value.messageId };
1718
- }
1719
- return msg;
1720
- })
1721
- );
1722
- break;
1723
- }
1724
- case "error": {
1725
- error.set(new Error(value));
1726
- break;
1727
- }
1728
- }
1729
- }
1730
- } catch (err) {
1731
- if ((0, import_provider_utils.isAbortError)(error) && ((_d = abortController == null ? void 0 : abortController.signal) == null ? void 0 : _d.aborted)) {
1732
- abortController = null;
1733
- return;
1734
- }
1735
- if (onError && err instanceof Error) {
1736
- onError(err);
1737
- }
1738
- error.set(err);
1739
- } finally {
1740
- abortController = null;
1741
- status.set("awaiting_message");
1742
- }
1743
- }
1744
- function setMessages(messages2) {
1745
- mutateMessages(messages2);
1746
- }
1747
- function stop() {
1748
- if (abortController) {
1749
- abortController.abort();
1750
- abortController = null;
1751
- }
1752
- }
1753
- async function submitMessage(e, requestOptions) {
1754
- e.preventDefault();
1755
- const inputValue = (0, import_store3.get)(input);
1756
- if (!inputValue)
1757
- return;
1758
- await append({ role: "user", content: inputValue }, requestOptions);
1759
- }
1760
- return {
1761
- messages,
1762
- error,
1763
- threadId: threadIdStore,
1764
- input,
1765
- append,
1766
- submitMessage,
1767
- status,
1768
- setMessages,
1769
- stop
1770
- };
1771
- }
1772
- // Annotate the CommonJS export names for ESM import in node:
1773
- 0 && (module.exports = {
1774
- useAssistant,
1775
- useChat,
1776
- useCompletion
1777
- });
1778
- //# sourceMappingURL=index.js.map