@pluno/product-agent-web 0.1.262 → 0.1.263

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.
@@ -1,13 +1,13 @@
1
- const Cs = ["main-chat-omnibox-hint", "main-chat-whatsapp-hint"], xs = "pluno.productAgent.deviceHints", Dn = ["pluno.productAgent.omniboxHintDismissed", "pluno.productAgent.whatsappHintDismissed"], Un = "pluno.productAgent.mainChatPromptDecisions";
2
- function Os(t) {
3
- const e = JSON.parse(t.getItem(xs) ?? "{}"), s = JSON.parse(t.getItem(Un) ?? "[]"), n = Object.fromEntries(Cs.map((i, r) => [i, e[i] === !0 || t.getItem(Dn[r]) === "true" || s.some((a) => a.scope.level === "device" && a.scope.key === "main-web-chat" && (a.promptKey === i || a.action === "dont_show_again" && a.category === (r ? "connections" : "product-tips")) && ["dismiss", "never", "dont_show_again"].includes(a.action))]));
4
- t.setItem(xs, JSON.stringify(n));
1
+ const Cs = ["main-chat-omnibox-hint", "main-chat-whatsapp-hint"], Os = "pluno.productAgent.deviceHints", Dn = ["pluno.productAgent.omniboxHintDismissed", "pluno.productAgent.whatsappHintDismissed"], Un = "pluno.productAgent.mainChatPromptDecisions";
2
+ function xs(t) {
3
+ const e = JSON.parse(t.getItem(Os) ?? "{}"), s = JSON.parse(t.getItem(Un) ?? "[]"), n = Object.fromEntries(Cs.map((i, r) => [i, e[i] === !0 || t.getItem(Dn[r]) === "true" || s.some((a) => a.scope.level === "device" && a.scope.key === "main-web-chat" && (a.promptKey === i || a.action === "dont_show_again" && a.category === (r ? "connections" : "product-tips")) && ["dismiss", "never", "dont_show_again"].includes(a.action))]));
4
+ t.setItem(Os, JSON.stringify(n));
5
5
  for (const i of Dn) t.removeItem(i);
6
6
  return t.setItem(Un, JSON.stringify(s.filter((i) => !Cs.includes(i.promptKey)))), n;
7
7
  }
8
8
  function Br(t, e) {
9
9
  if (!Cs.includes(e)) throw new Error("Unknown device hint.");
10
- t.setItem(xs, JSON.stringify({ ...Os(t), [e]: !0 }));
10
+ t.setItem(Os, JSON.stringify({ ...xs(t), [e]: !0 }));
11
11
  }
12
12
  function Yt(t, e, s, n) {
13
13
  if (s.authorityId !== t.account.authority?.authorityId || s.generation !== t.account.authority.generation) return t;
@@ -25,14 +25,14 @@ function Yt(t, e, s, n) {
25
25
  });
26
26
  p.awaitingBaseline = !1, p.ignoredTurns = d.filter((h) => !m.includes(h));
27
27
  }
28
- const f = {};
28
+ const g = {};
29
29
  for (const [m, h] of Object.entries(p.turns)) {
30
- const v = l && d.includes(m), b = v && !h.active ? n : h.startedAt;
31
- f[m] = { ...h, startedAt: b, active: v, notifications: !h.notificationsSuppressed && (h.notifications || v && n - b >= 1e4) };
30
+ const v = l && d.includes(m), I = v && !h.active ? n : h.startedAt;
31
+ g[m] = { ...h, startedAt: I, active: v, notifications: !h.notificationsSuppressed && (h.notifications || v && n - I >= 1e4) };
32
32
  }
33
33
  if (l)
34
- for (const m of d) !p.ignoredTurns.includes(m) && !f[m] && (f[m] = { startedAt: n, active: !0, notifications: !1, tab_grouping: (t.interactions.crossTabTurns[o.sessionId] ?? []).includes(m) });
35
- i[a] = { ...p, turns: f };
34
+ for (const m of d) !p.ignoredTurns.includes(m) && !g[m] && (g[m] = { startedAt: n, active: !0, notifications: !1, tab_grouping: (t.interactions.crossTabTurns[o.sessionId] ?? []).includes(m) });
35
+ i[a] = { ...p, turns: g };
36
36
  }
37
37
  return { ...t, interactions: { ...t.interactions, openings: i, openingGeneration: r } };
38
38
  }
@@ -40,10 +40,10 @@ function Ci(t, e, s) {
40
40
  const n = t.interactions.openings[e];
41
41
  return n?.sessionId ? n.shown[s] ?? Object.entries(n.turns).find(([, i]) => i.active && i[s])?.[0] ?? null : null;
42
42
  }
43
- function xt(t, e) {
43
+ function Ot(t, e) {
44
44
  return e === "limit_exceeded" ? { allowed: !1, reason: "credits_exhausted", actions: ["upgrade", "earn_credits"] } : e === "subscription_required" || e === "subscription_inactive" || e === "payment_issue" || e === "subscription_invalid" || e === "payment_required" ? { allowed: !1, reason: "payment_issue", actions: ["upgrade"] } : t ?? { allowed: !0, reason: "allowed", actions: [] };
45
45
  }
46
- const xi = {
46
+ const Oi = {
47
47
  connect: "canConnect",
48
48
  read_account: "canReadAccount",
49
49
  read_appearance: "canReadAppearance",
@@ -199,10 +199,10 @@ const xi = {
199
199
  function J(t, e) {
200
200
  return Fr[t][e] === !0;
201
201
  }
202
- function Oi(t, e, s = null, n = !0) {
202
+ function xi(t, e, s = null, n = !0) {
203
203
  const i = (a, o) => ({ operation: e, allowed: a === "allowed", reason: a, recovery: o }), r = t.authority;
204
204
  if (!r) return i("authentication", "login");
205
- if (!J(r.profile, xi[e])) return i("capability", "none");
205
+ if (!J(r.profile, Oi[e])) return i("capability", "none");
206
206
  if (s && t.preferences?.blockedOrigins.includes(s)) return i("blocked_origin", "settings");
207
207
  if (!n) return i("device", "settings");
208
208
  if (["send_message", "retry_message", "start_deep_flow"].includes(e) && !r.profile.startsWith("embedded_")) {
@@ -223,7 +223,7 @@ function he(t) {
223
223
  if (!e) throw new Error("Display timestamps must retain the backend UTC precision.");
224
224
  return `${e[1]}.${(e[2] ?? "").padEnd(6, "0")}`;
225
225
  }
226
- function Ot(t) {
226
+ function xt(t) {
227
227
  return "revision" in t.data ? t.data.revision : null;
228
228
  }
229
229
  function me(t) {
@@ -303,68 +303,68 @@ function $r(t, e) {
303
303
  return s && n >= 0 ? s.slice(0, n + 1) : [e];
304
304
  }
305
305
  function Ie(t, e, s) {
306
- const n = t.submissionOrder.map((_) => t.submissions[_]).filter((_) => _.conversationScopeId === s), i = e.selections[s]?.sessionId ?? n.find((_) => !_.cancelled && _.sessionId !== null)?.sessionId ?? null, r = i ? t.sessions[i] : void 0, a = t.submissionOrder.map((_) => t.submissions[_]).filter((_) => i ? _.sessionId === i || _.sessionId === null && _.conversationScopeId === s : _.conversationScopeId === s), o = Object.values(r?.items ?? {}).sort((_, O) => {
307
- const U = he(_.created_at), H = he(O.created_at);
308
- return U < H ? -1 : U > H ? 1 : _.id < O.id ? -1 : _.id > O.id ? 1 : 0;
309
- }), c = a.filter((_) => (!_.cancelled || _.conversationScopeId === s && (_.sessionId === null || _.sessionId === i || i === null && _ === a[a.length - 1])) && !r?.items[_.userMessageId] && !r?.removedItems[_.userMessageId]), d = {};
310
- for (const _ of o) {
311
- const O = Ot(_);
312
- if (O === null) continue;
313
- const U = r?.streams[_.id];
314
- d[_.id] = U ? U.state === "open" ? "open" : O < U.revision ? "awaiting_content" : U.state : "open";
306
+ const n = t.submissionOrder.map((S) => t.submissions[S]).filter((S) => S.conversationScopeId === s), i = e.selections[s]?.sessionId ?? n.find((S) => !S.cancelled && S.sessionId !== null)?.sessionId ?? null, r = i ? t.sessions[i] : void 0, a = t.submissionOrder.map((S) => t.submissions[S]).filter((S) => i ? S.sessionId === i || S.sessionId === null && S.conversationScopeId === s : S.conversationScopeId === s), o = Object.values(r?.items ?? {}).sort((S, x) => {
307
+ const U = he(S.created_at), H = he(x.created_at);
308
+ return U < H ? -1 : U > H ? 1 : S.id < x.id ? -1 : S.id > x.id ? 1 : 0;
309
+ }), c = a.filter((S) => (!S.cancelled || S.conversationScopeId === s && (S.sessionId === null || S.sessionId === i || i === null && S === a[a.length - 1])) && !r?.items[S.userMessageId] && !r?.removedItems[S.userMessageId]), d = {};
310
+ for (const S of o) {
311
+ const x = xt(S);
312
+ if (x === null) continue;
313
+ const U = r?.streams[S.id];
314
+ d[S.id] = U ? U.state === "open" ? "open" : x < U.revision ? "awaiting_content" : U.state : "open";
315
315
  }
316
316
  const l = [];
317
- for (const _ of o)
318
- if (_.type === "user_message")
319
- l.push({ id: _.id, userMessageId: _.id, activityIds: [], outcomeIds: [], collapsed: !1 });
317
+ for (const S of o)
318
+ if (S.type === "user_message")
319
+ l.push({ id: S.id, userMessageId: S.id, activityIds: [], outcomeIds: [], collapsed: !1 });
320
320
  else {
321
- l.length || l.push({ id: `leading:${_.id}`, userMessageId: null, activityIds: [], outcomeIds: [], collapsed: !1 });
322
- const O = l.length - 1, U = l[O], H = _.type === "commentary" || _.type === "tool_summary" ? "activityIds" : "outcomeIds";
323
- l[O] = { ...U, [H]: [...U[H], _.id] };
321
+ l.length || l.push({ id: `leading:${S.id}`, userMessageId: null, activityIds: [], outcomeIds: [], collapsed: !1 });
322
+ const x = l.length - 1, U = l[x], H = S.type === "commentary" || S.type === "tool_summary" ? "activityIds" : "outcomeIds";
323
+ l[x] = { ...U, [H]: [...U[H], S.id] };
324
324
  }
325
- for (const _ of c) {
326
- const O = l.findIndex((U) => {
325
+ for (const S of c) {
326
+ const x = l.findIndex((U) => {
327
327
  const H = a.find((ot) => ot.userMessageId === U.userMessageId), Fe = r?.items[U.userMessageId ?? U.activityIds[0] ?? U.outcomeIds[0]];
328
- return (H?.submittedAt ?? (Fe ? Date.parse(Fe.created_at) : 1 / 0)) > _.submittedAt;
328
+ return (H?.submittedAt ?? (Fe ? Date.parse(Fe.created_at) : 1 / 0)) > S.submittedAt;
329
329
  });
330
- l.splice(O < 0 ? l.length : O, 0, {
331
- id: _.userMessageId,
332
- userMessageId: _.userMessageId,
330
+ l.splice(x < 0 ? l.length : x, 0, {
331
+ id: S.userMessageId,
332
+ userMessageId: S.userMessageId,
333
333
  activityIds: [],
334
334
  outcomeIds: [],
335
335
  collapsed: !1
336
336
  });
337
337
  }
338
- const u = r?.execution, p = a.filter((_) => !_.cancelled && _.delivery !== "failed"), f = p.filter((_) => _.delivery !== "accepted" && _.executionVersion === null), m = p.filter((_) => _.delivery === "accepted" && _.executionVersion === null), h = p[p.length - 1], v = f.length > 0, b = h !== void 0 && m.includes(h);
339
- let S = v ? "submitting" : b ? "awaiting_execution" : u?.phase ?? "idle";
340
- const k = Object.entries(t.stops).filter(([_]) => _ === s || i !== null && e.selections[_]?.sessionId === i).map(([, _]) => _).find((_) => (!a.length || _.userMessageIds.includes(a[a.length - 1].userMessageId) || !v && !b && de(u).some((O) => _.userMessageIds.includes(O))) && (!u || u.version <= _.executionVersion || ["thinking", "steering", "queued", "stopping"].includes(u.phase) || a.some((O) => O.cancelled && O.executionVersion === null && _.userMessageIds.includes(O.userMessageId)))), g = u && ["thinking", "steering", "queued", "stopping"].includes(u.phase) || a.some((_) => _.delivery === "accepted" && _.executionVersion === null && k?.userMessageIds.includes(_.userMessageId));
341
- k && g && !v && (!u || !["thinking", "steering", "queued", "stopping"].includes(u.phase) || de(u).every((_) => k.userMessageIds.includes(_))) && (S = "stopping"), k && !g && !v && a.some((_) => _.cancelled && _.executionVersion === null && k.userMessageIds.includes(_.userMessageId)) && (S = a.some((_) => k.userMessageIds.includes(_.userMessageId) && ["sending", "uncertain"].includes(_.delivery)) ? "stopping" : "stopped");
342
- const y = ["thinking", "steering", "queued"].includes(S), I = t.stops[s] ?? k, w = I?.userMessageIds.filter((_) => !["completed", "failed"].includes(r?.executionByUserMessage[_]?.phase ?? "")) ?? [], R = w.some((_) => {
343
- const O = a.find((H) => H.userMessageId === _);
344
- return !Object.values(t.operations).some((H) => H.command.type === "run.stop" && H.command.payload.expectedUserMessageId === _ && H.phase === "done") && (O?.executionVersion === null && ["sending", "uncertain", "accepted"].includes(O.delivery) || !!(u && de(u).includes(_) && ["thinking", "steering", "queued", "stopping"].includes(u.phase)));
345
- }), T = u?.user_message_ids ?? [], C = v || b ? h?.userMessageId ?? null : T[T.length - 1] ?? null, E = l.find((_) => _.userMessageId === C), q = y ? [...E?.activityIds ?? []].reverse().find((_) => d[_] === "open") ?? null : null, x = i !== null && !!e.selections[s]?.provisionalId && o.length === 0 && a.length === 0 && // The first persisted idle snapshot already has a positive synchronization version.
346
- (!r?.execution || r.execution.phase === "idle" && r.execution.user_message_ids.length === 0) && Object.values(t.operations).some((_) => _.conversationScopeId === s && _.phase === "done" && ["runtime.warmup", "attachment.prepare"].includes(_.command.type) && !_.command.payload.sessionId && _.result?.sessionId === i);
338
+ const u = r?.execution, p = a.filter((S) => !S.cancelled && S.delivery !== "failed"), g = p.filter((S) => S.delivery !== "accepted" && S.executionVersion === null), m = p.filter((S) => S.delivery === "accepted" && S.executionVersion === null), h = p[p.length - 1], v = g.length > 0, I = h !== void 0 && m.includes(h);
339
+ let k = v ? "submitting" : I ? "awaiting_execution" : u?.phase ?? "idle";
340
+ const w = Object.entries(t.stops).filter(([S]) => S === s || i !== null && e.selections[S]?.sessionId === i).map(([, S]) => S).find((S) => (!a.length || S.userMessageIds.includes(a[a.length - 1].userMessageId) || !v && !I && de(u).some((x) => S.userMessageIds.includes(x))) && (!u || u.version <= S.executionVersion || ["thinking", "steering", "queued", "stopping"].includes(u.phase) || a.some((x) => x.cancelled && x.executionVersion === null && S.userMessageIds.includes(x.userMessageId)))), f = u && ["thinking", "steering", "queued", "stopping"].includes(u.phase) || a.some((S) => S.delivery === "accepted" && S.executionVersion === null && w?.userMessageIds.includes(S.userMessageId));
341
+ w && f && !v && (!u || !["thinking", "steering", "queued", "stopping"].includes(u.phase) || de(u).every((S) => w.userMessageIds.includes(S))) && (k = "stopping"), w && !f && !v && a.some((S) => S.cancelled && S.executionVersion === null && w.userMessageIds.includes(S.userMessageId)) && (k = a.some((S) => w.userMessageIds.includes(S.userMessageId) && ["sending", "uncertain"].includes(S.delivery)) ? "stopping" : "stopped");
342
+ const y = ["thinking", "steering", "queued"].includes(k), b = t.stops[s] ?? w, _ = b?.userMessageIds.filter((S) => !["completed", "failed"].includes(r?.executionByUserMessage[S]?.phase ?? "")) ?? [], R = _.some((S) => {
343
+ const x = a.find((H) => H.userMessageId === S);
344
+ return !Object.values(t.operations).some((H) => H.command.type === "run.stop" && H.command.payload.expectedUserMessageId === S && H.phase === "done") && (x?.executionVersion === null && ["sending", "uncertain", "accepted"].includes(x.delivery) || !!(u && de(u).includes(S) && ["thinking", "steering", "queued", "stopping"].includes(u.phase)));
345
+ }), T = u?.user_message_ids ?? [], C = v || I ? h?.userMessageId ?? null : T[T.length - 1] ?? null, E = l.find((S) => S.userMessageId === C), q = y ? [...E?.activityIds ?? []].reverse().find((S) => d[S] === "open") ?? null : null, O = i !== null && !!e.selections[s]?.provisionalId && o.length === 0 && a.length === 0 && // The first persisted idle snapshot already has a positive synchronization version.
346
+ (!r?.execution || r.execution.phase === "idle" && r.execution.user_message_ids.length === 0) && Object.values(t.operations).some((S) => S.conversationScopeId === s && S.phase === "done" && ["runtime.warmup", "attachment.prepare"].includes(S.command.type) && !S.command.payload.sessionId && S.result?.sessionId === i);
347
347
  return G({
348
348
  historyRefreshFailure: r?.historyRefreshFailure ?? null,
349
349
  selectionKey: s ? JSON.stringify([t.authorityId, t.generation, s]) : void 0,
350
- isDraftSession: x,
350
+ isDraftSession: O,
351
351
  proactiveQuestion: t.proactiveQuestions[s] ?? null,
352
352
  sessionId: i,
353
353
  items: o,
354
354
  optimistic: c,
355
355
  submissions: a,
356
356
  followUps: r?.followUps ?? [],
357
- isRetrying: Object.values(t.operations).some((_) => _.command.type === "chat.retry_last_user_message" && _.command.payload.sessionId === i && ["waiting", "running", "uncertain"].includes(_.phase)),
358
- deliveries: Object.fromEntries(a.filter((_) => t.deliveries[_.userMessageId]).map((_) => [_.userMessageId, t.deliveries[_.userMessageId]])),
357
+ isRetrying: Object.values(t.operations).some((S) => S.command.type === "chat.retry_last_user_message" && S.command.payload.sessionId === i && ["waiting", "running", "uncertain"].includes(S.phase)),
358
+ deliveries: Object.fromEntries(a.filter((S) => t.deliveries[S.userMessageId]).map((S) => [S.userMessageId, t.deliveries[S.userMessageId]])),
359
359
  removedItems: r?.removedItems ?? {},
360
360
  streamStates: d,
361
361
  preparation: r?.preparation ?? null,
362
- stop: I ? { ...I, userMessageIds: w, pending: R } : null,
363
- segments: l.map((_, O) => ({ ..._, collapsed: y ? _.userMessageId !== C : O < l.length - 1 || _.activityIds.length > 0 })),
364
- activity: { phase: S, activeItemId: q, userMessageId: C, executionKey: JSON.stringify([...de(u)].sort()) },
362
+ stop: b ? { ...b, userMessageIds: _, pending: R } : null,
363
+ segments: l.map((S, x) => ({ ...S, collapsed: y ? S.userMessageId !== C : x < l.length - 1 || S.activityIds.length > 0 })),
364
+ activity: { phase: k, activeItemId: q, userMessageId: C, executionKey: JSON.stringify([...de(u)].sort()) },
365
365
  // Staging transfers the immutable input to the core. Waiting for backend acceptance leaves
366
366
  // the same submitted text in the optimistic transcript and composer during delivery.
367
- receipts: n.filter((_) => !_.cancelled && e.clients[_.clientScopeId] === s).map((_) => ({ viewId: _.viewId, userMessageId: _.userMessageId, acceptedRendererRevision: _.rendererRevision }))
367
+ receipts: n.filter((S) => !S.cancelled && e.clients[S.clientScopeId] === s).map((S) => ({ viewId: S.viewId, userMessageId: S.userMessageId, acceptedRendererRevision: S.rendererRevision }))
368
368
  });
369
369
  }
370
370
  function Di(t, e) {
@@ -427,7 +427,7 @@ function Hr(t, e, s) {
427
427
  const n = t.account.authority;
428
428
  if (!n) return [];
429
429
  const i = J(n.profile, "canShowPersonalFeatures"), r = [], a = t.features.now, o = (c) => {
430
- const d = Object.values(t.features.pending).filter((f) => f.mode === "mutation" && c.includes(f.key)), l = d.some((f) => f.status === "pending"), u = d[d.length - 1], p = u?.status === "error" ? u.error : null;
430
+ const d = Object.values(t.features.pending).filter((g) => g.mode === "mutation" && c.includes(g.key)), l = d.some((g) => g.status === "pending"), u = d[d.length - 1], p = u?.status === "error" ? u.error : null;
431
431
  return { status: l ? "pending" : p ? "error" : "presentable", error: p };
432
432
  };
433
433
  if (n.profile === "main_web_chat") for (const [c, d] of Object.entries(t.interactions.deviceHints)) {
@@ -455,9 +455,9 @@ function Hr(t, e, s) {
455
455
  if (!J(n.profile, d)) continue;
456
456
  const l = s.conversationScopeId ? t.interactions.openings[s.conversationScopeId] : void 0;
457
457
  if (!s.sessionId || !l || l.sessionId !== s.sessionId || !Ci(t, s.conversationScopeId, c) || t.features.refreshRequired && !l.shown[c] || n.profile === "main_web_chat" && !t.interactions.bridgeReady && !l.shown[c]) continue;
458
- const u = Qe(t, c), p = t.interactions.preferencePrompts[c], f = t.interactions.deviceFacts[c], m = `preference:${c}`, h = u === null;
459
- if (u === !1 || t.features.desiredPreferences[c] === !1 || h && p.snoozedUntil && Date.parse(p.snoozedUntil) > a || !h && (f.permission !== "missing" || f.snoozedUntil && Date.parse(f.snoozedUntil) > a)) continue;
460
- const v = Object.values(t.interactions.devicePending).some((k) => k.feature === c), b = o([m, `preferenceSnooze:${c}`, `preferenceAcknowledge:${c}`]), S = b.error ?? t.interactions.deviceErrors[c] ?? (l.shown[c] && t.interactions.bridgeError ? { code: "connection_interrupted", message: t.interactions.bridgeError, retryable: !0 } : null);
458
+ const u = Qe(t, c), p = t.interactions.preferencePrompts[c], g = t.interactions.deviceFacts[c], m = `preference:${c}`, h = u === null;
459
+ if (u === !1 || t.features.desiredPreferences[c] === !1 || h && p.snoozedUntil && Date.parse(p.snoozedUntil) > a || !h && (g.permission !== "missing" || g.snoozedUntil && Date.parse(g.snoozedUntil) > a)) continue;
460
+ const v = Object.values(t.interactions.devicePending).some((w) => w.feature === c), I = o([m, `preferenceSnooze:${c}`, `preferenceAcknowledge:${c}`]), k = I.error ?? t.interactions.deviceErrors[c] ?? (l.shown[c] && t.interactions.bridgeError ? { code: "connection_interrupted", message: t.interactions.bridgeError, retryable: !0 } : null);
461
461
  r.push({
462
462
  id: m,
463
463
  category: h ? "preference" : "permission",
@@ -468,10 +468,10 @@ function Hr(t, e, s) {
468
468
  sourceVersion: l.generation,
469
469
  decisionRevision: p.revision,
470
470
  actions: h ? ["enable", "not_now", "dont_enable"] : ["allow", "not_now"],
471
- status: v ? "pending" : S ? "error" : b.status,
472
- error: S,
471
+ status: v ? "pending" : k ? "error" : I.status,
472
+ error: k,
473
473
  payload: { feature: c, openingGeneration: l.generation },
474
- nextEligibleAt: h ? p.snoozedUntil : f.snoozedUntil
474
+ nextEligibleAt: h ? p.snoozedUntil : g.snoozedUntil
475
475
  });
476
476
  }
477
477
  for (const c of Object.values(t.interactions.sources)) {
@@ -484,7 +484,7 @@ function Hr(t, e, s) {
484
484
  if (d.wait_for_terminal && (!m || !Ui(m, c.user_message_id)) || (n.profile.startsWith("extension_") ? t.interactions.localSharing[c.id]?.resolved : Bn(t.interactions.decisions[`prompt:social_share:${c.id}`], a))) continue;
485
485
  }
486
486
  if (d.kind === "integration_auth" && !J(n.profile, "canManageIntegrationAuth") || d.kind === "personal_channel" && !i) continue;
487
- const l = d.kind === "integration_auth" && c.lifecycle === "pending" && Date.parse(d.expires_at) <= a ? "expired" : c.lifecycle, u = t.interactions.decisions[`prompt:social_share:${c.id}`], p = t.interactions.localSharing[c.id], f = Object.values(t.interactions.actions).filter((m) => m.interactionId === c.id && m.sourceVersion === c.version && (m.operation.kind !== "connect" || m.operation.source.conversation_id === c.conversation_id)).slice(-1)[0];
487
+ const l = d.kind === "integration_auth" && c.lifecycle === "pending" && Date.parse(d.expires_at) <= a ? "expired" : c.lifecycle, u = t.interactions.decisions[`prompt:social_share:${c.id}`], p = t.interactions.localSharing[c.id], g = Object.values(t.interactions.actions).filter((m) => m.interactionId === c.id && m.sourceVersion === c.version && (m.operation.kind !== "connect" || m.operation.source.conversation_id === c.conversation_id)).slice(-1)[0];
488
488
  r.push({
489
489
  id: c.id,
490
490
  category: d.kind,
@@ -495,9 +495,9 @@ function Hr(t, e, s) {
495
495
  sourceVersion: c.version,
496
496
  decisionRevision: n.profile.startsWith("extension_") ? p?.revision ?? 0 : u?.revision ?? 0,
497
497
  actions: d.kind === "sharing" ? ["copy", "share", "dismiss"] : d.kind === "integration_auth" ? ["connect"] : ["pair"],
498
- ...d.kind === "integration_auth" ? { actionLabels: { connect: f?.status === "error" ? "Try again" : l === "pending" ? "Connect" : "Reconnect" } } : {},
498
+ ...d.kind === "integration_auth" ? { actionLabels: { connect: g?.status === "error" ? "Try again" : l === "pending" ? "Connect" : "Reconnect" } } : {},
499
499
  ...o([`prompt:social_share:${c.id}`]),
500
- ...f?.status === "pending" || f?.status === "error" ? { status: f.status, error: f.error } : {},
500
+ ...g?.status === "pending" || g?.status === "error" ? { status: g.status, error: g.error } : {},
501
501
  payload: d.kind === "integration_auth" ? { ...d, lifecycle: l } : d,
502
502
  nextEligibleAt: null
503
503
  });
@@ -506,7 +506,7 @@ function Hr(t, e, s) {
506
506
  for (const c of Object.values(t.interactions.welcome)) {
507
507
  const d = c.category === "morning_report" ? "canManageMorningReport" : "canManageProactiveSuggestions", l = c.category === "morning_report" ? "category:morning_report" : `prompt:proactive_suggestion:${c.sourceSuggestionId ?? c.id}`;
508
508
  if (c.clientScopeId && c.clientScopeId !== s.clientScopeId || !c.eligible || c.expiresAt !== void 0 && c.expiresAt <= a || !J(n.profile, d) || Bn(t.interactions.decisions[l], a)) continue;
509
- const u = o([l]), p = ji(t, c.id, s), f = u.status === "pending" || p?.status === "pending" ? "pending" : u.error || p?.status === "error" ? "error" : "presentable";
509
+ const u = o([l]), p = ji(t, c.id, s), g = u.status === "pending" || p?.status === "pending" ? "pending" : u.error || p?.status === "error" ? "error" : "presentable";
510
510
  r.push({
511
511
  id: c.id,
512
512
  category: c.category,
@@ -517,7 +517,7 @@ function Hr(t, e, s) {
517
517
  sourceVersion: null,
518
518
  decisionRevision: t.interactions.decisions[l]?.revision ?? 0,
519
519
  actions: c.category === "morning_report" ? ["run", "snooze"] : ["run", "edit", "not_now", "never", "feedback"],
520
- status: f,
520
+ status: g,
521
521
  error: u.error ?? (p?.status === "error" ? p.error : null),
522
522
  payload: { text: c.text, tasks: c.tasks, sourceSuggestionId: c.sourceSuggestionId ?? c.id },
523
523
  nextEligibleAt: t.interactions.decisions[l]?.nextEligibleAt ?? null
@@ -576,9 +576,9 @@ function Vr(t, e, s, n) {
576
576
  return { state: i, effects: r, command: { type: "stage7.mutate", authority: a, now: e.now, requestId: e.requestId, mutation: h } };
577
577
  }
578
578
  const p = Object.values(i.interactions.sources).find((h) => h.id === u.sourceId && h.conversation_id === u.conversationId);
579
- let f;
579
+ let g;
580
580
  if (u.category === "device_hint")
581
- f = { kind: "saveHint", interactionId: u.id };
581
+ g = { kind: "saveHint", interactionId: u.id };
582
582
  else if (e.action === "dismiss") {
583
583
  if (!a.profile.startsWith("extension_")) return { state: i, effects: r, command: {
584
584
  type: "stage7.mutate",
@@ -587,38 +587,38 @@ function Vr(t, e, s, n) {
587
587
  requestId: e.requestId,
588
588
  mutation: { kind: "decision", category: "social_share", promptKey: u.id, action: "dismiss", expectedRevision: e.expectedRevision }
589
589
  } };
590
- f = { kind: "saveSharing", interactionId: u.id, expectedRevision: e.expectedRevision };
590
+ g = { kind: "saveSharing", interactionId: u.id, expectedRevision: e.expectedRevision };
591
591
  } else if (e.action === "copy" || e.action === "share") {
592
592
  if (p?.payload.kind !== "sharing") throw new Error("Missing sharing source.");
593
593
  const h = Object.values(i.interactions.actions).find((v) => v.interactionId === u.id && v.step === "perform" && v.status === "error" && (v.operation.kind === "copy" || v.operation.kind === "share"));
594
594
  if (h && h.error?.code !== "interaction_not_started") throw new Error("The previous sharing action has an uncertain outcome.");
595
- f = { kind: e.action, interactionId: u.id, variant: p.payload.variant, ...e.sharePlatform ? { platform: e.sharePlatform } : {} };
595
+ g = { kind: e.action, interactionId: u.id, variant: p.payload.variant, ...e.sharePlatform ? { platform: e.sharePlatform } : {} };
596
596
  } else if (e.action === "connect") {
597
597
  if (p?.payload.kind !== "integration_auth") throw new Error("Missing integration request.");
598
- f = { kind: "connect", interactionId: u.id, authRequestId: p.payload.request_id, source: p };
598
+ g = { kind: "connect", interactionId: u.id, authRequestId: p.payload.request_id, source: p };
599
599
  } else if (e.action === "pair") {
600
600
  if (p?.payload.kind !== "personal_channel") throw new Error("Missing channel request.");
601
- f = { kind: "pair", interactionId: u.id, requestId: p.payload.request_id, managementUrl: p.payload.management_url };
601
+ g = { kind: "pair", interactionId: u.id, requestId: p.payload.request_id, managementUrl: p.payload.management_url };
602
602
  } else {
603
603
  const h = ji(i, u.id, { clientScopeId: e.clientScopeId, conversationScopeId: n.clients[e.clientScopeId] });
604
604
  if (h?.status === "error" && h.error?.code !== "interaction_not_started") throw new Error("Reconcile the previous action before trying again.");
605
605
  if (e.action !== "edit") {
606
606
  if (a.profile.startsWith("extension_") && !e.origin) throw new Error("Task submission requires the current page origin.");
607
- const S = Oi(i.account, "send_message", e.origin ?? null);
608
- if (!S.allowed) throw new Error(`Task submission unavailable: ${S.reason}.`);
607
+ const k = xi(i.account, "send_message", e.origin ?? null);
608
+ if (!k.allowed) throw new Error(`Task submission unavailable: ${k.reason}.`);
609
609
  }
610
- const v = i.interactions.welcome[u.id], b = v.category === "morning_report" ? v.tasks[e.taskIndex ?? 0] : v.text;
611
- if (!b) throw new Error("Missing selected task.");
612
- f = {
610
+ const v = i.interactions.welcome[u.id], I = v.category === "morning_report" ? v.tasks[e.taskIndex ?? 0] : v.text;
611
+ if (!I) throw new Error("Missing selected task.");
612
+ g = {
613
613
  kind: e.action === "edit" ? "edit" : "run",
614
614
  interactionId: u.id,
615
- text: b,
615
+ text: I,
616
616
  clientScopeId: e.clientScopeId,
617
617
  conversationScopeId: n.clients[e.clientScopeId],
618
618
  submissionId: e.requestId
619
619
  };
620
620
  }
621
- const m = f.kind === "saveSharing" || f.kind === "saveHint" ? "persist" : "perform";
621
+ const m = g.kind === "saveSharing" || g.kind === "saveHint" ? "persist" : "perform";
622
622
  c(e.requestId, {
623
623
  interactionId: u.id,
624
624
  clientScopeId: e.clientScopeId,
@@ -627,11 +627,11 @@ function Vr(t, e, s, n) {
627
627
  action: e.action,
628
628
  expectedRevision: e.expectedRevision,
629
629
  sourceVersion: e.sourceVersion ?? null,
630
- operation: f,
630
+ operation: g,
631
631
  step: m,
632
632
  status: "pending",
633
633
  error: null
634
- }), d(e.requestId, f, m);
634
+ }), d(e.requestId, g, m);
635
635
  } else if (e.type === "stage7.retry_action") {
636
636
  const l = i.interactions.actions[e.requestId];
637
637
  if (!l || l.step !== "persist" || l.status !== "error") throw new Error("An uncertain browser action cannot be replayed.");
@@ -639,7 +639,7 @@ function Vr(t, e, s, n) {
639
639
  return { state: i, effects: r, command: { type: "stage7.retry", authority: a, now: e.now, requestId: `sharing:${e.requestId}` } };
640
640
  d(e.requestId, l.operation, "persist");
641
641
  } else {
642
- const l = Object.entries(i.interactions.actions).find(([f, m]) => o(f, m.step) === e.effectId && m.status === "pending");
642
+ const l = Object.entries(i.interactions.actions).find(([g, m]) => o(g, m.step) === e.effectId && m.status === "pending");
643
643
  if (!l) return { state: i, effects: r, command: null };
644
644
  const [u, p] = l;
645
645
  if (e.type === "effect.failed") c(u, { ...p, status: "error", error: e.error });
@@ -652,8 +652,8 @@ function Vr(t, e, s, n) {
652
652
  requestId: `sharing:${u}`,
653
653
  mutation: { kind: "decision", category: "social_share", promptKey: p.interactionId, action: "shared", expectedRevision: p.expectedRevision }
654
654
  } };
655
- const f = { kind: "saveSharing", interactionId: p.interactionId, expectedRevision: p.expectedRevision };
656
- c(u, { ...p, operation: f, step: "persist" }), d(u, f, "persist");
655
+ const g = { kind: "saveSharing", interactionId: p.interactionId, expectedRevision: p.expectedRevision };
656
+ c(u, { ...p, operation: g, step: "persist" }), d(u, g, "persist");
657
657
  } else
658
658
  c(u, { ...p, status: "done" }), p.operation.kind === "saveHint" && (i = { ...i, interactions: { ...i.interactions, deviceHints: { ...i.interactions.deviceHints, [p.interactionId]: !0 } } }), p.operation.kind === "saveSharing" && (i = { ...i, interactions: { ...i.interactions, localSharing: {
659
659
  ...i.interactions.localSharing,
@@ -670,21 +670,21 @@ function Kr(t, e, s, n) {
670
670
  let i = t;
671
671
  const r = [], a = (u) => {
672
672
  i = { ...i, ...u };
673
- }, o = (u, p, f) => JSON.stringify(["stage7", e.authorityId, e.generation, u, p, ...f === void 0 ? [] : [f]]), c = (u, p) => Li(u) && "origin" in u && u.origin === p, d = (u) => Object.values(i.pending).some((p) => p.mode === "mutation" && ["pending", "queued"].includes(p.status) && c(p.operation, u)), l = (u) => {
673
+ }, o = (u, p, g) => JSON.stringify(["stage7", e.authorityId, e.generation, u, p, ...g === void 0 ? [] : [g]]), c = (u, p) => Li(u) && "origin" in u && u.origin === p, d = (u) => Object.values(i.pending).some((p) => p.mode === "mutation" && ["pending", "queued"].includes(p.status) && c(p.operation, u)), l = (u) => {
674
674
  const p = i.pending[u];
675
675
  a({ pending: { ...i.pending, [u]: { ...p, status: "pending" } } }), r.push({ kind: "stage7.query", id: u, input: { authority: e, requestId: p.requestId, query: p.operation } });
676
676
  };
677
677
  if (s.type === "stage7.query" && s.query.kind === "appearance") {
678
678
  const u = { ...s.query, kind: "appearance" }, p = n(u);
679
679
  if (Object.values(i.pending).some((h) => h.mode === "query" && h.key === p)) return { state: i, effects: r };
680
- const f = o("query", s.requestId, i.appearanceEpochs[u.origin] ?? 0), m = i.pending[f];
680
+ const g = o("query", s.requestId, i.appearanceEpochs[u.origin] ?? 0), m = i.pending[g];
681
681
  if (m && m.fingerprint !== JSON.stringify(u)) throw new Error("Query request ID changed payload.");
682
682
  a({
683
683
  appearanceQueries: { ...i.appearanceQueries, [p]: u },
684
684
  queries: { ...i.queries, [p]: De(i.queries[p] ?? me(p), { key: p, requestId: re(s.requestId), mode: "replace" }) },
685
- pending: { ...i.pending, [f]: {
685
+ pending: { ...i.pending, [g]: {
686
686
  requestId: s.requestId,
687
- effectId: f,
687
+ effectId: g,
688
688
  fingerprint: JSON.stringify(u),
689
689
  key: p,
690
690
  generation: e.generation,
@@ -694,23 +694,23 @@ function Kr(t, e, s, n) {
694
694
  error: null,
695
695
  result: null
696
696
  } }
697
- }), d(u.origin) || l(f);
697
+ }), d(u.origin) || l(g);
698
698
  } else if (s.type === "stage7.mutate" && (s.mutation.kind === "sampleStyle" || s.mutation.kind === "saveStyle" || s.mutation.kind === "scribble" || s.mutation.kind === "deleteStyle")) {
699
- const u = s.mutation, p = u.origin, f = o("mutate", s.requestId), m = i.pending[f], h = JSON.stringify(u);
699
+ const u = s.mutation, p = u.origin, g = o("mutate", s.requestId), m = i.pending[g], h = JSON.stringify(u);
700
700
  if (m) {
701
701
  if (m.fingerprint !== h) throw new Error("Request ID was reused with a different payload.");
702
702
  return { state: i, effects: r };
703
703
  }
704
- const v = d(p), b = (i.appearanceEpochs[p] ?? 0) + 1, S = { ...i.pending };
705
- for (const [k, g] of Object.entries(S)) {
706
- if (g.mode !== "query" || !c(g.operation, p)) continue;
707
- delete S[k];
708
- const y = o("query", g.requestId, b);
709
- S[y] = { ...g, effectId: y, status: "queued" };
704
+ const v = d(p), I = (i.appearanceEpochs[p] ?? 0) + 1, k = { ...i.pending };
705
+ for (const [w, f] of Object.entries(k)) {
706
+ if (f.mode !== "query" || !c(f.operation, p)) continue;
707
+ delete k[w];
708
+ const y = o("query", f.requestId, I);
709
+ k[y] = { ...f, effectId: y, status: "queued" };
710
710
  }
711
- S[f] = {
711
+ k[g] = {
712
712
  requestId: s.requestId,
713
- effectId: f,
713
+ effectId: g,
714
714
  fingerprint: h,
715
715
  key: `appearance:${p}`,
716
716
  generation: e.generation,
@@ -720,30 +720,30 @@ function Kr(t, e, s, n) {
720
720
  status: v ? "queued" : "pending",
721
721
  error: null,
722
722
  result: null
723
- }, a({ pending: S, appearanceEpochs: { ...i.appearanceEpochs, [p]: b } }), v || r.push({ kind: "stage7.mutate", id: f, input: { authority: e, requestId: s.requestId, mutation: u } });
723
+ }, a({ pending: k, appearanceEpochs: { ...i.appearanceEpochs, [p]: I } }), v || r.push({ kind: "stage7.mutate", id: g, input: { authority: e, requestId: s.requestId, mutation: u } });
724
724
  } else if (s.type === "effect.completed" || s.type === "effect.failed") {
725
725
  const u = i.pending[s.effectId];
726
726
  if (!u || u.status !== "pending" || !("origin" in u.operation)) return { state: i, effects: r };
727
727
  const p = u.operation.origin;
728
728
  if (s.effectKind !== "stage7.query" && s.effectKind !== "stage7.mutate") return { state: i, effects: r };
729
- const f = s.type === "effect.completed" ? s.output.data : null;
730
- if (f && (f.kind !== "appearance" || f.origin !== p)) throw new Error("Appearance response does not match its origin.");
729
+ const g = s.type === "effect.completed" ? s.output.data : null;
730
+ if (g && (g.kind !== "appearance" || g.origin !== p)) throw new Error("Appearance response does not match its origin.");
731
731
  const m = { ...i.pending }, h = { ...i.queries };
732
732
  if (u.mode === "query") {
733
733
  delete m[s.effectId];
734
734
  const v = h[u.key];
735
- v?.requestId === u.requestId && (h[u.key] = s.type === "effect.failed" ? { ...v, status: "error", error: s.error, requestId: null } : { ...v, status: "ready", data: f, error: null, requestId: null, updatedAt: s.output.completedAt });
736
- } else if (m[s.effectId] = { ...u, status: f ? "done" : "error", result: f, error: s.type === "effect.failed" ? s.error : null }, f && s.type === "effect.completed") {
737
- for (const [v, b] of Object.entries(i.appearanceQueries))
738
- b.origin === p && (h[v] = { ...h[v], status: "ready", data: f, requestId: null, error: null, updatedAt: s.output.completedAt });
739
- for (const [v, b] of Object.entries(m)) b.mode === "query" && c(b.operation, p) && delete m[v];
735
+ v?.requestId === u.requestId && (h[u.key] = s.type === "effect.failed" ? { ...v, status: "error", error: s.error, requestId: null } : { ...v, status: "ready", data: g, error: null, requestId: null, updatedAt: s.output.completedAt });
736
+ } else if (m[s.effectId] = { ...u, status: g ? "done" : "error", result: g, error: s.type === "effect.failed" ? s.error : null }, g && s.type === "effect.completed") {
737
+ for (const [v, I] of Object.entries(i.appearanceQueries))
738
+ I.origin === p && (h[v] = { ...h[v], status: "ready", data: g, requestId: null, error: null, updatedAt: s.output.completedAt });
739
+ for (const [v, I] of Object.entries(m)) I.mode === "query" && c(I.operation, p) && delete m[v];
740
740
  } else if (s.type === "effect.failed")
741
- for (const [v, b] of Object.entries(m)) b.mode === "mutation" && b.status === "queued" && c(b.operation, p) && (m[v] = { ...b, status: "error", error: { code: "appearance_write_cancelled", message: "Refresh appearance before saving again.", retryable: !1 } });
741
+ for (const [v, I] of Object.entries(m)) I.mode === "mutation" && I.status === "queued" && c(I.operation, p) && (m[v] = { ...I, status: "error", error: { code: "appearance_write_cancelled", message: "Refresh appearance before saving again.", retryable: !1 } });
742
742
  if (a({ pending: m, queries: h }), u.mode === "mutation") {
743
- const v = Object.values(i.pending).find((b) => b.mode === "mutation" && b.status === "queued" && c(b.operation, p));
743
+ const v = Object.values(i.pending).find((I) => I.mode === "mutation" && I.status === "queued" && c(I.operation, p));
744
744
  if (v && (v.operation.kind === "sampleStyle" || v.operation.kind === "saveStyle" || v.operation.kind === "scribble" || v.operation.kind === "deleteStyle"))
745
745
  a({ pending: { ...i.pending, [v.effectId]: { ...v, status: "pending" } } }), r.push({ kind: "stage7.mutate", id: v.effectId, input: { authority: e, requestId: v.requestId, mutation: v.operation } });
746
- else for (const [b, S] of Object.entries(i.pending)) S.mode === "query" && S.status === "queued" && c(S.operation, p) && l(b);
746
+ else for (const [I, k] of Object.entries(i.pending)) k.mode === "query" && k.status === "queued" && c(k.operation, p) && l(I);
747
747
  }
748
748
  }
749
749
  return { state: i, effects: r };
@@ -833,7 +833,7 @@ const Gr = {
833
833
  blockedOrigins: "manage_origin_access"
834
834
  };
835
835
  function et(t, e) {
836
- if (!J(t.profile, xi[Gr[e.kind]])) throw new Error("Feature capability unavailable.");
836
+ if (!J(t.profile, Oi[Gr[e.kind]])) throw new Error("Feature capability unavailable.");
837
837
  if (["decisions", "decision", "preferencePrompts"].includes(e.kind) && !J(t.profile, "canShowPersonalFeatures")) throw new Error("Personal feature unavailable.");
838
838
  if (t.profile.startsWith("embedded_") && e.kind === "targetFeedback") throw new Error("Embedded target feedback has no supported contract.");
839
839
  if (e.kind === "proactiveFeedback" && !J(t.profile, "canManageProactiveSuggestions")) throw new Error("Proactive feedback unavailable.");
@@ -851,28 +851,28 @@ function Se(t, e, s) {
851
851
  }
852
852
  function js(t, e, s) {
853
853
  let n = t;
854
- const i = [], r = (g) => {
855
- n = { ...n, features: { ...n.features, ...g } };
856
- }, a = (g) => {
857
- n = { ...n, interactions: { ...n.interactions, ...g } };
854
+ const i = [], r = (f) => {
855
+ n = { ...n, features: { ...n.features, ...f } };
856
+ }, a = (f) => {
857
+ n = { ...n, interactions: { ...n.interactions, ...f } };
858
858
  };
859
859
  if (e.type === "stage7.initialize") {
860
- const g = n.account.authority;
861
- return g && JSON.stringify(g) === JSON.stringify(e.authority) ? { state: n, effects: i } : { state: { account: Ds(e.authority), features: Ns(e.now), interactions: Us() }, effects: i };
860
+ const f = n.account.authority;
861
+ return f && JSON.stringify(f) === JSON.stringify(e.authority) ? { state: n, effects: i } : { state: { account: Ds(e.authority), features: Ns(e.now), interactions: Us() }, effects: i };
862
862
  }
863
863
  const o = n.account.authority;
864
864
  if (!o) return { state: n, effects: i };
865
865
  if ("authority" in e && JSON.stringify(e.authority) !== JSON.stringify(o)) return { state: n, effects: i };
866
866
  if (e.type === "stage7.retire") return { state: { account: Ds(), features: Ns(e.now), interactions: Us() }, effects: i };
867
867
  "now" in e && r({ now: e.now });
868
- const c = (g, y) => {
869
- const I = { ...n.features.contextObservers }, w = I[g];
870
- if (y === null ? delete I[g] : I[g] = ue(o, { kind: "originContext", clientScopeId: g, origin: y, pageUrl: "" }), r({ contextObservers: I }), !w || Object.values(I).includes(w)) return;
871
- const R = { ...n.features.queries }, T = { ...n.features.polls }, C = { ...n.features.contextReads }, E = { ...n.features.originContextQueries }, q = { ...n.features.pending }, x = E[w]?.origin, _ = { ...n.features.contextRunOrigins };
872
- for (const [O, U] of Object.entries(_)) U === x && delete _[O];
873
- delete R[w], delete T[w], delete C[w], delete E[w];
874
- for (const [O, U] of Object.entries(q)) U.mode === "query" && U.key === w && delete q[O];
875
- r({ queries: R, polls: T, contextReads: C, originContextQueries: E, contextRunOrigins: _, pending: q });
868
+ const c = (f, y) => {
869
+ const b = { ...n.features.contextObservers }, _ = b[f];
870
+ if (y === null ? delete b[f] : b[f] = ue(o, { kind: "originContext", clientScopeId: f, origin: y, pageUrl: "" }), r({ contextObservers: b }), !_ || Object.values(b).includes(_)) return;
871
+ const R = { ...n.features.queries }, T = { ...n.features.polls }, C = { ...n.features.contextReads }, E = { ...n.features.originContextQueries }, q = { ...n.features.pending }, O = E[_]?.origin, S = { ...n.features.contextRunOrigins };
872
+ for (const [x, U] of Object.entries(S)) U === O && delete S[x];
873
+ delete R[_], delete T[_], delete C[_], delete E[_];
874
+ for (const [x, U] of Object.entries(q)) U.mode === "query" && U.key === _ && delete q[x];
875
+ r({ queries: R, polls: T, contextReads: C, originContextQueries: E, contextRunOrigins: S, pending: q });
876
876
  };
877
877
  if (e.type === "stage7.account_fallback") return { state: { ...n, account: {
878
878
  ...n.account,
@@ -881,83 +881,83 @@ function js(t, e, s) {
881
881
  const d = e.type === "stage7.query" ? e.query : e.type === "stage7.mutate" ? e.mutation : e.type === "effect.completed" || e.type === "effect.failed" ? n.features.pending[e.effectId]?.operation : null;
882
882
  if (d && Li(d)) {
883
883
  et(o, d);
884
- const g = Kr(n.features, o, e, (y) => ue(o, y));
885
- return { state: { ...n, features: g.state }, effects: g.effects };
884
+ const f = Kr(n.features, o, e, (y) => ue(o, y));
885
+ return { state: { ...n, features: f.state }, effects: f.effects };
886
886
  }
887
887
  if (e.type === "stage7.act" || e.type === "stage7.retry_action" || (e.type === "effect.completed" || e.type === "effect.failed") && e.effectKind === "stage7.platform") {
888
- const g = Vr(n, e, s.conversation, s.directory);
889
- if (!g.command) return { state: g.state, effects: g.effects };
890
- const y = js(g.state, g.command, s);
891
- return { state: y.state, effects: [...g.effects, ...y.effects] };
892
- }
893
- const l = (g, y, I) => {
894
- const w = g === "notifications" ? "canRequestNotificationPermission" : "canGroupSessionTabs";
895
- if (!J(o.profile, w) || Qe(n, g) !== !0 || n.features.desiredPreferences[g] === !1 || Object.values(n.interactions.devicePending).some((C) => C.feature === g && (y === "check" || C.action !== "check"))) return;
896
- const R = Se(o, "device", I), T = { ...n.interactions.deviceErrors };
897
- delete T[g], a({ deviceErrors: T, devicePending: { ...n.interactions.devicePending, [R]: { feature: g, requestId: I, generation: o.generation, desired: !0, action: y } } }), i.push({ kind: "stage7.device", id: R, input: { authority: o, requestId: I, feature: g, action: y, now: n.features.now } });
898
- }, u = (g, y) => {
899
- const I = y ? n.interactions.promptActions[y.replace(/:ack$/, "")] : void 0, w = { ...n.interactions.openings };
900
- for (const [R, T] of Object.entries(w)) {
901
- if (I?.scope === R && I.openingGeneration === T.generation && ["enable", "allow"].includes(I.action)) continue;
888
+ const f = Vr(n, e, s.conversation, s.directory);
889
+ if (!f.command) return { state: f.state, effects: f.effects };
890
+ const y = js(f.state, f.command, s);
891
+ return { state: y.state, effects: [...f.effects, ...y.effects] };
892
+ }
893
+ const l = (f, y, b) => {
894
+ const _ = f === "notifications" ? "canRequestNotificationPermission" : "canGroupSessionTabs";
895
+ if (!J(o.profile, _) || Qe(n, f) !== !0 || n.features.desiredPreferences[f] === !1 || Object.values(n.interactions.devicePending).some((C) => C.feature === f && (y === "check" || C.action !== "check"))) return;
896
+ const R = Se(o, "device", b), T = { ...n.interactions.deviceErrors };
897
+ delete T[f], a({ deviceErrors: T, devicePending: { ...n.interactions.devicePending, [R]: { feature: f, requestId: b, generation: o.generation, desired: !0, action: y } } }), i.push({ kind: "stage7.device", id: R, input: { authority: o, requestId: b, feature: f, action: y, now: n.features.now } });
898
+ }, u = (f, y) => {
899
+ const b = y ? n.interactions.promptActions[y.replace(/:ack$/, "")] : void 0, _ = { ...n.interactions.openings };
900
+ for (const [R, T] of Object.entries(_)) {
901
+ if (b?.scope === R && b.openingGeneration === T.generation && ["enable", "allow"].includes(b.action)) continue;
902
902
  const C = { ...T.shown };
903
- delete C[g], w[R] = {
903
+ delete C[f], _[R] = {
904
904
  ...T,
905
905
  shown: C,
906
- turns: Object.fromEntries(Object.entries(T.turns).map(([E, q]) => [E, { ...q, [g]: !1, [`${g}Suppressed`]: !0 }]))
906
+ turns: Object.fromEntries(Object.entries(T.turns).map(([E, q]) => [E, { ...q, [f]: !1, [`${f}Suppressed`]: !0 }]))
907
907
  };
908
908
  }
909
- a({ openings: w });
910
- }, p = (g, y = null) => {
911
- if (g.kind === "preferences" && n.account.preferences && g.value.preferencesVersion > n.account.preferences.preferencesVersion)
912
- for (const I of ["notifications", "tab_grouping"]) {
913
- const w = I === "notifications" ? "taskNotificationsEnabled" : "tabGroupingEnabled";
914
- g.value[w] !== n.account.preferences[w] && u(I, y);
915
- }
916
- if (g.kind === "preferencePrompts" || g.kind === "preferencePrompt")
917
- for (const I of ["notifications", "tab_grouping"]) {
918
- const w = g.kind === "preferencePrompts" ? g.value[I] : g.feature === I ? g.value : null;
919
- w && w.revision > n.interactions.preferencePrompts[I].revision && u(I, w.requestId);
920
- }
921
- g.kind === "preferences" && (n = { ...n, account: Wr(n.account, g.value) }), g.kind === "preferencePrompts" && (n = { ...n, interactions: jn(n.interactions, g.value) }), g.kind === "preferencePrompt" && (n = { ...n, interactions: jn(n.interactions, { ...n.interactions.preferencePrompts, [g.feature]: g.value }) }), g.kind === "decisions" && (n = { ...n, interactions: es(n.interactions, g.decisions) }), g.kind === "decision" && (n = { ...n, interactions: es(n.interactions, [g.value]) });
922
- }, f = (g, y) => {
923
- const I = n.interactions.deviceFacts[g];
924
- y.revision <= I.revision || (Qe(n, g) === !0 && (y.permission === "granted" && I.permission !== "granted" || y.snoozedUntil && y.snoozedUntil !== I.snoozedUntil) && u(g, null), a({ deviceFacts: { ...n.interactions.deviceFacts, [g]: y } }));
925
- }, m = (g, y, I = !1) => {
926
- et(o, g);
927
- const w = ue(o, g), R = Se(o, "query", y);
928
- if (g.kind === "originContext") {
929
- const q = n.features.queries[w], x = n.features.contextReads[w];
930
- if (r({ originContextQueries: { ...n.features.originContextQueries, [w]: g } }), !I && (q?.status === "ready" || q?.status === "error") && x && (n.features.now - x.settledAt < 3e4 || q.error && !q.error.retryable && q.error.code !== "runtime_error")) return;
909
+ a({ openings: _ });
910
+ }, p = (f, y = null) => {
911
+ if (f.kind === "preferences" && n.account.preferences && f.value.preferencesVersion > n.account.preferences.preferencesVersion)
912
+ for (const b of ["notifications", "tab_grouping"]) {
913
+ const _ = b === "notifications" ? "taskNotificationsEnabled" : "tabGroupingEnabled";
914
+ f.value[_] !== n.account.preferences[_] && u(b, y);
915
+ }
916
+ if (f.kind === "preferencePrompts" || f.kind === "preferencePrompt")
917
+ for (const b of ["notifications", "tab_grouping"]) {
918
+ const _ = f.kind === "preferencePrompts" ? f.value[b] : f.feature === b ? f.value : null;
919
+ _ && _.revision > n.interactions.preferencePrompts[b].revision && u(b, _.requestId);
920
+ }
921
+ f.kind === "preferences" && (n = { ...n, account: Wr(n.account, f.value) }), f.kind === "preferencePrompts" && (n = { ...n, interactions: jn(n.interactions, f.value) }), f.kind === "preferencePrompt" && (n = { ...n, interactions: jn(n.interactions, { ...n.interactions.preferencePrompts, [f.feature]: f.value }) }), f.kind === "decisions" && (n = { ...n, interactions: es(n.interactions, f.decisions) }), f.kind === "decision" && (n = { ...n, interactions: es(n.interactions, [f.value]) });
922
+ }, g = (f, y) => {
923
+ const b = n.interactions.deviceFacts[f];
924
+ y.revision <= b.revision || (Qe(n, f) === !0 && (y.permission === "granted" && b.permission !== "granted" || y.snoozedUntil && y.snoozedUntil !== b.snoozedUntil) && u(f, null), a({ deviceFacts: { ...n.interactions.deviceFacts, [f]: y } }));
925
+ }, m = (f, y, b = !1) => {
926
+ et(o, f);
927
+ const _ = ue(o, f), R = Se(o, "query", y);
928
+ if (f.kind === "originContext") {
929
+ const q = n.features.queries[_], O = n.features.contextReads[_];
930
+ if (r({ originContextQueries: { ...n.features.originContextQueries, [_]: f } }), !b && (q?.status === "ready" || q?.status === "error") && O && (n.features.now - O.settledAt < 3e4 || q.error && !q.error.retryable && q.error.code !== "runtime_error")) return;
931
931
  }
932
932
  const T = n.features.pending[R];
933
- if (T && T.fingerprint !== JSON.stringify(g)) throw new Error("Query request ID changed payload.");
934
- if (T?.status === "pending" || Object.values(n.features.pending).some((q) => q.mode === "query" && q.key === w && q.status === "pending")) return;
935
- const C = n.features.queries[w] ?? me(w), E = De(C, { key: w, requestId: re(y), mode: "replace" });
936
- r({ queries: { ...n.features.queries, [w]: E }, pending: { ...n.features.pending, [R]: {
933
+ if (T && T.fingerprint !== JSON.stringify(f)) throw new Error("Query request ID changed payload.");
934
+ if (T?.status === "pending" || Object.values(n.features.pending).some((q) => q.mode === "query" && q.key === _ && q.status === "pending")) return;
935
+ const C = n.features.queries[_] ?? me(_), E = De(C, { key: _, requestId: re(y), mode: "replace" });
936
+ r({ queries: { ...n.features.queries, [_]: E }, pending: { ...n.features.pending, [R]: {
937
937
  requestId: y,
938
938
  effectId: R,
939
- fingerprint: JSON.stringify(g),
940
- key: w,
939
+ fingerprint: JSON.stringify(f),
940
+ key: _,
941
941
  generation: o.generation,
942
- operation: g,
942
+ operation: f,
943
943
  mode: "query",
944
944
  status: "pending",
945
945
  error: null,
946
946
  result: null
947
- } } }), g.kind === "account" && (n = { ...n, account: { ...n.account, query: De(n.account.query, { key: w, requestId: re(y), mode: "replace" }) } }), i.push({ kind: "stage7.query", id: R, input: { authority: o, requestId: y, query: g } });
948
- }, h = (g, y, I = !1) => {
949
- if (et(o, g), g.kind === "report" && !n.account.query.data?.user?.isSuperuser) throw new Error("Chat reporting requires superuser access.");
950
- const w = Se(o, "mutate", y), R = JSON.stringify(g), T = n.features.pending[w];
947
+ } } }), f.kind === "account" && (n = { ...n, account: { ...n.account, query: De(n.account.query, { key: _, requestId: re(y), mode: "replace" }) } }), i.push({ kind: "stage7.query", id: R, input: { authority: o, requestId: y, query: f } });
948
+ }, h = (f, y, b = !1) => {
949
+ if (et(o, f), f.kind === "report" && !n.account.query.data?.user?.isSuperuser) throw new Error("Chat reporting requires superuser access.");
950
+ const _ = Se(o, "mutate", y), R = JSON.stringify(f), T = n.features.pending[_];
951
951
  if (T) {
952
952
  if (T.fingerprint !== R) throw new Error("Request ID was reused with a different payload.");
953
- if (!I || T.status !== "error") return;
954
- if (!["decision", "preferenceSnooze", "preferenceAcknowledge"].includes(g.kind)) throw new Error("This operation cannot be replayed automatically.");
953
+ if (!b || T.status !== "error") return;
954
+ if (!["decision", "preferenceSnooze", "preferenceAcknowledge"].includes(f.kind)) throw new Error("This operation cannot be replayed automatically.");
955
955
  if (["conflict", "409"].includes(T.error?.code ?? "")) throw new Error("Refresh the conflicting decision before making another choice.");
956
956
  }
957
- if (g.kind === "preference" && (r({ desiredPreferences: { ...n.features.desiredPreferences, [g.feature]: g.enabled } }), Object.values(n.features.pending).some((C) => C.status === "pending" && C.operation.kind === "preference" && C.operation.feature === g.feature))) {
958
- const C = n.features.queuedPreferences[g.feature];
957
+ if (f.kind === "preference" && (r({ desiredPreferences: { ...n.features.desiredPreferences, [f.feature]: f.enabled } }), Object.values(n.features.pending).some((C) => C.status === "pending" && C.operation.kind === "preference" && C.operation.feature === f.feature))) {
958
+ const C = n.features.queuedPreferences[f.feature];
959
959
  if (C && C.requestId !== y) {
960
- const E = Se(o, "mutate", C.requestId), q = { kind: "preference", feature: g.feature, enabled: C.enabled };
960
+ const E = Se(o, "mutate", C.requestId), q = { kind: "preference", feature: f.feature, enabled: C.enabled };
961
961
  r({ pending: { ...n.features.pending, [E]: {
962
962
  requestId: C.requestId,
963
963
  effectId: E,
@@ -971,27 +971,27 @@ function js(t, e, s) {
971
971
  error: { code: "preference_superseded", message: "A newer preference choice replaced this request.", retryable: !1 }
972
972
  } } });
973
973
  }
974
- r({ queuedPreferences: { ...n.features.queuedPreferences, [g.feature]: { requestId: y, enabled: g.enabled } } });
974
+ r({ queuedPreferences: { ...n.features.queuedPreferences, [f.feature]: { requestId: y, enabled: f.enabled } } });
975
975
  return;
976
976
  }
977
- if (g.kind === "generatePrompts") {
978
- const C = { kind: "starterPrompts", ...g.page, includeUserSuggestions: g.includeUserSuggestions ?? !1 }, E = ue(o, C), q = n.features.queries[E] ?? me(E);
977
+ if (f.kind === "generatePrompts") {
978
+ const C = { kind: "starterPrompts", ...f.page, includeUserSuggestions: f.includeUserSuggestions ?? !1 }, E = ue(o, C), q = n.features.queries[E] ?? me(E);
979
979
  r({ queries: { ...n.features.queries, [E]: De(q, { key: E, requestId: re(y), mode: "replace" }) } });
980
980
  }
981
- r({ pending: { ...n.features.pending, [w]: { requestId: y, effectId: w, fingerprint: R, key: Ln(g), generation: o.generation, operation: g, mode: "mutation", status: "pending", error: null, result: null } } }), i.push({ kind: "stage7.mutate", id: w, input: { authority: o, requestId: y, mutation: g } });
982
- }, v = (g) => {
981
+ r({ pending: { ...n.features.pending, [_]: { requestId: y, effectId: _, fingerprint: R, key: Ln(f), generation: o.generation, operation: f, mode: "mutation", status: "pending", error: null, result: null } } }), i.push({ kind: "stage7.mutate", id: _, input: { authority: o, requestId: y, mutation: f } });
982
+ }, v = (f) => {
983
983
  if (!(!J(o.profile, "canManagePreferences") || n.features.refreshBatch)) {
984
984
  for (const y of Object.values(n.features.pending))
985
985
  y.mode === "mutation" && y.operation.kind === "preferenceAcknowledge" && y.status === "error" && !["conflict", "409"].includes(y.error?.code ?? "") && h(y.operation, y.requestId, !0);
986
986
  for (const y of ["account", "preferences", "preferencePrompts", "decisions"])
987
- Object.values(n.features.pending).some((I) => I.mode === "query" && I.status === "pending" && I.operation.kind === y) || m({ kind: y }, `${g}:${y}`);
987
+ Object.values(n.features.pending).some((b) => b.mode === "query" && b.status === "pending" && b.operation.kind === y) || m({ kind: y }, `${f}:${y}`);
988
988
  r({ refreshAt: null, refreshBatch: { pending: Object.values(n.features.pending).filter((y) => y.mode === "query" && y.status === "pending" && ["account", "preferences", "preferencePrompts", "decisions"].includes(y.operation.kind)).map((y) => y.effectId), failed: !1 } });
989
989
  }
990
- }, b = (g, y) => {
991
- const I = n.features.refreshBatch;
992
- if (I?.pending.includes(g)) {
993
- const w = I.pending.filter((T) => T !== g), R = I.failed || y;
994
- if (w.length) r({ refreshBatch: { pending: w, failed: R } });
990
+ }, I = (f, y) => {
991
+ const b = n.features.refreshBatch;
992
+ if (b?.pending.includes(f)) {
993
+ const _ = b.pending.filter((T) => T !== f), R = b.failed || y;
994
+ if (_.length) r({ refreshBatch: { pending: _, failed: R } });
995
995
  else {
996
996
  const T = R ? n.features.failures + 1 : 0;
997
997
  r({ refreshBatch: null, failures: T, refreshAt: n.features.now + Math.min(6e4 * 2 ** T, 9e5) });
@@ -1002,22 +1002,22 @@ function js(t, e, s) {
1002
1002
  };
1003
1003
  switch (e.type) {
1004
1004
  case "stage7.account_refusal": {
1005
- const g = xt(void 0, e.code);
1006
- if (g.allowed) return { state: n, effects: i };
1007
- const y = { ...n.features.queries }, I = { ...n.features.pending }, w = [];
1008
- for (const [R, T] of Object.entries(I)) {
1005
+ const f = Ot(void 0, e.code);
1006
+ if (f.allowed) return { state: n, effects: i };
1007
+ const y = { ...n.features.queries }, b = { ...n.features.pending }, _ = [];
1008
+ for (const [R, T] of Object.entries(b)) {
1009
1009
  if (T.operation.kind !== "account" || T.status === "done" || T.status === "error") continue;
1010
1010
  const C = { code: e.code, message: "The backend refused account access. Refresh account status before retrying.", retryable: !0 };
1011
- I[R] = { ...T, status: "error", error: C }, w.push(R);
1011
+ b[R] = { ...T, status: "error", error: C }, _.push(R);
1012
1012
  const E = y[T.key];
1013
1013
  E && (y[T.key] = ct(E, { key: T.key, requestId: re(T.requestId), error: C }));
1014
1014
  }
1015
- n = { ...n, features: { ...n.features, pending: I, queries: y }, account: {
1015
+ n = { ...n, features: { ...n.features, pending: b, queries: y }, account: {
1016
1016
  ...n.account,
1017
- refusal: g,
1017
+ refusal: f,
1018
1018
  query: { ...n.account.query, requestId: null, status: n.account.query.data ? "ready" : "not_requested" }
1019
1019
  } };
1020
- for (const R of w) b(R, !0);
1020
+ for (const R of _) I(R, !0);
1021
1021
  break;
1022
1022
  }
1023
1023
  case "stage7.context_observe":
@@ -1025,8 +1025,8 @@ function js(t, e, s) {
1025
1025
  break;
1026
1026
  case "stage7.query":
1027
1027
  if (e.query.kind === "originContext" && (c(e.query.clientScopeId, e.query.origin), e.force)) {
1028
- const g = ue(o, e.query), y = { ...n.features.contextReads };
1029
- delete y[g], r({ contextReads: y });
1028
+ const f = ue(o, e.query), y = { ...n.features.contextReads };
1029
+ delete y[f], r({ contextReads: y });
1030
1030
  }
1031
1031
  m(e.query, e.requestId, e.force);
1032
1032
  break;
@@ -1034,16 +1034,16 @@ function js(t, e, s) {
1034
1034
  h(e.mutation, e.requestId);
1035
1035
  break;
1036
1036
  case "stage7.retry": {
1037
- const g = n.features.pending[Se(o, "mutate", e.requestId)];
1038
- if (!g || g.mode !== "mutation") throw new Error("Unknown mutation request.");
1039
- h(g.operation, e.requestId, !0);
1037
+ const f = n.features.pending[Se(o, "mutate", e.requestId)];
1038
+ if (!f || f.mode !== "mutation") throw new Error("Unknown mutation request.");
1039
+ h(f.operation, e.requestId, !0);
1040
1040
  break;
1041
1041
  }
1042
1042
  case "stage7.reconcile":
1043
1043
  if (r({ schedulerError: null }), e.reason !== "periodic" || n.features.refreshAt === null || e.now >= n.features.refreshAt) {
1044
1044
  if (e.reason === "startup" && r({ refreshRequired: !0 }), e.reason === "wake" || e.reason === "reconnect") {
1045
- const g = Object.values(n.features.pending).some((y) => y.mode === "query" && y.status === "pending" && ["account", "preferences", "preferencePrompts", "decisions"].includes(y.operation.kind));
1046
- r({ refreshRequired: !0, refreshQueuedRequestId: g ? `after:${e.requestId}` : n.features.refreshQueuedRequestId });
1045
+ const f = Object.values(n.features.pending).some((y) => y.mode === "query" && y.status === "pending" && ["account", "preferences", "preferencePrompts", "decisions"].includes(y.operation.kind));
1046
+ r({ refreshRequired: !0, refreshQueuedRequestId: f ? `after:${e.requestId}` : n.features.refreshQueuedRequestId });
1047
1047
  }
1048
1048
  v(e.requestId);
1049
1049
  }
@@ -1056,77 +1056,77 @@ function js(t, e, s) {
1056
1056
  break;
1057
1057
  case "stage7.restore_prompt_openings": {
1058
1058
  if (!o.profile.startsWith("extension_")) throw new Error("Prompt restoration requires an extension opening checkpoint.");
1059
- const g = new Set(Object.values(s.directory.clients)), y = Object.fromEntries(Object.entries(e.checkpoint.openings).filter(([I, w]) => g.has(I) && s.directory.selections[I]?.sessionId === w.sessionId));
1059
+ const f = new Set(Object.values(s.directory.clients)), y = Object.fromEntries(Object.entries(e.checkpoint.openings).filter(([b, _]) => f.has(b) && s.directory.selections[b]?.sessionId === _.sessionId));
1060
1060
  a({ ...e.checkpoint, openings: y, openingGeneration: Math.max(n.interactions.openingGeneration, e.checkpoint.openingGeneration) });
1061
1061
  break;
1062
1062
  }
1063
1063
  case "stage7.prompt_view": {
1064
- const g = s.directory.clients[e.clientScopeId];
1065
- if (!g) break;
1064
+ const f = s.directory.clients[e.clientScopeId];
1065
+ if (!f) break;
1066
1066
  const y = { ...n.interactions.openings };
1067
- e.open || delete y[g], a({ openings: y, closedScopes: { ...n.interactions.closedScopes, [g]: !e.open } }), n = Yt(n, s.conversation, s.directory, e.now);
1067
+ e.open || delete y[f], a({ openings: y, closedScopes: { ...n.interactions.closedScopes, [f]: !e.open } }), n = Yt(n, s.conversation, s.directory, e.now);
1068
1068
  break;
1069
1069
  }
1070
1070
  case "stage7.prompt_shown": {
1071
- const g = s.directory.clients[e.clientScopeId], y = n.interactions.openings[g];
1071
+ const f = s.directory.clients[e.clientScopeId], y = n.interactions.openings[f];
1072
1072
  if (!y || y.generation !== e.openingGeneration) break;
1073
- const I = Ci(n, g, e.feature);
1074
- I && a({ openings: { ...n.interactions.openings, [g]: { ...y, shown: { ...y.shown, [e.feature]: I } } } });
1073
+ const b = Ci(n, f, e.feature);
1074
+ b && a({ openings: { ...n.interactions.openings, [f]: { ...y, shown: { ...y.shown, [e.feature]: b } } } });
1075
1075
  break;
1076
1076
  }
1077
1077
  case "stage7.cross_tab": {
1078
1078
  a({ crossTabTurns: { ...n.interactions.crossTabTurns, [e.sessionId]: [.../* @__PURE__ */ new Set([...n.interactions.crossTabTurns[e.sessionId] ?? [], e.userMessageId])] } });
1079
- const g = { ...n.interactions.openings };
1080
- for (const [y, I] of Object.entries(g)) {
1081
- const w = I.turns[e.userMessageId];
1082
- I.sessionId === e.sessionId && w && !w.tab_groupingSuppressed && (g[y] = { ...I, turns: { ...I.turns, [e.userMessageId]: { ...w, tab_grouping: !0 } } });
1079
+ const f = { ...n.interactions.openings };
1080
+ for (const [y, b] of Object.entries(f)) {
1081
+ const _ = b.turns[e.userMessageId];
1082
+ b.sessionId === e.sessionId && _ && !_.tab_groupingSuppressed && (f[y] = { ...b, turns: { ...b.turns, [e.userMessageId]: { ..._, tab_grouping: !0 } } });
1083
1083
  }
1084
- a({ openings: g });
1084
+ a({ openings: f });
1085
1085
  break;
1086
1086
  }
1087
1087
  case "stage7.permission": {
1088
1088
  if (Qe(n, e.feature) !== !0) throw new Error("Permission setup requires a saved On preference.");
1089
- const g = n.interactions.deviceFacts[e.feature].snoozedUntil;
1090
- if (!e.settings && g && Date.parse(g) > e.now) break;
1089
+ const f = n.interactions.deviceFacts[e.feature].snoozedUntil;
1090
+ if (!e.settings && f && Date.parse(f) > e.now) break;
1091
1091
  l(e.feature, e.action, e.requestId);
1092
1092
  break;
1093
1093
  }
1094
1094
  case "stage7.device_fact":
1095
- f(e.feature, e.fact);
1095
+ g(e.feature, e.fact);
1096
1096
  break;
1097
1097
  case "stage7.import_legacy_decisions":
1098
- if (!o.profile.startsWith("extension_") || e.decisions.some((g) => g.revision !== 0)) throw new Error("Invalid legacy decision import.");
1098
+ if (!o.profile.startsWith("extension_") || e.decisions.some((f) => f.revision !== 0)) throw new Error("Invalid legacy decision import.");
1099
1099
  n = { ...n, interactions: es(n.interactions, e.decisions) };
1100
1100
  break;
1101
1101
  case "stage7.device_hints": {
1102
1102
  if (o.profile !== "main_web_chat") throw new Error("Main-web hints unavailable.");
1103
- const g = { ...n.interactions.deviceHints };
1104
- for (const [y, I] of Object.entries(e.hints)) g[y] = g[y] === !0 || I;
1105
- a({ deviceHints: g });
1103
+ const f = { ...n.interactions.deviceHints };
1104
+ for (const [y, b] of Object.entries(e.hints)) f[y] = f[y] === !0 || b;
1105
+ a({ deviceHints: f });
1106
1106
  break;
1107
1107
  }
1108
1108
  case "stage7.local_sharing": {
1109
- const g = { ...n.interactions.localSharing };
1110
- for (const [y, I] of Object.entries(e.decisions))
1111
- (!g[y] || I.revision > g[y].revision) && (g[y] = I);
1112
- a({ localSharing: g, localSharingReady: !0 });
1109
+ const f = { ...n.interactions.localSharing };
1110
+ for (const [y, b] of Object.entries(e.decisions))
1111
+ (!f[y] || b.revision > f[y].revision) && (f[y] = b);
1112
+ a({ localSharing: f, localSharingReady: !0 });
1113
1113
  break;
1114
1114
  }
1115
1115
  case "stage7.sources": {
1116
- const g = { ...n.interactions.sources };
1116
+ const f = { ...n.interactions.sources };
1117
1117
  for (const y of e.sources) {
1118
1118
  if (!Number.isSafeInteger(y.version) || y.version < 0) throw new Error("Invalid source version.");
1119
- const I = JSON.stringify([y.conversation_id, y.id]), w = g[I];
1120
- if (!(w && w.version >= y.version)) {
1121
- if (w && w.payload.kind !== y.payload.kind) throw new Error("Interaction source changed category.");
1122
- g[I] = {
1119
+ const b = JSON.stringify([y.conversation_id, y.id]), _ = f[b];
1120
+ if (!(_ && _.version >= y.version)) {
1121
+ if (_ && _.payload.kind !== y.payload.kind) throw new Error("Interaction source changed category.");
1122
+ f[b] = {
1123
1123
  ...y,
1124
- lifecycle: w?.lifecycle === "completed" ? "completed" : y.lifecycle,
1125
- payload: w?.payload.kind === "sharing" && y.payload.kind === "sharing" ? { ...y.payload, variant: w.payload.variant } : y.payload
1124
+ lifecycle: _?.lifecycle === "completed" ? "completed" : y.lifecycle,
1125
+ payload: _?.payload.kind === "sharing" && y.payload.kind === "sharing" ? { ...y.payload, variant: _.payload.variant } : y.payload
1126
1126
  };
1127
1127
  }
1128
1128
  }
1129
- a({ sources: g });
1129
+ a({ sources: f });
1130
1130
  break;
1131
1131
  }
1132
1132
  case "stage7.local_style":
@@ -1135,11 +1135,11 @@ function js(t, e, s) {
1135
1135
  break;
1136
1136
  case "stage7.morning": {
1137
1137
  if (!e.text?.trim()) {
1138
- const I = { ...n.interactions.welcome };
1139
- delete I[e.id], a({ welcome: I });
1138
+ const b = { ...n.interactions.welcome };
1139
+ delete b[e.id], a({ welcome: b });
1140
1140
  break;
1141
1141
  }
1142
- const g = e.signupAgeDays, y = e.retained === !0 || e.localHour >= 5 && e.lastShownDate !== e.localDate && (g === 1 || g === 3 || g === 5 || g >= 7 && g % 7 === 0);
1142
+ const f = e.signupAgeDays, y = e.retained === !0 || e.localHour >= 5 && e.lastShownDate !== e.localDate && (f === 1 || f === 3 || f === 5 || f >= 7 && f % 7 === 0);
1143
1143
  a({ welcome: { ...n.interactions.welcome, [e.id]: { id: e.id, text: e.text, tasks: e.tasks, category: "morning_report", eligible: y } } });
1144
1144
  break;
1145
1145
  }
@@ -1148,8 +1148,8 @@ function js(t, e, s) {
1148
1148
  break;
1149
1149
  case "stage7.deep_flow": {
1150
1150
  if (!J(o.profile, "canStartDeepFlow")) throw new Error("Deep flow unavailable.");
1151
- const g = n.features.deepFlows[e.clientScopeId];
1152
- if ((g?.id ?? null) !== e.expectedId || g && e.flow && e.flow.id !== g.id || e.flow && g && g.status !== "running") break;
1151
+ const f = n.features.deepFlows[e.clientScopeId];
1152
+ if ((f?.id ?? null) !== e.expectedId || f && e.flow && e.flow.id !== f.id || e.flow && f && f.status !== "running") break;
1153
1153
  const y = { ...n.features.deepFlows };
1154
1154
  e.flow ? y[e.clientScopeId] = e.flow : delete y[e.clientScopeId], r({ deepFlows: y });
1155
1155
  break;
@@ -1160,166 +1160,166 @@ function js(t, e, s) {
1160
1160
  if (e.effectId !== n.features.timerId) break;
1161
1161
  if (r({ timerId: null, timerDeadline: null, schedulerError: e.type === "effect.failed" ? e.error : null }), e.type === "effect.completed") {
1162
1162
  r({ now: e.output.now }), n = Yt(n, s.conversation, s.directory, e.output.now);
1163
- for (const [I, w] of Object.entries(n.features.polls)) {
1164
- if (w.deadline > e.output.now) continue;
1165
- Object.values(n.features.pending).some((T) => T.mode === "query" && T.key === I && T.status === "pending") || m(w.query.kind === "originContext" ? { ...w.query, trigger: "poll" } : w.query, `poll:${I}:${e.output.now}`, !0);
1163
+ for (const [b, _] of Object.entries(n.features.polls)) {
1164
+ if (_.deadline > e.output.now) continue;
1165
+ Object.values(n.features.pending).some((T) => T.mode === "query" && T.key === b && T.status === "pending") || m(_.query.kind === "originContext" ? { ..._.query, trigger: "poll" } : _.query, `poll:${b}:${e.output.now}`, !0);
1166
1166
  const R = { ...n.features.polls };
1167
- delete R[I], r({ polls: R });
1167
+ delete R[b], r({ polls: R });
1168
1168
  }
1169
1169
  n.features.refreshAt !== null && e.output.now >= n.features.refreshAt && v(`timer:${e.output.now}`);
1170
1170
  }
1171
1171
  break;
1172
1172
  }
1173
1173
  if (e.effectKind === "stage7.device") {
1174
- const I = n.interactions.devicePending[e.effectId];
1175
- if (!I) break;
1176
- const w = { ...n.interactions.devicePending };
1177
- if (delete w[e.effectId], a({ devicePending: w }), e.type === "effect.completed") {
1178
- if (I.action !== "check" && n.interactions.promptActions[I.requestId] && !n.features.pending[Se(o, "mutate", `${I.requestId}:ack`)]) {
1179
- const R = n.interactions.promptActions[I.requestId];
1180
- u(R.feature, I.requestId), h({
1174
+ const b = n.interactions.devicePending[e.effectId];
1175
+ if (!b) break;
1176
+ const _ = { ...n.interactions.devicePending };
1177
+ if (delete _[e.effectId], a({ devicePending: _ }), e.type === "effect.completed") {
1178
+ if (b.action !== "check" && n.interactions.promptActions[b.requestId] && !n.features.pending[Se(o, "mutate", `${b.requestId}:ack`)]) {
1179
+ const R = n.interactions.promptActions[b.requestId];
1180
+ u(R.feature, b.requestId), h({
1181
1181
  kind: "preferenceAcknowledge",
1182
1182
  feature: R.feature,
1183
1183
  action: R.action,
1184
1184
  expectedRevision: R.expectedRevision
1185
- }, `${I.requestId}:ack`);
1185
+ }, `${b.requestId}:ack`);
1186
1186
  }
1187
- f(I.feature, e.output.fact);
1188
- } else Qe(n, I.feature) === !0 && n.features.desiredPreferences[I.feature] !== !1 && a({ deviceErrors: { ...n.interactions.deviceErrors, [I.feature]: e.error } });
1187
+ g(b.feature, e.output.fact);
1188
+ } else Qe(n, b.feature) === !0 && n.features.desiredPreferences[b.feature] !== !1 && a({ deviceErrors: { ...n.interactions.deviceErrors, [b.feature]: e.error } });
1189
1189
  break;
1190
1190
  }
1191
- const g = n.features.pending[e.effectId];
1192
- if (!g || g.status !== "pending" || g.generation !== o.generation) break;
1191
+ const f = n.features.pending[e.effectId];
1192
+ if (!f || f.status !== "pending" || f.generation !== o.generation) break;
1193
1193
  const y = e.type === "effect.failed";
1194
- if (r({ pending: { ...n.features.pending, [e.effectId]: { ...g, status: y ? "error" : "done", error: y ? e.error : null, result: y ? null : e.output.data } } }), g.mode === "query") {
1195
- const I = { ...n.features.pending };
1196
- delete I[e.effectId], r({ pending: I });
1197
- const w = n.features.queries[g.key];
1198
- if (!w || w.requestId !== g.requestId) break;
1199
- if (["originContext", "userContext", "contextRun"].includes(g.operation.kind)) {
1194
+ if (r({ pending: { ...n.features.pending, [e.effectId]: { ...f, status: y ? "error" : "done", error: y ? e.error : null, result: y ? null : e.output.data } } }), f.mode === "query") {
1195
+ const b = { ...n.features.pending };
1196
+ delete b[e.effectId], r({ pending: b });
1197
+ const _ = n.features.queries[f.key];
1198
+ if (!_ || _.requestId !== f.requestId) break;
1199
+ if (["originContext", "userContext", "contextRun"].includes(f.operation.kind)) {
1200
1200
  const R = { ...n.features.polls };
1201
- delete R[g.key], r({ polls: R, contextReads: { ...n.features.contextReads, [g.key]: {
1201
+ delete R[f.key], r({ polls: R, contextReads: { ...n.features.contextReads, [f.key]: {
1202
1202
  settledAt: y ? n.features.now : e.output.completedAt,
1203
- failures: y ? (n.features.contextReads[g.key]?.failures ?? 0) + 1 : 0
1203
+ failures: y ? (n.features.contextReads[f.key]?.failures ?? 0) + 1 : 0
1204
1204
  } } });
1205
1205
  }
1206
1206
  if (y)
1207
- r({ queries: { ...n.features.queries, [g.key]: ct(w, { key: g.key, requestId: re(g.requestId), error: e.error }) } }), g.operation.kind === "account" && (n = { ...n, account: { ...n.account, query: ct(n.account.query, { key: g.key, requestId: re(g.requestId), error: e.error }) } });
1207
+ r({ queries: { ...n.features.queries, [f.key]: ct(_, { key: f.key, requestId: re(f.requestId), error: e.error }) } }), f.operation.kind === "account" && (n = { ...n, account: { ...n.account, query: ct(n.account.query, { key: f.key, requestId: re(f.requestId), error: e.error }) } });
1208
1208
  else {
1209
- if (e.output.data.kind !== g.operation.kind) throw new Error("Feature response kind does not match the query.");
1210
- r({ now: e.output.completedAt, queries: { ...n.features.queries, [g.key]: Zt(w, { key: g.key, requestId: re(g.requestId), data: e.output.data, cursor: null, updatedAt: e.output.completedAt }) } }), p(e.output.data, g.requestId), e.output.data.kind === "account" && (n = { ...n, account: { ...n.account, refusal: null, query: Zt(n.account.query, { key: g.key, requestId: re(g.requestId), data: e.output.data.value, cursor: null, updatedAt: e.output.completedAt }) } });
1209
+ if (e.output.data.kind !== f.operation.kind) throw new Error("Feature response kind does not match the query.");
1210
+ r({ now: e.output.completedAt, queries: { ...n.features.queries, [f.key]: Zt(_, { key: f.key, requestId: re(f.requestId), data: e.output.data, cursor: null, updatedAt: e.output.completedAt }) } }), p(e.output.data, f.requestId), e.output.data.kind === "account" && (n = { ...n, account: { ...n.account, refusal: null, query: Zt(n.account.query, { key: f.key, requestId: re(f.requestId), data: e.output.data.value, cursor: null, updatedAt: e.output.completedAt }) } });
1211
1211
  }
1212
1212
  } else if (!y)
1213
- r({ now: e.output.completedAt }), p(e.output.data, g.requestId);
1213
+ r({ now: e.output.completedAt }), p(e.output.data, f.requestId);
1214
1214
  else if (["conflict", "409"].includes(e.error.code)) {
1215
- const I = g.operation.kind === "decision" ? "decisions" : g.operation.kind === "preferenceSnooze" || g.operation.kind === "preferenceAcknowledge" ? "preferencePrompts" : "preferences";
1216
- m({ kind: I }, `conflict:${g.requestId}`);
1217
- }
1218
- if (g.mode === "mutation" && g.operation.kind === "decision") {
1219
- const I = { ...n.interactions.actions };
1220
- for (const [w, R] of Object.entries(I))
1221
- R.step === "persist" && g.requestId === `sharing:${w}` && (R.operation.kind === "copy" || R.operation.kind === "share") && (I[w] = { ...R, status: y ? "error" : "done", error: y ? e.error : null });
1222
- a({ actions: I });
1223
- }
1224
- if (!y && g.mode === "mutation" && g.operation.kind === "preference" && n.interactions.promptActions[g.requestId]) {
1225
- const I = n.interactions.promptActions[g.requestId];
1226
- u(I.feature, g.requestId), h({
1215
+ const b = f.operation.kind === "decision" ? "decisions" : f.operation.kind === "preferenceSnooze" || f.operation.kind === "preferenceAcknowledge" ? "preferencePrompts" : "preferences";
1216
+ m({ kind: b }, `conflict:${f.requestId}`);
1217
+ }
1218
+ if (f.mode === "mutation" && f.operation.kind === "decision") {
1219
+ const b = { ...n.interactions.actions };
1220
+ for (const [_, R] of Object.entries(b))
1221
+ R.step === "persist" && f.requestId === `sharing:${_}` && (R.operation.kind === "copy" || R.operation.kind === "share") && (b[_] = { ...R, status: y ? "error" : "done", error: y ? e.error : null });
1222
+ a({ actions: b });
1223
+ }
1224
+ if (!y && f.mode === "mutation" && f.operation.kind === "preference" && n.interactions.promptActions[f.requestId]) {
1225
+ const b = n.interactions.promptActions[f.requestId];
1226
+ u(b.feature, f.requestId), h({
1227
1227
  kind: "preferenceAcknowledge",
1228
- feature: I.feature,
1229
- action: I.action,
1230
- expectedRevision: I.expectedRevision
1231
- }, `${g.requestId}:ack`);
1228
+ feature: b.feature,
1229
+ action: b.action,
1230
+ expectedRevision: b.expectedRevision
1231
+ }, `${f.requestId}:ack`);
1232
1232
  }
1233
- if (b(e.effectId, y), g.operation.kind === "generatePrompts") {
1234
- const I = { kind: "starterPrompts", ...g.operation.page, includeUserSuggestions: g.operation.includeUserSuggestions ?? !1 }, w = ue(o, I), R = n.features.queries[w];
1235
- R?.requestId === g.requestId && r({ queries: { ...n.features.queries, [w]: y ? ct(R, { key: w, requestId: re(g.requestId), error: e.error }) : Zt(R, { key: w, requestId: re(g.requestId), data: e.output.data, cursor: null, updatedAt: e.output.completedAt }) } });
1233
+ if (I(e.effectId, y), f.operation.kind === "generatePrompts") {
1234
+ const b = { kind: "starterPrompts", ...f.operation.page, includeUserSuggestions: f.operation.includeUserSuggestions ?? !1 }, _ = ue(o, b), R = n.features.queries[_];
1235
+ R?.requestId === f.requestId && r({ queries: { ...n.features.queries, [_]: y ? ct(R, { key: _, requestId: re(f.requestId), error: e.error }) : Zt(R, { key: _, requestId: re(f.requestId), data: e.output.data, cursor: null, updatedAt: e.output.completedAt }) } });
1236
1236
  }
1237
1237
  if (!y && e.output.data.kind === "originContext") {
1238
- const I = e.output.data, w = g.operation.kind === "originContext" || g.operation.kind === "refreshContext" ? g.operation.origin : null;
1239
- if (w) {
1240
- if (I.value.runId && ["queued", "pending", "running", "in_progress", "stopping", "cancel_requested"].includes(I.value.status))
1241
- r({ contextRunOrigins: { ...n.features.contextRunOrigins, [I.value.runId]: w } });
1238
+ const b = e.output.data, _ = f.operation.kind === "originContext" || f.operation.kind === "refreshContext" ? f.operation.origin : null;
1239
+ if (_) {
1240
+ if (b.value.runId && ["queued", "pending", "running", "in_progress", "stopping", "cancel_requested"].includes(b.value.status))
1241
+ r({ contextRunOrigins: { ...n.features.contextRunOrigins, [b.value.runId]: _ } });
1242
1242
  else {
1243
1243
  const R = { ...n.features.contextRunOrigins };
1244
- for (const [T, C] of Object.entries(R)) C === w && delete R[T];
1244
+ for (const [T, C] of Object.entries(R)) C === _ && delete R[T];
1245
1245
  r({ contextRunOrigins: R });
1246
1246
  }
1247
- if (g.mode === "mutation") {
1247
+ if (f.mode === "mutation") {
1248
1248
  const R = { ...n.features.queries }, T = { ...n.features.pending }, C = { ...n.features.contextReads }, E = { ...n.features.polls };
1249
- for (const [q, x] of Object.entries(n.features.originContextQueries))
1250
- if (x.origin === w) {
1251
- R[q] = { ...R[q], data: I, status: "ready", error: null, requestId: null, updatedAt: e.output.completedAt }, C[q] = { settledAt: e.output.completedAt, failures: 0 }, delete E[q];
1252
- for (const [_, O] of Object.entries(T)) O.mode === "query" && O.key === q && delete T[_];
1253
- ["queued", "pending", "running", "in_progress", "stopping", "cancel_requested"].includes(I.value.status) && (E[q] = { query: { ...x, kind: "originContext", trigger: "poll" }, deadline: n.features.now + 5e3 });
1249
+ for (const [q, O] of Object.entries(n.features.originContextQueries))
1250
+ if (O.origin === _) {
1251
+ R[q] = { ...R[q], data: b, status: "ready", error: null, requestId: null, updatedAt: e.output.completedAt }, C[q] = { settledAt: e.output.completedAt, failures: 0 }, delete E[q];
1252
+ for (const [S, x] of Object.entries(T)) x.mode === "query" && x.key === q && delete T[S];
1253
+ ["queued", "pending", "running", "in_progress", "stopping", "cancel_requested"].includes(b.value.status) && (E[q] = { query: { ...O, kind: "originContext", trigger: "poll" }, deadline: n.features.now + 5e3 });
1254
1254
  }
1255
1255
  r({ queries: R, pending: T, contextReads: C, polls: E });
1256
1256
  }
1257
1257
  }
1258
1258
  }
1259
1259
  if (!y && e.output.data.kind === "contextRun" && !["queued", "pending", "running", "in_progress", "stopping", "cancel_requested"].includes(e.output.data.value.status)) {
1260
- const I = e.output.data.value.runId, w = I ? n.features.contextRunOrigins[I] : null;
1261
- if (w && I) {
1260
+ const b = e.output.data.value.runId, _ = b ? n.features.contextRunOrigins[b] : null;
1261
+ if (_ && b) {
1262
1262
  const R = { ...n.features.contextRunOrigins };
1263
- delete R[I], r({ contextRunOrigins: R });
1263
+ delete R[b], r({ contextRunOrigins: R });
1264
1264
  for (const [T, C] of Object.entries(n.features.originContextQueries)) {
1265
- if (C.origin !== w) continue;
1265
+ if (C.origin !== _) continue;
1266
1266
  const E = { ...n.features.pending };
1267
- for (const [q, x] of Object.entries(E)) x.mode === "query" && x.key === T && delete E[q];
1268
- r({ pending: E }), m({ ...C, kind: "originContext" }, `context-final:${g.requestId}:${T}`, !0);
1267
+ for (const [q, O] of Object.entries(E)) O.mode === "query" && O.key === T && delete E[q];
1268
+ r({ pending: E }), m({ ...C, kind: "originContext" }, `context-final:${f.requestId}:${T}`, !0);
1269
1269
  }
1270
1270
  }
1271
1271
  }
1272
1272
  if (!y && ["originContext", "userContext", "contextRun"].includes(e.output.data.kind)) {
1273
- const I = e.output.data;
1274
- if (I.kind === "originContext" || I.kind === "userContext" || I.kind === "contextRun") {
1275
- const w = I.kind === "originContext" ? g.mode === "query" && g.operation.kind === "originContext" && Object.values(n.features.contextObservers).includes(g.key) ? g.operation : null : I.kind === "userContext" ? { kind: "userContext" } : I.value.runId ? { kind: "contextRun", runId: I.value.runId } : null;
1276
- if (w && ["queued", "pending", "running", "in_progress", "stopping", "cancel_requested"].includes(I.value.status)) {
1277
- const R = ue(o, w);
1278
- r({ polls: { ...n.features.polls, [R]: { query: w, deadline: n.features.now + 5e3 } } });
1273
+ const b = e.output.data;
1274
+ if (b.kind === "originContext" || b.kind === "userContext" || b.kind === "contextRun") {
1275
+ const _ = b.kind === "originContext" ? f.mode === "query" && f.operation.kind === "originContext" && Object.values(n.features.contextObservers).includes(f.key) ? f.operation : null : b.kind === "userContext" ? { kind: "userContext" } : b.value.runId ? { kind: "contextRun", runId: b.value.runId } : null;
1276
+ if (_ && ["queued", "pending", "running", "in_progress", "stopping", "cancel_requested"].includes(b.value.status)) {
1277
+ const R = ue(o, _);
1278
+ r({ polls: { ...n.features.polls, [R]: { query: _, deadline: n.features.now + 5e3 } } });
1279
1279
  }
1280
1280
  }
1281
1281
  }
1282
- if (!y && g.operation.kind === "stopContext")
1283
- for (const [I, w] of Object.entries(n.features.originContextQueries)) {
1284
- const R = n.features.queries[I]?.data;
1285
- if (R?.kind === "originContext" && R.value.runId === g.operation.runId) {
1282
+ if (!y && f.operation.kind === "stopContext")
1283
+ for (const [b, _] of Object.entries(n.features.originContextQueries)) {
1284
+ const R = n.features.queries[b]?.data;
1285
+ if (R?.kind === "originContext" && R.value.runId === f.operation.runId) {
1286
1286
  const T = { ...n.features.pending };
1287
- for (const [C, E] of Object.entries(T)) E.mode === "query" && E.key === I && delete T[C];
1288
- r({ pending: T }), m({ ...w, kind: "originContext" }, `context-stop:${g.requestId}:${I}`, !0);
1287
+ for (const [C, E] of Object.entries(T)) E.mode === "query" && E.key === b && delete T[C];
1288
+ r({ pending: T }), m({ ..._, kind: "originContext" }, `context-stop:${f.requestId}:${b}`, !0);
1289
1289
  }
1290
1290
  }
1291
- if (y && g.mode === "query" && ["originContext", "userContext", "contextRun"].includes(g.operation.kind) && e.error.retryable && (n.features.contextReads[g.key]?.failures ?? 0) <= 3) {
1292
- const I = g.operation, w = ue(o, I);
1293
- r({ polls: { ...n.features.polls, [w]: { query: I, deadline: n.features.now + 5e3 * (n.features.contextReads[g.key]?.failures ?? 1) } } });
1291
+ if (y && f.mode === "query" && ["originContext", "userContext", "contextRun"].includes(f.operation.kind) && e.error.retryable && (n.features.contextReads[f.key]?.failures ?? 0) <= 3) {
1292
+ const b = f.operation, _ = ue(o, b);
1293
+ r({ polls: { ...n.features.polls, [_]: { query: b, deadline: n.features.now + 5e3 * (n.features.contextReads[f.key]?.failures ?? 1) } } });
1294
1294
  }
1295
- if (g.operation.kind === "preference") {
1296
- const I = g.operation.feature, w = n.features.queuedPreferences[I];
1297
- if (w) {
1295
+ if (f.operation.kind === "preference") {
1296
+ const b = f.operation.feature, _ = n.features.queuedPreferences[b];
1297
+ if (_) {
1298
1298
  const R = { ...n.features.queuedPreferences };
1299
- delete R[I], r({ queuedPreferences: R }), h({ kind: "preference", feature: I, enabled: w.enabled }, w.requestId);
1299
+ delete R[b], r({ queuedPreferences: R }), h({ kind: "preference", feature: b, enabled: _.enabled }, _.requestId);
1300
1300
  } else {
1301
1301
  const R = { ...n.features.desiredPreferences };
1302
- delete R[I], r({ desiredPreferences: R });
1302
+ delete R[b], r({ desiredPreferences: R });
1303
1303
  }
1304
1304
  }
1305
- if (!y && e.output.data.kind === "preferences") for (const I of ["notifications", "tab_grouping"]) l(I, "check", `preference:${g.requestId}:${I}`);
1306
- n.features.refreshRequired && !n.features.refreshBatch && !n.features.refreshQueuedRequestId && ["account", "preferences", "preferencePrompts", "decisions"].every((I) => Object.values(n.features.queries).some((w) => w.data?.kind === I && w.status === "ready")) && r({ refreshRequired: !1 });
1305
+ if (!y && e.output.data.kind === "preferences") for (const b of ["notifications", "tab_grouping"]) l(b, "check", `preference:${f.requestId}:${b}`);
1306
+ n.features.refreshRequired && !n.features.refreshBatch && !n.features.refreshQueuedRequestId && ["account", "preferences", "preferencePrompts", "decisions"].every((b) => Object.values(n.features.queries).some((_) => _.data?.kind === b && _.status === "ready")) && r({ refreshRequired: !1 });
1307
1307
  break;
1308
1308
  }
1309
1309
  }
1310
- const S = [
1310
+ const k = [
1311
1311
  n.features.refreshAt,
1312
- ...Object.values(n.interactions.openings).flatMap((g) => Object.values(g.turns).filter((y) => y.active && !y.notifications && !y.notificationsSuppressed).map((y) => y.startedAt + 1e4)),
1313
- ...Object.values(n.interactions.welcome).map((g) => g.eligible ? g.expiresAt ?? null : null),
1314
- ...Object.values(n.interactions.sources).map((g) => g.lifecycle === "pending" && g.payload.kind === "integration_auth" ? Date.parse(g.payload.expires_at) : null),
1315
- ...Object.values(n.features.polls).map((g) => g.deadline),
1316
- ...Object.values(n.interactions.decisions).map((g) => g.nextEligibleAt ? Date.parse(g.nextEligibleAt) : null),
1317
- ...Object.values(n.interactions.preferencePrompts).map((g) => g.snoozedUntil ? Date.parse(g.snoozedUntil) : null),
1318
- ...Object.values(n.interactions.deviceFacts).map((g) => g.snoozedUntil ? Date.parse(g.snoozedUntil) : null)
1319
- ].filter((g) => g !== null && g > n.features.now), k = S.length ? Math.min(...S) : null;
1320
- if (k !== n.features.timerDeadline && !n.features.schedulerError) {
1321
- const g = n.features.timerRevision + 1, y = k === null ? null : Se(o, "wait", `${g}:${k}`);
1322
- r({ timerId: y, timerDeadline: k, timerRevision: g }), k !== null && y && i.push({ kind: "stage7.wait", id: y, input: { authority: o, deadline: k } });
1312
+ ...Object.values(n.interactions.openings).flatMap((f) => Object.values(f.turns).filter((y) => y.active && !y.notifications && !y.notificationsSuppressed).map((y) => y.startedAt + 1e4)),
1313
+ ...Object.values(n.interactions.welcome).map((f) => f.eligible ? f.expiresAt ?? null : null),
1314
+ ...Object.values(n.interactions.sources).map((f) => f.lifecycle === "pending" && f.payload.kind === "integration_auth" ? Date.parse(f.payload.expires_at) : null),
1315
+ ...Object.values(n.features.polls).map((f) => f.deadline),
1316
+ ...Object.values(n.interactions.decisions).map((f) => f.nextEligibleAt ? Date.parse(f.nextEligibleAt) : null),
1317
+ ...Object.values(n.interactions.preferencePrompts).map((f) => f.snoozedUntil ? Date.parse(f.snoozedUntil) : null),
1318
+ ...Object.values(n.interactions.deviceFacts).map((f) => f.snoozedUntil ? Date.parse(f.snoozedUntil) : null)
1319
+ ].filter((f) => f !== null && f > n.features.now), w = k.length ? Math.min(...k) : null;
1320
+ if (w !== n.features.timerDeadline && !n.features.schedulerError) {
1321
+ const f = n.features.timerRevision + 1, y = w === null ? null : Se(o, "wait", `${f}:${w}`);
1322
+ r({ timerId: y, timerDeadline: w, timerRevision: f }), w !== null && y && i.push({ kind: "stage7.wait", id: y, input: { authority: o, deadline: w } });
1323
1323
  }
1324
1324
  return { state: n, effects: i };
1325
1325
  }
@@ -1376,7 +1376,7 @@ function P(t) {
1376
1376
  function ce(t) {
1377
1377
  return t == null ? null : P(t);
1378
1378
  }
1379
- function xe(t) {
1379
+ function Oe(t) {
1380
1380
  if (typeof t != "number" || !Number.isSafeInteger(t) || t < 0) throw new Error("Invalid feature revision.");
1381
1381
  return t;
1382
1382
  }
@@ -1401,23 +1401,23 @@ function ze(t) {
1401
1401
  return {
1402
1402
  taskNotificationsEnabled: ts(e.taskNotificationsEnabled),
1403
1403
  tabGroupingEnabled: ts(e.tabGroupingEnabled),
1404
- preferencesVersion: xe(e.preferencesVersion),
1404
+ preferencesVersion: Oe(e.preferencesVersion),
1405
1405
  scribbleStyleEnabled: ts(e.scribbleStyleEnabled),
1406
1406
  blockedOrigins: bt(e.blockedServiceOrigins),
1407
1407
  personalInstructions: ce(e.personalInstructions),
1408
- securityPolicyVersion: xe(e.securityPolicyVersion)
1408
+ securityPolicyVersion: Oe(e.securityPolicyVersion)
1409
1409
  };
1410
1410
  }
1411
1411
  function Pt(t) {
1412
1412
  const e = N(t);
1413
- return { eligibleSince: Mt(e.eligibleSince), revision: xe(e.revision), requestId: ce(e.requestId), snoozedUntil: Mt(e.snoozedUntil) };
1413
+ return { eligibleSince: Mt(e.eligibleSince), revision: Oe(e.revision), requestId: ce(e.requestId), snoozedUntil: Mt(e.snoozedUntil) };
1414
1414
  }
1415
1415
  function Qr(t) {
1416
1416
  const e = N(t);
1417
1417
  return { notifications: Pt(e.notifications), tab_grouping: Pt(e.tabGrouping) };
1418
1418
  }
1419
1419
  function Fn(t) {
1420
- const e = N(t), s = N(e.request), n = P(s.category), i = P(s.action), r = { category: n, action: i, promptKey: P(s.promptKey), expectedRevision: xe(s.expectedRevision) };
1420
+ const e = N(t), s = N(e.request), n = P(s.category), i = P(s.action), r = { category: n, action: i, promptKey: P(s.promptKey), expectedRevision: Oe(s.expectedRevision) };
1421
1421
  cn(r);
1422
1422
  const a = P(e.outcome);
1423
1423
  if (!["resolved", "snoozed", "suppressed"].includes(a)) throw new Error("Invalid decision outcome.");
@@ -1427,7 +1427,7 @@ function Fn(t) {
1427
1427
  if (a === "snoozed" && c === null) throw new Error("Missing decision deadline.");
1428
1428
  return {
1429
1429
  decisionKey: P(e.decisionKey),
1430
- revision: xe(e.revision),
1430
+ revision: Oe(e.revision),
1431
1431
  decidedAt: o,
1432
1432
  request: { ...r, requestId: P(s.requestId) },
1433
1433
  outcome: a,
@@ -1450,11 +1450,11 @@ function Xr(t) {
1450
1450
  if (s.template === "semantic_interaction") return { ...n, condition: { template: s.template, event: ss(s.event) } };
1451
1451
  if (s.template === "event_sequence") {
1452
1452
  if (!Array.isArray(s.steps)) throw new Error("Invalid proactive sequence.");
1453
- return { ...n, condition: { template: s.template, steps: s.steps.map(ss), withinSeconds: xe(s.withinSeconds) } };
1453
+ return { ...n, condition: { template: s.template, steps: s.steps.map(ss), withinSeconds: Oe(s.withinSeconds) } };
1454
1454
  }
1455
1455
  if (s.template === "page_state_after_event") {
1456
1456
  const i = N(s.state);
1457
- return { ...n, condition: { template: s.template, event: ss(s.event), withinSeconds: xe(s.withinSeconds), state: {
1457
+ return { ...n, condition: { template: s.template, event: ss(s.event), withinSeconds: Oe(s.withinSeconds), state: {
1458
1458
  urlRegex: P(i.urlRegex),
1459
1459
  ...i.textRegex == null ? {} : { textRegex: P(i.textRegex) },
1460
1460
  ...i.roleRegex == null ? {} : { roleRegex: P(i.roleRegex) },
@@ -1714,7 +1714,7 @@ function Fi(t, e, s) {
1714
1714
  };
1715
1715
  const p = (m, h) => {
1716
1716
  d || (d = !0, l(), u(), m ? o(m) : a(h));
1717
- }, f = () => {
1717
+ }, g = () => {
1718
1718
  if (!c) return;
1719
1719
  const m = t.engine.getState().slices;
1720
1720
  if (JSON.stringify(m.account.authority) !== JSON.stringify(n)) {
@@ -1732,8 +1732,8 @@ function Fi(t, e, s) {
1732
1732
  }
1733
1733
  h?.status === "error" ? p(h.error) : h?.status === "done" && p(null, h.result);
1734
1734
  };
1735
- l = t.engine.subscribe(f), u = t.onDispose(() => p(new Error("Feature runtime disposed."))), t.engine.dispatch({ ...e, authority: n, requestId: r, now: Date.now() }).then(() => {
1736
- c = !0, f();
1735
+ l = t.engine.subscribe(g), u = t.onDispose(() => p(new Error("Feature runtime disposed."))), t.engine.dispatch({ ...e, authority: n, requestId: r, now: Date.now() }).then(() => {
1736
+ c = !0, g();
1737
1737
  }, (m) => p(m));
1738
1738
  });
1739
1739
  }
@@ -1747,7 +1747,7 @@ async function no(t, e, s = crypto.randomUUID()) {
1747
1747
  };
1748
1748
  const p = (h) => {
1749
1749
  d || (d = !0, l(), u(), h ? o(h) : a());
1750
- }, f = () => {
1750
+ }, g = () => {
1751
1751
  if (!c) return;
1752
1752
  const h = t.engine.getState().slices;
1753
1753
  if (JSON.stringify(h.account.authority) !== JSON.stringify(n)) return p(new Error("Feature authority retired."));
@@ -1756,25 +1756,25 @@ async function no(t, e, s = crypto.randomUUID()) {
1756
1756
  v.status === "error" ? p(v.error) : v.status === "done" && p();
1757
1757
  return;
1758
1758
  }
1759
- const b = Object.values(h.features.pending).find((k) => k.requestId === r);
1760
- if (b) {
1761
- b.status === "error" ? p(b.error) : b.status === "done" && p();
1759
+ const I = Object.values(h.features.pending).find((w) => w.requestId === r);
1760
+ if (I) {
1761
+ I.status === "error" ? p(I.error) : I.status === "done" && p();
1762
1762
  return;
1763
1763
  }
1764
- if (Object.values(h.interactions.devicePending).some((k) => k.requestId === r)) return;
1765
- const S = e.interactionId === "preference:notifications" ? "notifications" : e.interactionId === "preference:tab_grouping" ? "tab_grouping" : null;
1766
- p(S ? h.interactions.deviceErrors[S] : void 0);
1764
+ if (Object.values(h.interactions.devicePending).some((w) => w.requestId === r)) return;
1765
+ const k = e.interactionId === "preference:notifications" ? "notifications" : e.interactionId === "preference:tab_grouping" ? "tab_grouping" : null;
1766
+ p(k ? h.interactions.deviceErrors[k] : void 0);
1767
1767
  };
1768
- l = t.engine.subscribe(f), u = t.onDispose(() => p(new Error("Feature runtime disposed.")));
1768
+ l = t.engine.subscribe(g), u = t.onDispose(() => p(new Error("Feature runtime disposed.")));
1769
1769
  const m = i ? { type: "stage7.retry_action", authority: n, now: Date.now(), requestId: r } : { type: "stage7.act", authority: n, now: Date.now(), requestId: r, ...e, sourceVersion: e.expectedSourceVersion ?? null };
1770
1770
  t.engine.dispatch(m).then(() => {
1771
- c = !0, f();
1771
+ c = !0, g();
1772
1772
  }, p);
1773
1773
  });
1774
1774
  }
1775
1775
  function io(t, e, s, n) {
1776
1776
  return Bi(t, e, s, n).map((i) => {
1777
- const r = i.sourceId ? Object.values(t.interactions.sources).find((m) => m.id === i.sourceId && m.conversation_id === i.conversationId) : null, a = r?.payload, o = i.payload.feature, c = i.category === "permission", d = i.category === "sharing" ? "social_share" : i.category === "integration_auth" ? "integration_connection" : i.category === "personal_channel" ? "personal_channel_connection" : o === "notifications" ? "task_notifications" : o === "tab_grouping" ? "tab_group_permission" : i.category, l = d === "integration_connection" && a?.kind === "integration_auth" ? `Connect ${a.app_name}` : d === "personal_channel_connection" ? "Connect WhatsApp" : null, u = o === "notifications" ? c ? "Allow notifications in this browser?" : "Get notified when Pluno finishes a task?" : o === "tab_grouping" ? c ? "Allow Pluno to group tabs in this browser?" : "Group tabs used by Pluno?" : i.category === "sharing" ? "Share what Pluno helped you accomplish." : String(i.payload.text ?? l ?? ""), p = Object.fromEntries(i.actions.map((m) => [m, i.actionLabels?.[m] ?? { enable: "Enable", not_now: "Not now", dont_enable: "Don't enable", allow: "Allow", run: i.category === "proactive_suggestion" ? "Yes" : "Start", edit: "Edit", never: "Never", snooze: "Snooze morning report", pair: "Pair WhatsApp", dismiss: "Dismiss", copy: "Copy", share: "Share", feedback: "Send feedback" }[m] ?? m])), f = a?.kind === "integration_auth" ? { type: "pipedream_auth_required", authRequestId: a.request_id, appSlug: a.app_slug, appName: a.app_name, appLogo: a.app_logo, expiresAt: a.expires_at } : a?.kind === "personal_channel" ? { type: "personal_channel_connection_required", requestId: a.request_id, channel: a.channel, managementUrl: a.management_url } : null;
1777
+ const r = i.sourceId ? Object.values(t.interactions.sources).find((m) => m.id === i.sourceId && m.conversation_id === i.conversationId) : null, a = r?.payload, o = i.payload.feature, c = i.category === "permission", d = i.category === "sharing" ? "social_share" : i.category === "integration_auth" ? "integration_connection" : i.category === "personal_channel" ? "personal_channel_connection" : o === "notifications" ? "task_notifications" : o === "tab_grouping" ? "tab_group_permission" : i.category, l = d === "integration_connection" && a?.kind === "integration_auth" ? `Connect ${a.app_name}` : d === "personal_channel_connection" ? "Connect WhatsApp" : null, u = o === "notifications" ? c ? "Allow notifications in this browser?" : "Get notified when Pluno finishes a task?" : o === "tab_grouping" ? c ? "Allow Pluno to group tabs in this browser?" : "Group tabs used by Pluno?" : i.category === "sharing" ? "Share what Pluno helped you accomplish." : String(i.payload.text ?? l ?? ""), p = Object.fromEntries(i.actions.map((m) => [m, i.actionLabels?.[m] ?? { enable: "Enable", not_now: "Not now", dont_enable: "Don't enable", allow: "Allow", run: i.category === "proactive_suggestion" ? "Yes" : "Start", edit: "Edit", never: "Never", snooze: "Snooze morning report", pair: "Pair WhatsApp", dismiss: "Dismiss", copy: "Copy", share: "Share", feedback: "Send feedback" }[m] ?? m])), g = a?.kind === "integration_auth" ? { type: "pipedream_auth_required", authRequestId: a.request_id, appSlug: a.app_slug, appName: a.app_name, appLogo: a.app_logo, expiresAt: a.expires_at } : a?.kind === "personal_channel" ? { type: "personal_channel_connection_required", requestId: a.request_id, channel: a.channel, managementUrl: a.management_url } : null;
1778
1778
  return {
1779
1779
  id: i.id,
1780
1780
  kind: d,
@@ -1783,7 +1783,7 @@ function io(t, e, s, n) {
1783
1783
  payload: {
1784
1784
  ...i.payload,
1785
1785
  error: i.error?.message ?? null,
1786
- ...f ? { request: f, status: i.payload.lifecycle ?? r?.lifecycle, error: i.error?.message ?? null } : {},
1786
+ ...g ? { request: g, status: i.payload.lifecycle ?? r?.lifecycle, error: i.error?.message ?? null } : {},
1787
1787
  ...i.category === "sharing" ? { candidate: { id: i.id, variant: a?.kind === "sharing" ? a.variant : "social" } } : {},
1788
1788
  ...i.category === "proactive_suggestion" ? { suggestion: { id: String(i.payload.sourceSuggestionId ?? i.id), interactionId: i.id, genericQuestion: String(i.payload.text ?? ""), question: String(i.payload.text ?? "") } } : {},
1789
1789
  ...i.category === "morning_report" ? { opening: i.payload.text, prompts: i.payload.tasks } : {}
@@ -1825,7 +1825,7 @@ function oo(t, e = null) {
1825
1825
  paymentIssue: null,
1826
1826
  pricingUrl: "",
1827
1827
  earnCreditsUrl: ""
1828
- }, i = Oi(t, "send_message"), r = i.reason === "unavailable" && n.submissionGate?.allowed === !1, a = t.refusal ?? (i.allowed ? n.submissionGate ?? { allowed: !0, reason: "allowed", actions: [] } : r ? n.submissionGate : {
1828
+ }, i = xi(t, "send_message"), r = i.reason === "unavailable" && n.submissionGate?.allowed === !1, a = t.refusal ?? (i.allowed ? n.submissionGate ?? { allowed: !0, reason: "allowed", actions: [] } : r ? n.submissionGate : {
1829
1829
  allowed: !1,
1830
1830
  reason: i.reason === "workspace" ? "workspace_required" : i.reason === "authentication" ? "authentication_required" : i.reason === "unavailable" ? "connection_required" : n.submissionGate?.reason ?? "credits_exhausted",
1831
1831
  actions: n.submissionGate?.actions ?? []
@@ -1836,7 +1836,7 @@ function oo(t, e = null) {
1836
1836
  } : void 0);
1837
1837
  return { ...n, ...o ? { auth: o } : {}, submissionGate: a, usingPaidCreditFallback: e ? t.paidFallbackBySession[e] ?? !1 : !1 };
1838
1838
  }
1839
- const ao = "0.1.262", jt = {
1839
+ const ao = "0.1.263", jt = {
1840
1840
  version: ao
1841
1841
  }, dn = (t) => t.selectedModel ?? t.historyModel ?? t.defaultModel, co = (t, e) => t.scopes[e];
1842
1842
  function Bt(t) {
@@ -1847,14 +1847,14 @@ function Ls(t, e) {
1847
1847
  if (t.removedItems[e.id]) return t;
1848
1848
  const s = he(e.created_at);
1849
1849
  he(e.updated_at);
1850
- const n = Ot(e);
1850
+ const n = xt(e);
1851
1851
  n !== null && Bt(n);
1852
1852
  const i = t.streams[e.id];
1853
1853
  if (n !== null && i && (i.state === "stopped" || i.state === "finished") && n > i.revision) return t;
1854
1854
  const r = t.items[e.id];
1855
1855
  if (r) {
1856
1856
  if (he(r.created_at) !== s) throw new Error("Display shell timestamp changed.");
1857
- const a = Ot(r);
1857
+ const a = xt(r);
1858
1858
  if (a !== null && n !== null) {
1859
1859
  if (n <= a) return t;
1860
1860
  } else if (he(e.updated_at) <= he(r.updated_at)) return t;
@@ -1880,7 +1880,7 @@ function Fs(t, e) {
1880
1880
  function lo(t) {
1881
1881
  const e = /* @__PURE__ */ new Set();
1882
1882
  for (const s of Object.values(t.items)) {
1883
- const n = Ot(s), i = t.streams[s.id];
1883
+ const n = xt(s), i = t.streams[s.id];
1884
1884
  n !== null && (!i || i.state === "open" || n < i.revision) && e.add(s.id);
1885
1885
  }
1886
1886
  for (const s of [...Object.keys(t.streams), ...Object.values(t.removedItems)])
@@ -1923,28 +1923,38 @@ function zs(t, e) {
1923
1923
  const s = e.clients[t.clientScopeId];
1924
1924
  return s === t.conversationScopeId || s === void 0 && t.sessionId !== null && (e.memberships[t.sessionId]?.members.length ?? 0) > 0;
1925
1925
  }
1926
- function Hs(t, e) {
1927
- if (t.authorityId !== (e.authorityId ?? "") || t.generation !== e.generation)
1928
- return Mi(e.authorityId ?? void 0, e.generation);
1929
- const s = Object.fromEntries(Object.entries(t.pendingRestoration).filter(([i]) => !e.clients[i]));
1930
- let n = Object.keys(s).length === Object.keys(t.pendingRestoration).length ? t : { ...t, pendingRestoration: s };
1931
- for (const i of Object.values(t.submissions)) {
1932
- if (n.pendingRestoration[i.clientScopeId] === i.conversationScopeId) continue;
1933
- i.delivery !== "accepted" && !i.cancelled && !zs(i, e) && (n = { ...n, submissions: { ...n.submissions, [i.userMessageId]: { ...i, cancelled: !0, cancellationReason: i.cancellationReason ?? "owner_lost" } } });
1934
- const r = e.selections[i.conversationScopeId]?.sessionId;
1935
- r && !n.submissions[i.userMessageId].cancelled && i.sessionId === null && (n = $s(n, n.submissions[i.userMessageId], r));
1936
- }
1937
- for (const [i, r] of Object.entries(n.requests)) {
1938
- if ((e.memberships[r.sessionId]?.members.length ?? 0) > 0) continue;
1939
- const a = { ...n.requests };
1940
- delete a[i];
1941
- const o = n.sessions[r.sessionId], c = o.queries[r.lane];
1942
- n = { ...n, requests: a, sessions: { ...n.sessions, [o.sessionId]: {
1943
- ...o,
1944
- queries: { ...o.queries, [r.lane]: { ...c, requestId: null, status: c.data === null ? "not_requested" : "ready" } }
1926
+ function Hs(t, e, s = !1) {
1927
+ if (t.authorityId !== (e.authorityId ?? "") || t.generation !== e.generation) {
1928
+ const r = Mi(e.authorityId ?? void 0, e.generation);
1929
+ if (!s || t.authorityId) return r;
1930
+ const a = Object.fromEntries(Object.entries(t.submissions).filter(([o, c]) => c.sessionId === null && !c.cancelled && t.deliveries[o]?.acceptance === "unissued" && e.clients[c.clientScopeId] === c.conversationScopeId));
1931
+ return {
1932
+ ...r,
1933
+ submissions: a,
1934
+ submissionOrder: t.submissionOrder.filter((o) => o in a),
1935
+ deliveries: Object.fromEntries(Object.keys(a).map((o) => [o, t.deliveries[o]])),
1936
+ effectsEnabled: t.effectsEnabled
1937
+ };
1938
+ }
1939
+ const n = Object.fromEntries(Object.entries(t.pendingRestoration).filter(([r]) => !e.clients[r]));
1940
+ let i = Object.keys(n).length === Object.keys(t.pendingRestoration).length ? t : { ...t, pendingRestoration: n };
1941
+ for (const r of Object.values(t.submissions)) {
1942
+ if (i.pendingRestoration[r.clientScopeId] === r.conversationScopeId) continue;
1943
+ r.delivery !== "accepted" && !r.cancelled && !zs(r, e) && (i = { ...i, submissions: { ...i.submissions, [r.userMessageId]: { ...r, cancelled: !0, cancellationReason: r.cancellationReason ?? "owner_lost" } } });
1944
+ const a = e.selections[r.conversationScopeId]?.sessionId;
1945
+ a && !i.submissions[r.userMessageId].cancelled && r.sessionId === null && (i = $s(i, i.submissions[r.userMessageId], a));
1946
+ }
1947
+ for (const [r, a] of Object.entries(i.requests)) {
1948
+ if ((e.memberships[a.sessionId]?.members.length ?? 0) > 0) continue;
1949
+ const o = { ...i.requests };
1950
+ delete o[r];
1951
+ const c = i.sessions[a.sessionId], d = c.queries[a.lane];
1952
+ i = { ...i, requests: o, sessions: { ...i.sessions, [c.sessionId]: {
1953
+ ...c,
1954
+ queries: { ...c.queries, [a.lane]: { ...d, requestId: null, status: d.data === null ? "not_requested" : "ready" } }
1945
1955
  } } };
1946
1956
  }
1947
- return G(n);
1957
+ return G(i);
1948
1958
  }
1949
1959
  function ut(t) {
1950
1960
  return JSON.stringify(t, (e, s) => s && typeof s == "object" && !Array.isArray(s) ? Object.fromEntries(Object.entries(s).sort(([n], [i]) => n.localeCompare(i))) : s);
@@ -1970,7 +1980,7 @@ function uo(t, e, s, n) {
1970
1980
  } : null });
1971
1981
  const p = { ...t.requests };
1972
1982
  delete p[e.effectId];
1973
- let f = t.submissions;
1983
+ let g = t.submissions;
1974
1984
  if (e.type === "effect.completed" && e.output.snapshot.conversation_id !== o.sessionId) throw new Error("Snapshot belongs to another conversation.");
1975
1985
  if (e.type === "effect.completed" && !e.output.snapshot.projection_ready && (e.output.snapshot.preparation === "pending" || e.output.snapshot.preparation === "busy")) {
1976
1986
  for (const m of e.output.snapshot.items) m.type === "user_message" && (c = Ls(c, m));
@@ -1991,21 +2001,21 @@ function uo(t, e, s, n) {
1991
2001
  o.lane === "current" && (c = { ...c, preparation: null });
1992
2002
  const h = c.queries.history, v = o.lane === "current" && (h.status === "not_requested" || m.next_cursor !== null && !c.items[m.next_cursor]);
1993
2003
  if (m.conversation_id !== o.sessionId) throw new Error("Snapshot belongs to another conversation.");
1994
- for (const b of m.removed_items) c = rs(c, b);
1995
- for (const b of m.items) c = Ls(c, b);
1996
- for (const b of m.streams) c = $i(c, b);
2004
+ for (const I of m.removed_items) c = rs(c, I);
2005
+ for (const I of m.items) c = Ls(c, I);
2006
+ for (const I of m.streams) c = $i(c, I);
1997
2007
  if (c = Fs(c, m.execution), c = rs(c, {
1998
2008
  type: "conversation.follow_ups.updated",
1999
2009
  conversation_id: m.conversation_id,
2000
2010
  version: m.follow_ups_version,
2001
2011
  follow_ups: m.follow_ups
2002
- }), m.interactions.some((b) => b.conversation_id !== m.conversation_id)) throw new Error("Interaction belongs to another conversation.");
2012
+ }), m.interactions.some((I) => I.conversation_id !== m.conversation_id)) throw new Error("Interaction belongs to another conversation.");
2003
2013
  if (a = { authorityId: t.authorityId, generation: t.generation, sessionId: o.sessionId, sources: m.interactions }, m.execution.version === c.execution?.version)
2004
- for (const b of o.acceptedUserMessageIds) {
2005
- const S = f[b];
2006
- S.executionVersion === null && (f = {
2007
- ...f,
2008
- [b]: { ...S, executionVersion: m.execution.version }
2014
+ for (const I of o.acceptedUserMessageIds) {
2015
+ const k = g[I];
2016
+ k.executionVersion === null && (g = {
2017
+ ...g,
2018
+ [I]: { ...k, executionVersion: m.execution.version }
2009
2019
  });
2010
2020
  }
2011
2021
  if (c = { ...c, queries: { ...c.queries, [o.lane]: {
@@ -2017,14 +2027,14 @@ function uo(t, e, s, n) {
2017
2027
  cursor: m.next_cursor,
2018
2028
  updatedAt: e.output.updatedAt
2019
2029
  } } }, v) {
2020
- for (const [b, S] of Object.entries(p))
2021
- S.sessionId === o.sessionId && S.lane === "history" && delete p[b];
2030
+ for (const [I, k] of Object.entries(p))
2031
+ k.sessionId === o.sessionId && k.lane === "history" && delete p[I];
2022
2032
  c = { ...c, queries: { ...c.queries, history: { ...c.queries.current, key: h.key } } };
2023
2033
  }
2024
2034
  }
2025
- i = { ...t, requests: p, submissions: f, sessions: { ...t.sessions, [c.sessionId]: c } };
2035
+ i = { ...t, requests: p, submissions: g, sessions: { ...t.sessions, [c.sessionId]: c } };
2026
2036
  } else {
2027
- if (e.authorityId !== t.authorityId || e.generation !== t.generation || !s.authorityId) return { state: t, effects: r };
2037
+ if (e.authorityId !== t.authorityId || e.generation !== t.generation || !s.authorityId && !["conversation.submission_stage", "conversation.submission_delivery", "conversation.stop"].includes(e.type)) return { state: t, effects: r };
2028
2038
  switch (e.type) {
2029
2039
  case "conversation.proactive_edit": {
2030
2040
  if (!Object.values(s.clients).includes(e.conversationScopeId)) return { state: t, effects: r };
@@ -2047,24 +2057,24 @@ function uo(t, e, s, n) {
2047
2057
  }
2048
2058
  case "conversation.submission_stage": {
2049
2059
  if (s.clients[e.clientScopeId] !== e.conversationScopeId) throw new Error("Submission selection has changed.");
2050
- const { type: o, authorityId: c, generation: d, prepareContext: l, ...u } = e, p = t.submissions[e.userMessageId];
2051
- if (p) {
2052
- const { contextPreparation: S, requestedModel: k, sessionId: g, delivery: y, cancelled: I, cancellationReason: w, error: R, executionVersion: T, ...C } = p;
2053
- if (ut(C) !== ut(u)) throw new Error("User-message identity cannot be reused with different input.");
2060
+ const { type: o, authorityId: c, generation: d, prepareContext: l, waitForAuthentication: u, ...p } = e, g = t.submissions[e.userMessageId];
2061
+ if (g) {
2062
+ const { contextPreparation: w, requestedModel: f, sessionId: y, delivery: b, cancelled: _, cancellationReason: R, error: T, executionVersion: C, ...E } = g;
2063
+ if (ut(E) !== ut(p)) throw new Error("User-message identity cannot be reused with different input.");
2054
2064
  return { state: t, effects: r };
2055
2065
  }
2056
- const f = s.selections[e.conversationScopeId], m = Object.values(t.submissions).find((S) => S.conversationScopeId === e.conversationScopeId && !S.cancelled && S.sessionId !== null), h = n.scopes[e.clientScopeId], v = {
2057
- ...X(u),
2066
+ const m = s.selections[e.conversationScopeId], h = Object.values(t.submissions).find((w) => w.conversationScopeId === e.conversationScopeId && !w.cancelled && w.sessionId !== null), v = n.scopes[e.clientScopeId], I = {
2067
+ ...X(p),
2058
2068
  ...l ? { contextPreparation: null } : {},
2059
2069
  // Extension staging can await page context after the picker has already changed.
2060
- requestedModel: h?.submissions[e.userMessageId] ? h.submissions[e.userMessageId].requestedModel ?? null : h ? dn(h) ?? null : null,
2061
- sessionId: f.sessionId ?? m?.sessionId ?? null,
2062
- delivery: "staged",
2070
+ requestedModel: v?.submissions[e.userMessageId] ? v.submissions[e.userMessageId].requestedModel ?? null : v ? dn(v) ?? null : null,
2071
+ sessionId: m.sessionId ?? h?.sessionId ?? null,
2072
+ delivery: u ? "failed" : "staged",
2063
2073
  cancelled: !1,
2064
- error: null,
2074
+ error: u ? { code: u, message: u === "unauthorized" ? "Open the Pluno login link, then return to Pluno." : "Pluno is reconnecting. Try again in a moment.", retryable: !1 } : null,
2065
2075
  executionVersion: null
2066
- }, b = { ...t.proactiveQuestions };
2067
- delete b[e.conversationScopeId], i = { ...t, proactiveQuestions: b, submissions: { ...t.submissions, [e.userMessageId]: v }, submissionOrder: [...t.submissionOrder, e.userMessageId] };
2076
+ }, k = { ...t.proactiveQuestions };
2077
+ delete k[e.conversationScopeId], i = { ...t, proactiveQuestions: k, submissions: { ...t.submissions, [e.userMessageId]: I }, submissionOrder: [...t.submissionOrder, e.userMessageId] };
2068
2078
  break;
2069
2079
  }
2070
2080
  case "conversation.submission_accepted": {
@@ -2081,14 +2091,14 @@ function uo(t, e, s, n) {
2081
2091
  }
2082
2092
  case "conversation.stop": {
2083
2093
  if (s.clients[e.clientScopeId] !== e.conversationScopeId) return { state: t, effects: r };
2084
- const o = s.selections[e.conversationScopeId].sessionId, c = o ? t.sessions[o]?.execution : null, d = Object.values(t.submissions).filter((h) => (o ? h.sessionId === o : h.conversationScopeId === e.conversationScopeId) && (!e.userMessageIds || e.userMessageIds.includes(h.userMessageId))), l = d.filter((h) => !h.cancelled && (h.delivery !== "failed" || t.deliveries[h.userMessageId]?.phase === "paused") && (h.delivery !== "accepted" || h.executionVersion === null)), u = l.length > 0, p = c && ["queued", "thinking", "steering", "stopping"].includes(c.phase) && (!e.userMessageIds || de(c).some((h) => e.userMessageIds.includes(h)));
2094
+ const o = s.selections[e.conversationScopeId].sessionId, c = o ? t.sessions[o]?.execution : null, d = Object.values(t.submissions).filter((h) => (o ? h.sessionId === o : h.conversationScopeId === e.conversationScopeId) && (!e.userMessageIds || e.userMessageIds.includes(h.userMessageId))), l = d.filter((h) => !h.cancelled && (h.delivery !== "failed" || t.deliveries[h.userMessageId]?.phase === "paused" || e.userMessageIds?.includes(h.userMessageId) && t.deliveries[h.userMessageId]?.acceptance === "unissued") && (h.delivery !== "accepted" || h.executionVersion === null)), u = l.length > 0, p = c && ["queued", "thinking", "steering", "stopping"].includes(c.phase) && (!e.userMessageIds || de(c).some((h) => e.userMessageIds.includes(h)));
2085
2095
  if (!u && !p && (c || !e.userMessageIds?.length)) return { state: t, effects: r };
2086
- const f = Array.from(new Set(e.userMessageIds ?? [...l.map((h) => h.userMessageId), ...p ? de(c) : []])), m = { ...t.submissions };
2096
+ const g = Array.from(new Set(e.userMessageIds ?? [...l.map((h) => h.userMessageId), ...p ? de(c) : []])), m = { ...t.submissions };
2087
2097
  for (const h of d)
2088
- f.includes(h.userMessageId) && h.delivery !== "accepted" && (m[h.userMessageId] = { ...h, cancelled: !0, cancellationReason: e.reason ?? "user_requested" });
2098
+ g.includes(h.userMessageId) && h.delivery !== "accepted" && (m[h.userMessageId] = { ...h, cancelled: !0, cancellationReason: e.reason ?? "user_requested" });
2089
2099
  i = { ...t, submissions: m, stops: { ...t.stops, [e.conversationScopeId]: {
2090
2100
  requestId: e.requestId,
2091
- userMessageIds: f,
2101
+ userMessageIds: g,
2092
2102
  executionVersion: c?.version ?? -1,
2093
2103
  reason: e.reason ?? "user_requested"
2094
2104
  } } };
@@ -2133,7 +2143,7 @@ function uo(t, e, s, n) {
2133
2143
  before: e.lane === "history" ? c.cursor : null,
2134
2144
  refreshItemIds: lo(o),
2135
2145
  retryPreparation: c.error?.code === "history_preparation_failed"
2136
- }, l = Object.values(t.submissions).filter((f) => f.sessionId === e.sessionId && f.delivery === "accepted" && f.executionVersion === null).map((f) => f.userMessageId), u = t.requestSequence + 1, p = `conversation:${t.generation}:${u}`;
2146
+ }, l = Object.values(t.submissions).filter((g) => g.sessionId === e.sessionId && g.delivery === "accepted" && g.executionVersion === null).map((g) => g.userMessageId), u = t.requestSequence + 1, p = `conversation:${t.generation}:${u}`;
2137
2147
  i = {
2138
2148
  ...t,
2139
2149
  requestSequence: u,
@@ -2172,15 +2182,15 @@ function ln(t, e) {
2172
2182
  if (u.cancelled && s.has(u.conversationScopeId) && t.stops[u.conversationScopeId]?.userMessageIds.includes(l) && !p?.items[l] && !p?.removedItems[l]) return !0;
2173
2183
  if (u.delivery === "accepted") {
2174
2184
  if (u.cancelled) return !i(l);
2175
- const f = u.sessionId ? t.sessions[u.sessionId] : void 0;
2176
- return u.executionVersion === null || !(f?.items[l] || f?.removedItems[l]);
2185
+ const g = u.sessionId ? t.sessions[u.sessionId] : void 0;
2186
+ return u.executionVersion === null || !(g?.items[l] || g?.removedItems[l]);
2177
2187
  }
2178
2188
  return !u.cancelled || we(t, l) || t.deliveries[l]?.phase === "running";
2179
2189
  }).map(([l, u]) => [l, u.delivery === "accepted" || u.cancelled ? { ...u, context: {}, contextPreparation: { pageContent: "", sessionTabs: [] } } : u])), a = Object.fromEntries(Object.entries(t.deliveries).filter(([l]) => l in r).map(([l, u]) => [l, r[l].delivery === "accepted" ? { ...u, phase: "done", effectId: null, command: null, uploads: [], completedUploads: 0 } : r[l].cancelled ? { ...u, command: null } : u])), o = Object.fromEntries(Object.entries(t.stops).filter(([l, u]) => u.userMessageIds.some((p) => {
2180
2190
  if (r[p]) return !0;
2181
2191
  if (!i(p)) return n.some((m) => m.command.payload.expectedUserMessageId === p && m.phase !== "done");
2182
- const f = Object.values(t.sessions).find((m) => m.executionByUserMessage[p])?.executionByUserMessage[p];
2183
- return s.has(l) && (!f || f.version <= u.executionVersion || !["completed", "failed", "stopped"].includes(f.phase));
2192
+ const g = Object.values(t.sessions).find((m) => m.executionByUserMessage[p])?.executionByUserMessage[p];
2193
+ return s.has(l) && (!g || g.version <= u.executionVersion || !["completed", "failed", "stopped"].includes(g.phase));
2184
2194
  }))), c = new Set(Object.values(o).flatMap((l) => l.userMessageIds)), d = Object.fromEntries(Object.entries(t.operations).filter(([, l]) => {
2185
2195
  if (!["done", "failed"].includes(l.phase)) return !0;
2186
2196
  if (l.command.type === "run.stop") return c.has(String(l.command.payload.expectedUserMessageId)) || Object.values(r).some((p) => p.cancelled && p.userMessageId === l.command.payload.expectedUserMessageId);
@@ -2188,7 +2198,7 @@ function ln(t, e) {
2188
2198
  if (l.command.type === "runtime.warmup") return e.selections[l.conversationScopeId]?.sessionId !== l.result?.sessionId;
2189
2199
  if (l.command.type !== "attachment.prepare") return !1;
2190
2200
  const u = l.command.payload.source;
2191
- return !Object.values(t.submissions).some((p) => p.conversationScopeId === l.conversationScopeId && p.delivery === "accepted" && p.attachments.some((f) => f.sourceId === u.sourceId));
2201
+ return !Object.values(t.submissions).some((p) => p.conversationScopeId === l.conversationScopeId && p.delivery === "accepted" && p.attachments.some((g) => g.sourceId === u.sourceId));
2192
2202
  }));
2193
2203
  return G({
2194
2204
  schema: 1,
@@ -2232,33 +2242,33 @@ function zn(t, e) {
2232
2242
  function Ws(t) {
2233
2243
  let e = t;
2234
2244
  const s = [];
2235
- if (!t.effectsEnabled) return { state: t, effects: s };
2245
+ if (!t.effectsEnabled || !t.authorityId) return { state: t, effects: s };
2236
2246
  const n = { authorityId: t.authorityId, generation: t.generation }, i = () => (e = { ...e, requestSequence: e.requestSequence + 1 }, `conversation:${e.generation}:${e.requestSequence}`), r = [...t.submissionOrder].sort((o, c) => (t.deliveries[o]?.queuePosition ?? 0) - (t.deliveries[c]?.queuePosition ?? 0));
2237
2247
  for (const o of r) {
2238
2248
  const c = e.submissions[o];
2239
2249
  let d = e.deliveries[o];
2240
2250
  if (t.pendingRestoration[c.clientScopeId] === c.conversationScopeId || !d || d.phase !== "waiting" || !we(e, o) || c.delivery === "accepted") continue;
2241
2251
  if (!d.prepared && !c.cancelled) {
2242
- const f = i();
2243
- e = { ...e, deliveries: { ...e.deliveries, [o]: { ...d, phase: "running", effectId: f } } }, s.push({ id: f, kind: "conversation.prepare", input: { ...n, submission: c, sources: c.attachments.slice(d.uploads.length) } });
2252
+ const g = i();
2253
+ e = { ...e, deliveries: { ...e.deliveries, [o]: { ...d, phase: "running", effectId: g } } }, s.push({ id: g, kind: "conversation.prepare", input: { ...n, submission: c, sources: c.attachments.slice(d.uploads.length) } });
2244
2254
  continue;
2245
2255
  }
2246
- if (c.contextPreparation === null && !c.cancelled || c.sessionId === null && Object.values(e.operations).some((f) => ["runtime.warmup", "attachment.prepare"].includes(f.command.type) && f.conversationScopeId === c.conversationScopeId && (["waiting", "running", "uncertain"].includes(f.phase) || f.phase === "done" && !!f.result?.sessionId)) || c.sessionId === null && r.some((f) => f !== o && r.indexOf(f) < r.indexOf(o) && e.submissions[f].conversationScopeId === c.conversationScopeId && e.deliveries[f] && !e.submissions[f].cancelled && (e.submissions[f].delivery !== "failed" || e.deliveries[f].acceptance === "uncertain" || e.deliveries[f].allocation === "uncertain"))) continue;
2256
+ if (c.contextPreparation === null && !c.cancelled || c.sessionId === null && Object.values(e.operations).some((g) => ["runtime.warmup", "attachment.prepare"].includes(g.command.type) && g.conversationScopeId === c.conversationScopeId && (["waiting", "running", "uncertain"].includes(g.phase) || g.phase === "done" && !!g.result?.sessionId)) || c.sessionId === null && r.some((g) => g !== o && r.indexOf(g) < r.indexOf(o) && e.submissions[g].conversationScopeId === c.conversationScopeId && e.deliveries[g] && !e.submissions[g].cancelled && (e.submissions[g].delivery !== "failed" || e.deliveries[g].acceptance === "uncertain" || e.deliveries[g].allocation === "uncertain"))) continue;
2247
2257
  for (; d.uploads.length < c.attachments.length; ) {
2248
- const f = c.attachments[d.uploads.length];
2249
- if (f.uploaded) {
2250
- d = { ...d, uploads: [...d.uploads, f.uploaded] };
2258
+ const g = c.attachments[d.uploads.length];
2259
+ if (g.uploaded) {
2260
+ d = { ...d, uploads: [...d.uploads, g.uploaded] };
2251
2261
  continue;
2252
2262
  }
2253
- const m = Object.values(e.operations).find((h) => h.command.type === "attachment.prepare" && h.conversationScopeId === c.conversationScopeId && h.phase === "done" && h.command.payload.source.sourceId === f.sourceId && h.result?.sessionId === c.sessionId);
2263
+ const m = Object.values(e.operations).find((h) => h.command.type === "attachment.prepare" && h.conversationScopeId === c.conversationScopeId && h.phase === "done" && h.command.payload.source.sourceId === g.sourceId && h.result?.sessionId === c.sessionId);
2254
2264
  if (!m) break;
2255
2265
  d = { ...d, uploads: [...d.uploads, m.result.attachment] };
2256
2266
  }
2257
2267
  for (; d.completedUploads < d.uploads.length && c.attachments[d.completedUploads].uploaded; )
2258
2268
  d = { ...d, completedUploads: d.completedUploads + 1 };
2259
- if (!c.cancelled && d.uploads.length === c.attachments.length && d.completedUploads === d.uploads.length && r.slice(0, r.indexOf(o)).some((f) => {
2260
- const m = e.submissions[f];
2261
- return (m.conversationScopeId === c.conversationScopeId || c.sessionId !== null && m.sessionId === c.sessionId) && m.delivery !== "accepted" && (m.delivery !== "failed" || e.deliveries[f]?.acceptance === "uncertain") && (!m.cancelled || we(e, f));
2269
+ if (!c.cancelled && d.uploads.length === c.attachments.length && d.completedUploads === d.uploads.length && r.slice(0, r.indexOf(o)).some((g) => {
2270
+ const m = e.submissions[g];
2271
+ return (m.conversationScopeId === c.conversationScopeId || c.sessionId !== null && m.sessionId === c.sessionId) && m.delivery !== "accepted" && (m.delivery !== "failed" || e.deliveries[g]?.acceptance === "uncertain") && (!m.cancelled || we(e, g));
2262
2272
  })) continue;
2263
2273
  const l = i();
2264
2274
  let u, p = d.command;
@@ -2296,7 +2306,7 @@ function Ws(t) {
2296
2306
  };
2297
2307
  for (const [o, c] of Object.entries(e.stops))
2298
2308
  for (const d of c.userMessageIds) {
2299
- const l = e.submissions[d], u = l?.sessionId ?? Object.values(e.sessions).find((f) => de(f.execution).includes(d))?.sessionId, p = l?.delivery === "accepted" || u && de(e.sessions[u]?.execution).includes(d);
2309
+ const l = e.submissions[d], u = l?.sessionId ?? Object.values(e.sessions).find((g) => de(g.execution).includes(d))?.sessionId, p = l?.delivery === "accepted" || u && de(e.sessions[u]?.execution).includes(d);
2300
2310
  u && p && a(`stop:${o}:${c.requestId}:${d}`, u, d, c.reason);
2301
2311
  }
2302
2312
  for (const o of Object.values(e.submissions))
@@ -2308,8 +2318,8 @@ function Ws(t) {
2308
2318
  ));
2309
2319
  for (const [o, c] of Object.entries(e.operations)) {
2310
2320
  if (c.phase !== "waiting" || c.conversationScopeId && Object.values(e.pendingRestoration).includes(c.conversationScopeId)) continue;
2311
- const d = Object.values(e.operations).filter((f) => f !== c && f.conversationScopeId === c.conversationScopeId && ["runtime.warmup", "attachment.prepare"].includes(f.command.type)), l = d.find((f) => f.phase === "done" && f.result?.sessionId)?.result, u = c.command.payload.sessionId ?? l?.sessionId ?? Object.values(e.submissions).find((f) => f.conversationScopeId === c.conversationScopeId && !f.cancelled && f.sessionId)?.sessionId ?? null;
2312
- if (c.conversationScopeId && ["runtime.warmup", "attachment.prepare"].includes(c.command.type) && !u && (d.some((f) => f.phase === "running" || f.phase === "uncertain") || Object.values(e.submissions).some((f) => f.conversationScopeId === c.conversationScopeId && e.deliveries[f.userMessageId]?.phase === "running"))) continue;
2321
+ const d = Object.values(e.operations).filter((g) => g !== c && g.conversationScopeId === c.conversationScopeId && ["runtime.warmup", "attachment.prepare"].includes(g.command.type)), l = d.find((g) => g.phase === "done" && g.result?.sessionId)?.result, u = c.command.payload.sessionId ?? l?.sessionId ?? Object.values(e.submissions).find((g) => g.conversationScopeId === c.conversationScopeId && !g.cancelled && g.sessionId)?.sessionId ?? null;
2322
+ if (c.conversationScopeId && ["runtime.warmup", "attachment.prepare"].includes(c.command.type) && !u && (d.some((g) => g.phase === "running" || g.phase === "uncertain") || Object.values(e.submissions).some((g) => g.conversationScopeId === c.conversationScopeId && e.deliveries[g.userMessageId]?.phase === "running"))) continue;
2313
2323
  if (c.command.type === "runtime.warmup" && l && !c.command.payload.sessionId) {
2314
2324
  e = { ...e, operations: { ...e.operations, [o]: { ...c, phase: "done", result: l } } };
2315
2325
  continue;
@@ -2337,37 +2347,37 @@ function ho(t, e, s, n) {
2337
2347
  e.effectKind === "conversation.checkpoint" && e.effectId === t.checkpointEffectId && (i = { ...i, checkpointEffectId: null, checkpointError: e.type === "effect.failed" ? e.error : null });
2338
2348
  const l = Object.keys(t.deliveries).find((p) => t.deliveries[p].effectId === e.effectId), u = Object.keys(t.operations).find((p) => t.operations[p].effectId === e.effectId);
2339
2349
  if (l) {
2340
- const p = t.deliveries[l], f = t.submissions[l];
2350
+ const p = t.deliveries[l], g = t.submissions[l];
2341
2351
  let m = { ...p, phase: "waiting", effectId: null };
2342
2352
  if (e.type === "effect.failed") {
2343
- const h = e.error.details?.acceptance === "unissued" && p.acceptance !== "accepted" ? "unissued" : e.error.details?.acceptance === "rejected" ? "rejected" : p.acceptance, v = e.error.details?.allocation === "unissued" ? "unissued" : p.allocation, b = e.effectKind === "conversation.command" && p.step === "send" && h === "unissued" || e.effectKind === "conversation.upload" && e.error.details?.allocation === "unissued", S = e.effectKind === "conversation.prepare" || b ? "failed" : h === "uncertain" || v === "uncertain" || e.error.retryable ? "uncertain" : "failed";
2344
- m = { ...m, phase: S, acceptance: h, allocation: v }, !f.cancelled && f.delivery !== "accepted" && (i = { ...i, submissions: {
2353
+ const h = e.error.details?.acceptance === "unissued" && p.acceptance !== "accepted" ? "unissued" : e.error.details?.acceptance === "rejected" ? "rejected" : p.acceptance, v = e.error.details?.allocation === "unissued" ? "unissued" : p.allocation, I = e.effectKind === "conversation.command" && p.step === "send" && h === "unissued" || e.effectKind === "conversation.upload" && e.error.details?.allocation === "unissued", k = e.effectKind === "conversation.prepare" || I ? "failed" : h === "uncertain" || v === "uncertain" || e.error.retryable ? "uncertain" : "failed";
2354
+ m = { ...m, phase: k, acceptance: h, allocation: v }, !g.cancelled && g.delivery !== "accepted" && (i = { ...i, submissions: {
2345
2355
  ...i.submissions,
2346
- [l]: { ...f, delivery: S, error: e.error }
2356
+ [l]: { ...g, delivery: k, error: e.error }
2347
2357
  } });
2348
2358
  } else if (e.effectKind === "conversation.prepare")
2349
- f.cancelled ? m = { ...m, phase: "failed" } : (m = { ...m, prepared: !0 }, i = { ...i, submissions: { ...i.submissions, [l]: {
2350
- ...f,
2351
- ...f.contextPreparation === null ? { contextPreparation: { pageContent: e.output.pageContent, sessionTabs: e.output.sessionTabs } } : {}
2359
+ g.cancelled ? m = { ...m, phase: "failed" } : (m = { ...m, prepared: !0 }, i = { ...i, submissions: { ...i.submissions, [l]: {
2360
+ ...g,
2361
+ ...g.contextPreparation === null ? { contextPreparation: { pageContent: e.output.pageContent, sessionTabs: e.output.sessionTabs } } : {}
2352
2362
  } } }, p.recoveryDeadline !== null && e.output.now >= p.recoveryDeadline && (m = { ...m, phase: "paused" }, i = { ...i, submissions: { ...i.submissions, [l]: {
2353
2363
  ...i.submissions[l],
2354
2364
  delivery: "failed",
2355
2365
  error: { code: "message_delivery_failed", message: "Pluno could not send this message. Try it again.", retryable: !0 }
2356
2366
  } } }));
2357
2367
  else if (e.effectKind === "conversation.upload") {
2358
- const h = X(e.output), v = f.attachments[p.uploads.length];
2359
- if (h.attachment.id !== v.sourceId || h.attachment.size_bytes !== v.sizeBytes || f.sessionId !== null && f.sessionId !== h.sessionId)
2368
+ const h = X(e.output), v = g.attachments[p.uploads.length];
2369
+ if (h.attachment.id !== v.sourceId || h.attachment.size_bytes !== v.sizeBytes || g.sessionId !== null && g.sessionId !== h.sessionId)
2360
2370
  throw new Error("Upload does not match the captured attachment or conversation.");
2361
2371
  m = { ...m, allocation: "resolved", uploads: [...p.uploads, h.attachment] };
2362
- const b = Object.fromEntries(Object.entries(i.submissions).map(([S, k]) => [
2363
- S,
2364
- k.conversationScopeId === f.conversationScopeId && (S === l || !k.cancelled && !f.cancelled) ? { ...k, sessionId: h.sessionId } : k
2372
+ const I = Object.fromEntries(Object.entries(i.submissions).map(([k, w]) => [
2373
+ k,
2374
+ w.conversationScopeId === g.conversationScopeId && (k === l || !w.cancelled && !g.cancelled) ? { ...w, sessionId: h.sessionId } : w
2365
2375
  ]));
2366
- i = { ...i, submissions: b };
2376
+ i = { ...i, submissions: I };
2367
2377
  } else if (e.effectKind === "conversation.receipt")
2368
2378
  if (e.output === null)
2369
- m = { ...m, phase: f.cancelled ? "uncertain" : "paused" }, f.cancelled || (i = { ...i, submissions: { ...i.submissions, [l]: {
2370
- ...f,
2379
+ m = { ...m, phase: g.cancelled ? "uncertain" : "paused" }, g.cancelled || (i = { ...i, submissions: { ...i.submissions, [l]: {
2380
+ ...g,
2371
2381
  delivery: "failed",
2372
2382
  error: { code: "message_acceptance_unconfirmed", message: "Pluno could not confirm whether this message was accepted. Try again.", retryable: !0 }
2373
2383
  } } });
@@ -2403,14 +2413,14 @@ function ho(t, e, s, n) {
2403
2413
  error: e.type === "effect.failed" ? e.error : null,
2404
2414
  result: e.type === "effect.completed" ? X(e.output) : null
2405
2415
  } } }, e.type === "effect.completed" && ["runtime.warmup", "attachment.prepare"].includes(p.command.type) && !p.command.payload.sessionId && p.conversationScopeId && !Object.values(s.clients).includes(p.conversationScopeId)) {
2406
- const f = e.output;
2407
- f?.sessionId && (i = { ...i, operations: {
2416
+ const g = e.output;
2417
+ g?.sessionId && (i = { ...i, operations: {
2408
2418
  ...i.operations,
2409
2419
  [`cleanup:${u}`]: Ks({
2410
2420
  request_id: `cleanup:${p.command.request_id}`,
2411
2421
  type: "session.reset",
2412
2422
  payload: {
2413
- sessionId: f.sessionId,
2423
+ sessionId: g.sessionId,
2414
2424
  ...p.command.payload.warmupId ? { warmupId: p.command.payload.warmupId } : {},
2415
2425
  ...p.command.payload.page ? { page: p.command.payload.page } : {}
2416
2426
  }
@@ -2419,44 +2429,56 @@ function ho(t, e, s, n) {
2419
2429
  }
2420
2430
  }
2421
2431
  } else if (e.authorityId === t.authorityId && e.generation === t.generation && s.authorityId) {
2422
- if (e.type === "conversation.enable_effects" && (i = { ...t, effectsEnabled: !0 }), e.type === "conversation.restore_delivery") {
2423
- const l = X(e.checkpoint);
2424
- if (l.schema !== 1 || l.authorityId !== t.authorityId || t.submissionOrder.length || Object.keys(t.operations).length)
2432
+ if (e.type === "conversation.enable_effects" && (i = { ...t, effectsEnabled: !0 }), e.type === "conversation.authentication_restored" && (i = { ...t, submissions: Object.fromEntries(Object.entries(t.submissions).map(([l, u]) => [
2433
+ l,
2434
+ !u.cancelled && u.delivery === "failed" && ["unauthorized", "401", "auth_reconnecting"].includes(u.error?.code ?? "") ? { ...u, error: { code: "message_delivery_failed", message: "Pluno is connected. Retry this message to send it.", retryable: !0 } } : u
2435
+ ])) }), e.type === "conversation.restore_delivery") {
2436
+ const l = X(e.checkpoint), u = t.submissionOrder.every((w) => t.deliveries[w]?.acceptance === "unissued" && t.submissions[w].delivery === "failed" && ["unauthorized", "auth_reconnecting"].includes(t.submissions[w].error?.code ?? ""));
2437
+ if (l.schema !== 1 || l.authorityId !== t.authorityId || !u || Object.keys(t.operations).length)
2425
2438
  throw new Error("Delivery restoration requires an empty engine with the same authenticated authority.");
2426
- const { schema: u, authorityId: p, ...f } = l, m = X(e.pendingRestoration ?? {}), h = (v) => !s.clients[v.clientScopeId] && m[v.clientScopeId] === v.conversationScopeId;
2439
+ const p = { ...t.submissions, ...l.submissions };
2440
+ for (const [w, f] of Object.entries(t.submissions))
2441
+ f.cancelled && (p[w] = { ...p[w], cancelled: !0, cancellationReason: f.cancellationReason });
2442
+ const g = {
2443
+ ...l,
2444
+ submissions: p,
2445
+ stops: { ...l.stops, ...t.stops },
2446
+ deliveries: { ...t.deliveries, ...l.deliveries },
2447
+ submissionOrder: [.../* @__PURE__ */ new Set([...l.submissionOrder, ...t.submissionOrder])]
2448
+ }, { schema: m, authorityId: h, ...v } = g, I = X(e.pendingRestoration ?? {}), k = (w) => !s.clients[w.clientScopeId] && I[w.clientScopeId] === w.conversationScopeId;
2427
2449
  i = {
2428
2450
  ...t,
2429
- ...f,
2430
- pendingRestoration: m,
2431
- requestSequence: Math.max(t.requestSequence, l.requestSequence),
2451
+ ...v,
2452
+ pendingRestoration: I,
2453
+ requestSequence: Math.max(t.requestSequence, g.requestSequence),
2432
2454
  effectsEnabled: !0,
2433
- submissions: Object.fromEntries(Object.entries(l.submissions).map(([v, b]) => [v, {
2434
- ...b,
2455
+ submissions: Object.fromEntries(Object.entries(g.submissions).map(([w, f]) => [w, {
2456
+ ...f,
2435
2457
  executionVersion: null,
2436
- cancelled: b.cancelled || !h(b) && !zs(b, s),
2437
- ...!b.cancelled && !h(b) && !zs(b, s) ? { cancellationReason: "owner_lost" } : {},
2438
- delivery: (b.contextPreparation === null || !l.deliveries[v]) && !b.cancelled && b.delivery !== "accepted" ? "failed" : b.delivery === "sending" ? "uncertain" : b.delivery,
2439
- error: b.contextPreparation === null && !b.cancelled ? { code: "context_preparation_interrupted", message: "Page context preparation was interrupted. Please send this message again.", retryable: !1 } : !l.deliveries[v] && b.delivery !== "accepted" && !b.cancelled ? { code: "submission_interrupted", message: "Message preparation was interrupted. Retry this message.", retryable: !0 } : b.error
2458
+ cancelled: f.cancelled || !k(f) && !zs(f, s),
2459
+ ...!f.cancelled && !k(f) && !zs(f, s) ? { cancellationReason: "owner_lost" } : {},
2460
+ delivery: (f.contextPreparation === null || !g.deliveries[w]) && !f.cancelled && f.delivery !== "accepted" ? "failed" : f.delivery === "sending" ? "uncertain" : f.delivery,
2461
+ error: f.contextPreparation === null && !f.cancelled && !["unauthorized", "auth_reconnecting"].includes(f.error?.code ?? "") ? { code: "context_preparation_interrupted", message: "Page context preparation was interrupted. Please send this message again.", retryable: !1 } : !g.deliveries[w] && f.delivery !== "accepted" && !f.cancelled ? { code: "submission_interrupted", message: "Message preparation was interrupted. Retry this message.", retryable: !0 } : f.error
2440
2462
  }])),
2441
- deliveries: Object.fromEntries(Object.entries(l.submissions).map(([v, b], S) => {
2442
- const k = l.deliveries[v], g = b.contextPreparation === null, y = b.delivery === "accepted" ? "accepted" : k?.acceptance ?? (k && (k.step === "send" || k.step === "receipt") ? "uncertain" : "unissued");
2443
- return [v, {
2444
- ...$n(b, S),
2445
- ...k,
2446
- acceptance: y,
2447
- allocation: b.sessionId !== null ? "resolved" : k?.allocation ?? (k?.step === "upload" ? "uncertain" : "unissued"),
2463
+ deliveries: Object.fromEntries(Object.entries(g.submissions).map(([w, f], y) => {
2464
+ const b = g.deliveries[w], _ = f.contextPreparation === null, R = f.delivery === "accepted" ? "accepted" : b?.acceptance ?? (b && (b.step === "send" || b.step === "receipt") ? "uncertain" : "unissued");
2465
+ return [w, {
2466
+ ...$n(f, y),
2467
+ ...b,
2468
+ acceptance: R,
2469
+ allocation: f.sessionId !== null ? "resolved" : b?.allocation ?? (b?.step === "upload" ? "uncertain" : "unissued"),
2448
2470
  effectId: null,
2449
2471
  // Readiness is authority-local and must be re-established after restart. Captured input stays immutable.
2450
- step: y === "uncertain" && k?.step === "send" && k.phase !== "done" ? "receipt" : k?.step ?? null,
2451
- prepared: y === "accepted",
2452
- queuePosition: k?.queuePosition ?? S,
2453
- phase: y === "accepted" ? "done" : g || !k ? "failed" : ["running", "waiting"].includes(k.phase) ? "uncertain" : k.phase
2472
+ step: R === "uncertain" && b?.step === "send" && b.phase !== "done" ? "receipt" : b?.step ?? null,
2473
+ prepared: R === "accepted",
2474
+ queuePosition: b?.queuePosition ?? y,
2475
+ phase: R === "accepted" ? "done" : _ || !b ? "failed" : ["running", "waiting"].includes(b.phase) ? "uncertain" : b.phase
2454
2476
  }];
2455
2477
  })),
2456
- operations: Object.fromEntries(Object.entries(l.operations).map(([v, b]) => [v, {
2457
- ...b,
2478
+ operations: Object.fromEntries(Object.entries(g.operations).map(([w, f]) => [w, {
2479
+ ...f,
2458
2480
  effectId: null,
2459
- phase: ["running", "waiting"].includes(b.phase) ? "uncertain" : b.phase
2481
+ phase: ["running", "waiting"].includes(f.phase) ? "uncertain" : f.phase
2460
2482
  }]))
2461
2483
  };
2462
2484
  }
@@ -2479,11 +2501,11 @@ function ho(t, e, s, n) {
2479
2501
  if (!l) throw new Error("Stage the immutable submission before sending.");
2480
2502
  const u = t.deliveries[e.userMessageId];
2481
2503
  if (u && !l.cancelled && l.delivery !== "accepted" && (u.phase === "uncertain" || e.manualRetry && ["paused", "failed"].includes(u.phase))) {
2482
- const f = (u.acceptance === "unissued" || u.acceptance === "rejected") && u.allocation !== "uncertain" ? Math.max(t.requestSequence, ...Object.values(t.deliveries).map((m) => m.queuePosition)) + 1 : u.queuePosition;
2504
+ const g = (u.acceptance === "unissued" || u.acceptance === "rejected") && u.allocation !== "uncertain" ? Math.max(t.requestSequence, ...Object.values(t.deliveries).map((m) => m.queuePosition)) + 1 : u.queuePosition;
2483
2505
  i = {
2484
2506
  ...t,
2485
2507
  effectsEnabled: !0,
2486
- requestSequence: Math.max(t.requestSequence, f),
2508
+ requestSequence: Math.max(t.requestSequence, g),
2487
2509
  submissions: { ...t.submissions, [e.userMessageId]: { ...l, delivery: "staged", error: null } },
2488
2510
  deliveries: { ...t.deliveries, [e.userMessageId]: {
2489
2511
  ...u,
@@ -2491,7 +2513,7 @@ function ho(t, e, s, n) {
2491
2513
  effectId: null,
2492
2514
  ...e.manualRetry && l.error?.code === "message_acceptance_unconfirmed" ? { step: "send" } : {},
2493
2515
  prepared: !1,
2494
- queuePosition: f,
2516
+ queuePosition: g,
2495
2517
  command: u.acceptance === "unissued" && u.step === "send" ? null : u.command,
2496
2518
  recoveryDeadline: e.manualRetry && u.recoveryDeadline !== null ? e.now + 18e4 : u.recoveryDeadline
2497
2519
  } }
@@ -2519,10 +2541,10 @@ function ho(t, e, s, n) {
2519
2541
  const u = t.operations[l.request_id];
2520
2542
  if (u && (JSON.stringify(u.command) !== JSON.stringify(l) || u.conversationScopeId !== (e.conversationScopeId ?? null))) throw new Error("Command identity changed.");
2521
2543
  if (!u) {
2522
- const p = l.type === "chat.retry_last_user_message" ? Object.fromEntries(Object.entries(t.stops).flatMap(([f, m]) => {
2523
- if (s.selections[f]?.sessionId !== l.payload.sessionId) return [[f, m]];
2544
+ const p = l.type === "chat.retry_last_user_message" ? Object.fromEntries(Object.entries(t.stops).flatMap(([g, m]) => {
2545
+ if (s.selections[g]?.sessionId !== l.payload.sessionId) return [[g, m]];
2524
2546
  const h = m.userMessageIds.filter((v) => v !== l.payload.clientMessageId);
2525
- return h.length ? [[f, { ...m, userMessageIds: h }]] : [];
2547
+ return h.length ? [[g, { ...m, userMessageIds: h }]] : [];
2526
2548
  })) : t.stops;
2527
2549
  i = { ...t, stops: p, effectsEnabled: !0, operations: {
2528
2550
  ...t.operations,
@@ -2541,7 +2563,7 @@ function ho(t, e, s, n) {
2541
2563
  ...o,
2542
2564
  effectsEnabled: !0,
2543
2565
  requestSequence: o.requestSequence + 1,
2544
- deliveries: { ...o.deliveries, [e.userMessageId]: $n(o.submissions[e.userMessageId], o.requestSequence + 1) }
2566
+ deliveries: { ...o.deliveries, [e.userMessageId]: { ...$n(o.submissions[e.userMessageId], o.requestSequence + 1), ...e.waitForAuthentication ? { phase: "failed" } : {} } }
2545
2567
  });
2546
2568
  for (const [l, u] of Object.entries(o.submissions)) {
2547
2569
  const p = o.deliveries[l];
@@ -2692,7 +2714,7 @@ function bo(t) {
2692
2714
  requestId: l?.request_id ?? "cancellation",
2693
2715
  clientMessageId: l ? String(l.payload.expectedUserMessageId) : null,
2694
2716
  sessionId: l ? String(l.payload.sessionId) : null
2695
- }), p = e, f = async () => {
2717
+ }), p = e, g = async () => {
2696
2718
  if (!t.isCurrent() || a.authorityId !== t.authorityId) throw new Error("Cancellation authority was retired.");
2697
2719
  if (!o && s && a.requestSequence <= s.requestSequence) return;
2698
2720
  const m = await i();
@@ -2701,13 +2723,13 @@ function bo(t) {
2701
2723
  if (o) {
2702
2724
  s = a, a.requestSequence >= (m?.requestSequence ?? 0) && (h.cancelled = {}, h.operations = {}, h.stops = {});
2703
2725
  for (const [v] of d) delete h.cancelled[v];
2704
- for (const [v, b] of Object.entries(a.stops)) h.stops[v]?.requestId === b.requestId && delete h.stops[v];
2705
- for (const [v, b] of c)
2706
- JSON.stringify(h.operations[v]?.command) === JSON.stringify(b.command) && delete h.operations[v];
2726
+ for (const [v, I] of Object.entries(a.stops)) h.stops[v]?.requestId === I.requestId && delete h.stops[v];
2727
+ for (const [v, I] of c)
2728
+ JSON.stringify(h.operations[v]?.command) === JSON.stringify(I.command) && delete h.operations[v];
2707
2729
  } else {
2708
- for (const [v, b] of d) s?.submissions[v]?.cancelled || (h.cancelled[v] = { ...b, context: {}, contextPreparation: { pageContent: "", sessionTabs: [] } });
2709
- for (const [v, b] of Object.entries(a.stops)) s?.stops[v]?.requestId !== b.requestId && (h.stops[v] = b);
2710
- for (const [v, b] of c) b.phase !== "done" && b.phase !== "failed" && JSON.stringify(s?.operations[v]?.command) !== JSON.stringify(b.command) && (h.operations[v] = { ...b, effectId: null, phase: "uncertain", result: null, error: null });
2730
+ for (const [v, I] of d) s?.submissions[v]?.cancelled || (h.cancelled[v] = { ...I, context: {}, contextPreparation: { pageContent: "", sessionTabs: [] } });
2731
+ for (const [v, I] of Object.entries(a.stops)) s?.stops[v]?.requestId !== I.requestId && (h.stops[v] = I);
2732
+ for (const [v, I] of c) I.phase !== "done" && I.phase !== "failed" && JSON.stringify(s?.operations[v]?.command) !== JSON.stringify(I.command) && (h.operations[v] = { ...I, effectId: null, phase: "uncertain", result: null, error: null });
2711
2733
  }
2712
2734
  if (!(!m && !Object.keys(h.cancelled).length && !Object.keys(h.operations).length && !Object.keys(h.stops).length) && !(JSON.stringify(m?.cancelled ?? {}) === JSON.stringify(h.cancelled) && JSON.stringify(m?.operations ?? {}) === JSON.stringify(h.operations) && JSON.stringify(m?.stops ?? {}) === JSON.stringify(h.stops))) {
2713
2735
  if (!t.isCurrent()) throw new Error("Cancellation authority was retired.");
@@ -2716,7 +2738,7 @@ function bo(t) {
2716
2738
  };
2717
2739
  return e = u.measure("cancellation_queue", () => p.then(() => {
2718
2740
  }, () => {
2719
- })).then(f), e;
2741
+ })).then(g), e;
2720
2742
  };
2721
2743
  return {
2722
2744
  save: (a) => r(a, !1),
@@ -2922,7 +2944,7 @@ function Co(t) {
2922
2944
  };
2923
2945
  return t && t in e ? e[t] : t ?? "embedded_custom_ui";
2924
2946
  }
2925
- function xo(t, e) {
2947
+ function Oo(t, e) {
2926
2948
  const s = {}, n = {};
2927
2949
  for (const i of e) {
2928
2950
  const r = i.command.payload, a = String(r.clientMessageId);
@@ -2959,7 +2981,7 @@ function os(t) {
2959
2981
  return null;
2960
2982
  }
2961
2983
  }
2962
- function Oo(t, e) {
2984
+ function xo(t, e) {
2963
2985
  try {
2964
2986
  window.sessionStorage.setItem(`pa.authority:${t}`, e);
2965
2987
  } catch (s) {
@@ -3071,7 +3093,7 @@ function Mo(t) {
3071
3093
  throw Object.assign(new Error("Submission was cancelled."), { code: "submission_cancelled", retryable: !1 });
3072
3094
  }, a = (o) => {
3073
3095
  if (!t.onTiming || o.submission.sessionId !== null) return;
3074
- const c = t.runtime(), d = Object.values(c.engine.getState().slices.conversation.operations).find((f) => f.command.type === "runtime.warmup" && f.conversationScopeId === o.submission.conversationScopeId && ["waiting", "running", "uncertain"].includes(f.phase));
3096
+ const c = t.runtime(), d = Object.values(c.engine.getState().slices.conversation.operations).find((g) => g.command.type === "runtime.warmup" && g.conversationScopeId === o.submission.conversationScopeId && ["waiting", "running", "uncertain"].includes(g.phase));
3075
3097
  if (!d) return;
3076
3098
  const l = te(t.onTiming, {
3077
3099
  operation: "send",
@@ -3084,10 +3106,10 @@ function Mo(t) {
3084
3106
  let u = () => {
3085
3107
  }, p = () => {
3086
3108
  };
3087
- l.measure("warmup_wait", () => new Promise((f, m) => {
3109
+ l.measure("warmup_wait", () => new Promise((g, m) => {
3088
3110
  const h = () => {
3089
- const v = c.engine.getState().slices, b = v.conversation.submissions[o.submission.userMessageId], S = v.conversation.operations[d.command.request_id];
3090
- !Q(t) || !b || b.cancelled || v.directory.clients[b.clientScopeId] !== b.conversationScopeId ? m(new Error("Warmup wait was retired.")) : (b.sessionId !== null || !S || !["waiting", "running", "uncertain"].includes(S.phase)) && f();
3111
+ const v = c.engine.getState().slices, I = v.conversation.submissions[o.submission.userMessageId], k = v.conversation.operations[d.command.request_id];
3112
+ !Q(t) || !I || I.cancelled || v.directory.clients[I.clientScopeId] !== I.conversationScopeId ? m(new Error("Warmup wait was retired.")) : (I.sessionId !== null || !k || !["waiting", "running", "uncertain"].includes(k.phase)) && g();
3091
3113
  };
3092
3114
  u = c.engine.subscribe(h), p = c.onDispose(() => m(new Error("Warmup wait was retired."))), h();
3093
3115
  })).catch(() => {
@@ -3099,16 +3121,16 @@ function Mo(t) {
3099
3121
  "conversation.prepare": async (o) => {
3100
3122
  r(o.submission.userMessageId);
3101
3123
  let c;
3102
- const d = new Promise((p, f) => {
3103
- c = setTimeout(() => f(Object.assign(
3124
+ const d = new Promise((p, g) => {
3125
+ c = setTimeout(() => g(Object.assign(
3104
3126
  new Error("Message preparation timed out. Retry this message."),
3105
3127
  { code: "submission_preparation_timeout", retryable: !0 }
3106
3128
  )), 18e4);
3107
3129
  });
3108
3130
  let l = () => {
3109
3131
  };
3110
- const u = new Promise((p, f) => {
3111
- l = t.runtime().onDispose(() => f(new Error("Submission runtime was disposed.")));
3132
+ const u = new Promise((p, g) => {
3133
+ l = t.runtime().onDispose(() => g(new Error("Submission runtime was disposed.")));
3112
3134
  });
3113
3135
  return Promise.race([t.prepareSubmission(o), d, u]).then((p) => (r(o.submission.userMessageId), a(o), p)).catch((p) => n(p, { operation: "conversation.prepare", requestId: o.submission.userMessageId })).finally(() => {
3114
3136
  clearTimeout(c), l();
@@ -3159,14 +3181,14 @@ function Mo(t) {
3159
3181
  );
3160
3182
  if (Z(t, o), p.request_id !== o.command.request_id || !Ne(p.result)) throw Object.assign(new Error("Conversation response identity mismatch."), { code: "acceptance_identity_mismatch" });
3161
3183
  if (o.command.type.startsWith("chat.")) {
3162
- const f = p.result;
3163
- if (typeof f?.sessionId != "string" || !f.sessionId || f.clientMessageId !== o.command.payload.clientMessageId || o.command.payload.sessionId && f.sessionId !== o.command.payload.sessionId) throw Object.assign(new Error("Conversation acceptance identity mismatch."), { code: "acceptance_identity_mismatch" });
3184
+ const g = p.result;
3185
+ if (typeof g?.sessionId != "string" || !g.sessionId || g.clientMessageId !== o.command.payload.clientMessageId || o.command.payload.sessionId && g.sessionId !== o.command.payload.sessionId) throw Object.assign(new Error("Conversation acceptance identity mismatch."), { code: "acceptance_identity_mismatch" });
3164
3186
  te(t.onTiming, {
3165
3187
  operation: "send",
3166
3188
  layer: "http",
3167
3189
  requestId: o.command.request_id,
3168
3190
  clientMessageId: String(d.clientMessageId),
3169
- sessionId: f.sessionId
3191
+ sessionId: g.sessionId
3170
3192
  }).mark("acceptance_received");
3171
3193
  }
3172
3194
  return p.result;
@@ -3226,14 +3248,14 @@ function Mo(t) {
3226
3248
  if (!h.ok) throw Object.assign(new Error("Attachment transfer failed."), { code: String(h.status) });
3227
3249
  }
3228
3250
  d();
3229
- const f = p.attachment, m = {
3230
- id: f.id ?? null,
3231
- name: f.name,
3232
- mime_type: f.mimeType,
3233
- size_bytes: f.sizeBytes,
3234
- storage_key: f.storageKey ?? null,
3235
- sandbox_path: f.sandboxPath ?? null,
3236
- file_url: f.fileUrl ?? null
3251
+ const g = p.attachment, m = {
3252
+ id: g.id ?? null,
3253
+ name: g.name,
3254
+ mime_type: g.mimeType,
3255
+ size_bytes: g.sizeBytes,
3256
+ storage_key: g.storageKey ?? null,
3257
+ sandbox_path: g.sandboxPath ?? null,
3258
+ file_url: g.fileUrl ?? null
3237
3259
  };
3238
3260
  return await t.onUploaded?.(o.source.sourceId, p.sessionId, m), d(), { sessionId: p.sessionId, attachment: m };
3239
3261
  }).catch((d) => {
@@ -3247,18 +3269,18 @@ function Mo(t) {
3247
3269
  "conversation.snapshot": (o) => Promise.resolve().then(async () => {
3248
3270
  Z(t, o);
3249
3271
  const c = t.runtime(), d = new AbortController(), l = () => {
3250
- const f = c.engine.getState().slices;
3251
- Q(t) ? f.directory.memberships[o.sessionId]?.members.length ? f.conversation.sessions[o.sessionId]?.queries[o.lane].requestId !== o.requestId && d.abort("request_replaced") : d.abort("observation_released") : d.abort("authority_retired");
3272
+ const g = c.engine.getState().slices;
3273
+ Q(t) ? g.directory.memberships[o.sessionId]?.members.length ? g.conversation.sessions[o.sessionId]?.queries[o.lane].requestId !== o.requestId && d.abort("request_replaced") : d.abort("observation_released") : d.abort("authority_retired");
3252
3274
  }, u = c.engine.subscribe(l), p = c.onDispose(() => d.abort("owner_disposed"));
3253
3275
  l();
3254
3276
  try {
3255
- const f = [];
3256
- for (let b = 0; b < Math.max(1, o.refreshItemIds.length); b += 200) {
3277
+ const g = [];
3278
+ for (let I = 0; I < Math.max(1, o.refreshItemIds.length); I += 200) {
3257
3279
  if (Z(t, o), !t.runtime().engine.getState().slices.directory.memberships[o.sessionId]?.members.length) throw new Error("Conversation observation was retired.");
3258
- const S = await t.http.request(
3280
+ const k = await t.http.request(
3259
3281
  `/${encodeURIComponent(o.sessionId)}/snapshot`,
3260
3282
  {},
3261
- { context: { ...i(), ...t.snapshotContext?.(o.sessionId) }, retry_preparation: o.retryPreparation === !0, limit: 100, before: o.before, refresh_item_ids: o.refreshItemIds.slice(b, b + 200) },
3283
+ { context: { ...i(), ...t.snapshotContext?.(o.sessionId) }, retry_preparation: o.retryPreparation === !0, limit: 100, before: o.before, refresh_item_ids: o.refreshItemIds.slice(I, I + 200) },
3262
3284
  "POST",
3263
3285
  "conversations",
3264
3286
  { readOnly: !0, signal: d.signal, diagnostic: {
@@ -3267,28 +3289,28 @@ function Mo(t) {
3267
3289
  ownerId: c.engine.getDiagnostics().ownerId,
3268
3290
  authorityGeneration: o.generation
3269
3291
  } }
3270
- ).catch((k) => {
3271
- if (f.length === 0) throw k;
3272
- const g = ke(k);
3273
- throw Object.assign(g, { details: { ...g.details, successfulRequests: f.length } });
3292
+ ).catch((w) => {
3293
+ if (g.length === 0) throw w;
3294
+ const f = ke(w);
3295
+ throw Object.assign(f, { details: { ...f.details, successfulRequests: g.length } });
3274
3296
  });
3275
- if (Z(t, o), S.conversation_id !== o.sessionId) throw new Error("Snapshot conversation identity mismatch.");
3276
- if (f.push(S), !S.projection_ready) break;
3297
+ if (Z(t, o), k.conversation_id !== o.sessionId) throw new Error("Snapshot conversation identity mismatch.");
3298
+ if (g.push(k), !k.projection_ready) break;
3277
3299
  }
3278
- const m = f[0];
3300
+ const m = g[0];
3279
3301
  if (o.before !== null && m.next_cursor === o.before)
3280
3302
  throw Object.assign(new Error("Conversation history cursor did not advance."), { code: "invalid_history_cursor" });
3281
- const h = f.reduce((b, S) => S.execution.version > b.version ? S.execution : b, m.execution), v = f.reduce((b, S) => S.follow_ups_version > b.follow_ups_version ? S : b, m);
3303
+ const h = g.reduce((I, k) => k.execution.version > I.version ? k.execution : I, m.execution), v = g.reduce((I, k) => k.follow_ups_version > I.follow_ups_version ? k : I, m);
3282
3304
  return { snapshot: {
3283
3305
  ...m,
3284
3306
  execution: h,
3285
- items: f.flatMap((b) => b.items),
3286
- streams: f.flatMap((b) => b.streams),
3287
- removed_items: f.flatMap((b) => b.removed_items),
3288
- interactions: f.flatMap((b) => b.interactions),
3307
+ items: g.flatMap((I) => I.items),
3308
+ streams: g.flatMap((I) => I.streams),
3309
+ removed_items: g.flatMap((I) => I.removed_items),
3310
+ interactions: g.flatMap((I) => I.interactions),
3289
3311
  follow_ups: v.follow_ups,
3290
3312
  follow_ups_version: v.follow_ups_version,
3291
- projection_ready: f.every((b) => b.projection_ready)
3313
+ projection_ready: g.every((I) => I.projection_ready)
3292
3314
  }, updatedAt: t.now() };
3293
3315
  } finally {
3294
3316
  u(), p();
@@ -3503,7 +3525,7 @@ function Uo(t, e, s, n) {
3503
3525
  function as(t, e, s, n) {
3504
3526
  const i = /* @__PURE__ */ new Map();
3505
3527
  for (const y of t.segments)
3506
- for (const I of [...y.activityIds, ...y.outcomeIds]) i.set(I, y.userMessageId);
3528
+ for (const b of [...y.activityIds, ...y.outcomeIds]) i.set(b, y.userMessageId);
3507
3529
  const r = t.items.map((y) => Uo(
3508
3530
  y,
3509
3531
  i.get(y.id) ?? null,
@@ -3516,15 +3538,15 @@ function as(t, e, s, n) {
3516
3538
  content: y.content,
3517
3539
  // There is no canonical timestamp before acceptance. Keep identity stable without fabricating one.
3518
3540
  createdAt: "",
3519
- retryable: y.delivery === "failed" && ["delivery", "preparation"].includes(Di(t, y.userMessageId)?.type ?? ""),
3520
- attachments: y.attachments.map((I) => ({
3521
- id: I.sourceId,
3522
- name: I.name,
3523
- mimeType: I.mimeType,
3524
- sizeBytes: I.sizeBytes
3541
+ retryable: y.delivery === "failed" && !["unauthorized", "401", "auth_reconnecting"].includes(y.error?.code ?? "") && ["delivery", "preparation"].includes(Di(t, y.userMessageId)?.type ?? ""),
3542
+ attachments: y.attachments.map((b) => ({
3543
+ id: b.sourceId,
3544
+ name: b.name,
3545
+ mimeType: b.mimeType,
3546
+ sizeBytes: b.sizeBytes
3525
3547
  }))
3526
3548
  });
3527
- const a = t.segments.flatMap((y) => r.filter((I) => I.id === y.userMessageId || y.activityIds.includes(I.id) || y.outcomeIds.includes(I.id)));
3549
+ const a = t.segments.flatMap((y) => r.filter((b) => b.id === y.userMessageId || y.activityIds.includes(b.id) || y.outcomeIds.includes(b.id)));
3528
3550
  t.proactiveQuestion && a.push({
3529
3551
  id: t.proactiveQuestion.id,
3530
3552
  role: "assistant",
@@ -3533,28 +3555,28 @@ function as(t, e, s, n) {
3533
3555
  createdAt: "",
3534
3556
  loading: !1
3535
3557
  });
3536
- const o = t.activity.phase, c = t.submissions.filter((y) => !y.cancelled && !["accepted", "failed"].includes(y.delivery)), d = t.submissions[t.submissions.length - 1], l = [...t.items].reverse().find((y) => y.type === "user_message"), u = ["queued", "thinking", "steering", "awaiting_execution"].includes(o), p = d?.delivery === "failed" && (u && t.activity.userMessageId != null && t.activity.userMessageId !== d.userMessageId || l !== void 0 && l.id !== d.userMessageId && Date.parse(l.created_at) > d.submittedAt), f = new Map(t.submissions.filter((y) => (y !== d || p) && !y.cancelled && y.delivery === "failed" && y.error).map((y) => [y.userMessageId, y])), m = a.flatMap((y) => {
3537
- const I = y.role === "user" ? f.get(y.id) : void 0;
3538
- return I?.error ? [y, {
3539
- id: `submission-error:${I.userMessageId}`,
3558
+ const o = t.activity.phase, c = t.submissions.filter((y) => !y.cancelled && !["accepted", "failed"].includes(y.delivery)), d = t.submissions[t.submissions.length - 1], l = [...t.items].reverse().find((y) => y.type === "user_message"), u = ["queued", "thinking", "steering", "awaiting_execution"].includes(o), p = d?.delivery === "failed" && (u && t.activity.userMessageId != null && t.activity.userMessageId !== d.userMessageId || l !== void 0 && l.id !== d.userMessageId && Date.parse(l.created_at) > d.submittedAt), g = new Map(t.submissions.filter((y) => (y !== d || p) && !y.cancelled && y.delivery === "failed" && y.error).map((y) => [y.userMessageId, y])), m = a.flatMap((y) => {
3559
+ const b = y.role === "user" ? g.get(y.id) : void 0;
3560
+ return b?.error ? [y, {
3561
+ id: `submission-error:${b.userMessageId}`,
3540
3562
  role: "system",
3541
3563
  dataType: "run_error",
3542
- respondsToUserMessageId: I.userMessageId,
3543
- content: I.error.message,
3564
+ respondsToUserMessageId: b.userMessageId,
3565
+ content: b.error.message,
3544
3566
  createdAt: "",
3545
3567
  loading: !1,
3546
- ...typeof I.error.details?.securitySettingsUrl == "string" ? { securitySettingsUrl: I.error.details.securitySettingsUrl } : {}
3568
+ ...typeof b.error.details?.securitySettingsUrl == "string" ? { securitySettingsUrl: b.error.details.securitySettingsUrl } : {}
3547
3569
  }] : [y];
3548
- }), h = e?.error != null && t.historyRefreshFailure != null && t.historyRefreshFailure.consecutiveFailures < 4, v = h ? null : e?.error ?? null, b = d?.delivery === "failed" && !d.cancelled && !p ? d.error : v, S = {
3570
+ }), h = e?.error != null && t.historyRefreshFailure != null && t.historyRefreshFailure.consecutiveFailures < 4, v = h ? null : e?.error ?? null, I = d?.delivery === "failed" && !d.cancelled && !p ? d.error : v, k = {
3549
3571
  isRetrying: t.isRetrying ?? !1,
3550
- historyRefreshFailure: b === e?.error ? t.historyRefreshFailure ?? null : null,
3572
+ historyRefreshFailure: I === e?.error ? t.historyRefreshFailure ?? null : null,
3551
3573
  conversationDiagnostics: {
3552
- ...b ? { errorMessageFingerprint: Vi(Ce(b.message)) } : {},
3553
- ...d && b && b === d.error && !p ? { failedClientMessageId: d.userMessageId } : {},
3554
- ...typeof b?.details?.requestId == "string" ? { errorRequestId: b.details.requestId } : {},
3555
- ...nt(b?.details?.errorNormalization) ? { errorNormalization: b.details.errorNormalization } : {},
3574
+ ...I ? { errorMessageFingerprint: Vi(Ce(I.message)) } : {},
3575
+ ...d && I && I === d.error && !p ? { failedClientMessageId: d.userMessageId } : {},
3576
+ ...typeof I?.details?.requestId == "string" ? { errorRequestId: I.details.requestId } : {},
3577
+ ...nt(I?.details?.errorNormalization) ? { errorNormalization: I.details.errorNormalization } : {},
3556
3578
  ...n ? { owner: n } : {},
3557
- ...ye(b?.details?.httpRequest) ? { httpRequest: b.details.httpRequest } : {},
3579
+ ...ye(I?.details?.httpRequest) ? { httpRequest: I.details.httpRequest } : {},
3558
3580
  queryStatus: e?.status ?? null,
3559
3581
  queryRequestId: e?.requestId ?? null,
3560
3582
  queryUpdatedAt: e?.updatedAt ?? null
@@ -3582,24 +3604,24 @@ function as(t, e, s, n) {
3582
3604
  turnPhase: o === "submitting" ? "sending" : ["queued", "awaiting_execution"].includes(o) ? "starting" : ["thinking", "steering"].includes(o) ? "thinking" : null,
3583
3605
  isThinking: u,
3584
3606
  taskStatus: o === "completed" ? "completed" : o === "failed" ? "failed" : o === "stopped" || o === "stopping" ? "stopped" : u || o === "submitting" ? "working" : null,
3585
- lastError: b?.message ?? null,
3586
- lastErrorCode: b?.code ?? null,
3587
- lastErrorSecuritySettingsUrl: typeof b?.details?.securitySettingsUrl == "string" ? b.details.securitySettingsUrl : null
3607
+ lastError: I?.message ?? null,
3608
+ lastErrorCode: I?.code ?? null,
3609
+ lastErrorSecuritySettingsUrl: typeof I?.details?.securitySettingsUrl == "string" ? I.details.securitySettingsUrl : null
3588
3610
  };
3589
- let k = S;
3590
- for (const y of t.optimistic.filter((I) => I.cancelled && !t.stop?.userMessageIds.includes(I.userMessageId))) {
3591
- const I = Gs(k, "", "stopped", [y.userMessageId], Gn(y.cancellationReason));
3592
- k = { ...k, messages: I.messages, segments: I.segments };
3593
- }
3594
- if (!t.stop) return k;
3595
- const g = Gs(
3596
- k,
3611
+ let w = k;
3612
+ for (const y of t.optimistic.filter((b) => b.cancelled && !t.stop?.userMessageIds.includes(b.userMessageId))) {
3613
+ const b = Gs(w, "", "stopped", [y.userMessageId], Gn(y.cancellationReason));
3614
+ w = { ...w, messages: b.messages, segments: b.segments };
3615
+ }
3616
+ if (!t.stop) return w;
3617
+ const f = Gs(
3618
+ w,
3597
3619
  "",
3598
3620
  t.stop.pending ? "stopping" : "stopped",
3599
3621
  t.stop.userMessageIds,
3600
3622
  Gn(t.stop.reason ?? "user_requested")
3601
3623
  );
3602
- return { ...S, messages: g.messages, segments: g.segments };
3624
+ return { ...k, messages: f.messages, segments: f.segments };
3603
3625
  }
3604
3626
  function Gn(t) {
3605
3627
  switch (t) {
@@ -4990,7 +5012,7 @@ var M;
4990
5012
  (function(t) {
4991
5013
  t[t.CONNECT = 0] = "CONNECT", t[t.DISCONNECT = 1] = "DISCONNECT", t[t.EVENT = 2] = "EVENT", t[t.ACK = 3] = "ACK", t[t.CONNECT_ERROR = 4] = "CONNECT_ERROR", t[t.BINARY_EVENT = 5] = "BINARY_EVENT", t[t.BINARY_ACK = 6] = "BINARY_ACK";
4992
5014
  })(M || (M = {}));
4993
- class xa {
5015
+ class Oa {
4994
5016
  /**
4995
5017
  * Encoder constructor
4996
5018
  *
@@ -5052,7 +5074,7 @@ class bn extends F {
5052
5074
  throw new Error("got plaintext data when reconstructing a packet");
5053
5075
  s = this.decodeString(e);
5054
5076
  const n = s.type === M.BINARY_EVENT;
5055
- n || s.type === M.BINARY_ACK ? (s.type = n ? M.EVENT : M.ACK, this.reconstructor = new Oa(s)) : super.emitReserved("decoded", s);
5077
+ n || s.type === M.BINARY_ACK ? (s.type = n ? M.EVENT : M.ACK, this.reconstructor = new xa(s)) : super.emitReserved("decoded", s);
5056
5078
  } else if (vn(e) || e.base64)
5057
5079
  if (this.reconstructor)
5058
5080
  s = this.reconstructor.takeBinaryData(e), s && (this.reconstructor = null, super.emitReserved("decoded", s));
@@ -5148,7 +5170,7 @@ class bn extends F {
5148
5170
  this.reconstructor && (this.reconstructor.finishedReconstruction(), this.reconstructor = null);
5149
5171
  }
5150
5172
  }
5151
- class Oa {
5173
+ class xa {
5152
5174
  constructor(e) {
5153
5175
  this.packet = e, this.buffers = [], this.reconPack = e;
5154
5176
  }
@@ -5183,7 +5205,7 @@ function ei(t) {
5183
5205
  const Pa = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
5184
5206
  __proto__: null,
5185
5207
  Decoder: bn,
5186
- Encoder: xa,
5208
+ Encoder: Oa,
5187
5209
  get PacketType() {
5188
5210
  return M;
5189
5211
  }
@@ -6362,7 +6384,7 @@ class ja {
6362
6384
  connection_id: `pa-sio:${this.socket.id}`,
6363
6385
  request_id: i,
6364
6386
  session_id: e.sessionId ?? e.session_id
6365
- }).replace(/[\u007f-\uffff]/g, (f) => `\\u${f.charCodeAt(0).toString(16).padStart(4, "0")}`)
6387
+ }).replace(/[\u007f-\uffff]/g, (g) => `\\u${g.charCodeAt(0).toString(16).padStart(4, "0")}`)
6366
6388
  },
6367
6389
  body: JSON.stringify({ request_id: i, type: "tool.result", payload: e })
6368
6390
  });
@@ -6441,24 +6463,24 @@ class or {
6441
6463
  }) : this.options.pendingAuthentication?.()), c();
6442
6464
  const p = this.options.authenticationFailure?.();
6443
6465
  if (p) throw p;
6444
- const f = this.auth.token;
6466
+ const g = this.auth.token;
6445
6467
  let m = null;
6446
6468
  try {
6447
6469
  let h = n;
6448
6470
  if (r === "conversations" && e === "/commands" && this.auth.role !== "session_surface" && this.options.executorConnection) {
6449
6471
  if (m = this.options.executorConnection(), !m) throw new A("Reconnecting the browser before continuing.", "executor_not_ready");
6450
- const S = n;
6451
- h = { ...S, context: { ...S.context, connection_id: m } };
6472
+ const k = n;
6473
+ h = { ...k, context: { ...k.context, connection_id: m } };
6452
6474
  }
6453
- const v = () => this.requestOnce(e, s, h, i, r, a.signal, a.diagnostic, ++l), b = await (a.timing ? a.timing.measure("http_request", v) : v());
6454
- return c(), b;
6475
+ const v = () => this.requestOnce(e, s, h, i, r, a.signal, a.diagnostic, ++l), I = await (a.timing ? a.timing.measure("http_request", v) : v());
6476
+ return c(), I;
6455
6477
  } catch (h) {
6456
6478
  if (c(!1), this.requests.signal.aborted || a.signal?.aborted) throw h;
6457
6479
  if (h instanceof A && h.code === "executor_not_ready" && m && u === 0 && this.options.restoreExecutor) {
6458
6480
  await this.options.restoreExecutor(m), u++, c();
6459
6481
  continue;
6460
6482
  }
6461
- if (!(h instanceof A) || !["unauthorized", "403"].includes(h.code) || !this.options.recoverAuthentication || !d || (await this.options.recoverAuthentication(f, h, d && u === 0), c(), !d || u !== 0)) throw h;
6483
+ if (!(h instanceof A) || !["unauthorized", "403"].includes(h.code) || !this.options.recoverAuthentication || !d || (await this.options.recoverAuthentication(g, h, d && u === 0), c(), !d || u !== 0)) throw h;
6462
6484
  u++;
6463
6485
  }
6464
6486
  }
@@ -6468,51 +6490,51 @@ class or {
6468
6490
  for (const [E, q] of Object.entries({ ...u, ...s }))
6469
6491
  q != null && l.searchParams.set(E, String(q));
6470
6492
  this.requests.signal.throwIfAborted(), a?.throwIfAborted();
6471
- const p = new AbortController(), f = { trigger: null }, m = (E) => {
6472
- p.signal.aborted || (f.trigger = E, p.abort());
6493
+ const p = new AbortController(), g = { trigger: null }, m = (E) => {
6494
+ p.signal.aborted || (g.trigger = E, p.abort());
6473
6495
  }, h = () => m("transport_disposed"), v = () => m(["owner_disposed", "authority_retired", "observation_released", "request_replaced"].includes(a?.reason) ? a.reason : "caller_cancelled");
6474
6496
  this.requests.signal.addEventListener("abort", h, { once: !0 }), a?.addEventListener("abort", v, { once: !0 });
6475
- const b = r === "conversations" && /^\/[^/]+\/snapshot$/.test(e) && i === "POST", S = /^\/conversations(?:\/[^/]+)?$/.test(e) && (i ?? (n === void 0 ? "GET" : "POST")) === "GET", k = setTimeout(() => m("deadline"), S ? 6e4 : b ? 3e4 : 15e3), g = Ba(), y = Date.now();
6476
- let I = null, w = !1, R = null, T = null, C = null;
6497
+ const I = r === "conversations" && /^\/[^/]+\/snapshot$/.test(e) && i === "POST", k = /^\/conversations(?:\/[^/]+)?$/.test(e) && (i ?? (n === void 0 ? "GET" : "POST")) === "GET", w = setTimeout(() => m("deadline"), k ? 6e4 : I ? 3e4 : 15e3), f = Ba(), y = Date.now();
6498
+ let b = null, _ = !1, R = null, T = null, C = null;
6477
6499
  try {
6478
6500
  const E = await Promise.resolve(fetch(l, {
6479
6501
  method: i ?? (n === void 0 ? "GET" : "POST"),
6480
6502
  cache: "no-store",
6481
6503
  signal: p.signal,
6482
- headers: { "x-product-agent-auth-request-id": g, authorization: d || r === "conversations" ? `Bearer ${this.auth.token}` : this.auth.token, "content-type": "application/json", ...b ? { "x-request-id": g } : {} },
6504
+ headers: { "x-product-agent-auth-request-id": f, authorization: d || r === "conversations" ? `Bearer ${this.auth.token}` : this.auth.token, "content-type": "application/json", ...I ? { "x-request-id": f } : {} },
6483
6505
  ...n === void 0 ? {} : { body: JSON.stringify(n) }
6484
6506
  })).catch((q) => {
6485
- throw w = !0, q;
6507
+ throw _ = !0, q;
6486
6508
  });
6487
- if (I = Date.now(), R = E.status, T = si(E.headers.get("x-request-id")), C = si(E.headers.get("x-cloud-trace-context")), !E.ok) {
6488
- const q = E.status === 401 ? "unauthorized" : E.status === 426 ? "update_required" : String(E.status), x = (await E.json().catch(() => null))?.detail;
6489
- if (d && E.status === 403 && (r === "conversations" && /^\/[^/]+\/snapshot$/.test(e) || (!r || r === "embed") && /^\/conversations\/[^/]+$/.test(e)) && ["Conversation unavailable", "Integration mismatch", "Embedded origin mismatch"].includes(x))
6509
+ if (b = Date.now(), R = E.status, T = si(E.headers.get("x-request-id")), C = si(E.headers.get("x-cloud-trace-context")), !E.ok) {
6510
+ const q = E.status === 401 ? "unauthorized" : E.status === 426 ? "update_required" : String(E.status), O = (await E.json().catch(() => null))?.detail;
6511
+ if (d && E.status === 403 && (r === "conversations" && /^\/[^/]+\/snapshot$/.test(e) || (!r || r === "embed") && /^\/conversations\/[^/]+$/.test(e)) && ["Conversation unavailable", "Integration mismatch", "Embedded origin mismatch"].includes(O))
6490
6512
  throw new A("Conversation unavailable", "conversation_access_denied");
6491
- if (r === "conversations" && e.endsWith("/snapshot") && E.status === 409 && x === "Display projection is not enabled")
6513
+ if (r === "conversations" && e.endsWith("/snapshot") && E.status === 409 && O === "Display projection is not enabled")
6492
6514
  throw new A("Conversation history is unavailable. Try loading this chat again after the service is ready.", "display_projection_disabled");
6493
- if (r === "conversations" && e === "/commands" && E.status === 409 && (x === "embedded_submission_conflict" || x === "embedded_submission_snapshot_unavailable"))
6494
- throw new A(x === "embedded_submission_conflict" ? "This message conflicts with an earlier submission. Review the conversation before retrying." : "This earlier submission cannot be verified. Review the conversation before retrying.", x, !1, void 0, !0);
6495
- if (r === "conversations" && e === "/commands" && (E.status === 409 && x?.code === "executor_not_ready" && x.retryable === !0 || E.status === 403 && x === "Register the executor before commands"))
6515
+ if (r === "conversations" && e === "/commands" && E.status === 409 && (O === "embedded_submission_conflict" || O === "embedded_submission_snapshot_unavailable"))
6516
+ throw new A(O === "embedded_submission_conflict" ? "This message conflicts with an earlier submission. Review the conversation before retrying." : "This earlier submission cannot be verified. Review the conversation before retrying.", O, !1, void 0, !0);
6517
+ if (r === "conversations" && e === "/commands" && (E.status === 409 && O?.code === "executor_not_ready" && O.retryable === !0 || E.status === 403 && O === "Register the executor before commands"))
6496
6518
  throw new A("Reconnecting the browser before continuing.", "executor_not_ready");
6497
- if (E.status !== 401 && x && typeof x == "object" && (["service_origin_not_allowed", "security_control_enforcement_unavailable"].includes(x.code) || !xt(void 0, x.code).allowed) && typeof x.message == "string")
6498
- throw new A(x.message, x.code, !1, {
6499
- ...typeof x.blockedOrigin == "string" ? { blockedOrigin: x.blockedOrigin } : {},
6500
- ...typeof x.securitySettingsUrl == "string" ? { securitySettingsUrl: x.securitySettingsUrl } : {}
6519
+ if (E.status !== 401 && O && typeof O == "object" && (["service_origin_not_allowed", "security_control_enforcement_unavailable"].includes(O.code) || !Ot(void 0, O.code).allowed) && typeof O.message == "string")
6520
+ throw new A(O.message, O.code, !1, {
6521
+ ...typeof O.blockedOrigin == "string" ? { blockedOrigin: O.blockedOrigin } : {},
6522
+ ...typeof O.securitySettingsUrl == "string" ? { securitySettingsUrl: O.securitySettingsUrl } : {}
6501
6523
  }, r === "conversations" && e === "/commands");
6502
- const _ = x === "Token expired" ? "token_expired" : x === "Invalid token" ? "invalid_token" : x?.reason, O = E.status === 401 && ["missing_token", "token_expired", "invalid_token", "user_not_found"].includes(_) ? { requestId: g, authTransport: "http", authEndpoint: `${r ?? (d ? "embed" : "runtime")}:${["snapshot", "me", "bootstrap", "commands", "activity", "session-history"].includes(e.split("/").pop()) ? e.split("/").pop() : "other"}`, reason: _, retryable: _ === "token_expired" && (x === "Token expired" || x.retryable === !0) } : void 0;
6503
- throw new A(E.status === 401 ? "Your session expired or is invalid. Reconnect to continue." : E.status === 403 ? "You don't have access to this conversation. Check your access and reconnect." : `Product Agent request failed (${E.status})`, q, !1, O);
6524
+ const S = O === "Token expired" ? "token_expired" : O === "Invalid token" ? "invalid_token" : O?.reason, x = E.status === 401 && ["missing_token", "token_expired", "invalid_token", "user_not_found"].includes(S) ? { requestId: f, authTransport: "http", authEndpoint: `${r ?? (d ? "embed" : "runtime")}:${["snapshot", "me", "bootstrap", "commands", "activity", "session-history"].includes(e.split("/").pop()) ? e.split("/").pop() : "other"}`, reason: S, retryable: S === "token_expired" && (O === "Token expired" || O.retryable === !0) } : void 0;
6525
+ throw new A(E.status === 401 ? "Your session expired or is invalid. Reconnect to continue." : E.status === 403 ? "You don't have access to this conversation. Check your access and reconnect." : `Product Agent request failed (${E.status})`, q, !1, x);
6504
6526
  }
6505
6527
  return await E.json();
6506
6528
  } catch (E) {
6507
- const q = f.trigger ?? ((E instanceof Error || E instanceof DOMException) && E.name === "AbortError" ? "unexpected_abort" : null), x = {
6508
- requestId: g,
6529
+ const q = g.trigger ?? ((E instanceof Error || E instanceof DOMException) && E.name === "AbortError" ? "unexpected_abort" : null), O = {
6530
+ requestId: f,
6509
6531
  method: i ?? (n === void 0 ? "GET" : "POST"),
6510
- route: b ? "/api/product-agent/conversations/:sessionId/snapshot" : e === "/commands" ? "/api/product-agent/:namespace/commands" : "/api/product-agent/:namespace/:operation",
6532
+ route: I ? "/api/product-agent/conversations/:sessionId/snapshot" : e === "/commands" ? "/api/product-agent/:namespace/commands" : "/api/product-agent/:namespace/:operation",
6511
6533
  status: R,
6512
6534
  abortTrigger: q,
6513
- category: q === "deadline" ? "request_timed_out" : q === "unexpected_abort" ? "connection_interrupted" : q ? "request_cancelled" : E instanceof A ? E.code : w ? "connection_interrupted" : "invalid_response",
6514
- responseHeadersMs: I === null ? null : Math.max(0, I - y),
6515
- responseBodyMs: I === null ? null : Math.max(0, Date.now() - I),
6535
+ category: q === "deadline" ? "request_timed_out" : q === "unexpected_abort" ? "connection_interrupted" : q ? "request_cancelled" : E instanceof A ? E.code : _ ? "connection_interrupted" : "invalid_response",
6536
+ responseHeadersMs: b === null ? null : Math.max(0, b - y),
6537
+ responseBodyMs: b === null ? null : Math.max(0, Date.now() - b),
6516
6538
  owner: q === "deadline" ? "http_deadline" : q === "transport_disposed" ? "http_transport" : q && q !== "unexpected_abort" ? "conversation_query" : R === null ? "browser" : "http_response",
6517
6539
  elapsedMs: Math.max(0, Date.now() - y),
6518
6540
  attempt: c,
@@ -6524,26 +6546,26 @@ class or {
6524
6546
  upstreamRequestId: T,
6525
6547
  upstreamTraceId: C
6526
6548
  };
6527
- ye(x) && Promise.resolve().then(() => this.options.onRequestFailure ? this.options.onRequestFailure(x) : console.warn("Product Agent HTTP request failed", x)).catch(() => {
6549
+ ye(O) && Promise.resolve().then(() => this.options.onRequestFailure ? this.options.onRequestFailure(O) : console.warn("Product Agent HTTP request failed", O)).catch(() => {
6528
6550
  });
6529
- const _ = ye(x) ? { httpRequest: x } : void 0;
6551
+ const S = ye(O) ? { httpRequest: O } : void 0;
6530
6552
  if (q !== null) {
6531
- const O = q !== "deadline" && q !== "unexpected_abort";
6553
+ const x = q !== "deadline" && q !== "unexpected_abort";
6532
6554
  throw new A(
6533
- O ? "The request was cancelled." : q === "deadline" ? "The request timed out. Please try again." : "The connection was interrupted. Please try again.",
6534
- O ? "request_cancelled" : q === "deadline" ? "request_timed_out" : "connection_interrupted",
6555
+ x ? "The request was cancelled." : q === "deadline" ? "The request timed out. Please try again." : "The connection was interrupted. Please try again.",
6556
+ x ? "request_cancelled" : q === "deadline" ? "request_timed_out" : "connection_interrupted",
6535
6557
  !0,
6536
- _
6558
+ S
6537
6559
  );
6538
6560
  }
6539
- throw E instanceof A && _ ? new A(E.message, E.code, E.outcomeUnknown, { ...E.detail, ..._ }, E.backendRefusal) : _ ? new A(
6540
- w ? "The connection was interrupted. Please try again." : b ? "The conversation response could not be read. Please try again." : "The response could not be read. Please try again.",
6561
+ throw E instanceof A && S ? new A(E.message, E.code, E.outcomeUnknown, { ...E.detail, ...S }, E.backendRefusal) : S ? new A(
6562
+ _ ? "The connection was interrupted. Please try again." : I ? "The conversation response could not be read. Please try again." : "The response could not be read. Please try again.",
6541
6563
  "connection_interrupted",
6542
6564
  !0,
6543
- _
6565
+ S
6544
6566
  ) : E;
6545
6567
  } finally {
6546
- clearTimeout(k), this.requests.signal.removeEventListener("abort", h), a?.removeEventListener("abort", v);
6568
+ clearTimeout(w), this.requests.signal.removeEventListener("abort", h), a?.removeEventListener("abort", v);
6547
6569
  }
6548
6570
  }
6549
6571
  }
@@ -6923,25 +6945,29 @@ class Va {
6923
6945
  }
6924
6946
  async restore(e) {
6925
6947
  const s = this.state();
6926
- if (!this.current() || Object.keys(s.clients).length || Object.keys(s.selections).length) return !1;
6948
+ if (!this.current()) return !1;
6927
6949
  const n = await this.options.persistence.read();
6928
6950
  if (!Ha(n) || n.authorityId !== this.options.authority.authorityId || n.browserSessionId !== this.options.persistence.sessionId()) return !1;
6929
6951
  const i = new Set(await this.options.persistence.liveClients());
6930
6952
  if (!this.current() || this.state().clients !== s.clients) return !1;
6931
- const r = n.bindings.filter((c) => i.has(c.clientScopeId));
6953
+ const r = n.bindings.filter((c) => {
6954
+ if (!i.has(c.clientScopeId) || s.clients[c.clientScopeId]) return !1;
6955
+ const d = s.selections[c.conversationScopeId];
6956
+ return !d || d.sessionId === c.sessionId && d.provisionalId === c.provisionalId;
6957
+ });
6932
6958
  if (e !== void 0 && r.some((c) => c.sessionId !== e)) return !1;
6933
6959
  const a = [], o = new Set(r.map((c) => c.sessionId));
6934
6960
  for (const c of o) {
6935
- const d = r.filter((f) => f.sessionId === c), l = c === null ? d[0] : d.find((f) => f.clientScopeId === n.mains[c]) ?? this.choose(d), u = [l, ...d.filter((f) => f !== l)], p = /* @__PURE__ */ new Set();
6936
- for (const f of u) {
6937
- const m = { ...this.options.authority, clientScopeId: f.clientScopeId, conversationScopeId: f.conversationScopeId, replacement: null };
6938
- f.provisionalId !== null && !p.has(f.conversationScopeId) ? (a.push({ ...m, type: "directory.provisional", provisionalId: f.provisionalId }), c !== null && (a.push({
6961
+ const d = r.filter((g) => g.sessionId === c), l = c === null ? d[0] : d.find((g) => g.clientScopeId === n.mains[c]) ?? this.choose(d), u = [l, ...d.filter((g) => g !== l)], p = /* @__PURE__ */ new Set();
6962
+ for (const g of u) {
6963
+ const m = { ...this.options.authority, clientScopeId: g.clientScopeId, conversationScopeId: g.conversationScopeId, replacement: null };
6964
+ g.provisionalId !== null && !p.has(g.conversationScopeId) && !s.selections[g.conversationScopeId]?.sessionId ? (a.push({ ...m, type: "directory.provisional", provisionalId: g.provisionalId }), c !== null && (a.push({
6939
6965
  ...this.options.authority,
6940
6966
  type: "directory.accepted",
6941
- conversationScopeId: f.conversationScopeId,
6942
- provisionalId: f.provisionalId,
6967
+ conversationScopeId: g.conversationScopeId,
6968
+ provisionalId: g.provisionalId,
6943
6969
  sessionId: c
6944
- }), p.add(f.conversationScopeId))) : a.push({ ...m, type: "directory.bind", sessionId: c, reason: "user" });
6970
+ }), p.add(g.conversationScopeId))) : a.push({ ...m, type: "directory.bind", sessionId: c, reason: "user" });
6945
6971
  }
6946
6972
  }
6947
6973
  return await Promise.all(a.map((c) => this.options.runtime.engine.dispatch(c))), !0;
@@ -7246,7 +7272,7 @@ class L extends EventTarget {
7246
7272
  if (n === "auth.session") {
7247
7273
  if (this.initialized) return;
7248
7274
  this.initialized = !0;
7249
- const p = this.bootstrapRequests.signal, f = this.credentialBootstrap ?? await this.httpTransport.request(
7275
+ const p = this.bootstrapRequests.signal, g = this.credentialBootstrap ?? await this.httpTransport.request(
7250
7276
  r ? "/bootstrap" : "/me",
7251
7277
  r ? o : {},
7252
7278
  void 0,
@@ -7254,8 +7280,8 @@ class L extends EventTarget {
7254
7280
  void 0,
7255
7281
  { signal: p }
7256
7282
  );
7257
- if (p.aborted || !this.isCurrent(s) || (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 }), p.aborted)) return;
7258
- this.options.auth.client_kind === "extension" && this.receive({ type: "executor.registered", userId: f.user.id }), this.bootstrapped = !0;
7283
+ if (p.aborted || !this.isCurrent(s) || (this.credentialBootstrap = null, !this.options.auth.community_id && g.user?.runtimeCommunityId && (this.options.auth.community_id = g.user.runtimeCommunityId), this.receive({ type: "auth.ok", ...g }), p.aborted)) return;
7284
+ this.options.auth.client_kind === "extension" && this.receive({ type: "executor.registered", userId: g.user.id }), this.bootstrapped = !0;
7259
7285
  for (const m of this.beforeBootstrap.splice(0)) this.receive(m);
7260
7286
  this.synchronizeReferences(), this.options.auth.client_kind === "web" && this.loadUserSuggestions(p);
7261
7287
  return;
@@ -7265,8 +7291,8 @@ class L extends EventTarget {
7265
7291
  return;
7266
7292
  }
7267
7293
  if (n === "starter_prompts.page_url" || n === "starter_prompts.page_context") {
7268
- const p = ++this.promptRevision, f = await this.http("/starter-prompts", o, n === "starter_prompts.page_context" ? { page_url: a, page_title: e.pageTitle ?? "", html_content: e.htmlContent ?? "" } : void 0);
7269
- this.isCurrent(s) && p === this.promptRevision && a === this.options.pageUrl() && this.receive({ type: "starterPrompts.updated", ...f });
7294
+ const p = ++this.promptRevision, g = await this.http("/starter-prompts", o, n === "starter_prompts.page_context" ? { page_url: a, page_title: e.pageTitle ?? "", html_content: e.htmlContent ?? "" } : void 0);
7295
+ this.isCurrent(s) && p === this.promptRevision && a === this.options.pageUrl() && this.receive({ type: "starterPrompts.updated", ...g });
7270
7296
  return;
7271
7297
  }
7272
7298
  if (n === "session.load") {
@@ -7615,7 +7641,14 @@ function qe(t, e, s) {
7615
7641
  const i = [];
7616
7642
  if (e.type === "directory.authority_replace") {
7617
7643
  if (e.expectedGeneration !== t.generation || e.generation <= t.generation) return { state: t, effects: i };
7618
- n = { ...ar(), authorityId: e.authorityId, generation: e.generation };
7644
+ const r = e.adoptLocalSubmissions && !t.authorityId ? Object.fromEntries(Object.entries(t.clients).filter(([, a]) => t.selections[a]?.sessionId === null)) : {};
7645
+ n = {
7646
+ ...ar(),
7647
+ authorityId: e.authorityId,
7648
+ generation: e.generation,
7649
+ clients: r,
7650
+ selections: Object.fromEntries(Object.values(r).map((a) => [a, t.selections[a]]))
7651
+ };
7619
7652
  } else if (e.type === "effect.completed" || e.type === "effect.failed") {
7620
7653
  const r = t.requests[e.effectId];
7621
7654
  if (!r || r.kind !== e.effectKind) return { state: t, effects: i };
@@ -7635,8 +7668,8 @@ function qe(t, e, s) {
7635
7668
  v !== void 0 && p[h.conversation_id] === v && (delete u[h.conversation_id], delete p[h.conversation_id]);
7636
7669
  }
7637
7670
  n = { ...n, durableActivityBySessionId: l, activityBySessionId: u, activityRevisionBySessionId: p };
7638
- const f = Object.fromEntries(Object.entries(n.optimisticEntries).filter(([, h]) => h.sessionId === null || !d.includes(h.sessionId)));
7639
- n = { ...n, optimisticEntries: f };
7671
+ const g = Object.fromEntries(Object.entries(n.optimisticEntries).filter(([, h]) => h.sessionId === null || !d.includes(h.sessionId)));
7672
+ n = { ...n, optimisticEntries: g };
7640
7673
  const m = [.../* @__PURE__ */ new Set([...c.mode === "append" ? c.data ?? [] : [], ...d])];
7641
7674
  n = { ...n, queries: { ...n.queries, [o]: {
7642
7675
  ...c,
@@ -7664,7 +7697,7 @@ function qe(t, e, s) {
7664
7697
  n = { ...n, mutations: { ...n.mutations, [r.input.sessionId]: o } };
7665
7698
  }
7666
7699
  } else {
7667
- if (e.authorityId !== t.authorityId || e.generation !== t.generation)
7700
+ if (e.authorityId !== (t.authorityId ?? "") || e.generation !== t.generation)
7668
7701
  return { state: t, effects: i };
7669
7702
  if (e.type === "directory.metadata_received")
7670
7703
  n = ps(t, e.metadata, !0);
@@ -7702,6 +7735,7 @@ function qe(t, e, s) {
7702
7735
  activityRevision: t.activityRevision + 1
7703
7736
  };
7704
7737
  else if (e.type === "directory.query" || e.type === "directory.mutate") {
7738
+ if (!t.authorityId) return { state: t, effects: i };
7705
7739
  if (Object.values(t.requests).some((c) => c.input.requestId === e.requestId))
7706
7740
  throw new Error("Directory request ID is already in flight.");
7707
7741
  const r = `${t.generation}:${t.requestSequence + 1}`, a = { authorityId: e.authorityId, generation: e.generation, requestId: e.requestId };
@@ -8069,51 +8103,51 @@ class pc {
8069
8103
  return { state: d.state === r.slices.activeUsers ? r : Object.freeze({ revision: r.revision + 1, slices: Object.freeze({ ...r.slices, activeUsers: d.state }) }), effects: d.effects };
8070
8104
  }
8071
8105
  if (cc(o)) {
8072
- const d = qe(r.slices.directory, o, r.slices.conversation), l = Ws(Hs(r.slices.conversation, d.state)), u = Vs(r.slices.conversation, l.state, d.state, d.state.clients !== r.slices.directory.clients), p = u.state, f = pi(r.slices.conversation, p, d.state);
8073
- return { state: f === r.slices.directory && p === r.slices.conversation ? r : Object.freeze({
8106
+ const d = qe(r.slices.directory, o, r.slices.conversation), l = Ws(Hs(r.slices.conversation, d.state, o.type === "directory.authority_replace" && o.adoptLocalSubmissions === !0)), u = Vs(r.slices.conversation, l.state, d.state, d.state.clients !== r.slices.directory.clients), p = u.state, g = pi(r.slices.conversation, p, d.state);
8107
+ return { state: g === r.slices.directory && p === r.slices.conversation ? r : Object.freeze({
8074
8108
  revision: r.revision + 1,
8075
- slices: Object.freeze({ ...r.slices, directory: f, conversation: p })
8109
+ slices: Object.freeze({ ...r.slices, directory: g, conversation: p })
8076
8110
  }), effects: [...u.effects, ...d.effects, ...l.effects] };
8077
8111
  }
8078
8112
  if (dc(o)) {
8079
8113
  const d = ho(r.slices.conversation, o, r.slices.directory, r.slices.modelSelection);
8080
8114
  let l = r.slices.directory;
8081
- for (const [S, k] of Object.entries(d.state.operations)) {
8082
- if (!["runtime.warmup", "attachment.prepare"].includes(k.command.type) || !k.conversationScopeId || k.phase !== "done" || r.slices.conversation.operations[S]?.phase === "done") continue;
8083
- const g = k.result, y = l.selections[k.conversationScopeId];
8084
- g?.sessionId && y?.provisionalId && y.sessionId === null && Object.values(l.clients).includes(k.conversationScopeId) && (l = qe(l, {
8115
+ for (const [k, w] of Object.entries(d.state.operations)) {
8116
+ if (!["runtime.warmup", "attachment.prepare"].includes(w.command.type) || !w.conversationScopeId || w.phase !== "done" || r.slices.conversation.operations[k]?.phase === "done") continue;
8117
+ const f = w.result, y = l.selections[w.conversationScopeId];
8118
+ f?.sessionId && y?.provisionalId && y.sessionId === null && Object.values(l.clients).includes(w.conversationScopeId) && (l = qe(l, {
8085
8119
  authorityId: d.state.authorityId,
8086
8120
  generation: d.state.generation,
8087
8121
  type: "directory.accepted",
8088
- conversationScopeId: k.conversationScopeId,
8122
+ conversationScopeId: w.conversationScopeId,
8089
8123
  provisionalId: y.provisionalId,
8090
- sessionId: g.sessionId
8124
+ sessionId: f.sessionId
8091
8125
  }).state);
8092
8126
  }
8093
- const u = Object.values(d.state.submissions).find((S) => S.delivery === "accepted" && r.slices.conversation.submissions[S.userMessageId]?.delivery !== "accepted");
8127
+ const u = Object.values(d.state.submissions).find((k) => k.delivery === "accepted" && r.slices.conversation.submissions[k.userMessageId]?.delivery !== "accepted");
8094
8128
  if (u) {
8095
- const S = l.selections[u.conversationScopeId];
8096
- !u.cancelled && S?.provisionalId && (l = qe(l, {
8129
+ const k = l.selections[u.conversationScopeId];
8130
+ !u.cancelled && k?.provisionalId && (l = qe(l, {
8097
8131
  type: "directory.accepted",
8098
8132
  authorityId: d.state.authorityId,
8099
8133
  generation: d.state.generation,
8100
8134
  conversationScopeId: u.conversationScopeId,
8101
- provisionalId: S.provisionalId,
8135
+ provisionalId: k.provisionalId,
8102
8136
  sessionId: u.sessionId
8103
8137
  }).state);
8104
8138
  }
8105
8139
  l = pi(r.slices.conversation, d.state, l);
8106
- const p = Ws(Hs(d.state, l)), f = Vs(d.state, p.state, l);
8140
+ const p = Ws(Hs(d.state, l)), g = Vs(d.state, p.state, l);
8107
8141
  let m = r.slices;
8108
- const h = [], v = d.interactionSources, b = m.account.authority;
8109
- if (v && b && b.authorityId === v.authorityId && b.generation === v.generation) {
8110
- const S = js(m, { type: "stage7.sources", authority: b, now: m.features.now, sources: v.sources }, { conversation: f.state, directory: l });
8111
- m = G(X({ account: S.state.account, features: S.state.features, interactions: S.state.interactions })), h.push(...S.effects);
8142
+ const h = [], v = d.interactionSources, I = m.account.authority;
8143
+ if (v && I && I.authorityId === v.authorityId && I.generation === v.generation) {
8144
+ const k = js(m, { type: "stage7.sources", authority: I, now: m.features.now, sources: v.sources }, { conversation: g.state, directory: l });
8145
+ m = G(X({ account: k.state.account, features: k.state.features, interactions: k.state.interactions })), h.push(...k.effects);
8112
8146
  }
8113
- return { state: f.state === r.slices.conversation && l === r.slices.directory && m === r.slices ? r : Object.freeze({
8147
+ return { state: g.state === r.slices.conversation && l === r.slices.directory && m === r.slices ? r : Object.freeze({
8114
8148
  revision: r.revision + 1,
8115
- slices: Object.freeze({ ...r.slices, account: m.account, features: m.features, interactions: m.interactions, directory: l, conversation: f.state })
8116
- }), effects: [...d.effects, ...h, ...f.effects, ...p.effects] };
8149
+ slices: Object.freeze({ ...r.slices, account: m.account, features: m.features, interactions: m.interactions, directory: l, conversation: g.state })
8150
+ }), effects: [...d.effects, ...h, ...g.effects, ...p.effects] };
8117
8151
  }
8118
8152
  const c = tc(r.slices.modelSelection, o);
8119
8153
  return { state: c === r.slices.modelSelection ? r : Object.freeze({
@@ -8420,9 +8454,9 @@ function Cc() {
8420
8454
  close: () => t.close()
8421
8455
  };
8422
8456
  }
8423
- return xc();
8457
+ return Oc();
8424
8458
  }
8425
- function xc() {
8459
+ function Oc() {
8426
8460
  const t = /* @__PURE__ */ new Set(), e = (s) => {
8427
8461
  if (s.key !== fs || !s.newValue)
8428
8462
  return;
@@ -8444,7 +8478,7 @@ function xc() {
8444
8478
  };
8445
8479
  }
8446
8480
  const mr = "schedule_follow_up";
8447
- function Oc(t) {
8481
+ function xc(t) {
8448
8482
  let e = t;
8449
8483
  if (typeof e == "string")
8450
8484
  try {
@@ -9043,7 +9077,7 @@ class iu {
9043
9077
  getState() {
9044
9078
  const e = Is(this.state);
9045
9079
  for (const [i, r] of this.submissionPreviews)
9046
- e.messages.some((a) => a.id === i) || (e.messages.push({ ...r.message, attachments: r.message.attachments?.map((a) => ({ ...a })) }), e.segments && (e.segments = [...e.segments, { id: i, userMessageId: i, activityIds: [], outcomeIds: [], collapsed: !1 }]), e.isLoadingSession = !1, r.pending && (e.activeResponseUserMessageId = i, e.pendingMessageStatus = "sending", e.turnPhase = "sending", e.activity = { phase: "submitting", activeItemId: null }), r.error && (e.lastError = r.error, e.lastErrorCode = "message_delivery_failed"));
9080
+ e.messages.some((a) => a.id === i) || (e.messages.push({ ...r.message, attachments: r.message.attachments?.map((a) => ({ ...a })) }), e.segments && (e.segments = [...e.segments, { id: i, userMessageId: i, activityIds: [], outcomeIds: [], collapsed: !1 }]), e.isLoadingSession = !1, r.pending && (e.activeResponseUserMessageId = i, e.pendingMessageStatus = "sending", e.turnPhase = "sending", e.activity = { phase: "submitting", activeItemId: null }), r.error && (e.lastError = r.error.message, e.lastErrorCode = ["unauthorized", "401", "auth_reconnecting", "submission_not_available"].includes(r.error.code) ? r.error.code : "message_delivery_failed"));
9047
9081
  this.stopError && (e.lastError = this.stopError, e.lastErrorCode = "stop_failed");
9048
9082
  const s = [...this.stopPreviews.keys()];
9049
9083
  if (!s.length) return e;
@@ -9218,7 +9252,7 @@ class iu {
9218
9252
  for (const u of s.attachments ?? [])
9219
9253
  u.id && this.attachmentFiles.delete(u.id);
9220
9254
  const l = this.submissionPreviews.get(r);
9221
- throw l && (l.pending = !1, l.error = Y(d).message, l.retry = !c && Y(d).code === "command_not_received" ? () => this.sendMessageNow(e, s, n) : void 0, this.emit("state", this.getState())), c && await this.adapter.dispatch({
9255
+ throw l && (l.pending = !1, l.error = Y(d), l.retry = !c && Y(d).code === "command_not_received" ? () => this.sendMessageNow(e, s, n) : void 0, this.emit("state", this.getState())), c && await this.adapter.dispatch({
9222
9256
  type: "conversation.fail_staged",
9223
9257
  clientMessageId: r,
9224
9258
  message: Y(d).message
@@ -9242,7 +9276,7 @@ class iu {
9242
9276
  return n && i ? (n.pending = !0, n.error = void 0, n.retry = void 0, this.pendingTransfers.set(s, (n.message.attachments ?? []).flatMap((a) => a.id ? [a.id] : [])), this.emit("state", this.getState()), await i()) : await this.dispatch({ type: "run.retry", clientMessageId: s }), !0;
9243
9277
  } catch (a) {
9244
9278
  if (!n) throw a;
9245
- return r === this.submissionGeneration && this.submissionPreviews.get(s) === n && (n.error = Y(a).message, this.emit("state", this.getState())), !1;
9279
+ return r === this.submissionGeneration && this.submissionPreviews.get(s) === n && (n.error = Y(a), this.emit("state", this.getState())), !1;
9246
9280
  } finally {
9247
9281
  i && this.pendingTransfers.delete(s), n && r === this.submissionGeneration && this.submissionPreviews.get(s) === n && (n.pending = !1, this.emit("state", this.getState()));
9248
9282
  }
@@ -9523,7 +9557,7 @@ function ws(t) {
9523
9557
  }
9524
9558
  return { ...e, ...Eo(t) };
9525
9559
  }
9526
- function Oe(t, e, s) {
9560
+ function xe(t, e, s) {
9527
9561
  if (typeof window > "u")
9528
9562
  return;
9529
9563
  const n = window.__PLUNO_PRODUCT_AGENT_TRACE_ID__;
@@ -9831,51 +9865,51 @@ class Ht {
9831
9865
  http: this.directoryHttp,
9832
9866
  now: () => Date.now(),
9833
9867
  prepareSubmission: async ({ submission: h, sources: v }) => {
9834
- const b = te(this.operationTimingReporter, {
9868
+ const I = te(this.operationTimingReporter, {
9835
9869
  operation: "send",
9836
9870
  layer: "sdk",
9837
9871
  requestId: h.requestId,
9838
9872
  clientMessageId: h.userMessageId,
9839
9873
  sessionId: h.sessionId
9840
9874
  });
9841
- let S = h.contextPreparation ?? { pageContent: "", sessionTabs: [] };
9875
+ let k = h.contextPreparation ?? { pageContent: "", sessionTabs: [] };
9842
9876
  if (h.contextPreparation === null) {
9843
- await b.measure("first_frame", () => new Promise((g) => {
9877
+ await I.measure("first_frame", () => new Promise((f) => {
9844
9878
  if (document.visibilityState !== "visible") {
9845
- setTimeout(g, 0);
9879
+ setTimeout(f, 0);
9846
9880
  return;
9847
9881
  }
9848
9882
  const y = () => {
9849
- cancelAnimationFrame(w), document.removeEventListener("visibilitychange", I), setTimeout(g, 0);
9850
- }, I = () => {
9883
+ cancelAnimationFrame(_), document.removeEventListener("visibilitychange", b), setTimeout(f, 0);
9884
+ }, b = () => {
9851
9885
  document.visibilityState !== "visible" && y();
9852
- }, w = requestAnimationFrame(y);
9853
- document.addEventListener("visibilitychange", I);
9886
+ }, _ = requestAnimationFrame(y);
9887
+ document.addEventListener("visibilitychange", b);
9854
9888
  }));
9855
- const k = h.context.page;
9856
- if (oe().url !== k.url) throw Object.assign(new Error("The page changed before preparation completed. Send this message again."), { code: "context_preparation_interrupted", retryable: !1 });
9857
- S = { pageContent: await b.measure("page_capture", async () => Rn()), sessionTabs: [] };
9889
+ const w = h.context.page;
9890
+ if (oe().url !== w.url) throw Object.assign(new Error("The page changed before preparation completed. Send this message again."), { code: "context_preparation_interrupted", retryable: !1 });
9891
+ k = { pageContent: await I.measure("page_capture", async () => Rn()), sessionTabs: [] };
9858
9892
  }
9859
- if (await b.measure("authentication", () => this.waitForAuthentication()), !n() || s !== this.directoryAuthority || this.clientRuntime.isDisposed) throw new Error("Submission authority was retired.");
9860
- for (const k of v)
9861
- if (!k.uploaded && (await this.attachmentPersistence.get(k.sourceId)?.catch(() => {
9893
+ if (await I.measure("authentication", () => this.waitForAuthentication()), !n() || s !== this.directoryAuthority || this.clientRuntime.isDisposed) throw new Error("Submission authority was retired.");
9894
+ for (const w of v)
9895
+ if (!w.uploaded && (await this.attachmentPersistence.get(w.sourceId)?.catch(() => {
9862
9896
  throw Object.assign(new Error("Attachment files could not be stored. Attach the files again and send a new message."), { code: "attachment_source_unavailable", retryable: !1 });
9863
- }), !await hi(k.sourceId)))
9897
+ }), !await hi(w.sourceId)))
9864
9898
  throw Object.assign(new Error("Attachment files are unavailable. Attach the files again and send a new message."), { code: "attachment_source_unavailable", retryable: !1 });
9865
- return b.mark("context_ready"), { ...S, now: Date.now() };
9899
+ return I.mark("context_ready"), { ...k, now: Date.now() };
9866
9900
  },
9867
9901
  connectionId: () => this.socket instanceof L ? this.socket.connectionId : null,
9868
9902
  prepareUpload: this.options.prepareAttachmentUpload ?? (this.options.productVariant === "customer_embedded" ? (h) => this.prepareEmbedAttachmentUpload(h, n) : void 0),
9869
- onUploaded: async (h, v, b) => {
9903
+ onUploaded: async (h, v, I) => {
9870
9904
  await ur(h, {
9871
9905
  sessionId: v,
9872
- sandboxPath: b.sandbox_path ?? void 0,
9873
- storageKey: b.storage_key ?? void 0,
9874
- fileUrl: b.file_url ? new URL(b.file_url, this.options.backendUrl).toString() : void 0,
9906
+ sandboxPath: I.sandbox_path ?? void 0,
9907
+ storageKey: I.storage_key ?? void 0,
9908
+ fileUrl: I.file_url ? new URL(I.file_url, this.options.backendUrl).toString() : void 0,
9875
9909
  lastUsedAt: Date.now()
9876
- }).catch((S) => V("web-sdk.attachments", "Failed to update persisted Product Agent attachment", {
9910
+ }).catch((k) => V("web-sdk.attachments", "Failed to update persisted Product Agent attachment", {
9877
9911
  attachmentId: h,
9878
- message: S instanceof Error ? S.message : String(S)
9912
+ message: k instanceof Error ? k.message : String(k)
9879
9913
  }));
9880
9914
  },
9881
9915
  persistUpload: this.options.persistAttachmentUpload,
@@ -9892,7 +9926,7 @@ class Ht {
9892
9926
  onTiming: (h) => {
9893
9927
  n() && this.reportOperationTiming(h);
9894
9928
  },
9895
- onCommand: (h) => Oe("client_event", h.type, ws({ ...h.payload, type: h.type })),
9929
+ onCommand: (h) => xe("client_event", h.type, ws({ ...h.payload, type: h.type })),
9896
9930
  onError: (h, v) => {
9897
9931
  if (this.options.productVariant === "customer_embedded" && v.operation === "conversation.snapshot" && h instanceof A && h.code === "conversation_access_denied") {
9898
9932
  v.sessionId === this.getState().sessionId && this.startNewSession({ notifyTransport: !1 });
@@ -9904,23 +9938,23 @@ class Ht {
9904
9938
  });
9905
9939
  const c = this.clientRuntime.engine.getState().slices.conversation, d = this.options.restorePersistedState === !1 || !this.authenticatedUserId ? null : os(i);
9906
9940
  if (this.authenticatedUserId && !c.submissionOrder.length && !Object.keys(c.operations).length) {
9907
- const h = this.queuedClientEvents.filter((S) => S.type === "chat.user_message"), v = d ? JSON.parse(d) : h.length ? xo(c, h.map((S) => {
9908
- const { type: k, ...g } = S, y = this.clientRuntime.engine.getState().slices.directory, I = y.clients[this.modelClientScopeId];
9941
+ const h = this.queuedClientEvents.filter((k) => k.type === "chat.user_message"), v = d ? JSON.parse(d) : h.length ? Oo(c, h.map((k) => {
9942
+ const { type: w, ...f } = k, y = this.clientRuntime.engine.getState().slices.directory, b = y.clients[this.modelClientScopeId];
9909
9943
  return {
9910
- command: { type: k, request_id: S.clientMessageId, payload: JSON.parse(JSON.stringify(g)) },
9911
- requestedModel: S.model ?? null,
9944
+ command: { type: w, request_id: k.clientMessageId, payload: JSON.parse(JSON.stringify(f)) },
9945
+ requestedModel: k.model ?? null,
9912
9946
  clientScopeId: this.modelClientScopeId,
9913
- conversationScopeId: I,
9947
+ conversationScopeId: b,
9914
9948
  viewId: `sdk:${this.modelClientScopeId}`,
9915
- sessionId: S.sessionId ?? y.selections[I]?.sessionId ?? null,
9949
+ sessionId: k.sessionId ?? y.selections[b]?.sessionId ?? null,
9916
9950
  entrySurface: this.options.entrySurface,
9917
9951
  submittedAt: Date.now()
9918
9952
  };
9919
- })) : null, b = this.options.restorePersistedState === !1 || !a ? v : await o.restore(
9953
+ })) : null, I = this.options.restorePersistedState === !1 || !a ? v : await o.restore(
9920
9954
  v ?? ln(c, this.clientRuntime.engine.getState().slices.directory)
9921
9955
  );
9922
9956
  if (!n()) return;
9923
- b && (v || Object.keys(b.operations).length || Object.keys(b.stops).length) && await this.clientRuntime.engine.dispatch({ ...s, type: "conversation.restore_delivery", checkpoint: b });
9957
+ I && (v || Object.keys(I.operations).length || Object.keys(I.stops).length) && await this.clientRuntime.engine.dispatch({ ...s, type: "conversation.restore_delivery", checkpoint: I });
9924
9958
  }
9925
9959
  if (this.authenticatedUserId && (this.queuedClientEvents = this.queuedClientEvents.filter((h) => !["chat.user_message", "chat.retry_last_user_message", "run.stop", "runtime.warmup", "session.reset", "attachment.upload_completed"].includes(h.type))), Re(this.options.clientId, this.queuedClientEvents), !n()) return;
9926
9960
  this.conversationObservation = new Po({
@@ -9931,15 +9965,15 @@ class Ht {
9931
9965
  enabled: () => !!this.token && !this.authenticationFailure && !this.refreshingDefaultCredentials && this.state.status !== "closed",
9932
9966
  socket: {
9933
9967
  retain: async (h, v) => {
9934
- const b = this.socket;
9935
- b instanceof L && await b.directoryRooms.retain(h, v).catch((S) => {
9936
- if (this.socket === b) throw S;
9968
+ const I = this.socket;
9969
+ I instanceof L && await I.directoryRooms.retain(h, v).catch((k) => {
9970
+ if (this.socket === I) throw k;
9937
9971
  });
9938
9972
  },
9939
9973
  release: async (h, v) => {
9940
- const b = this.socket;
9941
- b instanceof L && await b.directoryRooms.release(h, v).catch((S) => {
9942
- if (this.socket === b) throw S;
9974
+ const I = this.socket;
9975
+ I instanceof L && await I.directoryRooms.release(h, v).catch((k) => {
9976
+ if (this.socket === I) throw k;
9943
9977
  });
9944
9978
  }
9945
9979
  },
@@ -9951,50 +9985,50 @@ class Ht {
9951
9985
  });
9952
9986
  const l = (h, v) => {
9953
9987
  if (this.firstResponseTimersByClientMessageId.size) {
9954
- for (const b of h)
9955
- (b.dataType === "run_status" || b.dataType === "run_error") && this.clearFirstResponseTimer(b.respondsToUserMessageId ?? null);
9956
- for (const b of h)
9957
- if (b.content.trim() && (b.role === "assistant" || b.dataType === "commentary_history" || b.dataType === "tool_summary")) {
9958
- const S = v ? this.clientRuntime.engine.getState().slices.conversation.sessions[v] : void 0;
9959
- for (const k of b.respondsToUserMessageId ? $r(S, b.respondsToUserMessageId) : [])
9960
- this.clearFirstResponseTimer(k, !0, v);
9988
+ for (const I of h)
9989
+ (I.dataType === "run_status" || I.dataType === "run_error") && this.clearFirstResponseTimer(I.respondsToUserMessageId ?? null);
9990
+ for (const I of h)
9991
+ if (I.content.trim() && (I.role === "assistant" || I.dataType === "commentary_history" || I.dataType === "tool_summary")) {
9992
+ const k = v ? this.clientRuntime.engine.getState().slices.conversation.sessions[v] : void 0;
9993
+ for (const w of I.respondsToUserMessageId ? $r(k, I.respondsToUserMessageId) : [])
9994
+ this.clearFirstResponseTimer(w, !0, v);
9961
9995
  }
9962
9996
  }
9963
9997
  };
9964
- let u = new Map(this.getState().messages.map((h) => [h.id, h])), p = this.clientRuntime.engine.getState().slices.conversation, f = this.clientRuntime.engine.getState().slices.directory.selections, m = this.clientRuntime.engine.getState().slices.directory.clients[this.modelClientScopeId];
9998
+ let u = new Map(this.getState().messages.map((h) => [h.id, h])), p = this.clientRuntime.engine.getState().slices.conversation, g = this.clientRuntime.engine.getState().slices.directory.selections, m = this.clientRuntime.engine.getState().slices.directory.clients[this.modelClientScopeId];
9965
9999
  this.conversationUnsubscribe = this.clientRuntime.engine.subscribe(() => {
9966
10000
  const h = this.clientRuntime.engine.getState().slices, v = p;
9967
10001
  p = h.conversation, Io(v, h.conversation, this.operationTimingReporter, "sdk");
9968
- const b = m !== h.directory.clients[this.modelClientScopeId];
9969
- m = h.directory.clients[this.modelClientScopeId], f !== h.directory.selections && (f = h.directory.selections, this.directoryScope.persist());
9970
- for (const k of Object.values(h.conversation.submissions)) {
9971
- if (k.delivery === "accepted" && v.submissions[k.userMessageId]?.delivery !== "accepted") {
9972
- const g = this.firstResponseTimersByClientMessageId.get(k.userMessageId);
9973
- g && (g.sessionId = k.sessionId), this.emit("ack", { clientMessageId: k.userMessageId, sessionId: k.sessionId });
9974
- const y = k.sessionId;
9975
- y && this.getState().sessionId === y && this.directoryHttp.request(`/sessions/${encodeURIComponent(y)}/history`, { limit: 200 }).then((I) => {
9976
- n() && this.getState().sessionId === y && this.state.status !== "closed" && vs(this.clientRuntime, this.modelClientScopeId, y, I.turns);
9977
- }).catch((I) => {
9978
- n() && this.getState().sessionId === y && this.handleDirectoryTransportError(I);
10002
+ const I = m !== h.directory.clients[this.modelClientScopeId];
10003
+ m = h.directory.clients[this.modelClientScopeId], g !== h.directory.selections && (g = h.directory.selections, this.directoryScope.persist());
10004
+ for (const w of Object.values(h.conversation.submissions)) {
10005
+ if (w.delivery === "accepted" && v.submissions[w.userMessageId]?.delivery !== "accepted") {
10006
+ const f = this.firstResponseTimersByClientMessageId.get(w.userMessageId);
10007
+ f && (f.sessionId = w.sessionId), this.emit("ack", { clientMessageId: w.userMessageId, sessionId: w.sessionId });
10008
+ const y = w.sessionId;
10009
+ y && this.getState().sessionId === y && this.directoryHttp.request(`/sessions/${encodeURIComponent(y)}/history`, { limit: 200 }).then((b) => {
10010
+ n() && this.getState().sessionId === y && this.state.status !== "closed" && vs(this.clientRuntime, this.modelClientScopeId, y, b.turns);
10011
+ }).catch((b) => {
10012
+ n() && this.getState().sessionId === y && this.handleDirectoryTransportError(b);
9979
10013
  });
9980
10014
  }
9981
- (k.cancelled || k.delivery === "failed") && this.clearFirstResponseTimer(k.userMessageId);
9982
- }
9983
- for (const [k, g] of Object.entries(h.directory.clients)) {
9984
- if (!k.startsWith(`background:${this.modelClientScopeId}:`)) continue;
9985
- const y = Ie(h.conversation, h.directory, g), I = y.sessionId ? h.conversation.sessions[y.sessionId] : void 0;
9986
- if (this.firstResponseTimersByClientMessageId.size && (l(as(y, I?.queries.current, this.options.backendUrl).messages, y.sessionId), ["failed", "stopped"].includes(y.activity.phase)))
9987
- for (const R of de(I?.execution)) this.clearFirstResponseTimer(R);
9988
- const w = y.activity.phase === "completed" && de(I?.execution).some((R) => this.firstResponseTimersByClientMessageId.has(R));
9989
- (b && y.sessionId === this.getState().sessionId || !w && ["completed", "failed", "stopped"].includes(y.activity.phase)) && this.directoryScope.detach(k);
9990
- }
9991
- const S = this.getState();
9992
- l(S.messages, S.sessionId);
9993
- for (const k of S.messages) {
9994
- const g = u.get(k.id);
9995
- (!g || g.content !== k.content || g.loading !== k.loading) && this.emit("message", k), k.content.trim() && k.content !== g?.content && (k.role === "assistant" || k.dataType === "commentary_history") && k.content.startsWith(g?.content ?? "") && this.emit("delta", k.content.slice(g?.content.length ?? 0));
9996
- }
9997
- u = new Map(S.messages.map((k) => [k.id, k])), this.rebuildRuntimeInteractions(), this.emit("state", S);
10015
+ (w.cancelled || w.delivery === "failed") && this.clearFirstResponseTimer(w.userMessageId);
10016
+ }
10017
+ for (const [w, f] of Object.entries(h.directory.clients)) {
10018
+ if (!w.startsWith(`background:${this.modelClientScopeId}:`)) continue;
10019
+ const y = Ie(h.conversation, h.directory, f), b = y.sessionId ? h.conversation.sessions[y.sessionId] : void 0;
10020
+ if (this.firstResponseTimersByClientMessageId.size && (l(as(y, b?.queries.current, this.options.backendUrl).messages, y.sessionId), ["failed", "stopped"].includes(y.activity.phase)))
10021
+ for (const R of de(b?.execution)) this.clearFirstResponseTimer(R);
10022
+ const _ = y.activity.phase === "completed" && de(b?.execution).some((R) => this.firstResponseTimersByClientMessageId.has(R));
10023
+ (I && y.sessionId === this.getState().sessionId || !_ && ["completed", "failed", "stopped"].includes(y.activity.phase)) && this.directoryScope.detach(w);
10024
+ }
10025
+ const k = this.getState();
10026
+ l(k.messages, k.sessionId);
10027
+ for (const w of k.messages) {
10028
+ const f = u.get(w.id);
10029
+ (!f || f.content !== w.content || f.loading !== w.loading) && this.emit("message", w), w.content.trim() && w.content !== f?.content && (w.role === "assistant" || w.dataType === "commentary_history") && w.content.startsWith(f?.content ?? "") && this.emit("delta", w.content.slice(f?.content.length ?? 0));
10030
+ }
10031
+ u = new Map(k.messages.map((w) => [w.id, w])), this.rebuildRuntimeInteractions(), this.emit("state", k);
9998
10032
  }), this.conversationObservation.wake();
9999
10033
  }
10000
10034
  async initializeDirectory() {
@@ -10016,7 +10050,7 @@ class Ht {
10016
10050
  }
10017
10051
  }
10018
10052
  handleDirectoryTransportError(e) {
10019
- if (!(e instanceof A) || this.authenticationFailure || !["unauthorized", "update_required", "service_origin_not_allowed", "security_control_enforcement_unavailable"].includes(e.code) && xt(void 0, e.code).allowed) return;
10053
+ if (!(e instanceof A) || this.authenticationFailure || !["unauthorized", "update_required", "service_origin_not_allowed", "security_control_enforcement_unavailable"].includes(e.code) && Ot(void 0, e.code).allowed) return;
10020
10054
  const s = e.detail && typeof e.detail == "object" ? e.detail : {};
10021
10055
  this.handleServerEvent({
10022
10056
  ...s,
@@ -10354,7 +10388,7 @@ class Ht {
10354
10388
  if (this.clientRuntime.isDisposed) return null;
10355
10389
  const n = e.trim(), i = s.attachments ?? [];
10356
10390
  if (!n && !i.length) return null;
10357
- if (this.options.productVariant === "customer_embedded" && (i.forEach(Tr), i.reduce((v, b) => v + b.sizeBytes, 0) > vr))
10391
+ if (this.options.productVariant === "customer_embedded" && (i.forEach(Tr), i.reduce((v, I) => v + I.sizeBytes, 0) > vr))
10358
10392
  throw new Error("Embedded attachments must total at most 50 MB per message");
10359
10393
  const r = s.clientMessageId ?? z(), a = te(this.operationTimingReporter, {
10360
10394
  operation: "send",
@@ -10407,20 +10441,20 @@ class Ht {
10407
10441
  submittedAt: s.submittedAt ?? Date.now()
10408
10442
  });
10409
10443
  const h = this.directoryAuthority;
10410
- return this.clientRuntime.isDisposed ? null : new Promise((v, b) => {
10411
- let S = null, k = null;
10412
- const g = () => {
10444
+ return this.clientRuntime.isDisposed ? null : new Promise((v, I) => {
10445
+ let k = null, w = null;
10446
+ const f = () => {
10413
10447
  const y = this.clientRuntime.engine.getState().slices.conversation.submissions[r];
10414
10448
  if (!(y && !y.cancelled && y.delivery !== "accepted" && y.delivery !== "failed"))
10415
- if (S?.(), k?.(), y?.delivery === "failed" && !y.cancelled) b(new Error(y.error?.message ?? "Message delivery failed."));
10449
+ if (k?.(), w?.(), y?.delivery === "failed" && !y.cancelled) I(new Error(y.error?.message ?? "Message delivery failed."));
10416
10450
  else {
10417
- const I = y?.invocation === "user" && y.contextPreparation?.pageContent ? y.context.page?.url : null;
10418
- y?.delivery === "accepted" && !y.cancelled && typeof I == "string" && c === this.submissionIntentRevision && h === this.directoryAuthority && this.clientRuntime.engine.getState().slices.directory.clients[this.modelClientScopeId] === m && (this.lastUserMessagePageUrl = I), v(y?.delivery === "accepted" && !y.cancelled ? r : null);
10451
+ const b = y?.invocation === "user" && y.contextPreparation?.pageContent ? y.context.page?.url : null;
10452
+ y?.delivery === "accepted" && !y.cancelled && typeof b == "string" && c === this.submissionIntentRevision && h === this.directoryAuthority && this.clientRuntime.engine.getState().slices.directory.clients[this.modelClientScopeId] === m && (this.lastUserMessagePageUrl = b), v(y?.delivery === "accepted" && !y.cancelled ? r : null);
10419
10453
  }
10420
10454
  };
10421
- S = this.clientRuntime.engine.subscribe(g), k = this.clientRuntime.onDispose(() => {
10422
- S?.(), v(null);
10423
- }), g();
10455
+ k = this.clientRuntime.engine.subscribe(f), w = this.clientRuntime.onDispose(() => {
10456
+ k?.(), v(null);
10457
+ }), f();
10424
10458
  });
10425
10459
  }
10426
10460
  reportResponseVisibility(e) {
@@ -10518,27 +10552,27 @@ class Ht {
10518
10552
  } }
10519
10553
  }), new Promise((d, l) => {
10520
10554
  let u, p;
10521
- const f = () => {
10555
+ const g = () => {
10522
10556
  const m = this.clientRuntime.engine.getState().slices, h = m.conversation.operations[c], v = m.directory.authorityId !== a.authorityId || m.directory.clients[this.modelClientScopeId] !== o;
10523
10557
  if (!v && h && !["done", "failed"].includes(h.phase)) return;
10524
10558
  if (u?.(), p?.(), v || !h || h.phase === "failed") {
10525
10559
  l(new Error(h?.error?.message ?? "Attachment preparation was cancelled."));
10526
10560
  return;
10527
10561
  }
10528
- const S = h.result.attachment;
10562
+ const k = h.result.attachment;
10529
10563
  d(Ar({
10530
- id: S.id,
10531
- name: S.name,
10532
- mimeType: S.mime_type,
10533
- sizeBytes: S.size_bytes,
10534
- storageKey: S.storage_key,
10535
- sandboxPath: S.sandbox_path,
10536
- fileUrl: S.file_url
10564
+ id: k.id,
10565
+ name: k.name,
10566
+ mimeType: k.mime_type,
10567
+ sizeBytes: k.size_bytes,
10568
+ storageKey: k.storage_key,
10569
+ sandboxPath: k.sandbox_path,
10570
+ fileUrl: k.file_url
10537
10571
  }, this.options.backendUrl));
10538
10572
  };
10539
- u = this.clientRuntime.engine.subscribe(f), p = this.clientRuntime.onDispose(() => {
10573
+ u = this.clientRuntime.engine.subscribe(g), p = this.clientRuntime.onDispose(() => {
10540
10574
  u?.(), l(new Error("Product Agent was disposed."));
10541
- }), f();
10575
+ }), g();
10542
10576
  });
10543
10577
  }
10544
10578
  async prepareEmbedAttachmentUpload(e, s) {
@@ -10558,7 +10592,7 @@ class Ht {
10558
10592
  let a = !1;
10559
10593
  return Pl(async () => {
10560
10594
  let o = await r(!1);
10561
- if (i(), !o.ok && jl(o.status) && this.options.tokenProvider && !a && (a = !0, o = await r(!0), i()), !o.ok) throw new xr("Failed to prepare attachment upload", o.status);
10595
+ if (i(), !o.ok && jl(o.status) && this.options.tokenProvider && !a && (a = !0, o = await r(!0), i()), !o.ok) throw new Or("Failed to prepare attachment upload", o.status);
10562
10596
  return await o.json();
10563
10597
  }, "Failed to prepare attachment upload");
10564
10598
  }
@@ -10807,10 +10841,10 @@ class Ht {
10807
10841
  return;
10808
10842
  }
10809
10843
  s = !0;
10810
- const p = this.getState().sessionId, f = () => !this.clientRuntime.isDisposed && JSON.stringify(this.clientRuntime.engine.getState().slices.account.authority) === JSON.stringify(u) && this.getState().sessionId === p;
10844
+ const p = this.getState().sessionId, g = () => !this.clientRuntime.isDisposed && JSON.stringify(this.clientRuntime.engine.getState().slices.account.authority) === JSON.stringify(u) && this.getState().sessionId === p;
10811
10845
  Promise.all(["notifications", "tab_grouping"].map(async (m) => {
10812
10846
  const h = await l.getState(m, p);
10813
- if (f()) {
10847
+ if (g()) {
10814
10848
  if (!h.bridgeReady) return h;
10815
10849
  if (await this.clientRuntime.engine.dispatch({
10816
10850
  type: "stage7.device_fact",
@@ -10823,7 +10857,7 @@ class Ht {
10823
10857
  return h;
10824
10858
  }
10825
10859
  })).then(async (m) => {
10826
- f() && await this.clientRuntime.engine.dispatch({
10860
+ g() && await this.clientRuntime.engine.dispatch({
10827
10861
  type: "stage7.bridge_ready",
10828
10862
  authority: u,
10829
10863
  now: Date.now(),
@@ -10831,7 +10865,7 @@ class Ht {
10831
10865
  error: m.find((h) => h?.error)?.error ?? null
10832
10866
  });
10833
10867
  }).catch(async () => {
10834
- f() && await this.clientRuntime.engine.dispatch({ type: "stage7.bridge_ready", authority: u, now: Date.now(), ready: !1, error: "The Pluno extension could not reconnect. Try again." });
10868
+ g() && await this.clientRuntime.engine.dispatch({ type: "stage7.bridge_ready", authority: u, now: Date.now(), ready: !1, error: "The Pluno extension could not reconnect. Try again." });
10835
10869
  }).finally(() => {
10836
10870
  s = !1, n && (n = !1, i());
10837
10871
  });
@@ -10861,16 +10895,16 @@ class Ht {
10861
10895
  ...r,
10862
10896
  "stage7.wait": e.wait,
10863
10897
  "stage7.device": async ({ feature: l, action: u, requestId: p }) => {
10864
- const f = this.options.runtimeAdapters?.featurePermissions;
10865
- if (!f) return { fact: { permission: "unsupported", revision: Date.now(), snoozedUntil: null }, completedAt: Date.now() };
10898
+ const g = this.options.runtimeAdapters?.featurePermissions;
10899
+ if (!g) return { fact: { permission: "unsupported", revision: Date.now(), snoozedUntil: null }, completedAt: Date.now() };
10866
10900
  const m = this.clientRuntime.engine.getState().slices.interactions, h = m.promptActions[p], v = h?.expectedRevision ?? m.preferencePrompts[l].revision;
10867
- u === "allow" && await f.enable(l, { requestId: p, expectedRevision: v, action: h?.action === "enable" ? "enable" : "allow" }), u === "not_now" && await f.dismiss(l, { requestId: p, expectedRevision: v, action: "not_now" });
10868
- const b = await f.getState(l, this.getState().sessionId);
10869
- if (!b.bridgeReady) throw new Error("The Pluno extension is reconnecting. Try again.");
10901
+ u === "allow" && await g.enable(l, { requestId: p, expectedRevision: v, action: h?.action === "enable" ? "enable" : "allow" }), u === "not_now" && await g.dismiss(l, { requestId: p, expectedRevision: v, action: "not_now" });
10902
+ const I = await g.getState(l, this.getState().sessionId);
10903
+ if (!I.bridgeReady) throw new Error("The Pluno extension is reconnecting. Try again.");
10870
10904
  return { fact: {
10871
- permission: b.permissionGranted === !0 ? "granted" : b.permissionNeeded ? "missing" : "unknown",
10905
+ permission: I.permissionGranted === !0 ? "granted" : I.permissionNeeded ? "missing" : "unknown",
10872
10906
  revision: Math.max(Date.now(), this.clientRuntime.engine.getState().slices.interactions.deviceFacts[l].revision + 1),
10873
- snoozedUntil: b.snoozedUntil ?? null
10907
+ snoozedUntil: I.snoozedUntil ?? null
10874
10908
  }, completedAt: Date.now() };
10875
10909
  },
10876
10910
  "stage7.platform": async (l) => {
@@ -10878,15 +10912,15 @@ class Ht {
10878
10912
  if (u.kind === "saveHint")
10879
10913
  Br(localStorage, u.interactionId);
10880
10914
  else if (u.kind === "connect" && p?.payload.kind === "integration_auth") {
10881
- const f = p.payload;
10915
+ const g = p.payload;
10882
10916
  if (!this.options.runtimeAdapters?.integrationAuthHandler) throw new Error("Connection handler unavailable.");
10883
10917
  await this.options.runtimeAdapters.integrationAuthHandler({
10884
10918
  type: "pipedream_auth_required",
10885
- authRequestId: f.request_id,
10886
- appSlug: f.app_slug,
10887
- appName: f.app_name,
10888
- appLogo: f.app_logo,
10889
- expiresAt: f.expires_at
10919
+ authRequestId: g.request_id,
10920
+ appSlug: g.app_slug,
10921
+ appName: g.app_name,
10922
+ appLogo: g.app_logo,
10923
+ expiresAt: g.expires_at
10890
10924
  });
10891
10925
  } else if (u.kind === "pair") {
10892
10926
  if (!this.options.runtimeAdapters?.personalChannelConnectionHandler) throw new Error("Pairing handler unavailable.");
@@ -10904,13 +10938,13 @@ class Ht {
10904
10938
  let a = "";
10905
10939
  const o = this.clientRuntime.engine.subscribe(() => {
10906
10940
  this.rebuildRuntimeInteractions();
10907
- const l = this.clientRuntime.engine.getState().slices, p = l.directory.selections[l.directory.clients[this.modelClientScopeId]]?.sessionId, f = JSON.stringify([p, p ? l.conversation.sessions[p]?.execution : null]);
10908
- f !== a && (a = f, i());
10941
+ const l = this.clientRuntime.engine.getState().slices, p = l.directory.selections[l.directory.clients[this.modelClientScopeId]]?.sessionId, g = JSON.stringify([p, p ? l.conversation.sessions[p]?.execution : null]);
10942
+ g !== a && (a = g, i());
10909
10943
  }), c = this.options.runtimeAdapters?.featurePermissions?.subscribe?.(i);
10910
10944
  this.clientRuntime.onDispose(() => c?.()), eo(this.clientRuntime, () => Date.now());
10911
10945
  const d = () => {
10912
10946
  const l = this.clientRuntime.engine.getState().slices.account.authority;
10913
- l?.profile === "main_web_chat" && this.options.entrySurface === "main_web_chat" && this.clientRuntime.engine.dispatch({ type: "stage7.device_hints", authority: l, now: Date.now(), hints: Os(localStorage) });
10947
+ l?.profile === "main_web_chat" && this.options.entrySurface === "main_web_chat" && this.clientRuntime.engine.dispatch({ type: "stage7.device_hints", authority: l, now: Date.now(), hints: xs(localStorage) });
10914
10948
  };
10915
10949
  window.addEventListener("storage", d), this.clientRuntime.onDispose(() => window.removeEventListener("storage", d)), this.clientRuntime.onDispose(() => {
10916
10950
  e.dispose(), o(), this.options.runtimeAdapters?.featurePermissions?.dispose?.();
@@ -10945,7 +10979,7 @@ class Ht {
10945
10979
  })), !0;
10946
10980
  }
10947
10981
  try {
10948
- return s.send(JSON.stringify(e)), Oe("client_event", e.type, ws(e)), !0;
10982
+ return s.send(JSON.stringify(e)), xe("client_event", e.type, ws(e)), !0;
10949
10983
  } catch (n) {
10950
10984
  return V("web-sdk.agent", "Pluno socket send failed; scheduling reconnect", {
10951
10985
  message: n instanceof Error ? n.message : String(n),
@@ -10957,7 +10991,7 @@ class Ht {
10957
10991
  reportHealthSignal(e, s = {}) {
10958
10992
  let n = this.getState();
10959
10993
  if (e === "first_response_slow" && s.sessionId && s.sessionId !== n.sessionId) {
10960
- const { conversation: m, directory: h } = this.clientRuntime.engine.getState().slices, v = Object.values(h.clients).find((b) => h.selections[b]?.sessionId === s.sessionId);
10994
+ const { conversation: m, directory: h } = this.clientRuntime.engine.getState().slices, v = Object.values(h.clients).find((I) => h.selections[I]?.sessionId === s.sessionId);
10961
10995
  v && (n = { ...n, ...as(
10962
10996
  Ie(m, h, v),
10963
10997
  m.sessions[s.sessionId]?.queries.current,
@@ -10993,10 +11027,10 @@ class Ht {
10993
11027
  ...n.sessionId ? { sessionId: n.sessionId } : {},
10994
11028
  ...s,
10995
11029
  ...s.renderedError?.runId ? { runId: s.renderedError.runId } : {}
10996
- }, { errorDiagnostic: a, responseDiagnostics: o, renderedError: c, uiInvariant: d, timings: l, httpRequest: u, historyRefreshFailure: p, ...f } = r;
10997
- for (const m of l ?? []) Oe("client_event", "operation_timing", { ...m });
10998
- if (Oe("client_event", "runtime.health", {
10999
- ...f,
11030
+ }, { errorDiagnostic: a, responseDiagnostics: o, renderedError: c, uiInvariant: d, timings: l, httpRequest: u, historyRefreshFailure: p, ...g } = r;
11031
+ for (const m of l ?? []) xe("client_event", "operation_timing", { ...m });
11032
+ if (xe("client_event", "runtime.health", {
11033
+ ...g,
11000
11034
  signalName: e,
11001
11035
  ...p ? { historyRefreshConsecutiveFailures: p.consecutiveFailures, historyRefreshEpisodeId: p.episodeId } : {}
11002
11036
  }), this.options.productVariant === "customer_embedded" || !this.socket || this.socket.readyState !== WebSocket.OPEN || this.authenticatedSocket !== this.socket) {
@@ -11090,7 +11124,7 @@ class Ht {
11090
11124
  ...s,
11091
11125
  connectionAttemptId: i
11092
11126
  };
11093
- this.transportDiagnosticEpisodes.set(r, c), this.transportDiagnosticEpisodes.size > 20 && this.transportDiagnosticEpisodes.delete(this.transportDiagnosticEpisodes.keys().next().value), e.startsWith("auth_") && Oe("client_event", "authentication_diagnostic", { ...c }), [1, 3, 10, 30, 100].includes(c.occurrenceCount) && (this.pendingTransportDiagnostics = [
11127
+ this.transportDiagnosticEpisodes.set(r, c), this.transportDiagnosticEpisodes.size > 20 && this.transportDiagnosticEpisodes.delete(this.transportDiagnosticEpisodes.keys().next().value), e.startsWith("auth_") && xe("client_event", "authentication_diagnostic", { ...c }), [1, 3, 10, 30, 100].includes(c.occurrenceCount) && (this.pendingTransportDiagnostics = [
11094
11128
  ...this.pendingTransportDiagnostics.filter((d) => d.id !== c.id),
11095
11129
  c
11096
11130
  ], this.pendingTransportDiagnostics.splice(0, Math.max(0, this.pendingTransportDiagnostics.length - 20)), this.flushClientDiagnostics());
@@ -11220,7 +11254,7 @@ class Ht {
11220
11254
  const s = ki(e);
11221
11255
  if (!s) return !1;
11222
11256
  const n = vt(e, "runtimeCommunityId") ?? this.directoryHttp.auth.community_id, i = `${this.options.clientId}:${s.id}:${n ?? this.options.productVariant}`, r = this.directoryAuthority.authorityId !== i, a = this.authenticatedUserId === null, o = a ? Object.values(this.clientRuntime.engine.getState().slices.conversation.operations).filter((l) => ["waiting", "running", "uncertain"].includes(l.phase) && (l.command.type === "run.stop" || l.command.type === "session.reset")).map((l) => l.command) : [], c = a && this.directoryAuthority.authorityId === `${this.options.clientId}:${this.options.runtimeCommunityId ?? this.options.productVariant}` ? this.state.sessionId : null;
11223
- if (this.authenticatedUserId = s.id, this.directoryHttp.auth.community_id = n, Oo(this.options.clientId, i), r) {
11257
+ if (this.authenticatedUserId = s.id, this.directoryHttp.auth.community_id = n, xo(this.options.clientId, i), r) {
11224
11258
  const l = this.directoryAuthority;
11225
11259
  this.directoryObservation.dispose(), this.conversationAdapterGeneration++, this.conversationObservation?.dispose(), this.directoryAuthority = { authorityId: i, generation: l.generation + 1 }, this.clientRuntime.engine.dispatch({ ...this.directoryAuthority, type: "directory.authority_replace", expectedGeneration: l.generation }), this.createDirectoryAdapters();
11226
11260
  const u = this.getModel();
@@ -11238,7 +11272,7 @@ class Ht {
11238
11272
  }
11239
11273
  };
11240
11274
  if (to(this.clientRuntime, d, Date.now()).then(async () => {
11241
- this.options.entrySurface === "main_web_chat" && d.profile === "main_web_chat" && await this.clientRuntime.engine.dispatch({ type: "stage7.device_hints", authority: d, now: Date.now(), hints: Os(localStorage) }), await this.refreshStarterPromptsForCurrentUrl();
11275
+ this.options.entrySurface === "main_web_chat" && d.profile === "main_web_chat" && await this.clientRuntime.engine.dispatch({ type: "stage7.device_hints", authority: d, now: Date.now(), hints: xs(localStorage) }), await this.refreshStarterPromptsForCurrentUrl();
11242
11276
  }).catch(() => {
11243
11277
  }), r || a) {
11244
11278
  const l = this.directoryAuthority;
@@ -11246,8 +11280,8 @@ class Ht {
11246
11280
  if (this.clientRuntime.isDisposed || this.directoryAuthority !== l) return;
11247
11281
  let u = !1;
11248
11282
  for (const p of o) {
11249
- const f = this.clientRuntime.engine.getState().slices.directory, m = f.clients[this.modelClientScopeId];
11250
- if (p.type === "run.stop" && f.selections[m]?.sessionId === p.payload.sessionId) {
11283
+ const g = this.clientRuntime.engine.getState().slices.directory, m = g.clients[this.modelClientScopeId];
11284
+ if (p.type === "run.stop" && g.selections[m]?.sessionId === p.payload.sessionId) {
11251
11285
  if (u) continue;
11252
11286
  u = !0;
11253
11287
  const h = o.filter((v) => v.type === "run.stop" && v.payload.sessionId === p.payload.sessionId).map((v) => String(v.payload.expectedUserMessageId));
@@ -11290,7 +11324,7 @@ class Ht {
11290
11324
  }
11291
11325
  }
11292
11326
  handleServerEvent(e) {
11293
- if (Oe("server_event", e.type, ws(e)), ["conversation.item.updated", "conversation.item.removed", "conversation.item.stream_finished", "conversation.execution.updated", "conversation.interaction.updated", "conversation.follow_ups.updated"].includes(e.type)) {
11327
+ if (xe("server_event", e.type, ws(e)), ["conversation.item.updated", "conversation.item.removed", "conversation.item.stream_finished", "conversation.execution.updated", "conversation.interaction.updated", "conversation.follow_ups.updated"].includes(e.type)) {
11294
11328
  this.conversationObservation?.receive(e);
11295
11329
  return;
11296
11330
  }
@@ -11340,7 +11374,7 @@ class Ht {
11340
11374
  this.setState({ status: "reconnecting", lastError: String(e.message), lastErrorCode: e.code });
11341
11375
  return;
11342
11376
  }
11343
- if (e.code === "service_origin_not_allowed" || e.code === "security_control_enforcement_unavailable" || !xt(void 0, String(e.code)).allowed) {
11377
+ if (e.code === "service_origin_not_allowed" || e.code === "security_control_enforcement_unavailable" || !Ot(void 0, String(e.code)).allowed) {
11344
11378
  this.applyAccountSubmissionError(String(e.code)), this.setState({
11345
11379
  status: "error",
11346
11380
  lastError: String(e.message),
@@ -11476,7 +11510,7 @@ class Ht {
11476
11510
  let l = null, u;
11477
11511
  l = await this.executeRuntimeHelper(), u = await wi(
11478
11512
  a,
11479
- xd(e.runtimeContext, this.options.backendUrl)
11513
+ Od(e.runtimeContext, this.options.backendUrl)
11480
11514
  ).catch((p) => ({
11481
11515
  ok: !1,
11482
11516
  exception: {
@@ -11518,7 +11552,7 @@ class Ht {
11518
11552
  }
11519
11553
  enableNetworkCapture() {
11520
11554
  this.networkCaptureCleanup || (this.networkCaptureCleanup = yd((e) => {
11521
- xl(e.url, this.options.backendUrl) || this.enqueueNetworkEvent(e);
11555
+ Ol(e.url, this.options.backendUrl) || this.enqueueNetworkEvent(e);
11522
11556
  }));
11523
11557
  }
11524
11558
  enqueueNetworkEvent(e) {
@@ -11733,46 +11767,46 @@ function yd(t) {
11733
11767
  }
11734
11768
  function vd() {
11735
11769
  const t = /* @__PURE__ */ new Set(), e = (p) => {
11736
- t.forEach((f) => {
11770
+ t.forEach((g) => {
11737
11771
  try {
11738
- f(p);
11772
+ g(p);
11739
11773
  } catch {
11740
11774
  }
11741
11775
  });
11742
- }, s = window.fetch, n = XMLHttpRequest.prototype.open, i = XMLHttpRequest.prototype.setRequestHeader, r = XMLHttpRequest.prototype.send, a = function(f, m) {
11776
+ }, s = window.fetch, n = XMLHttpRequest.prototype.open, i = XMLHttpRequest.prototype.setRequestHeader, r = XMLHttpRequest.prototype.send, a = function(g, m) {
11743
11777
  const h = Date.now();
11744
11778
  let v;
11745
11779
  try {
11746
- v = s.call(this, f, m);
11747
- } catch (b) {
11748
- throw b;
11780
+ v = s.call(this, g, m);
11781
+ } catch (I) {
11782
+ throw I;
11749
11783
  }
11750
11784
  try {
11751
- const b = f instanceof Request ? f : null, S = Al(f, b), k = qr(m?.headers ?? b?.headers);
11752
- if (!Me(S, k, m?.body)) {
11785
+ const I = g instanceof Request ? g : null, k = Al(g, I), w = qr(m?.headers ?? I?.headers);
11786
+ if (!Me(k, w, m?.body)) {
11753
11787
  const y = {
11754
11788
  requestId: qs("fetch"),
11755
- url: fe(S, ks),
11756
- method: (m?.method ?? b?.method ?? "GET").toUpperCase(),
11757
- requestHeaders: k,
11789
+ url: fe(k, ks),
11790
+ method: (m?.method ?? I?.method ?? "GET").toUpperCase(),
11791
+ requestHeaders: w,
11758
11792
  requestBody: Ti(m?.body),
11759
11793
  resourceType: "fetch",
11760
11794
  startedAt: new Date(h).toISOString()
11761
11795
  };
11762
11796
  v.then(
11763
- (I) => {
11764
- El(I, y, h, e).catch(() => {
11797
+ (b) => {
11798
+ El(b, y, h, e).catch(() => {
11765
11799
  e({
11766
11800
  ...y,
11767
- responseStatus: I.status,
11801
+ responseStatus: b.status,
11768
11802
  durationMs: Date.now() - h
11769
11803
  });
11770
11804
  });
11771
11805
  },
11772
- (I) => {
11806
+ (b) => {
11773
11807
  e({
11774
11808
  ...y,
11775
- errorText: fe(I instanceof Error ? I.message : String(I)),
11809
+ errorText: fe(b instanceof Error ? b.message : String(b)),
11776
11810
  durationMs: Date.now() - h
11777
11811
  });
11778
11812
  }
@@ -11781,24 +11815,24 @@ function vd() {
11781
11815
  } catch {
11782
11816
  }
11783
11817
  return v;
11784
- }, o = function(f, m, h, v, b) {
11785
- const S = n.call(this, f, m, h ?? !0, v ?? void 0, b ?? void 0), k = typeof m == "string" ? m : m.toString();
11818
+ }, o = function(g, m, h, v, I) {
11819
+ const k = n.call(this, g, m, h ?? !0, v ?? void 0, I ?? void 0), w = typeof m == "string" ? m : m.toString();
11786
11820
  return Es.set(this, {
11787
11821
  requestId: qs("xhr"),
11788
- method: String(f ?? "GET").toUpperCase(),
11789
- url: fe(k, ks),
11822
+ method: String(g ?? "GET").toUpperCase(),
11823
+ url: fe(w, ks),
11790
11824
  requestHeaders: {},
11791
11825
  startedAtMs: Date.now(),
11792
11826
  startedAt: (/* @__PURE__ */ new Date()).toISOString(),
11793
- excluded: Me(k)
11794
- }), S;
11795
- }, c = function(f, m) {
11796
- const h = i.call(this, f, m), v = Es.get(this);
11797
- return v && Object.keys(v.requestHeaders).length < kn && (v.requestHeaders[f] = Tn(f, m), v.excluded = v.excluded || Me(v.url, v.requestHeaders)), h;
11798
- }, d = function(f) {
11827
+ excluded: Me(w)
11828
+ }), k;
11829
+ }, c = function(g, m) {
11830
+ const h = i.call(this, g, m), v = Es.get(this);
11831
+ return v && Object.keys(v.requestHeaders).length < kn && (v.requestHeaders[g] = Tn(g, m), v.excluded = v.excluded || Me(v.url, v.requestHeaders)), h;
11832
+ }, d = function(g) {
11799
11833
  try {
11800
11834
  const m = Es.get(this);
11801
- m && (m.excluded = m.excluded || Me(m.url, m.requestHeaders, f), m.requestBody = Ti(f), m.excluded || this.addEventListener(
11835
+ m && (m.excluded = m.excluded || Me(m.url, m.requestHeaders, g), m.requestBody = Ti(g), m.excluded || this.addEventListener(
11802
11836
  "loadend",
11803
11837
  () => {
11804
11838
  queueMicrotask(() => {
@@ -11827,7 +11861,7 @@ function vd() {
11827
11861
  ));
11828
11862
  } catch {
11829
11863
  }
11830
- return r.call(this, f ?? null);
11864
+ return r.call(this, g ?? null);
11831
11865
  };
11832
11866
  try {
11833
11867
  window.fetch = a;
@@ -11848,8 +11882,8 @@ function vd() {
11848
11882
  let l = null;
11849
11883
  if (typeof PerformanceObserver < "u") {
11850
11884
  l = new PerformanceObserver((p) => {
11851
- for (const f of p.getEntries()) {
11852
- const m = f;
11885
+ for (const g of p.getEntries()) {
11886
+ const m = g;
11853
11887
  if (m.initiatorType === "fetch" || m.initiatorType === "xmlhttprequest" || Me(m.name))
11854
11888
  continue;
11855
11889
  const h = performance.timeOrigin + m.startTime;
@@ -12021,7 +12055,7 @@ async function wi(t, e) {
12021
12055
  a = window.setTimeout(() => u(d), n);
12022
12056
  })
12023
12057
  ]);
12024
- return l === d ? Od(n) : {
12058
+ return l === d ? xd(n) : {
12025
12059
  ok: !0,
12026
12060
  result: l,
12027
12061
  console: r,
@@ -12050,7 +12084,7 @@ async function wi(t, e) {
12050
12084
  e?.deactivate(), a !== void 0 && window.clearTimeout(a), console.log = o.log, console.info = o.info, console.warn = o.warn, console.error = o.error;
12051
12085
  }
12052
12086
  }
12053
- function xd(t, e) {
12087
+ function Od(t, e) {
12054
12088
  if (!t || typeof t != "object")
12055
12089
  return;
12056
12090
  const s = t.sandboxFilesToken;
@@ -12094,7 +12128,7 @@ function xd(t, e) {
12094
12128
  }
12095
12129
  };
12096
12130
  }
12097
- function Od(t) {
12131
+ function xd(t) {
12098
12132
  return {
12099
12133
  ok: !1,
12100
12134
  exception: {
@@ -12161,8 +12195,8 @@ function Rn() {
12161
12195
  if (!document.body)
12162
12196
  return "";
12163
12197
  const t = [], e = [], s = (h, v) => {
12164
- const b = Be(v);
12165
- !b || e.includes(b) || (t.push([h, b]), e.push(b));
12198
+ const I = Be(v);
12199
+ !I || e.includes(I) || (t.push([h, I]), e.push(I));
12166
12200
  };
12167
12201
  s("Selected text", window.getSelection()?.toString() ?? "");
12168
12202
  const n = "[role='dialog'], [role='alertdialog'], dialog[open], [aria-modal='true']", i = Array.from(document.querySelectorAll(n)).filter(
@@ -12179,8 +12213,8 @@ ${v}`).join(`
12179
12213
  `, l = `
12180
12214
 
12181
12215
  Visible page text:
12182
- `, u = 12e3 - d.length - l.length, p = Math.min(o.length, 7900), f = c.slice(0, u - p), m = o.slice(0, u - f.length);
12183
- return `${d}${f}${l}${m}`;
12216
+ `, u = 12e3 - d.length - l.length, p = Math.min(o.length, 7900), g = c.slice(0, u - p), m = o.slice(0, u - g.length);
12217
+ return `${d}${g}${l}${m}`;
12184
12218
  }
12185
12219
  function tt(t) {
12186
12220
  return t.innerText ?? t.textContent ?? "";
@@ -12288,49 +12322,49 @@ function Ld(t, e) {
12288
12322
  "data-cy"
12289
12323
  ], d = ["aria-label", "placeholder", "data-testid", "data-test", "data-qa", "data-cy"], { priorityElements: l, priorityTargets: u } = Fd(), p = new Set(t);
12290
12324
  e && p.add(e);
12291
- let f = 0;
12292
- const m = (k) => {
12293
- const g = k.getAttribute("role");
12294
- return g && !a.has(g) ? g : "";
12295
- }, h = (k) => {
12296
- const g = k.getAttribute("data-testid") || k.getAttribute("data-test") || k.getAttribute("data-qa") || k.getAttribute("data-cy") || "";
12297
- return `${k.tagName.toLowerCase()}|${m(k)}|${g}`;
12298
- }, v = (k, g, y) => {
12299
- const I = (w, R) => {
12300
- const T = w.tagName.toLowerCase(), C = window.getComputedStyle(w), E = l.has(w);
12301
- if (f >= 1e3 && !E || y.has(w) || r.has(T) || w.matches(".pluno-pa-widget-host, [data-pluno-product-agent-widget]") || C.display === "none" || C.visibility === "hidden")
12325
+ let g = 0;
12326
+ const m = (w) => {
12327
+ const f = w.getAttribute("role");
12328
+ return f && !a.has(f) ? f : "";
12329
+ }, h = (w) => {
12330
+ const f = w.getAttribute("data-testid") || w.getAttribute("data-test") || w.getAttribute("data-qa") || w.getAttribute("data-cy") || "";
12331
+ return `${w.tagName.toLowerCase()}|${m(w)}|${f}`;
12332
+ }, v = (w, f, y) => {
12333
+ const b = (_, R) => {
12334
+ const T = _.tagName.toLowerCase(), C = window.getComputedStyle(_), E = l.has(_);
12335
+ if (g >= 1e3 && !E || y.has(_) || r.has(T) || _.matches(".pluno-pa-widget-host, [data-pluno-product-agent-widget]") || C.display === "none" || C.visibility === "hidden")
12302
12336
  return { lines: [], hasUsefulContent: !1, textPreview: "", containsTextElement: !1 };
12303
- f += 1;
12304
- const q = m(w), x = _r(w), _ = o.has(q) || ["button", "input", "textarea", "select", "iframe", "canvas"].includes(T) || T === "a" && w.hasAttribute("href"), O = Array.from(w.children).filter((D) => D instanceof HTMLElement), U = /* @__PURE__ */ new Map();
12305
- for (const D of O) {
12337
+ g += 1;
12338
+ const q = m(_), O = _r(_), S = o.has(q) || ["button", "input", "textarea", "select", "iframe", "canvas"].includes(T) || T === "a" && _.hasAttribute("href"), x = Array.from(_.children).filter((D) => D instanceof HTMLElement), U = /* @__PURE__ */ new Map();
12339
+ for (const D of x) {
12306
12340
  const $ = h(D);
12307
12341
  U.set($, (U.get($) ?? 0) + 1);
12308
12342
  }
12309
12343
  const H = /* @__PURE__ */ new Map(), Fe = /* @__PURE__ */ new Map();
12310
- for (const D of O) {
12344
+ for (const D of x) {
12311
12345
  const $ = h(D), ve = Fe.get($) ?? 0;
12312
12346
  Fe.set($, ve + 1), (U.get($) ?? 0) > 8 && ve >= 6 && !l.has(D) && H.set($, (H.get($) ?? 0) + 1);
12313
12347
  }
12314
12348
  const ot = /* @__PURE__ */ new Map(), qn = /* @__PURE__ */ new Set(), Kt = [], Cn = [];
12315
- for (const D of O) {
12349
+ for (const D of x) {
12316
12350
  const $ = h(D), ve = U.get($) ?? 0, Mn = ot.get($) ?? 0;
12317
12351
  if (ot.set($, Mn + 1), ve > 8 && Mn >= 6 && !l.has(D)) {
12318
12352
  qn.has($) || (Kt.push([`… ${H.get($) ?? 0} similar siblings omitted`]), qn.add($));
12319
12353
  continue;
12320
12354
  }
12321
- const Pn = I(D, R);
12355
+ const Pn = b(D, R);
12322
12356
  Cn.push(Pn), Kt.push(Pn.lines);
12323
12357
  }
12324
12358
  const Wt = [];
12325
- if (w.shadowRoot)
12326
- for (const D of Array.from(w.shadowRoot.children))
12327
- D instanceof HTMLElement && Wt.push(I(D, R + 1));
12328
- const at = [...Cn, ...Wt], Gt = x.length > 0 || _ || at.some((D) => D.hasUsefulContent), xn = Be(
12329
- [x, ...at.map((D) => D.textPreview)].filter(Boolean).join(" ")
12330
- ).slice(0, 180), jr = w.hasAttribute("contenteditable") && (x.length > 0 || !w.querySelector("[contenteditable]")), On = d.some((D) => w.hasAttribute(D)) || !!q || jr, Jt = (w.getClientRects().length > 0 || C.display === "contents") && (s.has(T) || On || E) && (Gt || E) && (!i.has(T) || Gt || On || E), Qt = Jt ? 1 : 0, $e = [];
12359
+ if (_.shadowRoot)
12360
+ for (const D of Array.from(_.shadowRoot.children))
12361
+ D instanceof HTMLElement && Wt.push(b(D, R + 1));
12362
+ const at = [...Cn, ...Wt], Gt = O.length > 0 || S || at.some((D) => D.hasUsefulContent), On = Be(
12363
+ [O, ...at.map((D) => D.textPreview)].filter(Boolean).join(" ")
12364
+ ).slice(0, 180), jr = _.hasAttribute("contenteditable") && (O.length > 0 || !_.querySelector("[contenteditable]")), xn = d.some((D) => _.hasAttribute(D)) || !!q || jr, Jt = (_.getClientRects().length > 0 || C.display === "contents") && (s.has(T) || xn || E) && (Gt || E) && (!i.has(T) || Gt || xn || E), Qt = Jt ? 1 : 0, $e = [];
12331
12365
  if (Jt) {
12332
- const D = at.some((ve) => ve.containsTextElement), $ = n.has(T) && !D ? xn : x;
12333
- $e.push(wr(w, c, a, $.slice(0, 180)));
12366
+ const D = at.some((ve) => ve.containsTextElement), $ = n.has(T) && !D ? On : O;
12367
+ $e.push(wr(_, c, a, $.slice(0, 180)));
12334
12368
  }
12335
12369
  for (const D of Kt)
12336
12370
  $e.push(...yt(D, Qt));
@@ -12348,22 +12382,22 @@ function Ld(t, e) {
12348
12382
  return {
12349
12383
  lines: $e,
12350
12384
  hasUsefulContent: Gt,
12351
- textPreview: xn,
12385
+ textPreview: On,
12352
12386
  containsTextElement: n.has(T) || at.some((D) => D.containsTextElement)
12353
12387
  };
12354
12388
  };
12355
- return [`--- ${g} ---`, ...I(k, 0).lines].join(`
12389
+ return [`--- ${f} ---`, ...b(w, 0).lines].join(`
12356
12390
  `);
12357
- }, b = [], S = Be(window.getSelection()?.toString() ?? "");
12358
- S && b.push(`--- selected text ---
12359
- ${JSON.stringify(S)}`), u.length > 0 && b.push($d(u, s, c, a));
12360
- for (const k of t.slice(0, 3))
12361
- b.push(v(k, "active overlay DOM", /* @__PURE__ */ new Set()));
12362
- if (e && b.push(v(e, "main DOM", /* @__PURE__ */ new Set())), document.body) {
12363
- const k = e || t.length ? "other visible DOM" : "visible DOM";
12364
- b.push(v(document.body, k, p));
12365
- }
12366
- return b.join(`
12391
+ }, I = [], k = Be(window.getSelection()?.toString() ?? "");
12392
+ k && I.push(`--- selected text ---
12393
+ ${JSON.stringify(k)}`), u.length > 0 && I.push($d(u, s, c, a));
12394
+ for (const w of t.slice(0, 3))
12395
+ I.push(v(w, "active overlay DOM", /* @__PURE__ */ new Set()));
12396
+ if (e && I.push(v(e, "main DOM", /* @__PURE__ */ new Set())), document.body) {
12397
+ const w = e || t.length ? "other visible DOM" : "visible DOM";
12398
+ I.push(v(document.body, w, p));
12399
+ }
12400
+ return I.join(`
12367
12401
 
12368
12402
  `);
12369
12403
  }
@@ -12654,7 +12688,7 @@ function Sr(t, e) {
12654
12688
  callId: Je(i) ?? void 0,
12655
12689
  sharePromptAllowed: r
12656
12690
  };
12657
- const a = Oc(i.output);
12691
+ const a = xc(i.output);
12658
12692
  if (a)
12659
12693
  return {
12660
12694
  id: String(s.id ?? crypto.randomUUID()),
@@ -13211,7 +13245,7 @@ function Cr(t) {
13211
13245
  return s !== null && Number.isInteger(n) && n >= 0 && n <= Sn && (e.startsWith("text/") || e.includes("json") || e.includes("javascript"));
13212
13246
  }
13213
13247
  function Me(t, e = {}, s) {
13214
- if (Ol(s))
13248
+ if (xl(s))
13215
13249
  return !0;
13216
13250
  const n = Object.entries(e).find(([i]) => i.toLowerCase() === "content-type")?.[1]?.toLowerCase();
13217
13251
  if (n?.includes("multipart/form-data") || n?.includes("application/octet-stream"))
@@ -13226,7 +13260,7 @@ function Me(t, e = {}, s) {
13226
13260
  return !0;
13227
13261
  }
13228
13262
  }
13229
- function xl(t, e) {
13263
+ function Ol(t, e) {
13230
13264
  if (Me(t))
13231
13265
  return !0;
13232
13266
  try {
@@ -13236,7 +13270,7 @@ function xl(t, e) {
13236
13270
  return !0;
13237
13271
  }
13238
13272
  }
13239
- function Ol(t) {
13273
+ function xl(t) {
13240
13274
  return t instanceof FormData || t instanceof Blob || t instanceof ArrayBuffer || ArrayBuffer.isView(t) || typeof ReadableStream < "u" && t instanceof ReadableStream;
13241
13275
  }
13242
13276
  function Ml(t) {
@@ -13258,7 +13292,7 @@ function fe(t, e = Sn) {
13258
13292
  function qs(t) {
13259
13293
  return `${t}-${Date.now()}-${Math.random().toString(16).slice(2)}`;
13260
13294
  }
13261
- class xr extends Error {
13295
+ class Or extends Error {
13262
13296
  constructor(e, s) {
13263
13297
  super(`${e} (${s})`), this.status = s, this.name = "AttachmentUploadHttpError", this.code = String(s);
13264
13298
  }
@@ -13283,7 +13317,7 @@ function Dl(t) {
13283
13317
  });
13284
13318
  }
13285
13319
  function Ul(t) {
13286
- return t instanceof xr ? Nl(t.status) : t instanceof TypeError;
13320
+ return t instanceof Or ? Nl(t.status) : t instanceof TypeError;
13287
13321
  }
13288
13322
  function Nl(t) {
13289
13323
  return t === 408 || t === 409 || t === 429 || t >= 500;
@@ -13291,7 +13325,7 @@ function Nl(t) {
13291
13325
  function jl(t) {
13292
13326
  return t === 401 || t === 403;
13293
13327
  }
13294
- const Vt = "[REDACTED_SECRET]", ge = "[REDACTED_TOKEN]", Bl = "[REDACTED_SIGNED_URL]", Ll = 20, Fl = /^(access_token|accessToken|refresh_token|refreshToken|id_token|idToken|authToken|token|api_key|apiKey|apikey|key|secret|signature|sig|password|passwd|pwd|code|state|session|jwt|csrf|csrfToken|xsrf|xsrfToken)$/i, Or = /\bBearer\s+[A-Za-z0-9._~+/=-]{12,}/gi, Mr = /\bBasic\s+[A-Za-z0-9+/=-]{12,}/gi, Pr = /\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\b/g, Dr = /\b(access_token|accessToken|refresh_token|refreshToken|id_token|idToken|authToken|api_key|apiKey|apikey|client_secret|clientSecret|password|secret|token|jwt|csrf|csrfToken|xsrf|xsrfToken)\b\s*[:=]\s*["']?[^"',&\s}]+/gi, $l = /\bhttps?:\/\/[^\s"'<>]+(?:X-Amz-Signature|X-Goog-Signature|Signature|sig=)[^\s"'<>]*/gi, zl = /\bhttps?:\/\/[^\s"'<>]+/gi, Hl = /[),.;\]]+$/;
13328
+ const Vt = "[REDACTED_SECRET]", ge = "[REDACTED_TOKEN]", Bl = "[REDACTED_SIGNED_URL]", Ll = 20, Fl = /^(access_token|accessToken|refresh_token|refreshToken|id_token|idToken|authToken|token|api_key|apiKey|apikey|key|secret|signature|sig|password|passwd|pwd|code|state|session|jwt|csrf|csrfToken|xsrf|xsrfToken)$/i, xr = /\bBearer\s+[A-Za-z0-9._~+/=-]{12,}/gi, Mr = /\bBasic\s+[A-Za-z0-9+/=-]{12,}/gi, Pr = /\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\b/g, Dr = /\b(access_token|accessToken|refresh_token|refreshToken|id_token|idToken|authToken|api_key|apiKey|apikey|client_secret|clientSecret|password|secret|token|jwt|csrf|csrfToken|xsrf|xsrfToken)\b\s*[:=]\s*["']?[^"',&\s}]+/gi, $l = /\bhttps?:\/\/[^\s"'<>]+(?:X-Amz-Signature|X-Goog-Signature|Signature|sig=)[^\s"'<>]*/gi, zl = /\bhttps?:\/\/[^\s"'<>]+/gi, Hl = /[),.;\]]+$/;
13295
13329
  function ne(t) {
13296
13330
  return Ut(t, 0, /* @__PURE__ */ new WeakSet());
13297
13331
  }
@@ -13329,10 +13363,10 @@ function Nr(t) {
13329
13363
  }
13330
13364
  }
13331
13365
  function Nt(t) {
13332
- return t.replace($l, Bl).replace(zl, Wl).replace(Or, `Bearer ${ge}`).replace(Mr, `Basic ${ge}`).replace(Pr, ge).replace(Dr, (e, s) => `${s}: ${Vt}`);
13366
+ return t.replace($l, Bl).replace(zl, Wl).replace(xr, `Bearer ${ge}`).replace(Mr, `Basic ${ge}`).replace(Pr, ge).replace(Dr, (e, s) => `${s}: ${Vt}`);
13333
13367
  }
13334
13368
  function Kl(t) {
13335
- return t.replace(Or, `Bearer ${ge}`).replace(Mr, `Basic ${ge}`).replace(Pr, ge).replace(Dr, (e, s) => `${s}: ${Vt}`);
13369
+ return t.replace(xr, `Bearer ${ge}`).replace(Mr, `Basic ${ge}`).replace(Pr, ge).replace(Dr, (e, s) => `${s}: ${Vt}`);
13336
13370
  }
13337
13371
  function Wl(t) {
13338
13372
  const e = t.match(Hl)?.[0] ?? "", s = e ? t.slice(0, -e.length) : t;