@ghuri/ai-widget 0.1.2 → 0.2.0

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.
@@ -0,0 +1,846 @@
1
+ // src/core/output.ts
2
+ function e(e) {
3
+ if (typeof e != "string") return e;
4
+ let t = e.trim();
5
+ if (!(t.startsWith("{") && t.endsWith("}")) && !(t.startsWith("[") && t.endsWith("]"))) return e;
6
+ try {
7
+ let n = JSON.parse(t);
8
+ return n && typeof n == "object" ? n : e;
9
+ } catch {
10
+ return e;
11
+ }
12
+ }
13
+ // src/core/history.ts
14
+ function t(e) {
15
+ let t = e.providerOptions?.ghuri?.attachments;
16
+ return Array.isArray(t) ? t.filter((e) => !!e && typeof e == "object" && typeof e.ref == "string" && typeof e.name == "string") : null;
17
+ }
18
+ function n(e) {
19
+ return typeof e.providerOptions?.ghuri?.note == "string";
20
+ }
21
+ function r(e) {
22
+ return typeof e == "string" ? e : (e ?? []).filter((e) => e.type === "text" && typeof e.text == "string" && !t(e) && !n(e)).map((e) => e.text).join("");
23
+ }
24
+ function i(t) {
25
+ switch (t?.type) {
26
+ case "execution-denied": return {
27
+ state: "denied",
28
+ errorText: typeof t.reason == "string" ? t.reason : void 0
29
+ };
30
+ case "error-text":
31
+ case "error-json": return {
32
+ state: "error",
33
+ errorText: typeof t.value == "string" ? t.value : JSON.stringify(t.value)
34
+ };
35
+ case void 0: return {
36
+ state: "done",
37
+ output: t
38
+ };
39
+ default: return {
40
+ state: "done",
41
+ output: e(t.value)
42
+ };
43
+ }
44
+ }
45
+ function a(e, n = [], a = /* @__PURE__ */ new Map()) {
46
+ let o = [], s = /* @__PURE__ */ new Map(), c = /* @__PURE__ */ new Map();
47
+ for (let e of n) e.title && a.set(e.toolName, e.title);
48
+ let l = null, u = 0, d = () => (l || (l = {
49
+ id: `h${u++}`,
50
+ role: "assistant",
51
+ parts: []
52
+ }, o.push(l)), l);
53
+ for (let n of e) if (n.role === "user") {
54
+ l = null;
55
+ let e = Array.isArray(n.content) ? n.content.flatMap((e) => t(e) ?? []) : [], i = r(n.content), a = [];
56
+ e.length && a.push({
57
+ kind: "attachments",
58
+ id: `h${u++}`,
59
+ attachments: e
60
+ }), (i || !e.length) && a.push({
61
+ kind: "text",
62
+ id: `h${u++}`,
63
+ text: i
64
+ }), o.push({
65
+ id: `h${u++}`,
66
+ role: "user",
67
+ parts: a
68
+ });
69
+ } else if (n.role === "assistant") {
70
+ let e = d(), t = typeof n.content == "string" ? [{
71
+ type: "text",
72
+ text: n.content
73
+ }] : n.content ?? [];
74
+ for (let n of t) if (n.type === "text" && typeof n.text == "string" && n.text) {
75
+ let t = e.parts.at(-1);
76
+ t?.kind === "text" ? t.text += n.text : e.parts.push({
77
+ kind: "text",
78
+ id: `h${u++}`,
79
+ text: n.text
80
+ });
81
+ } else if (n.type === "tool-call" && typeof n.toolCallId == "string") {
82
+ let t = a.get(n.toolName), r = {
83
+ kind: "tool",
84
+ toolCallId: n.toolCallId,
85
+ toolName: String(n.toolName ?? ""),
86
+ ...t ? { title: t } : {},
87
+ input: n.input,
88
+ state: "running"
89
+ };
90
+ s.set(r.toolCallId, r), e.parts.push(r);
91
+ } else if (n.type === "tool-approval-request" && typeof n.toolCallId == "string") {
92
+ let e = s.get(n.toolCallId);
93
+ e && (e.state = "awaiting-approval", e.approvalId = n.approvalId, c.set(n.approvalId, e));
94
+ }
95
+ } else if (n.role === "tool" && Array.isArray(n.content)) {
96
+ for (let e of n.content) if (e.type === "tool-approval-response") {
97
+ let t = c.get(e.approvalId);
98
+ t && t.state === "awaiting-approval" && (t.state = e.approved ? "running" : "denied");
99
+ } else if (e.type === "tool-result") {
100
+ let t = s.get(e.toolCallId);
101
+ t && Object.assign(t, i(e.output));
102
+ }
103
+ }
104
+ let f = new Set(n.map((e) => e.toolCallId));
105
+ for (let e of s.values()) e.state === "awaiting-approval" && !f.has(e.toolCallId) && (e.state = "denied");
106
+ return o.filter((e) => e.parts.length > 0);
107
+ }
108
+ // src/core/prepare.ts
109
+ var o = .85;
110
+ function s(e, t, n) {
111
+ let r = Math.max(e, t);
112
+ if (!r || r <= n) return {
113
+ width: e,
114
+ height: t
115
+ };
116
+ let i = n / r;
117
+ return {
118
+ width: Math.max(1, Math.round(e * i)),
119
+ height: Math.max(1, Math.round(t * i))
120
+ };
121
+ }
122
+ async function c(e, t) {
123
+ let { contentType: n } = t;
124
+ if (n === "image/gif" || typeof createImageBitmap != "function") return {
125
+ blob: e,
126
+ contentType: n
127
+ };
128
+ let r;
129
+ try {
130
+ r = await createImageBitmap(e, { imageOrientation: "from-image" });
131
+ } catch {
132
+ return {
133
+ blob: e,
134
+ contentType: n
135
+ };
136
+ }
137
+ try {
138
+ let i = s(r.width, r.height, t.maxEdge), a = await l(r, i, n);
139
+ return a ? {
140
+ blob: a,
141
+ contentType: a.type || n,
142
+ ...i
143
+ } : {
144
+ blob: e,
145
+ contentType: n,
146
+ width: r.width,
147
+ height: r.height
148
+ };
149
+ } finally {
150
+ r.close();
151
+ }
152
+ }
153
+ async function l(e, t, n) {
154
+ if (typeof OffscreenCanvas == "function") {
155
+ let r = new OffscreenCanvas(t.width, t.height), i = r.getContext("2d");
156
+ return i ? (i.drawImage(e, 0, 0, t.width, t.height), r.convertToBlob({
157
+ type: n,
158
+ quality: o
159
+ }).catch(() => null)) : null;
160
+ }
161
+ if (typeof document > "u") return null;
162
+ let r = document.createElement("canvas");
163
+ r.width = t.width, r.height = t.height;
164
+ let i = r.getContext("2d");
165
+ return i ? (i.drawImage(e, 0, 0, t.width, t.height), new Promise((e) => r.toBlob((t) => e(t), n, o))) : null;
166
+ }
167
+ // src/core/sse.ts
168
+ function u(e) {
169
+ let t = new d(), n = t.push(e);
170
+ return n.push(...t.end()), n;
171
+ }
172
+ var d = class {
173
+ buffer = "";
174
+ carry = "";
175
+ done = !1;
176
+ push(e) {
177
+ let t = this.carry + e;
178
+ this.carry = "", t.endsWith("\r") && (this.carry = "\r", t = t.slice(0, -1)), this.buffer += t.replace(/\r\n?/g, "\n");
179
+ let n = [], r = this.buffer.indexOf("\n\n");
180
+ for (; r !== -1;) {
181
+ let e = this.buffer.slice(0, r);
182
+ this.buffer = this.buffer.slice(r + 2);
183
+ let t = this.parseEvent(e);
184
+ t && n.push(t), r = this.buffer.indexOf("\n\n");
185
+ }
186
+ return n;
187
+ }
188
+ end() {
189
+ this.carry = "";
190
+ let e = this.buffer.trim();
191
+ if (this.buffer = "", !e) return [];
192
+ let t = this.parseEvent(e);
193
+ return t ? [t] : [];
194
+ }
195
+ parseEvent(e) {
196
+ let t = [];
197
+ for (let n of e.split("\n")) n.startsWith("data:") && t.push(n.slice(n.startsWith("data: ") ? 6 : 5));
198
+ if (!t.length) return null;
199
+ let n = t.join("\n");
200
+ if (n === "[DONE]") return this.done = !0, null;
201
+ try {
202
+ let e = JSON.parse(n);
203
+ return e && typeof e == "object" && typeof e.type == "string" ? e : null;
204
+ } catch {
205
+ return null;
206
+ }
207
+ }
208
+ };
209
+ async function* f(e, t) {
210
+ let n = new d(), r = new TextDecoder(), i = e.getReader(), a = () => void i.cancel().catch(() => {});
211
+ t?.addEventListener("abort", a, { once: !0 });
212
+ try {
213
+ for (;;) {
214
+ if (t?.aborted) return;
215
+ let { value: e, done: a } = await i.read();
216
+ if (a) break;
217
+ for (let t of n.push(r.decode(e, { stream: !0 }))) yield t;
218
+ }
219
+ for (let e of n.push(r.decode())) yield e;
220
+ for (let e of n.end()) yield e;
221
+ } finally {
222
+ t?.removeEventListener("abort", a), i.releaseLock();
223
+ }
224
+ }
225
+ // src/core/client.ts
226
+ var p = 3e4, m = {
227
+ accept: [
228
+ "image/jpeg",
229
+ "image/png",
230
+ "image/webp",
231
+ "image/gif"
232
+ ],
233
+ maxCount: 10,
234
+ maxBytes: 5242880,
235
+ maxEdge: 2048
236
+ };
237
+ function h(e = !1) {
238
+ return {
239
+ status: "idle",
240
+ conversationId: null,
241
+ messages: [],
242
+ pendingApprovals: [],
243
+ problem: null,
244
+ lastTurn: null,
245
+ canAttach: e,
246
+ uploads: []
247
+ };
248
+ }
249
+ function g(e) {
250
+ try {
251
+ return typeof URL.createObjectURL == "function" ? URL.createObjectURL(e) : void 0;
252
+ } catch {
253
+ return;
254
+ }
255
+ }
256
+ function _(e) {
257
+ try {
258
+ e && typeof URL.revokeObjectURL == "function" && URL.revokeObjectURL(e);
259
+ } catch {}
260
+ }
261
+ var v = class extends Error {
262
+ status;
263
+ code;
264
+ detail;
265
+ retryAfter;
266
+ fields;
267
+ constructor(e, t, n, r, i = {}) {
268
+ super(n || `HTTP ${e}`), this.status = e, this.code = t, this.detail = n, this.retryAfter = r, this.fields = i;
269
+ }
270
+ };
271
+ async function y(e) {
272
+ let t = null;
273
+ try {
274
+ t = await e.json();
275
+ } catch {}
276
+ let n = Number(e.headers.get("retry-after"));
277
+ return new v(e.status, typeof t?.code == "string" ? t.code : "", typeof t?.detail == "string" ? t.detail : "", Number.isFinite(n) && n > 0 ? n : void 0, t && typeof t == "object" && !Array.isArray(t) ? t : {});
278
+ }
279
+ function b(e) {
280
+ if (!(e instanceof v)) return { code: "unavailable" };
281
+ let { status: t, code: n, detail: r } = e, i = e.fields.attachments;
282
+ return t === 400 && Array.isArray(i) ? {
283
+ code: "photos-refused",
284
+ ...typeof i[0] == "string" ? { message: i[0] } : {}
285
+ } : t === 429 ? {
286
+ code: "throttled",
287
+ ...e.retryAfter ? { retryAfter: e.retryAfter } : {}
288
+ } : n === "turn_in_progress" ? { code: "in-progress" } : n === "conversation_too_long" ? { code: "conversation-full" } : n === "mcp_forbidden" ? { code: "forbidden" } : n === "mcp_unavailable" || t === 502 ? { code: "store-unreachable" } : n === "model_unavailable" || n === "no_active_profile" || t === 503 ? { code: "unavailable" } : {
289
+ code: "failed",
290
+ ...r ? { message: r } : {}
291
+ };
292
+ }
293
+ function x(e) {
294
+ return e instanceof DOMException ? e.name === "AbortError" : e?.name === "AbortError";
295
+ }
296
+ function S(e, t) {
297
+ let n = new Date(e.expiresAt).getTime();
298
+ return Number.isNaN(n) || n - p > t;
299
+ }
300
+ function C(e) {
301
+ return {
302
+ ...e,
303
+ messages: e.messages.map((e) => ({
304
+ ...e,
305
+ parts: e.parts.map((e) => ({ ...e }))
306
+ })),
307
+ pendingApprovals: [...e.pendingApprovals],
308
+ uploads: e.uploads.map((e) => ({ ...e }))
309
+ };
310
+ }
311
+ var w = class {
312
+ opts;
313
+ state;
314
+ view;
315
+ listeners = /* @__PURE__ */ new Set();
316
+ events = /* @__PURE__ */ new Map();
317
+ session = null;
318
+ starting = null;
319
+ controller = null;
320
+ tools = /* @__PURE__ */ new Map();
321
+ titles = /* @__PURE__ */ new Map();
322
+ retryAction = null;
323
+ generation = 0;
324
+ seq = 0;
325
+ files = /* @__PURE__ */ new Map();
326
+ previews = /* @__PURE__ */ new Set();
327
+ policy = null;
328
+ loadingPolicy = null;
329
+ constructor(e) {
330
+ this.opts = {
331
+ ...e,
332
+ apiUrl: e.apiUrl.replace(/\/+$/, "")
333
+ }, this.state = h(!1), this.view = C(this.state);
334
+ }
335
+ getState() {
336
+ return this.view;
337
+ }
338
+ subscribe(e) {
339
+ return this.listeners.add(e), () => this.listeners.delete(e);
340
+ }
341
+ on(e, t) {
342
+ let n = this.events.get(e);
343
+ return n || (n = /* @__PURE__ */ new Set(), this.events.set(e, n)), n.add(t), () => n.delete(t);
344
+ }
345
+ emit(e, t) {
346
+ for (let n of this.events.get(e) ?? []) n(t);
347
+ }
348
+ changed(e = {}) {
349
+ Object.assign(this.state, e), this.view = C(this.state);
350
+ for (let e of this.listeners) e(this.view);
351
+ }
352
+ id(e) {
353
+ return this.seq += 1, `${e}${this.seq}`;
354
+ }
355
+ now() {
356
+ return (this.opts.now ?? Date.now)();
357
+ }
358
+ async ensureSession() {
359
+ let e = this.session;
360
+ return e && S(e, this.now()) ? e : (this.session = null, this.starting ||= this.opts.startSession().then((e) => (this.session = e, e)).finally(() => {
361
+ this.starting = null;
362
+ }), this.starting);
363
+ }
364
+ async request(e, t = {}, n = !1) {
365
+ let r = await this.ensureSession(), i = new Headers(t.headers);
366
+ i.set("authorization", `Bearer ${r.sessionToken}`), t.body !== void 0 && i.set("content-type", "application/json");
367
+ let a = await (this.opts.fetch ?? fetch)(`${this.opts.apiUrl}${e}`, {
368
+ ...t,
369
+ headers: i
370
+ });
371
+ if (a.status !== 401 || n) return a;
372
+ let o = await y(a);
373
+ if (this.changed({ problem: { code: "reconnecting" } }), o.code === "user_token_expired") try {
374
+ await this.opts.refreshUserToken(r.sessionId);
375
+ } catch {
376
+ this.session = null;
377
+ }
378
+ else this.session = null;
379
+ let s = await this.request(e, t, !0);
380
+ return this.state.problem?.code === "reconnecting" && this.changed({ problem: null }), s;
381
+ }
382
+ async json(e, t = {}) {
383
+ let n = await this.request(e, t);
384
+ if (!n.ok) throw await y(n);
385
+ return await n.json();
386
+ }
387
+ async send(e) {
388
+ let t = e.trim(), n = this.state.uploads.filter((e) => e.status === "ready" && e.attachment);
389
+ if (!t && !n.length || this.busy() || this.uploading() || this.retryable()) return;
390
+ for (let e of this.state.pendingApprovals) {
391
+ let t = this.tools.get(e.toolCallId);
392
+ t && (t.state = "denied");
393
+ }
394
+ let r = n.map((e) => e.attachment), i = [];
395
+ if (r.length) {
396
+ let e = {
397
+ kind: "attachments",
398
+ id: this.id("p"),
399
+ attachments: n.map((e) => ({
400
+ ...e.attachment,
401
+ ...e.previewUrl ? { previewUrl: e.previewUrl } : {}
402
+ }))
403
+ };
404
+ i.push(e);
405
+ }
406
+ t && i.push({
407
+ kind: "text",
408
+ id: this.id("t"),
409
+ text: t
410
+ }), this.state.messages.push({
411
+ id: this.id("u"),
412
+ role: "user",
413
+ parts: i
414
+ });
415
+ for (let e of this.state.uploads) e.status !== "ready" && _(e.previewUrl);
416
+ this.files = /* @__PURE__ */ new Map(), this.changed({
417
+ pendingApprovals: [],
418
+ problem: null,
419
+ uploads: []
420
+ });
421
+ let a = this.state.conversationId;
422
+ await this.turn("/v1/chat", {
423
+ message: t,
424
+ ...a ? { conversationId: a } : {},
425
+ ...r.length ? { attachments: r } : {},
426
+ ...!a && this.opts.uploadFile ? { capabilities: { attachments: !0 } } : {}
427
+ });
428
+ }
429
+ attachmentLimits() {
430
+ let e = this.opts.attachments ?? {}, t = e.accept?.length ? e.accept : [...m.accept], n = this.policy?.accept?.length ? this.policy.accept : null;
431
+ return {
432
+ accept: n ? t.filter((e) => n.includes(e)) : t,
433
+ maxCount: Math.min(e.maxCount ?? m.maxCount, this.policy?.maxCount ?? m.maxCount, m.maxCount),
434
+ maxBytes: e.maxBytes ?? m.maxBytes,
435
+ maxEdge: e.maxEdge ?? m.maxEdge
436
+ };
437
+ }
438
+ retryable() {
439
+ return this.state.uploads.some((e) => e.status === "failed" && e.error === "upload");
440
+ }
441
+ newConversationTakesPhotos() {
442
+ return !!this.opts.uploadFile && this.policy?.enabled === !0;
443
+ }
444
+ loadCapabilities() {
445
+ return !this.opts.uploadFile || this.policy ? Promise.resolve() : (this.loadingPolicy ||= (async () => {
446
+ try {
447
+ let e = (await this.json("/v1/capabilities"))?.attachments ?? {};
448
+ this.policy = {
449
+ enabled: e.enabled === !0,
450
+ ...Array.isArray(e.accept) ? { accept: e.accept.filter((e) => typeof e == "string") } : {},
451
+ ...Number.isInteger(e.maxCount) ? { maxCount: e.maxCount } : {}
452
+ };
453
+ } catch (e) {
454
+ e instanceof v && e.status === 404 && (this.policy = { enabled: !1 });
455
+ } finally {
456
+ this.loadingPolicy = null;
457
+ }
458
+ !this.state.conversationId && this.state.canAttach !== this.newConversationTakesPhotos() && this.changed({ canAttach: this.newConversationTakesPhotos() });
459
+ })(), this.loadingPolicy);
460
+ }
461
+ uploading() {
462
+ return this.state.uploads.some((e) => e.status === "preparing" || e.status === "uploading");
463
+ }
464
+ upload(e) {
465
+ return this.state.uploads.find((t) => t.id === e);
466
+ }
467
+ refuse(e, t, n) {
468
+ e.status = "failed", e.error = t, n && (e.message = n), this.emit("attachment-error", {
469
+ name: e.name,
470
+ contentType: e.contentType,
471
+ reason: t,
472
+ ...n ? { message: n } : {}
473
+ });
474
+ }
475
+ addFiles(e) {
476
+ if (!this.state.canAttach || !this.opts.uploadFile) return;
477
+ let { accept: t, maxCount: n } = this.attachmentLimits();
478
+ for (let r of Array.from(e)) {
479
+ let e = r.name || "photo", i = r.type || "", a = {
480
+ id: this.id("f"),
481
+ name: e,
482
+ contentType: i,
483
+ size: r.size,
484
+ status: "preparing",
485
+ progress: 0
486
+ }, o = t.includes(i) ? g(r) : void 0;
487
+ o && (a.previewUrl = o, this.previews.add(o)), this.state.uploads.push(a);
488
+ let s = this.state.uploads.filter((e) => e.status !== "failed" || e.error === "upload").length;
489
+ t.includes(i) ? s > n ? this.refuse(a, "count") : (this.files.set(a.id, { file: r }), this.startUpload(a.id)) : this.refuse(a, "type");
490
+ }
491
+ this.changed();
492
+ }
493
+ removeUpload(e) {
494
+ let t = this.upload(e);
495
+ t && (this.files.get(e)?.controller?.abort(), this.files.delete(e), _(t.previewUrl), t.previewUrl && this.previews.delete(t.previewUrl), this.changed({ uploads: this.state.uploads.filter((t) => t.id !== e) }));
496
+ }
497
+ retryUpload(e) {
498
+ let t = this.upload(e);
499
+ t?.status === "failed" && t.error === "upload" && this.files.has(e) && this.startUpload(e);
500
+ }
501
+ async startUpload(e) {
502
+ let t = this.files.get(e), n = this.upload(e), r = this.opts.uploadFile;
503
+ if (!t || !n || !r) return;
504
+ let i = this.generation, a = () => i === this.generation && this.upload(e) === n, o = new AbortController();
505
+ t.controller = o, Object.assign(n, {
506
+ status: "preparing",
507
+ progress: 0,
508
+ error: void 0,
509
+ message: void 0
510
+ }), this.changed();
511
+ let { maxBytes: s, maxEdge: l } = this.attachmentLimits();
512
+ try {
513
+ let e = this.opts.prepareImage ?? c, i;
514
+ try {
515
+ i = await e(t.file, {
516
+ maxEdge: l,
517
+ contentType: n.contentType
518
+ });
519
+ } catch {
520
+ i = {
521
+ blob: t.file,
522
+ contentType: n.contentType
523
+ };
524
+ }
525
+ if (!a() || o.signal.aborted) return;
526
+ if (i.blob.size > s) {
527
+ this.refuse(n, "size"), this.changed();
528
+ return;
529
+ }
530
+ Object.assign(n, {
531
+ status: "uploading",
532
+ size: i.blob.size
533
+ }), this.changed();
534
+ let u = await r(i.blob, {
535
+ name: n.name,
536
+ contentType: i.contentType,
537
+ size: i.blob.size,
538
+ ...i.width ? { width: i.width } : {},
539
+ ...i.height ? { height: i.height } : {},
540
+ signal: o.signal,
541
+ onProgress: (e) => {
542
+ a() && n.status === "uploading" && (n.progress = Math.max(0, Math.min(1, Number(e) || 0)), this.changed());
543
+ }
544
+ });
545
+ if (!a() || o.signal.aborted) return;
546
+ if (!u || typeof u.ref != "string" || !u.ref) throw Error("The upload gave no reference.");
547
+ Object.assign(n, {
548
+ status: "ready",
549
+ progress: 1,
550
+ attachment: {
551
+ ...u,
552
+ name: u.name || n.name,
553
+ contentType: u.contentType || i.contentType,
554
+ ...i.width && !u.width ? { width: i.width } : {},
555
+ ...i.height && !u.height ? { height: i.height } : {}
556
+ }
557
+ }), this.changed();
558
+ } catch (e) {
559
+ if (!a() || x(e) || o.signal.aborted) return;
560
+ this.refuse(n, "upload", e instanceof Error && e.message ? e.message : void 0), this.changed();
561
+ }
562
+ }
563
+ dropPhotos() {
564
+ for (let e of this.files.values()) e.controller?.abort();
565
+ this.files = /* @__PURE__ */ new Map();
566
+ for (let e of this.previews) _(e);
567
+ this.previews = /* @__PURE__ */ new Set();
568
+ }
569
+ async decide(e) {
570
+ let t = this.state.conversationId;
571
+ if (!t || this.busy() || !this.state.pendingApprovals.length) return;
572
+ let n = this.state.pendingApprovals, r = new Map(e.map((e) => [e.approvalId, e]));
573
+ for (let e of n) {
574
+ let t = this.tools.get(e.toolCallId);
575
+ t && (t.state = r.get(e.approvalId)?.approved ? "running" : "denied");
576
+ }
577
+ if (this.changed({
578
+ pendingApprovals: [],
579
+ problem: null
580
+ }), await this.turn(`/v1/conversations/${encodeURIComponent(t)}/approvals`, { decisions: e }) === "not-sent") {
581
+ for (let e of n) {
582
+ let t = this.tools.get(e.toolCallId);
583
+ t && (t.state = "awaiting-approval");
584
+ }
585
+ this.retryAction = () => this.decide(e), this.changed({
586
+ pendingApprovals: n,
587
+ status: "awaiting-approval"
588
+ });
589
+ }
590
+ }
591
+ approveAll() {
592
+ return this.decide(this.state.pendingApprovals.map((e) => ({
593
+ approvalId: e.approvalId,
594
+ approved: !0
595
+ })));
596
+ }
597
+ rejectAll(e) {
598
+ return this.decide(this.state.pendingApprovals.map((t) => ({
599
+ approvalId: t.approvalId,
600
+ approved: !1,
601
+ ...e ? { reason: e } : {}
602
+ })));
603
+ }
604
+ stop() {
605
+ this.controller?.abort();
606
+ }
607
+ async retry() {
608
+ let e = this.retryAction;
609
+ e && !this.busy() && (this.retryAction = null, this.changed({ problem: null }), await e());
610
+ }
611
+ dismissProblem() {
612
+ this.changed({ problem: null });
613
+ }
614
+ newConversation() {
615
+ this.generation += 1, this.controller?.abort(), this.dropPhotos(), this.tools = /* @__PURE__ */ new Map(), this.retryAction = null, this.state = h(this.newConversationTakesPhotos()), this.changed(), this.loadCapabilities();
616
+ }
617
+ async listConversations(e = {}) {
618
+ let t = new URLSearchParams({
619
+ limit: String(e.limit ?? 30),
620
+ offset: String(e.offset ?? 0)
621
+ });
622
+ return this.json(`/v1/conversations?${t}`);
623
+ }
624
+ async openConversation(e) {
625
+ this.generation += 1;
626
+ let t = this.generation;
627
+ this.controller?.abort(), this.changed({
628
+ status: "loading",
629
+ problem: null
630
+ });
631
+ try {
632
+ let n = await this.json(`/v1/conversations/${encodeURIComponent(e)}`);
633
+ if (t !== this.generation) return;
634
+ for (let [e, t] of Object.entries(n.toolTitles ?? {})) typeof t == "string" && t && this.titles.set(e, t);
635
+ let r = n.pendingApprovals ?? [];
636
+ for (let e of r) e.title && this.titles.set(e.toolName, e.title);
637
+ let i = a(n.messages ?? [], r, this.titles);
638
+ this.tools = /* @__PURE__ */ new Map();
639
+ for (let e of i) for (let t of e.parts) t.kind === "tool" && this.tools.set(t.toolCallId, t);
640
+ this.keepPreviews(r), this.retryAction = null, this.dropPhotos(), this.state = {
641
+ ...h(!!this.opts.uploadFile && n.attachments === !0),
642
+ conversationId: e,
643
+ messages: i,
644
+ pendingApprovals: r,
645
+ status: r.length ? "awaiting-approval" : "idle"
646
+ }, this.changed();
647
+ } catch (n) {
648
+ if (t !== this.generation) return;
649
+ this.retryAction = () => this.openConversation(e), this.changed({
650
+ status: "idle",
651
+ problem: b(n)
652
+ });
653
+ }
654
+ }
655
+ async reload() {
656
+ this.state.conversationId && await this.openConversation(this.state.conversationId);
657
+ }
658
+ async end() {
659
+ this.controller?.abort();
660
+ let e = this.session;
661
+ this.session = null, this.newConversation(), e && await this.opts.endSession?.(e.sessionId);
662
+ }
663
+ busy() {
664
+ return this.state.status === "sending" || this.state.status === "streaming" || this.state.status === "loading";
665
+ }
666
+ async turn(e, t) {
667
+ let n = this.generation, r = () => n === this.generation, i = {
668
+ id: this.id("a"),
669
+ role: "assistant",
670
+ parts: []
671
+ };
672
+ this.state.messages.push(i), this.changed({ status: "sending" });
673
+ let a = new AbortController();
674
+ this.controller = a;
675
+ let o;
676
+ try {
677
+ if (o = await this.request(e, {
678
+ method: "POST",
679
+ body: JSON.stringify(t),
680
+ headers: { accept: "text/event-stream, application/json;q=0.9" },
681
+ signal: a.signal
682
+ }), !o.ok) throw await y(o);
683
+ } catch (n) {
684
+ if (this.controller === a && (this.controller = null), !r()) return "answered";
685
+ if (this.drop(i), x(n)) return this.changed({ status: "idle" }), "not-sent";
686
+ let o = b(n);
687
+ if (o.code === "photos-refused") {
688
+ let e = this.state.messages.at(-1);
689
+ return e?.role === "user" && this.drop(e), this.policy = null, this.changed({
690
+ status: "idle",
691
+ problem: o,
692
+ canAttach: !1
693
+ }), this.loadCapabilities(), "not-sent";
694
+ }
695
+ return this.retryAction = () => this.turn(e, t).then(() => void 0), this.changed({
696
+ status: "idle",
697
+ problem: o
698
+ }), "not-sent";
699
+ }
700
+ if (!r()) return "answered";
701
+ this.changed({ status: "streaming" });
702
+ let s = !1, c = null, l = !1, u = /* @__PURE__ */ new Map();
703
+ try {
704
+ let e = o.body ? f(o.body, a.signal) : T(await o.text());
705
+ for await (let t of e) {
706
+ if (!r()) break;
707
+ t.type === "finish" ? s = !0 : t.type === "data-turn" && (c = t.data), this.apply(t, i, u), this.changed();
708
+ }
709
+ } catch (e) {
710
+ x(e) || (l = !0);
711
+ } finally {
712
+ this.controller === a && (this.controller = null);
713
+ }
714
+ if (!r()) return "answered";
715
+ if (i.parts.length || this.drop(i), c) this.finishTurn(c);
716
+ else {
717
+ let e = a.signal.aborted;
718
+ this.settleUnfinished(e), e || !l && s || this.state.problem || (this.state.problem = { code: "cut-off" }), this.changed({ status: this.state.pendingApprovals.length ? "awaiting-approval" : "idle" });
719
+ }
720
+ return "answered";
721
+ }
722
+ settleUnfinished(e) {
723
+ let t = e ? "Stopped before it finished." : "The reply was cut off before it finished.";
724
+ for (let e of this.tools.values()) (e.state === "input" || e.state === "running") && (e.state = "error", e.errorText = e.approvalId ? `${t} The result was not recorded; check before trying again.` : t);
725
+ }
726
+ drop(e) {
727
+ this.state.messages = this.state.messages.filter((t) => t !== e);
728
+ }
729
+ finishTurn(e) {
730
+ this.settleUnfinished(!1);
731
+ let t = e.pendingApprovals ?? [];
732
+ for (let e of t) e.title && this.titles.set(e.toolName, e.title);
733
+ this.keepPreviews(t);
734
+ let n = this.state.problem;
735
+ if (e.userTokenExpired) {
736
+ n = { code: "token-expired" };
737
+ let e = this.session;
738
+ e && this.opts.refreshUserToken(e.sessionId).catch(() => this.session = null);
739
+ } else e.limitReached === "steps" ? n = { code: "step-limit" } : e.status === "error" && (n = e.limitReached === "conversation" ? { code: "conversation-full" } : e.limitReached === "output" ? { code: e.cut === "text" ? "answer-cut" : "too-long" } : {
740
+ code: "failed",
741
+ ...e.error ? { message: e.error } : {}
742
+ });
743
+ this.changed({
744
+ conversationId: e.conversationId ?? this.state.conversationId,
745
+ pendingApprovals: t,
746
+ lastTurn: e,
747
+ problem: n,
748
+ status: t.length ? "awaiting-approval" : "idle"
749
+ }), t.length && this.emit("approval-pending", { approvals: t }), this.emit("turn-end", e);
750
+ }
751
+ keepPreviews(e) {
752
+ for (let t of e) {
753
+ let e = this.tools.get(t.toolCallId);
754
+ e && t.preview && (e.preview = t.preview);
755
+ }
756
+ }
757
+ apply(t, n, r) {
758
+ let i = t;
759
+ switch (t.type) {
760
+ case "start": {
761
+ let e = i.messageMetadata?.conversationId;
762
+ typeof e == "string" && (this.state.conversationId = e);
763
+ return;
764
+ }
765
+ case "text-start": {
766
+ let e = {
767
+ kind: "text",
768
+ id: this.id("t"),
769
+ text: ""
770
+ };
771
+ r.set(String(i.id), e), n.parts.push(e);
772
+ return;
773
+ }
774
+ case "text-delta": {
775
+ let e = r.get(String(i.id));
776
+ e || (e = {
777
+ kind: "text",
778
+ id: this.id("t"),
779
+ text: ""
780
+ }, r.set(String(i.id), e), n.parts.push(e)), e.text += String(i.delta ?? "");
781
+ return;
782
+ }
783
+ case "tool-input-start":
784
+ case "tool-input-available": {
785
+ let e = this.toolPart(i, n);
786
+ t.type === "tool-input-available" && (e.input = i.input, e.state === "input" && (e.state = "running"));
787
+ return;
788
+ }
789
+ case "tool-input-error": {
790
+ let e = this.toolPart(i, n);
791
+ e.state = "error", e.errorText = String(i.errorText ?? "");
792
+ return;
793
+ }
794
+ case "tool-approval-request": {
795
+ let e = this.tools.get(String(i.toolCallId));
796
+ e && (e.state = "awaiting-approval", e.approvalId = String(i.approvalId));
797
+ return;
798
+ }
799
+ case "tool-output-available":
800
+ case "tool-output-error": {
801
+ let n = this.tools.get(String(i.toolCallId));
802
+ if (!n) return;
803
+ t.type === "tool-output-available" ? (n.state = "done", n.output = e(i.output)) : (n.state = "error", n.errorText = String(i.errorText ?? "")), this.emit("tool-result", {
804
+ toolCallId: n.toolCallId,
805
+ toolName: n.toolName,
806
+ ...n.title ? { title: n.title } : {},
807
+ input: n.input,
808
+ ...n.state === "done" ? { output: n.output } : { error: n.errorText }
809
+ });
810
+ return;
811
+ }
812
+ case "tool-output-denied": {
813
+ let e = this.tools.get(String(i.toolCallId));
814
+ e && (e.state = "denied");
815
+ return;
816
+ }
817
+ case "error":
818
+ this.state.problem = {
819
+ code: "failed",
820
+ ...i.errorText ? { message: String(i.errorText) } : {}
821
+ };
822
+ return;
823
+ default: return;
824
+ }
825
+ }
826
+ toolPart(e, t) {
827
+ let n = String(e.toolCallId), r = this.tools.get(n);
828
+ if (r || (r = {
829
+ kind: "tool",
830
+ toolCallId: n,
831
+ toolName: String(e.toolName ?? ""),
832
+ state: "input"
833
+ }, this.tools.set(n, r), t.parts.push(r)), typeof e.title == "string" && e.title) r.title = e.title, this.titles.set(r.toolName, e.title);
834
+ else if (!r.title) {
835
+ let e = this.titles.get(r.toolName);
836
+ e && (r.title = e);
837
+ }
838
+ return r;
839
+ }
840
+ };
841
+ async function* T(e) {
842
+ yield* u(e);
843
+ }
844
+ export { u as a, s as c, d as i, a as l, w as n, f as o, b as r, c as s, m as t, e as u };
845
+
846
+ //# sourceMappingURL=core-HrvNVLh8.js.map