@pluno/product-agent-web 0.1.234 → 0.1.235

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.
@@ -263,19 +263,19 @@ function Z(s) {
263
263
  function at(s) {
264
264
  return "revision" in s.data ? s.data.revision : null;
265
265
  }
266
- function be(s) {
266
+ function we(s) {
267
267
  if (s === null || typeof s == "string" || typeof s == "boolean") return !0;
268
268
  if (typeof s == "number") return Number.isFinite(s);
269
- if (Array.isArray(s)) return s.every(be);
269
+ if (Array.isArray(s)) return s.every(we);
270
270
  if (typeof s != "object") return !1;
271
271
  const e = Object.getPrototypeOf(s);
272
- return e !== Object.prototype && e !== null ? !1 : Object.values(s).every(be);
272
+ return e !== Object.prototype && e !== null ? !1 : Object.values(s).every(we);
273
273
  }
274
274
  function X(s) {
275
275
  return s !== null && typeof s == "object" && !Object.isFrozen(s) && (Object.values(s).forEach(X), Object.freeze(s)), s;
276
276
  }
277
277
  function Q(s) {
278
- if (!be(s)) throw new Error("Conversation inputs must be JSON-safe values.");
278
+ if (!we(s)) throw new Error("Conversation inputs must be JSON-safe values.");
279
279
  return JSON.parse(JSON.stringify(s));
280
280
  }
281
281
  function Ti(s = "", e = 0) {
@@ -429,23 +429,23 @@ function Fn(s, e, t, i) {
429
429
  else {
430
430
  const h = Q(e.output.snapshot);
431
431
  a.lane === "current" && (c = { ...c, preparation: null });
432
- const m = c.queries.history, p = a.lane === "current" && (m.status === "not_requested" || h.next_cursor !== null && !c.items[h.next_cursor]);
432
+ const f = c.queries.history, m = a.lane === "current" && (f.status === "not_requested" || h.next_cursor !== null && !c.items[h.next_cursor]);
433
433
  if (h.conversation_id !== a.sessionId) throw new Error("Snapshot belongs to another conversation.");
434
- for (const f of h.removed_items) c = At(c, f);
435
- for (const f of h.items) c = Vt(c, f);
436
- for (const f of h.streams) c = ki(c, f);
434
+ for (const p of h.removed_items) c = At(c, p);
435
+ for (const p of h.items) c = Vt(c, p);
436
+ for (const p of h.streams) c = ki(c, p);
437
437
  if (c = Kt(c, h.execution), c = At(c, {
438
438
  type: "conversation.follow_ups.updated",
439
439
  conversation_id: h.conversation_id,
440
440
  version: h.follow_ups_version,
441
441
  follow_ups: h.follow_ups
442
- }), h.interactions.some((f) => f.conversation_id !== h.conversation_id)) throw new Error("Interaction belongs to another conversation.");
442
+ }), h.interactions.some((p) => p.conversation_id !== h.conversation_id)) throw new Error("Interaction belongs to another conversation.");
443
443
  if (o = { authorityId: s.authorityId, generation: s.generation, sessionId: a.sessionId, sources: h.interactions }, h.execution.version === c.execution?.version)
444
- for (const f of a.acceptedUserMessageIds) {
445
- const y = d[f];
444
+ for (const p of a.acceptedUserMessageIds) {
445
+ const y = d[p];
446
446
  y.executionVersion === null && (d = {
447
447
  ...d,
448
- [f]: { ...y, executionVersion: h.execution.version }
448
+ [p]: { ...y, executionVersion: h.execution.version }
449
449
  });
450
450
  }
451
451
  if (c = { ...c, queries: { ...c.queries, [a.lane]: {
@@ -456,10 +456,10 @@ function Fn(s, e, t, i) {
456
456
  data: Object.keys(c.items),
457
457
  cursor: h.next_cursor,
458
458
  updatedAt: e.output.updatedAt
459
- } } }, p) {
460
- for (const [f, y] of Object.entries(l))
461
- y.sessionId === a.sessionId && y.lane === "history" && delete l[f];
462
- c = { ...c, queries: { ...c.queries, history: { ...c.queries.current, key: m.key } } };
459
+ } } }, m) {
460
+ for (const [p, y] of Object.entries(l))
461
+ y.sessionId === a.sessionId && y.lane === "history" && delete l[p];
462
+ c = { ...c, queries: { ...c.queries, history: { ...c.queries.current, key: f.key } } };
463
463
  }
464
464
  }
465
465
  n = { ...s, requests: l, submissions: d, sessions: { ...s.sessions, [c.sessionId]: c } };
@@ -489,22 +489,22 @@ function Fn(s, e, t, i) {
489
489
  if (t.clients[e.clientScopeId] !== e.conversationScopeId) throw new Error("Submission selection has changed.");
490
490
  const { type: a, authorityId: c, generation: u, prepareContext: l, ...d } = e, h = s.submissions[e.userMessageId];
491
491
  if (h) {
492
- const { contextPreparation: A, requestedModel: _, sessionId: I, delivery: v, cancelled: S, error: C, executionVersion: Y, ...T } = h;
492
+ const { contextPreparation: A, requestedModel: S, sessionId: w, delivery: I, cancelled: _, error: C, executionVersion: Y, ...T } = h;
493
493
  if (Fe(T) !== Fe(d)) throw new Error("User-message identity cannot be reused with different input.");
494
494
  return { state: s, effects: r };
495
495
  }
496
- const m = t.selections[e.conversationScopeId], p = Object.values(s.submissions).find((A) => A.conversationScopeId === e.conversationScopeId && !A.cancelled && A.sessionId !== null), f = i.scopes[e.clientScopeId], y = {
496
+ const f = t.selections[e.conversationScopeId], m = Object.values(s.submissions).find((A) => A.conversationScopeId === e.conversationScopeId && !A.cancelled && A.sessionId !== null), p = i.scopes[e.clientScopeId], y = {
497
497
  ...Q(d),
498
498
  ...l ? { contextPreparation: null } : {},
499
499
  // Extension staging can await page context after the picker has already changed.
500
- requestedModel: f?.submissions[e.userMessageId] ? f.submissions[e.userMessageId].requestedModel ?? null : f ? fs(f) ?? null : null,
501
- sessionId: m.sessionId ?? p?.sessionId ?? null,
500
+ requestedModel: p?.submissions[e.userMessageId] ? p.submissions[e.userMessageId].requestedModel ?? null : p ? fs(p) ?? null : null,
501
+ sessionId: f.sessionId ?? m?.sessionId ?? null,
502
502
  delivery: "staged",
503
503
  cancelled: !1,
504
504
  error: null,
505
505
  executionVersion: null
506
- }, b = { ...s.proactiveQuestions };
507
- delete b[e.conversationScopeId], n = { ...s, proactiveQuestions: b, submissions: { ...s.submissions, [e.userMessageId]: y }, submissionOrder: [...s.submissionOrder, e.userMessageId] };
506
+ }, v = { ...s.proactiveQuestions };
507
+ delete v[e.conversationScopeId], n = { ...s, proactiveQuestions: v, submissions: { ...s.submissions, [e.userMessageId]: y }, submissionOrder: [...s.submissionOrder, e.userMessageId] };
508
508
  break;
509
509
  }
510
510
  case "conversation.submission_accepted": {
@@ -521,14 +521,14 @@ function Fn(s, e, t, i) {
521
521
  }
522
522
  case "conversation.stop": {
523
523
  if (t.clients[e.clientScopeId] !== e.conversationScopeId) return { state: s, effects: r };
524
- const a = t.selections[e.conversationScopeId].sessionId, c = a ? s.sessions[a]?.execution : null, u = Object.values(s.submissions).filter((f) => (a ? f.sessionId === a : f.conversationScopeId === e.conversationScopeId) && (!e.userMessageIds || e.userMessageIds.includes(f.userMessageId))), l = u.filter((f) => !f.cancelled && (f.delivery !== "failed" || s.deliveries[f.userMessageId]?.phase === "paused") && (f.delivery !== "accepted" || f.executionVersion === null)), d = l.length > 0, h = c && ["queued", "thinking", "steering", "stopping"].includes(c.phase) && (!e.userMessageIds || ee(c).some((f) => e.userMessageIds.includes(f)));
524
+ const a = t.selections[e.conversationScopeId].sessionId, c = a ? s.sessions[a]?.execution : null, u = Object.values(s.submissions).filter((p) => (a ? p.sessionId === a : p.conversationScopeId === e.conversationScopeId) && (!e.userMessageIds || e.userMessageIds.includes(p.userMessageId))), l = u.filter((p) => !p.cancelled && (p.delivery !== "failed" || s.deliveries[p.userMessageId]?.phase === "paused") && (p.delivery !== "accepted" || p.executionVersion === null)), d = l.length > 0, h = c && ["queued", "thinking", "steering", "stopping"].includes(c.phase) && (!e.userMessageIds || ee(c).some((p) => e.userMessageIds.includes(p)));
525
525
  if (!d && !h && (c || !e.userMessageIds?.length)) return { state: s, effects: r };
526
- const m = Array.from(new Set(e.userMessageIds ?? [...l.map((f) => f.userMessageId), ...h ? ee(c) : []])), p = { ...s.submissions };
527
- for (const f of u)
528
- m.includes(f.userMessageId) && f.delivery !== "accepted" && (p[f.userMessageId] = { ...f, cancelled: !0 });
529
- n = { ...s, submissions: p, stops: { ...s.stops, [e.conversationScopeId]: {
526
+ const f = Array.from(new Set(e.userMessageIds ?? [...l.map((p) => p.userMessageId), ...h ? ee(c) : []])), m = { ...s.submissions };
527
+ for (const p of u)
528
+ f.includes(p.userMessageId) && p.delivery !== "accepted" && (m[p.userMessageId] = { ...p, cancelled: !0 });
529
+ n = { ...s, submissions: m, stops: { ...s.stops, [e.conversationScopeId]: {
530
530
  requestId: e.requestId,
531
- userMessageIds: m,
531
+ userMessageIds: f,
532
532
  executionVersion: c?.version ?? -1,
533
533
  reason: e.reason ?? "user_requested"
534
534
  } } };
@@ -573,7 +573,7 @@ function Fn(s, e, t, i) {
573
573
  before: e.lane === "history" ? c.cursor : null,
574
574
  refreshItemIds: $n(a),
575
575
  retryPreparation: c.error?.code === "history_preparation_failed"
576
- }, l = Object.values(s.submissions).filter((m) => m.sessionId === e.sessionId && m.delivery === "accepted" && m.executionVersion === null).map((m) => m.userMessageId), d = s.requestSequence + 1, h = `conversation:${s.generation}:${d}`;
576
+ }, l = Object.values(s.submissions).filter((f) => f.sessionId === e.sessionId && f.delivery === "accepted" && f.executionVersion === null).map((f) => f.userMessageId), d = s.requestSequence + 1, h = `conversation:${s.generation}:${d}`;
577
577
  n = {
578
578
  ...s,
579
579
  requestSequence: d,
@@ -600,15 +600,15 @@ function qi(s, e) {
600
600
  if (d.cancelled && t.has(d.conversationScopeId) && s.stops[d.conversationScopeId]?.userMessageIds.includes(l) && !h?.items[l] && !h?.removedItems[l]) return !0;
601
601
  if (d.delivery === "accepted") {
602
602
  if (d.cancelled) return !n(l);
603
- const m = d.sessionId ? s.sessions[d.sessionId] : void 0;
604
- return d.executionVersion === null || !(m?.items[l] || m?.removedItems[l]);
603
+ const f = d.sessionId ? s.sessions[d.sessionId] : void 0;
604
+ return d.executionVersion === null || !(f?.items[l] || f?.removedItems[l]);
605
605
  }
606
606
  return !d.cancelled || he(s, l) || s.deliveries[l]?.phase === "running";
607
607
  }).map(([l, d]) => [l, d.delivery === "accepted" || d.cancelled ? { ...d, context: {}, contextPreparation: { pageContent: "", sessionTabs: [] } } : d])), o = Object.fromEntries(Object.entries(s.deliveries).filter(([l]) => l in r).map(([l, d]) => [l, r[l].delivery === "accepted" ? { ...d, phase: "done", effectId: null, command: null, uploads: [], completedUploads: 0 } : r[l].cancelled ? { ...d, command: null } : d])), a = Object.fromEntries(Object.entries(s.stops).filter(([l, d]) => d.userMessageIds.some((h) => {
608
608
  if (r[h]) return !0;
609
- if (!n(h)) return i.some((p) => p.command.payload.expectedUserMessageId === h && p.phase !== "done");
610
- const m = Object.values(s.sessions).find((p) => p.executionByUserMessage[h])?.executionByUserMessage[h];
611
- return t.has(l) && (!m || m.version <= d.executionVersion || !["completed", "failed", "stopped"].includes(m.phase));
609
+ if (!n(h)) return i.some((m) => m.command.payload.expectedUserMessageId === h && m.phase !== "done");
610
+ const f = Object.values(s.sessions).find((m) => m.executionByUserMessage[h])?.executionByUserMessage[h];
611
+ return t.has(l) && (!f || f.version <= d.executionVersion || !["completed", "failed", "stopped"].includes(f.phase));
612
612
  }))), c = new Set(Object.values(a).flatMap((l) => l.userMessageIds)), u = Object.fromEntries(Object.entries(s.operations).filter(([, l]) => {
613
613
  if (!["done", "failed"].includes(l.phase)) return !0;
614
614
  if (l.command.type === "run.stop") return c.has(String(l.command.payload.expectedUserMessageId)) || Object.values(r).some((h) => h.cancelled && h.userMessageId === l.command.payload.expectedUserMessageId);
@@ -616,7 +616,7 @@ function qi(s, e) {
616
616
  if (l.command.type === "runtime.warmup") return e.selections[l.conversationScopeId]?.sessionId !== l.result?.sessionId;
617
617
  if (l.command.type !== "attachment.prepare") return !1;
618
618
  const d = l.command.payload.source;
619
- return !Object.values(s.submissions).some((h) => h.conversationScopeId === l.conversationScopeId && h.delivery === "accepted" && h.attachments.some((m) => m.sourceId === d.sourceId));
619
+ return !Object.values(s.submissions).some((h) => h.conversationScopeId === l.conversationScopeId && h.delivery === "accepted" && h.attachments.some((f) => f.sourceId === d.sourceId));
620
620
  }));
621
621
  return X({
622
622
  schema: 1,
@@ -672,15 +672,15 @@ function Xt(s) {
672
672
  c = { ...c, uploads: [...c.uploads, h.uploaded] };
673
673
  continue;
674
674
  }
675
- const m = Object.values(e.operations).find((p) => p.command.type === "attachment.prepare" && p.conversationScopeId === a.conversationScopeId && p.phase === "done" && p.command.payload.source.sourceId === h.sourceId && p.result?.sessionId === a.sessionId);
676
- if (!m) break;
677
- c = { ...c, uploads: [...c.uploads, m.result.attachment] };
675
+ const f = Object.values(e.operations).find((m) => m.command.type === "attachment.prepare" && m.conversationScopeId === a.conversationScopeId && m.phase === "done" && m.command.payload.source.sourceId === h.sourceId && m.result?.sessionId === a.sessionId);
676
+ if (!f) break;
677
+ c = { ...c, uploads: [...c.uploads, f.result.attachment] };
678
678
  }
679
679
  for (; c.completedUploads < c.uploads.length && a.attachments[c.completedUploads].uploaded; )
680
680
  c = { ...c, completedUploads: c.completedUploads + 1 };
681
681
  if (!a.cancelled && c.uploads.length === a.attachments.length && c.completedUploads === c.uploads.length && s.submissionOrder.slice(0, s.submissionOrder.indexOf(o)).some((h) => {
682
- const m = e.submissions[h];
683
- return (m.conversationScopeId === a.conversationScopeId || a.sessionId !== null && m.sessionId === a.sessionId) && m.delivery !== "accepted" && (m.delivery !== "failed" || e.deliveries[h]?.phase === "paused") && (!m.cancelled || he(e, h));
682
+ const f = e.submissions[h];
683
+ return (f.conversationScopeId === a.conversationScopeId || a.sessionId !== null && f.sessionId === a.sessionId) && f.delivery !== "accepted" && (f.delivery !== "failed" || e.deliveries[h]?.phase === "paused") && (!f.cancelled || he(e, h));
684
684
  })) continue;
685
685
  const u = n();
686
686
  let l, d = c.command;
@@ -754,49 +754,49 @@ function Wn(s, e, t, i) {
754
754
  e.effectKind === "conversation.checkpoint" && e.effectId === s.checkpointEffectId && (n = { ...n, checkpointEffectId: null, checkpointError: e.type === "effect.failed" ? e.error : null });
755
755
  const l = Object.keys(s.deliveries).find((h) => s.deliveries[h].effectId === e.effectId), d = Object.keys(s.operations).find((h) => s.operations[h].effectId === e.effectId);
756
756
  if (l) {
757
- const h = s.deliveries[l], m = s.submissions[l];
758
- let p = { ...h, phase: "waiting", effectId: null };
757
+ const h = s.deliveries[l], f = s.submissions[l];
758
+ let m = { ...h, phase: "waiting", effectId: null };
759
759
  if (e.type === "effect.failed") {
760
- const f = e.error.retryable ? "uncertain" : "failed";
761
- p = { ...p, phase: f }, !m.cancelled && m.delivery !== "accepted" && (n = { ...n, submissions: {
760
+ const p = e.error.retryable ? "uncertain" : "failed";
761
+ m = { ...m, phase: p }, !f.cancelled && f.delivery !== "accepted" && (n = { ...n, submissions: {
762
762
  ...n.submissions,
763
- [l]: { ...m, delivery: f, error: e.error }
763
+ [l]: { ...f, delivery: p, error: e.error }
764
764
  } });
765
765
  } else if (e.effectKind === "conversation.upload") {
766
- const f = Q(e.output), y = m.attachments[h.uploads.length];
767
- if (f.attachment.id !== y.sourceId || f.attachment.size_bytes !== y.sizeBytes || m.sessionId !== null && m.sessionId !== f.sessionId)
766
+ const p = Q(e.output), y = f.attachments[h.uploads.length];
767
+ if (p.attachment.id !== y.sourceId || p.attachment.size_bytes !== y.sizeBytes || f.sessionId !== null && f.sessionId !== p.sessionId)
768
768
  throw new Error("Upload does not match the captured attachment or conversation.");
769
- p = { ...p, uploads: [...h.uploads, f.attachment] };
770
- const b = Object.fromEntries(Object.entries(n.submissions).map(([A, _]) => [
769
+ m = { ...m, uploads: [...h.uploads, p.attachment] };
770
+ const v = Object.fromEntries(Object.entries(n.submissions).map(([A, S]) => [
771
771
  A,
772
- _.conversationScopeId === m.conversationScopeId && (A === l || !_.cancelled && !m.cancelled) ? { ..._, sessionId: f.sessionId } : _
772
+ S.conversationScopeId === f.conversationScopeId && (A === l || !S.cancelled && !f.cancelled) ? { ...S, sessionId: p.sessionId } : S
773
773
  ]));
774
- n = { ...n, submissions: b };
774
+ n = { ...n, submissions: v };
775
775
  } else if (e.effectKind === "conversation.receipt")
776
- if (e.output === null) p = { ...p, phase: "uncertain" };
776
+ if (e.output === null) m = { ...m, phase: "uncertain" };
777
777
  else {
778
- const f = js(e.output, l);
779
- p = { ...p, phase: "done" }, r = {
778
+ const p = js(e.output, l);
779
+ m = { ...m, phase: "done" }, r = {
780
780
  type: "conversation.submission_accepted",
781
781
  authorityId: s.authorityId,
782
782
  generation: s.generation,
783
783
  userMessageId: l,
784
- sessionId: f.sessionId
784
+ sessionId: p.sessionId
785
785
  };
786
786
  }
787
787
  else if (e.effectKind === "conversation.command" && h.step === "complete")
788
- p = { ...p, completedUploads: h.completedUploads + 1, command: null };
788
+ m = { ...m, completedUploads: h.completedUploads + 1, command: null };
789
789
  else if (e.effectKind === "conversation.command" && h.step === "send") {
790
- const f = js(e.output, l);
791
- p = { ...p, phase: "done" }, r = {
790
+ const p = js(e.output, l);
791
+ m = { ...m, phase: "done" }, r = {
792
792
  type: "conversation.submission_accepted",
793
793
  authorityId: s.authorityId,
794
794
  generation: s.generation,
795
795
  userMessageId: l,
796
- sessionId: f.sessionId
796
+ sessionId: p.sessionId
797
797
  };
798
798
  }
799
- n = { ...n, deliveries: { ...n.deliveries, [l]: p } };
799
+ n = { ...n, deliveries: { ...n.deliveries, [l]: m } };
800
800
  } else if (d) {
801
801
  const h = s.operations[d];
802
802
  if (n = { ...n, operations: { ...n.operations, [d]: {
@@ -806,14 +806,14 @@ function Wn(s, e, t, i) {
806
806
  error: e.type === "effect.failed" ? e.error : null,
807
807
  result: e.type === "effect.completed" ? Q(e.output) : null
808
808
  } } }, e.type === "effect.completed" && ["runtime.warmup", "attachment.prepare"].includes(h.command.type) && !h.command.payload.sessionId && h.conversationScopeId && !Object.values(t.clients).includes(h.conversationScopeId)) {
809
- const m = e.output;
810
- m?.sessionId && (n = { ...n, operations: {
809
+ const f = e.output;
810
+ f?.sessionId && (n = { ...n, operations: {
811
811
  ...n.operations,
812
812
  [`cleanup:${d}`]: Jt({
813
813
  request_id: `cleanup:${h.command.request_id}`,
814
814
  type: "session.reset",
815
815
  payload: {
816
- sessionId: m.sessionId,
816
+ sessionId: f.sessionId,
817
817
  ...h.command.payload.warmupId ? { warmupId: h.command.payload.warmupId } : {},
818
818
  ...h.command.payload.page ? { page: h.command.payload.page } : {}
819
819
  }
@@ -826,28 +826,28 @@ function Wn(s, e, t, i) {
826
826
  const l = Q(e.checkpoint);
827
827
  if (l.schema !== 1 || l.authorityId !== s.authorityId || s.submissionOrder.length || Object.keys(s.operations).length)
828
828
  throw new Error("Delivery restoration requires an empty engine with the same authenticated authority.");
829
- const { schema: d, authorityId: h, ...m } = l;
829
+ const { schema: d, authorityId: h, ...f } = l;
830
830
  n = {
831
831
  ...s,
832
- ...m,
832
+ ...f,
833
833
  requestSequence: Math.max(s.requestSequence, l.requestSequence),
834
834
  effectsEnabled: !0,
835
- submissions: Object.fromEntries(Object.entries(l.submissions).map(([p, f]) => [p, {
836
- ...f,
835
+ submissions: Object.fromEntries(Object.entries(l.submissions).map(([m, p]) => [m, {
836
+ ...p,
837
837
  executionVersion: null,
838
- cancelled: f.cancelled || !Ci(f, t),
839
- delivery: f.contextPreparation === null && !f.cancelled ? "failed" : f.delivery === "sending" ? "uncertain" : f.delivery,
840
- error: f.contextPreparation === null && !f.cancelled ? { code: "context_preparation_interrupted", message: "Page context preparation was interrupted. Please send this message again.", retryable: !1 } : f.error
838
+ cancelled: p.cancelled || !Ci(p, t),
839
+ delivery: p.contextPreparation === null && !p.cancelled ? "failed" : p.delivery === "sending" ? "uncertain" : p.delivery,
840
+ error: p.contextPreparation === null && !p.cancelled ? { code: "context_preparation_interrupted", message: "Page context preparation was interrupted. Please send this message again.", retryable: !1 } : p.error
841
841
  }])),
842
- deliveries: Object.fromEntries(Object.entries(l.deliveries).map(([p, f]) => [p, {
843
- ...f,
842
+ deliveries: Object.fromEntries(Object.entries(l.deliveries).map(([m, p]) => [m, {
843
+ ...p,
844
844
  effectId: null,
845
- phase: ["running", "waiting"].includes(f.phase) ? "uncertain" : f.phase
845
+ phase: ["running", "waiting"].includes(p.phase) ? "uncertain" : p.phase
846
846
  }])),
847
- operations: Object.fromEntries(Object.entries(l.operations).map(([p, f]) => [p, {
848
- ...f,
847
+ operations: Object.fromEntries(Object.entries(l.operations).map(([m, p]) => [m, {
848
+ ...p,
849
849
  effectId: null,
850
- phase: ["running", "waiting"].includes(f.phase) ? "uncertain" : f.phase
850
+ phase: ["running", "waiting"].includes(p.phase) ? "uncertain" : p.phase
851
851
  }]))
852
852
  };
853
853
  }
@@ -898,10 +898,10 @@ function Wn(s, e, t, i) {
898
898
  const d = s.operations[l.request_id];
899
899
  if (d && (JSON.stringify(d.command) !== JSON.stringify(l) || d.conversationScopeId !== (e.conversationScopeId ?? null))) throw new Error("Command identity changed.");
900
900
  if (!d) {
901
- const h = l.type === "chat.retry_last_user_message" ? Object.fromEntries(Object.entries(s.stops).flatMap(([m, p]) => {
902
- if (t.selections[m]?.sessionId !== l.payload.sessionId) return [[m, p]];
903
- const f = p.userMessageIds.filter((y) => y !== l.payload.clientMessageId);
904
- return f.length ? [[m, { ...p, userMessageIds: f }]] : [];
901
+ const h = l.type === "chat.retry_last_user_message" ? Object.fromEntries(Object.entries(s.stops).flatMap(([f, m]) => {
902
+ if (t.selections[f]?.sessionId !== l.payload.sessionId) return [[f, m]];
903
+ const p = m.userMessageIds.filter((y) => y !== l.payload.clientMessageId);
904
+ return p.length ? [[f, { ...m, userMessageIds: p }]] : [];
905
905
  })) : s.stops;
906
906
  n = { ...s, stops: h, effectsEnabled: !0, operations: {
907
907
  ...s.operations,
@@ -1048,7 +1048,7 @@ function Vn(s) {
1048
1048
  "conversations",
1049
1049
  { timing: c }
1050
1050
  ));
1051
- if (j(s, o), u.request_id !== o.command.request_id || !be(u.result)) throw new Error("Conversation response identity mismatch.");
1051
+ if (j(s, o), u.request_id !== o.command.request_id || !we(u.result)) throw new Error("Conversation response identity mismatch.");
1052
1052
  if (o.command.type.startsWith("chat.")) {
1053
1053
  const l = u.result;
1054
1054
  if (typeof l?.sessionId != "string" || !l.sessionId || l.clientMessageId !== o.command.payload.clientMessageId || o.command.payload.sessionId && l.sessionId !== o.command.payload.sessionId) throw new Error("Conversation acceptance identity mismatch.");
@@ -1067,8 +1067,8 @@ function Vn(s) {
1067
1067
  }).measure("attachment_upload", () => Promise.resolve().then(async () => {
1068
1068
  const a = () => {
1069
1069
  if (j(s, o), !o.preparationId) return r(o.submission.userMessageId);
1070
- const m = s.runtime().engine.getState().slices.directory;
1071
- if (!Object.values(m.clients).includes(o.submission.conversationScopeId))
1070
+ const f = s.runtime().engine.getState().slices.directory;
1071
+ if (!Object.values(f.clients).includes(o.submission.conversationScopeId))
1072
1072
  throw Object.assign(new Error("Attachment preparation was cancelled."), { code: "submission_cancelled", retryable: !1 });
1073
1073
  };
1074
1074
  a(), await t(), a();
@@ -1091,8 +1091,8 @@ function Vn(s) {
1091
1091
  if (a(), !l.sessionId || o.submission.sessionId && l.sessionId !== o.submission.sessionId || l.attachment.id !== o.source.sourceId || l.attachment.mimeType !== o.source.mimeType || l.attachment.sizeBytes !== o.source.sizeBytes)
1092
1092
  throw Object.assign(new Error("Attachment preparation identity mismatch."), { code: "attachment_identity_mismatch", retryable: !1 });
1093
1093
  if ("uploadUrl" in l) {
1094
- const m = await fetch(s.http.resolveUrl(l.uploadUrl), { method: l.uploadMethod, headers: l.uploadHeaders, body: c });
1095
- if (!m.ok) throw Object.assign(new Error("Attachment transfer failed."), { code: String(m.status) });
1094
+ const f = await fetch(s.http.resolveUrl(l.uploadUrl), { method: l.uploadMethod, headers: l.uploadHeaders, body: c });
1095
+ if (!f.ok) throw Object.assign(new Error("Attachment transfer failed."), { code: String(f.status) });
1096
1096
  }
1097
1097
  a();
1098
1098
  const d = l.attachment, h = {
@@ -1263,7 +1263,7 @@ class Kn {
1263
1263
  }
1264
1264
  }
1265
1265
  const Gn = /(\]\()(\/api\/product-agent\/attachments\/download\?[^)\s]+)(\))/g;
1266
- function ye(s, e) {
1266
+ function ve(s, e) {
1267
1267
  return e ? s.replace(
1268
1268
  Gn,
1269
1269
  (t, i, n, r) => `${i}${new URL(n, e).toString()}${r}`
@@ -1314,21 +1314,21 @@ function Qn(s, e, t, i) {
1314
1314
  };
1315
1315
  switch (s.type) {
1316
1316
  case "user_message":
1317
- return { ...r, role: "user", content: ye(s.data.content, i), attachments: s.data.attachments.map((o) => $s(o, i)) };
1317
+ return { ...r, role: "user", content: ve(s.data.content, i), attachments: s.data.attachments.map((o) => $s(o, i)) };
1318
1318
  case "final_response":
1319
1319
  return {
1320
1320
  ...r,
1321
1321
  role: "assistant",
1322
1322
  phase: "final_answer",
1323
- content: ye(s.data.content, i),
1323
+ content: ve(s.data.content, i),
1324
1324
  attachments: s.data.attachments.map((o) => $s(o, i)),
1325
1325
  loading: n,
1326
1326
  streamState: t
1327
1327
  };
1328
1328
  case "commentary":
1329
- return { ...r, role: "tool", phase: "commentary", dataType: "commentary_history", content: ye(s.data.content, i), loading: n };
1329
+ return { ...r, role: "tool", phase: "commentary", dataType: "commentary_history", content: ve(s.data.content, i), loading: n };
1330
1330
  case "tool_summary":
1331
- return { ...r, role: "tool", dataType: "tool_summary", content: ye(s.data.content, i), loading: n };
1331
+ return { ...r, role: "tool", dataType: "tool_summary", content: ve(s.data.content, i), loading: n };
1332
1332
  // The supported public renderer recognizes run_error; a bare error system row is silently omitted.
1333
1333
  case "error":
1334
1334
  return {
@@ -1345,28 +1345,28 @@ function Qn(s, e, t, i) {
1345
1345
  }
1346
1346
  function Jn(s, e, t, i) {
1347
1347
  const n = /* @__PURE__ */ new Map();
1348
- for (const v of s.segments)
1349
- for (const S of [...v.activityIds, ...v.outcomeIds]) n.set(S, v.userMessageId);
1350
- const r = s.items.map((v) => Qn(
1351
- v,
1352
- n.get(v.id) ?? null,
1353
- s.streamStates[v.id],
1348
+ for (const I of s.segments)
1349
+ for (const _ of [...I.activityIds, ...I.outcomeIds]) n.set(_, I.userMessageId);
1350
+ const r = s.items.map((I) => Qn(
1351
+ I,
1352
+ n.get(I.id) ?? null,
1353
+ s.streamStates[I.id],
1354
1354
  t
1355
1355
  ));
1356
- for (const v of s.optimistic) r.push({
1357
- id: v.userMessageId,
1356
+ for (const I of s.optimistic) r.push({
1357
+ id: I.userMessageId,
1358
1358
  role: "user",
1359
- content: v.content,
1359
+ content: I.content,
1360
1360
  // There is no canonical timestamp before acceptance. Keep identity stable without fabricating one.
1361
1361
  createdAt: "",
1362
- attachments: v.attachments.map((S) => ({
1363
- id: S.sourceId,
1364
- name: S.name,
1365
- mimeType: S.mimeType,
1366
- sizeBytes: S.sizeBytes
1362
+ attachments: I.attachments.map((_) => ({
1363
+ id: _.sourceId,
1364
+ name: _.name,
1365
+ mimeType: _.mimeType,
1366
+ sizeBytes: _.sizeBytes
1367
1367
  }))
1368
1368
  });
1369
- const o = s.segments.flatMap((v) => r.filter((S) => S.id === v.userMessageId || v.activityIds.includes(S.id) || v.outcomeIds.includes(S.id)));
1369
+ const o = s.segments.flatMap((I) => r.filter((_) => _.id === I.userMessageId || I.activityIds.includes(_.id) || I.outcomeIds.includes(_.id)));
1370
1370
  s.proactiveQuestion && o.push({
1371
1371
  id: s.proactiveQuestion.id,
1372
1372
  role: "assistant",
@@ -1375,19 +1375,19 @@ function Jn(s, e, t, i) {
1375
1375
  createdAt: "",
1376
1376
  loading: !1
1377
1377
  });
1378
- const a = s.activity.phase, c = s.submissions.filter((v) => !v.cancelled && !["accepted", "failed"].includes(v.delivery)), u = s.submissions[s.submissions.length - 1], l = [...s.items].reverse().find((v) => v.type === "user_message"), d = ["queued", "thinking", "steering", "awaiting_execution"].includes(a), h = u?.delivery === "failed" && (d && s.activity.userMessageId != null && s.activity.userMessageId !== u.userMessageId || l !== void 0 && l.id !== u.userMessageId && Date.parse(l.created_at) > u.submittedAt), m = new Map(s.submissions.filter((v) => (v !== u || h) && !v.cancelled && v.delivery === "failed" && v.error).map((v) => [v.userMessageId, v])), p = o.flatMap((v) => {
1379
- const S = v.role === "user" ? m.get(v.id) : void 0;
1380
- return S?.error ? [v, {
1381
- id: `submission-error:${S.userMessageId}`,
1378
+ const a = s.activity.phase, c = s.submissions.filter((I) => !I.cancelled && !["accepted", "failed"].includes(I.delivery)), u = s.submissions[s.submissions.length - 1], l = [...s.items].reverse().find((I) => I.type === "user_message"), d = ["queued", "thinking", "steering", "awaiting_execution"].includes(a), h = u?.delivery === "failed" && (d && s.activity.userMessageId != null && s.activity.userMessageId !== u.userMessageId || l !== void 0 && l.id !== u.userMessageId && Date.parse(l.created_at) > u.submittedAt), f = new Map(s.submissions.filter((I) => (I !== u || h) && !I.cancelled && I.delivery === "failed" && I.error).map((I) => [I.userMessageId, I])), m = o.flatMap((I) => {
1379
+ const _ = I.role === "user" ? f.get(I.id) : void 0;
1380
+ return _?.error ? [I, {
1381
+ id: `submission-error:${_.userMessageId}`,
1382
1382
  role: "system",
1383
1383
  dataType: "run_error",
1384
- respondsToUserMessageId: S.userMessageId,
1385
- content: S.error.message,
1384
+ respondsToUserMessageId: _.userMessageId,
1385
+ content: _.error.message,
1386
1386
  createdAt: "",
1387
1387
  loading: !1,
1388
- ...typeof S.error.details?.securitySettingsUrl == "string" ? { securitySettingsUrl: S.error.details.securitySettingsUrl } : {}
1389
- }] : [v];
1390
- }), f = u?.delivery === "failed" && !u.cancelled && !h ? u.error : e?.error ?? null, y = {
1388
+ ...typeof _.error.details?.securitySettingsUrl == "string" ? { securitySettingsUrl: _.error.details.securitySettingsUrl } : {}
1389
+ }] : [I];
1390
+ }), p = u?.delivery === "failed" && !u.cancelled && !h ? u.error : e?.error ?? null, y = {
1391
1391
  conversationDiagnostics: {
1392
1392
  ...i ? { owner: i } : {},
1393
1393
  queryStatus: e?.status ?? null,
@@ -1398,13 +1398,13 @@ function Jn(s, e, t, i) {
1398
1398
  selectionKey: s.selectionKey,
1399
1399
  isDraftSession: s.isDraftSession,
1400
1400
  sessionId: s.sessionId,
1401
- messages: p,
1401
+ messages: m,
1402
1402
  removedItems: s.removedItems,
1403
1403
  activeResponseUserMessageId: s.activity.userMessageId ?? s.segments[s.segments.length - 1]?.userMessageId ?? u?.userMessageId ?? null,
1404
1404
  segments: s.segments,
1405
1405
  activity: s.activity,
1406
1406
  receipts: s.receipts,
1407
- activeScheduledFollowUps: s.followUps.map((v) => ({ taskId: v.task_id, dueAt: v.due_at })),
1407
+ activeScheduledFollowUps: s.followUps.map((I) => ({ taskId: I.task_id, dueAt: I.due_at })),
1408
1408
  // A selected, not-yet-requested conversation must not paint the empty new-chat welcome state.
1409
1409
  isLoadingSession: !!s.preparation || !s.isDraftSession && s.sessionId !== null && (!e || e.status === "not_requested" || e.status === "loading" && e.data === null),
1410
1410
  // Streams are already canonical items. A second draft field would render the same text twice.
@@ -1413,22 +1413,22 @@ function Jn(s, e, t, i) {
1413
1413
  assistantDraftPhase: null,
1414
1414
  assistantDraftRespondsToUserMessageId: null,
1415
1415
  assistantDraftRunId: null,
1416
- pendingMessageStatus: c.length ? c.some((v) => v.delivery === "uncertain") ? "reconnecting" : "sending" : null,
1416
+ pendingMessageStatus: c.length ? c.some((I) => I.delivery === "uncertain") ? "reconnecting" : "sending" : null,
1417
1417
  turnPhase: a === "submitting" ? "sending" : ["queued", "awaiting_execution"].includes(a) ? "starting" : ["thinking", "steering"].includes(a) ? "thinking" : null,
1418
1418
  isThinking: d,
1419
1419
  taskStatus: a === "completed" ? "completed" : a === "failed" ? "failed" : a === "stopped" || a === "stopping" ? "stopped" : d || a === "submitting" ? "working" : null,
1420
- lastError: f?.message ?? null,
1421
- lastErrorCode: f?.code ?? null,
1422
- lastErrorSecuritySettingsUrl: typeof f?.details?.securitySettingsUrl == "string" ? f.details.securitySettingsUrl : null
1423
- }, b = s.optimistic.filter((v) => v.cancelled && !s.stop?.userMessageIds.includes(v.userMessageId)).map((v) => v.userMessageId), A = Yt(y, "", "stopped", b), _ = { ...y, messages: A.messages, segments: A.segments };
1424
- if (!s.stop) return _;
1425
- const I = Yt(_, "", s.stop.pending ? "stopping" : "stopped", s.stop.userMessageIds);
1426
- return { ...y, messages: I.messages, segments: I.segments };
1427
- }
1428
- function ve(s, e, t) {
1420
+ lastError: p?.message ?? null,
1421
+ lastErrorCode: p?.code ?? null,
1422
+ lastErrorSecuritySettingsUrl: typeof p?.details?.securitySettingsUrl == "string" ? p.details.securitySettingsUrl : null
1423
+ }, v = s.optimistic.filter((I) => I.cancelled && !s.stop?.userMessageIds.includes(I.userMessageId)).map((I) => I.userMessageId), A = Yt(y, "", "stopped", v), S = { ...y, messages: A.messages, segments: A.segments };
1424
+ if (!s.stop) return S;
1425
+ const w = Yt(S, "", s.stop.pending ? "stopping" : "stopped", s.stop.userMessageIds);
1426
+ return { ...y, messages: w.messages, segments: w.segments };
1427
+ }
1428
+ function Ie(s, e, t) {
1429
1429
  const i = s.submissionOrder.map((g) => s.submissions[g]).filter((g) => g.conversationScopeId === t), n = e.selections[t]?.sessionId ?? i.find((g) => !g.cancelled && g.sessionId !== null)?.sessionId ?? null, r = n ? s.sessions[n] : void 0, o = s.submissionOrder.map((g) => s.submissions[g]).filter((g) => n ? g.sessionId === n || g.sessionId === null && g.conversationScopeId === t : g.conversationScopeId === t), a = Object.values(r?.items ?? {}).sort((g, k) => {
1430
- const q = Z(g.created_at), P = Z(k.created_at);
1431
- return q < P ? -1 : q > P ? 1 : g.id < k.id ? -1 : g.id > k.id ? 1 : 0;
1430
+ const q = Z(g.created_at), x = Z(k.created_at);
1431
+ return q < x ? -1 : q > x ? 1 : g.id < k.id ? -1 : g.id > k.id ? 1 : 0;
1432
1432
  }), c = o.filter((g) => (!g.cancelled || g.conversationScopeId === t && (g.sessionId === null || g.sessionId === n || n === null && g === o[o.length - 1])) && !r?.items[g.userMessageId] && !r?.removedItems[g.userMessageId]), u = {};
1433
1433
  for (const g of a) {
1434
1434
  const k = at(g);
@@ -1442,13 +1442,13 @@ function ve(s, e, t) {
1442
1442
  l.push({ id: g.id, userMessageId: g.id, activityIds: [], outcomeIds: [], collapsed: !1 });
1443
1443
  else {
1444
1444
  l.length || l.push({ id: `leading:${g.id}`, userMessageId: null, activityIds: [], outcomeIds: [], collapsed: !1 });
1445
- const k = l.length - 1, q = l[k], P = g.type === "commentary" || g.type === "tool_summary" ? "activityIds" : "outcomeIds";
1446
- l[k] = { ...q, [P]: [...q[P], g.id] };
1445
+ const k = l.length - 1, q = l[k], x = g.type === "commentary" || g.type === "tool_summary" ? "activityIds" : "outcomeIds";
1446
+ l[k] = { ...q, [x]: [...q[x], g.id] };
1447
1447
  }
1448
1448
  for (const g of c) {
1449
1449
  const k = l.findIndex((q) => {
1450
- const P = o.find((Le) => Le.userMessageId === q.userMessageId), _e = r?.items[q.userMessageId ?? q.activityIds[0] ?? q.outcomeIds[0]];
1451
- return (P?.submittedAt ?? (_e ? Date.parse(_e.created_at) : 1 / 0)) > g.submittedAt;
1450
+ const x = o.find((Le) => Le.userMessageId === q.userMessageId), Ae = r?.items[q.userMessageId ?? q.activityIds[0] ?? q.outcomeIds[0]];
1451
+ return (x?.submittedAt ?? (Ae ? Date.parse(Ae.created_at) : 1 / 0)) > g.submittedAt;
1452
1452
  });
1453
1453
  l.splice(k < 0 ? l.length : k, 0, {
1454
1454
  id: g.userMessageId,
@@ -1458,14 +1458,14 @@ function ve(s, e, t) {
1458
1458
  collapsed: !1
1459
1459
  });
1460
1460
  }
1461
- const d = r?.execution, h = o.filter((g) => !g.cancelled && g.delivery !== "failed"), m = h.filter((g) => g.delivery !== "accepted" && g.executionVersion === null), p = h.filter((g) => g.delivery === "accepted" && g.executionVersion === null), f = h[h.length - 1], y = m.length > 0, b = f !== void 0 && p.includes(f);
1462
- let A = y ? "submitting" : b ? "awaiting_execution" : d?.phase ?? "idle";
1463
- const _ = Object.entries(s.stops).filter(([g]) => g === t || n !== null && e.selections[g]?.sessionId === n).map(([, g]) => g).find((g) => (!o.length || g.userMessageIds.includes(o[o.length - 1].userMessageId) || !y && !b && ee(d).some((k) => g.userMessageIds.includes(k))) && (!d || d.version <= g.executionVersion || ["thinking", "steering", "queued", "stopping"].includes(d.phase) || o.some((k) => k.cancelled && k.executionVersion === null && g.userMessageIds.includes(k.userMessageId)))), I = d && ["thinking", "steering", "queued", "stopping"].includes(d.phase) || o.some((g) => g.delivery === "accepted" && g.executionVersion === null && _?.userMessageIds.includes(g.userMessageId));
1464
- _ && I && !y && (!d || !["thinking", "steering", "queued", "stopping"].includes(d.phase) || ee(d).every((g) => _.userMessageIds.includes(g))) && (A = "stopping"), _ && !I && !y && o.some((g) => g.cancelled && g.executionVersion === null && _.userMessageIds.includes(g.userMessageId)) && (A = o.some((g) => _.userMessageIds.includes(g.userMessageId) && ["sending", "uncertain"].includes(g.delivery)) ? "stopping" : "stopped");
1465
- const v = ["thinking", "steering", "queued"].includes(A), S = s.stops[t] ?? _, C = S?.userMessageIds.filter((g) => !["completed", "failed"].includes(r?.executionByUserMessage[g]?.phase ?? "")) ?? [], Y = C.some((g) => {
1466
- const k = o.find((P) => P.userMessageId === g);
1467
- return !Object.values(s.operations).some((P) => P.command.type === "run.stop" && P.command.payload.expectedUserMessageId === g && P.phase === "done") && (k?.executionVersion === null && ["sending", "uncertain", "accepted"].includes(k.delivery) || !!(d && ee(d).includes(g) && ["thinking", "steering", "queued", "stopping"].includes(d.phase)));
1468
- }), T = d?.user_message_ids ?? [], ae = y || b ? f?.userMessageId ?? null : T[T.length - 1] ?? null, pe = l.find((g) => g.userMessageId === ae), Be = v ? [...pe?.activityIds ?? []].reverse().find((g) => u[g] === "open") ?? null : null, fe = n !== null && !!e.selections[t]?.provisionalId && a.length === 0 && o.length === 0 && // The first persisted idle snapshot already has a positive synchronization version.
1461
+ const d = r?.execution, h = o.filter((g) => !g.cancelled && g.delivery !== "failed"), f = h.filter((g) => g.delivery !== "accepted" && g.executionVersion === null), m = h.filter((g) => g.delivery === "accepted" && g.executionVersion === null), p = h[h.length - 1], y = f.length > 0, v = p !== void 0 && m.includes(p);
1462
+ let A = y ? "submitting" : v ? "awaiting_execution" : d?.phase ?? "idle";
1463
+ const S = Object.entries(s.stops).filter(([g]) => g === t || n !== null && e.selections[g]?.sessionId === n).map(([, g]) => g).find((g) => (!o.length || g.userMessageIds.includes(o[o.length - 1].userMessageId) || !y && !v && ee(d).some((k) => g.userMessageIds.includes(k))) && (!d || d.version <= g.executionVersion || ["thinking", "steering", "queued", "stopping"].includes(d.phase) || o.some((k) => k.cancelled && k.executionVersion === null && g.userMessageIds.includes(k.userMessageId)))), w = d && ["thinking", "steering", "queued", "stopping"].includes(d.phase) || o.some((g) => g.delivery === "accepted" && g.executionVersion === null && S?.userMessageIds.includes(g.userMessageId));
1464
+ S && w && !y && (!d || !["thinking", "steering", "queued", "stopping"].includes(d.phase) || ee(d).every((g) => S.userMessageIds.includes(g))) && (A = "stopping"), S && !w && !y && o.some((g) => g.cancelled && g.executionVersion === null && S.userMessageIds.includes(g.userMessageId)) && (A = o.some((g) => S.userMessageIds.includes(g.userMessageId) && ["sending", "uncertain"].includes(g.delivery)) ? "stopping" : "stopped");
1465
+ const I = ["thinking", "steering", "queued"].includes(A), _ = s.stops[t] ?? S, C = _?.userMessageIds.filter((g) => !["completed", "failed"].includes(r?.executionByUserMessage[g]?.phase ?? "")) ?? [], Y = C.some((g) => {
1466
+ const k = o.find((x) => x.userMessageId === g);
1467
+ return !Object.values(s.operations).some((x) => x.command.type === "run.stop" && x.command.payload.expectedUserMessageId === g && x.phase === "done") && (k?.executionVersion === null && ["sending", "uncertain", "accepted"].includes(k.delivery) || !!(d && ee(d).includes(g) && ["thinking", "steering", "queued", "stopping"].includes(d.phase)));
1468
+ }), T = d?.user_message_ids ?? [], ae = y || v ? p?.userMessageId ?? null : T[T.length - 1] ?? null, pe = l.find((g) => g.userMessageId === ae), Be = I ? [...pe?.activityIds ?? []].reverse().find((g) => u[g] === "open") ?? null : null, fe = n !== null && !!e.selections[t]?.provisionalId && a.length === 0 && o.length === 0 && // The first persisted idle snapshot already has a positive synchronization version.
1469
1469
  (!r?.execution || r.execution.phase === "idle" && r.execution.user_message_ids.length === 0) && Object.values(s.operations).some((g) => g.conversationScopeId === t && g.phase === "done" && ["runtime.warmup", "attachment.prepare"].includes(g.command.type) && !g.command.payload.sessionId && g.result?.sessionId === n);
1470
1470
  return X({
1471
1471
  selectionKey: t ? JSON.stringify([s.authorityId, s.generation, t]) : void 0,
@@ -1480,8 +1480,8 @@ function ve(s, e, t) {
1480
1480
  removedItems: r?.removedItems ?? {},
1481
1481
  streamStates: u,
1482
1482
  preparation: r?.preparation ?? null,
1483
- stop: S ? { ...S, userMessageIds: C, pending: Y } : null,
1484
- segments: l.map((g, k) => ({ ...g, collapsed: v ? g.userMessageId !== ae : k < l.length - 1 || g.activityIds.length > 0 })),
1483
+ stop: _ ? { ..._, userMessageIds: C, pending: Y } : null,
1484
+ segments: l.map((g, k) => ({ ...g, collapsed: I ? g.userMessageId !== ae : k < l.length - 1 || g.activityIds.length > 0 })),
1485
1485
  activity: { phase: A, activeItemId: Be, userMessageId: ae, executionKey: JSON.stringify([...ee(d)].sort()) },
1486
1486
  // Staging transfers the immutable input to the core. Waiting for backend acceptance leaves
1487
1487
  // the same submitted text in the optimistic transcript and composer during delivery.
@@ -1496,7 +1496,7 @@ function Xn(s, e) {
1496
1496
  return s.sessionId && i ? { type: "execution", userMessageId: i, sessionId: s.sessionId } : null;
1497
1497
  }
1498
1498
  function Yn(s, e) {
1499
- return X({ scopes: Object.fromEntries([...new Set(Object.values(e.clients))].map((t) => [t, ve(s, e, t)])) });
1499
+ return X({ scopes: Object.fromEntries([...new Set(Object.values(e.clients))].map((t) => [t, Ie(s, e, t)])) });
1500
1500
  }
1501
1501
  function Zn(s, e) {
1502
1502
  if (!e) return !1;
@@ -2138,7 +2138,7 @@ class Tr extends Ar {
2138
2138
  }), this.pollXhr = e;
2139
2139
  }
2140
2140
  }
2141
- let Ie = class et extends M {
2141
+ let be = class et extends M {
2142
2142
  /**
2143
2143
  * Request constructor
2144
2144
  *
@@ -2235,8 +2235,8 @@ let Ie = class et extends M {
2235
2235
  this._cleanup();
2236
2236
  }
2237
2237
  };
2238
- Ie.requestsCount = 0;
2239
- Ie.requests = {};
2238
+ be.requestsCount = 0;
2239
+ be.requests = {};
2240
2240
  if (typeof document < "u") {
2241
2241
  if (typeof attachEvent == "function")
2242
2242
  attachEvent("onunload", Vs);
@@ -2246,8 +2246,8 @@ if (typeof document < "u") {
2246
2246
  }
2247
2247
  }
2248
2248
  function Vs() {
2249
- for (let s in Ie.requests)
2250
- Ie.requests.hasOwnProperty(s) && Ie.requests[s].abort();
2249
+ for (let s in be.requests)
2250
+ be.requests.hasOwnProperty(s) && be.requests[s].abort();
2251
2251
  }
2252
2252
  const kr = (function() {
2253
2253
  const s = $i({
@@ -2262,7 +2262,7 @@ class Cr extends Tr {
2262
2262
  this.supportsBinary = kr && !t;
2263
2263
  }
2264
2264
  request(e = {}) {
2265
- return Object.assign(e, { xd: this.xd }, this.opts), new Ie($i, this.uri(), e);
2265
+ return Object.assign(e, { xd: this.xd }, this.opts), new be($i, this.uri(), e);
2266
2266
  }
2267
2267
  }
2268
2268
  function $i(s) {
@@ -3676,10 +3676,10 @@ class Hi extends M {
3676
3676
  }
3677
3677
  }
3678
3678
  }
3679
- function Se(s) {
3679
+ function _e(s) {
3680
3680
  s = s || {}, this.ms = s.min || 100, this.max = s.max || 1e4, this.factor = s.factor || 2, this.jitter = s.jitter > 0 && s.jitter <= 1 ? s.jitter : 0, this.attempts = 0;
3681
3681
  }
3682
- Se.prototype.duration = function() {
3682
+ _e.prototype.duration = function() {
3683
3683
  var s = this.ms * Math.pow(this.factor, this.attempts++);
3684
3684
  if (this.jitter) {
3685
3685
  var e = Math.random(), t = Math.floor(e * this.jitter * s);
@@ -3687,22 +3687,22 @@ Se.prototype.duration = function() {
3687
3687
  }
3688
3688
  return Math.min(s, this.max) | 0;
3689
3689
  };
3690
- Se.prototype.reset = function() {
3690
+ _e.prototype.reset = function() {
3691
3691
  this.attempts = 0;
3692
3692
  };
3693
- Se.prototype.setMin = function(s) {
3693
+ _e.prototype.setMin = function(s) {
3694
3694
  this.ms = s;
3695
3695
  };
3696
- Se.prototype.setMax = function(s) {
3696
+ _e.prototype.setMax = function(s) {
3697
3697
  this.max = s;
3698
3698
  };
3699
- Se.prototype.setJitter = function(s) {
3699
+ _e.prototype.setJitter = function(s) {
3700
3700
  this.jitter = s;
3701
3701
  };
3702
3702
  class is extends M {
3703
3703
  constructor(e, t) {
3704
3704
  var i;
3705
- super(), this.nsps = {}, this.subs = [], e && typeof e == "object" && (t = e, e = void 0), t = t || {}, t.path = t.path || "/socket.io", this.opts = t, pt(this, t), this.reconnection(t.reconnection !== !1), this.reconnectionAttempts(t.reconnectionAttempts || 1 / 0), this.reconnectionDelay(t.reconnectionDelay || 1e3), this.reconnectionDelayMax(t.reconnectionDelayMax || 5e3), this.randomizationFactor((i = t.randomizationFactor) !== null && i !== void 0 ? i : 0.5), this.backoff = new Se({
3705
+ super(), this.nsps = {}, this.subs = [], e && typeof e == "object" && (t = e, e = void 0), t = t || {}, t.path = t.path || "/socket.io", this.opts = t, pt(this, t), this.reconnection(t.reconnection !== !1), this.reconnectionAttempts(t.reconnectionAttempts || 1 / 0), this.reconnectionDelay(t.reconnectionDelay || 1e3), this.reconnectionDelayMax(t.reconnectionDelayMax || 5e3), this.randomizationFactor((i = t.randomizationFactor) !== null && i !== void 0 ? i : 0.5), this.backoff = new _e({
3706
3706
  min: this.reconnectionDelay(),
3707
3707
  max: this.reconnectionDelayMax(),
3708
3708
  jitter: this.randomizationFactor()
@@ -3937,12 +3937,12 @@ class is extends M {
3937
3937
  this._reconnecting = !1, this.backoff.reset(), this.emitReserved("reconnect", e);
3938
3938
  }
3939
3939
  }
3940
- const Ee = {};
3940
+ const Re = {};
3941
3941
  function nt(s, e) {
3942
3942
  typeof s == "object" && (e = s, s = void 0), e = e || {};
3943
- const t = jr(s, e.path || "/socket.io"), i = t.source, n = t.id, r = t.path, o = Ee[n] && r in Ee[n].nsps, a = e.forceNew || e["force new connection"] || e.multiplex === !1 || o;
3943
+ const t = jr(s, e.path || "/socket.io"), i = t.source, n = t.id, r = t.path, o = Re[n] && r in Re[n].nsps, a = e.forceNew || e["force new connection"] || e.multiplex === !1 || o;
3944
3944
  let c;
3945
- return a ? c = new is(i, e) : (Ee[n] || (Ee[n] = new is(i, e)), c = Ee[n]), t.query && !e.query && (e.query = t.queryKey), c.socket(t.path, e);
3945
+ return a ? c = new is(i, e) : (Re[n] || (Re[n] = new is(i, e)), c = Re[n]), t.query && !e.query && (e.query = t.queryKey), c.socket(t.path, e);
3946
3946
  }
3947
3947
  Object.assign(nt, {
3948
3948
  Manager: is,
@@ -3962,7 +3962,7 @@ const Zr = 45e3, eo = /* @__PURE__ */ new Set([
3962
3962
  "tool.started",
3963
3963
  "tool.result"
3964
3964
  ]);
3965
- class w extends Error {
3965
+ class b extends Error {
3966
3966
  constructor(e, t, i = !1, n, r = !1) {
3967
3967
  super(e), this.code = t, this.outcomeUnknown = i, this.detail = n, this.backendRefusal = r, this.code = t === "401" ? "unauthorized" : t;
3968
3968
  }
@@ -3973,7 +3973,7 @@ class w extends Error {
3973
3973
  }
3974
3974
  function Gs(s, e) {
3975
3975
  const t = s.result && typeof s.result == "object" ? s.result : void 0, i = typeof t?.message == "string" && t.message.trim() ? t.message : `${e} (${s.code ?? "request_rejected"})`;
3976
- return new w(i, s.code ?? "request_rejected", !1, s.result, !0);
3976
+ return new b(i, s.code ?? "request_rejected", !1, s.result, !0);
3977
3977
  }
3978
3978
  class to {
3979
3979
  constructor(e) {
@@ -3992,7 +3992,7 @@ class to {
3992
3992
  this.invalidate(!1), this.restoreBackoff();
3993
3993
  }), this.socket.io.on("reconnect", () => this.restoreBackoff()), this.socket.on("connection.ready", (t) => {
3994
3994
  if (t.protocol !== 1 || t.role !== this.options.auth.role || t.display_projection_ready !== !1) {
3995
- this.options.onError(new w("Unsupported Product Agent transport negotiation", "protocol_error")), this.disconnect();
3995
+ this.options.onError(new b("Unsupported Product Agent transport negotiation", "protocol_error")), this.disconnect();
3996
3996
  return;
3997
3997
  }
3998
3998
  this.admitted = t, this.activate();
@@ -4003,7 +4003,7 @@ class to {
4003
4003
  )), this.socket.on("connect_error", (t) => {
4004
4004
  const i = t.data?.code;
4005
4005
  if (i === "unauthorized" && t.data?.reason === "token_expired" && t.data.retryable === !0) {
4006
- this.options.onError(new w(t.message, i, !1, t.data)), this.disconnect();
4006
+ this.options.onError(new b(t.message, i, !1, t.data)), this.disconnect();
4007
4007
  return;
4008
4008
  }
4009
4009
  if (!i || t.data?.retryable === !0) {
@@ -4015,7 +4015,7 @@ class to {
4015
4015
  }
4016
4016
  return;
4017
4017
  }
4018
- (i === "unauthorized" || i === "update_required") && (this.rejectedToken = this.options.auth.token), this.options.onError(new w(t.message, i ?? "connection_error", !1, t.data)), this.rejectedToken === this.options.auth.token && this.disconnect();
4018
+ (i === "unauthorized" || i === "update_required") && (this.rejectedToken = this.options.auth.token), this.options.onError(new b(t.message, i ?? "connection_error", !1, t.data)), this.rejectedToken === this.options.auth.token && this.disconnect();
4019
4019
  }), this.socket.on("conversation.event", (t) => {
4020
4020
  this.ready && t.protocol === 1 && t.session_id && this.bindings.get(t.session_id)?.owners.size && this.options.onEvent("conversation.event", t.event);
4021
4021
  }), this.socket.on("conversation.metadata.updated", (t) => {
@@ -4042,7 +4042,7 @@ class to {
4042
4042
  const n = this.generation, r = await this.options.onToolCall(t);
4043
4043
  i({ received: r && !!this.ready && n === this.generation });
4044
4044
  }), this.socket.on("executor.replaced", () => {
4045
- this.retired = !0, this.options.onError(new w("Browser executor was replaced", "executor_replaced")), this.disconnect();
4045
+ this.retired = !0, this.options.onError(new b("Browser executor was replaced", "executor_replaced")), this.disconnect();
4046
4046
  });
4047
4047
  }
4048
4048
  options;
@@ -4076,11 +4076,11 @@ class to {
4076
4076
  return this.ready && this.socket.id ? `pa-sio:${this.socket.id}` : null;
4077
4077
  }
4078
4078
  async restoreExecutor(e) {
4079
- if (this.connectionId !== e) throw new w("Browser connection changed.", "executor_not_ready");
4079
+ if (this.connectionId !== e) throw new b("Browser connection changed.", "executor_not_ready");
4080
4080
  if (this.executorRecovery) return this.executorRecovery;
4081
4081
  const t = this.request("executor.register", {}, this.generation).then(() => {
4082
4082
  }, (i) => {
4083
- throw i instanceof w && (i.outcomeUnknown || i.code === "disconnected") ? new w("Reconnecting the browser before continuing.", "executor_not_ready") : i;
4083
+ throw i instanceof b && (i.outcomeUnknown || i.code === "disconnected") ? new b("Reconnecting the browser before continuing.", "executor_not_ready") : i;
4084
4084
  });
4085
4085
  this.executorRecovery = t;
4086
4086
  try {
@@ -4117,7 +4117,7 @@ class to {
4117
4117
  beginAttempt() {
4118
4118
  this.clearReadinessTimers(), this.active = !0, this.attempt = { connectionAttemptId: crypto.randomUUID(), reconnectAttempt: this.attemptCount++, startedAt: Date.now() }, this.socket.auth = { ...this.options.auth, connection_attempt_id: this.attempt.connectionAttemptId }, this.options.onAttempt?.(this.attempt);
4119
4119
  const e = this.generation, t = (i) => {
4120
- e !== this.generation || !this.active || (this.options.onError(new w("Product Agent readiness timed out", i, !1, {
4120
+ e !== this.generation || !this.active || (this.options.onError(new b("Product Agent readiness timed out", i, !1, {
4121
4121
  retryable: !0,
4122
4122
  ...this.attempt,
4123
4123
  readinessPhase: this.ready ? "bootstrap" : this.admitted ? "activation" : "namespace_ready"
@@ -4131,20 +4131,20 @@ class to {
4131
4131
  async retain(e, t) {
4132
4132
  let i = this.bindings.get(e);
4133
4133
  if (!i) {
4134
- if (this.bindings.size >= 64) throw new w("Too many conversation subscriptions", "subscription_limit");
4134
+ if (this.bindings.size >= 64) throw new b("Too many conversation subscriptions", "subscription_limit");
4135
4135
  i = { id: crypto.randomUUID(), owners: /* @__PURE__ */ new Set(), joinedGeneration: -1 }, this.bindings.set(e, i);
4136
4136
  }
4137
4137
  if (i.owners.add(t), !this.ready) return;
4138
4138
  const n = this.generation;
4139
4139
  await this.synchronize().catch((r) => {
4140
- throw n !== this.generation || (i.owners.delete(t), r instanceof w && r.outcomeUnknown && this.ready && (i.joinedGeneration = this.generation), this.synchronize().catch((o) => this.options.onError(o))), r;
4140
+ throw n !== this.generation || (i.owners.delete(t), r instanceof b && r.outcomeUnknown && this.ready && (i.joinedGeneration = this.generation), this.synchronize().catch((o) => this.options.onError(o))), r;
4141
4141
  });
4142
4142
  }
4143
4143
  async release(e, t) {
4144
4144
  this.bindings.get(e)?.owners.delete(t), this.ready && await this.synchronize();
4145
4145
  }
4146
4146
  async rpc(e, t) {
4147
- if (!eo.has(e)) throw new w("Operation requires its HTTP adapter", "unsupported_rpc");
4147
+ if (!eo.has(e)) throw new b("Operation requires its HTTP adapter", "unsupported_rpc");
4148
4148
  const i = this.generation, n = JSON.stringify(t);
4149
4149
  return e === "run.stop" && this.uploadingResult ? (this.assertReady(i), this.request("runtime.rpc", { type: e, payload: JSON.parse(n) }, i)) : this.enqueue(async () => {
4150
4150
  if (this.assertReady(i), e === "tool.result") {
@@ -4162,7 +4162,7 @@ class to {
4162
4162
  if (this.options.auth.role !== "session_surface" && await this.request("executor.register", {}, e), e !== this.generation || !this.socket.connected) return;
4163
4163
  this.ready = t, await this.synchronize(!0), e === this.generation && this.ready && (this.options.bootstrapRequired || this.markReady(), this.options.onReady(t));
4164
4164
  } catch (i) {
4165
- e === this.generation && this.activationFailed(i instanceof w ? i : new w(String(i), "activation_error"));
4165
+ e === this.generation && this.activationFailed(i instanceof b ? i : new b(String(i), "activation_error"));
4166
4166
  } finally {
4167
4167
  e === this.generation && (this.activating = !1);
4168
4168
  }
@@ -4182,7 +4182,7 @@ class to {
4182
4182
  subscription_id: n.id,
4183
4183
  ...this.options.displaySchema === "canonical" ? { display_schema: "canonical" } : {}
4184
4184
  }, t).then(() => !0).catch((o) => {
4185
- if (o instanceof w && !o.outcomeUnknown && o.detail?.retryable !== !0 && this.bindings.get(i) === n && (this.bindings.delete(i), e))
4185
+ if (o instanceof b && !o.outcomeUnknown && o.detail?.retryable !== !0 && this.bindings.get(i) === n && (this.bindings.delete(i), e))
4186
4186
  return this.options.onError(o), !1;
4187
4187
  throw o;
4188
4188
  })) continue;
@@ -4194,7 +4194,7 @@ class to {
4194
4194
  }
4195
4195
  enqueue(e) {
4196
4196
  if (this.queuedOperations >= 128) {
4197
- const i = new w("Product Agent transport queue is full", "backpressure");
4197
+ const i = new b("Product Agent transport queue is full", "backpressure");
4198
4198
  return this.recoverUncertainDelivery(i, this.generation), Promise.reject(i);
4199
4199
  }
4200
4200
  this.queuedOperations++;
@@ -4205,7 +4205,7 @@ class to {
4205
4205
  }), t;
4206
4206
  }
4207
4207
  assertReady(e) {
4208
- if (!this.ready || !this.socket.connected || e !== this.generation) throw new w("Transport is not ready", "disconnected");
4208
+ if (!this.ready || !this.socket.connected || e !== this.generation) throw new b("Transport is not ready", "disconnected");
4209
4209
  }
4210
4210
  async uploadResult(e, t, i) {
4211
4211
  const n = crypto.randomUUID();
@@ -4225,48 +4225,48 @@ class to {
4225
4225
  connection_id: `pa-sio:${this.socket.id}`,
4226
4226
  request_id: n,
4227
4227
  session_id: e.sessionId ?? e.session_id
4228
- }).replace(/[\u007f-\uffff]/g, (m) => `\\u${m.charCodeAt(0).toString(16).padStart(4, "0")}`)
4228
+ }).replace(/[\u007f-\uffff]/g, (f) => `\\u${f.charCodeAt(0).toString(16).padStart(4, "0")}`)
4229
4229
  },
4230
4230
  body: JSON.stringify({ request_id: n, type: "tool.result", payload: e })
4231
4231
  });
4232
4232
  if (d.status >= 500)
4233
- throw new w("Result upload outcome is unknown", "delivery_unknown", !0);
4234
- if (!d.ok) throw new w(`Result upload rejected (${d.status})`, String(d.status), !1, void 0, !0);
4233
+ throw new b("Result upload outcome is unknown", "delivery_unknown", !0);
4234
+ if (!d.ok) throw new b(`Result upload rejected (${d.status})`, String(d.status), !1, void 0, !0);
4235
4235
  const h = await d.json();
4236
4236
  if (t !== this.generation || r.signal.aborted)
4237
- throw new w("Result upload outcome is unknown", "delivery_unknown", !0);
4237
+ throw new b("Result upload outcome is unknown", "delivery_unknown", !0);
4238
4238
  if (h?.request_id !== n || typeof h.ok != "boolean")
4239
- throw new w("Invalid result acknowledgement identity", "invalid_ack", !0);
4239
+ throw new b("Invalid result acknowledgement identity", "invalid_ack", !0);
4240
4240
  if (!h.ok) throw Gs(h, "Product Agent result rejected");
4241
4241
  return h.result;
4242
4242
  } catch (u) {
4243
- const l = u instanceof w ? u : new w("Result upload outcome is unknown", "delivery_unknown", !0);
4243
+ const l = u instanceof b ? u : new b("Result upload outcome is unknown", "delivery_unknown", !0);
4244
4244
  throw this.recoverUncertainDelivery(l, t), l;
4245
4245
  } finally {
4246
4246
  clearTimeout(c), this.uploadingResult = !1, this.pending.delete(o);
4247
4247
  }
4248
4248
  }
4249
4249
  request(e, t, i) {
4250
- if (!this.socket.connected || i !== this.generation) return Promise.reject(new w("Transport disconnected", "disconnected"));
4250
+ if (!this.socket.connected || i !== this.generation) return Promise.reject(new b("Transport disconnected", "disconnected"));
4251
4251
  const n = crypto.randomUUID();
4252
4252
  return new Promise((r, o) => {
4253
4253
  const a = (c) => {
4254
4254
  this.pending.delete(a), o(c);
4255
4255
  };
4256
4256
  this.pending.add(a), this.socket.timeout(this.options.requestTimeoutMs ?? 15e3).emit(e, { ...t, request_id: n }, (c, u) => {
4257
- this.pending.delete(a) && (c || i !== this.generation ? o(new w("Delivery outcome is unknown; reconcile without repeating execution", "delivery_unknown", !0)) : u?.request_id !== n || typeof u.ok != "boolean" ? o(new w("Invalid acknowledgement identity", "invalid_ack", !0)) : u.ok ? r(u.result) : o(Gs(u, "Product Agent request rejected")));
4257
+ this.pending.delete(a) && (c || i !== this.generation ? o(new b("Delivery outcome is unknown; reconcile without repeating execution", "delivery_unknown", !0)) : u?.request_id !== n || typeof u.ok != "boolean" ? o(new b("Invalid acknowledgement identity", "invalid_ack", !0)) : u.ok ? r(u.result) : o(Gs(u, "Product Agent request rejected")));
4258
4258
  });
4259
4259
  }).catch((r) => {
4260
4260
  throw this.recoverUncertainDelivery(r, i), r;
4261
4261
  });
4262
4262
  }
4263
4263
  recoverUncertainDelivery(e, t) {
4264
- e instanceof w && (e.outcomeUnknown || e.code === "backpressure" && !e.backendRefusal) && t === this.generation && this.active && this.socket.io.engine.close();
4264
+ e instanceof b && (e.outcomeUnknown || e.code === "backpressure" && !e.backendRefusal) && t === this.generation && this.active && this.socket.io.engine.close();
4265
4265
  }
4266
4266
  invalidate(e = !1) {
4267
4267
  if (this.clearReadinessTimers(), !!this.active) {
4268
4268
  this.active = !1, this.generation++, this.ready = null, this.admitted = null, this.activating = !1;
4269
- for (const t of [...this.pending]) t(new w("Connection lost before acknowledgement", "delivery_unknown", !0));
4269
+ for (const t of [...this.pending]) t(new b("Connection lost before acknowledgement", "delivery_unknown", !0));
4270
4270
  this.options.onDisconnect(e);
4271
4271
  }
4272
4272
  }
@@ -4287,7 +4287,7 @@ class Wi {
4287
4287
  async request(e, t = {}, i, n, r, o = {}) {
4288
4288
  if (o.skipAuthentication) return this.requestOnce(e, t, i, n, r, o.signal);
4289
4289
  const a = this.options.authority?.(), c = () => {
4290
- if (a !== this.options.authority?.()) throw new w("Conversation authority was retired.", "authority_retired", !0);
4290
+ if (a !== this.options.authority?.()) throw new b("Conversation authority was retired.", "authority_retired", !0);
4291
4291
  this.requests.signal.throwIfAborted(), o.signal?.throwIfAborted();
4292
4292
  }, u = o.readOnly ?? (n ?? (i === void 0 ? "GET" : "POST")) === "GET";
4293
4293
  for (let l = 0; ; l++) {
@@ -4297,61 +4297,62 @@ class Wi {
4297
4297
  const d = this.options.authenticationFailure?.();
4298
4298
  if (d) throw d;
4299
4299
  const h = this.auth.token;
4300
- let m = null;
4300
+ let f = null;
4301
4301
  try {
4302
- let p = i;
4302
+ let m = i;
4303
4303
  if (r === "conversations" && e === "/commands" && this.auth.role !== "session_surface" && this.options.executorConnection) {
4304
- if (m = this.options.executorConnection(), !m) throw new w("Reconnecting the browser before continuing.", "executor_not_ready");
4304
+ if (f = this.options.executorConnection(), !f) throw new b("Reconnecting the browser before continuing.", "executor_not_ready");
4305
4305
  const y = i;
4306
- p = { ...y, context: { ...y.context, connection_id: m } };
4306
+ m = { ...y, context: { ...y.context, connection_id: f } };
4307
4307
  }
4308
- const f = await (o.timing ? o.timing.measure("http_request", () => this.requestOnce(e, t, p, n, r, o.signal)) : this.requestOnce(e, t, p, n, r, o.signal));
4309
- return c(), f;
4310
- } catch (p) {
4311
- if (c(), p instanceof w && p.code === "executor_not_ready" && m && l === 0 && this.options.restoreExecutor) {
4312
- await this.options.restoreExecutor(m), c();
4308
+ const p = await (o.timing ? o.timing.measure("http_request", () => this.requestOnce(e, t, m, n, r, o.signal)) : this.requestOnce(e, t, m, n, r, o.signal));
4309
+ return c(), p;
4310
+ } catch (m) {
4311
+ if (c(), m instanceof b && m.code === "executor_not_ready" && f && l === 0 && this.options.restoreExecutor) {
4312
+ await this.options.restoreExecutor(f), c();
4313
4313
  continue;
4314
4314
  }
4315
- if (!(p instanceof w) || !["unauthorized", "403"].includes(p.code) || !this.options.recoverAuthentication || !u || (await this.options.recoverAuthentication(h, p, u && l === 0), c(), !u || l !== 0)) throw p;
4315
+ if (!(m instanceof b) || !["unauthorized", "403"].includes(m.code) || !this.options.recoverAuthentication || !u || (await this.options.recoverAuthentication(h, m, u && l === 0), c(), !u || l !== 0)) throw m;
4316
4316
  }
4317
4317
  }
4318
4318
  }
4319
4319
  async requestOnce(e, t, i, n, r, o) {
4320
4320
  const a = this.auth.client_kind === "embed", c = new URL(`/api/product-agent/${r ?? (a ? "embed" : "runtime")}${e}`, this.options.backendUrl), u = r === "conversations" ? {} : a ? { client_id: this.auth.client_id, transport_id: this.auth.transport_id } : { community_id: this.auth.community_id, automation_run_id: this.auth.automation_run_id };
4321
- for (const [p, f] of Object.entries({ ...u, ...t }))
4322
- f != null && c.searchParams.set(p, String(f));
4321
+ for (const [p, y] of Object.entries({ ...u, ...t }))
4322
+ y != null && c.searchParams.set(p, String(y));
4323
4323
  this.requests.signal.throwIfAborted(), o?.throwIfAborted();
4324
4324
  const l = new AbortController(), d = () => l.abort();
4325
4325
  this.requests.signal.addEventListener("abort", d, { once: !0 }), o?.addEventListener("abort", d, { once: !0 });
4326
- let h = !1;
4326
+ const h = crypto.randomUUID();
4327
+ let f = !1;
4327
4328
  const m = setTimeout(() => {
4328
- h = !0, d();
4329
+ f = !0, d();
4329
4330
  }, 15e3);
4330
4331
  try {
4331
4332
  const p = await fetch(c, {
4332
4333
  method: n ?? (i === void 0 ? "GET" : "POST"),
4333
4334
  cache: "no-store",
4334
4335
  signal: l.signal,
4335
- headers: { authorization: a || r === "conversations" ? `Bearer ${this.auth.token}` : this.auth.token, "content-type": "application/json" },
4336
+ headers: { "x-product-agent-auth-request-id": h, authorization: a || r === "conversations" ? `Bearer ${this.auth.token}` : this.auth.token, "content-type": "application/json" },
4336
4337
  ...i === void 0 ? {} : { body: JSON.stringify(i) }
4337
4338
  });
4338
4339
  if (!p.ok) {
4339
- const f = p.status === 401 ? "unauthorized" : p.status === 426 ? "update_required" : String(p.status), y = (await p.json().catch(() => null))?.detail;
4340
- if (r === "conversations" && e.endsWith("/snapshot") && p.status === 409 && y === "Display projection is not enabled")
4341
- throw new w("Conversation history is unavailable. Try loading this chat again after the service is ready.", "display_projection_disabled");
4342
- if (r === "conversations" && e === "/commands" && (p.status === 409 && y?.code === "executor_not_ready" && y.retryable === !0 || p.status === 403 && y === "Register the executor before commands"))
4343
- throw new w("Reconnecting the browser before continuing.", "executor_not_ready");
4344
- if (p.status !== 401 && y && typeof y == "object" && (["service_origin_not_allowed", "security_control_enforcement_unavailable"].includes(y.code) || !Ye(void 0, y.code).allowed) && typeof y.message == "string")
4345
- throw new w(y.message, y.code, !1, {
4346
- ...typeof y.blockedOrigin == "string" ? { blockedOrigin: y.blockedOrigin } : {},
4347
- ...typeof y.securitySettingsUrl == "string" ? { securitySettingsUrl: y.securitySettingsUrl } : {}
4340
+ const y = p.status === 401 ? "unauthorized" : p.status === 426 ? "update_required" : String(p.status), v = (await p.json().catch(() => null))?.detail;
4341
+ if (r === "conversations" && e.endsWith("/snapshot") && p.status === 409 && v === "Display projection is not enabled")
4342
+ throw new b("Conversation history is unavailable. Try loading this chat again after the service is ready.", "display_projection_disabled");
4343
+ if (r === "conversations" && e === "/commands" && (p.status === 409 && v?.code === "executor_not_ready" && v.retryable === !0 || p.status === 403 && v === "Register the executor before commands"))
4344
+ throw new b("Reconnecting the browser before continuing.", "executor_not_ready");
4345
+ if (p.status !== 401 && v && typeof v == "object" && (["service_origin_not_allowed", "security_control_enforcement_unavailable"].includes(v.code) || !Ye(void 0, v.code).allowed) && typeof v.message == "string")
4346
+ throw new b(v.message, v.code, !1, {
4347
+ ...typeof v.blockedOrigin == "string" ? { blockedOrigin: v.blockedOrigin } : {},
4348
+ ...typeof v.securitySettingsUrl == "string" ? { securitySettingsUrl: v.securitySettingsUrl } : {}
4348
4349
  });
4349
- const b = y === "Token expired" ? "token_expired" : y?.reason, A = p.status === 401 && ["missing_token", "token_expired", "invalid_token", "user_not_found"].includes(b) ? { reason: b, retryable: b === "token_expired" && (y === "Token expired" || y.retryable === !0) } : void 0;
4350
- throw new w(p.status === 401 ? "Your session expired or is invalid. Reconnect to continue." : p.status === 403 ? "You don't have access to this conversation. Check your access and reconnect." : `Product Agent request failed (${p.status})`, f, !1, A);
4350
+ const A = v === "Token expired" ? "token_expired" : v === "Invalid token" ? "invalid_token" : v?.reason, S = p.status === 401 && ["missing_token", "token_expired", "invalid_token", "user_not_found"].includes(A) ? { requestId: h, authTransport: "http", authEndpoint: `${r ?? (a ? "embed" : "runtime")}:${["snapshot", "me", "bootstrap", "commands", "activity", "session-history"].includes(e.split("/").pop()) ? e.split("/").pop() : "other"}`, reason: A, retryable: A === "token_expired" && (v === "Token expired" || v.retryable === !0) } : void 0;
4351
+ throw new b(p.status === 401 ? "Your session expired or is invalid. Reconnect to continue." : p.status === 403 ? "You don't have access to this conversation. Check your access and reconnect." : `Product Agent request failed (${p.status})`, y, !1, S);
4351
4352
  }
4352
4353
  return await p.json();
4353
4354
  } catch (p) {
4354
- throw h && !this.requests.signal.aborted && !o?.aborted ? new w("The request timed out. Please try again.", "request_timed_out", !0) : p;
4355
+ throw f && !this.requests.signal.aborted && !o?.aborted ? new b("The request timed out. Please try again.", "request_timed_out", !0) : p;
4355
4356
  } finally {
4356
4357
  clearTimeout(m), this.requests.signal.removeEventListener("abort", d), o?.removeEventListener("abort", d);
4357
4358
  }
@@ -4386,7 +4387,7 @@ function Vi() {
4386
4387
  requestSequence: 0
4387
4388
  });
4388
4389
  }
4389
- function D(s) {
4390
+ function U(s) {
4390
4391
  return JSON.stringify([s.kind, s.origin, s.limit]);
4391
4392
  }
4392
4393
  function so(s) {
@@ -4397,7 +4398,7 @@ function $(s) {
4397
4398
  const e = s.currentAuthority();
4398
4399
  return e.authorityId === s.authority.authorityId && e.generation === s.authority.generation;
4399
4400
  }
4400
- function Re(s, e) {
4401
+ function Te(s, e) {
4401
4402
  if (!$(s) || e.authorityId !== s.authority.authorityId || e.generation !== s.authority.generation)
4402
4403
  throw new Error("Directory authority is no longer current.");
4403
4404
  }
@@ -4432,18 +4433,18 @@ function no(s) {
4432
4433
  return {
4433
4434
  "directory.query": async (i) => {
4434
4435
  try {
4435
- Re(s, i);
4436
+ Te(s, i);
4436
4437
  const n = Me(i.query), r = { origin: n.origin, pinned: n.kind === "pinned", cursor: i.cursor, limit: n.limit };
4437
4438
  let o;
4438
4439
  if (s.http.auth.client_kind === "embed") {
4439
4440
  const a = await s.http.request("/conversations", { ...r, page_url: n.origin ?? s.pageUrl() });
4440
- Re(s, i), o = { entries: await Promise.all(a.sessions.map(async (u) => ({
4441
+ Te(s, i), o = { entries: await Promise.all(a.sessions.map(async (u) => ({
4441
4442
  ...await Ki(s.http, u.id),
4442
4443
  ...typeof u.isActive == "boolean" ? { is_active: u.isActive } : {}
4443
4444
  }))), next_cursor: a.nextCursor };
4444
4445
  } else
4445
4446
  o = await s.http.request("/conversations", r, void 0, "GET", e);
4446
- return Re(s, i), { ...o, updatedAt: s.now() };
4447
+ return Te(s, i), { ...o, updatedAt: s.now() };
4447
4448
  } catch (n) {
4448
4449
  throw $({ authority: i, currentAuthority: s.currentAuthority }) && s.onError?.(n), n;
4449
4450
  }
@@ -4452,9 +4453,9 @@ function no(s) {
4452
4453
  const r = (t.get(i.sessionId) ?? Promise.resolve()).catch(() => {
4453
4454
  }).then(async () => {
4454
4455
  try {
4455
- Re(s, i);
4456
+ Te(s, i);
4456
4457
  const a = await s.http.request(`/conversations/${encodeURIComponent(i.sessionId)}`, {}, i.patch, "PATCH", e);
4457
- return Re(s, i), a;
4458
+ return Te(s, i), a;
4458
4459
  } catch (a) {
4459
4460
  throw $({ authority: i, currentAuthority: s.currentAuthority }) && s.onError?.(a), a;
4460
4461
  }
@@ -4519,26 +4520,26 @@ class ro {
4519
4520
  open(e, t = "replace", i) {
4520
4521
  if (this.disposed || !$(this.boundary)) return Promise.resolve();
4521
4522
  e = Me(e);
4522
- const n = D(e);
4523
+ const n = U(e);
4523
4524
  return t === "replace" && this.options.runtime.engine.getState().slices.directory.queries[n]?.requestId ? (this.refreshAfterRequest.add(n), Promise.resolve()) : (this.requestPage(e, t, i).catch((r) => this.report(r)), Promise.resolve());
4524
4525
  }
4525
4526
  requestPage(e, t = "replace", i) {
4526
4527
  return e = Me(e), this.enqueueQuery(e, () => this.readPage(e, t, i));
4527
4528
  }
4528
4529
  enqueueQuery(e, t) {
4529
- const i = D(e), n = this.queryRequests.get(i), r = (async () => (await n?.catch(() => {
4530
+ const i = U(e), n = this.queryRequests.get(i), r = (async () => (await n?.catch(() => {
4530
4531
  }), t()))();
4531
4532
  return this.queryRequests.set(i, r), r.finally(() => {
4532
4533
  if (this.queryRequests.get(i) === r) {
4533
4534
  this.queryRequests.delete(i);
4534
4535
  for (const o of this.observedQueryStates())
4535
- o.status === "ready" && o.invalidated && this.isObserved(o.query) && !this.queryRequests.has(D(o.query)) && this.refreshObservedQuery(o.query).catch((a) => this.report(a));
4536
+ o.status === "ready" && o.invalidated && this.isObserved(o.query) && !this.queryRequests.has(U(o.query)) && this.refreshObservedQuery(o.query).catch((a) => this.report(a));
4536
4537
  }
4537
4538
  }).catch(() => {
4538
4539
  }), r;
4539
4540
  }
4540
4541
  async readPage(e, t, i) {
4541
- for (; !this.disposed && $(this.boundary) && this.options.runtime.engine.getState().slices.directory.queries[D(e)]?.requestId; )
4542
+ for (; !this.disposed && $(this.boundary) && this.options.runtime.engine.getState().slices.directory.queries[U(e)]?.requestId; )
4542
4543
  await this.waitForQuery(e, !1);
4543
4544
  if (this.disposed || !$(this.boundary)) throw new Error("Directory authority is no longer current.");
4544
4545
  return await this.options.runtime.engine.dispatch({
@@ -4548,7 +4549,7 @@ class ro {
4548
4549
  requestId: this.options.nextRequestId(),
4549
4550
  mode: t,
4550
4551
  ...i !== void 0 ? { cursor: i } : {}
4551
- }), await this.waitForQuery(e, !0), this.options.runtime.engine.getState().slices.directory.queries[D(e)]?.pageData ?? [];
4552
+ }), await this.waitForQuery(e, !0), this.options.runtime.engine.getState().slices.directory.queries[U(e)]?.pageData ?? [];
4552
4553
  }
4553
4554
  refresh(e, t = !1) {
4554
4555
  return this.refreshPages(e, t, () => !0);
@@ -4559,15 +4560,15 @@ class ro {
4559
4560
  refreshPages(e, t, i) {
4560
4561
  return e = Me(e), this.enqueueQuery(e, async () => {
4561
4562
  if (!i() || (await this.readPage(e, "replace"), !t)) return;
4562
- let n = this.options.runtime.engine.getState().slices.directory.queries[D(e)]?.cursor ?? null;
4563
+ let n = this.options.runtime.engine.getState().slices.directory.queries[U(e)]?.cursor ?? null;
4563
4564
  for (; n !== null && i(); ) {
4564
4565
  const r = n;
4565
- if (await this.readPage(e, "append", r), n = this.options.runtime.engine.getState().slices.directory.queries[D(e)]?.cursor ?? null, n === r) throw new Error("Conversation directory returned the same cursor twice");
4566
+ if (await this.readPage(e, "append", r), n = this.options.runtime.engine.getState().slices.directory.queries[U(e)]?.cursor ?? null, n === r) throw new Error("Conversation directory returned the same cursor twice");
4566
4567
  }
4567
4568
  });
4568
4569
  }
4569
4570
  waitForQuery(e, t) {
4570
- const i = D(e);
4571
+ const i = U(e);
4571
4572
  return new Promise((n, r) => {
4572
4573
  let o = null;
4573
4574
  const a = () => {
@@ -4584,10 +4585,10 @@ class ro {
4584
4585
  }
4585
4586
  observedQueryStates() {
4586
4587
  const e = this.options.runtime.engine.getState().slices.directory.queries;
4587
- return this.options.observedQueries().flatMap((t) => e[D(Me(t))] ?? []);
4588
+ return this.options.observedQueries().flatMap((t) => e[U(Me(t))] ?? []);
4588
4589
  }
4589
4590
  isObserved(e) {
4590
- return !this.disposed && $(this.boundary) && (this.options.enabled?.() ?? !0) && this.observedQueryStates().some((t) => D(t.query) === D(e));
4591
+ return !this.disposed && $(this.boundary) && (this.options.enabled?.() ?? !0) && this.observedQueryStates().some((t) => U(t.query) === U(e));
4591
4592
  }
4592
4593
  async refreshObservedQueries() {
4593
4594
  await Promise.all(this.observedQueryStates().map((e) => this.refreshObservedQuery(e.query)));
@@ -4703,16 +4704,16 @@ class ao {
4703
4704
  if (e !== void 0 && r.some((c) => c.sessionId !== e)) return !1;
4704
4705
  const o = [], a = new Set(r.map((c) => c.sessionId));
4705
4706
  for (const c of a) {
4706
- const u = r.filter((m) => m.sessionId === c), l = c === null ? u[0] : u.find((m) => m.clientScopeId === i.mains[c]) ?? this.choose(u), d = [l, ...u.filter((m) => m !== l)], h = /* @__PURE__ */ new Set();
4707
- for (const m of d) {
4708
- const p = { ...this.options.authority, clientScopeId: m.clientScopeId, conversationScopeId: m.conversationScopeId, replacement: null };
4709
- m.provisionalId !== null && !h.has(m.conversationScopeId) ? (o.push({ ...p, type: "directory.provisional", provisionalId: m.provisionalId }), c !== null && (o.push({
4707
+ const u = r.filter((f) => f.sessionId === c), l = c === null ? u[0] : u.find((f) => f.clientScopeId === i.mains[c]) ?? this.choose(u), d = [l, ...u.filter((f) => f !== l)], h = /* @__PURE__ */ new Set();
4708
+ for (const f of d) {
4709
+ const m = { ...this.options.authority, clientScopeId: f.clientScopeId, conversationScopeId: f.conversationScopeId, replacement: null };
4710
+ f.provisionalId !== null && !h.has(f.conversationScopeId) ? (o.push({ ...m, type: "directory.provisional", provisionalId: f.provisionalId }), c !== null && (o.push({
4710
4711
  ...this.options.authority,
4711
4712
  type: "directory.accepted",
4712
- conversationScopeId: m.conversationScopeId,
4713
- provisionalId: m.provisionalId,
4713
+ conversationScopeId: f.conversationScopeId,
4714
+ provisionalId: f.provisionalId,
4714
4715
  sessionId: c
4715
- }), h.add(m.conversationScopeId))) : o.push({ ...p, type: "directory.bind", sessionId: c, reason: "user" });
4716
+ }), h.add(f.conversationScopeId))) : o.push({ ...m, type: "directory.bind", sessionId: c, reason: "user" });
4716
4717
  }
4717
4718
  }
4718
4719
  return await Promise.all(o.map((c) => this.options.runtime.engine.dispatch(c))), !0;
@@ -4746,7 +4747,7 @@ function lo(s, e, t = () => crypto.randomUUID()) {
4746
4747
  };
4747
4748
  }
4748
4749
  }
4749
- class U extends EventTarget {
4750
+ class P extends EventTarget {
4750
4751
  constructor(e) {
4751
4752
  super(), this.options = e, this.httpTransport = new Wi({
4752
4753
  ...e,
@@ -4910,7 +4911,7 @@ class U extends EventTarget {
4910
4911
  try {
4911
4912
  return await this.transport.rpc(e.type, Object.fromEntries(Object.entries(e).filter(([t]) => t !== "type"))), !0;
4912
4913
  } catch (t) {
4913
- return t instanceof w && t.code === "backpressure" && !t.backendRefusal || this.fail(t, e), t instanceof w && t.backendRefusal;
4914
+ return t instanceof b && t.code === "backpressure" && !t.backendRefusal || this.fail(t, e), t instanceof b && t.backendRefusal;
4914
4915
  }
4915
4916
  }
4916
4917
  receive(e) {
@@ -4929,13 +4930,13 @@ class U extends EventTarget {
4929
4930
  }
4930
4931
  buffer(e, t) {
4931
4932
  if (e.length >= 128) {
4932
- this.fail(new w("Product Agent delivery buffer is full", "backpressure")), this.close();
4933
+ this.fail(new b("Product Agent delivery buffer is full", "backpressure")), this.close();
4933
4934
  return;
4934
4935
  }
4935
4936
  e.push(t);
4936
4937
  }
4937
4938
  fail(e, t, i = !1) {
4938
- const n = e instanceof w ? e : new w(String(e), "request_failed");
4939
+ const n = e instanceof b ? e : new b(String(e), "request_failed");
4939
4940
  if (n.code === "disconnected" || n.outcomeUnknown) return;
4940
4941
  const r = n.detail && typeof n.detail == "object" ? n.detail : {};
4941
4942
  this.options.auth.client_kind === "extension" && n.code === "update_required" && r.version_status && this.receive(r.version_status), this.receive({
@@ -4955,7 +4956,7 @@ class U extends EventTarget {
4955
4956
  return this.httpTransport.request(e, t, i, n);
4956
4957
  }
4957
4958
  isRetryableRead(e) {
4958
- return e instanceof TypeError || e instanceof DOMException && e.name === "AbortError" || e instanceof w && ["request_timed_out", "408", "429", "500", "502", "503", "504"].includes(e.code);
4959
+ return e instanceof TypeError || e instanceof DOMException && e.name === "AbortError" || e instanceof b && ["request_timed_out", "408", "429", "500", "502", "503", "504"].includes(e.code);
4959
4960
  }
4960
4961
  async loadUserSuggestions(e, t = 0) {
4961
4962
  const i = this.promptRevision, n = this.options.pageUrl();
@@ -4966,7 +4967,7 @@ class U extends EventTarget {
4966
4967
  } catch (r) {
4967
4968
  if (e.aborted) return;
4968
4969
  if (!this.isRetryableRead(r)) {
4969
- i === this.promptRevision && n === this.options.pageUrl() && this.receive({ type: "starterPrompts.updated", starterPromptsLoading: !1 }), r instanceof w && ["unauthorized", "update_required"].includes(r.code) ? this.fail(r) : console.error("Product Agent optional suggestions could not be loaded", r);
4970
+ i === this.promptRevision && n === this.options.pageUrl() && this.receive({ type: "starterPrompts.updated", starterPromptsLoading: !1 }), r instanceof b && ["unauthorized", "update_required"].includes(r.code) ? this.fail(r) : console.error("Product Agent optional suggestions could not be loaded", r);
4970
4971
  return;
4971
4972
  }
4972
4973
  this.suggestionTimer = setTimeout(() => {
@@ -4979,7 +4980,7 @@ class U extends EventTarget {
4979
4980
  if (i === "auth.session") {
4980
4981
  if (this.initialized) return;
4981
4982
  this.initialized = !0;
4982
- const h = this.bootstrapRequests.signal, m = this.credentialBootstrap ?? await this.httpTransport.request(
4983
+ const h = this.bootstrapRequests.signal, f = this.credentialBootstrap ?? await this.httpTransport.request(
4983
4984
  r ? "/bootstrap" : "/me",
4984
4985
  r ? a : {},
4985
4986
  void 0,
@@ -4987,9 +4988,9 @@ class U extends EventTarget {
4987
4988
  void 0,
4988
4989
  { signal: h }
4989
4990
  );
4990
- if (h.aborted || !this.isCurrent(t) || (this.credentialBootstrap = null, !this.options.auth.community_id && m.user?.runtimeCommunityId && (this.options.auth.community_id = m.user.runtimeCommunityId), this.receive({ type: "auth.ok", ...m }), h.aborted)) return;
4991
- this.options.auth.client_kind === "extension" && this.receive({ type: "executor.registered", userId: m.user.id }), this.bootstrapped = !0;
4992
- for (const p of this.beforeBootstrap.splice(0)) this.receive(p);
4991
+ if (h.aborted || !this.isCurrent(t) || (this.credentialBootstrap = null, !this.options.auth.community_id && f.user?.runtimeCommunityId && (this.options.auth.community_id = f.user.runtimeCommunityId), this.receive({ type: "auth.ok", ...f }), h.aborted)) return;
4992
+ this.options.auth.client_kind === "extension" && this.receive({ type: "executor.registered", userId: f.user.id }), this.bootstrapped = !0;
4993
+ for (const m of this.beforeBootstrap.splice(0)) this.receive(m);
4993
4994
  this.synchronizeReferences(), this.options.auth.client_kind === "web" && this.loadUserSuggestions(h);
4994
4995
  return;
4995
4996
  }
@@ -4998,8 +4999,8 @@ class U extends EventTarget {
4998
4999
  return;
4999
5000
  }
5000
5001
  if (i === "starter_prompts.page_url" || i === "starter_prompts.page_context") {
5001
- const h = ++this.promptRevision, m = await this.http("/starter-prompts", a, i === "starter_prompts.page_context" ? { page_url: o, page_title: e.pageTitle ?? "", html_content: e.htmlContent ?? "" } : void 0);
5002
- this.isCurrent(t) && h === this.promptRevision && o === this.options.pageUrl() && this.receive({ type: "starterPrompts.updated", ...m });
5002
+ const h = ++this.promptRevision, f = await this.http("/starter-prompts", a, i === "starter_prompts.page_context" ? { page_url: o, page_title: e.pageTitle ?? "", html_content: e.htmlContent ?? "" } : void 0);
5003
+ this.isCurrent(t) && h === this.promptRevision && o === this.options.pageUrl() && this.receive({ type: "starterPrompts.updated", ...f });
5003
5004
  return;
5004
5005
  }
5005
5006
  if (i === "session.load") {
@@ -5354,26 +5355,26 @@ function le(s, e) {
5354
5355
  if (!n || n.kind !== e.effectKind) return { state: s, effects: i };
5355
5356
  const r = { ...s.requests };
5356
5357
  if (delete r[e.effectId], t = { ...s, requests: r }, n.kind === "directory.query") {
5357
- const o = D(n.input.query), a = s.queries[o];
5358
+ const o = U(n.input.query), a = s.queries[o];
5358
5359
  if (a.requestId !== n.input.requestId) return { state: De(t), effects: i };
5359
5360
  if (e.type === "effect.failed")
5360
5361
  t = { ...t, queries: { ...t.queries, [o]: { ...a, status: "error", error: { ...e.error }, requestId: null } } };
5361
5362
  else if (e.effectKind === "directory.query") {
5362
- for (const p of e.output.entries) t = Ct(t, p, !0);
5363
- const c = e.output.entries.map((p) => p.conversation_id), u = { ...t.durableActivityBySessionId }, l = { ...t.activityBySessionId }, d = { ...t.activityRevisionBySessionId };
5364
- for (const p of e.output.entries) {
5365
- if (typeof p.is_active != "boolean") continue;
5366
- u[p.conversation_id] = p.is_active;
5367
- const f = a.startedAtActivityRevisionBySessionId[p.conversation_id];
5368
- f !== void 0 && d[p.conversation_id] === f && (delete l[p.conversation_id], delete d[p.conversation_id]);
5363
+ for (const m of e.output.entries) t = Ct(t, m, !0);
5364
+ const c = e.output.entries.map((m) => m.conversation_id), u = { ...t.durableActivityBySessionId }, l = { ...t.activityBySessionId }, d = { ...t.activityRevisionBySessionId };
5365
+ for (const m of e.output.entries) {
5366
+ if (typeof m.is_active != "boolean") continue;
5367
+ u[m.conversation_id] = m.is_active;
5368
+ const p = a.startedAtActivityRevisionBySessionId[m.conversation_id];
5369
+ p !== void 0 && d[m.conversation_id] === p && (delete l[m.conversation_id], delete d[m.conversation_id]);
5369
5370
  }
5370
5371
  t = { ...t, durableActivityBySessionId: u, activityBySessionId: l, activityRevisionBySessionId: d };
5371
- const h = Object.fromEntries(Object.entries(t.optimisticEntries).filter(([, p]) => p.sessionId === null || !c.includes(p.sessionId)));
5372
+ const h = Object.fromEntries(Object.entries(t.optimisticEntries).filter(([, m]) => m.sessionId === null || !c.includes(m.sessionId)));
5372
5373
  t = { ...t, optimisticEntries: h };
5373
- const m = [.../* @__PURE__ */ new Set([...a.mode === "append" ? a.data ?? [] : [], ...c])];
5374
+ const f = [.../* @__PURE__ */ new Set([...a.mode === "append" ? a.data ?? [] : [], ...c])];
5374
5375
  t = { ...t, queries: { ...t.queries, [o]: {
5375
5376
  ...a,
5376
- data: m,
5377
+ data: f,
5377
5378
  pageData: c,
5378
5379
  status: "ready",
5379
5380
  requestId: null,
@@ -5439,7 +5440,7 @@ function le(s, e) {
5439
5440
  const n = `${s.generation}:${s.requestSequence + 1}`, r = { authorityId: e.authorityId, generation: e.generation, requestId: e.requestId };
5440
5441
  let o;
5441
5442
  if (e.type === "directory.query") {
5442
- const a = D(e.query), c = s.queries[a];
5443
+ const a = U(e.query), c = s.queries[a];
5443
5444
  if (c?.requestId !== null && c?.requestId !== void 0) return { state: s, effects: i };
5444
5445
  if (e.mode === "append" && e.cursor === void 0 && (!c?.data || c.cursor === null)) return { state: s, effects: i };
5445
5446
  const u = { ...e.query };
@@ -5691,7 +5692,7 @@ class _o {
5691
5692
  }
5692
5693
  }
5693
5694
  function Ao(s) {
5694
- if (s.details !== void 0 && !be(s.details))
5695
+ if (s.details !== void 0 && !we(s.details))
5695
5696
  throw new TypeError("Product Agent transported error details must be JSON-safe.");
5696
5697
  return {
5697
5698
  code: s.code,
@@ -5774,7 +5775,7 @@ function ni(s, e, t) {
5774
5775
  for (const [o, a] of Object.entries(t.memberships)) {
5775
5776
  const c = t.clients[a.members[0]];
5776
5777
  if (!c) continue;
5777
- const u = ve(e, t, c), l = ve(s, t, c);
5778
+ const u = Ie(e, t, c), l = Ie(s, t, c);
5778
5779
  if (u.activity.phase === l.activity.phase) continue;
5779
5780
  const d = ["submitting", "awaiting_execution", "thinking", "steering", "queued", "stopping"].includes(u.activity.phase);
5780
5781
  i = le(i, { ...n, type: "directory.activity_set", sessionId: o, active: d }).state;
@@ -5809,27 +5810,27 @@ class qo {
5809
5810
  if (To(o)) {
5810
5811
  const c = Wn(n.slices.conversation, o, n.slices.directory, n.slices.modelSelection);
5811
5812
  let u = n.slices.directory;
5812
- for (const [m, p] of Object.entries(c.state.operations)) {
5813
- if (!["runtime.warmup", "attachment.prepare"].includes(p.command.type) || !p.conversationScopeId || p.phase !== "done" || n.slices.conversation.operations[m]?.phase === "done") continue;
5814
- const f = p.result, y = u.selections[p.conversationScopeId];
5815
- f?.sessionId && y?.provisionalId && y.sessionId === null && Object.values(u.clients).includes(p.conversationScopeId) && (u = le(u, {
5813
+ for (const [f, m] of Object.entries(c.state.operations)) {
5814
+ if (!["runtime.warmup", "attachment.prepare"].includes(m.command.type) || !m.conversationScopeId || m.phase !== "done" || n.slices.conversation.operations[f]?.phase === "done") continue;
5815
+ const p = m.result, y = u.selections[m.conversationScopeId];
5816
+ p?.sessionId && y?.provisionalId && y.sessionId === null && Object.values(u.clients).includes(m.conversationScopeId) && (u = le(u, {
5816
5817
  authorityId: c.state.authorityId,
5817
5818
  generation: c.state.generation,
5818
5819
  type: "directory.accepted",
5819
- conversationScopeId: p.conversationScopeId,
5820
+ conversationScopeId: m.conversationScopeId,
5820
5821
  provisionalId: y.provisionalId,
5821
- sessionId: f.sessionId
5822
+ sessionId: p.sessionId
5822
5823
  }).state);
5823
5824
  }
5824
- const l = Object.values(c.state.submissions).find((m) => m.delivery === "accepted" && n.slices.conversation.submissions[m.userMessageId]?.delivery !== "accepted");
5825
+ const l = Object.values(c.state.submissions).find((f) => f.delivery === "accepted" && n.slices.conversation.submissions[f.userMessageId]?.delivery !== "accepted");
5825
5826
  if (l) {
5826
- const m = u.selections[l.conversationScopeId];
5827
- !l.cancelled && m?.provisionalId && (u = le(u, {
5827
+ const f = u.selections[l.conversationScopeId];
5828
+ !l.cancelled && f?.provisionalId && (u = le(u, {
5828
5829
  type: "directory.accepted",
5829
5830
  authorityId: c.state.authorityId,
5830
5831
  generation: c.state.generation,
5831
5832
  conversationScopeId: l.conversationScopeId,
5832
- provisionalId: m.provisionalId,
5833
+ provisionalId: f.provisionalId,
5833
5834
  sessionId: l.sessionId
5834
5835
  }).state);
5835
5836
  }
@@ -5870,7 +5871,7 @@ class qo {
5870
5871
  code: n instanceof Error && "retryable" in n && typeof n.retryable == "boolean" && "code" in n && typeof n.code == "string" ? n.code : "runtime_error",
5871
5872
  message: n instanceof Error ? n.message : String(n),
5872
5873
  retryable: n instanceof Error && "retryable" in n && n.retryable === !0,
5873
- ...n instanceof Error && "details" in n && n.details !== null && typeof n.details == "object" && !Array.isArray(n.details) && be(n.details) ? { details: n.details } : {}
5874
+ ...n instanceof Error && "details" in n && n.details !== null && typeof n.details == "object" && !Array.isArray(n.details) && we(n.details) ? { details: n.details } : {}
5874
5875
  })
5875
5876
  });
5876
5877
  }
@@ -6055,7 +6056,7 @@ function zo(s) {
6055
6056
  return (s.type === "function_call" || s.type === "tool_call") && s.name === Fo;
6056
6057
  }
6057
6058
  const qt = "pluno.productAgent.transportId", Ho = "pluno.productAgent.transportIdentity", Mt = "pluno.productAgent.transportIdentity.event", Wo = 50, Vo = globalThis.setTimeout.bind(globalThis);
6058
- let Te = null;
6059
+ let ke = null;
6059
6060
  const rt = /* @__PURE__ */ new Set(), Ot = /* @__PURE__ */ new Map();
6060
6061
  async function Ko(s = en()) {
6061
6062
  const e = s.randomUUID(), t = s.storage.getItem(qt);
@@ -6096,16 +6097,16 @@ async function Ko(s = en()) {
6096
6097
  };
6097
6098
  }
6098
6099
  async function Go(s = !1) {
6099
- Te || (Te = Ko({
6100
+ ke || (ke = Ko({
6100
6101
  ...en(),
6101
6102
  skipStoredIdentityCollisionCheck: s
6102
- }), Te.then((n) => {
6103
+ }), ke.then((n) => {
6103
6104
  const r = (o) => {
6104
- o.persisted || (n.release(), Te = null, rt.clear(), window.removeEventListener("pagehide", r));
6105
+ o.persisted || (n.release(), ke = null, rt.clear(), window.removeEventListener("pagehide", r));
6105
6106
  };
6106
6107
  window.addEventListener("pagehide", r);
6107
6108
  }));
6108
- const e = await Te, t = Qo();
6109
+ const e = await ke, t = Qo();
6109
6110
  rt.add(t);
6110
6111
  let i = !1;
6111
6112
  return {
@@ -6908,9 +6909,9 @@ class Td {
6908
6909
  d.push(h);
6909
6910
  continue;
6910
6911
  }
6911
- const m = h.id ? this.attachmentFiles.get(h.id) : void 0;
6912
- if (!m) throw new Error(`Attachment bytes are unavailable for ${h.name}`);
6913
- if (d.push(await o.measure("attachment_transfer", () => this.adapter.uploadAttachment(m, h, { clientMessageId: r }))), i !== this.submissionGeneration) return null;
6912
+ const f = h.id ? this.attachmentFiles.get(h.id) : void 0;
6913
+ if (!f) throw new Error(`Attachment bytes are unavailable for ${h.name}`);
6914
+ if (d.push(await o.measure("attachment_transfer", () => this.adapter.uploadAttachment(f, h, { clientMessageId: r }))), i !== this.submissionGeneration) return null;
6914
6915
  }
6915
6916
  a = d;
6916
6917
  }
@@ -7215,7 +7216,7 @@ function Nt(s) {
7215
7216
  }
7216
7217
  return { ...e, ...qn(s) };
7217
7218
  }
7218
- function ke(s, e, t) {
7219
+ function me(s, e, t) {
7219
7220
  if (typeof window > "u")
7220
7221
  return;
7221
7222
  const i = window.__PLUNO_PRODUCT_AGENT_TRACE_ID__;
@@ -7267,7 +7268,7 @@ function pi(s) {
7267
7268
  }
7268
7269
  return !0;
7269
7270
  }
7270
- function me(s) {
7271
+ function ge(s) {
7271
7272
  if (s instanceof Error)
7272
7273
  return s;
7273
7274
  if (s && typeof s == "object") {
@@ -7290,8 +7291,8 @@ class gt {
7290
7291
  authenticationFailure: () => this.authenticationFailure,
7291
7292
  pendingAuthentication: () => this.credentialRecovery ?? (this.credentialRecoveryFailure ? Promise.reject(this.credentialRecoveryFailure) : null),
7292
7293
  recoverAuthentication: (n, r, o) => this.recoverHttpAuthentication(n, r, o),
7293
- executorConnection: () => this.socket instanceof U ? this.socket.connectionId : null,
7294
- restoreExecutor: (n) => this.socket instanceof U ? this.socket.restoreExecutor(n) : Promise.reject(new w("Browser is reconnecting.", "executor_not_ready")),
7294
+ executorConnection: () => this.socket instanceof P ? this.socket.connectionId : null,
7295
+ restoreExecutor: (n) => this.socket instanceof P ? this.socket.restoreExecutor(n) : Promise.reject(new b("Browser is reconnecting.", "executor_not_ready")),
7295
7296
  auth: {
7296
7297
  protocol: 1,
7297
7298
  token: e.token ?? "",
@@ -7350,6 +7351,8 @@ class gt {
7350
7351
  connectionInProgress = !1;
7351
7352
  token = null;
7352
7353
  rejectedTransportToken = null;
7354
+ /** @internal */
7355
+ invalidCredentialRecoveryAttempted = !1;
7353
7356
  refreshingDefaultCredentials = !1;
7354
7357
  credentialRecovery = null;
7355
7358
  credentialRecoveryFailure = null;
@@ -7488,9 +7491,9 @@ class gt {
7488
7491
  authority: this.directoryAuthority,
7489
7492
  http: this.directoryHttp,
7490
7493
  isActiveTurn: (t) => this.clientRuntime.engine.getProjection().directory.activityBySessionId[t] === !0,
7491
- nextRequestId: x,
7494
+ nextRequestId: D,
7492
7495
  onError: (t) => {
7493
- this.handleDirectoryTransportError(t), this.emit("error", me(t));
7496
+ this.handleDirectoryTransportError(t), this.emit("error", ge(t));
7494
7497
  },
7495
7498
  wakeup: { start: () => {
7496
7499
  }, stop: () => {
@@ -7523,18 +7526,18 @@ class gt {
7523
7526
  isCurrent: i,
7524
7527
  http: this.directoryHttp,
7525
7528
  now: () => Date.now(),
7526
- connectionId: () => this.socket instanceof U ? this.socket.connectionId : null,
7529
+ connectionId: () => this.socket instanceof P ? this.socket.connectionId : null,
7527
7530
  prepareUpload: this.options.prepareAttachmentUpload ?? (this.options.productVariant === "customer_embedded" ? (d) => this.prepareEmbedAttachmentUpload(d, i) : void 0),
7528
- onUploaded: async (d, h, m) => {
7531
+ onUploaded: async (d, h, f) => {
7529
7532
  await Xi(d, {
7530
7533
  sessionId: h,
7531
- sandboxPath: m.sandbox_path ?? void 0,
7532
- storageKey: m.storage_key ?? void 0,
7533
- fileUrl: m.file_url ? new URL(m.file_url, this.options.backendUrl).toString() : void 0,
7534
+ sandboxPath: f.sandbox_path ?? void 0,
7535
+ storageKey: f.storage_key ?? void 0,
7536
+ fileUrl: f.file_url ? new URL(f.file_url, this.options.backendUrl).toString() : void 0,
7534
7537
  lastUsedAt: Date.now()
7535
- }).catch((p) => N("web-sdk.attachments", "Failed to update persisted Product Agent attachment", {
7538
+ }).catch((m) => N("web-sdk.attachments", "Failed to update persisted Product Agent attachment", {
7536
7539
  attachmentId: d,
7537
- message: p instanceof Error ? p.message : String(p)
7540
+ message: m instanceof Error ? m.message : String(m)
7538
7541
  }));
7539
7542
  },
7540
7543
  persistUpload: this.options.persistAttachmentUpload,
@@ -7550,22 +7553,22 @@ class gt {
7550
7553
  onTiming: (d) => {
7551
7554
  i() && this.reportOperationTiming(d);
7552
7555
  },
7553
- onCommand: (d) => ke("client_event", d.type, Nt({ ...d.payload, type: d.type })),
7556
+ onCommand: (d) => me("client_event", d.type, Nt({ ...d.payload, type: d.type })),
7554
7557
  onError: (d) => this.handleDirectoryTransportError(d)
7555
7558
  }),
7556
7559
  "conversation.interactions": this.createConversationInteractionPort()
7557
7560
  });
7558
7561
  const r = this.clientRuntime.engine.getState().slices.conversation, o = this.options.restorePersistedState === !1 || !this.authenticatedUserId ? null : Bs(n);
7559
7562
  if (this.authenticatedUserId && !r.submissionOrder.length && !Object.keys(r.operations).length) {
7560
- const d = this.queuedClientEvents.filter((m) => m.type === "chat.user_message"), h = o ? JSON.parse(o) : d.length ? Bn(r, d.map((m) => {
7561
- const { type: p, ...f } = m, y = this.clientRuntime.engine.getState().slices.directory, b = y.clients[this.modelClientScopeId];
7563
+ const d = this.queuedClientEvents.filter((f) => f.type === "chat.user_message"), h = o ? JSON.parse(o) : d.length ? Bn(r, d.map((f) => {
7564
+ const { type: m, ...p } = f, y = this.clientRuntime.engine.getState().slices.directory, v = y.clients[this.modelClientScopeId];
7562
7565
  return {
7563
- command: { type: p, request_id: m.clientMessageId, payload: JSON.parse(JSON.stringify(f)) },
7564
- requestedModel: m.model ?? null,
7566
+ command: { type: m, request_id: f.clientMessageId, payload: JSON.parse(JSON.stringify(p)) },
7567
+ requestedModel: f.model ?? null,
7565
7568
  clientScopeId: this.modelClientScopeId,
7566
- conversationScopeId: b,
7569
+ conversationScopeId: v,
7567
7570
  viewId: `sdk:${this.modelClientScopeId}`,
7568
- sessionId: m.sessionId ?? y.selections[b]?.sessionId ?? null,
7571
+ sessionId: f.sessionId ?? y.selections[v]?.sessionId ?? null,
7569
7572
  entrySurface: this.options.entrySurface,
7570
7573
  submittedAt: Date.now()
7571
7574
  };
@@ -7581,19 +7584,19 @@ class gt {
7581
7584
  enabled: () => !!this.token && !this.authenticationFailure && !this.refreshingDefaultCredentials && this.state.status !== "closed",
7582
7585
  socket: {
7583
7586
  retain: async (d, h) => {
7584
- const m = this.socket;
7585
- m instanceof U && await m.directoryRooms.retain(d, h).catch((p) => {
7586
- if (this.socket === m) throw p;
7587
+ const f = this.socket;
7588
+ f instanceof P && await f.directoryRooms.retain(d, h).catch((m) => {
7589
+ if (this.socket === f) throw m;
7587
7590
  });
7588
7591
  },
7589
7592
  release: async (d, h) => {
7590
- const m = this.socket;
7591
- m instanceof U && await m.directoryRooms.release(d, h).catch((p) => {
7592
- if (this.socket === m) throw p;
7593
+ const f = this.socket;
7594
+ f instanceof P && await f.directoryRooms.release(d, h).catch((m) => {
7595
+ if (this.socket === f) throw m;
7593
7596
  });
7594
7597
  }
7595
7598
  },
7596
- nextRequestId: x,
7599
+ nextRequestId: D,
7597
7600
  wakeup: { start: () => {
7598
7601
  }, stop: () => {
7599
7602
  } },
@@ -7603,34 +7606,34 @@ class gt {
7603
7606
  this.conversationUnsubscribe = this.clientRuntime.engine.subscribe(() => {
7604
7607
  const d = this.clientRuntime.engine.getState().slices, h = c;
7605
7608
  c = d.conversation;
7606
- const m = l !== d.directory.clients[this.modelClientScopeId];
7609
+ const f = l !== d.directory.clients[this.modelClientScopeId];
7607
7610
  l = d.directory.clients[this.modelClientScopeId], u !== d.directory.selections && (u = d.directory.selections, this.directoryScope.persist());
7608
- for (const f of Object.values(d.conversation.submissions)) {
7609
- if (f.delivery === "accepted" && h.submissions[f.userMessageId]?.delivery !== "accepted") {
7610
- this.emit("ack", { clientMessageId: f.userMessageId, sessionId: f.sessionId });
7611
- const y = f.sessionId;
7612
- y && this.getState().sessionId === y && this.directoryHttp.request(`/sessions/${encodeURIComponent(y)}/history`, { limit: 200 }).then((b) => {
7613
- i() && this.getState().sessionId === y && this.state.status !== "closed" && xt(this.clientRuntime, this.modelClientScopeId, y, b.turns);
7614
- }).catch((b) => {
7615
- i() && this.getState().sessionId === y && this.handleDirectoryTransportError(b);
7611
+ for (const p of Object.values(d.conversation.submissions)) {
7612
+ if (p.delivery === "accepted" && h.submissions[p.userMessageId]?.delivery !== "accepted") {
7613
+ this.emit("ack", { clientMessageId: p.userMessageId, sessionId: p.sessionId });
7614
+ const y = p.sessionId;
7615
+ y && this.getState().sessionId === y && this.directoryHttp.request(`/sessions/${encodeURIComponent(y)}/history`, { limit: 200 }).then((v) => {
7616
+ i() && this.getState().sessionId === y && this.state.status !== "closed" && xt(this.clientRuntime, this.modelClientScopeId, y, v.turns);
7617
+ }).catch((v) => {
7618
+ i() && this.getState().sessionId === y && this.handleDirectoryTransportError(v);
7616
7619
  });
7617
7620
  }
7618
- (f.cancelled || f.delivery === "failed") && this.clearFirstResponseTimer(f.userMessageId);
7621
+ (p.cancelled || p.delivery === "failed") && this.clearFirstResponseTimer(p.userMessageId);
7619
7622
  }
7620
- for (const [f, y] of Object.entries(d.directory.clients)) {
7621
- if (!f.startsWith(`background:${this.modelClientScopeId}:`)) continue;
7622
- const b = ve(d.conversation, d.directory, y);
7623
- (m && b.sessionId === this.getState().sessionId || ["completed", "failed", "stopped"].includes(b.activity.phase)) && this.directoryScope.detach(f);
7623
+ for (const [p, y] of Object.entries(d.directory.clients)) {
7624
+ if (!p.startsWith(`background:${this.modelClientScopeId}:`)) continue;
7625
+ const v = Ie(d.conversation, d.directory, y);
7626
+ (f && v.sessionId === this.getState().sessionId || ["completed", "failed", "stopped"].includes(v.activity.phase)) && this.directoryScope.detach(p);
7624
7627
  }
7625
- const p = this.getState();
7626
- for (const f of p.messages) {
7627
- const y = a.get(f.id);
7628
- if ((!y || y.content !== f.content || y.loading !== f.loading) && this.emit("message", f), f.content.trim() && f.content !== y?.content) {
7629
- const b = f.role === "assistant" || f.dataType === "commentary_history";
7630
- b && f.content.startsWith(y?.content ?? "") && this.emit("delta", f.content.slice(y?.content.length ?? 0)), (b || f.dataType === "tool_summary") && this.clearFirstResponseTimer(f.respondsToUserMessageId ?? null, !0);
7628
+ const m = this.getState();
7629
+ for (const p of m.messages) {
7630
+ const y = a.get(p.id);
7631
+ if ((!y || y.content !== p.content || y.loading !== p.loading) && this.emit("message", p), p.content.trim() && p.content !== y?.content) {
7632
+ const v = p.role === "assistant" || p.dataType === "commentary_history";
7633
+ v && p.content.startsWith(y?.content ?? "") && this.emit("delta", p.content.slice(y?.content.length ?? 0)), (v || p.dataType === "tool_summary") && this.clearFirstResponseTimer(p.respondsToUserMessageId ?? null, !0);
7631
7634
  }
7632
7635
  }
7633
- a = new Map(p.messages.map((f) => [f.id, f])), this.rebuildRuntimeInteractions(), this.emit("state", p);
7636
+ a = new Map(m.messages.map((p) => [p.id, p])), this.rebuildRuntimeInteractions(), this.emit("state", m);
7634
7637
  }), this.conversationObservation.wake();
7635
7638
  }
7636
7639
  async initializeDirectory() {
@@ -7644,7 +7647,7 @@ class gt {
7644
7647
  this.modelClientScopeId,
7645
7648
  this.directoryConversationScopeId,
7646
7649
  t
7647
- ) : (this.directoryProvisionalId = x(), await this.directoryScope.provisional(
7650
+ ) : (this.directoryProvisionalId = D(), await this.directoryScope.provisional(
7648
7651
  this.modelClientScopeId,
7649
7652
  this.directoryConversationScopeId,
7650
7653
  this.directoryProvisionalId
@@ -7652,7 +7655,7 @@ class gt {
7652
7655
  }
7653
7656
  }
7654
7657
  handleDirectoryTransportError(e) {
7655
- if (!(e instanceof w) || this.authenticationFailure || !["unauthorized", "update_required", "service_origin_not_allowed", "security_control_enforcement_unavailable"].includes(e.code) && Ye(void 0, e.code).allowed) return;
7658
+ if (!(e instanceof b) || this.authenticationFailure || !["unauthorized", "update_required", "service_origin_not_allowed", "security_control_enforcement_unavailable"].includes(e.code) && Ye(void 0, e.code).allowed) return;
7656
7659
  const t = e.detail && typeof e.detail == "object" ? e.detail : {};
7657
7660
  this.handleServerEvent({
7658
7661
  ...t,
@@ -7673,7 +7676,7 @@ class gt {
7673
7676
  );
7674
7677
  }
7675
7678
  async beginDirectoryProvisional() {
7676
- const e = x();
7679
+ const e = D();
7677
7680
  this.directoryProvisionalId = e, this.directoryConversationScopeId = `conversation:${this.modelClientScopeId}:${e}`, await this.directoryScope.provisional(
7678
7681
  this.modelClientScopeId,
7679
7682
  this.directoryConversationScopeId,
@@ -7685,7 +7688,7 @@ class gt {
7685
7688
  return i.add(t), this.listeners[e] = i, () => i.delete(t);
7686
7689
  }
7687
7690
  getState() {
7688
- const e = this.clientRuntime.engine.getState().slices, t = e.directory.clients[this.modelClientScopeId] ?? this.directoryConversationScopeId, i = ve(e.conversation, e.directory, t), n = Jn(
7691
+ const e = this.clientRuntime.engine.getState().slices, t = e.directory.clients[this.modelClientScopeId] ?? this.directoryConversationScopeId, i = Ie(e.conversation, e.directory, t), n = Jn(
7689
7692
  i,
7690
7693
  i.sessionId ? e.conversation.sessions[i.sessionId]?.queries.current : void 0,
7691
7694
  this.options.backendUrl,
@@ -7713,7 +7716,7 @@ class gt {
7713
7716
  ...this.directoryAuthority,
7714
7717
  type: "conversation.proactive_edit",
7715
7718
  conversationScopeId: i,
7716
- id: `proactive-edit:${x()}`,
7719
+ id: `proactive-edit:${D()}`,
7717
7720
  content: t
7718
7721
  });
7719
7722
  }
@@ -7762,7 +7765,7 @@ class gt {
7762
7765
  }
7763
7766
  async connect() {
7764
7767
  return this.clientRuntime.route("conversation", { core: async () => {
7765
- if (this.socket instanceof U && this.socket.initialReadinessExpired) {
7768
+ if (this.socket instanceof P && this.socket.initialReadinessExpired) {
7766
7769
  const n = this.socket;
7767
7770
  await new Promise((r) => {
7768
7771
  const o = () => {
@@ -7793,11 +7796,11 @@ class gt {
7793
7796
  this.setState({ status: "error", lastError: i });
7794
7797
  return;
7795
7798
  }
7796
- if (this.socket instanceof U) {
7799
+ if (this.socket instanceof P) {
7797
7800
  await this.replaceDefaultTransportCredentials(this.socket);
7798
7801
  return;
7799
7802
  }
7800
- const n = rc(this.options.backendUrl), r = this.options.webSocketFactory?.(n) ?? new U({
7803
+ const n = rc(this.options.backendUrl), r = this.options.webSocketFactory?.(n) ?? new P({
7801
7804
  displaySchema: "canonical",
7802
7805
  backendUrl: this.options.backendUrl,
7803
7806
  entrySurface: this.options.entrySurface,
@@ -7838,12 +7841,12 @@ class gt {
7838
7841
  if (this.socket !== r)
7839
7842
  return;
7840
7843
  const a = yi(o.data);
7841
- if (r instanceof U && a.type === "tool.call" && !mc(a)) {
7844
+ if (r instanceof P && a.type === "tool.call" && !mc(a)) {
7842
7845
  this.setState({ status: "error", lastError: "Invalid tool-call envelope", lastErrorCode: "invalid_tool_call" });
7843
7846
  return;
7844
7847
  }
7845
7848
  const c = this.handleServerEvent(a);
7846
- r instanceof U && a.type === "tool.call" && c === !0 && r.acceptMessage(o);
7849
+ r instanceof P && a.type === "tool.call" && c === !0 && r.acceptMessage(o);
7847
7850
  }), r.addEventListener("sendfailure", (o) => {
7848
7851
  this.socket === r && (this.clearSocketPhaseTimers(), this.stopHeartbeat(), this.socket = null, this.setReconnectingState(), this.scheduleReconnect(), r.readyState !== WebSocket.CLOSED && r.readyState !== WebSocket.CLOSING && r.close());
7849
7852
  }), r.addEventListener("close", (o) => {
@@ -7866,11 +7869,11 @@ class gt {
7866
7869
  } catch (n) {
7867
7870
  if (t !== this.connectionAttemptId || this.state.status === "closed")
7868
7871
  return;
7869
- if (n instanceof w && (n.code === "unauthorized" || n.code === "update_required")) {
7872
+ if (n instanceof b && (n.code === "unauthorized" || n.code === "update_required")) {
7870
7873
  this.handleDirectoryTransportError(n);
7871
7874
  return;
7872
7875
  }
7873
- const r = me(n);
7876
+ const r = ge(n);
7874
7877
  if (pi(n)) {
7875
7878
  N("web-sdk.agent", "Pluno connection attempt failed; retrying", {
7876
7879
  message: r.message,
@@ -7916,7 +7919,7 @@ class gt {
7916
7919
  this.authenticatingWarmupHints.delete(a), !(this.clientRuntime.isDisposed || r !== this.submissionIntentRevision || o && o !== this.authenticatedUserId) && this.warmup(e);
7917
7920
  }, (c) => {
7918
7921
  this.authenticatingWarmupHints.delete(a), this.clientRuntime.isDisposed || N("web-sdk.warmup", "Authentication did not admit the warm-up hint", {
7919
- message: me(c).message
7922
+ message: ge(c).message
7920
7923
  });
7921
7924
  });
7922
7925
  return;
@@ -7924,13 +7927,13 @@ class gt {
7924
7927
  if (!this.token) return;
7925
7928
  const t = this.getState().sessionId, i = this.activeComposerWarmupId ? this.clientRuntime.engine.getState().slices.conversation.operations[this.activeComposerWarmupId] : void 0;
7926
7929
  if (e === "composer_input" && i && ["waiting", "running", "uncertain"].includes(i.phase)) return;
7927
- const n = e === "composer_input" ? x() : null;
7930
+ const n = e === "composer_input" ? D() : null;
7928
7931
  n && (this.activeComposerWarmupId = n), this.clientRuntime.engine.dispatch({
7929
7932
  ...this.directoryAuthority,
7930
7933
  type: "conversation.operation",
7931
7934
  ...n ? { conversationScopeId: this.clientRuntime.engine.getState().slices.directory.clients[this.modelClientScopeId] } : {},
7932
7935
  command: {
7933
- request_id: n ?? x(),
7936
+ request_id: n ?? D(),
7934
7937
  type: "runtime.warmup",
7935
7938
  payload: {
7936
7939
  reason: e,
@@ -7962,9 +7965,9 @@ class gt {
7962
7965
  if (this.clientRuntime.isDisposed) return null;
7963
7966
  const i = e.trim(), n = t.attachments ?? [];
7964
7967
  if (!i && !n.length) return null;
7965
- if (this.options.productVariant === "customer_embedded" && (n.forEach(mn), n.reduce((I, v) => I + v.sizeBytes, 0) > nn))
7968
+ if (this.options.productVariant === "customer_embedded" && (n.forEach(mn), n.reduce((w, I) => w + I.sizeBytes, 0) > nn))
7966
7969
  throw new Error("Embedded attachments must total at most 50 MB per message");
7967
- const r = t.clientMessageId ?? x(), o = ue(this.operationTimingReporter, {
7970
+ const r = t.clientMessageId ?? D(), o = ue(this.operationTimingReporter, {
7968
7971
  operation: "send",
7969
7972
  layer: "sdk",
7970
7973
  requestId: r,
@@ -7974,41 +7977,41 @@ class gt {
7974
7977
  o.mark("submit");
7975
7978
  const a = ai(this.clientRuntime, this.modelClientScopeId, r), c = this.submissionIntentRevision, u = this.authenticatedUserId;
7976
7979
  t.initiatedBy || this.startFirstResponseTimer(r, t.submittedAt);
7977
- const l = o.measure("authentication", () => this.waitForAuthentication()).then(() => null, (I) => me(I));
7980
+ const l = o.measure("authentication", () => this.waitForAuthentication()).then(() => null, (w) => ge(w));
7978
7981
  if (!u) {
7979
- const I = await l;
7980
- if (I) throw I;
7982
+ const w = await l;
7983
+ if (w) throw w;
7981
7984
  }
7982
7985
  if (this.clientRuntime.isDisposed || c !== this.submissionIntentRevision || u && u !== this.authenticatedUserId) return null;
7983
7986
  ai(this.clientRuntime, this.modelClientScopeId, r, a ?? null);
7984
7987
  const d = this.clientRuntime.engine.getState().slices.conversation.submissions[r];
7985
- if (d && (d.content !== i || JSON.stringify(d.attachments.map((I) => I.sourceId)) !== JSON.stringify(n.map((I) => I.id ?? I.storageKey ?? I.sandboxPath)))) throw new Error("User-message identity cannot be reused with different input.");
7986
- const h = V(), m = !d && !t.initiatedBy && this.options.capturePageContent !== !1 && this.lastUserMessagePageUrl !== h.url, f = this.clientRuntime.engine.getState().slices.directory.clients[this.modelClientScopeId];
7987
- if (!f) throw new Error("Conversation selection is not initialized.");
7988
+ if (d && (d.content !== i || JSON.stringify(d.attachments.map((w) => w.sourceId)) !== JSON.stringify(n.map((w) => w.id ?? w.storageKey ?? w.sandboxPath)))) throw new Error("User-message identity cannot be reused with different input.");
7989
+ const h = V(), f = !d && !t.initiatedBy && this.options.capturePageContent !== !1 && this.lastUserMessagePageUrl !== h.url, p = this.clientRuntime.engine.getState().slices.directory.clients[this.modelClientScopeId];
7990
+ if (!p) throw new Error("Conversation selection is not initialized.");
7988
7991
  d || await this.clientRuntime.engine.dispatch({
7989
7992
  ...this.directoryAuthority,
7990
7993
  type: "conversation.submission_stage",
7991
- prepareContext: m,
7994
+ prepareContext: f,
7992
7995
  userMessageId: r,
7993
7996
  requestId: r,
7994
7997
  clientScopeId: this.modelClientScopeId,
7995
- conversationScopeId: f,
7998
+ conversationScopeId: p,
7996
7999
  viewId: `sdk:${this.modelClientScopeId}`,
7997
8000
  rendererRevision: t.submittedAt ?? ++this.composerRevision,
7998
8001
  content: i,
7999
- attachments: n.map((I) => ({
8000
- sourceId: I.id ?? I.storageKey ?? I.sandboxPath,
8001
- name: I.name,
8002
- mimeType: I.mimeType,
8003
- sizeBytes: I.sizeBytes,
8004
- ...I.storageKey || I.sandboxPath ? { uploaded: {
8005
- id: I.id ?? null,
8006
- name: I.name,
8007
- mime_type: I.mimeType,
8008
- size_bytes: I.sizeBytes,
8009
- storage_key: I.storageKey ?? null,
8010
- sandbox_path: I.sandboxPath ?? null,
8011
- file_url: I.fileUrl ?? null
8002
+ attachments: n.map((w) => ({
8003
+ sourceId: w.id ?? w.storageKey ?? w.sandboxPath,
8004
+ name: w.name,
8005
+ mimeType: w.mimeType,
8006
+ sizeBytes: w.sizeBytes,
8007
+ ...w.storageKey || w.sandboxPath ? { uploaded: {
8008
+ id: w.id ?? null,
8009
+ name: w.name,
8010
+ mime_type: w.mimeType,
8011
+ size_bytes: w.sizeBytes,
8012
+ storage_key: w.storageKey ?? null,
8013
+ sandbox_path: w.sandboxPath ?? null,
8014
+ file_url: w.fileUrl ?? null
8012
8015
  } } : {}
8013
8016
  })),
8014
8017
  context: JSON.parse(JSON.stringify({
@@ -8019,36 +8022,36 @@ class gt {
8019
8022
  invocation: nc(t.invocation ?? t.initiatedBy),
8020
8023
  entrySurface: this.options.entrySurface,
8021
8024
  submittedAt: t.submittedAt ?? Date.now()
8022
- }), m && await o.measure("first_frame", () => new Promise((I) => {
8025
+ }), f && await o.measure("first_frame", () => new Promise((w) => {
8023
8026
  if (document.visibilityState !== "visible") {
8024
- setTimeout(I, 0);
8027
+ setTimeout(w, 0);
8025
8028
  return;
8026
8029
  }
8027
- const v = () => {
8028
- cancelAnimationFrame(C), document.removeEventListener("visibilitychange", S), setTimeout(I, 0);
8029
- }, S = () => {
8030
- document.visibilityState !== "visible" && v();
8031
- }, C = requestAnimationFrame(v);
8032
- document.addEventListener("visibilitychange", S);
8030
+ const I = () => {
8031
+ cancelAnimationFrame(C), document.removeEventListener("visibilitychange", _), setTimeout(w, 0);
8032
+ }, _ = () => {
8033
+ document.visibilityState !== "visible" && I();
8034
+ }, C = requestAnimationFrame(I);
8035
+ document.addEventListener("visibilitychange", _);
8033
8036
  })).then(async () => {
8034
8037
  if (this.clientRuntime.isDisposed || c !== this.submissionIntentRevision || u && u !== this.authenticatedUserId) return;
8035
- const I = await o.measure("page_capture", async () => V().url === h.url ? Rs() : "");
8038
+ const w = await o.measure("page_capture", async () => V().url === h.url ? Rs() : "");
8036
8039
  await this.clientRuntime.engine.dispatch({
8037
8040
  ...this.directoryAuthority,
8038
8041
  type: "conversation.context_prepared",
8039
8042
  userMessageId: r,
8040
- pageContent: I,
8043
+ pageContent: w,
8041
8044
  sessionTabs: []
8042
8045
  });
8043
- }).catch((I) => {
8046
+ }).catch((w) => {
8044
8047
  throw !this.clientRuntime.isDisposed && c === this.submissionIntentRevision && this.clientRuntime.engine.accept({
8045
8048
  ...this.directoryAuthority,
8046
8049
  type: "conversation.submission_delivery",
8047
8050
  userMessageId: r,
8048
8051
  requestId: r,
8049
8052
  delivery: "failed",
8050
- error: { code: "page_capture_failed", message: me(I).message, retryable: !1 }
8051
- }), I;
8053
+ error: { code: "page_capture_failed", message: ge(w).message, retryable: !1 }
8054
+ }), w;
8052
8055
  }), o.mark("context_ready");
8053
8056
  const y = await l;
8054
8057
  if (this.clientRuntime.isDisposed || c !== this.submissionIntentRevision || u && u !== this.authenticatedUserId) return null;
@@ -8061,15 +8064,15 @@ class gt {
8061
8064
  delivery: "failed",
8062
8065
  error: { code: "authentication_failed", message: y.message, retryable: !1 }
8063
8066
  }), y;
8064
- const b = this.clientRuntime.engine.getState().slices.conversation.submissions[r], A = b?.invocation === "user" && b.contextPreparation?.pageContent ? b.context.page?.url : null, _ = this.directoryAuthority;
8065
- return await this.clientRuntime.engine.dispatch({ ...this.directoryAuthority, type: "conversation.submit", userMessageId: r, now: Date.now() }), this.clientRuntime.isDisposed ? null : new Promise((I, v) => {
8066
- let S = null, C = null;
8067
+ const v = this.clientRuntime.engine.getState().slices.conversation.submissions[r], A = v?.invocation === "user" && v.contextPreparation?.pageContent ? v.context.page?.url : null, S = this.directoryAuthority;
8068
+ return await this.clientRuntime.engine.dispatch({ ...this.directoryAuthority, type: "conversation.submit", userMessageId: r, now: Date.now() }), this.clientRuntime.isDisposed ? null : new Promise((w, I) => {
8069
+ let _ = null, C = null;
8067
8070
  const Y = () => {
8068
8071
  const T = this.clientRuntime.engine.getState().slices.conversation.submissions[r];
8069
- T && !T.cancelled && T.delivery !== "accepted" && T.delivery !== "failed" || (S?.(), C?.(), T?.delivery === "failed" && !T.cancelled ? v(new Error(T.error?.message ?? "Message delivery failed.")) : (T?.delivery === "accepted" && !T.cancelled && typeof A == "string" && c === this.submissionIntentRevision && _ === this.directoryAuthority && this.clientRuntime.engine.getState().slices.directory.clients[this.modelClientScopeId] === f && (this.lastUserMessagePageUrl = A), I(T?.delivery === "accepted" && !T.cancelled ? r : null)));
8072
+ T && !T.cancelled && T.delivery !== "accepted" && T.delivery !== "failed" || (_?.(), C?.(), T?.delivery === "failed" && !T.cancelled ? I(new Error(T.error?.message ?? "Message delivery failed.")) : (T?.delivery === "accepted" && !T.cancelled && typeof A == "string" && c === this.submissionIntentRevision && S === this.directoryAuthority && this.clientRuntime.engine.getState().slices.directory.clients[this.modelClientScopeId] === p && (this.lastUserMessagePageUrl = A), w(T?.delivery === "accepted" && !T.cancelled ? r : null)));
8070
8073
  };
8071
- S = this.clientRuntime.engine.subscribe(Y), C = this.clientRuntime.onDispose(() => {
8072
- S?.(), I(null);
8074
+ _ = this.clientRuntime.engine.subscribe(Y), C = this.clientRuntime.onDispose(() => {
8075
+ _?.(), w(null);
8073
8076
  }), Y();
8074
8077
  });
8075
8078
  }
@@ -8102,9 +8105,9 @@ class gt {
8102
8105
  } });
8103
8106
  }
8104
8107
  retryLastMessage() {
8105
- const e = this.clientRuntime.engine.getState().slices, t = e.directory.clients[this.modelClientScopeId], i = ve(e.conversation, e.directory, t), n = Xn(i);
8108
+ const e = this.clientRuntime.engine.getState().slices, t = e.directory.clients[this.modelClientScopeId], i = Ie(e.conversation, e.directory, t), n = Xn(i);
8106
8109
  return n ? n.type === "delivery" ? (this.clientRuntime.engine.dispatch({ ...this.directoryAuthority, type: "conversation.submit", userMessageId: n.userMessageId, now: Date.now(), manualRetry: !0 }), !0) : (this.clientRuntime.engine.dispatch({ ...this.directoryAuthority, type: "conversation.operation", command: {
8107
- request_id: x(),
8110
+ request_id: D(),
8108
8111
  type: "chat.retry_last_user_message",
8109
8112
  payload: {
8110
8113
  sessionId: n.sessionId,
@@ -8115,7 +8118,7 @@ class gt {
8115
8118
  }
8116
8119
  createLocalAttachment(e) {
8117
8120
  this.options.productVariant === "customer_embedded" && Hc(e);
8118
- const t = x(), i = {
8121
+ const t = D(), i = {
8119
8122
  id: t,
8120
8123
  name: e.name || "attachment",
8121
8124
  mimeType: fn(e),
@@ -8158,14 +8161,14 @@ class gt {
8158
8161
  } }
8159
8162
  }), new Promise((u, l) => {
8160
8163
  let d, h;
8161
- const m = () => {
8162
- const p = this.clientRuntime.engine.getState().slices, f = p.conversation.operations[c], y = p.directory.authorityId !== o.authorityId || p.directory.clients[this.modelClientScopeId] !== a;
8163
- if (!y && f && !["done", "failed"].includes(f.phase)) return;
8164
- if (d?.(), h?.(), y || !f || f.phase === "failed") {
8165
- l(new Error(f?.error?.message ?? "Attachment preparation was cancelled."));
8164
+ const f = () => {
8165
+ const m = this.clientRuntime.engine.getState().slices, p = m.conversation.operations[c], y = m.directory.authorityId !== o.authorityId || m.directory.clients[this.modelClientScopeId] !== a;
8166
+ if (!y && p && !["done", "failed"].includes(p.phase)) return;
8167
+ if (d?.(), h?.(), y || !p || p.phase === "failed") {
8168
+ l(new Error(p?.error?.message ?? "Attachment preparation was cancelled."));
8166
8169
  return;
8167
8170
  }
8168
- const A = f.result.attachment;
8171
+ const A = p.result.attachment;
8169
8172
  u(pn({
8170
8173
  id: A.id,
8171
8174
  name: A.name,
@@ -8176,9 +8179,9 @@ class gt {
8176
8179
  fileUrl: A.file_url
8177
8180
  }, this.options.backendUrl));
8178
8181
  };
8179
- d = this.clientRuntime.engine.subscribe(m), h = this.clientRuntime.onDispose(() => {
8182
+ d = this.clientRuntime.engine.subscribe(f), h = this.clientRuntime.onDispose(() => {
8180
8183
  d?.(), l(new Error("Product Agent was disposed."));
8181
- }), m();
8184
+ }), f();
8182
8185
  });
8183
8186
  }
8184
8187
  async prepareEmbedAttachmentUpload(e, t) {
@@ -8207,7 +8210,7 @@ class gt {
8207
8210
  ue((t) => this.reportOperationTiming(t), {
8208
8211
  operation: "stop",
8209
8212
  layer: "sdk",
8210
- requestId: x(),
8213
+ requestId: D(),
8211
8214
  clientMessageId: e.activeResponseUserMessageId ?? e.messages.filter((t) => t.role === "user").slice(-1)[0]?.id ?? null,
8212
8215
  sessionId: e.sessionId
8213
8216
  }).mark("stop"), this.stopConversation("user_requested");
@@ -8224,7 +8227,7 @@ class gt {
8224
8227
  type: "conversation.stop",
8225
8228
  clientScopeId: this.modelClientScopeId,
8226
8229
  conversationScopeId: i,
8227
- requestId: x(),
8230
+ requestId: D(),
8228
8231
  reason: e
8229
8232
  });
8230
8233
  }
@@ -8234,7 +8237,7 @@ class gt {
8234
8237
  resetConversationSelection(e) {
8235
8238
  const t = this.getState();
8236
8239
  this.retainNavigatedConversation(), !this.options.keepRunsActiveOnSessionNavigation && e.notifyTransport !== !1 && this.stopConversation("new_chat"), this.cleanupSessionBrowserApis(), e.notifyTransport !== !1 && t.sessionId && this.clientRuntime.engine.dispatch({ ...this.directoryAuthority, type: "conversation.operation", command: {
8237
- request_id: x(),
8240
+ request_id: D(),
8238
8241
  type: "session.reset",
8239
8242
  payload: {
8240
8243
  sessionId: t.sessionId,
@@ -8249,7 +8252,7 @@ class gt {
8249
8252
  t,
8250
8253
  i !== null ? "append" : "replace",
8251
8254
  i ?? void 0
8252
- ), r = this.clientRuntime.engine.getProjection().directory, o = r.queries[D(t)];
8255
+ ), r = this.clientRuntime.engine.getProjection().directory, o = r.queries[U(t)];
8253
8256
  if (o.error) throw new Error(o.error.message);
8254
8257
  return {
8255
8258
  sessions: n.map((a) => this.toSessionHistoryEntry(r.entities[a])),
@@ -8259,7 +8262,7 @@ class gt {
8259
8262
  }
8260
8263
  getSessionHistoryState() {
8261
8264
  return this.clientRuntime.project("directory", { core: () => {
8262
- const e = this.clientRuntime.engine.getProjection().directory, t = e.queries[D(this.getDirectoryQuery("recent"))], n = [e.queries[D(this.getDirectoryQuery("pinned"))], t].filter((d) => d !== void 0), r = Object.values(e.optimisticEntries).reverse(), o = [...new Set(n.flatMap((d) => d.data ?? []))], a = new Set(r.flatMap((d) => d.sessionId ? [d.sessionId] : [])), c = [...r.map((d) => d.id), ...o.filter((d) => !a.has(d))], u = Object.fromEntries([
8265
+ const e = this.clientRuntime.engine.getProjection().directory, t = e.queries[U(this.getDirectoryQuery("recent"))], n = [e.queries[U(this.getDirectoryQuery("pinned"))], t].filter((d) => d !== void 0), r = Object.values(e.optimisticEntries).reverse(), o = [...new Set(n.flatMap((d) => d.data ?? []))], a = new Set(r.flatMap((d) => d.sessionId ? [d.sessionId] : [])), c = [...r.map((d) => d.id), ...o.filter((d) => !a.has(d))], u = Object.fromEntries([
8263
8266
  ...r.map((d) => [d.id, {
8264
8267
  id: d.id,
8265
8268
  title: null,
@@ -8297,13 +8300,13 @@ class gt {
8297
8300
  }
8298
8301
  loadMoreSessionHistory() {
8299
8302
  return this.clientRuntime.route("directory", { core: async () => {
8300
- const e = this.getDirectoryQuery("recent"), t = this.clientRuntime.engine.getState().slices.directory.queries[D(e)];
8303
+ const e = this.getDirectoryQuery("recent"), t = this.clientRuntime.engine.getState().slices.directory.queries[U(e)];
8301
8304
  t?.cursor && await this.directoryObservation.requestPage(e, "append", t.cursor);
8302
8305
  } });
8303
8306
  }
8304
8307
  setSessionPinned(e, t) {
8305
8308
  return this.clientRuntime.route("directory", { core: async () => {
8306
- const i = x();
8309
+ const i = D();
8307
8310
  await this.clientRuntime.engine.dispatch({
8308
8311
  ...this.directoryAuthority,
8309
8312
  type: "directory.mutate",
@@ -8323,7 +8326,7 @@ class gt {
8323
8326
  }
8324
8327
  renameSession(e, t) {
8325
8328
  return this.clientRuntime.route("directory", { core: async () => {
8326
- const i = x();
8329
+ const i = D();
8327
8330
  await this.clientRuntime.engine.dispatch({
8328
8331
  ...this.directoryAuthority,
8329
8332
  type: "directory.mutate",
@@ -8581,7 +8584,7 @@ class gt {
8581
8584
  const t = this.clientRuntime.engine.getProjection().directory;
8582
8585
  if (Object.values(t.optimisticEntries).some((n) => n.id === e && n.sessionId === null)) return;
8583
8586
  !this.options.keepRunsActiveOnSessionNavigation && this.state.sessionId !== e && this.stopConversation("session_switch"), this.retainNavigatedConversation();
8584
- const i = "conversation:" + this.modelClientScopeId + ":" + x();
8587
+ const i = "conversation:" + this.modelClientScopeId + ":" + D();
8585
8588
  this.directoryConversationScopeId = i, this.lastUserMessagePageUrl = null, this.clientRuntime.engine.dispatch({ type: "model.scope_navigate", clientScopeId: this.modelClientScopeId, sessionId: e }), this.directoryScope.bind(this.modelClientScopeId, this.directoryConversationScopeId, e).then(async () => {
8586
8589
  await this.directoryScope.persist(), this.state.sessionId === e && (t.intents[e]?.observe && this.conversationObservation?.refresh(e).catch((n) => this.handleDirectoryTransportError(n)), this.send({ type: "page.upsert", sessionId: e, page: V(), model: this.getModel() }));
8587
8590
  });
@@ -8594,14 +8597,14 @@ class gt {
8594
8597
  if (!this.socket || this.socket.readyState !== WebSocket.OPEN)
8595
8598
  return !1;
8596
8599
  const t = this.socket;
8597
- if ((e.type === "tool.result" || e.type === "run.stop") && t instanceof U) {
8600
+ if ((e.type === "tool.result" || e.type === "run.stop") && t instanceof P) {
8598
8601
  const i = this.queuedClientEvents.find((n) => "sessionId" in n && n.sessionId === e.sessionId && (e.type === "tool.result" && n.type === "tool.result" && n.callId === e.callId || e.type === "run.stop" && n.type === "run.stop" && n.expectedUserMessageId === e.expectedUserMessageId)) ?? e;
8599
8602
  return this.queuedClientEvents.includes(i) || this.queuedClientEvents.push(i), ce(this.options.clientId, this.queuedClientEvents), this.pendingRetainedCommandDeliveries.has(i) || (this.pendingRetainedCommandDeliveries.add(i), t.sendRetainedCommand(z(i)).then((n) => {
8600
8603
  this.pendingRetainedCommandDeliveries.delete(i), n && (this.queuedClientEvents = this.queuedClientEvents.filter((r) => r !== i), ce(this.options.clientId, this.queuedClientEvents));
8601
8604
  })), !0;
8602
8605
  }
8603
8606
  try {
8604
- return t.send(JSON.stringify(e)), ke("client_event", e.type, Nt(e)), !0;
8607
+ return t.send(JSON.stringify(e)), me("client_event", e.type, Nt(e)), !0;
8605
8608
  } catch (i) {
8606
8609
  return N("web-sdk.agent", "Pluno socket send failed; scheduling reconnect", {
8607
8610
  message: i instanceof Error ? i.message : String(i),
@@ -8642,8 +8645,8 @@ class gt {
8642
8645
  ...t,
8643
8646
  ...t.renderedError?.runId ? { runId: t.renderedError.runId } : {}
8644
8647
  }, { responseDiagnostics: o, renderedError: a, uiInvariant: c, timings: u, ...l } = r;
8645
- for (const d of u ?? []) ke("client_event", "operation_timing", { ...d });
8646
- if (ke("client_event", "runtime.health", { ...l, signalName: e }), this.options.productVariant === "customer_embedded" || !this.socket || this.socket.readyState !== WebSocket.OPEN || this.authenticatedSocket !== this.socket) {
8648
+ for (const d of u ?? []) me("client_event", "operation_timing", { ...d });
8649
+ if (me("client_event", "runtime.health", { ...l, signalName: e }), this.options.productVariant === "customer_embedded" || !this.socket || this.socket.readyState !== WebSocket.OPEN || this.authenticatedSocket !== this.socket) {
8647
8650
  this.queueHealthDiagnostic(r);
8648
8651
  return;
8649
8652
  }
@@ -8714,7 +8717,7 @@ class gt {
8714
8717
  }
8715
8718
  /** @internal */
8716
8719
  reportTransportDiagnostic(e, t = {}) {
8717
- const i = typeof navigator > "u" ? "unknown" : navigator.onLine === !1 ? "offline" : "online", n = `${e}:${t.closeCode ?? "none"}:${i}`, r = (/* @__PURE__ */ new Date()).toISOString(), o = this.transportDiagnosticEpisodes.get(n), a = {
8720
+ const i = typeof navigator > "u" ? "unknown" : navigator.onLine === !1 ? "offline" : "online", n = `${e}:${t.requestId ?? t.connectionAttemptId ?? "none"}:${t.closeCode ?? "none"}:${i}`, r = (/* @__PURE__ */ new Date()).toISOString(), o = this.transportDiagnosticEpisodes.get(n), a = {
8718
8721
  id: o?.id ?? crypto.randomUUID(),
8719
8722
  phase: e,
8720
8723
  entrySurface: this.options.entrySurface,
@@ -8725,7 +8728,7 @@ class gt {
8725
8728
  connectivity: i,
8726
8729
  ...t
8727
8730
  };
8728
- this.transportDiagnosticEpisodes.set(n, a), [1, 3, 10, 30, 100].includes(a.occurrenceCount) && (this.pendingTransportDiagnostics = [
8731
+ this.transportDiagnosticEpisodes.set(n, a), this.transportDiagnosticEpisodes.size > 20 && this.transportDiagnosticEpisodes.delete(this.transportDiagnosticEpisodes.keys().next().value), e.startsWith("auth_") && me("client_event", "authentication_diagnostic", { ...a }), [1, 3, 10, 30, 100].includes(a.occurrenceCount) && (this.pendingTransportDiagnostics = [
8729
8732
  ...this.pendingTransportDiagnostics.filter((c) => c.id !== a.id),
8730
8733
  a
8731
8734
  ], this.pendingTransportDiagnostics.splice(0, Math.max(0, this.pendingTransportDiagnostics.length - 20)), this.flushClientDiagnostics());
@@ -8736,6 +8739,7 @@ class gt {
8736
8739
  }
8737
8740
  /** @internal */
8738
8741
  async flushClientDiagnostics() {
8742
+ if (this.refreshingDefaultCredentials) return;
8739
8743
  if (this.clientDiagnosticsFlush)
8740
8744
  return await this.clientDiagnosticsFlush;
8741
8745
  if (this.clientDiagnosticsRetryTimer !== null || this.pendingTransportDiagnostics.length === 0 && this.pendingHealthDiagnostics.length === 0)
@@ -8759,12 +8763,16 @@ class gt {
8759
8763
  this.scheduleClientDiagnosticsRetry();
8760
8764
  return;
8761
8765
  }
8762
- const t = this.pendingTransportDiagnostics.slice(0, 20), i = this.pendingHealthDiagnostics.slice(0, 20), n = this.options.productVariant === "customer_embedded" ? "/api/product-agent/embed/diagnostics" : "/api/product-agent/runtime/diagnostics";
8766
+ const t = this.pendingTransportDiagnostics.slice(0, 20), i = this.pendingHealthDiagnostics.slice(0, 20), n = [...t].reverse().find((a) => a.phase.startsWith("auth_")), r = n?.requestId ?? n?.connectionAttemptId, o = this.options.productVariant === "customer_embedded" ? "/api/product-agent/embed/diagnostics" : "/api/product-agent/runtime/diagnostics";
8763
8767
  try {
8764
- const r = await fetch(new URL(n, this.options.backendUrl), {
8768
+ const a = await fetch(new URL(o, this.options.backendUrl), {
8765
8769
  method: "POST",
8766
8770
  headers: {
8767
8771
  "content-type": "application/json",
8772
+ // Authentication can reject diagnostics too. These bounded hints let that rejection log retain
8773
+ // the recovery outcome without accepting an unauthenticated body or weakening access checks.
8774
+ ...n ? { "x-product-agent-auth-phase": n.phase } : {},
8775
+ ...r ? { "x-product-agent-auth-request-id": r } : {},
8768
8776
  authorization: this.options.productVariant === "customer_embedded" ? `Bearer ${e}` : e
8769
8777
  },
8770
8778
  body: JSON.stringify({
@@ -8775,24 +8783,24 @@ class gt {
8775
8783
  }),
8776
8784
  signal: AbortSignal.timeout(1e4)
8777
8785
  });
8778
- if (r.status === 401 || r.status === 403) {
8779
- const c = new Set(t.map((l) => l.id)), u = new Set(i.map((l) => l.id));
8786
+ if (a.status === 401 || a.status === 403) {
8787
+ const l = new Set(t.map((h) => h.id)), d = new Set(i.map((h) => h.id));
8780
8788
  this.pendingTransportDiagnostics = this.pendingTransportDiagnostics.filter(
8781
- (l) => !c.has(l.id)
8789
+ (h) => !l.has(h.id)
8782
8790
  ), this.pendingHealthDiagnostics = this.pendingHealthDiagnostics.filter(
8783
- (l) => !u.has(l.id)
8791
+ (h) => !d.has(h.id)
8784
8792
  );
8785
8793
  return;
8786
8794
  }
8787
- if (!r.ok)
8788
- throw new Error(`Client diagnostic upload failed (${r.status})`);
8789
- const o = new Map(
8790
- t.map((c) => [c.id, c.occurrenceCount])
8791
- ), a = new Set(i.map((c) => c.id));
8795
+ if (!a.ok)
8796
+ throw new Error(`Client diagnostic upload failed (${a.status})`);
8797
+ const c = new Map(
8798
+ t.map((l) => [l.id, l.occurrenceCount])
8799
+ ), u = new Set(i.map((l) => l.id));
8792
8800
  this.pendingTransportDiagnostics = this.pendingTransportDiagnostics.filter(
8793
- (c) => !o.has(c.id) || c.occurrenceCount > (o.get(c.id) ?? 0)
8801
+ (l) => !c.has(l.id) || l.occurrenceCount > (c.get(l.id) ?? 0)
8794
8802
  ), this.pendingHealthDiagnostics = this.pendingHealthDiagnostics.filter(
8795
- (c) => !a.has(c.id)
8803
+ (l) => !u.has(l.id)
8796
8804
  );
8797
8805
  } catch {
8798
8806
  this.scheduleClientDiagnosticsRetry();
@@ -8838,7 +8846,7 @@ class gt {
8838
8846
  }
8839
8847
  flushQueuedClientEvents() {
8840
8848
  const e = [...this.queuedClientEvents];
8841
- this.queuedClientEvents = this.queuedClientEvents.filter((t) => (t.type === "tool.result" || t.type === "run.stop") && this.socket instanceof U), ce(this.options.clientId, this.queuedClientEvents);
8849
+ this.queuedClientEvents = this.queuedClientEvents.filter((t) => (t.type === "tool.result" || t.type === "run.stop") && this.socket instanceof P), ce(this.options.clientId, this.queuedClientEvents);
8842
8850
  for (let t = 0; t < e.length; t++)
8843
8851
  if (!this.sendNow(z(e[t]))) {
8844
8852
  this.queuedClientEvents.unshift(...e.slice(t).filter((i) => !this.queuedClientEvents.includes(i)));
@@ -8857,7 +8865,7 @@ class gt {
8857
8865
  const u = this.directoryAuthority;
8858
8866
  this.directoryObservation.dispose(), this.conversationAdapterGeneration++, this.conversationObservation?.dispose(), this.directoryAuthority = { authorityId: n, generation: u.generation + 1 }, this.clientRuntime.engine.dispatch({ ...this.directoryAuthority, type: "directory.authority_replace", expectedGeneration: u.generation }), this.createDirectoryAdapters();
8859
8867
  const l = this.getModel();
8860
- o || (this.pendingWidgetLifecycleEvents = []), this.resetForAuthenticationScopeChange(), c && (this.directoryConversationScopeId = `conversation:${this.modelClientScopeId}:${x()}`, this.clientRuntime.engine.dispatch({ type: "model.scope_navigate", clientScopeId: this.modelClientScopeId, sessionId: c }), this.directoryScope.bind(this.modelClientScopeId, this.directoryConversationScopeId, c).then(() => this.directoryScope.persist())), l && this.setModel(l);
8868
+ o || (this.pendingWidgetLifecycleEvents = []), this.resetForAuthenticationScopeChange(), c && (this.directoryConversationScopeId = `conversation:${this.modelClientScopeId}:${D()}`, this.clientRuntime.engine.dispatch({ type: "model.scope_navigate", clientScopeId: this.modelClientScopeId, sessionId: c }), this.directoryScope.bind(this.modelClientScopeId, this.directoryConversationScopeId, c).then(() => this.directoryScope.persist())), l && this.setModel(l);
8861
8869
  }
8862
8870
  if (r || o) {
8863
8871
  const u = this.directoryAuthority;
@@ -8865,19 +8873,19 @@ class gt {
8865
8873
  if (this.clientRuntime.isDisposed || this.directoryAuthority !== u) return;
8866
8874
  let l = !1;
8867
8875
  for (const d of a) {
8868
- const h = this.clientRuntime.engine.getState().slices.directory, m = h.clients[this.modelClientScopeId];
8869
- if (d.type === "run.stop" && h.selections[m]?.sessionId === d.payload.sessionId) {
8876
+ const h = this.clientRuntime.engine.getState().slices.directory, f = h.clients[this.modelClientScopeId];
8877
+ if (d.type === "run.stop" && h.selections[f]?.sessionId === d.payload.sessionId) {
8870
8878
  if (l) continue;
8871
8879
  l = !0;
8872
- const p = a.filter((f) => f.type === "run.stop" && f.payload.sessionId === d.payload.sessionId).map((f) => String(f.payload.expectedUserMessageId));
8880
+ const m = a.filter((p) => p.type === "run.stop" && p.payload.sessionId === d.payload.sessionId).map((p) => String(p.payload.expectedUserMessageId));
8873
8881
  await this.clientRuntime.engine.dispatch({
8874
8882
  ...u,
8875
8883
  type: "conversation.stop",
8876
8884
  clientScopeId: this.modelClientScopeId,
8877
- conversationScopeId: m,
8885
+ conversationScopeId: f,
8878
8886
  requestId: d.request_id,
8879
8887
  reason: d.payload.reason,
8880
- userMessageIds: p
8888
+ userMessageIds: m
8881
8889
  });
8882
8890
  } else (d.type === "run.stop" || d.type === "session.reset") && await this.clientRuntime.engine.dispatch({ ...u, type: "conversation.operation", command: d });
8883
8891
  }
@@ -8905,7 +8913,7 @@ class gt {
8905
8913
  }
8906
8914
  }
8907
8915
  handleServerEvent(e) {
8908
- if (ke("server_event", e.type, Nt(e)), ["conversation.item.updated", "conversation.item.removed", "conversation.item.stream_finished", "conversation.execution.updated", "conversation.interaction.updated", "conversation.follow_ups.updated"].includes(e.type)) {
8916
+ if (me("server_event", e.type, Nt(e)), ["conversation.item.updated", "conversation.item.removed", "conversation.item.stream_finished", "conversation.execution.updated", "conversation.interaction.updated", "conversation.follow_ups.updated"].includes(e.type)) {
8909
8917
  this.conversationObservation?.receive(e);
8910
8918
  return;
8911
8919
  }
@@ -8976,13 +8984,30 @@ class gt {
8976
8984
  });
8977
8985
  return;
8978
8986
  }
8987
+ if (!this.options.webSocketFactory && (e.code === "unauthorized" || e.code === "401") && e.reason === "invalid_token" && (this.canRefreshInvalidCredential() || this.credentialRecovery !== null)) {
8988
+ const t = this.socket;
8989
+ if (t instanceof P) {
8990
+ this.credentialRecovery || this.refreshCredentials(
8991
+ t,
8992
+ !0,
8993
+ new b("", "unauthorized", !1, {
8994
+ reason: e.reason,
8995
+ authTransport: e.authTransport,
8996
+ requestId: e.requestId,
8997
+ authEndpoint: e.authEndpoint
8998
+ })
8999
+ ).catch(() => {
9000
+ });
9001
+ return;
9002
+ }
9003
+ }
8979
9004
  if ((e.code === "unauthorized" || e.code === "401") && e.reason === "token_expired" && e.retryable === !0 && this.options.tokenProvider) {
8980
9005
  const t = this.socket;
8981
- t instanceof U ? this.refreshDefaultTransportCredentials(t) : (this.invalidateProviderToken(), this.clearSocketPhaseTimers(), this.stopHeartbeat(), this.setReconnectingState(), this.socket = null, this.scheduleReconnect(), t?.close());
9006
+ t instanceof P ? this.refreshDefaultTransportCredentials(t) : (this.invalidateProviderToken(), this.clearSocketPhaseTimers(), this.stopHeartbeat(), this.setReconnectingState(), this.socket = null, this.scheduleReconnect(), t?.close());
8982
9007
  return;
8983
9008
  }
8984
9009
  if (!this.options.webSocketFactory && (e.code === "unauthorized" || e.code === "update_required" || e.code === "executor_replaced")) {
8985
- this.stopAuthentication(new w(String(e.message), String(e.code), !1));
9010
+ this.stopAuthentication(new b(String(e.message), String(e.code), !1, { reason: e.reason, authTransport: "socket" }));
8986
9011
  return;
8987
9012
  }
8988
9013
  ["unauthorized", "update_required", "executor_replaced", "connection_failed"].includes(String(e.code)) && this.setState({ status: "error", lastError: String(e.message), lastErrorCode: String(e.code) });
@@ -9142,7 +9167,7 @@ class gt {
9142
9167
  Math.max(La(this.reconnectAttempts), e)
9143
9168
  );
9144
9169
  this.reconnectAttempts += 1, this.reconnectTimer = window.setTimeout(() => {
9145
- this.reconnectTimer = null, (this.refreshingDefaultCredentials && this.socket instanceof U ? this.refreshDefaultTransportCredentials(this.socket) : this.connect()).catch((n) => {
9170
+ this.reconnectTimer = null, (this.refreshingDefaultCredentials && this.socket instanceof P ? this.refreshDefaultTransportCredentials(this.socket) : this.connect()).catch((n) => {
9146
9171
  N("web-sdk.agent", "Pluno reconnect failed; retrying", {
9147
9172
  message: n instanceof Error ? n.message : String(n),
9148
9173
  queuedClientEventCount: this.queuedClientEvents.length,
@@ -9174,43 +9199,70 @@ class gt {
9174
9199
  local_runtime_client_id: this.options.localRuntimeClientId ?? void 0
9175
9200
  }, o, r), this.refreshingDefaultCredentials = !1;
9176
9201
  }
9202
+ /** @internal */
9203
+ canRefreshInvalidCredential() {
9204
+ return !this.invalidCredentialRecoveryAttempted && !this.options.token && !!this.options.tokenProvider && this.options.productVariant === "personal" && ["main_web_chat", "automation"].includes(this.options.entrySurface);
9205
+ }
9206
+ /** @internal */
9207
+ authenticationDiagnostic(e) {
9208
+ const t = e?.detail;
9209
+ return {
9210
+ authReason: ["invalid_token", "token_expired", "missing_token", "user_not_found"].includes(t?.reason ?? "") ? t.reason : "unknown",
9211
+ authTransport: t?.authTransport === "http" ? "http" : "socket",
9212
+ ...t?.requestId && /^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/.test(t.requestId) ? { requestId: t.requestId, .../^(runtime|embed|extension|conversations):(snapshot|me|bootstrap|commands|activity|session-history|other)$/.test(t.authEndpoint ?? "") ? { authEndpoint: t.authEndpoint } : {} } : {},
9213
+ ...this.socket instanceof P ? { connectionAttemptId: this.socket.connectionAttempt?.connectionAttemptId } : {}
9214
+ };
9215
+ }
9177
9216
  stopAuthentication(e) {
9178
- this.authenticationFailure = e, this.rejectedTransportToken = e.code === "403" ? null : this.token, this.refreshingDefaultCredentials = !1, this.reconnectTimer !== null && window.clearTimeout(this.reconnectTimer), this.reconnectTimer = null, this.clearSocketPhaseTimers(), this.stopHeartbeat();
9217
+ this.reportTransportDiagnostic("auth_rejected", this.authenticationDiagnostic(e)), e.code === "unauthorized" && (e = new b("Your chat session could not be refreshed. Reload the page to reconnect.", e.code, !1, e.detail)), this.authenticationFailure = e, this.rejectedTransportToken = e.code === "403" ? null : this.token, this.refreshingDefaultCredentials = !1, this.reconnectTimer !== null && window.clearTimeout(this.reconnectTimer), this.reconnectTimer = null, this.clearSocketPhaseTimers(), this.stopHeartbeat();
9179
9218
  const t = this.socket;
9180
9219
  this.socket = null, this.setState({ status: "error", lastError: e.message, lastErrorCode: e.code }), t?.close(), this.directoryObservation?.reconcile(), this.conversationObservation?.wake();
9181
9220
  }
9182
9221
  async recoverHttpAuthentication(e, t, i) {
9183
9222
  if (this.authenticationFailure) throw this.authenticationFailure;
9184
9223
  const n = t.detail;
9185
- if (t.code === "unauthorized" && n?.reason === "token_expired" && n.retryable === !0 && this.options.tokenProvider && i) {
9224
+ if (t.code === "unauthorized" && n?.reason === "invalid_token" && this.invalidCredentialRecoveryAttempted) {
9186
9225
  if (this.credentialRecovery) return this.credentialRecovery;
9187
9226
  if (this.directoryHttp.auth.token !== e) return;
9188
- const r = this.socket;
9189
- if (r instanceof U) return this.refreshCredentials(r);
9227
+ }
9228
+ const r = n?.reason === "invalid_token" && this.canRefreshInvalidCredential();
9229
+ if (t.code === "unauthorized" && (n?.reason === "token_expired" && n.retryable === !0 || r) && this.options.tokenProvider && i) {
9230
+ if (this.credentialRecovery) return this.credentialRecovery;
9231
+ if (this.directoryHttp.auth.token !== e) return;
9232
+ const o = this.socket;
9233
+ if (o instanceof P) return this.refreshCredentials(o, r, t);
9190
9234
  if (this.options.webSocketFactory) throw t;
9191
9235
  }
9192
9236
  throw this.stopAuthentication(t), t;
9193
9237
  }
9194
- refreshCredentials(e) {
9238
+ refreshCredentials(e, t = !1, i) {
9195
9239
  if (this.credentialRecovery) return this.credentialRecovery;
9196
- this.credentialRecoveryFailure = null, this.clearSocketPhaseTimers(), this.stopHeartbeat(), this.refreshingDefaultCredentials = !0, e.pause(), this.setReconnectingState(), this.directoryObservation.reconcile(), this.conversationObservation?.wake();
9197
- const t = (async () => {
9198
- const i = await this.acquireToken("connect", { forceRefresh: !0 });
9240
+ this.credentialRecoveryFailure = null;
9241
+ const n = this.token, r = this.authenticationDiagnostic(i ?? new b(
9242
+ "",
9243
+ "unauthorized",
9244
+ !1,
9245
+ { reason: t ? "invalid_token" : "token_expired" }
9246
+ ));
9247
+ t && (this.invalidCredentialRecoveryAttempted = !0), this.clearSocketPhaseTimers(), this.stopHeartbeat(), this.refreshingDefaultCredentials = !0, this.reportTransportDiagnostic("auth_refresh_started", r), e.pause(), this.setReconnectingState(), this.directoryObservation.reconcile(), this.conversationObservation?.wake();
9248
+ const o = (async () => {
9249
+ const a = await this.acquireToken("connect", { forceRefresh: !0 });
9199
9250
  if (this.socket !== e || this.state.status === "closed" || this.clientRuntime.isDisposed)
9200
- throw new w("Conversation authority was retired.", "authority_retired", !0);
9201
- if (!i) throw new re("Pluno token provider did not return a token", !1);
9202
- this.directoryHttp.auth.token = i, await this.replaceDefaultTransportCredentials(e);
9203
- })().catch((i) => {
9204
- if (this.credentialRecoveryFailure = me(i), this.socket !== e || this.state.status === "closed") throw i;
9205
- if (i instanceof w && ["unauthorized", "403", "update_required"].includes(i.code) || !pi(i)) {
9206
- const n = i instanceof w ? i : new w("Your session could not be refreshed. Reconnect to continue.", "unauthorized", !1);
9207
- throw this.stopAuthentication(n), n;
9251
+ throw new b("Conversation authority was retired.", "authority_retired", !0);
9252
+ if (!a) throw new re("Pluno token provider did not return a token", !1);
9253
+ if (t && a === n) throw new b("Credential did not change.", "unauthorized", !1);
9254
+ this.directoryHttp.auth.token = a, await this.replaceDefaultTransportCredentials(e), this.reportTransportDiagnostic("auth_refresh_validated", r);
9255
+ })().catch((a) => {
9256
+ if (this.reportTransportDiagnostic("auth_refresh_failed", r), this.credentialRecoveryFailure = ge(a), this.socket !== e || this.state.status === "closed") throw a;
9257
+ if (a instanceof b && ["unauthorized", "403", "update_required"].includes(a.code) || !pi(a)) {
9258
+ const c = a instanceof b ? a : new b("Your session could not be refreshed. Reconnect to continue.", "unauthorized", !1);
9259
+ throw this.stopAuthentication(c), c;
9208
9260
  }
9209
- throw this.scheduleReconnect(), i;
9261
+ throw this.scheduleReconnect(), a;
9210
9262
  }).finally(() => {
9211
- this.credentialRecovery === t && (this.credentialRecovery = null);
9263
+ this.credentialRecovery === o && (this.credentialRecovery = null), this.flushClientDiagnostics();
9212
9264
  });
9213
- return this.credentialRecovery = t, t;
9265
+ return this.credentialRecovery = o, o;
9214
9266
  }
9215
9267
  async refreshDefaultTransportCredentials(e) {
9216
9268
  this.authenticationFailure || await this.refreshCredentials(e).catch((t) => {
@@ -9249,7 +9301,7 @@ class gt {
9249
9301
  this.clientRuntime.isDisposed || (this.state = e, this.clientRuntime.engine.dispatch({ type: "activeUsers.authenticate", authenticated: !!(this.token && this.state.user && this.state.status !== "closed") }), this.rebuildRuntimeInteractions(), this.emit("state", this.getState()));
9250
9302
  }
9251
9303
  setReconnectingState() {
9252
- if (this.socket instanceof U && this.socket.initialReadinessExpired) return;
9304
+ if (this.socket instanceof P && this.socket.initialReadinessExpired) return;
9253
9305
  this.conversationObservation?.wake();
9254
9306
  const e = this.state.lastError !== null && (!this.state.isThinking || this.state.lastErrorCode === "connection_failed");
9255
9307
  this.setState({
@@ -9269,47 +9321,47 @@ function $a(s) {
9269
9321
  }
9270
9322
  function Fa() {
9271
9323
  const s = /* @__PURE__ */ new Set(), e = (h) => {
9272
- s.forEach((m) => {
9324
+ s.forEach((f) => {
9273
9325
  try {
9274
- m(h);
9326
+ f(h);
9275
9327
  } catch {
9276
9328
  }
9277
9329
  });
9278
- }, t = window.fetch, i = XMLHttpRequest.prototype.open, n = XMLHttpRequest.prototype.setRequestHeader, r = XMLHttpRequest.prototype.send, o = function(m, p) {
9279
- const f = Date.now();
9330
+ }, t = window.fetch, i = XMLHttpRequest.prototype.open, n = XMLHttpRequest.prototype.setRequestHeader, r = XMLHttpRequest.prototype.send, o = function(f, m) {
9331
+ const p = Date.now();
9280
9332
  let y;
9281
9333
  try {
9282
- y = t.call(this, m, p);
9283
- } catch (b) {
9284
- throw b;
9334
+ y = t.call(this, f, m);
9335
+ } catch (v) {
9336
+ throw v;
9285
9337
  }
9286
9338
  try {
9287
- const b = m instanceof Request ? m : null, A = Jc(m, b), _ = gn(p?.headers ?? b?.headers);
9288
- if (!ge(A, _, p?.body)) {
9289
- const v = {
9339
+ const v = f instanceof Request ? f : null, A = Jc(f, v), S = gn(m?.headers ?? v?.headers);
9340
+ if (!ye(A, S, m?.body)) {
9341
+ const I = {
9290
9342
  requestId: Ht("fetch"),
9291
9343
  url: te(A, jt),
9292
- method: (p?.method ?? b?.method ?? "GET").toUpperCase(),
9293
- requestHeaders: _,
9294
- requestBody: _i(p?.body),
9344
+ method: (m?.method ?? v?.method ?? "GET").toUpperCase(),
9345
+ requestHeaders: S,
9346
+ requestBody: _i(m?.body),
9295
9347
  resourceType: "fetch",
9296
- startedAt: new Date(f).toISOString()
9348
+ startedAt: new Date(p).toISOString()
9297
9349
  };
9298
9350
  y.then(
9299
- (S) => {
9300
- Xc(S, v, f, e).catch(() => {
9351
+ (_) => {
9352
+ Xc(_, I, p, e).catch(() => {
9301
9353
  e({
9302
- ...v,
9303
- responseStatus: S.status,
9304
- durationMs: Date.now() - f
9354
+ ...I,
9355
+ responseStatus: _.status,
9356
+ durationMs: Date.now() - p
9305
9357
  });
9306
9358
  });
9307
9359
  },
9308
- (S) => {
9360
+ (_) => {
9309
9361
  e({
9310
- ...v,
9311
- errorText: te(S instanceof Error ? S.message : String(S)),
9312
- durationMs: Date.now() - f
9362
+ ...I,
9363
+ errorText: te(_ instanceof Error ? _.message : String(_)),
9364
+ durationMs: Date.now() - p
9313
9365
  });
9314
9366
  }
9315
9367
  );
@@ -9317,42 +9369,42 @@ function Fa() {
9317
9369
  } catch {
9318
9370
  }
9319
9371
  return y;
9320
- }, a = function(m, p, f, y, b) {
9321
- const A = i.call(this, m, p, f ?? !0, y ?? void 0, b ?? void 0), _ = typeof p == "string" ? p : p.toString();
9372
+ }, a = function(f, m, p, y, v) {
9373
+ const A = i.call(this, f, m, p ?? !0, y ?? void 0, v ?? void 0), S = typeof m == "string" ? m : m.toString();
9322
9374
  return $t.set(this, {
9323
9375
  requestId: Ht("xhr"),
9324
- method: String(m ?? "GET").toUpperCase(),
9325
- url: te(_, jt),
9376
+ method: String(f ?? "GET").toUpperCase(),
9377
+ url: te(S, jt),
9326
9378
  requestHeaders: {},
9327
9379
  startedAtMs: Date.now(),
9328
9380
  startedAt: (/* @__PURE__ */ new Date()).toISOString(),
9329
- excluded: ge(_)
9381
+ excluded: ye(S)
9330
9382
  }), A;
9331
- }, c = function(m, p) {
9332
- const f = n.call(this, m, p), y = $t.get(this);
9333
- return y && Object.keys(y.requestHeaders).length < Es && (y.requestHeaders[m] = Cs(m, p), y.excluded = y.excluded || ge(y.url, y.requestHeaders)), f;
9334
- }, u = function(m) {
9383
+ }, c = function(f, m) {
9384
+ const p = n.call(this, f, m), y = $t.get(this);
9385
+ return y && Object.keys(y.requestHeaders).length < Es && (y.requestHeaders[f] = Cs(f, m), y.excluded = y.excluded || ye(y.url, y.requestHeaders)), p;
9386
+ }, u = function(f) {
9335
9387
  try {
9336
- const p = $t.get(this);
9337
- p && (p.excluded = p.excluded || ge(p.url, p.requestHeaders, m), p.requestBody = _i(m), p.excluded || this.addEventListener(
9388
+ const m = $t.get(this);
9389
+ m && (m.excluded = m.excluded || ye(m.url, m.requestHeaders, f), m.requestBody = _i(f), m.excluded || this.addEventListener(
9338
9390
  "loadend",
9339
9391
  () => {
9340
9392
  queueMicrotask(() => {
9341
9393
  try {
9342
- const f = id(this.getAllResponseHeaders());
9394
+ const p = id(this.getAllResponseHeaders());
9343
9395
  e({
9344
- requestId: p.requestId,
9345
- url: p.url,
9346
- method: p.method,
9347
- requestHeaders: p.requestHeaders,
9348
- requestBody: p.requestBody,
9396
+ requestId: m.requestId,
9397
+ url: m.url,
9398
+ method: m.method,
9399
+ requestHeaders: m.requestHeaders,
9400
+ requestBody: m.requestBody,
9349
9401
  resourceType: "xhr",
9350
9402
  responseStatus: this.status,
9351
- responseHeaders: f,
9352
- responseBody: Zc(this, f),
9403
+ responseHeaders: p,
9404
+ responseBody: Zc(this, p),
9353
9405
  errorText: this.status === 0 ? "XHR request failed or was aborted" : void 0,
9354
- startedAt: p.startedAt,
9355
- durationMs: Date.now() - p.startedAtMs
9406
+ startedAt: m.startedAt,
9407
+ durationMs: Date.now() - m.startedAtMs
9356
9408
  });
9357
9409
  } catch {
9358
9410
  return;
@@ -9363,7 +9415,7 @@ function Fa() {
9363
9415
  ));
9364
9416
  } catch {
9365
9417
  }
9366
- return r.call(this, m ?? null);
9418
+ return r.call(this, f ?? null);
9367
9419
  };
9368
9420
  try {
9369
9421
  window.fetch = o;
@@ -9384,19 +9436,19 @@ function Fa() {
9384
9436
  let l = null;
9385
9437
  if (typeof PerformanceObserver < "u") {
9386
9438
  l = new PerformanceObserver((h) => {
9387
- for (const m of h.getEntries()) {
9388
- const p = m;
9389
- if (p.initiatorType === "fetch" || p.initiatorType === "xmlhttprequest" || ge(p.name))
9439
+ for (const f of h.getEntries()) {
9440
+ const m = f;
9441
+ if (m.initiatorType === "fetch" || m.initiatorType === "xmlhttprequest" || ye(m.name))
9390
9442
  continue;
9391
- const f = performance.timeOrigin + p.startTime;
9443
+ const p = performance.timeOrigin + m.startTime;
9392
9444
  e({
9393
9445
  requestId: Ht("resource"),
9394
- url: te(p.name, jt),
9446
+ url: te(m.name, jt),
9395
9447
  method: "GET",
9396
9448
  resourceType: "resource",
9397
- responseStatus: p.responseStatus,
9398
- startedAt: new Date(f).toISOString(),
9399
- durationMs: p.duration
9449
+ responseStatus: m.responseStatus,
9450
+ startedAt: new Date(p).toISOString(),
9451
+ durationMs: m.duration
9400
9452
  });
9401
9453
  }
9402
9454
  });
@@ -9699,32 +9751,32 @@ function dc() {
9699
9751
  function Rs() {
9700
9752
  if (!document.body)
9701
9753
  return "";
9702
- const s = [], e = [], t = (f, y) => {
9703
- const b = we(y);
9704
- !b || e.includes(b) || (s.push([f, b]), e.push(b));
9754
+ const s = [], e = [], t = (p, y) => {
9755
+ const v = Se(y);
9756
+ !v || e.includes(v) || (s.push([p, v]), e.push(v));
9705
9757
  };
9706
9758
  t("Selected text", window.getSelection()?.toString() ?? "");
9707
9759
  const i = "[role='dialog'], [role='alertdialog'], dialog[open], [aria-modal='true']", n = Array.from(document.querySelectorAll(i)).filter(
9708
- (f) => on(f) && !f.parentElement?.closest(i)
9760
+ (p) => on(p) && !p.parentElement?.closest(i)
9709
9761
  );
9710
- for (const f of n.slice(0, 3))
9711
- t("Active overlay", Ft(Pe(f), e));
9762
+ for (const p of n.slice(0, 3))
9763
+ t("Active overlay", Ft(Pe(p), e));
9712
9764
  const r = lc(), o = r ? Ft(Pe(r), e) : "";
9713
9765
  t("Main page content", o), t("Additional visible page text", Ft(Pe(document.body), e));
9714
- const a = s.map(([f, y]) => `${f}:
9766
+ const a = s.map(([p, y]) => `${p}:
9715
9767
  ${y}`).join(`
9716
9768
 
9717
9769
  `).trim().slice(0, 12e3), c = uc(n, r).trim(), u = `Simplified DOM outline:
9718
9770
  `, l = `
9719
9771
 
9720
9772
  Visible page text:
9721
- `, d = 12e3 - u.length - l.length, h = Math.min(a.length, 7900), m = c.slice(0, d - h), p = a.slice(0, d - m.length);
9722
- return `${u}${m}${l}${p}`;
9773
+ `, d = 12e3 - u.length - l.length, h = Math.min(a.length, 7900), f = c.slice(0, d - h), m = a.slice(0, d - f.length);
9774
+ return `${u}${f}${l}${m}`;
9723
9775
  }
9724
9776
  function Pe(s) {
9725
9777
  return s.innerText ?? s.textContent ?? "";
9726
9778
  }
9727
- function we(s) {
9779
+ function Se(s) {
9728
9780
  return (s ?? "").replace(/\u00a0/g, " ").replace(/\r\n?/g, `
9729
9781
  `).split(`
9730
9782
  `).map((e) => e.replace(/[ \t]+/g, " ").trim()).join(`
@@ -9733,10 +9785,10 @@ function we(s) {
9733
9785
  `).trim();
9734
9786
  }
9735
9787
  function Ft(s, e) {
9736
- let t = we(s);
9788
+ let t = Se(s);
9737
9789
  for (const i of e)
9738
9790
  t = t.replace(i, "");
9739
- return we(t);
9791
+ return Se(t);
9740
9792
  }
9741
9793
  function on(s) {
9742
9794
  const e = window.getComputedStyle(s);
@@ -9827,52 +9879,52 @@ function uc(s, e) {
9827
9879
  "data-cy"
9828
9880
  ], u = ["aria-label", "placeholder", "data-testid", "data-test", "data-qa", "data-cy"], { priorityElements: l, priorityTargets: d } = hc(), h = new Set(s);
9829
9881
  e && h.add(e);
9830
- let m = 0;
9831
- const p = (_) => {
9832
- const I = _.getAttribute("role");
9833
- return I && !o.has(I) ? I : "";
9834
- }, f = (_) => {
9835
- const I = _.getAttribute("data-testid") || _.getAttribute("data-test") || _.getAttribute("data-qa") || _.getAttribute("data-cy") || "";
9836
- return `${_.tagName.toLowerCase()}|${p(_)}|${I}`;
9837
- }, y = (_, I, v) => {
9838
- const S = (C, Y) => {
9882
+ let f = 0;
9883
+ const m = (S) => {
9884
+ const w = S.getAttribute("role");
9885
+ return w && !o.has(w) ? w : "";
9886
+ }, p = (S) => {
9887
+ const w = S.getAttribute("data-testid") || S.getAttribute("data-test") || S.getAttribute("data-qa") || S.getAttribute("data-cy") || "";
9888
+ return `${S.tagName.toLowerCase()}|${m(S)}|${w}`;
9889
+ }, y = (S, w, I) => {
9890
+ const _ = (C, Y) => {
9839
9891
  const T = C.tagName.toLowerCase(), ae = window.getComputedStyle(C), pe = l.has(C);
9840
- if (m >= 1e3 && !pe || v.has(C) || r.has(T) || C.matches(".pluno-pa-widget-host, [data-pluno-product-agent-widget]") || ae.display === "none" || ae.visibility === "hidden")
9892
+ if (f >= 1e3 && !pe || I.has(C) || r.has(T) || C.matches(".pluno-pa-widget-host, [data-pluno-product-agent-widget]") || ae.display === "none" || ae.visibility === "hidden")
9841
9893
  return { lines: [], hasUsefulContent: !1, textPreview: "", containsTextElement: !1 };
9842
- m += 1;
9843
- const Be = p(C), fe = cn(C), g = a.has(Be) || ["button", "input", "textarea", "select", "iframe", "canvas"].includes(T) || T === "a" && C.hasAttribute("href"), k = Array.from(C.children).filter((R) => R instanceof HTMLElement), q = /* @__PURE__ */ new Map();
9894
+ f += 1;
9895
+ const Be = m(C), fe = cn(C), g = a.has(Be) || ["button", "input", "textarea", "select", "iframe", "canvas"].includes(T) || T === "a" && C.hasAttribute("href"), k = Array.from(C.children).filter((R) => R instanceof HTMLElement), q = /* @__PURE__ */ new Map();
9844
9896
  for (const R of k) {
9845
- const O = f(R);
9897
+ const O = p(R);
9846
9898
  q.set(O, (q.get(O) ?? 0) + 1);
9847
9899
  }
9848
- const P = /* @__PURE__ */ new Map(), _e = /* @__PURE__ */ new Map();
9900
+ const x = /* @__PURE__ */ new Map(), Ae = /* @__PURE__ */ new Map();
9849
9901
  for (const R of k) {
9850
- const O = f(R), ie = _e.get(O) ?? 0;
9851
- _e.set(O, ie + 1), (q.get(O) ?? 0) > 8 && ie >= 6 && !l.has(R) && P.set(O, (P.get(O) ?? 0) + 1);
9902
+ const O = p(R), ie = Ae.get(O) ?? 0;
9903
+ Ae.set(O, ie + 1), (q.get(O) ?? 0) > 8 && ie >= 6 && !l.has(R) && x.set(O, (x.get(O) ?? 0) + 1);
9852
9904
  }
9853
9905
  const Le = /* @__PURE__ */ new Map(), qs = /* @__PURE__ */ new Set(), vt = [], Ms = [];
9854
9906
  for (const R of k) {
9855
- const O = f(R), ie = q.get(O) ?? 0, xs = Le.get(O) ?? 0;
9907
+ const O = p(R), ie = q.get(O) ?? 0, xs = Le.get(O) ?? 0;
9856
9908
  if (Le.set(O, xs + 1), ie > 8 && xs >= 6 && !l.has(R)) {
9857
- qs.has(O) || (vt.push([`… ${P.get(O) ?? 0} similar siblings omitted`]), qs.add(O));
9909
+ qs.has(O) || (vt.push([`… ${x.get(O) ?? 0} similar siblings omitted`]), qs.add(O));
9858
9910
  continue;
9859
9911
  }
9860
- const Ds = S(R, Y);
9912
+ const Ds = _(R, Y);
9861
9913
  Ms.push(Ds), vt.push(Ds.lines);
9862
9914
  }
9863
9915
  const It = [];
9864
9916
  if (C.shadowRoot)
9865
9917
  for (const R of Array.from(C.shadowRoot.children))
9866
- R instanceof HTMLElement && It.push(S(R, Y + 1));
9867
- const je = [...Ms, ...It], bt = fe.length > 0 || g || je.some((R) => R.hasUsefulContent), Os = we(
9918
+ R instanceof HTMLElement && It.push(_(R, Y + 1));
9919
+ const je = [...Ms, ...It], bt = fe.length > 0 || g || je.some((R) => R.hasUsefulContent), Os = Se(
9868
9920
  [fe, ...je.map((R) => R.textPreview)].filter(Boolean).join(" ")
9869
- ).slice(0, 180), En = C.hasAttribute("contenteditable") && (fe.length > 0 || !C.querySelector("[contenteditable]")), Ps = u.some((R) => C.hasAttribute(R)) || !!Be || En, wt = (C.getClientRects().length > 0 || ae.display === "contents") && (t.has(T) || Ps || pe) && (bt || pe) && (!n.has(T) || bt || Ps || pe), St = wt ? 1 : 0, Ae = [];
9921
+ ).slice(0, 180), En = C.hasAttribute("contenteditable") && (fe.length > 0 || !C.querySelector("[contenteditable]")), Ps = u.some((R) => C.hasAttribute(R)) || !!Be || En, wt = (C.getClientRects().length > 0 || ae.display === "contents") && (t.has(T) || Ps || pe) && (bt || pe) && (!n.has(T) || bt || Ps || pe), St = wt ? 1 : 0, Ee = [];
9870
9922
  if (wt) {
9871
9923
  const R = je.some((ie) => ie.containsTextElement), O = i.has(T) && !R ? Os : fe;
9872
- Ae.push(an(C, c, o, O.slice(0, 180)));
9924
+ Ee.push(an(C, c, o, O.slice(0, 180)));
9873
9925
  }
9874
9926
  for (const R of vt)
9875
- Ae.push(...Ke(R, St));
9927
+ Ee.push(...Ke(R, St));
9876
9928
  const _t = It.flatMap((R) => R.lines);
9877
9929
  if (_t.length > 0) {
9878
9930
  const R = _t.slice(0, 20);
@@ -9880,29 +9932,29 @@ function uc(s, e) {
9880
9932
  const O = T.includes("tooltip") || T.includes("popper") || T.includes("loader");
9881
9933
  if (Y < 2 && !O) {
9882
9934
  const ie = wt ? "#shadow-root" : `${T} #shadow-root`;
9883
- Ae.push(...Ke([ie, ...Ke(R, 1)], St));
9935
+ Ee.push(...Ke([ie, ...Ke(R, 1)], St));
9884
9936
  } else
9885
- Ae.push(...Ke(R, St));
9937
+ Ee.push(...Ke(R, St));
9886
9938
  }
9887
9939
  return {
9888
- lines: Ae,
9940
+ lines: Ee,
9889
9941
  hasUsefulContent: bt,
9890
9942
  textPreview: Os,
9891
9943
  containsTextElement: i.has(T) || je.some((R) => R.containsTextElement)
9892
9944
  };
9893
9945
  };
9894
- return [`--- ${I} ---`, ...S(_, 0).lines].join(`
9946
+ return [`--- ${w} ---`, ..._(S, 0).lines].join(`
9895
9947
  `);
9896
- }, b = [], A = we(window.getSelection()?.toString() ?? "");
9897
- A && b.push(`--- selected text ---
9898
- ${JSON.stringify(A)}`), d.length > 0 && b.push(pc(d, t, c, o));
9899
- for (const _ of s.slice(0, 3))
9900
- b.push(y(_, "active overlay DOM", /* @__PURE__ */ new Set()));
9901
- if (e && b.push(y(e, "main DOM", /* @__PURE__ */ new Set())), document.body) {
9902
- const _ = e || s.length ? "other visible DOM" : "visible DOM";
9903
- b.push(y(document.body, _, h));
9904
- }
9905
- return b.join(`
9948
+ }, v = [], A = Se(window.getSelection()?.toString() ?? "");
9949
+ A && v.push(`--- selected text ---
9950
+ ${JSON.stringify(A)}`), d.length > 0 && v.push(pc(d, t, c, o));
9951
+ for (const S of s.slice(0, 3))
9952
+ v.push(y(S, "active overlay DOM", /* @__PURE__ */ new Set()));
9953
+ if (e && v.push(y(e, "main DOM", /* @__PURE__ */ new Set())), document.body) {
9954
+ const S = e || s.length ? "other visible DOM" : "visible DOM";
9955
+ v.push(y(document.body, S, h));
9956
+ }
9957
+ return v.join(`
9906
9958
 
9907
9959
  `);
9908
9960
  }
@@ -9998,7 +10050,7 @@ function Ke(s, e) {
9998
10050
  return s.map((i) => `${t}${i}`);
9999
10051
  }
10000
10052
  function cn(s) {
10001
- return we(
10053
+ return Se(
10002
10054
  Array.from(s.childNodes).filter((e) => e.nodeType === Node.TEXT_NODE).map((e) => e.textContent ?? "").join(" ")
10003
10055
  );
10004
10056
  }
@@ -10110,7 +10162,7 @@ function wc() {
10110
10162
  const t = crypto.randomUUID();
10111
10163
  return window.localStorage.setItem(s, t), t;
10112
10164
  }
10113
- function x() {
10165
+ function D() {
10114
10166
  return crypto.randomUUID();
10115
10167
  }
10116
10168
  function Ii(s) {
@@ -10143,7 +10195,7 @@ function ln(s, e) {
10143
10195
  id: typeof n.id == "string" ? n.id : String(t.id ?? crypto.randomUUID()),
10144
10196
  role: "assistant",
10145
10197
  ...n.phase === "commentary" || n.phase === "final_answer" ? { phase: n.phase } : {},
10146
- content: ye(
10198
+ content: ve(
10147
10199
  bi(n.content),
10148
10200
  e
10149
10201
  ),
@@ -10160,7 +10212,7 @@ function ln(s, e) {
10160
10212
  id: String(t.id ?? crypto.randomUUID()),
10161
10213
  role: r,
10162
10214
  ...n.phase === "commentary" || n.phase === "final_answer" ? { phase: n.phase } : {},
10163
- content: ye(
10215
+ content: ve(
10164
10216
  bi(n.content),
10165
10217
  e
10166
10218
  ),
@@ -10755,7 +10807,7 @@ function yn(s) {
10755
10807
  const e = s.get("content-type")?.toLowerCase() ?? "", t = s.get("content-length"), i = Number(t);
10756
10808
  return t !== null && Number.isInteger(i) && i >= 0 && i <= As && (e.startsWith("text/") || e.includes("json") || e.includes("javascript"));
10757
10809
  }
10758
- function ge(s, e = {}, t) {
10810
+ function ye(s, e = {}, t) {
10759
10811
  if (sd(t))
10760
10812
  return !0;
10761
10813
  const i = Object.entries(e).find(([n]) => n.toLowerCase() === "content-type")?.[1]?.toLowerCase();
@@ -10772,7 +10824,7 @@ function ge(s, e = {}, t) {
10772
10824
  }
10773
10825
  }
10774
10826
  function td(s, e) {
10775
- if (ge(s))
10827
+ if (ye(s))
10776
10828
  return !0;
10777
10829
  try {
10778
10830
  const t = new URL(s, location.href), i = new URL(e);