@ghuri/ai-widget 0.4.0 → 0.7.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.
@@ -49,12 +49,16 @@ function a(e) {
49
49
  return Array.isArray(t) ? t.filter((e) => !!e && typeof e == "object" && typeof e.ref == "string" && typeof e.name == "string") : null;
50
50
  }
51
51
  function o(e) {
52
- return typeof e.providerOptions?.ghuri?.note == "string";
52
+ let t = e.providerOptions?.ghuri?.selections;
53
+ return Array.isArray(t) ? t.filter((e) => !!e && typeof e == "object" && typeof e.label == "string") : null;
53
54
  }
54
55
  function s(e) {
55
- return typeof e == "string" ? e : (e ?? []).filter((e) => e.type === "text" && typeof e.text == "string" && !a(e) && !o(e)).map((e) => e.text).join("");
56
+ return typeof e.providerOptions?.ghuri?.note == "string";
56
57
  }
57
- function c(t) {
58
+ function c(e) {
59
+ return typeof e == "string" ? e : (e ?? []).filter((e) => e.type === "text" && typeof e.text == "string" && !a(e) && !o(e) && !s(e)).map((e) => e.text).join("");
60
+ }
61
+ function l(t) {
58
62
  switch (t?.type) {
59
63
  case "execution-denied": return {
60
64
  state: "denied",
@@ -83,32 +87,38 @@ function c(t) {
83
87
  };
84
88
  }
85
89
  }
86
- function l(e, t = [], n = /* @__PURE__ */ new Map()) {
87
- let r = [], i = /* @__PURE__ */ new Map(), o = /* @__PURE__ */ new Map();
90
+ function u(e, t = [], n = /* @__PURE__ */ new Map()) {
91
+ let r = [], i = /* @__PURE__ */ new Map(), u = /* @__PURE__ */ new Map();
88
92
  for (let e of t) e.title && n.set(e.toolName, e.title);
89
- let l = null, u = 0, d = () => (l || (l = {
90
- id: `h${u++}`,
93
+ let d = null, f = 0, p = () => (d || (d = {
94
+ id: `h${f++}`,
91
95
  role: "assistant",
92
96
  parts: []
93
- }, r.push(l)), l);
97
+ }, r.push(d)), d);
94
98
  for (let t of e) if (t.role === "user") {
95
- l = null;
96
- let e = Array.isArray(t.content) ? t.content.flatMap((e) => a(e) ?? []) : [], n = s(t.content), i = [];
97
- e.length && i.push({
99
+ d = null;
100
+ let e = Array.isArray(t.content) ? t.content.flatMap((e) => a(e) ?? []) : [], n = Array.isArray(t.content) ? t.content.flatMap((e) => o(e) ?? []) : [], i = c(t.content);
101
+ if (!i && !e.length && Array.isArray(t.content) && t.content.length && t.content.every(s)) continue;
102
+ let l = [];
103
+ n.length && l.push({
104
+ kind: "selections",
105
+ id: `h${f++}`,
106
+ selections: n
107
+ }), e.length && l.push({
98
108
  kind: "attachments",
99
- id: `h${u++}`,
109
+ id: `h${f++}`,
100
110
  attachments: e
101
- }), (n || !e.length) && i.push({
111
+ }), (i || !e.length) && l.push({
102
112
  kind: "text",
103
- id: `h${u++}`,
104
- text: n
113
+ id: `h${f++}`,
114
+ text: i
105
115
  }), r.push({
106
- id: `h${u++}`,
116
+ id: `h${f++}`,
107
117
  role: "user",
108
- parts: i
118
+ parts: l
109
119
  });
110
120
  } else if (t.role === "assistant") {
111
- let e = d(), r = typeof t.content == "string" ? [{
121
+ let e = p(), r = typeof t.content == "string" ? [{
112
122
  type: "text",
113
123
  text: t.content
114
124
  }] : t.content ?? [];
@@ -116,7 +126,7 @@ function l(e, t = [], n = /* @__PURE__ */ new Map()) {
116
126
  let n = e.parts.at(-1);
117
127
  n?.kind === "text" ? n.text += t.text : e.parts.push({
118
128
  kind: "text",
119
- id: `h${u++}`,
129
+ id: `h${f++}`,
120
130
  text: t.text
121
131
  });
122
132
  } else if (t.type === "tool-call" && typeof t.toolCallId == "string") {
@@ -131,35 +141,35 @@ function l(e, t = [], n = /* @__PURE__ */ new Map()) {
131
141
  i.set(a.toolCallId, a), e.parts.push(a);
132
142
  } else if (t.type === "tool-approval-request" && typeof t.toolCallId == "string") {
133
143
  let e = i.get(t.toolCallId);
134
- e && (e.state = "awaiting-approval", e.approvalId = t.approvalId, o.set(t.approvalId, e));
144
+ e && (e.state = "awaiting-approval", e.approvalId = t.approvalId, u.set(t.approvalId, e));
135
145
  }
136
146
  } else if (t.role === "tool" && Array.isArray(t.content)) {
137
147
  for (let e of t.content) if (e.type === "tool-approval-response") {
138
- let t = o.get(e.approvalId);
148
+ let t = u.get(e.approvalId);
139
149
  t && t.state === "awaiting-approval" && (t.state = e.approved ? "running" : "denied");
140
150
  } else if (e.type === "tool-result") {
141
151
  let t = i.get(e.toolCallId);
142
- t && Object.assign(t, c(e.output));
152
+ t && Object.assign(t, l(e.output));
143
153
  }
144
154
  }
145
- let f = new Set(t.map((e) => e.toolCallId));
146
- for (let e of i.values()) e.state === "awaiting-approval" && !f.has(e.toolCallId) && (e.state = "denied");
155
+ let m = new Set(t.map((e) => e.toolCallId));
156
+ for (let e of i.values()) e.state === "awaiting-approval" && !m.has(e.toolCallId) && (e.state = "denied");
147
157
  return r.filter((e) => e.parts.length > 0);
148
158
  }
149
159
  // src/core/prepare.ts
150
- var u = .85, d = .7, f = {
160
+ var d = .85, f = .7, p = {
151
161
  "image/jpeg": "jpg",
152
162
  "image/png": "png",
153
163
  "image/webp": "webp",
154
164
  "image/gif": "gif"
155
- }, p = /\.(jpe?g|jfif|png|webp|gif|heic|heif|avif|bmp|tiff?)$/i;
156
- function m(e, t) {
157
- let n = f[t];
165
+ }, m = /\.(jpe?g|jfif|png|webp|gif|heic|heif|avif|bmp|tiff?)$/i;
166
+ function h(e, t) {
167
+ let n = p[t];
158
168
  if (!n) return e;
159
- let r = p.exec(e)?.[1]?.toLowerCase();
169
+ let r = m.exec(e)?.[1]?.toLowerCase();
160
170
  return r === n || n === "jpg" && (r === "jpeg" || r === "jfif") ? e : `${r ? e.slice(0, -r.length - 1) : e}.${n}`;
161
171
  }
162
- function h(e, t, n) {
172
+ function g(e, t, n) {
163
173
  let r = Math.max(e, t);
164
174
  if (!r || r <= n) return {
165
175
  width: e,
@@ -171,7 +181,7 @@ function h(e, t, n) {
171
181
  height: Math.max(1, Math.round(t * i))
172
182
  };
173
183
  }
174
- async function g(e, t) {
184
+ async function _(e, t) {
175
185
  let { contentType: n } = t;
176
186
  if (n === "image/gif" || typeof createImageBitmap != "function") return {
177
187
  blob: e,
@@ -187,14 +197,14 @@ async function g(e, t) {
187
197
  };
188
198
  }
189
199
  try {
190
- let i = h(r.width, r.height, t.maxEdge), a = y(r, i), o = a && await b(a, n, u);
200
+ let i = g(r.width, r.height, t.maxEdge), a = b(r, i), o = a && await x(a, n, d);
191
201
  if (!a || !o) return {
192
202
  blob: e,
193
203
  contentType: n,
194
204
  width: r.width,
195
205
  height: r.height
196
206
  };
197
- let s = t.targetBytes && o.size > t.targetBytes ? await _(a, t.targetBytes) : null, c = s && s.size < o.size ? s : o;
207
+ let s = t.targetBytes && o.size > t.targetBytes ? await v(a, t.targetBytes) : null, c = s && s.size < o.size ? s : o;
198
208
  return {
199
209
  blob: c,
200
210
  contentType: c.type || n,
@@ -204,16 +214,16 @@ async function g(e, t) {
204
214
  r.close();
205
215
  }
206
216
  }
207
- async function _(e, t) {
208
- let n = v(e) ? "image/jpeg" : "image/webp", r = await b(e, n, u);
217
+ async function v(e, t) {
218
+ let n = y(e) ? "image/jpeg" : "image/webp", r = await x(e, n, d);
209
219
  if (!r || r.type !== n) return null;
210
220
  if (r.size > t) {
211
- let t = await b(e, n, d);
221
+ let t = await x(e, n, f);
212
222
  t && t.type === n && t.size < r.size && (r = t);
213
223
  }
214
224
  return r;
215
225
  }
216
- function v(e) {
226
+ function y(e) {
217
227
  let t = e.getContext("2d");
218
228
  if (!t) return !1;
219
229
  let n;
@@ -225,7 +235,7 @@ function v(e) {
225
235
  for (let e = 3; e < n.length; e += 4) if (n[e] !== 255) return !1;
226
236
  return !0;
227
237
  }
228
- function y(e, t) {
238
+ function b(e, t) {
229
239
  let n;
230
240
  if (typeof OffscreenCanvas == "function") n = new OffscreenCanvas(t.width, t.height);
231
241
  else if (typeof document < "u") n = document.createElement("canvas"), n.width = t.width, n.height = t.height;
@@ -233,18 +243,18 @@ function y(e, t) {
233
243
  let r = n.getContext("2d");
234
244
  return r ? (r.drawImage(e, 0, 0, t.width, t.height), n) : null;
235
245
  }
236
- function b(e, t, n) {
246
+ function x(e, t, n) {
237
247
  return "convertToBlob" in e ? e.convertToBlob({
238
248
  type: t,
239
249
  quality: n
240
250
  }).catch(() => null) : new Promise((r) => e.toBlob((e) => r(e), t, n));
241
251
  }
242
252
  // src/core/sse.ts
243
- function x(e) {
244
- let t = new S(), n = t.push(e);
253
+ function S(e) {
254
+ let t = new C(), n = t.push(e);
245
255
  return n.push(...t.end()), n;
246
256
  }
247
- var S = class {
257
+ var C = class {
248
258
  buffer = "";
249
259
  carry = "";
250
260
  done = !1;
@@ -281,8 +291,8 @@ var S = class {
281
291
  }
282
292
  }
283
293
  };
284
- async function* C(e, t) {
285
- let n = new S(), r = new TextDecoder(), i = e.getReader(), a = () => void i.cancel().catch(() => {});
294
+ async function* w(e, t) {
295
+ let n = new C(), r = new TextDecoder(), i = e.getReader(), a = () => void i.cancel().catch(() => {});
286
296
  t?.addEventListener("abort", a, { once: !0 });
287
297
  try {
288
298
  for (;;) {
@@ -297,8 +307,35 @@ async function* C(e, t) {
297
307
  t?.removeEventListener("abort", a), i.releaseLock();
298
308
  }
299
309
  }
310
+ // src/core/handover.ts
311
+ function T(e) {
312
+ let t = e.replace(/^\s*<handover>\s*\n?/, "").replace(/\n?\s*<\/handover>\s*$/, "").split("\n"), n = t.findIndex((e) => !e.trim());
313
+ return (n >= 0 ? t.slice(n + 1) : t).join("\n").trim();
314
+ }
315
+ var E = "Summary, written by the assistant at the end of that conversation:", D = "(No summary could be written; the record below is complete.)", O = "Record, kept by Ghuri AI:";
316
+ function k(e) {
317
+ return A(e).lines;
318
+ }
319
+ function A(e) {
320
+ let t = T(e).split("\n"), n = t[0]?.trim() === D;
321
+ n && (t = t.slice(1).filter((e) => e.trim() !== O));
322
+ let r = n, i = [];
323
+ for (let e of t) {
324
+ if (!e.trim()) continue;
325
+ e.trim() === O && (r = !0);
326
+ let t = e.trim() === O || e.trim() === E || r && !e.startsWith("- ");
327
+ i.push({
328
+ text: e,
329
+ heading: t
330
+ });
331
+ }
332
+ return {
333
+ summary: !n,
334
+ lines: i
335
+ };
336
+ }
300
337
  // src/core/client.ts
301
- var w = 3e4, T = {
338
+ var j = 3e4, M = {
302
339
  accept: [
303
340
  "image/jpeg",
304
341
  "image/png",
@@ -308,12 +345,14 @@ var w = 3e4, T = {
308
345
  maxCount: 10,
309
346
  maxBytes: 5242880,
310
347
  maxEdge: 2048
311
- }, E = {
348
+ }, N = {
312
349
  maxEdge: 1568,
313
350
  targetBytes: 1e6
314
351
  };
315
- function D(e = !1) {
352
+ function P(e = !1, t = !1) {
316
353
  return {
354
+ selections: [],
355
+ canSelect: t,
317
356
  status: "idle",
318
357
  conversationId: null,
319
358
  messages: [],
@@ -322,22 +361,27 @@ function D(e = !1) {
322
361
  lastTurn: null,
323
362
  canAttach: e,
324
363
  uploads: [],
325
- allowances: []
364
+ allowances: [],
365
+ full: !1,
366
+ continuing: !1,
367
+ continuedFrom: null,
368
+ handover: null,
369
+ continuedIn: null
326
370
  };
327
371
  }
328
- function O(e) {
372
+ function F(e) {
329
373
  try {
330
374
  return typeof URL.createObjectURL == "function" ? URL.createObjectURL(e) : void 0;
331
375
  } catch {
332
376
  return;
333
377
  }
334
378
  }
335
- function k(e) {
379
+ function I(e) {
336
380
  try {
337
381
  e && typeof URL.revokeObjectURL == "function" && URL.revokeObjectURL(e);
338
382
  } catch {}
339
383
  }
340
- var A = class extends Error {
384
+ var L = "This change had already started, and its result was not recorded. Check before trying again.", R = class extends Error {
341
385
  status;
342
386
  code;
343
387
  detail;
@@ -347,18 +391,21 @@ var A = class extends Error {
347
391
  super(n || `HTTP ${e}`), this.status = e, this.code = t, this.detail = n, this.retryAfter = r, this.fields = i;
348
392
  }
349
393
  };
350
- async function j(e) {
394
+ async function z(e) {
351
395
  let t = null;
352
396
  try {
353
397
  t = await e.json();
354
398
  } catch {}
355
399
  let n = Number(e.headers.get("retry-after"));
356
- return new A(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 : {});
400
+ return new R(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 : {});
357
401
  }
358
- function M(e) {
359
- if (!(e instanceof A)) return { code: "unavailable" };
360
- let { status: t, code: n, detail: r } = e, i = e.fields.attachments;
361
- return t === 400 && Array.isArray(i) ? {
402
+ function B(e) {
403
+ if (!(e instanceof R)) return { code: "unavailable" };
404
+ let { status: t, code: n, detail: r } = e, i = e.fields.attachments, a = e.fields.selections;
405
+ return t === 400 && Array.isArray(a) ? {
406
+ code: "selections-refused",
407
+ ...typeof a[0] == "string" ? { message: a[0] } : {}
408
+ } : t === 400 && Array.isArray(i) ? {
362
409
  code: "photos-refused",
363
410
  ...typeof i[0] == "string" ? { message: i[0] } : {}
364
411
  } : t === 429 ? {
@@ -369,14 +416,14 @@ function M(e) {
369
416
  ...r ? { message: r } : {}
370
417
  };
371
418
  }
372
- function N(e) {
419
+ function V(e) {
373
420
  return e instanceof DOMException ? e.name === "AbortError" : e?.name === "AbortError";
374
421
  }
375
- function P(e, t) {
422
+ function H(e, t) {
376
423
  let n = new Date(e.expiresAt).getTime();
377
- return Number.isNaN(n) || n - w > t;
424
+ return Number.isNaN(n) || n - j > t;
378
425
  }
379
- function F(e) {
426
+ function U(e) {
380
427
  return {
381
428
  ...e,
382
429
  messages: e.messages.map((e) => ({
@@ -385,10 +432,44 @@ function F(e) {
385
432
  })),
386
433
  pendingApprovals: [...e.pendingApprovals],
387
434
  uploads: e.uploads.map((e) => ({ ...e })),
388
- allowances: [...e.allowances]
435
+ allowances: [...e.allowances],
436
+ selections: e.selections.map((e) => ({ ...e }))
437
+ };
438
+ }
439
+ var W = {
440
+ label: 80,
441
+ name: 80,
442
+ text: 160,
443
+ version: 40,
444
+ page: 300
445
+ };
446
+ function G(e, t) {
447
+ if (typeof e != "string") return;
448
+ let n = e.replace(/\s+/g, " ").trim();
449
+ if (n) return n.length > t ? `${n.slice(0, t - 1)}…` : n;
450
+ }
451
+ function K(e) {
452
+ let t = G(e?.label, W.label);
453
+ if (!t) return null;
454
+ let n = {
455
+ ...e,
456
+ label: t
389
457
  };
458
+ for (let t of [
459
+ "name",
460
+ "text",
461
+ "version"
462
+ ]) {
463
+ let r = G(e[t], W[t]);
464
+ r ? n[t] = r : delete n[t];
465
+ }
466
+ if (typeof e.page == "string") {
467
+ let t = e.page.split(/[?#]/)[0];
468
+ t.startsWith("/") && t.length <= W.page ? n.page = t : delete n.page;
469
+ }
470
+ return n;
390
471
  }
391
- var I = class {
472
+ var q = class {
392
473
  opts;
393
474
  state;
394
475
  view;
@@ -405,13 +486,15 @@ var I = class {
405
486
  files = /* @__PURE__ */ new Map();
406
487
  previews = /* @__PURE__ */ new Set();
407
488
  policy = null;
489
+ selectionPolicy = null;
490
+ sending = [];
408
491
  loadingPolicy = null;
409
492
  capabilitiesWanted = !1;
410
493
  constructor(e) {
411
494
  this.opts = {
412
495
  ...e,
413
496
  apiUrl: e.apiUrl.replace(/\/+$/, "")
414
- }, this.state = D(!1), this.view = F(this.state);
497
+ }, this.state = P(!1), this.view = U(this.state);
415
498
  }
416
499
  getState() {
417
500
  return this.view;
@@ -427,7 +510,7 @@ var I = class {
427
510
  for (let n of this.events.get(e) ?? []) n(t);
428
511
  }
429
512
  changed(e = {}) {
430
- Object.assign(this.state, e), this.view = F(this.state);
513
+ Object.assign(this.state, e), this.view = U(this.state);
431
514
  for (let e of this.listeners) e(this.view);
432
515
  }
433
516
  id(e) {
@@ -438,7 +521,7 @@ var I = class {
438
521
  }
439
522
  async ensureSession() {
440
523
  let e = this.session;
441
- return e && P(e, this.now()) ? e : (this.session = null, this.starting ||= this.opts.startSession().then((e) => (this.session = e, e)).finally(() => {
524
+ return e && H(e, this.now()) ? e : (this.session = null, this.starting ||= this.opts.startSession().then((e) => (this.session = e, e)).finally(() => {
442
525
  this.starting = null;
443
526
  }), this.starting);
444
527
  }
@@ -450,7 +533,7 @@ var I = class {
450
533
  headers: i
451
534
  });
452
535
  if (a.status !== 401 || n) return a;
453
- let o = await j(a);
536
+ let o = await z(a);
454
537
  if (this.changed({ problem: { code: "reconnecting" } }), o.code === "user_token_expired") try {
455
538
  await this.opts.refreshUserToken(r.sessionId);
456
539
  } catch {
@@ -462,18 +545,32 @@ var I = class {
462
545
  }
463
546
  async json(e, t = {}) {
464
547
  let n = await this.request(e, t);
465
- if (!n.ok) throw await j(n);
548
+ if (!n.ok) throw await z(n);
466
549
  return await n.json();
467
550
  }
468
551
  async send(e) {
469
552
  let t = e.trim(), n = this.state.uploads.filter((e) => e.status === "ready" && e.attachment);
470
553
  if (!t && !n.length || this.busy() || this.uploading() || this.retryable()) return;
554
+ if (this.state.full) {
555
+ this.changed({ problem: { code: "conversation-full" } });
556
+ return;
557
+ }
558
+ let r = this.state.selections;
559
+ if (r.length && (!t || !this.state.canSelect)) return;
471
560
  for (let e of this.state.pendingApprovals) {
472
561
  let t = this.tools.get(e.toolCallId);
473
562
  t && (t.state = "denied");
474
563
  }
475
- let r = n.map((e) => e.attachment), i = [];
476
- if (r.length) {
564
+ let i = n.map((e) => e.attachment), a = [], o = r.map(({ id: e, ...t }) => t);
565
+ if (o.length) {
566
+ let e = {
567
+ kind: "selections",
568
+ id: this.id("p"),
569
+ selections: o
570
+ };
571
+ a.push(e);
572
+ }
573
+ if (i.length) {
477
574
  let e = {
478
575
  kind: "attachments",
479
576
  id: this.id("p"),
@@ -482,63 +579,106 @@ var I = class {
482
579
  ...e.previewUrl ? { previewUrl: e.previewUrl } : {}
483
580
  }))
484
581
  };
485
- i.push(e);
582
+ a.push(e);
486
583
  }
487
- t && i.push({
584
+ t && a.push({
488
585
  kind: "text",
489
586
  id: this.id("t"),
490
587
  text: t
491
588
  }), this.state.messages.push({
492
589
  id: this.id("u"),
493
590
  role: "user",
494
- parts: i
591
+ parts: a
495
592
  });
496
- for (let e of this.state.uploads) e.status !== "ready" && k(e.previewUrl);
497
- this.files = /* @__PURE__ */ new Map(), this.changed({
593
+ for (let e of this.state.uploads) e.status !== "ready" && I(e.previewUrl);
594
+ this.files = /* @__PURE__ */ new Map(), this.sending = r, this.changed({
498
595
  pendingApprovals: [],
499
596
  problem: null,
500
- uploads: []
501
- });
502
- let a = this.state.conversationId;
597
+ uploads: [],
598
+ selections: []
599
+ }), r.length && this.emit("selection-sent", { ids: r.map((e) => e.id) });
600
+ let s = this.state.conversationId;
503
601
  await this.turn("/v1/chat", {
504
602
  message: t,
505
- ...a ? { conversationId: a } : {},
506
- ...r.length ? { attachments: r } : {},
507
- ...!a && this.opts.uploadFile ? { capabilities: { attachments: !0 } } : {}
603
+ ...s ? { conversationId: s } : {},
604
+ ...i.length ? { attachments: i } : {},
605
+ ...o.length ? { selections: o } : {},
606
+ ...!s && this.opts.uploadFile ? { capabilities: { attachments: !0 } } : {}
508
607
  });
509
608
  }
510
609
  attachmentLimits() {
511
- let e = this.opts.attachments ?? {}, t = e.accept?.length ? e.accept : [...T.accept], n = this.policy?.accept?.length ? this.policy.accept : null, r = this.policy?.vision === !0;
610
+ let e = this.opts.attachments ?? {}, t = e.accept?.length ? e.accept : [...M.accept], n = this.policy?.accept?.length ? this.policy.accept : null, r = this.policy?.vision === !0;
512
611
  return {
513
612
  accept: n ? t.filter((e) => n.includes(e)) : t,
514
- maxCount: Math.min(e.maxCount ?? T.maxCount, this.policy?.maxCount ?? T.maxCount, T.maxCount),
515
- maxBytes: e.maxBytes ?? T.maxBytes,
516
- maxEdge: e.maxEdge ?? (r ? E.maxEdge : T.maxEdge),
517
- ...e.targetBytes || r ? { targetBytes: e.targetBytes ?? E.targetBytes } : {}
613
+ maxCount: Math.min(e.maxCount ?? M.maxCount, this.policy?.maxCount ?? M.maxCount, M.maxCount),
614
+ maxBytes: e.maxBytes ?? M.maxBytes,
615
+ maxEdge: e.maxEdge ?? (r ? N.maxEdge : M.maxEdge),
616
+ ...e.targetBytes || r ? { targetBytes: e.targetBytes ?? N.targetBytes } : {}
518
617
  };
519
618
  }
520
619
  retryable() {
521
620
  return this.state.uploads.some((e) => e.status === "failed" && e.error === "upload");
522
621
  }
622
+ newConversationTakesSelections() {
623
+ return !!this.opts.selections && this.selectionPolicy?.enabled === !0;
624
+ }
625
+ addSelection(e) {
626
+ if (!this.opts.selections || this.selectionPolicy?.enabled === !1) return null;
627
+ let t = K(e);
628
+ if (!t) return null;
629
+ this.selectionPolicy || this.loadCapabilities();
630
+ let n = this.selectionLimit(), r = [...this.state.selections];
631
+ for (; r.length >= n;) {
632
+ let e = r.shift();
633
+ this.emit("selection-removed", { id: e.id });
634
+ }
635
+ let i = this.id("s");
636
+ return r.push({
637
+ ...t,
638
+ id: i
639
+ }), this.changed({ selections: r }), i;
640
+ }
641
+ selectionLimit() {
642
+ return Math.max(1, Math.min(3, this.selectionPolicy?.maxCount ?? 3));
643
+ }
644
+ removeSelection(e) {
645
+ let t = this.state.selections.filter((t) => t.id !== e);
646
+ t.length !== this.state.selections.length && (this.changed({ selections: t }), this.emit("selection-removed", { id: e }));
647
+ }
648
+ clearSelections() {
649
+ let e = this.state.selections.map((e) => e.id);
650
+ if (e.length) {
651
+ this.changed({ selections: [] });
652
+ for (let t of e) this.emit("selection-removed", { id: t });
653
+ }
654
+ }
523
655
  newConversationTakesPhotos() {
524
656
  return !!this.opts.uploadFile && this.policy?.enabled === !0;
525
657
  }
526
658
  loadCapabilities() {
527
- return !this.opts.uploadFile || (this.capabilitiesWanted = !0, this.policy) ? Promise.resolve() : (this.loadingPolicy ||= (async () => {
659
+ return !this.opts.uploadFile && !this.opts.selections || (this.capabilitiesWanted = !0, this.policy) ? Promise.resolve() : (this.loadingPolicy ||= (async () => {
528
660
  try {
529
- let e = (await this.json("/v1/capabilities"))?.attachments ?? {};
661
+ let e = await this.json("/v1/capabilities"), t = e?.selections ?? {};
662
+ this.selectionPolicy = {
663
+ enabled: t.enabled === !0,
664
+ ...Number.isInteger(t.maxCount) ? { maxCount: t.maxCount } : {}
665
+ };
666
+ let n = e?.attachments ?? {};
530
667
  this.policy = {
531
- enabled: e.enabled === !0,
532
- ...Array.isArray(e.accept) ? { accept: e.accept.filter((e) => typeof e == "string") } : {},
533
- ...Number.isInteger(e.maxCount) ? { maxCount: e.maxCount } : {},
534
- ...e.vision === !0 ? { vision: !0 } : {}
668
+ enabled: n.enabled === !0,
669
+ ...Array.isArray(n.accept) ? { accept: n.accept.filter((e) => typeof e == "string") } : {},
670
+ ...Number.isInteger(n.maxCount) ? { maxCount: n.maxCount } : {},
671
+ ...n.vision === !0 ? { vision: !0 } : {}
535
672
  };
536
673
  } catch (e) {
537
- e instanceof A && e.status === 404 && (this.policy = { enabled: !1 });
674
+ e instanceof R && e.status === 404 && (this.policy = { enabled: !1 }, this.selectionPolicy = { enabled: !1 });
538
675
  } finally {
539
676
  this.loadingPolicy = null;
540
677
  }
541
- !this.state.conversationId && this.state.canAttach !== this.newConversationTakesPhotos() && this.changed({ canAttach: this.newConversationTakesPhotos() });
678
+ this.state.conversationId || this.changed({
679
+ canAttach: this.newConversationTakesPhotos(),
680
+ canSelect: this.newConversationTakesSelections()
681
+ }), this.selectionPolicy?.enabled === !1 && this.state.selections.length && this.clearSelections();
542
682
  })(), this.loadingPolicy);
543
683
  }
544
684
  uploading() {
@@ -566,7 +706,7 @@ var I = class {
566
706
  size: r.size,
567
707
  status: "preparing",
568
708
  progress: 0
569
- }, o = t.includes(i) ? O(r) : void 0;
709
+ }, o = t.includes(i) ? F(r) : void 0;
570
710
  o && (a.previewUrl = o, this.previews.add(o)), this.state.uploads.push(a);
571
711
  let s = this.state.uploads.filter((e) => e.status !== "failed" || e.error === "upload").length;
572
712
  t.includes(i) ? s > n ? this.refuse(a, "count") : (this.files.set(a.id, { file: r }), this.startUpload(a.id)) : this.refuse(a, "type");
@@ -575,7 +715,7 @@ var I = class {
575
715
  }
576
716
  removeUpload(e) {
577
717
  let t = this.upload(e);
578
- t && (t.attachment && this.discard(t.attachment), this.files.get(e)?.controller?.abort(), this.files.delete(e), k(t.previewUrl), t.previewUrl && this.previews.delete(t.previewUrl), this.changed({ uploads: this.state.uploads.filter((t) => t.id !== e) }));
718
+ t && (t.attachment && this.discard(t.attachment), this.files.get(e)?.controller?.abort(), this.files.delete(e), I(t.previewUrl), t.previewUrl && this.previews.delete(t.previewUrl), this.changed({ uploads: this.state.uploads.filter((t) => t.id !== e) }));
579
719
  }
580
720
  retryUpload(e) {
581
721
  let t = this.upload(e);
@@ -593,7 +733,7 @@ var I = class {
593
733
  }), this.changed();
594
734
  let { maxBytes: s, maxEdge: c, targetBytes: l } = this.attachmentLimits();
595
735
  try {
596
- let e = this.opts.prepareImage ?? g, i;
736
+ let e = this.opts.prepareImage ?? _, i;
597
737
  try {
598
738
  i = await e(t.file, {
599
739
  maxEdge: c,
@@ -614,7 +754,7 @@ var I = class {
614
754
  Object.assign(n, {
615
755
  status: "uploading",
616
756
  size: i.blob.size,
617
- name: m(n.name, i.contentType),
757
+ name: h(n.name, i.contentType),
618
758
  contentType: i.contentType
619
759
  }), this.changed();
620
760
  let u = await r(i.blob, {
@@ -645,7 +785,7 @@ var I = class {
645
785
  }
646
786
  }), this.changed();
647
787
  } catch (e) {
648
- if (!a() || N(e) || o.signal.aborted) return;
788
+ if (!a() || V(e) || o.signal.aborted) return;
649
789
  this.refuse(n, "upload", e instanceof Error && e.message ? e.message : void 0), this.changed();
650
790
  }
651
791
  }
@@ -659,7 +799,7 @@ var I = class {
659
799
  for (let e of this.state.uploads) e.attachment && this.discard(e.attachment);
660
800
  for (let e of this.files.values()) e.controller?.abort();
661
801
  this.files = /* @__PURE__ */ new Map();
662
- for (let e of this.previews) k(e);
802
+ for (let e of this.previews) I(e);
663
803
  this.previews = /* @__PURE__ */ new Set();
664
804
  }
665
805
  async decide(e) {
@@ -668,7 +808,7 @@ var I = class {
668
808
  let n = this.state.pendingApprovals, r = new Map(e.map((e) => [e.approvalId, e]));
669
809
  for (let e of n) {
670
810
  let t = this.tools.get(e.toolCallId), n = r.get(e.approvalId);
671
- t && (t.state = n?.approved ? "running" : "denied"), t && n?.approved && n.allowForConversation && (t.granted = !0);
811
+ t && e.started ? (t.state = "error", t.errorText = L) : (t && (t.state = n?.approved ? "running" : "denied"), t && n?.approved && n.allowForConversation && (t.granted = !0));
672
812
  }
673
813
  if (this.changed({
674
814
  pendingApprovals: [],
@@ -676,7 +816,7 @@ var I = class {
676
816
  }), await this.turn(`/v1/conversations/${encodeURIComponent(t)}/approvals`, { decisions: e }) === "not-sent") {
677
817
  for (let e of n) {
678
818
  let t = this.tools.get(e.toolCallId);
679
- t && (t.state = "awaiting-approval", delete t.granted);
819
+ t && (t.state = "awaiting-approval", delete t.granted, delete t.errorText);
680
820
  }
681
821
  this.retryAction = () => this.decide(e), this.changed({
682
822
  pendingApprovals: n,
@@ -691,7 +831,7 @@ var I = class {
691
831
  let n = await this.json(`/v1/conversations/${encodeURIComponent(t)}/allowances/${encodeURIComponent(e)}`, { method: "DELETE" });
692
832
  return this.changed({ allowances: n.allowances ?? [] }), !0;
693
833
  } catch (t) {
694
- let n = M(t);
834
+ let n = B(t);
695
835
  return this.changed({
696
836
  allowances: this.state.allowances.filter((t) => t.toolName !== e),
697
837
  ...t?.status === 404 ? {} : { problem: n }
@@ -721,11 +861,39 @@ var I = class {
721
861
  dismissProblem() {
722
862
  this.changed({ problem: null });
723
863
  }
864
+ async continueConversation() {
865
+ let e = this.state.conversationId;
866
+ if (!e || this.state.continuing || this.busy()) return;
867
+ if (this.state.continuedIn) return this.openConversation(this.state.continuedIn);
868
+ if (!this.state.full || this.state.pendingApprovals.length) return;
869
+ let t = this.generation;
870
+ this.retryAction = null, this.changed({
871
+ continuing: !0,
872
+ problem: null
873
+ });
874
+ let n;
875
+ try {
876
+ n = (await this.json(`/v1/conversations/${encodeURIComponent(e)}/continue`, {
877
+ method: "POST",
878
+ body: JSON.stringify(this.opts.uploadFile ? { capabilities: { attachments: !0 } } : {})
879
+ })).conversationId;
880
+ } catch (e) {
881
+ if (t !== this.generation) return;
882
+ this.retryAction = () => this.continueConversation(), this.changed({
883
+ continuing: !1,
884
+ problem: B(e)
885
+ });
886
+ return;
887
+ }
888
+ t === this.generation && await this.openConversation(n);
889
+ }
724
890
  newConversation() {
725
891
  this.reset(), this.capabilitiesWanted && this.loadCapabilities();
726
892
  }
727
- reset() {
728
- this.generation += 1, this.controller?.abort(), this.dropPhotos(), this.tools = /* @__PURE__ */ new Map(), this.retryAction = null, this.state = D(this.newConversationTakesPhotos()), this.changed();
893
+ reset(e = {}) {
894
+ this.generation += 1, this.controller?.abort(), this.dropPhotos(), this.tools = /* @__PURE__ */ new Map(), this.retryAction = null;
895
+ let t = e.keepSelections === !1 ? [] : this.state.selections;
896
+ this.state = P(this.newConversationTakesPhotos(), this.newConversationTakesSelections()), this.state.selections = t, this.changed();
729
897
  }
730
898
  async listConversations(e = {}) {
731
899
  let t = new URLSearchParams({
@@ -747,7 +915,7 @@ var I = class {
747
915
  for (let [e, t] of Object.entries(n.toolTitles ?? {})) typeof t == "string" && t && this.titles.set(e, t);
748
916
  let r = n.pendingApprovals ?? [];
749
917
  for (let e of r) e.title && this.titles.set(e.toolName, e.title);
750
- let i = l(n.messages ?? [], r, this.titles);
918
+ let i = u(n.messages ?? [], r, this.titles);
751
919
  this.tools = /* @__PURE__ */ new Map();
752
920
  for (let e of i) for (let t of e.parts) t.kind === "tool" && this.tools.set(t.toolCallId, t);
753
921
  this.keepPreviews(r);
@@ -755,19 +923,32 @@ var I = class {
755
923
  let t = this.tools.get(e.toolCallId);
756
924
  t && (t.allowed = !0, e.preview && (t.preview = e.preview));
757
925
  }
926
+ for (let e of n.decidedCalls ?? []) {
927
+ let t = this.tools.get(e.toolCallId);
928
+ t && e.preview && !t.preview && (t.preview = e.preview);
929
+ }
758
930
  this.retryAction = null, this.dropPhotos(), this.state = {
759
- ...D(!!this.opts.uploadFile && n.attachments === !0),
931
+ ...P(!!this.opts.uploadFile && n.attachments === !0, !!this.opts.selections && n.selections === !0),
932
+ selections: this.state.selections,
760
933
  conversationId: e,
761
934
  messages: i,
762
935
  pendingApprovals: r,
763
936
  allowances: n.allowances ?? [],
764
- status: r.length ? "awaiting-approval" : "idle"
937
+ status: r.length ? "awaiting-approval" : "idle",
938
+ full: n.limitReached === "conversation",
939
+ problem: n.limitReached === "conversation" ? { code: "conversation-full" } : null,
940
+ continuedFrom: n.continuedFrom ? {
941
+ id: n.continuedFrom,
942
+ title: n.title ?? ""
943
+ } : null,
944
+ handover: n.handover || null,
945
+ continuedIn: n.continuedIn ?? null
765
946
  }, this.changed();
766
947
  } catch (n) {
767
948
  if (t !== this.generation) return;
768
949
  this.retryAction = () => this.openConversation(e), this.changed({
769
950
  status: "idle",
770
- problem: M(n)
951
+ problem: B(n)
771
952
  });
772
953
  }
773
954
  }
@@ -777,7 +958,7 @@ var I = class {
777
958
  async end() {
778
959
  this.controller?.abort();
779
960
  let e = this.session;
780
- this.session = null, this.capabilitiesWanted = !1, this.reset(), e && await this.opts.endSession?.(e.sessionId);
961
+ this.session = null, this.capabilitiesWanted = !1, this.reset({ keepSelections: !1 }), e && await this.opts.endSession?.(e.sessionId);
781
962
  }
782
963
  busy() {
783
964
  return this.state.status === "sending" || this.state.status === "streaming" || this.state.status === "loading";
@@ -798,35 +979,45 @@ var I = class {
798
979
  body: JSON.stringify(t),
799
980
  headers: { accept: "text/event-stream, application/json;q=0.9" },
800
981
  signal: a.signal
801
- }), !o.ok) throw await j(o);
982
+ }), !o.ok) throw await z(o);
802
983
  } catch (n) {
803
- if (this.controller === a && (this.controller = null), !r()) return "answered";
804
- if (this.drop(i), N(n)) return this.changed({ status: "idle" }), "not-sent";
805
- let o = M(n);
806
- if (o.code === "photos-refused") {
984
+ let o = e === "/v1/chat" ? this.sending : [];
985
+ if (this.sending = [], this.controller === a && (this.controller = null), !r()) return "answered";
986
+ if (this.drop(i), V(n)) return this.changed({ status: "idle" }), "not-sent";
987
+ let s = B(n);
988
+ if (s.code === "selections-refused") {
989
+ let e = this.state.messages.at(-1);
990
+ return e?.role === "user" && this.drop(e), this.changed({
991
+ status: "idle",
992
+ problem: s,
993
+ selections: o,
994
+ canSelect: !1
995
+ }), "not-sent";
996
+ }
997
+ if (s.code === "photos-refused") {
807
998
  let e = this.state.messages.at(-1);
808
999
  return e?.role === "user" && this.drop(e), this.policy = null, this.changed({
809
1000
  status: "idle",
810
- problem: o,
1001
+ problem: s,
811
1002
  canAttach: !1
812
1003
  }), this.loadCapabilities(), "not-sent";
813
1004
  }
814
- return this.retryAction = () => this.turn(e, t).then(() => void 0), this.changed({
1005
+ return this.retryAction = () => this.turn(e, t).then(() => void 0), s.code === "conversation-full" && (this.retryAction = null, this.state.full = !0, o.length && (this.state.selections = o)), this.changed({
815
1006
  status: "idle",
816
- problem: o
1007
+ problem: s
817
1008
  }), "not-sent";
818
1009
  }
819
- if (!r()) return "answered";
1010
+ if (this.sending = [], !r()) return "answered";
820
1011
  this.changed({ status: "streaming" });
821
1012
  let s = !1, c = null, l = !1, u = /* @__PURE__ */ new Map();
822
1013
  try {
823
- let e = o.body ? C(o.body, a.signal) : L(await o.text());
1014
+ let e = o.body ? w(o.body, a.signal) : J(await o.text());
824
1015
  for await (let t of e) {
825
1016
  if (!r()) break;
826
1017
  t.type === "finish" ? s = !0 : t.type === "data-turn" && (c = t.data), this.apply(t, i, u), this.changed();
827
1018
  }
828
1019
  } catch (e) {
829
- N(e) || (l = !0);
1020
+ V(e) || (l = !0);
830
1021
  } finally {
831
1022
  this.controller === a && (this.controller = null);
832
1023
  }
@@ -847,6 +1038,10 @@ var I = class {
847
1038
  }
848
1039
  finishTurn(e) {
849
1040
  this.settleUnfinished(!1);
1041
+ for (let t of e.decisions ?? []) {
1042
+ let e = this.tools.get(t.toolCallId);
1043
+ e && (t.outcome === "cancelled" ? e.state = "denied" : t.outcome === "done" ? e.state !== "done" && (e.state = "done") : (e.state = "error", e.errorText = t.outcome === "unknown" ? L : t.error ?? e.errorText ?? ""));
1044
+ }
850
1045
  let t = e.pendingApprovals ?? [];
851
1046
  for (let e of t) e.title && this.titles.set(e.toolName, e.title);
852
1047
  this.keepPreviews(t);
@@ -855,7 +1050,7 @@ var I = class {
855
1050
  n = { code: "token-expired" };
856
1051
  let e = this.session;
857
1052
  e && this.opts.refreshUserToken(e.sessionId).catch(() => this.session = null);
858
- } 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" } : {
1053
+ } else e.limitReached === "steps" ? n = { code: "step-limit" } : e.limitReached === "conversation" ? n = { code: "conversation-full" } : e.status === "error" && (n = e.limitReached === "output" ? { code: e.cut === "text" ? "answer-cut" : "too-long" } : {
859
1054
  code: "failed",
860
1055
  ...e.error ? { message: e.error } : {}
861
1056
  });
@@ -865,7 +1060,8 @@ var I = class {
865
1060
  lastTurn: e,
866
1061
  allowances: e.allowances ?? [],
867
1062
  problem: n,
868
- status: t.length ? "awaiting-approval" : "idle"
1063
+ status: t.length ? "awaiting-approval" : "idle",
1064
+ full: this.state.full || e.limitReached === "conversation"
869
1065
  }), t.length && this.emit("approval-pending", { approvals: t }), this.emit("turn-end", e);
870
1066
  }
871
1067
  keepPreviews(e) {
@@ -970,9 +1166,9 @@ var I = class {
970
1166
  return r;
971
1167
  }
972
1168
  };
973
- async function* L(e) {
974
- yield* x(e);
1169
+ async function* J(e) {
1170
+ yield* S(e);
975
1171
  }
976
- export { x as a, h as c, i as d, r as f, S as i, l, I as n, C as o, M as r, g as s, T as t, e as u };
1172
+ export { A as a, S as c, g as d, u as f, r as h, k as i, w as l, i as m, q as n, T as o, e as p, B as r, C as s, M as t, _ as u };
977
1173
 
978
- //# sourceMappingURL=core-9svu5kzm.js.map
1174
+ //# sourceMappingURL=core-B_prP9RO.js.map