@ghuri/ai-widget 0.5.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,34 +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(), l = /* @__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 u = null, d = 0, f = () => (u || (u = {
90
- id: `h${d++}`,
93
+ let d = null, f = 0, p = () => (d || (d = {
94
+ id: `h${f++}`,
91
95
  role: "assistant",
92
96
  parts: []
93
- }, r.push(u)), u);
97
+ }, r.push(d)), d);
94
98
  for (let t of e) if (t.role === "user") {
95
- u = null;
96
- let e = Array.isArray(t.content) ? t.content.flatMap((e) => a(e) ?? []) : [], n = s(t.content);
97
- if (!n && !e.length && Array.isArray(t.content) && t.content.length && t.content.every(o)) continue;
98
- let i = [];
99
- 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({
100
108
  kind: "attachments",
101
- id: `h${d++}`,
109
+ id: `h${f++}`,
102
110
  attachments: e
103
- }), (n || !e.length) && i.push({
111
+ }), (i || !e.length) && l.push({
104
112
  kind: "text",
105
- id: `h${d++}`,
106
- text: n
113
+ id: `h${f++}`,
114
+ text: i
107
115
  }), r.push({
108
- id: `h${d++}`,
116
+ id: `h${f++}`,
109
117
  role: "user",
110
- parts: i
118
+ parts: l
111
119
  });
112
120
  } else if (t.role === "assistant") {
113
- let e = f(), r = typeof t.content == "string" ? [{
121
+ let e = p(), r = typeof t.content == "string" ? [{
114
122
  type: "text",
115
123
  text: t.content
116
124
  }] : t.content ?? [];
@@ -118,7 +126,7 @@ function l(e, t = [], n = /* @__PURE__ */ new Map()) {
118
126
  let n = e.parts.at(-1);
119
127
  n?.kind === "text" ? n.text += t.text : e.parts.push({
120
128
  kind: "text",
121
- id: `h${d++}`,
129
+ id: `h${f++}`,
122
130
  text: t.text
123
131
  });
124
132
  } else if (t.type === "tool-call" && typeof t.toolCallId == "string") {
@@ -133,35 +141,35 @@ function l(e, t = [], n = /* @__PURE__ */ new Map()) {
133
141
  i.set(a.toolCallId, a), e.parts.push(a);
134
142
  } else if (t.type === "tool-approval-request" && typeof t.toolCallId == "string") {
135
143
  let e = i.get(t.toolCallId);
136
- e && (e.state = "awaiting-approval", e.approvalId = t.approvalId, l.set(t.approvalId, e));
144
+ e && (e.state = "awaiting-approval", e.approvalId = t.approvalId, u.set(t.approvalId, e));
137
145
  }
138
146
  } else if (t.role === "tool" && Array.isArray(t.content)) {
139
147
  for (let e of t.content) if (e.type === "tool-approval-response") {
140
- let t = l.get(e.approvalId);
148
+ let t = u.get(e.approvalId);
141
149
  t && t.state === "awaiting-approval" && (t.state = e.approved ? "running" : "denied");
142
150
  } else if (e.type === "tool-result") {
143
151
  let t = i.get(e.toolCallId);
144
- t && Object.assign(t, c(e.output));
152
+ t && Object.assign(t, l(e.output));
145
153
  }
146
154
  }
147
- let p = new Set(t.map((e) => e.toolCallId));
148
- for (let e of i.values()) e.state === "awaiting-approval" && !p.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");
149
157
  return r.filter((e) => e.parts.length > 0);
150
158
  }
151
159
  // src/core/prepare.ts
152
- var u = .85, d = .7, f = {
160
+ var d = .85, f = .7, p = {
153
161
  "image/jpeg": "jpg",
154
162
  "image/png": "png",
155
163
  "image/webp": "webp",
156
164
  "image/gif": "gif"
157
- }, p = /\.(jpe?g|jfif|png|webp|gif|heic|heif|avif|bmp|tiff?)$/i;
158
- function m(e, t) {
159
- 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];
160
168
  if (!n) return e;
161
- let r = p.exec(e)?.[1]?.toLowerCase();
169
+ let r = m.exec(e)?.[1]?.toLowerCase();
162
170
  return r === n || n === "jpg" && (r === "jpeg" || r === "jfif") ? e : `${r ? e.slice(0, -r.length - 1) : e}.${n}`;
163
171
  }
164
- function h(e, t, n) {
172
+ function g(e, t, n) {
165
173
  let r = Math.max(e, t);
166
174
  if (!r || r <= n) return {
167
175
  width: e,
@@ -173,7 +181,7 @@ function h(e, t, n) {
173
181
  height: Math.max(1, Math.round(t * i))
174
182
  };
175
183
  }
176
- async function g(e, t) {
184
+ async function _(e, t) {
177
185
  let { contentType: n } = t;
178
186
  if (n === "image/gif" || typeof createImageBitmap != "function") return {
179
187
  blob: e,
@@ -189,14 +197,14 @@ async function g(e, t) {
189
197
  };
190
198
  }
191
199
  try {
192
- 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);
193
201
  if (!a || !o) return {
194
202
  blob: e,
195
203
  contentType: n,
196
204
  width: r.width,
197
205
  height: r.height
198
206
  };
199
- 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;
200
208
  return {
201
209
  blob: c,
202
210
  contentType: c.type || n,
@@ -206,16 +214,16 @@ async function g(e, t) {
206
214
  r.close();
207
215
  }
208
216
  }
209
- async function _(e, t) {
210
- 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);
211
219
  if (!r || r.type !== n) return null;
212
220
  if (r.size > t) {
213
- let t = await b(e, n, d);
221
+ let t = await x(e, n, f);
214
222
  t && t.type === n && t.size < r.size && (r = t);
215
223
  }
216
224
  return r;
217
225
  }
218
- function v(e) {
226
+ function y(e) {
219
227
  let t = e.getContext("2d");
220
228
  if (!t) return !1;
221
229
  let n;
@@ -227,7 +235,7 @@ function v(e) {
227
235
  for (let e = 3; e < n.length; e += 4) if (n[e] !== 255) return !1;
228
236
  return !0;
229
237
  }
230
- function y(e, t) {
238
+ function b(e, t) {
231
239
  let n;
232
240
  if (typeof OffscreenCanvas == "function") n = new OffscreenCanvas(t.width, t.height);
233
241
  else if (typeof document < "u") n = document.createElement("canvas"), n.width = t.width, n.height = t.height;
@@ -235,18 +243,18 @@ function y(e, t) {
235
243
  let r = n.getContext("2d");
236
244
  return r ? (r.drawImage(e, 0, 0, t.width, t.height), n) : null;
237
245
  }
238
- function b(e, t, n) {
246
+ function x(e, t, n) {
239
247
  return "convertToBlob" in e ? e.convertToBlob({
240
248
  type: t,
241
249
  quality: n
242
250
  }).catch(() => null) : new Promise((r) => e.toBlob((e) => r(e), t, n));
243
251
  }
244
252
  // src/core/sse.ts
245
- function x(e) {
246
- let t = new S(), n = t.push(e);
253
+ function S(e) {
254
+ let t = new C(), n = t.push(e);
247
255
  return n.push(...t.end()), n;
248
256
  }
249
- var S = class {
257
+ var C = class {
250
258
  buffer = "";
251
259
  carry = "";
252
260
  done = !1;
@@ -283,8 +291,8 @@ var S = class {
283
291
  }
284
292
  }
285
293
  };
286
- async function* C(e, t) {
287
- 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(() => {});
288
296
  t?.addEventListener("abort", a, { once: !0 });
289
297
  try {
290
298
  for (;;) {
@@ -299,8 +307,35 @@ async function* C(e, t) {
299
307
  t?.removeEventListener("abort", a), i.releaseLock();
300
308
  }
301
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
+ }
302
337
  // src/core/client.ts
303
- var w = 3e4, T = {
338
+ var j = 3e4, M = {
304
339
  accept: [
305
340
  "image/jpeg",
306
341
  "image/png",
@@ -310,12 +345,14 @@ var w = 3e4, T = {
310
345
  maxCount: 10,
311
346
  maxBytes: 5242880,
312
347
  maxEdge: 2048
313
- }, E = {
348
+ }, N = {
314
349
  maxEdge: 1568,
315
350
  targetBytes: 1e6
316
351
  };
317
- function D(e = !1) {
352
+ function P(e = !1, t = !1) {
318
353
  return {
354
+ selections: [],
355
+ canSelect: t,
319
356
  status: "idle",
320
357
  conversationId: null,
321
358
  messages: [],
@@ -332,23 +369,19 @@ function D(e = !1) {
332
369
  continuedIn: null
333
370
  };
334
371
  }
335
- function O(e) {
336
- let t = e.replace(/^\s*<handover>\s*\n?/, "").replace(/\n?\s*<\/handover>\s*$/, "").split("\n"), n = t.findIndex((e) => !e.trim());
337
- return (n >= 0 ? t.slice(n + 1) : t).join("\n").trim();
338
- }
339
- function k(e) {
372
+ function F(e) {
340
373
  try {
341
374
  return typeof URL.createObjectURL == "function" ? URL.createObjectURL(e) : void 0;
342
375
  } catch {
343
376
  return;
344
377
  }
345
378
  }
346
- function A(e) {
379
+ function I(e) {
347
380
  try {
348
381
  e && typeof URL.revokeObjectURL == "function" && URL.revokeObjectURL(e);
349
382
  } catch {}
350
383
  }
351
- var j = "This change had already started, and its result was not recorded. Check before trying again.", M = 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 {
352
385
  status;
353
386
  code;
354
387
  detail;
@@ -358,18 +391,21 @@ var j = "This change had already started, and its result was not recorded. Check
358
391
  super(n || `HTTP ${e}`), this.status = e, this.code = t, this.detail = n, this.retryAfter = r, this.fields = i;
359
392
  }
360
393
  };
361
- async function N(e) {
394
+ async function z(e) {
362
395
  let t = null;
363
396
  try {
364
397
  t = await e.json();
365
398
  } catch {}
366
399
  let n = Number(e.headers.get("retry-after"));
367
- return new M(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 : {});
368
401
  }
369
- function P(e) {
370
- if (!(e instanceof M)) return { code: "unavailable" };
371
- let { status: t, code: n, detail: r } = e, i = e.fields.attachments;
372
- 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) ? {
373
409
  code: "photos-refused",
374
410
  ...typeof i[0] == "string" ? { message: i[0] } : {}
375
411
  } : t === 429 ? {
@@ -380,14 +416,14 @@ function P(e) {
380
416
  ...r ? { message: r } : {}
381
417
  };
382
418
  }
383
- function F(e) {
419
+ function V(e) {
384
420
  return e instanceof DOMException ? e.name === "AbortError" : e?.name === "AbortError";
385
421
  }
386
- function I(e, t) {
422
+ function H(e, t) {
387
423
  let n = new Date(e.expiresAt).getTime();
388
- return Number.isNaN(n) || n - w > t;
424
+ return Number.isNaN(n) || n - j > t;
389
425
  }
390
- function L(e) {
426
+ function U(e) {
391
427
  return {
392
428
  ...e,
393
429
  messages: e.messages.map((e) => ({
@@ -396,10 +432,44 @@ function L(e) {
396
432
  })),
397
433
  pendingApprovals: [...e.pendingApprovals],
398
434
  uploads: e.uploads.map((e) => ({ ...e })),
399
- 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
400
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;
401
471
  }
402
- var R = class {
472
+ var q = class {
403
473
  opts;
404
474
  state;
405
475
  view;
@@ -416,13 +486,15 @@ var R = class {
416
486
  files = /* @__PURE__ */ new Map();
417
487
  previews = /* @__PURE__ */ new Set();
418
488
  policy = null;
489
+ selectionPolicy = null;
490
+ sending = [];
419
491
  loadingPolicy = null;
420
492
  capabilitiesWanted = !1;
421
493
  constructor(e) {
422
494
  this.opts = {
423
495
  ...e,
424
496
  apiUrl: e.apiUrl.replace(/\/+$/, "")
425
- }, this.state = D(!1), this.view = L(this.state);
497
+ }, this.state = P(!1), this.view = U(this.state);
426
498
  }
427
499
  getState() {
428
500
  return this.view;
@@ -438,7 +510,7 @@ var R = class {
438
510
  for (let n of this.events.get(e) ?? []) n(t);
439
511
  }
440
512
  changed(e = {}) {
441
- Object.assign(this.state, e), this.view = L(this.state);
513
+ Object.assign(this.state, e), this.view = U(this.state);
442
514
  for (let e of this.listeners) e(this.view);
443
515
  }
444
516
  id(e) {
@@ -449,7 +521,7 @@ var R = class {
449
521
  }
450
522
  async ensureSession() {
451
523
  let e = this.session;
452
- return e && I(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(() => {
453
525
  this.starting = null;
454
526
  }), this.starting);
455
527
  }
@@ -461,7 +533,7 @@ var R = class {
461
533
  headers: i
462
534
  });
463
535
  if (a.status !== 401 || n) return a;
464
- let o = await N(a);
536
+ let o = await z(a);
465
537
  if (this.changed({ problem: { code: "reconnecting" } }), o.code === "user_token_expired") try {
466
538
  await this.opts.refreshUserToken(r.sessionId);
467
539
  } catch {
@@ -473,7 +545,7 @@ var R = class {
473
545
  }
474
546
  async json(e, t = {}) {
475
547
  let n = await this.request(e, t);
476
- if (!n.ok) throw await N(n);
548
+ if (!n.ok) throw await z(n);
477
549
  return await n.json();
478
550
  }
479
551
  async send(e) {
@@ -483,12 +555,22 @@ var R = class {
483
555
  this.changed({ problem: { code: "conversation-full" } });
484
556
  return;
485
557
  }
558
+ let r = this.state.selections;
559
+ if (r.length && (!t || !this.state.canSelect)) return;
486
560
  for (let e of this.state.pendingApprovals) {
487
561
  let t = this.tools.get(e.toolCallId);
488
562
  t && (t.state = "denied");
489
563
  }
490
- let r = n.map((e) => e.attachment), i = [];
491
- 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) {
492
574
  let e = {
493
575
  kind: "attachments",
494
576
  id: this.id("p"),
@@ -497,63 +579,106 @@ var R = class {
497
579
  ...e.previewUrl ? { previewUrl: e.previewUrl } : {}
498
580
  }))
499
581
  };
500
- i.push(e);
582
+ a.push(e);
501
583
  }
502
- t && i.push({
584
+ t && a.push({
503
585
  kind: "text",
504
586
  id: this.id("t"),
505
587
  text: t
506
588
  }), this.state.messages.push({
507
589
  id: this.id("u"),
508
590
  role: "user",
509
- parts: i
591
+ parts: a
510
592
  });
511
- for (let e of this.state.uploads) e.status !== "ready" && A(e.previewUrl);
512
- 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({
513
595
  pendingApprovals: [],
514
596
  problem: null,
515
- uploads: []
516
- });
517
- 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;
518
601
  await this.turn("/v1/chat", {
519
602
  message: t,
520
- ...a ? { conversationId: a } : {},
521
- ...r.length ? { attachments: r } : {},
522
- ...!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 } } : {}
523
607
  });
524
608
  }
525
609
  attachmentLimits() {
526
- 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;
527
611
  return {
528
612
  accept: n ? t.filter((e) => n.includes(e)) : t,
529
- maxCount: Math.min(e.maxCount ?? T.maxCount, this.policy?.maxCount ?? T.maxCount, T.maxCount),
530
- maxBytes: e.maxBytes ?? T.maxBytes,
531
- maxEdge: e.maxEdge ?? (r ? E.maxEdge : T.maxEdge),
532
- ...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 } : {}
533
617
  };
534
618
  }
535
619
  retryable() {
536
620
  return this.state.uploads.some((e) => e.status === "failed" && e.error === "upload");
537
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
+ }
538
655
  newConversationTakesPhotos() {
539
656
  return !!this.opts.uploadFile && this.policy?.enabled === !0;
540
657
  }
541
658
  loadCapabilities() {
542
- 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 () => {
543
660
  try {
544
- 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 ?? {};
545
667
  this.policy = {
546
- enabled: e.enabled === !0,
547
- ...Array.isArray(e.accept) ? { accept: e.accept.filter((e) => typeof e == "string") } : {},
548
- ...Number.isInteger(e.maxCount) ? { maxCount: e.maxCount } : {},
549
- ...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 } : {}
550
672
  };
551
673
  } catch (e) {
552
- e instanceof M && e.status === 404 && (this.policy = { enabled: !1 });
674
+ e instanceof R && e.status === 404 && (this.policy = { enabled: !1 }, this.selectionPolicy = { enabled: !1 });
553
675
  } finally {
554
676
  this.loadingPolicy = null;
555
677
  }
556
- !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();
557
682
  })(), this.loadingPolicy);
558
683
  }
559
684
  uploading() {
@@ -581,7 +706,7 @@ var R = class {
581
706
  size: r.size,
582
707
  status: "preparing",
583
708
  progress: 0
584
- }, o = t.includes(i) ? k(r) : void 0;
709
+ }, o = t.includes(i) ? F(r) : void 0;
585
710
  o && (a.previewUrl = o, this.previews.add(o)), this.state.uploads.push(a);
586
711
  let s = this.state.uploads.filter((e) => e.status !== "failed" || e.error === "upload").length;
587
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");
@@ -590,7 +715,7 @@ var R = class {
590
715
  }
591
716
  removeUpload(e) {
592
717
  let t = this.upload(e);
593
- t && (t.attachment && this.discard(t.attachment), this.files.get(e)?.controller?.abort(), this.files.delete(e), A(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) }));
594
719
  }
595
720
  retryUpload(e) {
596
721
  let t = this.upload(e);
@@ -608,7 +733,7 @@ var R = class {
608
733
  }), this.changed();
609
734
  let { maxBytes: s, maxEdge: c, targetBytes: l } = this.attachmentLimits();
610
735
  try {
611
- let e = this.opts.prepareImage ?? g, i;
736
+ let e = this.opts.prepareImage ?? _, i;
612
737
  try {
613
738
  i = await e(t.file, {
614
739
  maxEdge: c,
@@ -629,7 +754,7 @@ var R = class {
629
754
  Object.assign(n, {
630
755
  status: "uploading",
631
756
  size: i.blob.size,
632
- name: m(n.name, i.contentType),
757
+ name: h(n.name, i.contentType),
633
758
  contentType: i.contentType
634
759
  }), this.changed();
635
760
  let u = await r(i.blob, {
@@ -660,7 +785,7 @@ var R = class {
660
785
  }
661
786
  }), this.changed();
662
787
  } catch (e) {
663
- if (!a() || F(e) || o.signal.aborted) return;
788
+ if (!a() || V(e) || o.signal.aborted) return;
664
789
  this.refuse(n, "upload", e instanceof Error && e.message ? e.message : void 0), this.changed();
665
790
  }
666
791
  }
@@ -674,7 +799,7 @@ var R = class {
674
799
  for (let e of this.state.uploads) e.attachment && this.discard(e.attachment);
675
800
  for (let e of this.files.values()) e.controller?.abort();
676
801
  this.files = /* @__PURE__ */ new Map();
677
- for (let e of this.previews) A(e);
802
+ for (let e of this.previews) I(e);
678
803
  this.previews = /* @__PURE__ */ new Set();
679
804
  }
680
805
  async decide(e) {
@@ -683,7 +808,7 @@ var R = class {
683
808
  let n = this.state.pendingApprovals, r = new Map(e.map((e) => [e.approvalId, e]));
684
809
  for (let e of n) {
685
810
  let t = this.tools.get(e.toolCallId), n = r.get(e.approvalId);
686
- t && e.started ? (t.state = "error", t.errorText = j) : (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));
687
812
  }
688
813
  if (this.changed({
689
814
  pendingApprovals: [],
@@ -706,7 +831,7 @@ var R = class {
706
831
  let n = await this.json(`/v1/conversations/${encodeURIComponent(t)}/allowances/${encodeURIComponent(e)}`, { method: "DELETE" });
707
832
  return this.changed({ allowances: n.allowances ?? [] }), !0;
708
833
  } catch (t) {
709
- let n = P(t);
834
+ let n = B(t);
710
835
  return this.changed({
711
836
  allowances: this.state.allowances.filter((t) => t.toolName !== e),
712
837
  ...t?.status === 404 ? {} : { problem: n }
@@ -756,7 +881,7 @@ var R = class {
756
881
  if (t !== this.generation) return;
757
882
  this.retryAction = () => this.continueConversation(), this.changed({
758
883
  continuing: !1,
759
- problem: P(e)
884
+ problem: B(e)
760
885
  });
761
886
  return;
762
887
  }
@@ -765,8 +890,10 @@ var R = class {
765
890
  newConversation() {
766
891
  this.reset(), this.capabilitiesWanted && this.loadCapabilities();
767
892
  }
768
- reset() {
769
- 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();
770
897
  }
771
898
  async listConversations(e = {}) {
772
899
  let t = new URLSearchParams({
@@ -788,7 +915,7 @@ var R = class {
788
915
  for (let [e, t] of Object.entries(n.toolTitles ?? {})) typeof t == "string" && t && this.titles.set(e, t);
789
916
  let r = n.pendingApprovals ?? [];
790
917
  for (let e of r) e.title && this.titles.set(e.toolName, e.title);
791
- let i = l(n.messages ?? [], r, this.titles);
918
+ let i = u(n.messages ?? [], r, this.titles);
792
919
  this.tools = /* @__PURE__ */ new Map();
793
920
  for (let e of i) for (let t of e.parts) t.kind === "tool" && this.tools.set(t.toolCallId, t);
794
921
  this.keepPreviews(r);
@@ -796,8 +923,13 @@ var R = class {
796
923
  let t = this.tools.get(e.toolCallId);
797
924
  t && (t.allowed = !0, e.preview && (t.preview = e.preview));
798
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
+ }
799
930
  this.retryAction = null, this.dropPhotos(), this.state = {
800
- ...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,
801
933
  conversationId: e,
802
934
  messages: i,
803
935
  pendingApprovals: r,
@@ -816,7 +948,7 @@ var R = class {
816
948
  if (t !== this.generation) return;
817
949
  this.retryAction = () => this.openConversation(e), this.changed({
818
950
  status: "idle",
819
- problem: P(n)
951
+ problem: B(n)
820
952
  });
821
953
  }
822
954
  }
@@ -826,7 +958,7 @@ var R = class {
826
958
  async end() {
827
959
  this.controller?.abort();
828
960
  let e = this.session;
829
- 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);
830
962
  }
831
963
  busy() {
832
964
  return this.state.status === "sending" || this.state.status === "streaming" || this.state.status === "loading";
@@ -847,35 +979,45 @@ var R = class {
847
979
  body: JSON.stringify(t),
848
980
  headers: { accept: "text/event-stream, application/json;q=0.9" },
849
981
  signal: a.signal
850
- }), !o.ok) throw await N(o);
982
+ }), !o.ok) throw await z(o);
851
983
  } catch (n) {
852
- if (this.controller === a && (this.controller = null), !r()) return "answered";
853
- if (this.drop(i), F(n)) return this.changed({ status: "idle" }), "not-sent";
854
- let o = P(n);
855
- 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") {
856
998
  let e = this.state.messages.at(-1);
857
999
  return e?.role === "user" && this.drop(e), this.policy = null, this.changed({
858
1000
  status: "idle",
859
- problem: o,
1001
+ problem: s,
860
1002
  canAttach: !1
861
1003
  }), this.loadCapabilities(), "not-sent";
862
1004
  }
863
- return this.retryAction = () => this.turn(e, t).then(() => void 0), o.code === "conversation-full" && (this.retryAction = null, this.state.full = !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({
864
1006
  status: "idle",
865
- problem: o
1007
+ problem: s
866
1008
  }), "not-sent";
867
1009
  }
868
- if (!r()) return "answered";
1010
+ if (this.sending = [], !r()) return "answered";
869
1011
  this.changed({ status: "streaming" });
870
1012
  let s = !1, c = null, l = !1, u = /* @__PURE__ */ new Map();
871
1013
  try {
872
- let e = o.body ? C(o.body, a.signal) : z(await o.text());
1014
+ let e = o.body ? w(o.body, a.signal) : J(await o.text());
873
1015
  for await (let t of e) {
874
1016
  if (!r()) break;
875
1017
  t.type === "finish" ? s = !0 : t.type === "data-turn" && (c = t.data), this.apply(t, i, u), this.changed();
876
1018
  }
877
1019
  } catch (e) {
878
- F(e) || (l = !0);
1020
+ V(e) || (l = !0);
879
1021
  } finally {
880
1022
  this.controller === a && (this.controller = null);
881
1023
  }
@@ -898,7 +1040,7 @@ var R = class {
898
1040
  this.settleUnfinished(!1);
899
1041
  for (let t of e.decisions ?? []) {
900
1042
  let e = this.tools.get(t.toolCallId);
901
- e && (t.outcome === "cancelled" ? e.state = "denied" : t.outcome === "done" ? e.state !== "done" && (e.state = "done") : (e.state = "error", e.errorText = t.outcome === "unknown" ? j : t.error ?? e.errorText ?? ""));
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 ?? ""));
902
1044
  }
903
1045
  let t = e.pendingApprovals ?? [];
904
1046
  for (let e of t) e.title && this.titles.set(e.toolName, e.title);
@@ -1024,9 +1166,9 @@ var R = class {
1024
1166
  return r;
1025
1167
  }
1026
1168
  };
1027
- async function* z(e) {
1028
- yield* x(e);
1169
+ async function* J(e) {
1170
+ yield* S(e);
1029
1171
  }
1030
- export { S as a, g as c, e as d, i as f, P as i, h as l, R as n, x as o, r as p, O as r, C as s, T as t, l 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 };
1031
1173
 
1032
- //# sourceMappingURL=core-4zFtqSww.js.map
1174
+ //# sourceMappingURL=core-B_prP9RO.js.map