@ghuri/ai-widget 0.1.3 → 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.
@@ -12,9 +12,16 @@ function e(e) {
12
12
  }
13
13
  // src/core/history.ts
14
14
  function t(e) {
15
- return typeof e == "string" ? e : (e ?? []).filter((e) => e.type === "text" && typeof e.text == "string").map((e) => e.text).join("");
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;
16
17
  }
17
- function n(t) {
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) {
18
25
  switch (t?.type) {
19
26
  case "execution-denied": return {
20
27
  state: "denied",
@@ -35,37 +42,44 @@ function n(t) {
35
42
  };
36
43
  }
37
44
  }
38
- function r(e, r = [], i = /* @__PURE__ */ new Map()) {
39
- let a = [], o = /* @__PURE__ */ new Map(), s = /* @__PURE__ */ new Map();
40
- for (let e of r) e.title && i.set(e.toolName, e.title);
41
- let c = null, l = 0, u = () => (c || (c = {
42
- id: `h${l++}`,
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++}`,
43
50
  role: "assistant",
44
51
  parts: []
45
- }, a.push(c)), c);
46
- for (let r of e) if (r.role === "user") c = null, a.push({
47
- id: `h${l++}`,
48
- role: "user",
49
- 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({
50
61
  kind: "text",
51
- id: `h${l++}`,
52
- text: t(r.content)
53
- }]
54
- });
55
- else if (r.role === "assistant") {
56
- let e = u(), t = typeof r.content == "string" ? [{
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" ? [{
57
71
  type: "text",
58
- text: r.content
59
- }] : r.content ?? [];
72
+ text: n.content
73
+ }] : n.content ?? [];
60
74
  for (let n of t) if (n.type === "text" && typeof n.text == "string" && n.text) {
61
75
  let t = e.parts.at(-1);
62
76
  t?.kind === "text" ? t.text += n.text : e.parts.push({
63
77
  kind: "text",
64
- id: `h${l++}`,
78
+ id: `h${u++}`,
65
79
  text: n.text
66
80
  });
67
81
  } else if (n.type === "tool-call" && typeof n.toolCallId == "string") {
68
- let t = i.get(n.toolName), r = {
82
+ let t = a.get(n.toolName), r = {
69
83
  kind: "tool",
70
84
  toolCallId: n.toolCallId,
71
85
  toolName: String(n.toolName ?? ""),
@@ -73,30 +87,89 @@ function r(e, r = [], i = /* @__PURE__ */ new Map()) {
73
87
  input: n.input,
74
88
  state: "running"
75
89
  };
76
- o.set(r.toolCallId, r), e.parts.push(r);
90
+ s.set(r.toolCallId, r), e.parts.push(r);
77
91
  } else if (n.type === "tool-approval-request" && typeof n.toolCallId == "string") {
78
- let e = o.get(n.toolCallId);
79
- e && (e.state = "awaiting-approval", e.approvalId = n.approvalId, s.set(n.approvalId, e));
92
+ let e = s.get(n.toolCallId);
93
+ e && (e.state = "awaiting-approval", e.approvalId = n.approvalId, c.set(n.approvalId, e));
80
94
  }
81
- } else if (r.role === "tool" && Array.isArray(r.content)) {
82
- for (let e of r.content) if (e.type === "tool-approval-response") {
83
- let t = s.get(e.approvalId);
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);
84
98
  t && t.state === "awaiting-approval" && (t.state = e.approved ? "running" : "denied");
85
99
  } else if (e.type === "tool-result") {
86
- let t = o.get(e.toolCallId);
87
- t && Object.assign(t, n(e.output));
100
+ let t = s.get(e.toolCallId);
101
+ t && Object.assign(t, i(e.output));
88
102
  }
89
103
  }
90
- let d = new Set(r.map((e) => e.toolCallId));
91
- for (let e of o.values()) e.state === "awaiting-approval" && !d.has(e.toolCallId) && (e.state = "denied");
92
- return a.filter((e) => e.parts.length > 0);
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;
93
166
  }
94
167
  // src/core/sse.ts
95
- function i(e) {
96
- let t = new a(), n = t.push(e);
168
+ function u(e) {
169
+ let t = new d(), n = t.push(e);
97
170
  return n.push(...t.end()), n;
98
171
  }
99
- var a = class {
172
+ var d = class {
100
173
  buffer = "";
101
174
  carry = "";
102
175
  done = !1;
@@ -133,9 +206,9 @@ var a = class {
133
206
  }
134
207
  }
135
208
  };
136
- async function* o(e, t) {
137
- let n = new a(), r = new TextDecoder(), i = e.getReader(), o = () => void i.cancel().catch(() => {});
138
- t?.addEventListener("abort", o, { once: !0 });
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 });
139
212
  try {
140
213
  for (;;) {
141
214
  if (t?.aborted) return;
@@ -146,42 +219,70 @@ async function* o(e, t) {
146
219
  for (let e of n.push(r.decode())) yield e;
147
220
  for (let e of n.end()) yield e;
148
221
  } finally {
149
- t?.removeEventListener("abort", o), i.releaseLock();
222
+ t?.removeEventListener("abort", a), i.releaseLock();
150
223
  }
151
224
  }
152
225
  // src/core/client.ts
153
- var s = 3e4;
154
- function c() {
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) {
155
238
  return {
156
239
  status: "idle",
157
240
  conversationId: null,
158
241
  messages: [],
159
242
  pendingApprovals: [],
160
243
  problem: null,
161
- lastTurn: null
244
+ lastTurn: null,
245
+ canAttach: e,
246
+ uploads: []
162
247
  };
163
248
  }
164
- var l = class extends Error {
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 {
165
262
  status;
166
263
  code;
167
264
  detail;
168
265
  retryAfter;
169
- constructor(e, t, n, r) {
170
- super(n || `HTTP ${e}`), this.status = e, this.code = t, this.detail = n, this.retryAfter = r;
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;
171
269
  }
172
270
  };
173
- async function u(e) {
271
+ async function y(e) {
174
272
  let t = null;
175
273
  try {
176
274
  t = await e.json();
177
275
  } catch {}
178
276
  let n = Number(e.headers.get("retry-after"));
179
- return new l(e.status, typeof t?.code == "string" ? t.code : "", typeof t?.detail == "string" ? t.detail : "", Number.isFinite(n) && n > 0 ? n : void 0);
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 : {});
180
278
  }
181
- function d(e) {
182
- if (!(e instanceof l)) return { code: "unavailable" };
183
- let { status: t, code: n, detail: r } = e;
184
- return t === 429 ? {
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 ? {
185
286
  code: "throttled",
186
287
  ...e.retryAfter ? { retryAfter: e.retryAfter } : {}
187
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" } : {
@@ -189,27 +290,28 @@ function d(e) {
189
290
  ...r ? { message: r } : {}
190
291
  };
191
292
  }
192
- function f(e) {
293
+ function x(e) {
193
294
  return e instanceof DOMException ? e.name === "AbortError" : e?.name === "AbortError";
194
295
  }
195
- function p(e, t) {
296
+ function S(e, t) {
196
297
  let n = new Date(e.expiresAt).getTime();
197
- return Number.isNaN(n) || n - s > t;
298
+ return Number.isNaN(n) || n - p > t;
198
299
  }
199
- function m(e) {
300
+ function C(e) {
200
301
  return {
201
302
  ...e,
202
303
  messages: e.messages.map((e) => ({
203
304
  ...e,
204
305
  parts: e.parts.map((e) => ({ ...e }))
205
306
  })),
206
- pendingApprovals: [...e.pendingApprovals]
307
+ pendingApprovals: [...e.pendingApprovals],
308
+ uploads: e.uploads.map((e) => ({ ...e }))
207
309
  };
208
310
  }
209
- var h = class {
311
+ var w = class {
210
312
  opts;
211
- state = c();
212
- view = m(this.state);
313
+ state;
314
+ view;
213
315
  listeners = /* @__PURE__ */ new Set();
214
316
  events = /* @__PURE__ */ new Map();
215
317
  session = null;
@@ -220,11 +322,15 @@ var h = class {
220
322
  retryAction = null;
221
323
  generation = 0;
222
324
  seq = 0;
325
+ files = /* @__PURE__ */ new Map();
326
+ previews = /* @__PURE__ */ new Set();
327
+ policy = null;
328
+ loadingPolicy = null;
223
329
  constructor(e) {
224
330
  this.opts = {
225
331
  ...e,
226
332
  apiUrl: e.apiUrl.replace(/\/+$/, "")
227
- };
333
+ }, this.state = h(!1), this.view = C(this.state);
228
334
  }
229
335
  getState() {
230
336
  return this.view;
@@ -240,7 +346,7 @@ var h = class {
240
346
  for (let n of this.events.get(e) ?? []) n(t);
241
347
  }
242
348
  changed(e = {}) {
243
- Object.assign(this.state, e), this.view = m(this.state);
349
+ Object.assign(this.state, e), this.view = C(this.state);
244
350
  for (let e of this.listeners) e(this.view);
245
351
  }
246
352
  id(e) {
@@ -251,7 +357,7 @@ var h = class {
251
357
  }
252
358
  async ensureSession() {
253
359
  let e = this.session;
254
- return e && p(e, this.now()) ? e : (this.session = null, this.starting ||= this.opts.startSession().then((e) => (this.session = e, e)).finally(() => {
360
+ return e && S(e, this.now()) ? e : (this.session = null, this.starting ||= this.opts.startSession().then((e) => (this.session = e, e)).finally(() => {
255
361
  this.starting = null;
256
362
  }), this.starting);
257
363
  }
@@ -263,7 +369,7 @@ var h = class {
263
369
  headers: i
264
370
  });
265
371
  if (a.status !== 401 || n) return a;
266
- let o = await u(a);
372
+ let o = await y(a);
267
373
  if (this.changed({ problem: { code: "reconnecting" } }), o.code === "user_token_expired") try {
268
374
  await this.opts.refreshUserToken(r.sessionId);
269
375
  } catch {
@@ -275,35 +381,191 @@ var h = class {
275
381
  }
276
382
  async json(e, t = {}) {
277
383
  let n = await this.request(e, t);
278
- if (!n.ok) throw await u(n);
384
+ if (!n.ok) throw await y(n);
279
385
  return await n.json();
280
386
  }
281
387
  async send(e) {
282
- let t = e.trim();
283
- if (!t || this.busy()) return;
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;
284
390
  for (let e of this.state.pendingApprovals) {
285
391
  let t = this.tools.get(e.toolCallId);
286
392
  t && (t.state = "denied");
287
393
  }
288
- let n = {
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({
289
411
  id: this.id("u"),
290
412
  role: "user",
291
- parts: [{
292
- kind: "text",
293
- id: this.id("t"),
294
- text: t
295
- }]
296
- };
297
- this.state.messages.push(n), this.changed({
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({
298
417
  pendingApprovals: [],
299
- problem: null
418
+ problem: null,
419
+ uploads: []
300
420
  });
301
- let r = this.state.conversationId;
421
+ let a = this.state.conversationId;
302
422
  await this.turn("/v1/chat", {
303
423
  message: t,
304
- ...r ? { conversationId: r } : {}
424
+ ...a ? { conversationId: a } : {},
425
+ ...r.length ? { attachments: r } : {},
426
+ ...!a && this.opts.uploadFile ? { capabilities: { attachments: !0 } } : {}
305
427
  });
306
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
+ }
307
569
  async decide(e) {
308
570
  let t = this.state.conversationId;
309
571
  if (!t || this.busy() || !this.state.pendingApprovals.length) return;
@@ -350,7 +612,7 @@ var h = class {
350
612
  this.changed({ problem: null });
351
613
  }
352
614
  newConversation() {
353
- this.generation += 1, this.controller?.abort(), this.tools = /* @__PURE__ */ new Map(), this.retryAction = null, this.state = c(), this.changed();
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();
354
616
  }
355
617
  async listConversations(e = {}) {
356
618
  let t = new URLSearchParams({
@@ -370,23 +632,23 @@ var h = class {
370
632
  let n = await this.json(`/v1/conversations/${encodeURIComponent(e)}`);
371
633
  if (t !== this.generation) return;
372
634
  for (let [e, t] of Object.entries(n.toolTitles ?? {})) typeof t == "string" && t && this.titles.set(e, t);
373
- let i = n.pendingApprovals ?? [];
374
- for (let e of i) e.title && this.titles.set(e.toolName, e.title);
375
- let a = r(n.messages ?? [], i, this.titles);
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);
376
638
  this.tools = /* @__PURE__ */ new Map();
377
- for (let e of a) for (let t of e.parts) t.kind === "tool" && this.tools.set(t.toolCallId, t);
378
- this.keepPreviews(i), this.retryAction = null, this.state = {
379
- ...c(),
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),
380
642
  conversationId: e,
381
- messages: a,
382
- pendingApprovals: i,
383
- status: i.length ? "awaiting-approval" : "idle"
643
+ messages: i,
644
+ pendingApprovals: r,
645
+ status: r.length ? "awaiting-approval" : "idle"
384
646
  }, this.changed();
385
647
  } catch (n) {
386
648
  if (t !== this.generation) return;
387
649
  this.retryAction = () => this.openConversation(e), this.changed({
388
650
  status: "idle",
389
- problem: d(n)
651
+ problem: b(n)
390
652
  });
391
653
  }
392
654
  }
@@ -410,39 +672,50 @@ var h = class {
410
672
  this.state.messages.push(i), this.changed({ status: "sending" });
411
673
  let a = new AbortController();
412
674
  this.controller = a;
413
- let s;
675
+ let o;
414
676
  try {
415
- if (s = await this.request(e, {
677
+ if (o = await this.request(e, {
416
678
  method: "POST",
417
679
  body: JSON.stringify(t),
418
680
  headers: { accept: "text/event-stream, application/json;q=0.9" },
419
681
  signal: a.signal
420
- }), !s.ok) throw await u(s);
682
+ }), !o.ok) throw await y(o);
421
683
  } catch (n) {
422
- return this.controller === a && (this.controller = null), r() ? (this.drop(i), f(n) ? (this.changed({ status: "idle" }), "not-sent") : (this.retryAction = () => this.turn(e, t).then(() => void 0), this.changed({
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({
423
696
  status: "idle",
424
- problem: d(n)
425
- }), "not-sent")) : "answered";
697
+ problem: o
698
+ }), "not-sent";
426
699
  }
427
700
  if (!r()) return "answered";
428
701
  this.changed({ status: "streaming" });
429
- let c = !1, l = null, p = !1, m = /* @__PURE__ */ new Map();
702
+ let s = !1, c = null, l = !1, u = /* @__PURE__ */ new Map();
430
703
  try {
431
- let e = s.body ? o(s.body, a.signal) : g(await s.text());
704
+ let e = o.body ? f(o.body, a.signal) : T(await o.text());
432
705
  for await (let t of e) {
433
706
  if (!r()) break;
434
- t.type === "finish" ? c = !0 : t.type === "data-turn" && (l = t.data), this.apply(t, i, m), this.changed();
707
+ t.type === "finish" ? s = !0 : t.type === "data-turn" && (c = t.data), this.apply(t, i, u), this.changed();
435
708
  }
436
709
  } catch (e) {
437
- f(e) || (p = !0);
710
+ x(e) || (l = !0);
438
711
  } finally {
439
712
  this.controller === a && (this.controller = null);
440
713
  }
441
714
  if (!r()) return "answered";
442
- if (i.parts.length || this.drop(i), l) this.finishTurn(l);
715
+ if (i.parts.length || this.drop(i), c) this.finishTurn(c);
443
716
  else {
444
717
  let e = a.signal.aborted;
445
- this.settleUnfinished(e), e || !p && c || this.state.problem || (this.state.problem = { code: "cut-off" }), this.changed({ status: this.state.pendingApprovals.length ? "awaiting-approval" : "idle" });
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" });
446
719
  }
447
720
  return "answered";
448
721
  }
@@ -454,6 +727,7 @@ var h = class {
454
727
  this.state.messages = this.state.messages.filter((t) => t !== e);
455
728
  }
456
729
  finishTurn(e) {
730
+ this.settleUnfinished(!1);
457
731
  let t = e.pendingApprovals ?? [];
458
732
  for (let e of t) e.title && this.titles.set(e.toolName, e.title);
459
733
  this.keepPreviews(t);
@@ -462,7 +736,7 @@ var h = class {
462
736
  n = { code: "token-expired" };
463
737
  let e = this.session;
464
738
  e && this.opts.refreshUserToken(e.sessionId).catch(() => this.session = null);
465
- } else e.status === "error" && (n = e.limitReached === "conversation" ? { code: "conversation-full" } : {
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" } : {
466
740
  code: "failed",
467
741
  ...e.error ? { message: e.error } : {}
468
742
  });
@@ -564,9 +838,9 @@ var h = class {
564
838
  return r;
565
839
  }
566
840
  };
567
- async function* g(e) {
568
- yield* i(e);
841
+ async function* T(e) {
842
+ yield* u(e);
569
843
  }
570
- export { o as a, i, d as n, r as o, a as r, e as s, h as t };
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 };
571
845
 
572
- //# sourceMappingURL=core-B5cGLmtw.js.map
846
+ //# sourceMappingURL=core-HrvNVLh8.js.map