@ghuri/ai-widget 0.1.3 → 0.3.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,875 @@
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
+ allowances: []
248
+ };
249
+ }
250
+ function g(e) {
251
+ try {
252
+ return typeof URL.createObjectURL == "function" ? URL.createObjectURL(e) : void 0;
253
+ } catch {
254
+ return;
255
+ }
256
+ }
257
+ function _(e) {
258
+ try {
259
+ e && typeof URL.revokeObjectURL == "function" && URL.revokeObjectURL(e);
260
+ } catch {}
261
+ }
262
+ var v = class extends Error {
263
+ status;
264
+ code;
265
+ detail;
266
+ retryAfter;
267
+ fields;
268
+ constructor(e, t, n, r, i = {}) {
269
+ super(n || `HTTP ${e}`), this.status = e, this.code = t, this.detail = n, this.retryAfter = r, this.fields = i;
270
+ }
271
+ };
272
+ async function y(e) {
273
+ let t = null;
274
+ try {
275
+ t = await e.json();
276
+ } catch {}
277
+ let n = Number(e.headers.get("retry-after"));
278
+ 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 : {});
279
+ }
280
+ function b(e) {
281
+ if (!(e instanceof v)) return { code: "unavailable" };
282
+ let { status: t, code: n, detail: r } = e, i = e.fields.attachments;
283
+ return t === 400 && Array.isArray(i) ? {
284
+ code: "photos-refused",
285
+ ...typeof i[0] == "string" ? { message: i[0] } : {}
286
+ } : t === 429 ? {
287
+ code: "throttled",
288
+ ...e.retryAfter ? { retryAfter: e.retryAfter } : {}
289
+ } : 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" } : {
290
+ code: "failed",
291
+ ...r ? { message: r } : {}
292
+ };
293
+ }
294
+ function x(e) {
295
+ return e instanceof DOMException ? e.name === "AbortError" : e?.name === "AbortError";
296
+ }
297
+ function S(e, t) {
298
+ let n = new Date(e.expiresAt).getTime();
299
+ return Number.isNaN(n) || n - p > t;
300
+ }
301
+ function C(e) {
302
+ return {
303
+ ...e,
304
+ messages: e.messages.map((e) => ({
305
+ ...e,
306
+ parts: e.parts.map((e) => ({ ...e }))
307
+ })),
308
+ pendingApprovals: [...e.pendingApprovals],
309
+ uploads: e.uploads.map((e) => ({ ...e })),
310
+ allowances: [...e.allowances]
311
+ };
312
+ }
313
+ var w = class {
314
+ opts;
315
+ state;
316
+ view;
317
+ listeners = /* @__PURE__ */ new Set();
318
+ events = /* @__PURE__ */ new Map();
319
+ session = null;
320
+ starting = null;
321
+ controller = null;
322
+ tools = /* @__PURE__ */ new Map();
323
+ titles = /* @__PURE__ */ new Map();
324
+ retryAction = null;
325
+ generation = 0;
326
+ seq = 0;
327
+ files = /* @__PURE__ */ new Map();
328
+ previews = /* @__PURE__ */ new Set();
329
+ policy = null;
330
+ loadingPolicy = null;
331
+ constructor(e) {
332
+ this.opts = {
333
+ ...e,
334
+ apiUrl: e.apiUrl.replace(/\/+$/, "")
335
+ }, this.state = h(!1), this.view = C(this.state);
336
+ }
337
+ getState() {
338
+ return this.view;
339
+ }
340
+ subscribe(e) {
341
+ return this.listeners.add(e), () => this.listeners.delete(e);
342
+ }
343
+ on(e, t) {
344
+ let n = this.events.get(e);
345
+ return n || (n = /* @__PURE__ */ new Set(), this.events.set(e, n)), n.add(t), () => n.delete(t);
346
+ }
347
+ emit(e, t) {
348
+ for (let n of this.events.get(e) ?? []) n(t);
349
+ }
350
+ changed(e = {}) {
351
+ Object.assign(this.state, e), this.view = C(this.state);
352
+ for (let e of this.listeners) e(this.view);
353
+ }
354
+ id(e) {
355
+ return this.seq += 1, `${e}${this.seq}`;
356
+ }
357
+ now() {
358
+ return (this.opts.now ?? Date.now)();
359
+ }
360
+ async ensureSession() {
361
+ let e = this.session;
362
+ return e && S(e, this.now()) ? e : (this.session = null, this.starting ||= this.opts.startSession().then((e) => (this.session = e, e)).finally(() => {
363
+ this.starting = null;
364
+ }), this.starting);
365
+ }
366
+ async request(e, t = {}, n = !1) {
367
+ let r = await this.ensureSession(), i = new Headers(t.headers);
368
+ i.set("authorization", `Bearer ${r.sessionToken}`), t.body !== void 0 && i.set("content-type", "application/json");
369
+ let a = await (this.opts.fetch ?? fetch)(`${this.opts.apiUrl}${e}`, {
370
+ ...t,
371
+ headers: i
372
+ });
373
+ if (a.status !== 401 || n) return a;
374
+ let o = await y(a);
375
+ if (this.changed({ problem: { code: "reconnecting" } }), o.code === "user_token_expired") try {
376
+ await this.opts.refreshUserToken(r.sessionId);
377
+ } catch {
378
+ this.session = null;
379
+ }
380
+ else this.session = null;
381
+ let s = await this.request(e, t, !0);
382
+ return this.state.problem?.code === "reconnecting" && this.changed({ problem: null }), s;
383
+ }
384
+ async json(e, t = {}) {
385
+ let n = await this.request(e, t);
386
+ if (!n.ok) throw await y(n);
387
+ return await n.json();
388
+ }
389
+ async send(e) {
390
+ let t = e.trim(), n = this.state.uploads.filter((e) => e.status === "ready" && e.attachment);
391
+ if (!t && !n.length || this.busy() || this.uploading() || this.retryable()) return;
392
+ for (let e of this.state.pendingApprovals) {
393
+ let t = this.tools.get(e.toolCallId);
394
+ t && (t.state = "denied");
395
+ }
396
+ let r = n.map((e) => e.attachment), i = [];
397
+ if (r.length) {
398
+ let e = {
399
+ kind: "attachments",
400
+ id: this.id("p"),
401
+ attachments: n.map((e) => ({
402
+ ...e.attachment,
403
+ ...e.previewUrl ? { previewUrl: e.previewUrl } : {}
404
+ }))
405
+ };
406
+ i.push(e);
407
+ }
408
+ t && i.push({
409
+ kind: "text",
410
+ id: this.id("t"),
411
+ text: t
412
+ }), this.state.messages.push({
413
+ id: this.id("u"),
414
+ role: "user",
415
+ parts: i
416
+ });
417
+ for (let e of this.state.uploads) e.status !== "ready" && _(e.previewUrl);
418
+ this.files = /* @__PURE__ */ new Map(), this.changed({
419
+ pendingApprovals: [],
420
+ problem: null,
421
+ uploads: []
422
+ });
423
+ let a = this.state.conversationId;
424
+ await this.turn("/v1/chat", {
425
+ message: t,
426
+ ...a ? { conversationId: a } : {},
427
+ ...r.length ? { attachments: r } : {},
428
+ ...!a && this.opts.uploadFile ? { capabilities: { attachments: !0 } } : {}
429
+ });
430
+ }
431
+ attachmentLimits() {
432
+ let e = this.opts.attachments ?? {}, t = e.accept?.length ? e.accept : [...m.accept], n = this.policy?.accept?.length ? this.policy.accept : null;
433
+ return {
434
+ accept: n ? t.filter((e) => n.includes(e)) : t,
435
+ maxCount: Math.min(e.maxCount ?? m.maxCount, this.policy?.maxCount ?? m.maxCount, m.maxCount),
436
+ maxBytes: e.maxBytes ?? m.maxBytes,
437
+ maxEdge: e.maxEdge ?? m.maxEdge
438
+ };
439
+ }
440
+ retryable() {
441
+ return this.state.uploads.some((e) => e.status === "failed" && e.error === "upload");
442
+ }
443
+ newConversationTakesPhotos() {
444
+ return !!this.opts.uploadFile && this.policy?.enabled === !0;
445
+ }
446
+ loadCapabilities() {
447
+ return !this.opts.uploadFile || this.policy ? Promise.resolve() : (this.loadingPolicy ||= (async () => {
448
+ try {
449
+ let e = (await this.json("/v1/capabilities"))?.attachments ?? {};
450
+ this.policy = {
451
+ enabled: e.enabled === !0,
452
+ ...Array.isArray(e.accept) ? { accept: e.accept.filter((e) => typeof e == "string") } : {},
453
+ ...Number.isInteger(e.maxCount) ? { maxCount: e.maxCount } : {}
454
+ };
455
+ } catch (e) {
456
+ e instanceof v && e.status === 404 && (this.policy = { enabled: !1 });
457
+ } finally {
458
+ this.loadingPolicy = null;
459
+ }
460
+ !this.state.conversationId && this.state.canAttach !== this.newConversationTakesPhotos() && this.changed({ canAttach: this.newConversationTakesPhotos() });
461
+ })(), this.loadingPolicy);
462
+ }
463
+ uploading() {
464
+ return this.state.uploads.some((e) => e.status === "preparing" || e.status === "uploading");
465
+ }
466
+ upload(e) {
467
+ return this.state.uploads.find((t) => t.id === e);
468
+ }
469
+ refuse(e, t, n) {
470
+ e.status = "failed", e.error = t, n && (e.message = n), this.emit("attachment-error", {
471
+ name: e.name,
472
+ contentType: e.contentType,
473
+ reason: t,
474
+ ...n ? { message: n } : {}
475
+ });
476
+ }
477
+ addFiles(e) {
478
+ if (!this.state.canAttach || !this.opts.uploadFile) return;
479
+ let { accept: t, maxCount: n } = this.attachmentLimits();
480
+ for (let r of Array.from(e)) {
481
+ let e = r.name || "photo", i = r.type || "", a = {
482
+ id: this.id("f"),
483
+ name: e,
484
+ contentType: i,
485
+ size: r.size,
486
+ status: "preparing",
487
+ progress: 0
488
+ }, o = t.includes(i) ? g(r) : void 0;
489
+ o && (a.previewUrl = o, this.previews.add(o)), this.state.uploads.push(a);
490
+ let s = this.state.uploads.filter((e) => e.status !== "failed" || e.error === "upload").length;
491
+ t.includes(i) ? s > n ? this.refuse(a, "count") : (this.files.set(a.id, { file: r }), this.startUpload(a.id)) : this.refuse(a, "type");
492
+ }
493
+ this.changed();
494
+ }
495
+ removeUpload(e) {
496
+ let t = this.upload(e);
497
+ 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) }));
498
+ }
499
+ retryUpload(e) {
500
+ let t = this.upload(e);
501
+ t?.status === "failed" && t.error === "upload" && this.files.has(e) && this.startUpload(e);
502
+ }
503
+ async startUpload(e) {
504
+ let t = this.files.get(e), n = this.upload(e), r = this.opts.uploadFile;
505
+ if (!t || !n || !r) return;
506
+ let i = this.generation, a = () => i === this.generation && this.upload(e) === n, o = new AbortController();
507
+ t.controller = o, Object.assign(n, {
508
+ status: "preparing",
509
+ progress: 0,
510
+ error: void 0,
511
+ message: void 0
512
+ }), this.changed();
513
+ let { maxBytes: s, maxEdge: l } = this.attachmentLimits();
514
+ try {
515
+ let e = this.opts.prepareImage ?? c, i;
516
+ try {
517
+ i = await e(t.file, {
518
+ maxEdge: l,
519
+ contentType: n.contentType
520
+ });
521
+ } catch {
522
+ i = {
523
+ blob: t.file,
524
+ contentType: n.contentType
525
+ };
526
+ }
527
+ if (!a() || o.signal.aborted) return;
528
+ if (i.blob.size > s) {
529
+ this.refuse(n, "size"), this.changed();
530
+ return;
531
+ }
532
+ Object.assign(n, {
533
+ status: "uploading",
534
+ size: i.blob.size
535
+ }), this.changed();
536
+ let u = await r(i.blob, {
537
+ name: n.name,
538
+ contentType: i.contentType,
539
+ size: i.blob.size,
540
+ ...i.width ? { width: i.width } : {},
541
+ ...i.height ? { height: i.height } : {},
542
+ signal: o.signal,
543
+ onProgress: (e) => {
544
+ a() && n.status === "uploading" && (n.progress = Math.max(0, Math.min(1, Number(e) || 0)), this.changed());
545
+ }
546
+ });
547
+ if (!a() || o.signal.aborted) return;
548
+ if (!u || typeof u.ref != "string" || !u.ref) throw Error("The upload gave no reference.");
549
+ Object.assign(n, {
550
+ status: "ready",
551
+ progress: 1,
552
+ attachment: {
553
+ ...u,
554
+ name: u.name || n.name,
555
+ contentType: u.contentType || i.contentType,
556
+ ...i.width && !u.width ? { width: i.width } : {},
557
+ ...i.height && !u.height ? { height: i.height } : {}
558
+ }
559
+ }), this.changed();
560
+ } catch (e) {
561
+ if (!a() || x(e) || o.signal.aborted) return;
562
+ this.refuse(n, "upload", e instanceof Error && e.message ? e.message : void 0), this.changed();
563
+ }
564
+ }
565
+ dropPhotos() {
566
+ for (let e of this.files.values()) e.controller?.abort();
567
+ this.files = /* @__PURE__ */ new Map();
568
+ for (let e of this.previews) _(e);
569
+ this.previews = /* @__PURE__ */ new Set();
570
+ }
571
+ async decide(e) {
572
+ let t = this.state.conversationId;
573
+ if (!t || this.busy() || !this.state.pendingApprovals.length) return;
574
+ let n = this.state.pendingApprovals, r = new Map(e.map((e) => [e.approvalId, e]));
575
+ for (let e of n) {
576
+ let t = this.tools.get(e.toolCallId), n = r.get(e.approvalId);
577
+ t && (t.state = n?.approved ? "running" : "denied"), t && n?.approved && n.allowForConversation && (t.granted = !0);
578
+ }
579
+ if (this.changed({
580
+ pendingApprovals: [],
581
+ problem: null
582
+ }), await this.turn(`/v1/conversations/${encodeURIComponent(t)}/approvals`, { decisions: e }) === "not-sent") {
583
+ for (let e of n) {
584
+ let t = this.tools.get(e.toolCallId);
585
+ t && (t.state = "awaiting-approval", delete t.granted);
586
+ }
587
+ this.retryAction = () => this.decide(e), this.changed({
588
+ pendingApprovals: n,
589
+ status: "awaiting-approval"
590
+ });
591
+ }
592
+ }
593
+ async revokeAllowance(e) {
594
+ let t = this.state.conversationId;
595
+ if (!t) return !1;
596
+ try {
597
+ let n = await this.json(`/v1/conversations/${encodeURIComponent(t)}/allowances/${encodeURIComponent(e)}`, { method: "DELETE" });
598
+ return this.changed({ allowances: n.allowances ?? [] }), !0;
599
+ } catch (t) {
600
+ let n = b(t);
601
+ return this.changed({
602
+ allowances: this.state.allowances.filter((t) => t.toolName !== e),
603
+ ...t?.status === 404 ? {} : { problem: n }
604
+ }), !1;
605
+ }
606
+ }
607
+ approveAll() {
608
+ return this.decide(this.state.pendingApprovals.map((e) => ({
609
+ approvalId: e.approvalId,
610
+ approved: !0
611
+ })));
612
+ }
613
+ rejectAll(e) {
614
+ return this.decide(this.state.pendingApprovals.map((t) => ({
615
+ approvalId: t.approvalId,
616
+ approved: !1,
617
+ ...e ? { reason: e } : {}
618
+ })));
619
+ }
620
+ stop() {
621
+ this.controller?.abort();
622
+ }
623
+ async retry() {
624
+ let e = this.retryAction;
625
+ e && !this.busy() && (this.retryAction = null, this.changed({ problem: null }), await e());
626
+ }
627
+ dismissProblem() {
628
+ this.changed({ problem: null });
629
+ }
630
+ newConversation() {
631
+ 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();
632
+ }
633
+ async listConversations(e = {}) {
634
+ let t = new URLSearchParams({
635
+ limit: String(e.limit ?? 30),
636
+ offset: String(e.offset ?? 0)
637
+ });
638
+ return this.json(`/v1/conversations?${t}`);
639
+ }
640
+ async openConversation(e) {
641
+ this.generation += 1;
642
+ let t = this.generation;
643
+ this.controller?.abort(), this.changed({
644
+ status: "loading",
645
+ problem: null
646
+ });
647
+ try {
648
+ let n = await this.json(`/v1/conversations/${encodeURIComponent(e)}`);
649
+ if (t !== this.generation) return;
650
+ for (let [e, t] of Object.entries(n.toolTitles ?? {})) typeof t == "string" && t && this.titles.set(e, t);
651
+ let r = n.pendingApprovals ?? [];
652
+ for (let e of r) e.title && this.titles.set(e.toolName, e.title);
653
+ let i = a(n.messages ?? [], r, this.titles);
654
+ this.tools = /* @__PURE__ */ new Map();
655
+ for (let e of i) for (let t of e.parts) t.kind === "tool" && this.tools.set(t.toolCallId, t);
656
+ this.keepPreviews(r);
657
+ for (let e of n.allowedCalls ?? []) {
658
+ let t = this.tools.get(e.toolCallId);
659
+ t && (t.allowed = !0, e.preview && (t.preview = e.preview));
660
+ }
661
+ this.retryAction = null, this.dropPhotos(), this.state = {
662
+ ...h(!!this.opts.uploadFile && n.attachments === !0),
663
+ conversationId: e,
664
+ messages: i,
665
+ pendingApprovals: r,
666
+ allowances: n.allowances ?? [],
667
+ status: r.length ? "awaiting-approval" : "idle"
668
+ }, this.changed();
669
+ } catch (n) {
670
+ if (t !== this.generation) return;
671
+ this.retryAction = () => this.openConversation(e), this.changed({
672
+ status: "idle",
673
+ problem: b(n)
674
+ });
675
+ }
676
+ }
677
+ async reload() {
678
+ this.state.conversationId && await this.openConversation(this.state.conversationId);
679
+ }
680
+ async end() {
681
+ this.controller?.abort();
682
+ let e = this.session;
683
+ this.session = null, this.newConversation(), e && await this.opts.endSession?.(e.sessionId);
684
+ }
685
+ busy() {
686
+ return this.state.status === "sending" || this.state.status === "streaming" || this.state.status === "loading";
687
+ }
688
+ async turn(e, t) {
689
+ let n = this.generation, r = () => n === this.generation, i = {
690
+ id: this.id("a"),
691
+ role: "assistant",
692
+ parts: []
693
+ };
694
+ this.state.messages.push(i), this.changed({ status: "sending" });
695
+ let a = new AbortController();
696
+ this.controller = a;
697
+ let o;
698
+ try {
699
+ if (o = await this.request(e, {
700
+ method: "POST",
701
+ body: JSON.stringify(t),
702
+ headers: { accept: "text/event-stream, application/json;q=0.9" },
703
+ signal: a.signal
704
+ }), !o.ok) throw await y(o);
705
+ } catch (n) {
706
+ if (this.controller === a && (this.controller = null), !r()) return "answered";
707
+ if (this.drop(i), x(n)) return this.changed({ status: "idle" }), "not-sent";
708
+ let o = b(n);
709
+ if (o.code === "photos-refused") {
710
+ let e = this.state.messages.at(-1);
711
+ return e?.role === "user" && this.drop(e), this.policy = null, this.changed({
712
+ status: "idle",
713
+ problem: o,
714
+ canAttach: !1
715
+ }), this.loadCapabilities(), "not-sent";
716
+ }
717
+ return this.retryAction = () => this.turn(e, t).then(() => void 0), this.changed({
718
+ status: "idle",
719
+ problem: o
720
+ }), "not-sent";
721
+ }
722
+ if (!r()) return "answered";
723
+ this.changed({ status: "streaming" });
724
+ let s = !1, c = null, l = !1, u = /* @__PURE__ */ new Map();
725
+ try {
726
+ let e = o.body ? f(o.body, a.signal) : T(await o.text());
727
+ for await (let t of e) {
728
+ if (!r()) break;
729
+ t.type === "finish" ? s = !0 : t.type === "data-turn" && (c = t.data), this.apply(t, i, u), this.changed();
730
+ }
731
+ } catch (e) {
732
+ x(e) || (l = !0);
733
+ } finally {
734
+ this.controller === a && (this.controller = null);
735
+ }
736
+ if (!r()) return "answered";
737
+ if (i.parts.length || this.drop(i), c) this.finishTurn(c);
738
+ else {
739
+ let e = a.signal.aborted;
740
+ 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" });
741
+ }
742
+ return "answered";
743
+ }
744
+ settleUnfinished(e) {
745
+ let t = e ? "Stopped before it finished." : "The reply was cut off before it finished.";
746
+ 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);
747
+ }
748
+ drop(e) {
749
+ this.state.messages = this.state.messages.filter((t) => t !== e);
750
+ }
751
+ finishTurn(e) {
752
+ this.settleUnfinished(!1);
753
+ let t = e.pendingApprovals ?? [];
754
+ for (let e of t) e.title && this.titles.set(e.toolName, e.title);
755
+ this.keepPreviews(t);
756
+ let n = this.state.problem;
757
+ if (e.userTokenExpired) {
758
+ n = { code: "token-expired" };
759
+ let e = this.session;
760
+ e && this.opts.refreshUserToken(e.sessionId).catch(() => this.session = null);
761
+ } 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" } : {
762
+ code: "failed",
763
+ ...e.error ? { message: e.error } : {}
764
+ });
765
+ this.changed({
766
+ conversationId: e.conversationId ?? this.state.conversationId,
767
+ pendingApprovals: t,
768
+ lastTurn: e,
769
+ allowances: e.allowances ?? [],
770
+ problem: n,
771
+ status: t.length ? "awaiting-approval" : "idle"
772
+ }), t.length && this.emit("approval-pending", { approvals: t }), this.emit("turn-end", e);
773
+ }
774
+ keepPreviews(e) {
775
+ for (let t of e) {
776
+ let e = this.tools.get(t.toolCallId);
777
+ e && t.preview && (e.preview = t.preview);
778
+ }
779
+ }
780
+ apply(t, n, r) {
781
+ let i = t;
782
+ switch (t.type) {
783
+ case "start": {
784
+ let e = i.messageMetadata?.conversationId;
785
+ typeof e == "string" && (this.state.conversationId = e);
786
+ return;
787
+ }
788
+ case "text-start": {
789
+ let e = {
790
+ kind: "text",
791
+ id: this.id("t"),
792
+ text: ""
793
+ };
794
+ r.set(String(i.id), e), n.parts.push(e);
795
+ return;
796
+ }
797
+ case "text-delta": {
798
+ let e = r.get(String(i.id));
799
+ e || (e = {
800
+ kind: "text",
801
+ id: this.id("t"),
802
+ text: ""
803
+ }, r.set(String(i.id), e), n.parts.push(e)), e.text += String(i.delta ?? "");
804
+ return;
805
+ }
806
+ case "tool-input-start":
807
+ case "tool-input-available": {
808
+ let e = this.toolPart(i, n);
809
+ t.type === "tool-input-available" && (e.input = i.input, e.state === "input" && (e.state = "running"));
810
+ return;
811
+ }
812
+ case "tool-input-error": {
813
+ let e = this.toolPart(i, n);
814
+ e.state = "error", e.errorText = String(i.errorText ?? "");
815
+ return;
816
+ }
817
+ case "tool-approval-request": {
818
+ let e = this.tools.get(String(i.toolCallId));
819
+ e && (e.state = "awaiting-approval", e.approvalId = String(i.approvalId));
820
+ return;
821
+ }
822
+ case "tool-output-available":
823
+ case "tool-output-error": {
824
+ let n = this.tools.get(String(i.toolCallId));
825
+ if (!n) return;
826
+ 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", {
827
+ toolCallId: n.toolCallId,
828
+ toolName: n.toolName,
829
+ ...n.title ? { title: n.title } : {},
830
+ input: n.input,
831
+ ...n.state === "done" ? { output: n.output } : { error: n.errorText }
832
+ });
833
+ return;
834
+ }
835
+ case "tool-output-denied": {
836
+ let e = this.tools.get(String(i.toolCallId));
837
+ e && (e.state = "denied");
838
+ return;
839
+ }
840
+ case "data-allowed": {
841
+ let e = i.data ?? {}, t = this.tools.get(String(e.toolCallId));
842
+ if (!t) return;
843
+ t.allowed = !0, e.preview && (t.preview = e.preview);
844
+ return;
845
+ }
846
+ case "error":
847
+ this.state.problem = {
848
+ code: "failed",
849
+ ...i.errorText ? { message: String(i.errorText) } : {}
850
+ };
851
+ return;
852
+ default: return;
853
+ }
854
+ }
855
+ toolPart(e, t) {
856
+ let n = String(e.toolCallId), r = this.tools.get(n);
857
+ if (r || (r = {
858
+ kind: "tool",
859
+ toolCallId: n,
860
+ toolName: String(e.toolName ?? ""),
861
+ state: "input"
862
+ }, 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);
863
+ else if (!r.title) {
864
+ let e = this.titles.get(r.toolName);
865
+ e && (r.title = e);
866
+ }
867
+ return r;
868
+ }
869
+ };
870
+ async function* T(e) {
871
+ yield* u(e);
872
+ }
873
+ 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 };
874
+
875
+ //# sourceMappingURL=core-2Z4rCitF.js.map