@pluno/product-agent-web 0.1.263 → 0.1.265

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.
@@ -17,21 +17,21 @@ function Yt(t, e, s, n) {
17
17
  if (t.interactions.closedScopes[a]) continue;
18
18
  const o = s.selections[a];
19
19
  if (!o) continue;
20
- const c = o.sessionId ? e.sessions[o.sessionId] : void 0, d = c?.execution?.user_message_ids ?? [], l = ["queued", "thinking", "steering"].includes(c?.execution?.phase ?? "idle"), u = t.interactions.openings[a], p = u && (u.sessionId === o.sessionId || u.sessionId === null) ? { ...u, sessionId: o.sessionId } : { sessionId: o.sessionId, generation: ++r, openedAt: n, awaitingBaseline: o.sessionId !== null && !c?.execution, ignoredTurns: d, turns: {}, shown: {} };
20
+ const c = o.sessionId ? e.sessions[o.sessionId] : void 0, l = c?.execution?.user_message_ids ?? [], d = ["queued", "thinking", "steering"].includes(c?.execution?.phase ?? "idle"), u = t.interactions.openings[a], p = u && (u.sessionId === o.sessionId || u.sessionId === null) ? { ...u, sessionId: o.sessionId } : { sessionId: o.sessionId, generation: ++r, openedAt: n, awaitingBaseline: o.sessionId !== null && !c?.execution, ignoredTurns: l, turns: {}, shown: {} };
21
21
  if (p.awaitingBaseline && c?.execution) {
22
- const m = d.filter((h) => {
22
+ const m = l.filter((h) => {
23
23
  const v = e.submissions[h];
24
24
  return v?.conversationScopeId === a && v.submittedAt >= p.openedAt;
25
25
  });
26
- p.awaitingBaseline = !1, p.ignoredTurns = d.filter((h) => !m.includes(h));
26
+ p.awaitingBaseline = !1, p.ignoredTurns = l.filter((h) => !m.includes(h));
27
27
  }
28
28
  const g = {};
29
29
  for (const [m, h] of Object.entries(p.turns)) {
30
- const v = l && d.includes(m), I = v && !h.active ? n : h.startedAt;
30
+ const v = d && l.includes(m), I = v && !h.active ? n : h.startedAt;
31
31
  g[m] = { ...h, startedAt: I, active: v, notifications: !h.notificationsSuppressed && (h.notifications || v && n - I >= 1e4) };
32
32
  }
33
- if (l)
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) });
33
+ if (d)
34
+ for (const m of l) !p.ignoredTurns.includes(m) && !g[m] && (g[m] = { startedAt: n, active: !0, notifications: !1, tab_grouping: (t.interactions.crossTabTurns[o.sessionId] ?? []).includes(m) });
35
35
  i[a] = { ...p, turns: g };
36
36
  }
37
37
  return { ...t, interactions: { ...t.interactions, openings: i, openingGeneration: r } };
@@ -303,47 +303,47 @@ 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((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);
306
+ const n = t.submissionOrder.map((k) => t.submissions[k]).filter((k) => k.conversationScopeId === s), i = e.selections[s]?.sessionId ?? n.find((k) => !k.cancelled && k.sessionId !== null)?.sessionId ?? null, r = i ? t.sessions[i] : void 0, a = t.submissionOrder.map((k) => t.submissions[k]).filter((k) => i ? k.sessionId === i || k.sessionId === null && k.conversationScopeId === s : k.conversationScopeId === s), o = Object.values(r?.items ?? {}).sort((k, x) => {
307
+ const U = he(k.created_at), H = he(x.created_at);
308
+ return U < H ? -1 : U > H ? 1 : k.id < x.id ? -1 : k.id > x.id ? 1 : 0;
309
+ }), c = a.filter((k) => (!k.cancelled || k.conversationScopeId === s && (k.sessionId === null || k.sessionId === i || i === null && k === a[a.length - 1])) && !r?.items[k.userMessageId] && !r?.removedItems[k.userMessageId]), l = {};
310
+ for (const k of o) {
311
+ const x = xt(k);
312
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";
313
+ const U = r?.streams[k.id];
314
+ l[k.id] = U ? U.state === "open" ? "open" : x < U.revision ? "awaiting_content" : U.state : "open";
315
315
  }
316
- const l = [];
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 });
316
+ const d = [];
317
+ for (const k of o)
318
+ if (k.type === "user_message")
319
+ d.push({ id: k.id, userMessageId: k.id, activityIds: [], outcomeIds: [], collapsed: !1 });
320
320
  else {
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] };
321
+ d.length || d.push({ id: `leading:${k.id}`, userMessageId: null, activityIds: [], outcomeIds: [], collapsed: !1 });
322
+ const x = d.length - 1, U = d[x], H = k.type === "commentary" || k.type === "tool_summary" ? "activityIds" : "outcomeIds";
323
+ d[x] = { ...U, [H]: [...U[H], k.id] };
324
324
  }
325
- for (const S of c) {
326
- const x = l.findIndex((U) => {
325
+ for (const k of c) {
326
+ const x = d.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)) > S.submittedAt;
328
+ return (H?.submittedAt ?? (Fe ? Date.parse(Fe.created_at) : 1 / 0)) > k.submittedAt;
329
329
  });
330
- l.splice(x < 0 ? l.length : x, 0, {
331
- id: S.userMessageId,
332
- userMessageId: S.userMessageId,
330
+ d.splice(x < 0 ? d.length : x, 0, {
331
+ id: k.userMessageId,
332
+ userMessageId: k.userMessageId,
333
333
  activityIds: [],
334
334
  outcomeIds: [],
335
335
  collapsed: !1
336
336
  });
337
337
  }
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);
338
+ const u = r?.execution, p = a.filter((k) => !k.cancelled && k.delivery !== "failed"), g = p.filter((k) => k.delivery !== "accepted" && k.executionVersion === null), m = p.filter((k) => k.delivery === "accepted" && k.executionVersion === null), h = p[p.length - 1], v = g.length > 0, I = h !== void 0 && m.includes(h);
339
+ let _ = v ? "submitting" : I ? "awaiting_execution" : u?.phase ?? "idle";
340
+ const S = Object.entries(t.stops).filter(([k]) => k === s || i !== null && e.selections[k]?.sessionId === i).map(([, k]) => k).find((k) => (!a.length || k.userMessageIds.includes(a[a.length - 1].userMessageId) || !v && !I && de(u).some((x) => k.userMessageIds.includes(x))) && (!u || u.version <= k.executionVersion || ["thinking", "steering", "queued", "stopping"].includes(u.phase) || a.some((x) => x.cancelled && x.executionVersion === null && k.userMessageIds.includes(x.userMessageId)))), f = u && ["thinking", "steering", "queued", "stopping"].includes(u.phase) || a.some((k) => k.delivery === "accepted" && k.executionVersion === null && S?.userMessageIds.includes(k.userMessageId));
341
+ S && f && !v && (!u || !["thinking", "steering", "queued", "stopping"].includes(u.phase) || de(u).every((k) => S.userMessageIds.includes(k))) && (_ = "stopping"), S && !f && !v && a.some((k) => k.cancelled && k.executionVersion === null && S.userMessageIds.includes(k.userMessageId)) && (_ = a.some((k) => S.userMessageIds.includes(k.userMessageId) && ["sending", "uncertain"].includes(k.delivery)) ? "stopping" : "stopped");
342
+ const b = ["thinking", "steering", "queued"].includes(_), y = t.stops[s] ?? S, w = y?.userMessageIds.filter((k) => !["completed", "failed"].includes(r?.executionByUserMessage[k]?.phase ?? "")) ?? [], R = w.some((k) => {
343
+ const x = a.find((H) => H.userMessageId === k);
344
+ return !Object.values(t.operations).some((H) => H.command.type === "run.stop" && H.command.payload.expectedUserMessageId === k && H.phase === "done") && (x?.executionVersion === null && ["sending", "uncertain", "accepted"].includes(x.delivery) || !!(u && de(u).includes(k) && ["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 = d.find((k) => k.userMessageId === C), q = b ? [...E?.activityIds ?? []].reverse().find((k) => l[k] === "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((k) => k.conversationScopeId === s && k.phase === "done" && ["runtime.warmup", "attachment.prepare"].includes(k.command.type) && !k.command.payload.sessionId && k.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,
@@ -354,24 +354,24 @@ function Ie(t, e, s) {
354
354
  optimistic: c,
355
355
  submissions: a,
356
356
  followUps: r?.followUps ?? [],
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]])),
357
+ isRetrying: Object.values(t.operations).some((k) => k.command.type === "chat.retry_last_user_message" && k.command.payload.sessionId === i && ["waiting", "running", "uncertain"].includes(k.phase)),
358
+ deliveries: Object.fromEntries(a.filter((k) => t.deliveries[k.userMessageId]).map((k) => [k.userMessageId, t.deliveries[k.userMessageId]])),
359
359
  removedItems: r?.removedItems ?? {},
360
- streamStates: d,
360
+ streamStates: l,
361
361
  preparation: r?.preparation ?? null,
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()) },
362
+ stop: y ? { ...y, userMessageIds: w, pending: R } : null,
363
+ segments: d.map((k, x) => ({ ...k, collapsed: b ? k.userMessageId !== C : x < d.length - 1 || k.activityIds.length > 0 })),
364
+ activity: { phase: _, 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((S) => !S.cancelled && e.clients[S.clientScopeId] === s).map((S) => ({ viewId: S.viewId, userMessageId: S.userMessageId, acceptedRendererRevision: S.rendererRevision }))
367
+ receipts: n.filter((k) => !k.cancelled && e.clients[k.clientScopeId] === s).map((k) => ({ viewId: k.viewId, userMessageId: k.userMessageId, acceptedRendererRevision: k.rendererRevision }))
368
368
  });
369
369
  }
370
370
  function Di(t, e) {
371
371
  const s = /* @__PURE__ */ new Set([
372
372
  ...t.items.filter((o) => o.type === "user_message").map((o) => o.id),
373
373
  ...t.submissions.filter((o) => o.delivery === "accepted").map((o) => o.userMessageId)
374
- ]), n = t.segments.reduce((o, c, d) => c.userMessageId && s.has(c.userMessageId) ? d : o, -1), i = t.submissions.filter((o) => o.error?.code !== "context_preparation_interrupted" || t.segments.findIndex((c) => c.userMessageId === o.userMessageId) > n), r = e ? t.submissions.find((o) => o.userMessageId === e) : t.submissions.find((o) => !o.cancelled && t.deliveries[o.userMessageId]?.phase === "paused") ?? [...i].reverse().find((o) => !o.cancelled && o.delivery !== "accepted");
374
+ ]), n = t.segments.reduce((o, c, l) => c.userMessageId && s.has(c.userMessageId) ? l : o, -1), i = t.submissions.filter((o) => o.error?.code !== "context_preparation_interrupted" || t.segments.findIndex((c) => c.userMessageId === o.userMessageId) > n), r = e ? t.submissions.find((o) => o.userMessageId === e) : t.submissions.find((o) => !o.cancelled && t.deliveries[o.userMessageId]?.phase === "paused") ?? [...i].reverse().find((o) => !o.cancelled && o.delivery !== "accepted");
375
375
  if (r && !r.cancelled && r.delivery === "failed" && r.contextPreparation === null && r.error?.code === "context_preparation_interrupted")
376
376
  return { type: "preparation", submission: r };
377
377
  if (r && !r.cancelled && (r.delivery === "uncertain" || r.delivery === "failed" && !["attachment_source_unavailable", "context_preparation_interrupted"].includes(r.error?.code ?? "") || t.deliveries[r.userMessageId]?.phase === "paused"))
@@ -427,12 +427,12 @@ 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((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
- return { status: l ? "pending" : p ? "error" : "presentable", error: p };
430
+ const l = Object.values(t.features.pending).filter((g) => g.mode === "mutation" && c.includes(g.key)), d = l.some((g) => g.status === "pending"), u = l[l.length - 1], p = u?.status === "error" ? u.error : null;
431
+ return { status: d ? "pending" : p ? "error" : "presentable", error: p };
432
432
  };
433
- if (n.profile === "main_web_chat") for (const [c, d] of Object.entries(t.interactions.deviceHints)) {
434
- if (d) continue;
435
- const l = Object.values(t.interactions.actions).filter((u) => u.interactionId === c).slice(-1)[0];
433
+ if (n.profile === "main_web_chat") for (const [c, l] of Object.entries(t.interactions.deviceHints)) {
434
+ if (l) continue;
435
+ const d = Object.values(t.interactions.actions).filter((u) => u.interactionId === c).slice(-1)[0];
436
436
  r.push({
437
437
  id: c,
438
438
  category: "device_hint",
@@ -443,21 +443,21 @@ function Hr(t, e, s) {
443
443
  sourceVersion: null,
444
444
  decisionRevision: 0,
445
445
  actions: ["dismiss"],
446
- status: l?.status === "pending" ? "pending" : l?.status === "error" ? "error" : "presentable",
447
- error: l?.error ?? null,
446
+ status: d?.status === "pending" ? "pending" : d?.status === "error" ? "error" : "presentable",
447
+ error: d?.error ?? null,
448
448
  payload: {},
449
449
  nextEligibleAt: null
450
450
  });
451
451
  }
452
452
  if (i && t.account.preferences)
453
453
  for (const c of ["notifications", "tab_grouping"]) {
454
- const d = c === "notifications" ? "canRequestNotificationPermission" : "canGroupSessionTabs";
455
- if (!J(n.profile, d)) continue;
456
- const l = s.conversationScopeId ? t.interactions.openings[s.conversationScopeId] : void 0;
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;
454
+ const l = c === "notifications" ? "canRequestNotificationPermission" : "canGroupSessionTabs";
455
+ if (!J(n.profile, l)) continue;
456
+ const d = s.conversationScopeId ? t.interactions.openings[s.conversationScopeId] : void 0;
457
+ if (!s.sessionId || !d || d.sessionId !== s.sessionId || !Ci(t, s.conversationScopeId, c) || t.features.refreshRequired && !d.shown[c] || n.profile === "main_web_chat" && !t.interactions.bridgeReady && !d.shown[c]) continue;
458
458
  const u = Qe(t, c), p = t.interactions.preferencePrompts[c], g = t.interactions.deviceFacts[c], m = `preference:${c}`, h = u === null;
459
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);
460
+ const v = Object.values(t.interactions.devicePending).some((S) => S.feature === c), I = o([m, `preferenceSnooze:${c}`, `preferenceAcknowledge:${c}`]), _ = I.error ?? t.interactions.deviceErrors[c] ?? (d.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",
@@ -465,48 +465,48 @@ function Hr(t, e, s) {
465
465
  sourceId: null,
466
466
  conversationId: null,
467
467
  userMessageId: null,
468
- sourceVersion: l.generation,
468
+ sourceVersion: d.generation,
469
469
  decisionRevision: p.revision,
470
470
  actions: h ? ["enable", "not_now", "dont_enable"] : ["allow", "not_now"],
471
- status: v ? "pending" : k ? "error" : I.status,
472
- error: k,
473
- payload: { feature: c, openingGeneration: l.generation },
471
+ status: v ? "pending" : _ ? "error" : I.status,
472
+ error: _,
473
+ payload: { feature: c, openingGeneration: d.generation },
474
474
  nextEligibleAt: h ? p.snoozedUntil : g.snoozedUntil
475
475
  });
476
476
  }
477
477
  for (const c of Object.values(t.interactions.sources)) {
478
478
  if (c.conversation_id !== s.sessionId || c.lifecycle === "completed" || c.payload.kind !== "integration_auth" && c.lifecycle !== "pending") continue;
479
- const d = c.payload;
480
- if (d.kind === "integration_auth" && n.interactionAdapters?.integrationAuth === !1 || d.kind === "personal_channel" && n.interactionAdapters?.personalChannel === !1 || !J(n.profile, "canManageInteractions")) continue;
481
- if (d.kind === "sharing") {
482
- if (!i || !J(n.profile, "canShare") || !d.eligible || c.invocation !== "user" || (n.profile.startsWith("extension_") ? !t.interactions.localSharingReady : t.features.refreshRequired)) continue;
479
+ const l = c.payload;
480
+ if (l.kind === "integration_auth" && n.interactionAdapters?.integrationAuth === !1 || l.kind === "personal_channel" && n.interactionAdapters?.personalChannel === !1 || !J(n.profile, "canManageInteractions")) continue;
481
+ if (l.kind === "sharing") {
482
+ if (!i || !J(n.profile, "canShare") || !l.eligible || c.invocation !== "user" || (n.profile.startsWith("extension_") ? !t.interactions.localSharingReady : t.features.refreshRequired)) continue;
483
483
  const m = e.sessions[c.conversation_id];
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;
484
+ if (l.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
- 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], 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];
486
+ if (l.kind === "integration_auth" && !J(n.profile, "canManageIntegrationAuth") || l.kind === "personal_channel" && !i) continue;
487
+ const d = l.kind === "integration_auth" && c.lifecycle === "pending" && Date.parse(l.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
- category: d.kind,
490
+ category: l.kind,
491
491
  placement: "turn",
492
492
  sourceId: c.id,
493
493
  conversationId: c.conversation_id,
494
494
  userMessageId: c.user_message_id,
495
495
  sourceVersion: c.version,
496
496
  decisionRevision: n.profile.startsWith("extension_") ? p?.revision ?? 0 : u?.revision ?? 0,
497
- actions: d.kind === "sharing" ? ["copy", "share", "dismiss"] : d.kind === "integration_auth" ? ["connect"] : ["pair"],
498
- ...d.kind === "integration_auth" ? { actionLabels: { connect: g?.status === "error" ? "Try again" : l === "pending" ? "Connect" : "Reconnect" } } : {},
497
+ actions: l.kind === "sharing" ? ["copy", "share", "dismiss"] : l.kind === "integration_auth" ? ["connect"] : ["pair"],
498
+ ...l.kind === "integration_auth" ? { actionLabels: { connect: g?.status === "error" ? "Try again" : d === "pending" ? "Connect" : "Reconnect" } } : {},
499
499
  ...o([`prompt:social_share:${c.id}`]),
500
500
  ...g?.status === "pending" || g?.status === "error" ? { status: g.status, error: g.error } : {},
501
- payload: d.kind === "integration_auth" ? { ...d, lifecycle: l } : d,
501
+ payload: l.kind === "integration_auth" ? { ...l, lifecycle: d } : l,
502
502
  nextEligibleAt: null
503
503
  });
504
504
  }
505
505
  if (i && s.newChat && !s.sessionId && !s.submissionStarted && !t.features.refreshRequired)
506
506
  for (const c of Object.values(t.interactions.welcome)) {
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
- 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), g = u.status === "pending" || p?.status === "pending" ? "pending" : u.error || p?.status === "error" ? "error" : "presentable";
507
+ const l = c.category === "morning_report" ? "canManageMorningReport" : "canManageProactiveSuggestions", d = c.category === "morning_report" ? "category:morning_report" : `prompt:proactive_suggestion:${c.sourceSuggestionId ?? c.id}`;
508
+ if (c.clientScopeId && c.clientScopeId !== s.clientScopeId || !c.eligible || c.expiresAt !== void 0 && c.expiresAt <= a || !J(n.profile, l) || Bn(t.interactions.decisions[d], a)) continue;
509
+ const u = o([d]), 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,
@@ -515,12 +515,12 @@ function Hr(t, e, s) {
515
515
  conversationId: null,
516
516
  userMessageId: null,
517
517
  sourceVersion: null,
518
- decisionRevision: t.interactions.decisions[l]?.revision ?? 0,
518
+ decisionRevision: t.interactions.decisions[d]?.revision ?? 0,
519
519
  actions: c.category === "morning_report" ? ["run", "snooze"] : ["run", "edit", "not_now", "never", "feedback"],
520
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
- nextEligibleAt: t.interactions.decisions[l]?.nextEligibleAt ?? null
523
+ nextEligibleAt: t.interactions.decisions[d]?.nextEligibleAt ?? null
524
524
  });
525
525
  }
526
526
  return r;
@@ -533,16 +533,16 @@ function Bi(t, e, s, n) {
533
533
  }
534
534
  function Vr(t, e, s, n) {
535
535
  let i = t;
536
- const r = [], a = i.account.authority, o = (l, u) => JSON.stringify(["stage7.platform", a.authorityId, a.generation, l, u]), c = (l, u) => {
537
- i = { ...i, interactions: { ...i.interactions, actions: { ...i.interactions.actions, [l]: u } } };
538
- }, d = (l, u, p) => {
539
- r.push({ kind: "stage7.platform", id: o(l, p), input: { authority: a, requestId: l, operation: u } });
536
+ const r = [], a = i.account.authority, o = (d, u) => JSON.stringify(["stage7.platform", a.authorityId, a.generation, d, u]), c = (d, u) => {
537
+ i = { ...i, interactions: { ...i.interactions, actions: { ...i.interactions.actions, [d]: u } } };
538
+ }, l = (d, u, p) => {
539
+ r.push({ kind: "stage7.platform", id: o(d, p), input: { authority: a, requestId: d, operation: u } });
540
540
  };
541
541
  if (e.type === "stage7.act") {
542
- const l = i.interactions.actions[e.requestId];
543
- if (l) {
542
+ const d = i.interactions.actions[e.requestId];
543
+ if (d) {
544
544
  const h = i.interactions.welcome[e.interactionId], v = h?.category === "morning_report" ? h.tasks[e.taskIndex ?? 0] : h?.text;
545
- if (l.interactionId !== e.interactionId || l.action !== e.action || l.expectedRevision !== e.expectedRevision || l.sourceVersion !== (e.sourceVersion ?? null) || l.clientScopeId !== e.clientScopeId || l.taskIndex !== (e.taskIndex ?? null) || (l.operation.kind === "run" || l.operation.kind === "edit") && l.operation.text !== v) throw new Error("Action request changed.");
545
+ if (d.interactionId !== e.interactionId || d.action !== e.action || d.expectedRevision !== e.expectedRevision || d.sourceVersion !== (e.sourceVersion ?? null) || d.clientScopeId !== e.clientScopeId || d.taskIndex !== (e.taskIndex ?? null) || (d.operation.kind === "run" || d.operation.kind === "edit") && d.operation.text !== v) throw new Error("Action request changed.");
546
546
  return { state: i, effects: r, command: null };
547
547
  }
548
548
  if (e.action === "feedback") {
@@ -604,8 +604,8 @@ function Vr(t, e, s, n) {
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 k = xi(i.account, "send_message", e.origin ?? null);
608
- if (!k.allowed) throw new Error(`Task submission unavailable: ${k.reason}.`);
607
+ const _ = xi(i.account, "send_message", e.origin ?? null);
608
+ if (!_.allowed) throw new Error(`Task submission unavailable: ${_.reason}.`);
609
609
  }
610
610
  const v = i.interactions.welcome[u.id], I = v.category === "morning_report" ? v.tasks[e.taskIndex ?? 0] : v.text;
611
611
  if (!I) throw new Error("Missing selected task.");
@@ -631,17 +631,17 @@ function Vr(t, e, s, n) {
631
631
  step: m,
632
632
  status: "pending",
633
633
  error: null
634
- }), d(e.requestId, g, m);
634
+ }), l(e.requestId, g, m);
635
635
  } else if (e.type === "stage7.retry_action") {
636
- const l = i.interactions.actions[e.requestId];
637
- if (!l || l.step !== "persist" || l.status !== "error") throw new Error("An uncertain browser action cannot be replayed.");
638
- if (c(e.requestId, { ...l, status: "pending", error: null }), !a.profile.startsWith("extension_") && (l.operation.kind === "copy" || l.operation.kind === "share"))
636
+ const d = i.interactions.actions[e.requestId];
637
+ if (!d || d.step !== "persist" || d.status !== "error") throw new Error("An uncertain browser action cannot be replayed.");
638
+ if (c(e.requestId, { ...d, status: "pending", error: null }), !a.profile.startsWith("extension_") && (d.operation.kind === "copy" || d.operation.kind === "share"))
639
639
  return { state: i, effects: r, command: { type: "stage7.retry", authority: a, now: e.now, requestId: `sharing:${e.requestId}` } };
640
- d(e.requestId, l.operation, "persist");
640
+ l(e.requestId, d.operation, "persist");
641
641
  } else {
642
- const l = Object.entries(i.interactions.actions).find(([g, m]) => o(g, m.step) === e.effectId && m.status === "pending");
643
- if (!l) return { state: i, effects: r, command: null };
644
- const [u, p] = l;
642
+ const d = Object.entries(i.interactions.actions).find(([g, m]) => o(g, m.step) === e.effectId && m.status === "pending");
643
+ if (!d) return { state: i, effects: r, command: null };
644
+ const [u, p] = d;
645
645
  if (e.type === "effect.failed") c(u, { ...p, status: "error", error: e.error });
646
646
  else if (p.operation.kind === "copy" || p.operation.kind === "share") {
647
647
  if (!a.profile.startsWith("extension_"))
@@ -653,7 +653,7 @@ function Vr(t, e, s, n) {
653
653
  mutation: { kind: "decision", category: "social_share", promptKey: p.interactionId, action: "shared", expectedRevision: p.expectedRevision }
654
654
  } };
655
655
  const g = { kind: "saveSharing", interactionId: p.interactionId, expectedRevision: p.expectedRevision };
656
- c(u, { ...p, operation: g, step: "persist" }), d(u, g, "persist");
656
+ c(u, { ...p, operation: g, step: "persist" }), l(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,7 +670,7 @@ 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, 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) => {
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, l = (u) => Object.values(i.pending).some((p) => p.mode === "mutation" && ["pending", "queued"].includes(p.status) && c(p.operation, u)), d = (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
  };
@@ -694,21 +694,21 @@ function Kr(t, e, s, n) {
694
694
  error: null,
695
695
  result: null
696
696
  } }
697
- }), d(u.origin) || l(g);
697
+ }), l(u.origin) || d(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
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), I = (i.appearanceEpochs[p] ?? 0) + 1, k = { ...i.pending };
705
- for (const [w, f] of Object.entries(k)) {
704
+ const v = l(p), I = (i.appearanceEpochs[p] ?? 0) + 1, _ = { ...i.pending };
705
+ for (const [S, f] of Object.entries(_)) {
706
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" };
707
+ delete _[S];
708
+ const b = o("query", f.requestId, I);
709
+ _[b] = { ...f, effectId: b, status: "queued" };
710
710
  }
711
- k[g] = {
711
+ _[g] = {
712
712
  requestId: s.requestId,
713
713
  effectId: g,
714
714
  fingerprint: h,
@@ -720,7 +720,7 @@ function Kr(t, e, s, n) {
720
720
  status: v ? "queued" : "pending",
721
721
  error: null,
722
722
  result: null
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 } });
723
+ }, a({ pending: _, 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 };
@@ -743,7 +743,7 @@ function Kr(t, e, s, n) {
743
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 [I, k] of Object.entries(i.pending)) k.mode === "query" && k.status === "queued" && c(k.operation, p) && l(I);
746
+ else for (const [I, _] of Object.entries(i.pending)) _.mode === "query" && _.status === "queued" && c(_.operation, p) && d(I);
747
747
  }
748
748
  }
749
749
  return { state: i, effects: r };
@@ -865,98 +865,98 @@ function js(t, e, s) {
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 = (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 });
868
+ const c = (f, b) => {
869
+ const y = { ...n.features.contextObservers }, w = y[f];
870
+ if (b === null ? delete y[f] : y[f] = ue(o, { kind: "originContext", clientScopeId: f, origin: b, pageUrl: "" }), r({ contextObservers: y }), !w || Object.values(y).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 }, O = E[w]?.origin, k = { ...n.features.contextRunOrigins };
872
+ for (const [x, U] of Object.entries(k)) U === O && delete k[x];
873
+ delete R[w], delete T[w], delete C[w], delete E[w];
874
+ for (const [x, U] of Object.entries(q)) U.mode === "query" && U.key === w && delete q[x];
875
+ r({ queries: R, polls: T, contextReads: C, originContextQueries: E, contextRunOrigins: k, pending: q });
876
876
  };
877
877
  if (e.type === "stage7.account_fallback") return { state: { ...n, account: {
878
878
  ...n.account,
879
879
  paidFallbackBySession: { ...n.account.paidFallbackBySession, [e.sessionId]: e.enabled }
880
880
  } }, effects: i };
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
- if (d && Li(d)) {
883
- et(o, d);
884
- const f = Kr(n.features, o, e, (y) => ue(o, y));
881
+ const l = 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
+ if (l && Li(l)) {
883
+ et(o, l);
884
+ const f = Kr(n.features, o, e, (b) => ue(o, b));
885
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
888
  const f = Vr(n, e, s.conversation, s.directory);
889
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;
890
+ const b = js(f.state, f.command, s);
891
+ return { state: b.state, effects: [...f.effects, ...b.effects] };
892
+ }
893
+ const d = (f, b, y) => {
894
+ const w = f === "notifications" ? "canRequestNotificationPermission" : "canGroupSessionTabs";
895
+ if (!J(o.profile, w) || Qe(n, f) !== !0 || n.features.desiredPreferences[f] === !1 || Object.values(n.interactions.devicePending).some((C) => C.feature === f && (b === "check" || C.action !== "check"))) return;
896
+ const R = Se(o, "device", y), T = { ...n.interactions.deviceErrors };
897
+ delete T[f], a({ deviceErrors: T, devicePending: { ...n.interactions.devicePending, [R]: { feature: f, requestId: y, generation: o.generation, desired: !0, action: b } } }), i.push({ kind: "stage7.device", id: R, input: { authority: o, requestId: y, feature: f, action: b, now: n.features.now } });
898
+ }, u = (f, b) => {
899
+ const y = b ? n.interactions.promptActions[b.replace(/:ack$/, "")] : void 0, w = { ...n.interactions.openings };
900
+ for (const [R, T] of Object.entries(w)) {
901
+ if (y?.scope === R && y.openingGeneration === T.generation && ["enable", "allow"].includes(y.action)) continue;
902
902
  const C = { ...T.shown };
903
- delete C[f], _[R] = {
903
+ delete C[f], w[R] = {
904
904
  ...T,
905
905
  shown: C,
906
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: _ });
910
- }, p = (f, y = null) => {
909
+ a({ openings: w });
910
+ }, p = (f, b = null) => {
911
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);
912
+ for (const y of ["notifications", "tab_grouping"]) {
913
+ const w = y === "notifications" ? "taskNotificationsEnabled" : "tabGroupingEnabled";
914
+ f.value[w] !== n.account.preferences[w] && u(y, b);
915
915
  }
916
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);
917
+ for (const y of ["notifications", "tab_grouping"]) {
918
+ const w = f.kind === "preferencePrompts" ? f.value[y] : f.feature === y ? f.value : null;
919
+ w && w.revision > n.interactions.preferencePrompts[y].revision && u(y, w.requestId);
920
920
  }
921
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) => {
922
+ }, g = (f, b) => {
923
+ const y = n.interactions.deviceFacts[f];
924
+ b.revision <= y.revision || (Qe(n, f) === !0 && (b.permission === "granted" && y.permission !== "granted" || b.snoozedUntil && b.snoozedUntil !== y.snoozedUntil) && u(f, null), a({ deviceFacts: { ...n.interactions.deviceFacts, [f]: b } }));
925
+ }, m = (f, b, y = !1) => {
926
926
  et(o, f);
927
- const _ = ue(o, f), R = Se(o, "query", y);
927
+ const w = ue(o, f), R = Se(o, "query", b);
928
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;
929
+ const q = n.features.queries[w], O = n.features.contextReads[w];
930
+ if (r({ originContextQueries: { ...n.features.originContextQueries, [w]: f } }), !y && (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
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
- requestId: y,
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(b), mode: "replace" });
936
+ r({ queries: { ...n.features.queries, [w]: E }, pending: { ...n.features.pending, [R]: {
937
+ requestId: b,
938
938
  effectId: R,
939
939
  fingerprint: JSON.stringify(f),
940
- key: _,
940
+ key: w,
941
941
  generation: o.generation,
942
942
  operation: f,
943
943
  mode: "query",
944
944
  status: "pending",
945
945
  error: null,
946
946
  result: null
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) => {
947
+ } } }), f.kind === "account" && (n = { ...n, account: { ...n.account, query: De(n.account.query, { key: w, requestId: re(b), mode: "replace" }) } }), i.push({ kind: "stage7.query", id: R, input: { authority: o, requestId: b, query: f } });
948
+ }, h = (f, b, y = !1) => {
949
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[_];
950
+ const w = Se(o, "mutate", b), R = JSON.stringify(f), T = n.features.pending[w];
951
951
  if (T) {
952
952
  if (T.fingerprint !== R) throw new Error("Request ID was reused with a different payload.");
953
- if (!b || T.status !== "error") return;
953
+ if (!y || T.status !== "error") return;
954
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
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
958
  const C = n.features.queuedPreferences[f.feature];
959
- if (C && C.requestId !== y) {
959
+ if (C && C.requestId !== b) {
960
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,
@@ -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, [f.feature]: { requestId: y, enabled: f.enabled } } });
974
+ r({ queuedPreferences: { ...n.features.queuedPreferences, [f.feature]: { requestId: b, enabled: f.enabled } } });
975
975
  return;
976
976
  }
977
977
  if (f.kind === "generatePrompts") {
978
978
  const C = { kind: "starterPrompts", ...f.page, includeUserSuggestions: f.includeUserSuggestions ?? !1 }, E = ue(o, C), q = n.features.queries[E] ?? me(E);
979
- r({ queries: { ...n.features.queries, [E]: De(q, { key: E, requestId: re(y), mode: "replace" }) } });
979
+ r({ queries: { ...n.features.queries, [E]: De(q, { key: E, requestId: re(b), mode: "replace" }) } });
980
980
  }
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 } });
981
+ r({ pending: { ...n.features.pending, [w]: { requestId: b, effectId: w, fingerprint: R, key: Ln(f), generation: o.generation, operation: f, mode: "mutation", status: "pending", error: null, result: null } } }), i.push({ kind: "stage7.mutate", id: w, input: { authority: o, requestId: b, mutation: f } });
982
982
  }, v = (f) => {
983
983
  if (!(!J(o.profile, "canManagePreferences") || n.features.refreshBatch)) {
984
- for (const y of Object.values(n.features.pending))
985
- y.mode === "mutation" && y.operation.kind === "preferenceAcknowledge" && y.status === "error" && !["conflict", "409"].includes(y.error?.code ?? "") && h(y.operation, y.requestId, !0);
986
- for (const y of ["account", "preferences", "preferencePrompts", "decisions"])
987
- Object.values(n.features.pending).some((b) => b.mode === "query" && b.status === "pending" && b.operation.kind === y) || m({ kind: y }, `${f}:${y}`);
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
- }
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 } });
984
+ for (const b of Object.values(n.features.pending))
985
+ b.mode === "mutation" && b.operation.kind === "preferenceAcknowledge" && b.status === "error" && !["conflict", "409"].includes(b.error?.code ?? "") && h(b.operation, b.requestId, !0);
986
+ for (const b of ["account", "preferences", "preferencePrompts", "decisions"])
987
+ Object.values(n.features.pending).some((y) => y.mode === "query" && y.status === "pending" && y.operation.kind === b) || m({ kind: b }, `${f}:${b}`);
988
+ r({ refreshAt: null, refreshBatch: { pending: Object.values(n.features.pending).filter((b) => b.mode === "query" && b.status === "pending" && ["account", "preferences", "preferencePrompts", "decisions"].includes(b.operation.kind)).map((b) => b.effectId), failed: !1 } });
989
+ }
990
+ }, I = (f, b) => {
991
+ const y = n.features.refreshBatch;
992
+ if (y?.pending.includes(f)) {
993
+ const w = y.pending.filter((T) => T !== f), R = y.failed || b;
994
+ if (w.length) r({ refreshBatch: { pending: w, 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) });
@@ -1004,20 +1004,20 @@ function js(t, e, s) {
1004
1004
  case "stage7.account_refusal": {
1005
1005
  const f = Ot(void 0, e.code);
1006
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)) {
1007
+ const b = { ...n.features.queries }, y = { ...n.features.pending }, w = [];
1008
+ for (const [R, T] of Object.entries(y)) {
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
- b[R] = { ...T, status: "error", error: C }, _.push(R);
1012
- const E = y[T.key];
1013
- E && (y[T.key] = ct(E, { key: T.key, requestId: re(T.requestId), error: C }));
1011
+ y[R] = { ...T, status: "error", error: C }, w.push(R);
1012
+ const E = b[T.key];
1013
+ E && (b[T.key] = ct(E, { key: T.key, requestId: re(T.requestId), error: C }));
1014
1014
  }
1015
- n = { ...n, features: { ...n.features, pending: b, queries: y }, account: {
1015
+ n = { ...n, features: { ...n.features, pending: y, queries: b }, account: {
1016
1016
  ...n.account,
1017
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 _) I(R, !0);
1020
+ for (const R of w) 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 f = ue(o, e.query), y = { ...n.features.contextReads };
1029
- delete y[f], r({ contextReads: y });
1028
+ const f = ue(o, e.query), b = { ...n.features.contextReads };
1029
+ delete b[f], r({ contextReads: b });
1030
1030
  }
1031
1031
  m(e.query, e.requestId, e.force);
1032
1032
  break;
@@ -1042,7 +1042,7 @@ function js(t, e, s) {
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 f = Object.values(n.features.pending).some((y) => y.mode === "query" && y.status === "pending" && ["account", "preferences", "preferencePrompts", "decisions"].includes(y.operation.kind));
1045
+ const f = Object.values(n.features.pending).some((b) => b.mode === "query" && b.status === "pending" && ["account", "preferences", "preferencePrompts", "decisions"].includes(b.operation.kind));
1046
1046
  r({ refreshRequired: !0, refreshQueuedRequestId: f ? `after:${e.requestId}` : n.features.refreshQueuedRequestId });
1047
1047
  }
1048
1048
  v(e.requestId);
@@ -1056,30 +1056,30 @@ 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 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
- a({ ...e.checkpoint, openings: y, openingGeneration: Math.max(n.interactions.openingGeneration, e.checkpoint.openingGeneration) });
1059
+ const f = new Set(Object.values(s.directory.clients)), b = Object.fromEntries(Object.entries(e.checkpoint.openings).filter(([y, w]) => f.has(y) && s.directory.selections[y]?.sessionId === w.sessionId));
1060
+ a({ ...e.checkpoint, openings: b, openingGeneration: Math.max(n.interactions.openingGeneration, e.checkpoint.openingGeneration) });
1061
1061
  break;
1062
1062
  }
1063
1063
  case "stage7.prompt_view": {
1064
1064
  const f = s.directory.clients[e.clientScopeId];
1065
1065
  if (!f) break;
1066
- const y = { ...n.interactions.openings };
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);
1066
+ const b = { ...n.interactions.openings };
1067
+ e.open || delete b[f], a({ openings: b, 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 f = s.directory.clients[e.clientScopeId], y = n.interactions.openings[f];
1072
- if (!y || y.generation !== e.openingGeneration) break;
1073
- const b = Ci(n, f, e.feature);
1074
- b && a({ openings: { ...n.interactions.openings, [f]: { ...y, shown: { ...y.shown, [e.feature]: b } } } });
1071
+ const f = s.directory.clients[e.clientScopeId], b = n.interactions.openings[f];
1072
+ if (!b || b.generation !== e.openingGeneration) break;
1073
+ const y = Ci(n, f, e.feature);
1074
+ y && a({ openings: { ...n.interactions.openings, [f]: { ...b, shown: { ...b.shown, [e.feature]: y } } } });
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
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 } } });
1080
+ for (const [b, y] of Object.entries(f)) {
1081
+ const w = y.turns[e.userMessageId];
1082
+ y.sessionId === e.sessionId && w && !w.tab_groupingSuppressed && (f[b] = { ...y, turns: { ...y.turns, [e.userMessageId]: { ...w, tab_grouping: !0 } } });
1083
1083
  }
1084
1084
  a({ openings: f });
1085
1085
  break;
@@ -1088,7 +1088,7 @@ function js(t, e, s) {
1088
1088
  if (Qe(n, e.feature) !== !0) throw new Error("Permission setup requires a saved On preference.");
1089
1089
  const f = n.interactions.deviceFacts[e.feature].snoozedUntil;
1090
1090
  if (!e.settings && f && Date.parse(f) > e.now) break;
1091
- l(e.feature, e.action, e.requestId);
1091
+ d(e.feature, e.action, e.requestId);
1092
1092
  break;
1093
1093
  }
1094
1094
  case "stage7.device_fact":
@@ -1101,28 +1101,28 @@ function js(t, e, s) {
1101
1101
  case "stage7.device_hints": {
1102
1102
  if (o.profile !== "main_web_chat") throw new Error("Main-web hints unavailable.");
1103
1103
  const f = { ...n.interactions.deviceHints };
1104
- for (const [y, b] of Object.entries(e.hints)) f[y] = f[y] === !0 || b;
1104
+ for (const [b, y] of Object.entries(e.hints)) f[b] = f[b] === !0 || y;
1105
1105
  a({ deviceHints: f });
1106
1106
  break;
1107
1107
  }
1108
1108
  case "stage7.local_sharing": {
1109
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);
1110
+ for (const [b, y] of Object.entries(e.decisions))
1111
+ (!f[b] || y.revision > f[b].revision) && (f[b] = y);
1112
1112
  a({ localSharing: f, localSharingReady: !0 });
1113
1113
  break;
1114
1114
  }
1115
1115
  case "stage7.sources": {
1116
1116
  const f = { ...n.interactions.sources };
1117
- for (const y of e.sources) {
1118
- if (!Number.isSafeInteger(y.version) || y.version < 0) throw new Error("Invalid source version.");
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
- ...y,
1124
- lifecycle: _?.lifecycle === "completed" ? "completed" : y.lifecycle,
1125
- payload: _?.payload.kind === "sharing" && y.payload.kind === "sharing" ? { ...y.payload, variant: _.payload.variant } : y.payload
1117
+ for (const b of e.sources) {
1118
+ if (!Number.isSafeInteger(b.version) || b.version < 0) throw new Error("Invalid source version.");
1119
+ const y = JSON.stringify([b.conversation_id, b.id]), w = f[y];
1120
+ if (!(w && w.version >= b.version)) {
1121
+ if (w && w.payload.kind !== b.payload.kind) throw new Error("Interaction source changed category.");
1122
+ f[y] = {
1123
+ ...b,
1124
+ lifecycle: w?.lifecycle === "completed" ? "completed" : b.lifecycle,
1125
+ payload: w?.payload.kind === "sharing" && b.payload.kind === "sharing" ? { ...b.payload, variant: w.payload.variant } : b.payload
1126
1126
  };
1127
1127
  }
1128
1128
  }
@@ -1135,12 +1135,12 @@ function js(t, e, s) {
1135
1135
  break;
1136
1136
  case "stage7.morning": {
1137
1137
  if (!e.text?.trim()) {
1138
- const b = { ...n.interactions.welcome };
1139
- delete b[e.id], a({ welcome: b });
1138
+ const y = { ...n.interactions.welcome };
1139
+ delete y[e.id], a({ welcome: y });
1140
1140
  break;
1141
1141
  }
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
- a({ welcome: { ...n.interactions.welcome, [e.id]: { id: e.id, text: e.text, tasks: e.tasks, category: "morning_report", eligible: y } } });
1142
+ const f = e.signupAgeDays, b = e.retained === !0 || e.localHour >= 5 && e.lastShownDate !== e.localDate && (f === 1 || f === 3 || f === 5 || f >= 7 && f % 7 === 0);
1143
+ a({ welcome: { ...n.interactions.welcome, [e.id]: { id: e.id, text: e.text, tasks: e.tasks, category: "morning_report", eligible: b } } });
1144
1144
  break;
1145
1145
  }
1146
1146
  case "stage7.welcome":
@@ -1150,8 +1150,8 @@ function js(t, e, s) {
1150
1150
  if (!J(o.profile, "canStartDeepFlow")) throw new Error("Deep flow unavailable.");
1151
1151
  const f = n.features.deepFlows[e.clientScopeId];
1152
1152
  if ((f?.id ?? null) !== e.expectedId || f && e.flow && e.flow.id !== f.id || e.flow && f && f.status !== "running") break;
1153
- const y = { ...n.features.deepFlows };
1154
- e.flow ? y[e.clientScopeId] = e.flow : delete y[e.clientScopeId], r({ deepFlows: y });
1153
+ const b = { ...n.features.deepFlows };
1154
+ e.flow ? b[e.clientScopeId] = e.flow : delete b[e.clientScopeId], r({ deepFlows: b });
1155
1155
  break;
1156
1156
  }
1157
1157
  case "effect.completed":
@@ -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 [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);
1163
+ for (const [y, 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 === y && T.status === "pending") || m(w.query.kind === "originContext" ? { ...w.query, trigger: "poll" } : w.query, `poll:${y}:${e.output.now}`, !0);
1166
1166
  const R = { ...n.features.polls };
1167
- delete R[b], r({ polls: R });
1167
+ delete R[y], 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 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({
1174
+ const y = n.interactions.devicePending[e.effectId];
1175
+ if (!y) break;
1176
+ const w = { ...n.interactions.devicePending };
1177
+ if (delete w[e.effectId], a({ devicePending: w }), e.type === "effect.completed") {
1178
+ if (y.action !== "check" && n.interactions.promptActions[y.requestId] && !n.features.pending[Se(o, "mutate", `${y.requestId}:ack`)]) {
1179
+ const R = n.interactions.promptActions[y.requestId];
1180
+ u(R.feature, y.requestId), h({
1181
1181
  kind: "preferenceAcknowledge",
1182
1182
  feature: R.feature,
1183
1183
  action: R.action,
1184
1184
  expectedRevision: R.expectedRevision
1185
- }, `${b.requestId}:ack`);
1185
+ }, `${y.requestId}:ack`);
1186
1186
  }
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 } });
1187
+ g(y.feature, e.output.fact);
1188
+ } else Qe(n, y.feature) === !0 && n.features.desiredPreferences[y.feature] !== !1 && a({ deviceErrors: { ...n.interactions.deviceErrors, [y.feature]: e.error } });
1189
1189
  break;
1190
1190
  }
1191
1191
  const f = n.features.pending[e.effectId];
1192
1192
  if (!f || f.status !== "pending" || f.generation !== o.generation) break;
1193
- const y = e.type === "effect.failed";
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;
1193
+ const b = e.type === "effect.failed";
1194
+ if (r({ pending: { ...n.features.pending, [e.effectId]: { ...f, status: b ? "error" : "done", error: b ? e.error : null, result: b ? null : e.output.data } } }), f.mode === "query") {
1195
+ const y = { ...n.features.pending };
1196
+ delete y[e.effectId], r({ pending: y });
1197
+ const w = n.features.queries[f.key];
1198
+ if (!w || w.requestId !== f.requestId) break;
1199
1199
  if (["originContext", "userContext", "contextRun"].includes(f.operation.kind)) {
1200
1200
  const R = { ...n.features.polls };
1201
1201
  delete R[f.key], r({ polls: R, contextReads: { ...n.features.contextReads, [f.key]: {
1202
- settledAt: y ? n.features.now : e.output.completedAt,
1203
- failures: y ? (n.features.contextReads[f.key]?.failures ?? 0) + 1 : 0
1202
+ settledAt: b ? n.features.now : e.output.completedAt,
1203
+ failures: b ? (n.features.contextReads[f.key]?.failures ?? 0) + 1 : 0
1204
1204
  } } });
1205
1205
  }
1206
- if (y)
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 }) } });
1206
+ if (b)
1207
+ r({ queries: { ...n.features.queries, [f.key]: ct(w, { 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
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 }) } });
1210
+ r({ now: e.output.completedAt, queries: { ...n.features.queries, [f.key]: Zt(w, { 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
- } else if (!y)
1212
+ } else if (!b)
1213
1213
  r({ now: e.output.completedAt }), p(e.output.data, f.requestId);
1214
1214
  else if (["conflict", "409"].includes(e.error.code)) {
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}`);
1215
+ const y = f.operation.kind === "decision" ? "decisions" : f.operation.kind === "preferenceSnooze" || f.operation.kind === "preferenceAcknowledge" ? "preferencePrompts" : "preferences";
1216
+ m({ kind: y }, `conflict:${f.requestId}`);
1217
1217
  }
1218
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({
1219
+ const y = { ...n.interactions.actions };
1220
+ for (const [w, R] of Object.entries(y))
1221
+ R.step === "persist" && f.requestId === `sharing:${w}` && (R.operation.kind === "copy" || R.operation.kind === "share") && (y[w] = { ...R, status: b ? "error" : "done", error: b ? e.error : null });
1222
+ a({ actions: y });
1223
+ }
1224
+ if (!b && f.mode === "mutation" && f.operation.kind === "preference" && n.interactions.promptActions[f.requestId]) {
1225
+ const y = n.interactions.promptActions[f.requestId];
1226
+ u(y.feature, f.requestId), h({
1227
1227
  kind: "preferenceAcknowledge",
1228
- feature: b.feature,
1229
- action: b.action,
1230
- expectedRevision: b.expectedRevision
1228
+ feature: y.feature,
1229
+ action: y.action,
1230
+ expectedRevision: y.expectedRevision
1231
1231
  }, `${f.requestId}:ack`);
1232
1232
  }
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 }) } });
1233
+ if (I(e.effectId, b), f.operation.kind === "generatePrompts") {
1234
+ const y = { kind: "starterPrompts", ...f.operation.page, includeUserSuggestions: f.operation.includeUserSuggestions ?? !1 }, w = ue(o, y), R = n.features.queries[w];
1235
+ R?.requestId === f.requestId && r({ queries: { ...n.features.queries, [w]: b ? ct(R, { key: w, requestId: re(f.requestId), error: e.error }) : Zt(R, { key: w, requestId: re(f.requestId), data: e.output.data, cursor: null, updatedAt: e.output.completedAt }) } });
1236
1236
  }
1237
- if (!y && e.output.data.kind === "originContext") {
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]: _ } });
1237
+ if (!b && e.output.data.kind === "originContext") {
1238
+ const y = e.output.data, w = f.operation.kind === "originContext" || f.operation.kind === "refreshContext" ? f.operation.origin : null;
1239
+ if (w) {
1240
+ if (y.value.runId && ["queued", "pending", "running", "in_progress", "stopping", "cancel_requested"].includes(y.value.status))
1241
+ r({ contextRunOrigins: { ...n.features.contextRunOrigins, [y.value.runId]: w } });
1242
1242
  else {
1243
1243
  const R = { ...n.features.contextRunOrigins };
1244
- for (const [T, C] of Object.entries(R)) C === _ && delete R[T];
1244
+ for (const [T, C] of Object.entries(R)) C === w && delete R[T];
1245
1245
  r({ contextRunOrigins: R });
1246
1246
  }
1247
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
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 });
1250
+ if (O.origin === w) {
1251
+ R[q] = { ...R[q], data: y, status: "ready", error: null, requestId: null, updatedAt: e.output.completedAt }, C[q] = { settledAt: e.output.completedAt, failures: 0 }, delete E[q];
1252
+ for (const [k, x] of Object.entries(T)) x.mode === "query" && x.key === q && delete T[k];
1253
+ ["queued", "pending", "running", "in_progress", "stopping", "cancel_requested"].includes(y.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
- if (!y && e.output.data.kind === "contextRun" && !["queued", "pending", "running", "in_progress", "stopping", "cancel_requested"].includes(e.output.data.value.status)) {
1260
- const b = e.output.data.value.runId, _ = b ? n.features.contextRunOrigins[b] : null;
1261
- if (_ && b) {
1259
+ if (!b && e.output.data.kind === "contextRun" && !["queued", "pending", "running", "in_progress", "stopping", "cancel_requested"].includes(e.output.data.value.status)) {
1260
+ const y = e.output.data.value.runId, w = y ? n.features.contextRunOrigins[y] : null;
1261
+ if (w && y) {
1262
1262
  const R = { ...n.features.contextRunOrigins };
1263
- delete R[b], r({ contextRunOrigins: R });
1263
+ delete R[y], r({ contextRunOrigins: R });
1264
1264
  for (const [T, C] of Object.entries(n.features.originContextQueries)) {
1265
- if (C.origin !== _) continue;
1265
+ if (C.origin !== w) continue;
1266
1266
  const E = { ...n.features.pending };
1267
1267
  for (const [q, O] of Object.entries(E)) O.mode === "query" && O.key === T && delete E[q];
1268
1268
  r({ pending: E }), m({ ...C, kind: "originContext" }, `context-final:${f.requestId}:${T}`, !0);
1269
1269
  }
1270
1270
  }
1271
1271
  }
1272
- if (!y && ["originContext", "userContext", "contextRun"].includes(e.output.data.kind)) {
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 } } });
1272
+ if (!b && ["originContext", "userContext", "contextRun"].includes(e.output.data.kind)) {
1273
+ const y = e.output.data;
1274
+ if (y.kind === "originContext" || y.kind === "userContext" || y.kind === "contextRun") {
1275
+ const w = y.kind === "originContext" ? f.mode === "query" && f.operation.kind === "originContext" && Object.values(n.features.contextObservers).includes(f.key) ? f.operation : null : y.kind === "userContext" ? { kind: "userContext" } : y.value.runId ? { kind: "contextRun", runId: y.value.runId } : null;
1276
+ if (w && ["queued", "pending", "running", "in_progress", "stopping", "cancel_requested"].includes(y.value.status)) {
1277
+ const R = ue(o, w);
1278
+ r({ polls: { ...n.features.polls, [R]: { query: w, deadline: n.features.now + 5e3 } } });
1279
1279
  }
1280
1280
  }
1281
1281
  }
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;
1282
+ if (!b && f.operation.kind === "stopContext")
1283
+ for (const [y, w] of Object.entries(n.features.originContextQueries)) {
1284
+ const R = n.features.queries[y]?.data;
1285
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 === b && delete T[C];
1288
- r({ pending: T }), m({ ..._, kind: "originContext" }, `context-stop:${f.requestId}:${b}`, !0);
1287
+ for (const [C, E] of Object.entries(T)) E.mode === "query" && E.key === y && delete T[C];
1288
+ r({ pending: T }), m({ ...w, kind: "originContext" }, `context-stop:${f.requestId}:${y}`, !0);
1289
1289
  }
1290
1290
  }
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) } } });
1291
+ if (b && f.mode === "query" && ["originContext", "userContext", "contextRun"].includes(f.operation.kind) && e.error.retryable && (n.features.contextReads[f.key]?.failures ?? 0) <= 3) {
1292
+ const y = f.operation, w = ue(o, y);
1293
+ r({ polls: { ...n.features.polls, [w]: { query: y, deadline: n.features.now + 5e3 * (n.features.contextReads[f.key]?.failures ?? 1) } } });
1294
1294
  }
1295
1295
  if (f.operation.kind === "preference") {
1296
- const b = f.operation.feature, _ = n.features.queuedPreferences[b];
1297
- if (_) {
1296
+ const y = f.operation.feature, w = n.features.queuedPreferences[y];
1297
+ if (w) {
1298
1298
  const R = { ...n.features.queuedPreferences };
1299
- delete R[b], r({ queuedPreferences: R }), h({ kind: "preference", feature: b, enabled: _.enabled }, _.requestId);
1299
+ delete R[y], r({ queuedPreferences: R }), h({ kind: "preference", feature: y, enabled: w.enabled }, w.requestId);
1300
1300
  } else {
1301
1301
  const R = { ...n.features.desiredPreferences };
1302
- delete R[b], r({ desiredPreferences: R });
1302
+ delete R[y], r({ desiredPreferences: R });
1303
1303
  }
1304
1304
  }
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 });
1305
+ if (!b && e.output.data.kind === "preferences") for (const y of ["notifications", "tab_grouping"]) d(y, "check", `preference:${f.requestId}:${y}`);
1306
+ n.features.refreshRequired && !n.features.refreshBatch && !n.features.refreshQueuedRequestId && ["account", "preferences", "preferencePrompts", "decisions"].every((y) => Object.values(n.features.queries).some((w) => w.data?.kind === y && w.status === "ready")) && r({ refreshRequired: !1 });
1307
1307
  break;
1308
1308
  }
1309
1309
  }
1310
- const k = [
1310
+ const _ = [
1311
1311
  n.features.refreshAt,
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)),
1312
+ ...Object.values(n.interactions.openings).flatMap((f) => Object.values(f.turns).filter((b) => b.active && !b.notifications && !b.notificationsSuppressed).map((b) => b.startedAt + 1e4)),
1313
1313
  ...Object.values(n.interactions.welcome).map((f) => f.eligible ? f.expiresAt ?? null : null),
1314
1314
  ...Object.values(n.interactions.sources).map((f) => f.lifecycle === "pending" && f.payload.kind === "integration_auth" ? Date.parse(f.payload.expires_at) : null),
1315
1315
  ...Object.values(n.features.polls).map((f) => f.deadline),
1316
1316
  ...Object.values(n.interactions.decisions).map((f) => f.nextEligibleAt ? Date.parse(f.nextEligibleAt) : null),
1317
1317
  ...Object.values(n.interactions.preferencePrompts).map((f) => f.snoozedUntil ? Date.parse(f.snoozedUntil) : null),
1318
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 } });
1319
+ ].filter((f) => f !== null && f > n.features.now), S = _.length ? Math.min(..._) : null;
1320
+ if (S !== n.features.timerDeadline && !n.features.schedulerError) {
1321
+ const f = n.features.timerRevision + 1, b = S === null ? null : Se(o, "wait", `${f}:${S}`);
1322
+ r({ timerId: b, timerDeadline: S, timerRevision: f }), S !== null && b && i.push({ kind: "stage7.wait", id: b, input: { authority: o, deadline: S } });
1323
1323
  }
1324
1324
  return { state: n, effects: i };
1325
1325
  }
@@ -1521,7 +1521,7 @@ function Yr(t) {
1521
1521
  return {
1522
1522
  "stage7.query": async ({ authority: s, query: n, requestId: i }) => {
1523
1523
  e(s), et(s, n);
1524
- const r = s.profile.startsWith("embedded_"), a = (c, d = {}) => t.http.request(c, d, void 0, "GET", r ? "embed" : "runtime");
1524
+ const r = s.profile.startsWith("embedded_"), a = (c, l = {}) => t.http.request(c, l, void 0, "GET", r ? "embed" : "runtime");
1525
1525
  let o;
1526
1526
  switch (n.kind) {
1527
1527
  case "account":
@@ -1558,9 +1558,9 @@ function Yr(t) {
1558
1558
  }
1559
1559
  case "originContext": {
1560
1560
  const c = { requestId: i, origin: n.origin, trigger: n.trigger ?? "page" };
1561
- t.onContextStatusRead?.({ ...c, phase: "started" }), o = await a("/context/status", { origin: n.origin, community_id: s.communityId }).then((d) => He("originContext", d)).then((d) => (t.onContextStatusRead?.({ ...c, phase: "ready" }), d), (d) => {
1562
- const l = Y(d);
1563
- throw t.onContextStatusRead?.({ ...c, phase: "failed", code: l.code, retryable: l.retryable }), d;
1561
+ t.onContextStatusRead?.({ ...c, phase: "started" }), o = await a("/context/status", { origin: n.origin, community_id: s.communityId }).then((l) => He("originContext", l)).then((l) => (t.onContextStatusRead?.({ ...c, phase: "ready" }), l), (l) => {
1562
+ const d = Y(l);
1563
+ throw t.onContextStatusRead?.({ ...c, phase: "failed", code: d.code, retryable: d.retryable }), l;
1564
1564
  });
1565
1565
  break;
1566
1566
  }
@@ -1581,7 +1581,7 @@ function Yr(t) {
1581
1581
  },
1582
1582
  "stage7.mutate": async ({ authority: s, mutation: n, requestId: i }) => {
1583
1583
  e(s), et(s, n);
1584
- const r = s.profile.startsWith("embedded_"), a = (c, d, l = "POST", u = {}) => t.http.request(c, u, d, l, r ? "embed" : "runtime", { readOnly: !1 });
1584
+ const r = s.profile.startsWith("embedded_"), a = (c, l, d = "POST", u = {}) => t.http.request(c, u, l, d, r ? "embed" : "runtime", { readOnly: !1 });
1585
1585
  let o;
1586
1586
  switch (n.kind) {
1587
1587
  case "preference":
@@ -1631,9 +1631,9 @@ function Yr(t) {
1631
1631
  break;
1632
1632
  }
1633
1633
  case "refreshContext": {
1634
- const c = N(await a("/context/refresh", { origin: n.origin, community_id: n.communityId })), d = He("originContext", c.status);
1635
- if (d.kind !== "originContext") throw new Error("Invalid origin context result.");
1636
- o = { ...d, value: { ...d.value, runId: P(c.runId), status: c.queued === !0 ? "queued" : d.value.status } };
1634
+ const c = N(await a("/context/refresh", { origin: n.origin, community_id: n.communityId })), l = He("originContext", c.status);
1635
+ if (l.kind !== "originContext") throw new Error("Invalid origin context result.");
1636
+ o = { ...l, value: { ...l.value, runId: P(c.runId), status: c.queued === !0 ? "queued" : l.value.status } };
1637
1637
  break;
1638
1638
  }
1639
1639
  case "refreshUserContext":
@@ -1689,7 +1689,7 @@ function eo(t, e) {
1689
1689
  a,
1690
1690
  r.directory.clients,
1691
1691
  r.directory.selections,
1692
- Object.entries(r.conversation.sessions).map(([c, d]) => [c, d.execution])
1692
+ Object.entries(r.conversation.sessions).map(([c, l]) => [c, l.execution])
1693
1693
  ]);
1694
1694
  s !== o && (s = o, t.engine.dispatch({ type: "stage7.observe_work", authority: a, now: e() }));
1695
1695
  }, i = t.engine.subscribe(n);
@@ -1709,11 +1709,11 @@ function Fi(t, e, s) {
1709
1709
  if (!n || t.isDisposed) return Promise.reject(new Error("Product Agent is not authenticated."));
1710
1710
  const r = (e.type === "stage7.mutate" && ["generatePrompts", "sampleStyle"].includes(e.mutation.kind) ? Object.values(t.engine.getState().slices.features.pending).find((a) => a.status === "pending" && a.mode === "mutation" && a.fingerprint === JSON.stringify(e.mutation)) : null)?.requestId ?? crypto.randomUUID();
1711
1711
  return new Promise((a, o) => {
1712
- let c = !1, d = !1, l = () => {
1712
+ let c = !1, l = !1, d = () => {
1713
1713
  }, u = () => {
1714
1714
  };
1715
1715
  const p = (m, h) => {
1716
- d || (d = !0, l(), u(), m ? o(m) : a(h));
1716
+ l || (l = !0, d(), u(), m ? o(m) : a(h));
1717
1717
  }, g = () => {
1718
1718
  if (!c) return;
1719
1719
  const m = t.engine.getState().slices;
@@ -1732,7 +1732,7 @@ 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(g), u = t.onDispose(() => p(new Error("Feature runtime disposed."))), t.engine.dispatch({ ...e, authority: n, requestId: r, now: Date.now() }).then(() => {
1735
+ d = 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
1736
  c = !0, g();
1737
1737
  }, (m) => p(m));
1738
1738
  });
@@ -1742,11 +1742,11 @@ async function no(t, e, s = crypto.randomUUID()) {
1742
1742
  if (!n || t.isDisposed) throw new Error("Product Agent is not authenticated.");
1743
1743
  const i = Object.entries(t.engine.getState().slices.interactions.actions).find(([, a]) => a.clientScopeId === e.clientScopeId && a.sourceVersion === (e.expectedSourceVersion ?? null) && a.interactionId === e.interactionId && a.action === e.action && a.expectedRevision === e.expectedRevision && a.status === "error" && a.step === "persist"), r = i?.[0] ?? s;
1744
1744
  await new Promise((a, o) => {
1745
- let c = !1, d = !1, l = () => {
1745
+ let c = !1, l = !1, d = () => {
1746
1746
  }, u = () => {
1747
1747
  };
1748
1748
  const p = (h) => {
1749
- d || (d = !0, l(), u(), h ? o(h) : a());
1749
+ l || (l = !0, d(), u(), h ? o(h) : a());
1750
1750
  }, g = () => {
1751
1751
  if (!c) return;
1752
1752
  const h = t.engine.getState().slices;
@@ -1756,16 +1756,16 @@ 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 I = Object.values(h.features.pending).find((w) => w.requestId === r);
1759
+ const I = Object.values(h.features.pending).find((S) => S.requestId === r);
1760
1760
  if (I) {
1761
1761
  I.status === "error" ? p(I.error) : I.status === "done" && p();
1762
1762
  return;
1763
1763
  }
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);
1764
+ if (Object.values(h.interactions.devicePending).some((S) => S.requestId === r)) return;
1765
+ const _ = e.interactionId === "preference:notifications" ? "notifications" : e.interactionId === "preference:tab_grouping" ? "tab_grouping" : null;
1766
+ p(_ ? h.interactions.deviceErrors[_] : void 0);
1767
1767
  };
1768
- l = t.engine.subscribe(g), u = t.onDispose(() => p(new Error("Feature runtime disposed.")));
1768
+ d = 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
1771
  c = !0, g();
@@ -1774,10 +1774,10 @@ async function no(t, e, s = crypto.randomUUID()) {
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])), 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;
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", l = 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, d = l === "integration_connection" && a?.kind === "integration_auth" ? `Connect ${a.app_name}` : l === "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 ?? d ?? ""), 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
- kind: d,
1780
+ kind: l,
1781
1781
  category: i.category,
1782
1782
  scope: { level: i.conversationId ? "session" : "user", key: i.conversationId ?? t.account.authority.userId },
1783
1783
  payload: {
@@ -1791,7 +1791,7 @@ function io(t, e, s, n) {
1791
1791
  placement: i.placement,
1792
1792
  userMessageId: i.userMessageId,
1793
1793
  sourceVersion: i.sourceVersion,
1794
- presentation: { title: l, body: u, actionLabels: p },
1794
+ presentation: { title: d, body: u, actionLabels: p },
1795
1795
  eligible: !0,
1796
1796
  status: i.status,
1797
1797
  allowedActions: i.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.263", jt = {
1839
+ const ao = "0.1.265", 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) {
@@ -1948,10 +1948,10 @@ function Hs(t, e, s = !1) {
1948
1948
  if ((e.memberships[a.sessionId]?.members.length ?? 0) > 0) continue;
1949
1949
  const o = { ...i.requests };
1950
1950
  delete o[r];
1951
- const c = i.sessions[a.sessionId], d = c.queries[a.lane];
1951
+ const c = i.sessions[a.sessionId], l = c.queries[a.lane];
1952
1952
  i = { ...i, requests: o, sessions: { ...i.sessions, [c.sessionId]: {
1953
1953
  ...c,
1954
- queries: { ...c.queries, [a.lane]: { ...d, requestId: null, status: d.data === null ? "not_requested" : "ready" } }
1954
+ queries: { ...c.queries, [a.lane]: { ...l, requestId: null, status: l.data === null ? "not_requested" : "ready" } }
1955
1955
  } } };
1956
1956
  }
1957
1957
  return G(i);
@@ -1967,10 +1967,10 @@ function uo(t, e, s, n) {
1967
1967
  const o = t.requests[e.effectId];
1968
1968
  if (!o || e.effectKind !== "conversation.snapshot") return { state: t, effects: r };
1969
1969
  let c = t.sessions[o.sessionId];
1970
- const d = c.queries[o.lane];
1971
- if (d.requestId !== o.requestId) return { state: t, effects: r };
1972
- const l = e.type === "effect.failed" && Pi(e.error.code), u = e.type === "effect.failed" && Number(e.error.details?.successfulRequests ?? 0) > 0 ? null : c.historyRefreshFailure;
1973
- o.lane === "current" && (c = { ...c, historyRefreshFailure: l ? {
1970
+ const l = c.queries[o.lane];
1971
+ if (l.requestId !== o.requestId) return { state: t, effects: r };
1972
+ const d = e.type === "effect.failed" && Pi(e.error.code), u = e.type === "effect.failed" && Number(e.error.details?.successfulRequests ?? 0) > 0 ? null : c.historyRefreshFailure;
1973
+ o.lane === "current" && (c = { ...c, historyRefreshFailure: d ? {
1974
1974
  sessionId: o.sessionId,
1975
1975
  episodeId: u?.episodeId ?? `${t.generation}:${o.sessionId}:${o.requestId}`,
1976
1976
  consecutiveFailures: (u?.consecutiveFailures ?? 0) + 1,
@@ -1987,11 +1987,11 @@ function uo(t, e, s, n) {
1987
1987
  c = Fs(c, e.output.snapshot.execution), c = {
1988
1988
  ...c,
1989
1989
  ...o.lane === "current" ? { preparation: e.output.snapshot.preparation } : {},
1990
- queries: { ...c.queries, [o.lane]: { ...d, status: "loading", requestId: null, error: null } }
1990
+ queries: { ...c.queries, [o.lane]: { ...l, status: "loading", requestId: null, error: null } }
1991
1991
  };
1992
1992
  } else if (e.type === "effect.failed" || !e.output.snapshot.projection_ready)
1993
1993
  c = { ...c, ...o.lane === "current" ? { preparation: null } : {}, queries: { ...c.queries, [o.lane]: {
1994
- ...d,
1994
+ ...l,
1995
1995
  status: "error",
1996
1996
  requestId: null,
1997
1997
  error: e.type === "effect.failed" ? X(e.error) : e.output.snapshot.preparation === "failed" || e.output.snapshot.preparation === "disabled" ? { code: "history_preparation_failed", message: "We couldn’t prepare this conversation. Try loading it again.", retryable: !1 } : { code: "projection_not_ready", message: "This conversation isn’t available yet. Try loading it again.", retryable: !0 }
@@ -2012,14 +2012,14 @@ function uo(t, e, s, n) {
2012
2012
  }), m.interactions.some((I) => I.conversation_id !== m.conversation_id)) throw new Error("Interaction belongs to another conversation.");
2013
2013
  if (a = { authorityId: t.authorityId, generation: t.generation, sessionId: o.sessionId, sources: m.interactions }, m.execution.version === c.execution?.version)
2014
2014
  for (const I of o.acceptedUserMessageIds) {
2015
- const k = g[I];
2016
- k.executionVersion === null && (g = {
2015
+ const _ = g[I];
2016
+ _.executionVersion === null && (g = {
2017
2017
  ...g,
2018
- [I]: { ...k, executionVersion: m.execution.version }
2018
+ [I]: { ..._, executionVersion: m.execution.version }
2019
2019
  });
2020
2020
  }
2021
2021
  if (c = { ...c, queries: { ...c.queries, [o.lane]: {
2022
- ...d,
2022
+ ...l,
2023
2023
  status: "ready",
2024
2024
  requestId: null,
2025
2025
  error: null,
@@ -2027,8 +2027,8 @@ function uo(t, e, s, n) {
2027
2027
  cursor: m.next_cursor,
2028
2028
  updatedAt: e.output.updatedAt
2029
2029
  } } }, v) {
2030
- for (const [I, k] of Object.entries(p))
2031
- k.sessionId === o.sessionId && k.lane === "history" && delete p[I];
2030
+ for (const [I, _] of Object.entries(p))
2031
+ _.sessionId === o.sessionId && _.lane === "history" && delete p[I];
2032
2032
  c = { ...c, queries: { ...c.queries, history: { ...c.queries.current, key: h.key } } };
2033
2033
  }
2034
2034
  }
@@ -2057,15 +2057,15 @@ function uo(t, e, s, n) {
2057
2057
  }
2058
2058
  case "conversation.submission_stage": {
2059
2059
  if (s.clients[e.clientScopeId] !== e.conversationScopeId) throw new Error("Submission selection has changed.");
2060
- const { type: o, authorityId: c, generation: d, prepareContext: l, waitForAuthentication: u, ...p } = e, g = t.submissions[e.userMessageId];
2060
+ const { type: o, authorityId: c, generation: l, prepareContext: d, waitForAuthentication: u, ...p } = e, g = t.submissions[e.userMessageId];
2061
2061
  if (g) {
2062
- const { contextPreparation: w, requestedModel: f, sessionId: y, delivery: b, cancelled: _, cancellationReason: R, error: T, executionVersion: C, ...E } = g;
2062
+ const { contextPreparation: S, requestedModel: f, sessionId: b, delivery: y, cancelled: w, cancellationReason: R, error: T, executionVersion: C, ...E } = g;
2063
2063
  if (ut(E) !== ut(p)) throw new Error("User-message identity cannot be reused with different input.");
2064
2064
  return { state: t, effects: r };
2065
2065
  }
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 = {
2066
+ const m = s.selections[e.conversationScopeId], h = Object.values(t.submissions).find((S) => S.conversationScopeId === e.conversationScopeId && !S.cancelled && S.sessionId !== null), v = n.scopes[e.clientScopeId], I = {
2067
2067
  ...X(p),
2068
- ...l ? { contextPreparation: null } : {},
2068
+ ...d ? { contextPreparation: null } : {},
2069
2069
  // Extension staging can await page context after the picker has already changed.
2070
2070
  requestedModel: v?.submissions[e.userMessageId] ? v.submissions[e.userMessageId].requestedModel ?? null : v ? dn(v) ?? null : null,
2071
2071
  sessionId: m.sessionId ?? h?.sessionId ?? null,
@@ -2073,8 +2073,8 @@ function uo(t, e, s, n) {
2073
2073
  cancelled: !1,
2074
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,
2075
2075
  executionVersion: null
2076
- }, k = { ...t.proactiveQuestions };
2077
- delete k[e.conversationScopeId], i = { ...t, proactiveQuestions: k, submissions: { ...t.submissions, [e.userMessageId]: I }, submissionOrder: [...t.submissionOrder, e.userMessageId] };
2076
+ }, _ = { ...t.proactiveQuestions };
2077
+ delete _[e.conversationScopeId], i = { ...t, proactiveQuestions: _, submissions: { ...t.submissions, [e.userMessageId]: I }, submissionOrder: [...t.submissionOrder, e.userMessageId] };
2078
2078
  break;
2079
2079
  }
2080
2080
  case "conversation.submission_accepted": {
@@ -2091,10 +2091,10 @@ function uo(t, e, s, n) {
2091
2091
  }
2092
2092
  case "conversation.stop": {
2093
2093
  if (s.clients[e.clientScopeId] !== e.conversationScopeId) return { state: t, effects: r };
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)));
2094
+ const o = s.selections[e.conversationScopeId].sessionId, c = o ? t.sessions[o]?.execution : null, l = Object.values(t.submissions).filter((h) => (o ? h.sessionId === o : h.conversationScopeId === e.conversationScopeId) && (!e.userMessageIds || e.userMessageIds.includes(h.userMessageId))), d = l.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 = d.length > 0, p = c && ["queued", "thinking", "steering", "stopping"].includes(c.phase) && (!e.userMessageIds || de(c).some((h) => e.userMessageIds.includes(h)));
2095
2095
  if (!u && !p && (c || !e.userMessageIds?.length)) return { state: t, effects: r };
2096
- const g = Array.from(new Set(e.userMessageIds ?? [...l.map((h) => h.userMessageId), ...p ? de(c) : []])), m = { ...t.submissions };
2097
- for (const h of d)
2096
+ const g = Array.from(new Set(e.userMessageIds ?? [...d.map((h) => h.userMessageId), ...p ? de(c) : []])), m = { ...t.submissions };
2097
+ for (const h of l)
2098
2098
  g.includes(h.userMessageId) && h.delivery !== "accepted" && (m[h.userMessageId] = { ...h, cancelled: !0, cancellationReason: e.reason ?? "user_requested" });
2099
2099
  i = { ...t, submissions: m, stops: { ...t.stops, [e.conversationScopeId]: {
2100
2100
  requestId: e.requestId,
@@ -2105,36 +2105,36 @@ function uo(t, e, s, n) {
2105
2105
  break;
2106
2106
  }
2107
2107
  case "conversation.display_received": {
2108
- const o = X(e.event), c = o.type === "conversation.item.updated" ? o.item.conversation_id : o.type === "conversation.execution.updated" ? o.execution.conversation_id : o.type === "conversation.interaction.updated" ? o.interaction.conversation_id : o.conversation_id, d = o.type === "conversation.item.updated" && o.item.type === "user_message" ? t.submissions[o.item.id] : void 0;
2109
- if (d && (i = $s(t, d, c)), !i.sessions[c] && !s.memberships[c]?.members.length && !d) return { state: t, effects: r };
2108
+ const o = X(e.event), c = o.type === "conversation.item.updated" ? o.item.conversation_id : o.type === "conversation.execution.updated" ? o.execution.conversation_id : o.type === "conversation.interaction.updated" ? o.interaction.conversation_id : o.conversation_id, l = o.type === "conversation.item.updated" && o.item.type === "user_message" ? t.submissions[o.item.id] : void 0;
2109
+ if (l && (i = $s(t, l, c)), !i.sessions[c] && !s.memberships[c]?.members.length && !l) return { state: t, effects: r };
2110
2110
  s.memberships[c]?.members.length && (o.type === "conversation.interaction.updated" || o.type === "conversation.execution.updated" || o.type === "conversation.item.updated" && o.item.type === "user_message") && (a = {
2111
2111
  authorityId: t.authorityId,
2112
2112
  generation: t.generation,
2113
2113
  sessionId: c,
2114
2114
  sources: o.type === "conversation.interaction.updated" ? [o.interaction] : []
2115
2115
  });
2116
- const l = i.sessions[c] ?? Ps(c), u = rs(l, o);
2117
- u !== l && (i = { ...i, sessions: { ...i.sessions, [c]: u } });
2116
+ const d = i.sessions[c] ?? Ps(c), u = rs(d, o);
2117
+ u !== d && (i = { ...i, sessions: { ...i.sessions, [c]: u } });
2118
2118
  break;
2119
2119
  }
2120
2120
  case "conversation.observation_released": {
2121
2121
  const o = t.sessions[e.sessionId];
2122
2122
  if (!o) return { state: t, effects: r };
2123
- const c = { ...t.requests }, d = { ...o.queries };
2124
- for (const [l, u] of Object.entries(c)) {
2123
+ const c = { ...t.requests }, l = { ...o.queries };
2124
+ for (const [d, u] of Object.entries(c)) {
2125
2125
  if (u.sessionId !== e.sessionId) continue;
2126
- delete c[l];
2127
- const p = d[u.lane];
2128
- d[u.lane] = { ...p, requestId: null, status: p.data === null ? "not_requested" : "ready" };
2126
+ delete c[d];
2127
+ const p = l[u.lane];
2128
+ l[u.lane] = { ...p, requestId: null, status: p.data === null ? "not_requested" : "ready" };
2129
2129
  }
2130
- d.history = me(d.history.key), i = { ...t, requests: c, sessions: { ...t.sessions, [e.sessionId]: { ...o, queries: d } } };
2130
+ l.history = me(l.history.key), i = { ...t, requests: c, sessions: { ...t.sessions, [e.sessionId]: { ...o, queries: l } } };
2131
2131
  break;
2132
2132
  }
2133
2133
  case "conversation.snapshot": {
2134
2134
  if (!s.memberships[e.sessionId]?.members.length) return { state: t, effects: r };
2135
2135
  const o = t.sessions[e.sessionId] ?? Ps(e.sessionId), c = o.queries[e.lane];
2136
2136
  if (c.requestId !== null) return { state: t, effects: r };
2137
- const d = {
2137
+ const l = {
2138
2138
  authorityId: e.authorityId,
2139
2139
  generation: e.generation,
2140
2140
  sessionId: e.sessionId,
@@ -2143,16 +2143,16 @@ function uo(t, e, s, n) {
2143
2143
  before: e.lane === "history" ? c.cursor : null,
2144
2144
  refreshItemIds: lo(o),
2145
2145
  retryPreparation: c.error?.code === "history_preparation_failed"
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}`;
2146
+ }, d = 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}`;
2147
2147
  i = {
2148
2148
  ...t,
2149
2149
  requestSequence: u,
2150
- requests: { ...t.requests, [p]: { ...d, acceptedUserMessageIds: l } },
2150
+ requests: { ...t.requests, [p]: { ...l, acceptedUserMessageIds: d } },
2151
2151
  sessions: { ...t.sessions, [e.sessionId]: { ...o, queries: {
2152
2152
  ...o.queries,
2153
- [e.lane]: De(c, { key: c.key, requestId: e.requestId, mode: d.before === null ? "replace" : "append" })
2153
+ [e.lane]: De(c, { key: c.key, requestId: e.requestId, mode: l.before === null ? "replace" : "append" })
2154
2154
  } } }
2155
- }, r.push({ id: p, kind: "conversation.snapshot", input: d });
2155
+ }, r.push({ id: p, kind: "conversation.snapshot", input: l });
2156
2156
  break;
2157
2157
  }
2158
2158
  }
@@ -2177,36 +2177,36 @@ const $n = (t, e) => ({
2177
2177
  command: null
2178
2178
  });
2179
2179
  function ln(t, e) {
2180
- const s = new Set(Object.values(e.clients)), n = Object.values(t.operations).filter((l) => l.command.type === "run.stop"), i = (l) => n.some((u) => u.command.payload.expectedUserMessageId === l && u.phase === "done"), r = Object.fromEntries(Object.entries(t.submissions).filter(([l, u]) => {
2180
+ const s = new Set(Object.values(e.clients)), n = Object.values(t.operations).filter((d) => d.command.type === "run.stop"), i = (d) => n.some((u) => u.command.payload.expectedUserMessageId === d && u.phase === "done"), r = Object.fromEntries(Object.entries(t.submissions).filter(([d, u]) => {
2181
2181
  const p = u.sessionId ? t.sessions[u.sessionId] : void 0;
2182
- if (u.cancelled && s.has(u.conversationScopeId) && t.stops[u.conversationScopeId]?.userMessageIds.includes(l) && !p?.items[l] && !p?.removedItems[l]) return !0;
2182
+ if (u.cancelled && s.has(u.conversationScopeId) && t.stops[u.conversationScopeId]?.userMessageIds.includes(d) && !p?.items[d] && !p?.removedItems[d]) return !0;
2183
2183
  if (u.delivery === "accepted") {
2184
- if (u.cancelled) return !i(l);
2184
+ if (u.cancelled) return !i(d);
2185
2185
  const g = u.sessionId ? t.sessions[u.sessionId] : void 0;
2186
- return u.executionVersion === null || !(g?.items[l] || g?.removedItems[l]);
2186
+ return u.executionVersion === null || !(g?.items[d] || g?.removedItems[d]);
2187
2187
  }
2188
- return !u.cancelled || we(t, l) || t.deliveries[l]?.phase === "running";
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) => {
2188
+ return !u.cancelled || we(t, d) || t.deliveries[d]?.phase === "running";
2189
+ }).map(([d, u]) => [d, u.delivery === "accepted" || u.cancelled ? { ...u, context: {}, contextPreparation: { pageContent: "", sessionTabs: [] } } : u])), a = Object.fromEntries(Object.entries(t.deliveries).filter(([d]) => d in r).map(([d, u]) => [d, r[d].delivery === "accepted" ? { ...u, phase: "done", effectId: null, command: null, uploads: [], completedUploads: 0 } : r[d].cancelled ? { ...u, command: null } : u])), o = Object.fromEntries(Object.entries(t.stops).filter(([d, u]) => u.userMessageIds.some((p) => {
2190
2190
  if (r[p]) return !0;
2191
2191
  if (!i(p)) return n.some((m) => m.command.payload.expectedUserMessageId === p && m.phase !== "done");
2192
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));
2194
- }))), c = new Set(Object.values(o).flatMap((l) => l.userMessageIds)), d = Object.fromEntries(Object.entries(t.operations).filter(([, l]) => {
2195
- if (!["done", "failed"].includes(l.phase)) return !0;
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);
2197
- if (l.phase !== "done" || !l.conversationScopeId || !s.has(l.conversationScopeId)) return !1;
2198
- if (l.command.type === "runtime.warmup") return e.selections[l.conversationScopeId]?.sessionId !== l.result?.sessionId;
2199
- if (l.command.type !== "attachment.prepare") return !1;
2200
- const u = l.command.payload.source;
2201
- return !Object.values(t.submissions).some((p) => p.conversationScopeId === l.conversationScopeId && p.delivery === "accepted" && p.attachments.some((g) => g.sourceId === u.sourceId));
2193
+ return s.has(d) && (!g || g.version <= u.executionVersion || !["completed", "failed", "stopped"].includes(g.phase));
2194
+ }))), c = new Set(Object.values(o).flatMap((d) => d.userMessageIds)), l = Object.fromEntries(Object.entries(t.operations).filter(([, d]) => {
2195
+ if (!["done", "failed"].includes(d.phase)) return !0;
2196
+ if (d.command.type === "run.stop") return c.has(String(d.command.payload.expectedUserMessageId)) || Object.values(r).some((p) => p.cancelled && p.userMessageId === d.command.payload.expectedUserMessageId);
2197
+ if (d.phase !== "done" || !d.conversationScopeId || !s.has(d.conversationScopeId)) return !1;
2198
+ if (d.command.type === "runtime.warmup") return e.selections[d.conversationScopeId]?.sessionId !== d.result?.sessionId;
2199
+ if (d.command.type !== "attachment.prepare") return !1;
2200
+ const u = d.command.payload.source;
2201
+ return !Object.values(t.submissions).some((p) => p.conversationScopeId === d.conversationScopeId && p.delivery === "accepted" && p.attachments.some((g) => g.sourceId === u.sourceId));
2202
2202
  }));
2203
2203
  return G({
2204
2204
  schema: 1,
2205
2205
  authorityId: t.authorityId,
2206
2206
  submissions: r,
2207
- submissionOrder: t.submissionOrder.filter((l) => l in r),
2207
+ submissionOrder: t.submissionOrder.filter((d) => d in r),
2208
2208
  deliveries: a,
2209
- operations: d,
2209
+ operations: l,
2210
2210
  stops: o,
2211
2211
  requestSequence: t.requestSequence
2212
2212
  });
@@ -2246,37 +2246,37 @@ function Ws(t) {
2246
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));
2247
2247
  for (const o of r) {
2248
2248
  const c = e.submissions[o];
2249
- let d = e.deliveries[o];
2250
- if (t.pendingRestoration[c.clientScopeId] === c.conversationScopeId || !d || d.phase !== "waiting" || !we(e, o) || c.delivery === "accepted") continue;
2251
- if (!d.prepared && !c.cancelled) {
2249
+ let l = e.deliveries[o];
2250
+ if (t.pendingRestoration[c.clientScopeId] === c.conversationScopeId || !l || l.phase !== "waiting" || !we(e, o) || c.delivery === "accepted") continue;
2251
+ if (!l.prepared && !c.cancelled) {
2252
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) } });
2253
+ e = { ...e, deliveries: { ...e.deliveries, [o]: { ...l, phase: "running", effectId: g } } }, s.push({ id: g, kind: "conversation.prepare", input: { ...n, submission: c, sources: c.attachments.slice(l.uploads.length) } });
2254
2254
  continue;
2255
2255
  }
2256
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;
2257
- for (; d.uploads.length < c.attachments.length; ) {
2258
- const g = c.attachments[d.uploads.length];
2257
+ for (; l.uploads.length < c.attachments.length; ) {
2258
+ const g = c.attachments[l.uploads.length];
2259
2259
  if (g.uploaded) {
2260
- d = { ...d, uploads: [...d.uploads, g.uploaded] };
2260
+ l = { ...l, uploads: [...l.uploads, g.uploaded] };
2261
2261
  continue;
2262
2262
  }
2263
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);
2264
2264
  if (!m) break;
2265
- d = { ...d, uploads: [...d.uploads, m.result.attachment] };
2265
+ l = { ...l, uploads: [...l.uploads, m.result.attachment] };
2266
2266
  }
2267
- for (; d.completedUploads < d.uploads.length && c.attachments[d.completedUploads].uploaded; )
2268
- d = { ...d, completedUploads: d.completedUploads + 1 };
2269
- if (!c.cancelled && d.uploads.length === c.attachments.length && d.completedUploads === d.uploads.length && r.slice(0, r.indexOf(o)).some((g) => {
2267
+ for (; l.completedUploads < l.uploads.length && c.attachments[l.completedUploads].uploaded; )
2268
+ l = { ...l, completedUploads: l.completedUploads + 1 };
2269
+ if (!c.cancelled && l.uploads.length === c.attachments.length && l.completedUploads === l.uploads.length && r.slice(0, r.indexOf(o)).some((g) => {
2270
2270
  const m = e.submissions[g];
2271
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));
2272
2272
  })) continue;
2273
- const l = i();
2274
- let u, p = d.command;
2275
- c.cancelled || d.step === "receipt" ? (u = "receipt", s.push({ id: l, kind: "conversation.receipt", input: { ...n, userMessageId: o, sessionId: c.sessionId } })) : d.uploads.length < c.attachments.length ? (u = "upload", s.push({ id: l, kind: "conversation.upload", input: { ...n, submission: c, source: c.attachments[d.uploads.length], previousAllocation: d.allocation } })) : (u = d.completedUploads < d.uploads.length ? "complete" : "send", u === "complete" && (d.step !== "complete" || !p) ? p = {
2276
- request_id: l,
2273
+ const d = i();
2274
+ let u, p = l.command;
2275
+ c.cancelled || l.step === "receipt" ? (u = "receipt", s.push({ id: d, kind: "conversation.receipt", input: { ...n, userMessageId: o, sessionId: c.sessionId } })) : l.uploads.length < c.attachments.length ? (u = "upload", s.push({ id: d, kind: "conversation.upload", input: { ...n, submission: c, source: c.attachments[l.uploads.length], previousAllocation: l.allocation } })) : (u = l.completedUploads < l.uploads.length ? "complete" : "send", u === "complete" && (l.step !== "complete" || !p) ? p = {
2276
+ request_id: d,
2277
2277
  type: "attachment.upload_completed",
2278
- payload: { sessionId: c.sessionId, clientMessageId: o, attachment: d.uploads[d.completedUploads] }
2279
- } : u === "send" && (d.step !== "send" || !p) && (p = {
2278
+ payload: { sessionId: c.sessionId, clientMessageId: o, attachment: l.uploads[l.completedUploads] }
2279
+ } : u === "send" && (l.step !== "send" || !p) && (p = {
2280
2280
  request_id: c.requestId,
2281
2281
  type: "chat.user_message",
2282
2282
  payload: {
@@ -2287,30 +2287,30 @@ function Ws(t) {
2287
2287
  model: c.requestedModel,
2288
2288
  invocation: c.invocation,
2289
2289
  entrySurface: c.entrySurface,
2290
- attachments: d.uploads
2290
+ attachments: l.uploads
2291
2291
  }
2292
- }), s.push({ id: l, kind: "conversation.command", input: { ...n, command: p, previousAcceptance: d.acceptance } })), e = {
2292
+ }), s.push({ id: d, kind: "conversation.command", input: { ...n, command: p, previousAcceptance: l.acceptance } })), e = {
2293
2293
  ...e,
2294
- deliveries: { ...e.deliveries, [o]: { ...d, phase: "running", effectId: l, step: u, command: p, acceptance: u === "send" ? "uncertain" : d.acceptance, allocation: u === "upload" && c.sessionId === null ? "uncertain" : d.allocation } },
2294
+ deliveries: { ...e.deliveries, [o]: { ...l, phase: "running", effectId: d, step: u, command: p, acceptance: u === "send" ? "uncertain" : l.acceptance, allocation: u === "upload" && c.sessionId === null ? "uncertain" : l.allocation } },
2295
2295
  submissions: { ...e.submissions, [o]: { ...c, delivery: "sending", error: null } }
2296
2296
  };
2297
2297
  }
2298
- const a = (o, c, d, l = "user_requested") => {
2298
+ const a = (o, c, l, d = "user_requested") => {
2299
2299
  if (e.operations[o]) return;
2300
2300
  const u = i();
2301
2301
  e = { ...e, operations: { ...e.operations, [o]: Ks({
2302
2302
  request_id: u,
2303
2303
  type: "run.stop",
2304
- payload: { sessionId: c, expectedUserMessageId: d, reason: l }
2304
+ payload: { sessionId: c, expectedUserMessageId: l, reason: d }
2305
2305
  }) } };
2306
2306
  };
2307
2307
  for (const [o, c] of Object.entries(e.stops))
2308
- for (const d of c.userMessageIds) {
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);
2310
- u && p && a(`stop:${o}:${c.requestId}:${d}`, u, d, c.reason);
2308
+ for (const l of c.userMessageIds) {
2309
+ const d = e.submissions[l], u = d?.sessionId ?? Object.values(e.sessions).find((g) => de(g.execution).includes(l))?.sessionId, p = d?.delivery === "accepted" || u && de(e.sessions[u]?.execution).includes(l);
2310
+ u && p && a(`stop:${o}:${c.requestId}:${l}`, u, l, c.reason);
2311
2311
  }
2312
2312
  for (const o of Object.values(e.submissions))
2313
- o.cancelled && o.delivery === "accepted" && o.sessionId && (Object.values(e.operations).some((d) => d.command.type === "run.stop" && d.command.payload.sessionId === o.sessionId && d.command.payload.expectedUserMessageId === o.userMessageId) || a(
2313
+ o.cancelled && o.delivery === "accepted" && o.sessionId && (Object.values(e.operations).some((l) => l.command.type === "run.stop" && l.command.payload.sessionId === o.sessionId && l.command.payload.expectedUserMessageId === o.userMessageId) || a(
2314
2314
  `cancel:${o.requestId}`,
2315
2315
  o.sessionId,
2316
2316
  o.userMessageId,
@@ -2318,10 +2318,10 @@ function Ws(t) {
2318
2318
  ));
2319
2319
  for (const [o, c] of Object.entries(e.operations)) {
2320
2320
  if (c.phase !== "waiting" || c.conversationScopeId && Object.values(e.pendingRestoration).includes(c.conversationScopeId)) 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;
2323
- if (c.command.type === "runtime.warmup" && l && !c.command.payload.sessionId) {
2324
- e = { ...e, operations: { ...e.operations, [o]: { ...c, phase: "done", result: l } } };
2321
+ const l = Object.values(e.operations).filter((g) => g !== c && g.conversationScopeId === c.conversationScopeId && ["runtime.warmup", "attachment.prepare"].includes(g.command.type)), d = l.find((g) => g.phase === "done" && g.result?.sessionId)?.result, u = c.command.payload.sessionId ?? d?.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 && (l.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;
2323
+ if (c.command.type === "runtime.warmup" && d && !c.command.payload.sessionId) {
2324
+ e = { ...e, operations: { ...e.operations, [o]: { ...c, phase: "done", result: d } } };
2325
2325
  continue;
2326
2326
  }
2327
2327
  const p = i();
@@ -2345,22 +2345,22 @@ function ho(t, e, s, n) {
2345
2345
  let i = t, r = e;
2346
2346
  if (e.type === "effect.completed" || e.type === "effect.failed") {
2347
2347
  e.effectKind === "conversation.checkpoint" && e.effectId === t.checkpointEffectId && (i = { ...i, checkpointEffectId: null, checkpointError: e.type === "effect.failed" ? e.error : null });
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);
2349
- if (l) {
2350
- const p = t.deliveries[l], g = t.submissions[l];
2348
+ const d = 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);
2349
+ if (d) {
2350
+ const p = t.deliveries[d], g = t.submissions[d];
2351
2351
  let m = { ...p, phase: "waiting", effectId: null };
2352
2352
  if (e.type === "effect.failed") {
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: {
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", _ = e.effectKind === "conversation.prepare" || I ? "failed" : h === "uncertain" || v === "uncertain" || e.error.retryable ? "uncertain" : "failed";
2354
+ m = { ...m, phase: _, acceptance: h, allocation: v }, !g.cancelled && g.delivery !== "accepted" && (i = { ...i, submissions: {
2355
2355
  ...i.submissions,
2356
- [l]: { ...g, delivery: k, error: e.error }
2356
+ [d]: { ...g, delivery: _, error: e.error }
2357
2357
  } });
2358
2358
  } else if (e.effectKind === "conversation.prepare")
2359
- g.cancelled ? m = { ...m, phase: "failed" } : (m = { ...m, prepared: !0 }, i = { ...i, submissions: { ...i.submissions, [l]: {
2359
+ g.cancelled ? m = { ...m, phase: "failed" } : (m = { ...m, prepared: !0 }, i = { ...i, submissions: { ...i.submissions, [d]: {
2360
2360
  ...g,
2361
2361
  ...g.contextPreparation === null ? { contextPreparation: { pageContent: e.output.pageContent, sessionTabs: e.output.sessionTabs } } : {}
2362
- } } }, p.recoveryDeadline !== null && e.output.now >= p.recoveryDeadline && (m = { ...m, phase: "paused" }, i = { ...i, submissions: { ...i.submissions, [l]: {
2363
- ...i.submissions[l],
2362
+ } } }, p.recoveryDeadline !== null && e.output.now >= p.recoveryDeadline && (m = { ...m, phase: "paused" }, i = { ...i, submissions: { ...i.submissions, [d]: {
2363
+ ...i.submissions[d],
2364
2364
  delivery: "failed",
2365
2365
  error: { code: "message_delivery_failed", message: "Pluno could not send this message. Try it again.", retryable: !0 }
2366
2366
  } } }));
@@ -2369,41 +2369,41 @@ function ho(t, e, s, n) {
2369
2369
  if (h.attachment.id !== v.sourceId || h.attachment.size_bytes !== v.sizeBytes || g.sessionId !== null && g.sessionId !== h.sessionId)
2370
2370
  throw new Error("Upload does not match the captured attachment or conversation.");
2371
2371
  m = { ...m, allocation: "resolved", uploads: [...p.uploads, h.attachment] };
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
2372
+ const I = Object.fromEntries(Object.entries(i.submissions).map(([_, S]) => [
2373
+ _,
2374
+ S.conversationScopeId === g.conversationScopeId && (_ === d || !S.cancelled && !g.cancelled) ? { ...S, sessionId: h.sessionId } : S
2375
2375
  ]));
2376
2376
  i = { ...i, submissions: I };
2377
2377
  } else if (e.effectKind === "conversation.receipt")
2378
2378
  if (e.output === null)
2379
- m = { ...m, phase: g.cancelled ? "uncertain" : "paused" }, g.cancelled || (i = { ...i, submissions: { ...i.submissions, [l]: {
2379
+ m = { ...m, phase: g.cancelled ? "uncertain" : "paused" }, g.cancelled || (i = { ...i, submissions: { ...i.submissions, [d]: {
2380
2380
  ...g,
2381
2381
  delivery: "failed",
2382
2382
  error: { code: "message_acceptance_unconfirmed", message: "Pluno could not confirm whether this message was accepted. Try again.", retryable: !0 }
2383
2383
  } } });
2384
2384
  else {
2385
- const h = zn(e.output, l);
2385
+ const h = zn(e.output, d);
2386
2386
  m = { ...m, phase: "done", acceptance: "accepted" }, r = {
2387
2387
  type: "conversation.submission_accepted",
2388
2388
  authorityId: t.authorityId,
2389
2389
  generation: t.generation,
2390
- userMessageId: l,
2390
+ userMessageId: d,
2391
2391
  sessionId: h.sessionId
2392
2392
  };
2393
2393
  }
2394
2394
  else if (e.effectKind === "conversation.command" && p.step === "complete")
2395
2395
  m = { ...m, completedUploads: p.completedUploads + 1, command: null };
2396
2396
  else if (e.effectKind === "conversation.command" && p.step === "send") {
2397
- const h = zn(e.output, l);
2397
+ const h = zn(e.output, d);
2398
2398
  m = { ...m, phase: "done", acceptance: "accepted" }, r = {
2399
2399
  type: "conversation.submission_accepted",
2400
2400
  authorityId: t.authorityId,
2401
2401
  generation: t.generation,
2402
- userMessageId: l,
2402
+ userMessageId: d,
2403
2403
  sessionId: h.sessionId
2404
2404
  };
2405
2405
  }
2406
- i = { ...i, deliveries: { ...i.deliveries, [l]: m } };
2406
+ i = { ...i, deliveries: { ...i.deliveries, [d]: m } };
2407
2407
  } else if (u) {
2408
2408
  const p = t.operations[u];
2409
2409
  if (i = { ...i, operations: { ...i.operations, [u]: {
@@ -2429,53 +2429,53 @@ function ho(t, e, s, n) {
2429
2429
  }
2430
2430
  }
2431
2431
  } else if (e.authorityId === t.authorityId && e.generation === t.generation && s.authorityId) {
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,
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(([d, u]) => [
2433
+ d,
2434
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
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)
2436
+ const d = X(e.checkpoint), u = t.submissionOrder.every((S) => t.deliveries[S]?.acceptance === "unissued" && t.submissions[S].delivery === "failed" && ["unauthorized", "auth_reconnecting"].includes(t.submissions[S].error?.code ?? ""));
2437
+ if (d.schema !== 1 || d.authorityId !== t.authorityId || !u || Object.keys(t.operations).length)
2438
2438
  throw new Error("Delivery restoration requires an empty engine with the same authenticated authority.");
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 });
2439
+ const p = { ...t.submissions, ...d.submissions };
2440
+ for (const [S, f] of Object.entries(t.submissions))
2441
+ f.cancelled && (p[S] = { ...p[S], cancelled: !0, cancellationReason: f.cancellationReason });
2442
2442
  const g = {
2443
- ...l,
2443
+ ...d,
2444
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;
2445
+ stops: { ...d.stops, ...t.stops },
2446
+ deliveries: { ...t.deliveries, ...d.deliveries },
2447
+ submissionOrder: [.../* @__PURE__ */ new Set([...d.submissionOrder, ...t.submissionOrder])]
2448
+ }, { schema: m, authorityId: h, ...v } = g, I = X(e.pendingRestoration ?? {}), _ = (S) => !s.clients[S.clientScopeId] && I[S.clientScopeId] === S.conversationScopeId;
2449
2449
  i = {
2450
2450
  ...t,
2451
2451
  ...v,
2452
2452
  pendingRestoration: I,
2453
2453
  requestSequence: Math.max(t.requestSequence, g.requestSequence),
2454
2454
  effectsEnabled: !0,
2455
- submissions: Object.fromEntries(Object.entries(g.submissions).map(([w, f]) => [w, {
2455
+ submissions: Object.fromEntries(Object.entries(g.submissions).map(([S, f]) => [S, {
2456
2456
  ...f,
2457
2457
  executionVersion: null,
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
2458
+ cancelled: f.cancelled || !_(f) && !zs(f, s),
2459
+ ...!f.cancelled && !_(f) && !zs(f, s) ? { cancellationReason: "owner_lost" } : {},
2460
+ delivery: (f.contextPreparation === null || !g.deliveries[S]) && !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[S] && f.delivery !== "accepted" && !f.cancelled ? { code: "submission_interrupted", message: "Message preparation was interrupted. Retry this message.", retryable: !0 } : f.error
2462
2462
  }])),
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,
2463
+ deliveries: Object.fromEntries(Object.entries(g.submissions).map(([S, f], b) => {
2464
+ const y = g.deliveries[S], w = f.contextPreparation === null, R = f.delivery === "accepted" ? "accepted" : y?.acceptance ?? (y && (y.step === "send" || y.step === "receipt") ? "uncertain" : "unissued");
2465
+ return [S, {
2466
+ ...$n(f, b),
2467
+ ...y,
2468
2468
  acceptance: R,
2469
- allocation: f.sessionId !== null ? "resolved" : b?.allocation ?? (b?.step === "upload" ? "uncertain" : "unissued"),
2469
+ allocation: f.sessionId !== null ? "resolved" : y?.allocation ?? (y?.step === "upload" ? "uncertain" : "unissued"),
2470
2470
  effectId: null,
2471
2471
  // Readiness is authority-local and must be re-established after restart. Captured input stays immutable.
2472
- step: R === "uncertain" && b?.step === "send" && b.phase !== "done" ? "receipt" : b?.step ?? null,
2472
+ step: R === "uncertain" && y?.step === "send" && y.phase !== "done" ? "receipt" : y?.step ?? null,
2473
2473
  prepared: R === "accepted",
2474
- queuePosition: b?.queuePosition ?? y,
2475
- phase: R === "accepted" ? "done" : _ || !b ? "failed" : ["running", "waiting"].includes(b.phase) ? "uncertain" : b.phase
2474
+ queuePosition: y?.queuePosition ?? b,
2475
+ phase: R === "accepted" ? "done" : w || !y ? "failed" : ["running", "waiting"].includes(y.phase) ? "uncertain" : y.phase
2476
2476
  }];
2477
2477
  })),
2478
- operations: Object.fromEntries(Object.entries(g.operations).map(([w, f]) => [w, {
2478
+ operations: Object.fromEntries(Object.entries(g.operations).map(([S, f]) => [S, {
2479
2479
  ...f,
2480
2480
  effectId: null,
2481
2481
  phase: ["running", "waiting"].includes(f.phase) ? "uncertain" : f.phase
@@ -2483,35 +2483,35 @@ function ho(t, e, s, n) {
2483
2483
  };
2484
2484
  }
2485
2485
  if (e.type === "conversation.restoration_resolved") {
2486
- const l = { ...i.pendingRestoration };
2487
- delete l[e.clientScopeId], i = Hs({ ...i, pendingRestoration: l }, s);
2486
+ const d = { ...i.pendingRestoration };
2487
+ delete d[e.clientScopeId], i = Hs({ ...i, pendingRestoration: d }, s);
2488
2488
  }
2489
2489
  if (e.type === "conversation.recover" && (i = {
2490
2490
  ...t,
2491
- deliveries: Object.fromEntries(Object.entries(t.deliveries).map(([l, u]) => [
2492
- l,
2493
- u.phase === "uncertain" && we(t, l) ? { ...u, phase: "waiting", prepared: !1 } : u
2491
+ deliveries: Object.fromEntries(Object.entries(t.deliveries).map(([d, u]) => [
2492
+ d,
2493
+ u.phase === "uncertain" && we(t, d) ? { ...u, phase: "waiting", prepared: !1 } : u
2494
2494
  ])),
2495
- operations: Object.fromEntries(Object.entries(t.operations).map(([l, u]) => [
2496
- l,
2495
+ operations: Object.fromEntries(Object.entries(t.operations).map(([d, u]) => [
2496
+ d,
2497
2497
  u.phase === "uncertain" && zi(u) ? { ...u, phase: "waiting" } : u
2498
2498
  ]))
2499
2499
  }), e.type === "conversation.submit") {
2500
- const l = t.submissions[e.userMessageId];
2501
- if (!l) throw new Error("Stage the immutable submission before sending.");
2500
+ const d = t.submissions[e.userMessageId];
2501
+ if (!d) throw new Error("Stage the immutable submission before sending.");
2502
2502
  const u = t.deliveries[e.userMessageId];
2503
- if (u && !l.cancelled && l.delivery !== "accepted" && (u.phase === "uncertain" || e.manualRetry && ["paused", "failed"].includes(u.phase))) {
2503
+ if (u && !d.cancelled && d.delivery !== "accepted" && (u.phase === "uncertain" || e.manualRetry && ["paused", "failed"].includes(u.phase))) {
2504
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;
2505
2505
  i = {
2506
2506
  ...t,
2507
2507
  effectsEnabled: !0,
2508
2508
  requestSequence: Math.max(t.requestSequence, g),
2509
- submissions: { ...t.submissions, [e.userMessageId]: { ...l, delivery: "staged", error: null } },
2509
+ submissions: { ...t.submissions, [e.userMessageId]: { ...d, delivery: "staged", error: null } },
2510
2510
  deliveries: { ...t.deliveries, [e.userMessageId]: {
2511
2511
  ...u,
2512
2512
  phase: "waiting",
2513
2513
  effectId: null,
2514
- ...e.manualRetry && l.error?.code === "message_acceptance_unconfirmed" ? { step: "send" } : {},
2514
+ ...e.manualRetry && d.error?.code === "message_acceptance_unconfirmed" ? { step: "send" } : {},
2515
2515
  prepared: !1,
2516
2516
  queuePosition: g,
2517
2517
  command: u.acceptance === "unissued" && u.step === "send" ? null : u.command,
@@ -2521,12 +2521,12 @@ function ho(t, e, s, n) {
2521
2521
  }
2522
2522
  }
2523
2523
  if (e.type === "conversation.recover" || e.type === "conversation.submit")
2524
- for (const [l, u] of Object.entries(i.deliveries)) {
2525
- const p = i.submissions[l];
2524
+ for (const [d, u] of Object.entries(i.deliveries)) {
2525
+ const p = i.submissions[d];
2526
2526
  u.phase !== "waiting" || p.cancelled || u.recoveryDeadline === null || e.now < u.recoveryDeadline || (i = {
2527
2527
  ...i,
2528
- deliveries: { ...i.deliveries, [l]: { ...u, phase: "paused" } },
2529
- submissions: { ...i.submissions, [l]: { ...p, delivery: "failed", error: {
2528
+ deliveries: { ...i.deliveries, [d]: { ...u, phase: "paused" } },
2529
+ submissions: { ...i.submissions, [d]: { ...p, delivery: "failed", error: {
2530
2530
  code: "message_delivery_failed",
2531
2531
  message: "Pluno could not send this message. Try it again.",
2532
2532
  retryable: !0
@@ -2534,27 +2534,27 @@ function ho(t, e, s, n) {
2534
2534
  });
2535
2535
  }
2536
2536
  if (e.type === "conversation.operation") {
2537
- const l = e.command;
2538
- if (l.type === "attachment.prepare" && !e.conversationScopeId) throw new Error("Attachment preparation requires a conversation scope.");
2539
- if (l.type === "chat.user_message") throw new Error("Messages must use the immutable submission pipeline.");
2540
- if (l.type === "run.stop" && !l.payload.expectedUserMessageId) throw new Error("Stop requires message correlation.");
2541
- const u = t.operations[l.request_id];
2542
- if (u && (JSON.stringify(u.command) !== JSON.stringify(l) || u.conversationScopeId !== (e.conversationScopeId ?? null))) throw new Error("Command identity changed.");
2537
+ const d = e.command;
2538
+ if (d.type === "attachment.prepare" && !e.conversationScopeId) throw new Error("Attachment preparation requires a conversation scope.");
2539
+ if (d.type === "chat.user_message") throw new Error("Messages must use the immutable submission pipeline.");
2540
+ if (d.type === "run.stop" && !d.payload.expectedUserMessageId) throw new Error("Stop requires message correlation.");
2541
+ const u = t.operations[d.request_id];
2542
+ if (u && (JSON.stringify(u.command) !== JSON.stringify(d) || u.conversationScopeId !== (e.conversationScopeId ?? null))) throw new Error("Command identity changed.");
2543
2543
  if (!u) {
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]];
2546
- const h = m.userMessageIds.filter((v) => v !== l.payload.clientMessageId);
2544
+ const p = d.type === "chat.retry_last_user_message" ? Object.fromEntries(Object.entries(t.stops).flatMap(([g, m]) => {
2545
+ if (s.selections[g]?.sessionId !== d.payload.sessionId) return [[g, m]];
2546
+ const h = m.userMessageIds.filter((v) => v !== d.payload.clientMessageId);
2547
2547
  return h.length ? [[g, { ...m, userMessageIds: h }]] : [];
2548
2548
  })) : t.stops;
2549
2549
  i = { ...t, stops: p, effectsEnabled: !0, operations: {
2550
2550
  ...t.operations,
2551
- [l.request_id]: Ks(l, e.conversationScopeId ?? null)
2551
+ [d.request_id]: Ks(d, e.conversationScopeId ?? null)
2552
2552
  } };
2553
2553
  }
2554
2554
  }
2555
2555
  if (e.type === "conversation.retry_operation") {
2556
- const l = t.operations[e.requestId];
2557
- l?.phase === "uncertain" && (i = { ...t, operations: { ...t.operations, [e.requestId]: { ...l, phase: "waiting" } } });
2556
+ const d = t.operations[e.requestId];
2557
+ d?.phase === "uncertain" && (i = { ...t, operations: { ...t.operations, [e.requestId]: { ...d, phase: "waiting" } } });
2558
2558
  }
2559
2559
  }
2560
2560
  const a = uo(i, r, s, n);
@@ -2565,26 +2565,26 @@ function ho(t, e, s, n) {
2565
2565
  requestSequence: o.requestSequence + 1,
2566
2566
  deliveries: { ...o.deliveries, [e.userMessageId]: { ...$n(o.submissions[e.userMessageId], o.requestSequence + 1), ...e.waitForAuthentication ? { phase: "failed" } : {} } }
2567
2567
  });
2568
- for (const [l, u] of Object.entries(o.submissions)) {
2569
- const p = o.deliveries[l];
2568
+ for (const [d, u] of Object.entries(o.submissions)) {
2569
+ const p = o.deliveries[d];
2570
2570
  p && (u.delivery === "accepted" && p.acceptance !== "accepted" ? o = {
2571
2571
  ...o,
2572
- deliveries: { ...o.deliveries, [l]: { ...p, acceptance: "accepted", phase: "done", effectId: null } }
2572
+ deliveries: { ...o.deliveries, [d]: { ...p, acceptance: "accepted", phase: "done", effectId: null } }
2573
2573
  } : (u.cancelled || u.delivery === "failed") && p.phase === "running" && !p.prepared && (o = {
2574
2574
  ...o,
2575
2575
  // Stop retires readiness work, but a previously issued message still needs receipt reconciliation.
2576
- deliveries: { ...o.deliveries, [l]: {
2576
+ deliveries: { ...o.deliveries, [d]: {
2577
2577
  ...p,
2578
- phase: u.cancelled && we(o, l) ? "waiting" : "failed",
2578
+ phase: u.cancelled && we(o, d) ? "waiting" : "failed",
2579
2579
  prepared: u.cancelled,
2580
2580
  effectId: null
2581
2581
  } }
2582
2582
  }));
2583
2583
  }
2584
- for (const [l, u] of Object.entries(o.deliveries))
2585
- u.phase === "paused" && o.submissions[l].cancelled && we(o, l) && (o = { ...o, deliveries: { ...o.deliveries, [l]: { ...u, phase: "waiting" } } });
2586
- const c = Ws(o), d = Vs(t, c.state, s, e.type === "conversation.recover" && t.checkpointError !== null);
2587
- return { state: d.state, effects: [...d.effects, ...a.effects, ...c.effects], interactionSources: a.interactionSources };
2584
+ for (const [d, u] of Object.entries(o.deliveries))
2585
+ u.phase === "paused" && o.submissions[d].cancelled && we(o, d) && (o = { ...o, deliveries: { ...o.deliveries, [d]: { ...u, phase: "waiting" } } });
2586
+ const c = Ws(o), l = Vs(t, c.state, s, e.type === "conversation.recover" && t.checkpointError !== null);
2587
+ return { state: l.state, effects: [...l.effects, ...a.effects, ...c.effects], interactionSources: a.interactionSources };
2588
2588
  }
2589
2589
  const fo = [
2590
2590
  "submit",
@@ -2664,7 +2664,7 @@ function te(t, e) {
2664
2664
  measure: (i, r) => r()
2665
2665
  };
2666
2666
  const s = performance.now(), n = (i, r, a, o, c) => {
2667
- const d = {
2667
+ const l = {
2668
2668
  ...e,
2669
2669
  stage: i,
2670
2670
  status: r,
@@ -2673,7 +2673,7 @@ function te(t, e) {
2673
2673
  durationMs: Math.max(0, Math.round(performance.now() - a)),
2674
2674
  ...r === "failed" ? { failureCategory: go(c) } : {}
2675
2675
  };
2676
- t && it(d) && Promise.resolve().then(() => t(d)).catch(() => {
2676
+ t && it(l) && Promise.resolve().then(() => t(l)).catch(() => {
2677
2677
  });
2678
2678
  };
2679
2679
  return {
@@ -2706,14 +2706,14 @@ function bo(t) {
2706
2706
  const i = () => n ??= t.read().catch((a) => {
2707
2707
  throw n = null, a;
2708
2708
  }), r = (a, o) => {
2709
- const c = Object.entries(a.operations).filter(([, m]) => m.command.type === "run.stop"), d = Object.entries(a.submissions).filter(([, m]) => m.cancelled);
2710
- if (!o && !d.length && !c.some(([, m]) => m.phase !== "done" && m.phase !== "failed")) return Promise.resolve();
2711
- const l = c[c.length - 1]?.[1].command, u = te(l ? t.onTiming : void 0, {
2709
+ const c = Object.entries(a.operations).filter(([, m]) => m.command.type === "run.stop"), l = Object.entries(a.submissions).filter(([, m]) => m.cancelled);
2710
+ if (!o && !l.length && !c.some(([, m]) => m.phase !== "done" && m.phase !== "failed")) return Promise.resolve();
2711
+ const d = c[c.length - 1]?.[1].command, u = te(d ? t.onTiming : void 0, {
2712
2712
  operation: "stop",
2713
2713
  layer: "http",
2714
- requestId: l?.request_id ?? "cancellation",
2715
- clientMessageId: l ? String(l.payload.expectedUserMessageId) : null,
2716
- sessionId: l ? String(l.payload.sessionId) : null
2714
+ requestId: d?.request_id ?? "cancellation",
2715
+ clientMessageId: d ? String(d.payload.expectedUserMessageId) : null,
2716
+ sessionId: d ? String(d.payload.sessionId) : null
2717
2717
  }), p = e, g = async () => {
2718
2718
  if (!t.isCurrent() || a.authorityId !== t.authorityId) throw new Error("Cancellation authority was retired.");
2719
2719
  if (!o && s && a.requestSequence <= s.requestSequence) return;
@@ -2722,12 +2722,12 @@ function bo(t) {
2722
2722
  const h = { authorityId: t.authorityId, requestSequence: Math.max(a.requestSequence, m?.requestSequence ?? 0), cancelled: { ...m?.cancelled }, operations: { ...m?.operations }, stops: { ...m?.stops } };
2723
2723
  if (o) {
2724
2724
  s = a, a.requestSequence >= (m?.requestSequence ?? 0) && (h.cancelled = {}, h.operations = {}, h.stops = {});
2725
- for (const [v] of d) delete h.cancelled[v];
2725
+ for (const [v] of l) delete h.cancelled[v];
2726
2726
  for (const [v, I] of Object.entries(a.stops)) h.stops[v]?.requestId === I.requestId && delete h.stops[v];
2727
2727
  for (const [v, I] of c)
2728
2728
  JSON.stringify(h.operations[v]?.command) === JSON.stringify(I.command) && delete h.operations[v];
2729
2729
  } else {
2730
- for (const [v, I] of d) s?.submissions[v]?.cancelled || (h.cancelled[v] = { ...I, context: {}, contextPreparation: { pageContent: "", sessionTabs: [] } });
2730
+ for (const [v, I] of l) s?.submissions[v]?.cancelled || (h.cancelled[v] = { ...I, context: {}, contextPreparation: { pageContent: "", sessionTabs: [] } });
2731
2731
  for (const [v, I] of Object.entries(a.stops)) s?.stops[v]?.requestId !== I.requestId && (h.stops[v] = I);
2732
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 });
2733
2733
  }
@@ -2749,18 +2749,18 @@ function bo(t) {
2749
2749
  if (!t.isCurrent()) return null;
2750
2750
  if (a.authorityId !== t.authorityId || o && o.authorityId !== t.authorityId) throw new Error("Cancellation checkpoint authority mismatch.");
2751
2751
  if (s = a, !o || a.requestSequence >= o.requestSequence) return a;
2752
- const c = { ...o.cancelled, ...a.submissions }, d = { ...a.operations, ...o.operations };
2753
- for (const [l, u] of Object.entries(a.operations))
2754
- (u.phase === "done" || u.phase === "failed") && JSON.stringify(u.command) === JSON.stringify(o.operations[l]?.command) && (d[l] = u);
2752
+ const c = { ...o.cancelled, ...a.submissions }, l = { ...a.operations, ...o.operations };
2753
+ for (const [d, u] of Object.entries(a.operations))
2754
+ (u.phase === "done" || u.phase === "failed") && JSON.stringify(u.command) === JSON.stringify(o.operations[d]?.command) && (l[d] = u);
2755
2755
  return {
2756
2756
  ...a,
2757
2757
  requestSequence: Math.max(a.requestSequence, o.requestSequence),
2758
- submissions: Object.fromEntries(Object.entries(c).map(([l, u]) => [
2759
- l,
2760
- l in o.cancelled ? { ...u, cancelled: !0, cancellationReason: o.cancelled[l].cancellationReason } : u
2758
+ submissions: Object.fromEntries(Object.entries(c).map(([d, u]) => [
2759
+ d,
2760
+ d in o.cancelled ? { ...u, cancelled: !0, cancellationReason: o.cancelled[d].cancellationReason } : u
2761
2761
  ])),
2762
- submissionOrder: [...a.submissionOrder, ...Object.keys(o.cancelled).filter((l) => !a.submissionOrder.includes(l))],
2763
- operations: d,
2762
+ submissionOrder: [...a.submissionOrder, ...Object.keys(o.cancelled).filter((d) => !a.submissionOrder.includes(d))],
2763
+ operations: l,
2764
2764
  stops: { ...a.stops, ...o.stops }
2765
2765
  };
2766
2766
  }
@@ -3057,7 +3057,7 @@ function Z(t, e) {
3057
3057
  throw Object.assign(new Error("Conversation authority was retired."), { code: "authority_retired", retryable: !0 });
3058
3058
  }
3059
3059
  function ke(t, e) {
3060
- const s = Y(t, "connection_interrupted", "web_transport"), { code: n, message: i } = s, r = t instanceof Error && "detail" in t ? t.detail : t instanceof Error && "details" in t ? t.details : void 0, a = r && typeof r == "object" && "httpRequest" in r ? r.httpRequest : r, o = a && typeof a == "object" ? a : {}, c = o.category ?? o.transportCode, d = o.elapsedMs ?? o.durationMs, l = r && typeof r == "object" && "successfulRequests" in r && typeof r.successfulRequests == "number" ? r.successfulRequests : 0, u = r && typeof r == "object" && "securitySettingsUrl" in r && typeof r.securitySettingsUrl == "string" ? r.securitySettingsUrl : void 0, p = r && typeof r == "object" && "httpRequest" in r && ye(r.httpRequest) ? r.httpRequest : void 0;
3060
+ const s = Y(t, "connection_interrupted", "web_transport"), { code: n, message: i } = s, r = t instanceof Error && "detail" in t ? t.detail : t instanceof Error && "details" in t ? t.details : void 0, a = r && typeof r == "object" && "httpRequest" in r ? r.httpRequest : r, o = a && typeof a == "object" ? a : {}, c = o.category ?? o.transportCode, l = o.elapsedMs ?? o.durationMs, d = r && typeof r == "object" && "successfulRequests" in r && typeof r.successfulRequests == "number" ? r.successfulRequests : 0, u = r && typeof r == "object" && "securitySettingsUrl" in r && typeof r.securitySettingsUrl == "string" ? r.securitySettingsUrl : void 0, p = r && typeof r == "object" && "httpRequest" in r && ye(r.httpRequest) ? r.httpRequest : void 0;
3061
3061
  return Object.assign(new Error(i), {
3062
3062
  code: n,
3063
3063
  // Keep the actionable public URL without copying arbitrary transport internals into durable errors.
@@ -3068,8 +3068,8 @@ function ke(t, e) {
3068
3068
  ...u ? { securitySettingsUrl: u } : {},
3069
3069
  ...typeof c == "string" && /^[a-z0-9_]{1,80}$/.test(c) ? { transportCode: c } : {},
3070
3070
  ...typeof o.requestId == "string" && /^[a-zA-Z0-9_-]{1,160}$/.test(o.requestId) ? { requestId: o.requestId } : {},
3071
- ...typeof d == "number" && Number.isFinite(d) && d >= 0 ? { durationMs: d } : {},
3072
- successfulRequests: l
3071
+ ...typeof l == "number" && Number.isFinite(l) && l >= 0 ? { durationMs: l } : {},
3072
+ successfulRequests: d
3073
3073
  },
3074
3074
  retryable: t !== null && typeof t == "object" && "retryable" in t && typeof t.retryable == "boolean" ? t.retryable : ["authority_retired", "executor_not_ready", "connection_interrupted", "request_timed_out", "408", "425", "429"].includes(n) || /^5\d\d$/.test(n)
3075
3075
  });
@@ -3077,39 +3077,39 @@ function ke(t, e) {
3077
3077
  function Mo(t) {
3078
3078
  let e = Promise.resolve();
3079
3079
  const s = (o = ln(t.runtime().engine.getState().slices.conversation, t.runtime().engine.getState().slices.directory), c = Promise.resolve()) => {
3080
- const d = c.then(() => ({ ok: !0 }), (u) => ({ ok: !1, error: u })), l = async () => {
3081
- const u = await d;
3080
+ const l = c.then(() => ({ ok: !0 }), (u) => ({ ok: !1, error: u })), d = async () => {
3081
+ const u = await l;
3082
3082
  if (!u.ok) throw u.error;
3083
3083
  return Z(t, t.authority), t.saveDelivery(o);
3084
3084
  };
3085
- return e = e.then(l, l), e;
3085
+ return e = e.then(d, d), e;
3086
3086
  }, n = (o, c) => {
3087
3087
  throw Q(t) && !(o instanceof Error && "code" in o && ["executor_not_ready", "request_timed_out"].includes(String(o.code))) && t.onError?.(o, c), ke(o, c);
3088
3088
  }, i = () => {
3089
- const { token: o, protocol: c, ...d } = t.http.auth;
3090
- return { ...d, ...t.connectionId() ? { connection_id: t.connectionId() } : {} };
3089
+ const { token: o, protocol: c, ...l } = t.http.auth;
3090
+ return { ...l, ...t.connectionId() ? { connection_id: t.connectionId() } : {} };
3091
3091
  }, r = (o) => {
3092
3092
  if (Z(t, t.authority), t.runtime().engine.getState().slices.conversation.submissions[o]?.cancelled)
3093
3093
  throw Object.assign(new Error("Submission was cancelled."), { code: "submission_cancelled", retryable: !1 });
3094
3094
  }, a = (o) => {
3095
3095
  if (!t.onTiming || o.submission.sessionId !== null) return;
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));
3097
- if (!d) return;
3098
- const l = te(t.onTiming, {
3096
+ const c = t.runtime(), l = 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));
3097
+ if (!l) return;
3098
+ const d = te(t.onTiming, {
3099
3099
  operation: "send",
3100
3100
  layer: "http",
3101
- requestId: d.command.request_id,
3101
+ requestId: l.command.request_id,
3102
3102
  clientMessageId: o.submission.userMessageId,
3103
- sessionId: typeof d.command.payload.warmupId == "string" ? d.command.payload.warmupId : null,
3103
+ sessionId: typeof l.command.payload.warmupId == "string" ? l.command.payload.warmupId : null,
3104
3104
  entrySurface: o.submission.entrySurface
3105
3105
  });
3106
3106
  let u = () => {
3107
3107
  }, p = () => {
3108
3108
  };
3109
- l.measure("warmup_wait", () => new Promise((g, m) => {
3109
+ d.measure("warmup_wait", () => new Promise((g, m) => {
3110
3110
  const h = () => {
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();
3111
+ const v = c.engine.getState().slices, I = v.conversation.submissions[o.submission.userMessageId], _ = v.conversation.operations[l.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 || !_ || !["waiting", "running", "uncertain"].includes(_.phase)) && g();
3113
3113
  };
3114
3114
  u = c.engine.subscribe(h), p = c.onDispose(() => m(new Error("Warmup wait was retired."))), h();
3115
3115
  })).catch(() => {
@@ -3121,19 +3121,19 @@ function Mo(t) {
3121
3121
  "conversation.prepare": async (o) => {
3122
3122
  r(o.submission.userMessageId);
3123
3123
  let c;
3124
- const d = new Promise((p, g) => {
3124
+ const l = new Promise((p, g) => {
3125
3125
  c = setTimeout(() => g(Object.assign(
3126
3126
  new Error("Message preparation timed out. Retry this message."),
3127
3127
  { code: "submission_preparation_timeout", retryable: !0 }
3128
3128
  )), 18e4);
3129
3129
  });
3130
- let l = () => {
3130
+ let d = () => {
3131
3131
  };
3132
3132
  const u = new Promise((p, g) => {
3133
- l = t.runtime().onDispose(() => g(new Error("Submission runtime was disposed.")));
3133
+ d = t.runtime().onDispose(() => g(new Error("Submission runtime was disposed.")));
3134
3134
  });
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(() => {
3136
- clearTimeout(c), l();
3135
+ return Promise.race([t.prepareSubmission(o), l, u]).then((p) => (r(o.submission.userMessageId), a(o), p)).catch((p) => n(p, { operation: "conversation.prepare", requestId: o.submission.userMessageId })).finally(() => {
3136
+ clearTimeout(c), d();
3137
3137
  });
3138
3138
  },
3139
3139
  "conversation.checkpoint": async (o) => (Z(t, o), await s(o.checkpoint, t.saveCancellation(o.checkpoint)).catch((c) => n(c, { operation: "conversation.checkpoint" })), Z(t, o), null),
@@ -3163,14 +3163,14 @@ function Mo(t) {
3163
3163
  let c = !1;
3164
3164
  return Promise.resolve().then(async () => {
3165
3165
  Z(t, o), (o.command.type === "chat.user_message" || o.command.type === "attachment.upload_completed") && r(String(o.command.payload.clientMessageId));
3166
- const d = o.command.payload, l = o.command.type === "runtime.warmup", u = te(["runtime.warmup", "chat.user_message", "chat.retry_last_user_message", "run.stop", "attachment.upload_completed"].includes(o.command.type) ? t.onTiming : void 0, {
3166
+ const l = o.command.payload, d = o.command.type === "runtime.warmup", u = te(["runtime.warmup", "chat.user_message", "chat.retry_last_user_message", "run.stop", "attachment.upload_completed"].includes(o.command.type) ? t.onTiming : void 0, {
3167
3167
  operation: o.command.type === "run.stop" ? "stop" : "send",
3168
3168
  layer: "http",
3169
3169
  requestId: o.command.request_id,
3170
- clientMessageId: l ? null : String(d.clientMessageId ?? d.expectedUserMessageId ?? o.command.request_id),
3171
- sessionId: typeof d.sessionId == "string" ? d.sessionId : l && typeof d.warmupId == "string" ? d.warmupId : null
3170
+ clientMessageId: d ? null : String(l.clientMessageId ?? l.expectedUserMessageId ?? o.command.request_id),
3171
+ sessionId: typeof l.sessionId == "string" ? l.sessionId : d && typeof l.warmupId == "string" ? l.warmupId : null
3172
3172
  });
3173
- return await u.measure(l ? "warmup_checkpoint" : "checkpoint", () => o.command.type === "run.stop" ? t.saveCancellation(t.runtime().engine.getState().slices.conversation) : s()), Z(t, o), (o.command.type === "chat.user_message" || o.command.type === "attachment.upload_completed") && r(String(o.command.payload.clientMessageId)), t.onCommand?.(o.command), c = !0, await u.measure(l ? "warmup_http" : "command_http", async () => {
3173
+ return await u.measure(d ? "warmup_checkpoint" : "checkpoint", () => o.command.type === "run.stop" ? t.saveCancellation(t.runtime().engine.getState().slices.conversation) : s()), Z(t, o), (o.command.type === "chat.user_message" || o.command.type === "attachment.upload_completed") && r(String(o.command.payload.clientMessageId)), t.onCommand?.(o.command), c = !0, await u.measure(d ? "warmup_http" : "command_http", async () => {
3174
3174
  const p = await t.http.request(
3175
3175
  "/commands",
3176
3176
  {},
@@ -3187,24 +3187,24 @@ function Mo(t) {
3187
3187
  operation: "send",
3188
3188
  layer: "http",
3189
3189
  requestId: o.command.request_id,
3190
- clientMessageId: String(d.clientMessageId),
3190
+ clientMessageId: String(l.clientMessageId),
3191
3191
  sessionId: g.sessionId
3192
3192
  }).mark("acceptance_received");
3193
3193
  }
3194
3194
  return p.result;
3195
3195
  });
3196
- }).catch((d) => {
3197
- if (o.previousAcceptance === "unissued" && d instanceof Error && "backendRefusal" in d && d.backendRefusal === !0) {
3198
- Q(t) && t.onError?.(d, { operation: o.command.type, requestId: o.command.request_id });
3199
- const l = ke(d);
3200
- throw Object.assign(l, { details: { ...l.details, acceptance: "rejected" } });
3196
+ }).catch((l) => {
3197
+ if (o.previousAcceptance === "unissued" && l instanceof Error && "backendRefusal" in l && l.backendRefusal === !0) {
3198
+ Q(t) && t.onError?.(l, { operation: o.command.type, requestId: o.command.request_id });
3199
+ const d = ke(l);
3200
+ throw Object.assign(d, { details: { ...d.details, acceptance: "rejected" } });
3201
3201
  }
3202
3202
  if (!c && o.previousAcceptance === "unissued") {
3203
- const l = ke(d);
3204
- throw Object.assign(l, { details: { ...l.details, acceptance: "unissued" } });
3203
+ const d = ke(l);
3204
+ throw Object.assign(d, { details: { ...d.details, acceptance: "unissued" } });
3205
3205
  }
3206
- if (d instanceof Error && "code" in d && d.code === "403") throw ke(d);
3207
- return n(d, { operation: o.command.type, requestId: o.command.request_id });
3206
+ if (l instanceof Error && "code" in l && l.code === "403") throw ke(l);
3207
+ return n(l, { operation: o.command.type, requestId: o.command.request_id });
3208
3208
  });
3209
3209
  },
3210
3210
  "conversation.upload": (o) => {
@@ -3216,15 +3216,15 @@ function Mo(t) {
3216
3216
  clientMessageId: o.submission.userMessageId,
3217
3217
  sessionId: o.submission.sessionId
3218
3218
  }).measure("attachment_upload", () => Promise.resolve().then(async () => {
3219
- const d = () => {
3219
+ const l = () => {
3220
3220
  if (Z(t, o), !o.preparationId) return r(o.submission.userMessageId);
3221
3221
  const h = t.runtime().engine.getState().slices.directory;
3222
3222
  if (!Object.values(h.clients).includes(o.submission.conversationScopeId))
3223
3223
  throw Object.assign(new Error("Attachment preparation was cancelled."), { code: "submission_cancelled", retryable: !1 });
3224
3224
  };
3225
- d(), await s(), d();
3226
- const l = await t.readAttachment(o.source.sourceId);
3227
- if (d(), l.size !== o.source.sizeBytes) throw Object.assign(new Error("Attachment source changed."), { code: "attachment_changed" });
3225
+ l(), await s(), l();
3226
+ const d = await t.readAttachment(o.source.sourceId);
3227
+ if (l(), d.size !== o.source.sizeBytes) throw Object.assign(new Error("Attachment source changed."), { code: "attachment_changed" });
3228
3228
  const u = {
3229
3229
  sessionId: o.submission.sessionId ?? void 0,
3230
3230
  attachmentId: o.source.sourceId,
@@ -3240,14 +3240,14 @@ function Mo(t) {
3240
3240
  entrySurface: o.submission.entrySurface
3241
3241
  };
3242
3242
  c = !0;
3243
- const p = t.persistUpload ? await t.persistUpload(u, new File([l], o.source.name, { type: o.source.mimeType })) : t.prepareUpload ? await t.prepareUpload(u) : await t.http.request("/attachments/upload", {}, u);
3244
- if (d(), !p.sessionId || o.submission.sessionId && p.sessionId !== o.submission.sessionId || p.attachment.id !== o.source.sourceId || p.attachment.mimeType !== o.source.mimeType || p.attachment.sizeBytes !== o.source.sizeBytes)
3243
+ const p = t.persistUpload ? await t.persistUpload(u, new File([d], o.source.name, { type: o.source.mimeType })) : t.prepareUpload ? await t.prepareUpload(u) : await t.http.request("/attachments/upload", {}, u);
3244
+ if (l(), !p.sessionId || o.submission.sessionId && p.sessionId !== o.submission.sessionId || p.attachment.id !== o.source.sourceId || p.attachment.mimeType !== o.source.mimeType || p.attachment.sizeBytes !== o.source.sizeBytes)
3245
3245
  throw Object.assign(new Error("Attachment preparation identity mismatch."), { code: "attachment_identity_mismatch", retryable: !1 });
3246
3246
  if ("uploadUrl" in p) {
3247
- const h = await fetch(t.http.resolveUrl(p.uploadUrl), { method: p.uploadMethod, headers: p.uploadHeaders, body: l });
3247
+ const h = await fetch(t.http.resolveUrl(p.uploadUrl), { method: p.uploadMethod, headers: p.uploadHeaders, body: d });
3248
3248
  if (!h.ok) throw Object.assign(new Error("Attachment transfer failed."), { code: String(h.status) });
3249
3249
  }
3250
- d();
3250
+ l();
3251
3251
  const g = p.attachment, m = {
3252
3252
  id: g.id ?? null,
3253
3253
  name: g.name,
@@ -3257,50 +3257,50 @@ function Mo(t) {
3257
3257
  sandbox_path: g.sandboxPath ?? null,
3258
3258
  file_url: g.fileUrl ?? null
3259
3259
  };
3260
- return await t.onUploaded?.(o.source.sourceId, p.sessionId, m), d(), { sessionId: p.sessionId, attachment: m };
3261
- }).catch((d) => {
3260
+ return await t.onUploaded?.(o.source.sourceId, p.sessionId, m), l(), { sessionId: p.sessionId, attachment: m };
3261
+ }).catch((l) => {
3262
3262
  if (!c && o.previousAllocation === "unissued") {
3263
- const l = ke(d);
3264
- throw Object.assign(l, { details: { ...l.details, allocation: "unissued" } });
3263
+ const d = ke(l);
3264
+ throw Object.assign(d, { details: { ...d.details, allocation: "unissued" } });
3265
3265
  }
3266
- return n(d, { operation: "conversation.upload", requestId: o.submission.userMessageId, ...o.submission.sessionId ? { sessionId: o.submission.sessionId } : {} });
3266
+ return n(l, { operation: "conversation.upload", requestId: o.submission.userMessageId, ...o.submission.sessionId ? { sessionId: o.submission.sessionId } : {} });
3267
3267
  }));
3268
3268
  },
3269
3269
  "conversation.snapshot": (o) => Promise.resolve().then(async () => {
3270
3270
  Z(t, o);
3271
- const c = t.runtime(), d = new AbortController(), l = () => {
3271
+ const c = t.runtime(), l = new AbortController(), d = () => {
3272
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");
3274
- }, u = c.engine.subscribe(l), p = c.onDispose(() => d.abort("owner_disposed"));
3275
- l();
3273
+ Q(t) ? g.directory.memberships[o.sessionId]?.members.length ? g.conversation.sessions[o.sessionId]?.queries[o.lane].requestId !== o.requestId && l.abort("request_replaced") : l.abort("observation_released") : l.abort("authority_retired");
3274
+ }, u = c.engine.subscribe(d), p = c.onDispose(() => l.abort("owner_disposed"));
3275
+ d();
3276
3276
  try {
3277
3277
  const g = [];
3278
3278
  for (let I = 0; I < Math.max(1, o.refreshItemIds.length); I += 200) {
3279
3279
  if (Z(t, o), !t.runtime().engine.getState().slices.directory.memberships[o.sessionId]?.members.length) throw new Error("Conversation observation was retired.");
3280
- const k = await t.http.request(
3280
+ const _ = await t.http.request(
3281
3281
  `/${encodeURIComponent(o.sessionId)}/snapshot`,
3282
3282
  {},
3283
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) },
3284
3284
  "POST",
3285
3285
  "conversations",
3286
- { readOnly: !0, signal: d.signal, diagnostic: {
3286
+ { readOnly: !0, signal: l.signal, diagnostic: {
3287
3287
  sessionId: o.sessionId,
3288
3288
  queryRequestId: o.requestId,
3289
3289
  ownerId: c.engine.getDiagnostics().ownerId,
3290
3290
  authorityGeneration: o.generation
3291
3291
  } }
3292
- ).catch((w) => {
3293
- if (g.length === 0) throw w;
3294
- const f = ke(w);
3292
+ ).catch((S) => {
3293
+ if (g.length === 0) throw S;
3294
+ const f = ke(S);
3295
3295
  throw Object.assign(f, { details: { ...f.details, successfulRequests: g.length } });
3296
3296
  });
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;
3297
+ if (Z(t, o), _.conversation_id !== o.sessionId) throw new Error("Snapshot conversation identity mismatch.");
3298
+ if (g.push(_), !_.projection_ready) break;
3299
3299
  }
3300
3300
  const m = g[0];
3301
3301
  if (o.before !== null && m.next_cursor === o.before)
3302
3302
  throw Object.assign(new Error("Conversation history cursor did not advance."), { code: "invalid_history_cursor" });
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);
3303
+ const h = g.reduce((I, _) => _.execution.version > I.version ? _.execution : I, m.execution), v = g.reduce((I, _) => _.follow_ups_version > I.follow_ups_version ? _ : I, m);
3304
3304
  return { snapshot: {
3305
3305
  ...m,
3306
3306
  execution: h,
@@ -3316,10 +3316,10 @@ function Mo(t) {
3316
3316
  u(), p();
3317
3317
  }
3318
3318
  }).catch((c) => {
3319
- const d = ke(c, { requestId: o.requestId, sessionId: o.sessionId });
3320
- if (["display_projection_disabled", "409", "connection_interrupted", "request_timed_out", "request_cancelled", "408", "425", "429", "500", "502", "503", "504"].includes(d.code))
3321
- throw Object.assign(d, { code: "history_load_failed", message: "We couldn’t refresh this conversation. Try again.", retryable: !0 });
3322
- if (Pi(d.code)) throw Object.assign(d, { retryable: !0 });
3319
+ const l = ke(c, { requestId: o.requestId, sessionId: o.sessionId });
3320
+ if (["display_projection_disabled", "409", "connection_interrupted", "request_timed_out", "request_cancelled", "408", "425", "429", "500", "502", "503", "504"].includes(l.code))
3321
+ throw Object.assign(l, { code: "history_load_failed", message: "We couldn’t refresh this conversation. Try again.", retryable: !0 });
3322
+ if (Pi(l.code)) throw Object.assign(l, { retryable: !0 });
3323
3323
  return n(c, { operation: "conversation.snapshot", requestId: o.requestId, sessionId: o.sessionId });
3324
3324
  })
3325
3325
  };
@@ -3358,11 +3358,11 @@ class Po {
3358
3358
  isActiveTurn: () => !1,
3359
3359
  poll: async () => {
3360
3360
  for (; !this.disposed && Q(this.options) && this.observations.get(r)?.history === o; ) {
3361
- const d = e.engine.getState().slices.conversation.sessions[r]?.queries.history;
3362
- if (!d || d.cursor === null || d.error && !d.error.retryable) return;
3363
- const l = d.cursor;
3361
+ const l = e.engine.getState().slices.conversation.sessions[r]?.queries.history;
3362
+ if (!l || l.cursor === null || l.error && !l.error.retryable) return;
3363
+ const d = l.cursor;
3364
3364
  if (await this.refresh(r, "history"), this.observations.get(r)?.history !== o) return;
3365
- if (e.engine.getState().slices.conversation.sessions[r]?.queries.history.cursor === l)
3365
+ if (e.engine.getState().slices.conversation.sessions[r]?.queries.history.cursor === d)
3366
3366
  throw new Error("Conversation history cursor did not advance.");
3367
3367
  }
3368
3368
  }
@@ -3371,15 +3371,15 @@ class Po {
3371
3371
  idleIntervalMs: 6e4,
3372
3372
  maxFailureIntervalMs: 6e4,
3373
3373
  isActiveTurn: () => {
3374
- const d = e.engine.getState().slices.conversation;
3375
- return !!d.sessions[r]?.preparation || ["thinking", "steering", "queued", "stopping"].includes(d.sessions[r]?.execution?.phase ?? "idle") || Object.values(d.submissions).some((l) => l.sessionId === r && !l.cancelled && !["accepted", "failed"].includes(l.delivery));
3374
+ const l = e.engine.getState().slices.conversation;
3375
+ return !!l.sessions[r]?.preparation || ["thinking", "steering", "queued", "stopping"].includes(l.sessions[r]?.execution?.phase ?? "idle") || Object.values(l.submissions).some((d) => d.sessionId === r && !d.cancelled && !["accepted", "failed"].includes(d.delivery));
3376
3376
  },
3377
3377
  poll: async () => {
3378
- const d = e.engine.getState().slices.conversation.sessions[r]?.queries.current;
3379
- if (d?.error && !d.error.retryable) return;
3378
+ const l = e.engine.getState().slices.conversation.sessions[r]?.queries.current;
3379
+ if (l?.error && !l.error.retryable) return;
3380
3380
  await this.refresh(r);
3381
- const l = e.engine.getState().slices.conversation.sessions[r]?.queries.history;
3382
- l?.status === "ready" && l.cursor !== null && o.refresh();
3381
+ const d = e.engine.getState().slices.conversation.sessions[r]?.queries.history;
3382
+ d?.status === "ready" && d.cursor !== null && o.refresh();
3383
3383
  }
3384
3384
  });
3385
3385
  this.observations.set(r, { current: c, history: o, roomRequested: !1 }), c.start(r, this.owner), o.start(r, this.owner);
@@ -3396,12 +3396,12 @@ class Po {
3396
3396
  if (!Q(this.options) || !this.observations.has(e)) return Promise.resolve();
3397
3397
  const r = i ?? this.options.nextRequestId();
3398
3398
  return n.engine.dispatch({ ...this.options.authority, type: "conversation.snapshot", sessionId: e, requestId: r, lane: s }).then(() => new Promise((o, c) => {
3399
- let d = null;
3400
- const l = () => {
3399
+ let l = null;
3400
+ const d = () => {
3401
3401
  const u = n.engine.getState().slices.conversation.sessions[e]?.queries[s], p = !this.disposed && Q(this.options) && this.observations.has(e);
3402
- return p && u?.requestId === r ? !1 : (d?.(), this.waiters.delete(l), p && u?.status === "error" ? c(u.error) : o(), !0);
3402
+ return p && u?.requestId === r ? !1 : (l?.(), this.waiters.delete(d), p && u?.status === "error" ? c(u.error) : o(), !0);
3403
3403
  };
3404
- l() || (this.waiters.add(l), d = n.engine.subscribe(l));
3404
+ d() || (this.waiters.add(d), l = n.engine.subscribe(d));
3405
3405
  }));
3406
3406
  }
3407
3407
  receive(e) {
@@ -3455,10 +3455,10 @@ function Gs(t, e, s = "stopped", n, i = "Run stopped by user.") {
3455
3455
  t.messages.filter((c) => c.role === "user").slice(-1)[0]?.id
3456
3456
  ].filter((c) => !!c)), a = t.messages.filter((c) => !(c.dataType === "run_status" && c.loading && r.has(c.respondsToUserMessageId ?? ""))).map((c) => r.has(c.respondsToUserMessageId ?? "") ? { ...c, loading: !1 } : c);
3457
3457
  for (const c of r)
3458
- a.some((d) => d.respondsToUserMessageId === c && (d.dataType === "run_status" || d.dataType === "run_error" || d.role === "assistant" && d.phase !== "commentary")) || a.some((d) => d.role === "user" && d.id === c) && a.push({ id: `local-interrupted:${c}`, role: "system", dataType: "run_status", provisional: s === "stopping", content: s === "stopping" ? "Stopping…" : i, createdAt: e, respondsToUserMessageId: c });
3458
+ a.some((l) => l.respondsToUserMessageId === c && (l.dataType === "run_status" || l.dataType === "run_error" || l.role === "assistant" && l.phase !== "commentary")) || a.some((l) => l.role === "user" && l.id === c) && a.push({ id: `local-interrupted:${c}`, role: "system", dataType: "run_status", provisional: s === "stopping", content: s === "stopping" ? "Stopping…" : i, createdAt: e, respondsToUserMessageId: c });
3459
3459
  const o = t.segments?.map((c) => ({ ...c, outcomeIds: [
3460
3460
  ...c.outcomeIds,
3461
- ...a.filter((d) => d.id === `local-interrupted:${c.userMessageId}` && !c.outcomeIds.includes(d.id)).map((d) => d.id)
3461
+ ...a.filter((l) => l.id === `local-interrupted:${c.userMessageId}` && !c.outcomeIds.includes(l.id)).map((l) => l.id)
3462
3462
  ] }));
3463
3463
  return {
3464
3464
  ...t,
@@ -3525,7 +3525,7 @@ function Uo(t, e, s, n) {
3525
3525
  function as(t, e, s, n) {
3526
3526
  const i = /* @__PURE__ */ new Map();
3527
3527
  for (const y of t.segments)
3528
- for (const b of [...y.activityIds, ...y.outcomeIds]) i.set(b, y.userMessageId);
3528
+ for (const w of [...y.activityIds, ...y.outcomeIds]) i.set(w, y.userMessageId);
3529
3529
  const r = t.items.map((y) => Uo(
3530
3530
  y,
3531
3531
  i.get(y.id) ?? null,
@@ -3539,14 +3539,19 @@ function as(t, e, s, n) {
3539
3539
  // There is no canonical timestamp before acceptance. Keep identity stable without fabricating one.
3540
3540
  createdAt: "",
3541
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
3542
+ attachments: y.attachments.map((w) => ({
3543
+ id: w.sourceId,
3544
+ name: w.name,
3545
+ mimeType: w.mimeType,
3546
+ sizeBytes: w.sizeBytes
3547
3547
  }))
3548
3548
  });
3549
- const a = t.segments.flatMap((y) => r.filter((b) => b.id === y.userMessageId || y.activityIds.includes(b.id) || y.outcomeIds.includes(b.id)));
3549
+ const a = t.segments.flatMap((y) => r.filter((w) => w.id === y.userMessageId || y.activityIds.includes(w.id) || y.outcomeIds.includes(w.id))), o = { ...t.removedItems };
3550
+ for (const y of t.segments) {
3551
+ if (!y.userMessageId) continue;
3552
+ const w = r.find((R) => y.outcomeIds.includes(R.id) && !R.loading && (R.dataType === "run_status" || R.dataType === "run_error" || R.role === "assistant" && R.phase === "final_answer" && R.streamState === "finished"));
3553
+ w && (o[`local-interrupted:${y.userMessageId}`] = w.id);
3554
+ }
3550
3555
  t.proactiveQuestion && a.push({
3551
3556
  id: t.proactiveQuestion.id,
3552
3557
  role: "assistant",
@@ -3555,28 +3560,28 @@ function as(t, e, s, n) {
3555
3560
  createdAt: "",
3556
3561
  loading: !1
3557
3562
  });
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}`,
3563
+ const c = t.activity.phase, l = t.submissions.filter((y) => !y.cancelled && !["accepted", "failed"].includes(y.delivery)), d = t.submissions[t.submissions.length - 1], u = [...t.items].reverse().find((y) => y.type === "user_message"), p = ["queued", "thinking", "steering", "awaiting_execution"].includes(c), g = d?.delivery === "failed" && (p && t.activity.userMessageId != null && t.activity.userMessageId !== d.userMessageId || u !== void 0 && u.id !== d.userMessageId && Date.parse(u.created_at) > d.submittedAt), m = new Map(t.submissions.filter((y) => (y !== d || g) && !y.cancelled && y.delivery === "failed" && y.error).map((y) => [y.userMessageId, y])), h = a.flatMap((y) => {
3564
+ const w = y.role === "user" ? m.get(y.id) : void 0;
3565
+ return w?.error ? [y, {
3566
+ id: `submission-error:${w.userMessageId}`,
3562
3567
  role: "system",
3563
3568
  dataType: "run_error",
3564
- respondsToUserMessageId: b.userMessageId,
3565
- content: b.error.message,
3569
+ respondsToUserMessageId: w.userMessageId,
3570
+ content: w.error.message,
3566
3571
  createdAt: "",
3567
3572
  loading: !1,
3568
- ...typeof b.error.details?.securitySettingsUrl == "string" ? { securitySettingsUrl: b.error.details.securitySettingsUrl } : {}
3573
+ ...typeof w.error.details?.securitySettingsUrl == "string" ? { securitySettingsUrl: w.error.details.securitySettingsUrl } : {}
3569
3574
  }] : [y];
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 = {
3575
+ }), v = e?.error != null && t.historyRefreshFailure != null && t.historyRefreshFailure.consecutiveFailures < 4, I = v ? null : e?.error ?? null, _ = d?.delivery === "failed" && !d.cancelled && !g ? d.error : I, S = {
3571
3576
  isRetrying: t.isRetrying ?? !1,
3572
- historyRefreshFailure: I === e?.error ? t.historyRefreshFailure ?? null : null,
3577
+ historyRefreshFailure: _ === e?.error ? t.historyRefreshFailure ?? null : null,
3573
3578
  conversationDiagnostics: {
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 } : {},
3579
+ ..._ ? { errorMessageFingerprint: Vi(Ce(_.message)) } : {},
3580
+ ...d && _ && _ === d.error && !g ? { failedClientMessageId: d.userMessageId } : {},
3581
+ ...typeof _?.details?.requestId == "string" ? { errorRequestId: _.details.requestId } : {},
3582
+ ...nt(_?.details?.errorNormalization) ? { errorNormalization: _.details.errorNormalization } : {},
3578
3583
  ...n ? { owner: n } : {},
3579
- ...ye(I?.details?.httpRequest) ? { httpRequest: I.details.httpRequest } : {},
3584
+ ...ye(_?.details?.httpRequest) ? { httpRequest: _.details.httpRequest } : {},
3580
3585
  queryStatus: e?.status ?? null,
3581
3586
  queryRequestId: e?.requestId ?? null,
3582
3587
  queryUpdatedAt: e?.updatedAt ?? null
@@ -3585,43 +3590,43 @@ function as(t, e, s, n) {
3585
3590
  selectionKey: t.selectionKey,
3586
3591
  isDraftSession: t.isDraftSession,
3587
3592
  sessionId: t.sessionId,
3588
- messages: m,
3589
- removedItems: t.removedItems,
3593
+ messages: h,
3594
+ removedItems: o,
3590
3595
  activeResponseUserMessageId: t.activity.userMessageId ?? t.segments[t.segments.length - 1]?.userMessageId ?? d?.userMessageId ?? null,
3591
3596
  segments: t.segments,
3592
3597
  activity: t.activity,
3593
3598
  receipts: t.receipts,
3594
3599
  activeScheduledFollowUps: t.followUps.map((y) => ({ taskId: y.task_id, dueAt: y.due_at })),
3595
3600
  // A selected, not-yet-requested conversation must not paint the empty new-chat welcome state.
3596
- isLoadingSession: !!t.preparation || !t.isDraftSession && t.sessionId !== null && (!e || e.status === "not_requested" || (e.status === "loading" || h && a.length === 0) && e.data === null),
3601
+ isLoadingSession: !!t.preparation || !t.isDraftSession && t.sessionId !== null && (!e || e.status === "not_requested" || (e.status === "loading" || v && a.length === 0) && e.data === null),
3597
3602
  // Streams are already canonical items. A second draft field would render the same text twice.
3598
3603
  assistantDraft: "",
3599
3604
  assistantDraftItemId: null,
3600
3605
  assistantDraftPhase: null,
3601
3606
  assistantDraftRespondsToUserMessageId: null,
3602
3607
  assistantDraftRunId: null,
3603
- pendingMessageStatus: c.length ? c.some((y) => y.delivery === "uncertain") ? "reconnecting" : "sending" : null,
3604
- turnPhase: o === "submitting" ? "sending" : ["queued", "awaiting_execution"].includes(o) ? "starting" : ["thinking", "steering"].includes(o) ? "thinking" : null,
3605
- isThinking: u,
3606
- taskStatus: o === "completed" ? "completed" : o === "failed" ? "failed" : o === "stopped" || o === "stopping" ? "stopped" : u || o === "submitting" ? "working" : null,
3607
- lastError: I?.message ?? null,
3608
- lastErrorCode: I?.code ?? null,
3609
- lastErrorSecuritySettingsUrl: typeof I?.details?.securitySettingsUrl == "string" ? I.details.securitySettingsUrl : null
3608
+ pendingMessageStatus: l.length ? l.some((y) => y.delivery === "uncertain") ? "reconnecting" : "sending" : null,
3609
+ turnPhase: c === "submitting" ? "sending" : ["queued", "awaiting_execution"].includes(c) ? "starting" : ["thinking", "steering"].includes(c) ? "thinking" : null,
3610
+ isThinking: p,
3611
+ taskStatus: c === "completed" ? "completed" : c === "failed" ? "failed" : c === "stopped" || c === "stopping" ? "stopped" : p || c === "submitting" ? "working" : null,
3612
+ lastError: _?.message ?? null,
3613
+ lastErrorCode: _?.code ?? null,
3614
+ lastErrorSecuritySettingsUrl: typeof _?.details?.securitySettingsUrl == "string" ? _.details.securitySettingsUrl : null
3610
3615
  };
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,
3616
+ let f = S;
3617
+ for (const y of t.optimistic.filter((w) => w.cancelled && !t.stop?.userMessageIds.includes(w.userMessageId))) {
3618
+ const w = Gs(f, "", "stopped", [y.userMessageId], Gn(y.cancellationReason));
3619
+ f = { ...f, messages: w.messages, segments: w.segments };
3620
+ }
3621
+ if (!t.stop) return f;
3622
+ const b = Gs(
3623
+ f,
3619
3624
  "",
3620
3625
  t.stop.pending ? "stopping" : "stopped",
3621
3626
  t.stop.userMessageIds,
3622
3627
  Gn(t.stop.reason ?? "user_requested")
3623
3628
  );
3624
- return { ...k, messages: f.messages, segments: f.segments };
3629
+ return { ...S, messages: b.messages, segments: b.segments };
3625
3630
  }
3626
3631
  function Gn(t) {
3627
3632
  switch (t) {
@@ -3830,10 +3835,10 @@ for (let t = 0; t < Yn.length; t++)
3830
3835
  const Ho = (t) => {
3831
3836
  let e = t.length * 0.75, s = t.length, n, i = 0, r, a, o, c;
3832
3837
  t[t.length - 1] === "=" && (e--, t[t.length - 2] === "=" && e--);
3833
- const d = new ArrayBuffer(e), l = new Uint8Array(d);
3838
+ const l = new ArrayBuffer(e), d = new Uint8Array(l);
3834
3839
  for (n = 0; n < s; n += 4)
3835
- r = Xe[t.charCodeAt(n)], a = Xe[t.charCodeAt(n + 1)], o = Xe[t.charCodeAt(n + 2)], c = Xe[t.charCodeAt(n + 3)], l[i++] = r << 2 | a >> 4, l[i++] = (a & 15) << 4 | o >> 2, l[i++] = (o & 3) << 6 | c & 63;
3836
- return d;
3840
+ r = Xe[t.charCodeAt(n)], a = Xe[t.charCodeAt(n + 1)], o = Xe[t.charCodeAt(n + 2)], c = Xe[t.charCodeAt(n + 3)], d[i++] = r << 2 | a >> 4, d[i++] = (a & 15) << 4 | o >> 2, d[i++] = (o & 3) << 6 | c & 63;
3841
+ return l;
3837
3842
  }, Vo = typeof ArrayBuffer == "function", mn = (t, e) => {
3838
3843
  if (typeof t != "string")
3839
3844
  return {
@@ -3928,12 +3933,12 @@ function Qo(t, e) {
3928
3933
  } else if (n === 2) {
3929
3934
  if (ht(s) < 8)
3930
3935
  break;
3931
- const c = ft(s, 8), d = new DataView(c.buffer, c.byteOffset, c.length), l = d.getUint32(0);
3932
- if (l > Math.pow(2, 21) - 1) {
3936
+ const c = ft(s, 8), l = new DataView(c.buffer, c.byteOffset, c.length), d = l.getUint32(0);
3937
+ if (d > Math.pow(2, 21) - 1) {
3933
3938
  o.enqueue(Js);
3934
3939
  break;
3935
3940
  }
3936
- i = l * Math.pow(2, 32) + d.getUint32(4), n = 3;
3941
+ i = d * Math.pow(2, 32) + l.getUint32(4), n = 3;
3937
3942
  } else {
3938
3943
  if (ht(s) < i)
3939
3944
  break;
@@ -4870,7 +4875,7 @@ class wa extends _e {
4870
4875
  if (this.upgrading = !0, this.emitReserved("upgrading", s), !s)
4871
4876
  return;
4872
4877
  _e.priorWebsocketSuccess = s.name === "websocket", this.transport.pause(() => {
4873
- n || this.readyState !== "closed" && (l(), this.setTransport(s), s.send([{ type: "upgrade" }]), this.emitReserved("upgrade", s), s = null, this.upgrading = !1, this.flush());
4878
+ n || this.readyState !== "closed" && (d(), this.setTransport(s), s.send([{ type: "upgrade" }]), this.emitReserved("upgrade", s), s = null, this.upgrading = !1, this.flush());
4874
4879
  });
4875
4880
  } else {
4876
4881
  const p = new Error("probe error");
@@ -4879,7 +4884,7 @@ class wa extends _e {
4879
4884
  }));
4880
4885
  };
4881
4886
  function r() {
4882
- n || (n = !0, l(), s.close(), s = null);
4887
+ n || (n = !0, d(), s.close(), s = null);
4883
4888
  }
4884
4889
  const a = (u) => {
4885
4890
  const p = new Error("probe error: " + u);
@@ -4891,13 +4896,13 @@ class wa extends _e {
4891
4896
  function c() {
4892
4897
  a("socket closed");
4893
4898
  }
4894
- function d(u) {
4899
+ function l(u) {
4895
4900
  s && u.name !== s.name && r();
4896
4901
  }
4897
- const l = () => {
4898
- s.removeListener("open", i), s.removeListener("error", a), s.removeListener("close", o), this.off("close", c), this.off("upgrading", d);
4902
+ const d = () => {
4903
+ s.removeListener("open", i), s.removeListener("error", a), s.removeListener("close", o), this.off("close", c), this.off("upgrading", l);
4899
4904
  };
4900
- s.once("open", i), s.once("error", a), s.once("close", o), this.once("close", c), this.once("upgrading", d), this._upgrades.indexOf("webtransport") !== -1 && e !== "webtransport" ? this.setTimeoutFn(() => {
4905
+ s.once("open", i), s.once("error", a), s.once("close", o), this.once("close", c), this.once("upgrading", l), this._upgrades.indexOf("webtransport") !== -1 && e !== "webtransport" ? this.setTimeoutFn(() => {
4901
4906
  n || s.open();
4902
4907
  }, 200) : s.open();
4903
4908
  }
@@ -5349,8 +5354,8 @@ class rr extends F {
5349
5354
  data: s
5350
5355
  };
5351
5356
  if (a.options = {}, a.options.compress = this.flags.compress !== !1, typeof s[s.length - 1] == "function") {
5352
- const l = this.ids++, u = s.pop();
5353
- this._registerAckCallback(l, u), a.id = l;
5357
+ const d = this.ids++, u = s.pop();
5358
+ this._registerAckCallback(d, u), a.id = d;
5354
5359
  }
5355
5360
  const o = (i = (n = this.io.engine) === null || n === void 0 ? void 0 : n.transport) === null || i === void 0 ? void 0 : i.writable, c = this.connected && !(!((r = this.io.engine) === null || r === void 0) && r._hasPingExpired());
5356
5361
  return this.flags.volatile && !o || (c ? (this.notifyOutgoingListeners(a), this.packet(a)) : this.sendBuffer.push(a)), this.flags = {}, this;
@@ -6369,18 +6374,18 @@ class ja {
6369
6374
  async uploadResult(e, s, n) {
6370
6375
  const i = crypto.randomUUID();
6371
6376
  this.uploadingResult = !0;
6372
- const r = new AbortController(), a = (d) => r.abort(d);
6377
+ const r = new AbortController(), a = (l) => r.abort(l);
6373
6378
  this.pending.add(a);
6374
6379
  const o = Math.min(40 * 6e4, 6e4 + Math.ceil(n / (128 * 1024)) * 1e3), c = setTimeout(() => r.abort(), o);
6375
6380
  try {
6376
- const { token: d, ...l } = this.options.auth, u = await fetch(new URL("/api/product-agent/socket-results", this.options.backendUrl), {
6381
+ const { token: l, ...d } = this.options.auth, u = await fetch(new URL("/api/product-agent/socket-results", this.options.backendUrl), {
6377
6382
  method: "POST",
6378
6383
  signal: r.signal,
6379
6384
  headers: {
6380
6385
  "content-type": "application/json",
6381
- authorization: `Bearer ${d}`,
6386
+ authorization: `Bearer ${l}`,
6382
6387
  "x-product-agent-result-context": JSON.stringify({
6383
- auth: l,
6388
+ auth: d,
6384
6389
  connection_id: `pa-sio:${this.socket.id}`,
6385
6390
  request_id: i,
6386
6391
  session_id: e.sessionId ?? e.session_id
@@ -6398,9 +6403,9 @@ class ja {
6398
6403
  throw new A("Invalid result acknowledgement identity", "invalid_ack", !0);
6399
6404
  if (!p.ok) throw ti(p, "Product Agent result rejected");
6400
6405
  return p.result;
6401
- } catch (d) {
6402
- const l = d instanceof A ? d : new A("Result upload outcome is unknown", "delivery_unknown", !0);
6403
- throw this.recoverUncertainDelivery(l, s), l;
6406
+ } catch (l) {
6407
+ const d = l instanceof A ? l : new A("Result upload outcome is unknown", "delivery_unknown", !0);
6408
+ throw this.recoverUncertainDelivery(d, s), d;
6404
6409
  } finally {
6405
6410
  clearTimeout(c), this.uploadingResult = !1, this.pending.delete(a);
6406
6411
  }
@@ -6412,8 +6417,8 @@ class ja {
6412
6417
  const o = (c) => {
6413
6418
  this.pending.delete(o), a(c);
6414
6419
  };
6415
- this.pending.add(o), this.socket.timeout(this.options.requestTimeoutMs ?? 15e3).emit(e, { ...s, request_id: i }, (c, d) => {
6416
- this.pending.delete(o) && (c || n !== this.generation ? a(new A("Delivery outcome is unknown; reconcile without repeating execution", "delivery_unknown", !0)) : d?.request_id !== i || typeof d.ok != "boolean" ? a(new A("Invalid acknowledgement identity", "invalid_ack", !0)) : d.ok ? r(d.result) : a(ti(d, "Product Agent request rejected")));
6420
+ this.pending.add(o), this.socket.timeout(this.options.requestTimeoutMs ?? 15e3).emit(e, { ...s, request_id: i }, (c, l) => {
6421
+ this.pending.delete(o) && (c || n !== this.generation ? a(new A("Delivery outcome is unknown; reconcile without repeating execution", "delivery_unknown", !0)) : l?.request_id !== i || typeof l.ok != "boolean" ? a(new A("Invalid acknowledgement identity", "invalid_ack", !0)) : l.ok ? r(l.result) : a(ti(l, "Product Agent request rejected")));
6417
6422
  });
6418
6423
  }).catch((r) => {
6419
6424
  throw this.recoverUncertainDelivery(r, n), r;
@@ -6455,8 +6460,8 @@ class or {
6455
6460
  const o = this.options.authority?.(), c = (u = !0) => {
6456
6461
  if (o !== this.options.authority?.()) throw new A("Conversation authority was retired.", "authority_retired", !0);
6457
6462
  u && (this.requests.signal.throwIfAborted(), a.signal?.throwIfAborted());
6458
- }, d = a.readOnly ?? (i ?? (n === void 0 ? "GET" : "POST")) === "GET";
6459
- let l = 0;
6463
+ }, l = a.readOnly ?? (i ?? (n === void 0 ? "GET" : "POST")) === "GET";
6464
+ let d = 0;
6460
6465
  for (let u = 0; ; ) {
6461
6466
  await (a.timing ? a.timing.measure("http_authentication", async () => {
6462
6467
  await this.options.pendingAuthentication?.();
@@ -6469,10 +6474,10 @@ class or {
6469
6474
  let h = n;
6470
6475
  if (r === "conversations" && e === "/commands" && this.auth.role !== "session_surface" && this.options.executorConnection) {
6471
6476
  if (m = this.options.executorConnection(), !m) throw new A("Reconnecting the browser before continuing.", "executor_not_ready");
6472
- const k = n;
6473
- h = { ...k, context: { ...k.context, connection_id: m } };
6477
+ const _ = n;
6478
+ h = { ..._, context: { ..._.context, connection_id: m } };
6474
6479
  }
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());
6480
+ const v = () => this.requestOnce(e, s, h, i, r, a.signal, a.diagnostic, ++d), I = await (a.timing ? a.timing.measure("http_request", v) : v());
6476
6481
  return c(), I;
6477
6482
  } catch (h) {
6478
6483
  if (c(!1), this.requests.signal.aborted || a.signal?.aborted) throw h;
@@ -6480,35 +6485,35 @@ class or {
6480
6485
  await this.options.restoreExecutor(m), u++, c();
6481
6486
  continue;
6482
6487
  }
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;
6488
+ if (!(h instanceof A) || !["unauthorized", "403"].includes(h.code) || !this.options.recoverAuthentication || !l || (await this.options.recoverAuthentication(g, h, l && u === 0), c(), !l || u !== 0)) throw h;
6484
6489
  u++;
6485
6490
  }
6486
6491
  }
6487
6492
  }
6488
6493
  async requestOnce(e, s, n, i, r, a, o, c = 1) {
6489
- const d = this.auth.client_kind === "embed", l = new URL(`/api/product-agent/${r ?? (d ? "embed" : "runtime")}${e}`, this.options.backendUrl), u = r === "conversations" ? {} : d ? { client_id: this.auth.client_id, transport_id: this.auth.transport_id } : { community_id: this.auth.community_id, automation_run_id: this.auth.automation_run_id };
6494
+ const l = this.auth.client_kind === "embed", d = new URL(`/api/product-agent/${r ?? (l ? "embed" : "runtime")}${e}`, this.options.backendUrl), u = r === "conversations" ? {} : l ? { client_id: this.auth.client_id, transport_id: this.auth.transport_id } : { community_id: this.auth.community_id, automation_run_id: this.auth.automation_run_id };
6490
6495
  for (const [E, q] of Object.entries({ ...u, ...s }))
6491
- q != null && l.searchParams.set(E, String(q));
6496
+ q != null && d.searchParams.set(E, String(q));
6492
6497
  this.requests.signal.throwIfAborted(), a?.throwIfAborted();
6493
6498
  const p = new AbortController(), g = { trigger: null }, m = (E) => {
6494
6499
  p.signal.aborted || (g.trigger = E, p.abort());
6495
6500
  }, h = () => m("transport_disposed"), v = () => m(["owner_disposed", "authority_retired", "observation_released", "request_replaced"].includes(a?.reason) ? a.reason : "caller_cancelled");
6496
6501
  this.requests.signal.addEventListener("abort", h, { once: !0 }), a?.addEventListener("abort", v, { once: !0 });
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;
6502
+ const I = r === "conversations" && /^\/[^/]+\/snapshot$/.test(e) && i === "POST", _ = /^\/conversations(?:\/[^/]+)?$/.test(e) && (i ?? (n === void 0 ? "GET" : "POST")) === "GET", S = setTimeout(() => m("deadline"), _ ? 6e4 : I ? 3e4 : 15e3), f = Ba(), b = Date.now();
6503
+ let y = null, w = !1, R = null, T = null, C = null;
6499
6504
  try {
6500
- const E = await Promise.resolve(fetch(l, {
6505
+ const E = await Promise.resolve(fetch(d, {
6501
6506
  method: i ?? (n === void 0 ? "GET" : "POST"),
6502
6507
  cache: "no-store",
6503
6508
  signal: p.signal,
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 } : {} },
6509
+ headers: { "x-product-agent-auth-request-id": f, authorization: l || r === "conversations" ? `Bearer ${this.auth.token}` : this.auth.token, "content-type": "application/json", ...I ? { "x-request-id": f } : {} },
6505
6510
  ...n === void 0 ? {} : { body: JSON.stringify(n) }
6506
6511
  })).catch((q) => {
6507
- throw _ = !0, q;
6512
+ throw w = !0, q;
6508
6513
  });
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) {
6514
+ if (y = 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
6515
  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))
6516
+ if (l && E.status === 403 && (r === "conversations" && /^\/[^/]+\/snapshot$/.test(e) || (!r || r === "embed") && /^\/conversations\/[^/]+$/.test(e)) && ["Conversation unavailable", "Integration mismatch", "Embedded origin mismatch"].includes(O))
6512
6517
  throw new A("Conversation unavailable", "conversation_access_denied");
6513
6518
  if (r === "conversations" && e.endsWith("/snapshot") && E.status === 409 && O === "Display projection is not enabled")
6514
6519
  throw new A("Conversation history is unavailable. Try loading this chat again after the service is ready.", "display_projection_disabled");
@@ -6521,7 +6526,7 @@ class or {
6521
6526
  ...typeof O.blockedOrigin == "string" ? { blockedOrigin: O.blockedOrigin } : {},
6522
6527
  ...typeof O.securitySettingsUrl == "string" ? { securitySettingsUrl: O.securitySettingsUrl } : {}
6523
6528
  }, r === "conversations" && e === "/commands");
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;
6529
+ const k = 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(k) ? { requestId: f, authTransport: "http", authEndpoint: `${r ?? (l ? "embed" : "runtime")}:${["snapshot", "me", "bootstrap", "commands", "activity", "session-history"].includes(e.split("/").pop()) ? e.split("/").pop() : "other"}`, reason: k, retryable: k === "token_expired" && (O === "Token expired" || O.retryable === !0) } : void 0;
6525
6530
  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);
6526
6531
  }
6527
6532
  return await E.json();
@@ -6532,11 +6537,11 @@ class or {
6532
6537
  route: I ? "/api/product-agent/conversations/:sessionId/snapshot" : e === "/commands" ? "/api/product-agent/:namespace/commands" : "/api/product-agent/:namespace/:operation",
6533
6538
  status: R,
6534
6539
  abortTrigger: q,
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),
6540
+ category: q === "deadline" ? "request_timed_out" : q === "unexpected_abort" ? "connection_interrupted" : q ? "request_cancelled" : E instanceof A ? E.code : w ? "connection_interrupted" : "invalid_response",
6541
+ responseHeadersMs: y === null ? null : Math.max(0, y - b),
6542
+ responseBodyMs: y === null ? null : Math.max(0, Date.now() - y),
6538
6543
  owner: q === "deadline" ? "http_deadline" : q === "transport_disposed" ? "http_transport" : q && q !== "unexpected_abort" ? "conversation_query" : R === null ? "browser" : "http_response",
6539
- elapsedMs: Math.max(0, Date.now() - y),
6544
+ elapsedMs: Math.max(0, Date.now() - b),
6540
6545
  attempt: c,
6541
6546
  queryRequestId: j(o?.queryRequestId),
6542
6547
  ownerId: j(o?.ownerId),
@@ -6548,24 +6553,24 @@ class or {
6548
6553
  };
6549
6554
  ye(O) && Promise.resolve().then(() => this.options.onRequestFailure ? this.options.onRequestFailure(O) : console.warn("Product Agent HTTP request failed", O)).catch(() => {
6550
6555
  });
6551
- const S = ye(O) ? { httpRequest: O } : void 0;
6556
+ const k = ye(O) ? { httpRequest: O } : void 0;
6552
6557
  if (q !== null) {
6553
6558
  const x = q !== "deadline" && q !== "unexpected_abort";
6554
6559
  throw new A(
6555
6560
  x ? "The request was cancelled." : q === "deadline" ? "The request timed out. Please try again." : "The connection was interrupted. Please try again.",
6556
6561
  x ? "request_cancelled" : q === "deadline" ? "request_timed_out" : "connection_interrupted",
6557
6562
  !0,
6558
- S
6563
+ k
6559
6564
  );
6560
6565
  }
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.",
6566
+ throw E instanceof A && k ? new A(E.message, E.code, E.outcomeUnknown, { ...E.detail, ...k }, E.backendRefusal) : k ? new A(
6567
+ w ? "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.",
6563
6568
  "connection_interrupted",
6564
6569
  !0,
6565
- S
6570
+ k
6566
6571
  ) : E;
6567
6572
  } finally {
6568
- clearTimeout(w), this.requests.signal.removeEventListener("abort", h), a?.removeEventListener("abort", v);
6573
+ clearTimeout(S), this.requests.signal.removeEventListener("abort", h), a?.removeEventListener("abort", v);
6569
6574
  }
6570
6575
  }
6571
6576
  }
@@ -6638,11 +6643,11 @@ function ni(t) {
6638
6643
  r || (r = !0, a(), s(new Error("Directory authority is no longer current.")));
6639
6644
  }, c = () => {
6640
6645
  if (r) return !0;
6641
- const d = t.runtime.engine.getState().slices.directory;
6642
- if (t.isDisposed() || d.authorityId !== t.authority.authorityId || d.generation !== t.authority.generation)
6646
+ const l = t.runtime.engine.getState().slices.directory;
6647
+ if (t.isDisposed() || l.authorityId !== t.authority.authorityId || l.generation !== t.authority.generation)
6643
6648
  return o(), !0;
6644
- const l = d.mutations[t.sessionId]?.[t.field];
6645
- return l && l.requestId !== t.requestId ? (r = !0, a(), s(new Error("Conversation update was superseded.")), !0) : l?.status === "pending" ? !1 : (r = !0, a(), l?.status === "failed" ? s(new Error(l.error?.message ?? t.failureMessage)) : e(), !0);
6649
+ const d = l.mutations[t.sessionId]?.[t.field];
6650
+ return d && d.requestId !== t.requestId ? (r = !0, a(), s(new Error("Conversation update was superseded.")), !0) : d?.status === "pending" ? !1 : (r = !0, a(), d?.status === "failed" ? s(new Error(d.error?.message ?? t.failureMessage)) : e(), !0);
6646
6651
  };
6647
6652
  c() || (n = t.runtime.engine.subscribe(c), i = t.runtime.onDispose(o));
6648
6653
  });
@@ -6657,9 +6662,9 @@ function $a(t) {
6657
6662
  let a;
6658
6663
  if (t.http.auth.client_kind === "embed") {
6659
6664
  const o = await t.http.request("/conversations", { ...r, page_url: i.origin ?? t.pageUrl() });
6660
- Ke(t, n), a = { entries: await Promise.all(o.sessions.map(async (d) => ({
6661
- ...await cr(t.http, d.id),
6662
- ...typeof d.isActive == "boolean" ? { is_active: d.isActive } : {}
6665
+ Ke(t, n), a = { entries: await Promise.all(o.sessions.map(async (l) => ({
6666
+ ...await cr(t.http, l.id),
6667
+ ...typeof l.isActive == "boolean" ? { is_active: l.isActive } : {}
6663
6668
  }))), next_cursor: o.nextCursor };
6664
6669
  } else
6665
6670
  a = await t.http.request("/conversations", r, void 0, "GET", e);
@@ -6824,8 +6829,8 @@ class za {
6824
6829
  const o = () => {
6825
6830
  a?.(), a = null, this.queryWaiters.delete(c);
6826
6831
  }, c = () => {
6827
- const d = this.options.runtime.engine.getState().slices.directory.queries[n];
6828
- return this.disposed || !ee(this.boundary) || !d ? (o(), s ? r(new Error("Directory authority is no longer current.")) : i(), !0) : d.requestId !== null ? !1 : (o(), s && d.status === "error" ? r(new Error(d.error?.message ?? "Conversation directory failed")) : i(), !0);
6832
+ const l = this.options.runtime.engine.getState().slices.directory.queries[n];
6833
+ return this.disposed || !ee(this.boundary) || !l ? (o(), s ? r(new Error("Directory authority is no longer current.")) : i(), !0) : l.requestId !== null ? !1 : (o(), s && l.status === "error" ? r(new Error(l.error?.message ?? "Conversation directory failed")) : i(), !0);
6829
6834
  };
6830
6835
  c() || (this.queryWaiters.add(c), a = this.options.runtime.engine.subscribe(c));
6831
6836
  });
@@ -6952,13 +6957,13 @@ class Va {
6952
6957
  if (!this.current() || this.state().clients !== s.clients) return !1;
6953
6958
  const r = n.bindings.filter((c) => {
6954
6959
  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;
6960
+ const l = s.selections[c.conversationScopeId];
6961
+ return !l || l.sessionId === c.sessionId && l.provisionalId === c.provisionalId;
6957
6962
  });
6958
6963
  if (e !== void 0 && r.some((c) => c.sessionId !== e)) return !1;
6959
6964
  const a = [], o = new Set(r.map((c) => c.sessionId));
6960
6965
  for (const c of o) {
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();
6966
+ const l = r.filter((g) => g.sessionId === c), d = c === null ? l[0] : l.find((g) => g.clientScopeId === n.mains[c]) ?? this.choose(l), u = [d, ...l.filter((g) => g !== d)], p = /* @__PURE__ */ new Set();
6962
6967
  for (const g of u) {
6963
6968
  const m = { ...this.options.authority, clientScopeId: g.clientScopeId, conversationScopeId: g.conversationScopeId, replacement: null };
6964
6969
  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({
@@ -7318,14 +7323,14 @@ class L extends EventTarget {
7318
7323
  if (n === "session.reset" && !e.sessionId && !e.warmupId) return;
7319
7324
  const c = n === "chat.user_message" || n === "chat.retry_last_user_message";
7320
7325
  c && e.sessionId && await this.retain(e.sessionId);
7321
- const l = await this.transport.rpc(n, i);
7322
- if (!l?.sessionId || !c && n !== "runtime.warmup") return;
7323
- const u = l.sessionId;
7326
+ const d = await this.transport.rpc(n, i);
7327
+ if (!d?.sessionId || !c && n !== "runtime.warmup") return;
7328
+ const u = d.sessionId;
7324
7329
  if (n === "runtime.warmup") {
7325
7330
  if (!this.isCurrent(s)) return;
7326
7331
  e.warmupId && this.receive({ type: "runtime.warmup_ack", sessionId: u, warmupId: e.warmupId, reason: e.reason });
7327
7332
  }
7328
- (n === "chat.user_message" || n === "chat.retry_last_user_message") && (s.submissionAccepted = !0, this.receive({ type: "submission.accepted", sessionId: u, clientMessageId: l.clientMessageId ?? e.clientMessageId })), await this.retain(u), this.isCurrent(s) && (n === "chat.user_message" || n === "runtime.warmup") && !e.sessionId && await this.hydrate(u, { sessionId: u, page: e.page }, s, e.warmupId);
7333
+ (n === "chat.user_message" || n === "chat.retry_last_user_message") && (s.submissionAccepted = !0, this.receive({ type: "submission.accepted", sessionId: u, clientMessageId: d.clientMessageId ?? e.clientMessageId })), await this.retain(u), this.isCurrent(s) && (n === "chat.user_message" || n === "runtime.warmup") && !e.sessionId && await this.hydrate(u, { sessionId: u, page: e.page }, s, e.warmupId);
7329
7334
  }
7330
7335
  isCurrent(e) {
7331
7336
  return this.readyState === 1 && this.contextRevisions.get(e.key) === e.revision;
@@ -7406,16 +7411,16 @@ function Ja(t, e, s) {
7406
7411
  const n = en.get(t)?.get(e);
7407
7412
  return n?.sessionId === s ? n : null;
7408
7413
  }
7409
- function Qa(t, e, s, n, i, r, a, o, c = null, d = !1) {
7410
- const l = n ? o.find((p) => p.role === "user" && (p.id === n || p.clientMessageId === n)) : void 0, u = l ? [...o].reverse().find((p) => (p.role === "assistant" || p.dataType === "commentary_history" || p.dataType === "tool_summary") && p.respondsToUserMessageId === l.id) : void 0;
7414
+ function Qa(t, e, s, n, i, r, a, o, c = null, l = !1) {
7415
+ const d = n ? o.find((p) => p.role === "user" && (p.id === n || p.clientMessageId === n)) : void 0, u = d ? [...o].reverse().find((p) => (p.role === "assistant" || p.dataType === "commentary_history" || p.dataType === "tool_summary") && p.respondsToUserMessageId === d.id) : void 0;
7411
7416
  return {
7412
7417
  capturedAt: (/* @__PURE__ */ new Date()).toISOString(),
7413
7418
  authenticated: i,
7414
7419
  activeClientMessageId: Te(r) ? r : null,
7415
7420
  pendingClientMessageId: Te(a) ? a : null,
7416
- clientUserMessageItemId: l && Te(l.id) ? l.id : null,
7421
+ clientUserMessageItemId: d && Te(d.id) ? d.id : null,
7417
7422
  clientResponseItemId: u && Te(u.id) ? u.id : null,
7418
- clientDraftObserved: !!(l && d && c === l.id),
7423
+ clientDraftObserved: !!(d && l && c === d.id),
7419
7424
  renderer: Ja(t, e, s)
7420
7425
  };
7421
7426
  }
@@ -7542,14 +7547,14 @@ function di(t, e, s) {
7542
7547
  delete r[e];
7543
7548
  let a = t.memberships;
7544
7549
  if (i !== null) {
7545
- const o = a[i], c = o.members.filter((l) => l !== e);
7546
- let d = o.mainClientScopeId;
7547
- if (d === e && (d = null, c.length > 0)) {
7550
+ const o = a[i], c = o.members.filter((d) => d !== e);
7551
+ let l = o.mainClientScopeId;
7552
+ if (l === e && (l = null, c.length > 0)) {
7548
7553
  if (!s || s.sessionId !== i || s.membershipRevision !== t.membershipRevision || !c.includes(s.clientScopeId))
7549
7554
  throw new Error("Main replacement must choose a current remaining member at the current membership revision.");
7550
- d = s.clientScopeId;
7555
+ l = s.clientScopeId;
7551
7556
  }
7552
- a = { ...a, [i]: { members: c, mainClientScopeId: d } };
7557
+ a = { ...a, [i]: { members: c, mainClientScopeId: l } };
7553
7558
  }
7554
7559
  return { ...t, clients: r, memberships: a, membershipRevision: t.membershipRevision + 1 };
7555
7560
  }
@@ -7660,21 +7665,21 @@ function qe(t, e, s) {
7660
7665
  n = { ...n, queries: { ...n.queries, [o]: { ...c, status: "error", error: { ...e.error }, requestId: null, consecutiveFailures: c.consecutiveFailures + 1 } } };
7661
7666
  else if (e.effectKind === "directory.query") {
7662
7667
  for (const h of e.output.entries) n = ps(n, h, !0);
7663
- const d = e.output.entries.map((h) => h.conversation_id), l = { ...n.durableActivityBySessionId }, u = { ...n.activityBySessionId }, p = { ...n.activityRevisionBySessionId };
7668
+ const l = e.output.entries.map((h) => h.conversation_id), d = { ...n.durableActivityBySessionId }, u = { ...n.activityBySessionId }, p = { ...n.activityRevisionBySessionId };
7664
7669
  for (const h of e.output.entries) {
7665
7670
  if (typeof h.is_active != "boolean") continue;
7666
- l[h.conversation_id] = h.is_active;
7671
+ d[h.conversation_id] = h.is_active;
7667
7672
  const v = c.startedAtActivityRevisionBySessionId[h.conversation_id];
7668
7673
  v !== void 0 && p[h.conversation_id] === v && (delete u[h.conversation_id], delete p[h.conversation_id]);
7669
7674
  }
7670
- n = { ...n, durableActivityBySessionId: l, activityBySessionId: u, activityRevisionBySessionId: p };
7671
- const g = Object.fromEntries(Object.entries(n.optimisticEntries).filter(([, h]) => h.sessionId === null || !d.includes(h.sessionId)));
7675
+ n = { ...n, durableActivityBySessionId: d, activityBySessionId: u, activityRevisionBySessionId: p };
7676
+ const g = Object.fromEntries(Object.entries(n.optimisticEntries).filter(([, h]) => h.sessionId === null || !l.includes(h.sessionId)));
7672
7677
  n = { ...n, optimisticEntries: g };
7673
- const m = [.../* @__PURE__ */ new Set([...c.mode === "append" ? c.data ?? [] : [], ...d])];
7678
+ const m = [.../* @__PURE__ */ new Set([...c.mode === "append" ? c.data ?? [] : [], ...l])];
7674
7679
  n = { ...n, queries: { ...n.queries, [o]: {
7675
7680
  ...c,
7676
7681
  data: m,
7677
- pageData: d,
7682
+ pageData: l,
7678
7683
  status: "ready",
7679
7684
  requestId: null,
7680
7685
  cursor: e.output.next_cursor,
@@ -7691,8 +7696,8 @@ function qe(t, e, s) {
7691
7696
  }
7692
7697
  const o = { ...n.mutations[r.input.sessionId] };
7693
7698
  for (const c of ["title", "pinned"]) {
7694
- const d = o[c];
7695
- d?.requestId === r.input.requestId && (e.type === "effect.failed" ? o[c] = { ...d, status: "failed", error: { ...e.error } } : delete o[c]);
7699
+ const l = o[c];
7700
+ l?.requestId === r.input.requestId && (e.type === "effect.failed" ? o[c] = { ...l, status: "failed", error: { ...e.error } } : delete o[c]);
7696
7701
  }
7697
7702
  n = { ...n, mutations: { ...n.mutations, [r.input.sessionId]: o } };
7698
7703
  }
@@ -7741,22 +7746,22 @@ function qe(t, e, s) {
7741
7746
  const r = `${t.generation}:${t.requestSequence + 1}`, a = { authorityId: e.authorityId, generation: e.generation, requestId: e.requestId };
7742
7747
  let o;
7743
7748
  if (e.type === "directory.query") {
7744
- const c = B(e.query), d = t.queries[c];
7745
- if (d?.requestId !== null && d?.requestId !== void 0) return { state: t, effects: i };
7746
- if (e.mode === "append" && e.cursor === void 0 && (!d?.data || d.cursor === null)) return { state: t, effects: i };
7747
- const l = { ...e.query };
7749
+ const c = B(e.query), l = t.queries[c];
7750
+ if (l?.requestId !== null && l?.requestId !== void 0) return { state: t, effects: i };
7751
+ if (e.mode === "append" && e.cursor === void 0 && (!l?.data || l.cursor === null)) return { state: t, effects: i };
7752
+ const d = { ...e.query };
7748
7753
  o = { kind: "directory.query", input: {
7749
7754
  ...a,
7750
- query: l,
7751
- cursor: e.cursor !== void 0 ? e.cursor : e.mode === "append" ? d?.cursor ?? null : null
7755
+ query: d,
7756
+ cursor: e.cursor !== void 0 ? e.cursor : e.mode === "append" ? l?.cursor ?? null : null
7752
7757
  } }, n = { ...t, queries: { ...t.queries, [c]: {
7753
- ...De(d ?? me(c), { key: c, requestId: e.requestId, mode: e.mode }),
7754
- query: l,
7758
+ ...De(l ?? me(c), { key: c, requestId: e.requestId, mode: e.mode }),
7759
+ query: d,
7755
7760
  requestSequence: t.requestSequence + 1,
7756
7761
  mode: e.mode,
7757
- invalidated: d?.invalidated ?? !1,
7758
- consecutiveFailures: e.resetRecovery ? 0 : d?.consecutiveFailures ?? 0,
7759
- pageData: d?.pageData ?? [],
7762
+ invalidated: l?.invalidated ?? !1,
7763
+ consecutiveFailures: e.resetRecovery ? 0 : l?.consecutiveFailures ?? 0,
7764
+ pageData: l?.pageData ?? [],
7760
7765
  startedAtMetadataRevision: t.metadataRevision,
7761
7766
  startedAtActivityRevisionBySessionId: t.activityRevisionBySessionId
7762
7767
  } } };
@@ -7764,12 +7769,12 @@ function qe(t, e, s) {
7764
7769
  const c = { ...e.patch };
7765
7770
  if (c.title === void 0 && c.pinned === void 0 || c.title !== void 0 && (!c.title.trim() || c.title.trim().length > 120)) throw new Error("Invalid directory mutation.");
7766
7771
  c.title !== void 0 && (c.title = c.title.trim()), o = { kind: "directory.mutate", input: { ...a, sessionId: e.sessionId, patch: c } };
7767
- const d = { ...t.mutations[e.sessionId] };
7768
- for (const l of ["title", "pinned"]) {
7769
- const u = c[l];
7770
- u !== void 0 && (d[l] = { requestId: e.requestId, value: u, status: "pending", error: null });
7772
+ const l = { ...t.mutations[e.sessionId] };
7773
+ for (const d of ["title", "pinned"]) {
7774
+ const u = c[d];
7775
+ u !== void 0 && (l[d] = { requestId: e.requestId, value: u, status: "pending", error: null });
7771
7776
  }
7772
- n = tn({ ...t, mutations: { ...t.mutations, [e.sessionId]: d } });
7777
+ n = tn({ ...t, mutations: { ...t.mutations, [e.sessionId]: l } });
7773
7778
  }
7774
7779
  n = { ...n, requestSequence: t.requestSequence + 1, requests: { ...n.requests, [r]: o } }, i.push({ id: r, ...o });
7775
7780
  } else
@@ -7897,13 +7902,13 @@ class oc {
7897
7902
  if (n) {
7898
7903
  const i = n.type === "directory.authority_replace" && s;
7899
7904
  i && (this.scopedDiagnostics.clear(), this.diagnosticEffects.clear());
7900
- const r = (d) => ({
7901
- ...d,
7905
+ const r = (l) => ({
7906
+ ...l,
7902
7907
  revision: n.sequence,
7903
- dropped: d.dropped + (d.transitions.length === 16 ? 1 : 0),
7904
- lastIntent: /^session\.(new|load)$/.test(n.type) ? n : d.lastIntent,
7905
- lastSelection: s && /^directory\.(bind|detach|provisional|accepted|authority_replace|restore)/.test(n.type) ? n : d.lastSelection,
7906
- transitions: [...d.transitions.slice(-15), n]
7908
+ dropped: l.dropped + (l.transitions.length === 16 ? 1 : 0),
7909
+ lastIntent: /^session\.(new|load)$/.test(n.type) ? n : l.lastIntent,
7910
+ lastSelection: s && /^directory\.(bind|detach|provisional|accepted|authority_replace|restore)/.test(n.type) ? n : l.lastSelection,
7911
+ transitions: [...l.transitions.slice(-15), n]
7907
7912
  }), a = { ownerId: this.diagnostics.ownerId, revision: n.sequence, dropped: 0, lastIntent: null, lastSelection: null, transitions: [] };
7908
7913
  this.diagnostics = r(i ? a : this.diagnostics);
7909
7914
  const o = n.clientScopeId ? `client:${n.clientScopeId}` : n.scopeId ? `scope:${n.scopeId}` : n.sessionId ? `session:${n.sessionId}` : n.type === "directory.authority_replace" ? "owner" : null;
@@ -8053,7 +8058,7 @@ function pi(t, e, s) {
8053
8058
  const o = e.submissions[a];
8054
8059
  if (o.cancelled || o.delivery === "failed" || r.has(o.conversationScopeId)) continue;
8055
8060
  r.add(o.conversationScopeId);
8056
- const c = Object.keys(s.optimisticEntries).some((d) => t.submissions[d]?.conversationScopeId === o.conversationScopeId && !n.optimisticEntries[d]);
8061
+ const c = Object.keys(s.optimisticEntries).some((l) => t.submissions[l]?.conversationScopeId === o.conversationScopeId && !n.optimisticEntries[l]);
8057
8062
  o.sessionId !== null || n.optimisticEntries[a] || t.submissions[a] && !c || (n = qe(n, { ...i, type: "directory.optimistic_upsert", entry: {
8058
8063
  id: `optimistic-user-message:${a}`,
8059
8064
  clientMessageId: a,
@@ -8067,9 +8072,9 @@ function pi(t, e, s) {
8067
8072
  for (const [a, o] of Object.entries(s.memberships)) {
8068
8073
  const c = s.clients[o.members[0]];
8069
8074
  if (!c) continue;
8070
- const d = Ie(e, s, c), l = Ie(t, s, c);
8071
- if (d.activity.phase === l.activity.phase) continue;
8072
- const u = ["submitting", "awaiting_execution", "thinking", "steering", "queued", "stopping"].includes(d.activity.phase);
8075
+ const l = Ie(e, s, c), d = Ie(t, s, c);
8076
+ if (l.activity.phase === d.activity.phase) continue;
8077
+ const u = ["submitting", "awaiting_execution", "thinking", "steering", "queued", "stopping"].includes(l.activity.phase);
8073
8078
  n = qe(n, { ...i, type: "directory.activity_set", sessionId: a, active: u }).state;
8074
8079
  }
8075
8080
  return n;
@@ -8093,61 +8098,61 @@ class pc {
8093
8098
  reducer: (r, a) => {
8094
8099
  const o = a.value;
8095
8100
  if (o.type.startsWith("stage7.") || (o.type === "effect.completed" || o.type === "effect.failed") && o.effectKind.startsWith("stage7.")) {
8096
- const d = js(r.slices, o, r.slices);
8097
- if (d.state === r.slices) return { state: r, effects: d.effects };
8098
- const l = G(X({ account: d.state.account, features: d.state.features, interactions: d.state.interactions }));
8099
- return { state: Object.freeze({ revision: r.revision + 1, slices: Object.freeze({ ...r.slices, ...l }) }), effects: d.effects };
8101
+ const l = js(r.slices, o, r.slices);
8102
+ if (l.state === r.slices) return { state: r, effects: l.effects };
8103
+ const d = G(X({ account: l.state.account, features: l.state.features, interactions: l.state.interactions }));
8104
+ return { state: Object.freeze({ revision: r.revision + 1, slices: Object.freeze({ ...r.slices, ...d }) }), effects: l.effects };
8100
8105
  }
8101
8106
  if (o.type.startsWith("activeUsers.") || (o.type === "effect.completed" || o.type === "effect.failed") && o.effectKind.startsWith("activeUsers.")) {
8102
- const d = Za(r.slices.activeUsers, o);
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 };
8107
+ const l = Za(r.slices.activeUsers, o);
8108
+ return { state: l.state === r.slices.activeUsers ? r : Object.freeze({ revision: r.revision + 1, slices: Object.freeze({ ...r.slices, activeUsers: l.state }) }), effects: l.effects };
8104
8109
  }
8105
8110
  if (cc(o)) {
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);
8111
+ const l = qe(r.slices.directory, o, r.slices.conversation), d = Ws(Hs(r.slices.conversation, l.state, o.type === "directory.authority_replace" && o.adoptLocalSubmissions === !0)), u = Vs(r.slices.conversation, d.state, l.state, l.state.clients !== r.slices.directory.clients), p = u.state, g = pi(r.slices.conversation, p, l.state);
8107
8112
  return { state: g === r.slices.directory && p === r.slices.conversation ? r : Object.freeze({
8108
8113
  revision: r.revision + 1,
8109
8114
  slices: Object.freeze({ ...r.slices, directory: g, conversation: p })
8110
- }), effects: [...u.effects, ...d.effects, ...l.effects] };
8115
+ }), effects: [...u.effects, ...l.effects, ...d.effects] };
8111
8116
  }
8112
8117
  if (dc(o)) {
8113
- const d = ho(r.slices.conversation, o, r.slices.directory, r.slices.modelSelection);
8114
- let l = r.slices.directory;
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, {
8119
- authorityId: d.state.authorityId,
8120
- generation: d.state.generation,
8118
+ const l = ho(r.slices.conversation, o, r.slices.directory, r.slices.modelSelection);
8119
+ let d = r.slices.directory;
8120
+ for (const [_, S] of Object.entries(l.state.operations)) {
8121
+ if (!["runtime.warmup", "attachment.prepare"].includes(S.command.type) || !S.conversationScopeId || S.phase !== "done" || r.slices.conversation.operations[_]?.phase === "done") continue;
8122
+ const f = S.result, b = d.selections[S.conversationScopeId];
8123
+ f?.sessionId && b?.provisionalId && b.sessionId === null && Object.values(d.clients).includes(S.conversationScopeId) && (d = qe(d, {
8124
+ authorityId: l.state.authorityId,
8125
+ generation: l.state.generation,
8121
8126
  type: "directory.accepted",
8122
- conversationScopeId: w.conversationScopeId,
8123
- provisionalId: y.provisionalId,
8127
+ conversationScopeId: S.conversationScopeId,
8128
+ provisionalId: b.provisionalId,
8124
8129
  sessionId: f.sessionId
8125
8130
  }).state);
8126
8131
  }
8127
- const u = Object.values(d.state.submissions).find((k) => k.delivery === "accepted" && r.slices.conversation.submissions[k.userMessageId]?.delivery !== "accepted");
8132
+ const u = Object.values(l.state.submissions).find((_) => _.delivery === "accepted" && r.slices.conversation.submissions[_.userMessageId]?.delivery !== "accepted");
8128
8133
  if (u) {
8129
- const k = l.selections[u.conversationScopeId];
8130
- !u.cancelled && k?.provisionalId && (l = qe(l, {
8134
+ const _ = d.selections[u.conversationScopeId];
8135
+ !u.cancelled && _?.provisionalId && (d = qe(d, {
8131
8136
  type: "directory.accepted",
8132
- authorityId: d.state.authorityId,
8133
- generation: d.state.generation,
8137
+ authorityId: l.state.authorityId,
8138
+ generation: l.state.generation,
8134
8139
  conversationScopeId: u.conversationScopeId,
8135
- provisionalId: k.provisionalId,
8140
+ provisionalId: _.provisionalId,
8136
8141
  sessionId: u.sessionId
8137
8142
  }).state);
8138
8143
  }
8139
- l = pi(r.slices.conversation, d.state, l);
8140
- const p = Ws(Hs(d.state, l)), g = Vs(d.state, p.state, l);
8144
+ d = pi(r.slices.conversation, l.state, d);
8145
+ const p = Ws(Hs(l.state, d)), g = Vs(l.state, p.state, d);
8141
8146
  let m = r.slices;
8142
- const h = [], v = d.interactionSources, I = m.account.authority;
8147
+ const h = [], v = l.interactionSources, I = m.account.authority;
8143
8148
  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);
8149
+ const _ = js(m, { type: "stage7.sources", authority: I, now: m.features.now, sources: v.sources }, { conversation: g.state, directory: d });
8150
+ m = G(X({ account: _.state.account, features: _.state.features, interactions: _.state.interactions })), h.push(..._.effects);
8146
8151
  }
8147
- return { state: g.state === r.slices.conversation && l === r.slices.directory && m === r.slices ? r : Object.freeze({
8152
+ return { state: g.state === r.slices.conversation && d === r.slices.directory && m === r.slices ? r : Object.freeze({
8148
8153
  revision: r.revision + 1,
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] };
8154
+ slices: Object.freeze({ ...r.slices, account: m.account, features: m.features, interactions: m.interactions, directory: d, conversation: g.state })
8155
+ }), effects: [...l.effects, ...h, ...g.effects, ...p.effects] };
8151
8156
  }
8152
8157
  const c = tc(r.slices.modelSelection, o);
8153
8158
  return { state: c === r.slices.modelSelection ? r : Object.freeze({
@@ -8288,15 +8293,15 @@ function In(t, e, s) {
8288
8293
  return new Promise((n, i) => {
8289
8294
  const r = t.transaction(sn, e), a = r.objectStore(sn);
8290
8295
  let o, c = !1;
8291
- s(a).then((d) => {
8292
- o = d;
8293
- }).catch((d) => {
8296
+ s(a).then((l) => {
8297
+ o = l;
8298
+ }).catch((l) => {
8294
8299
  c = !0;
8295
8300
  try {
8296
8301
  r.abort();
8297
8302
  } catch {
8298
8303
  }
8299
- i(d);
8304
+ i(l);
8300
8305
  }), r.oncomplete = () => {
8301
8306
  c || n(o);
8302
8307
  }, r.onerror = () => {
@@ -9092,13 +9097,13 @@ class iu {
9092
9097
  o.role === "user" && this.submissionPreviews.delete(o.id);
9093
9098
  this.state = Is(e);
9094
9099
  for (const [o, c] of this.stopPreviews) {
9095
- const d = e.activity?.executionKey;
9096
- (c !== void 0 && c !== "[]" && d !== void 0 && d !== "[]" && (d !== c || ["completed", "failed", "stopped"].includes(e.activity.phase)) || (c === void 0 || c === "[]") && e.messages.some((u) => u.respondsToUserMessageId === o && !u.provisional && u.loading !== !0 && (u.dataType === "run_status" || u.dataType === "run_error" || u.role === "assistant" && u.phase !== "commentary" && (u.streamState === void 0 || ["finished", "stopped", "failed"].includes(u.streamState))))) && this.stopPreviews.delete(o);
9100
+ const l = e.activity?.executionKey;
9101
+ (c !== void 0 && c !== "[]" && l !== void 0 && l !== "[]" && (l !== c || ["completed", "failed", "stopped"].includes(e.activity.phase)) || (c === void 0 || c === "[]") && e.messages.some((u) => u.respondsToUserMessageId === o && !u.provisional && u.loading !== !0 && (u.dataType === "run_status" || u.dataType === "run_error" || u.role === "assistant" && u.phase !== "commentary" && (u.streamState === void 0 || ["finished", "stopped", "failed"].includes(u.streamState))))) && this.stopPreviews.delete(o);
9097
9102
  }
9098
9103
  if (this.pendingStop?.userMessageIds.every((o) => !this.stopPreviews.has(o)) && (this.pendingStop = null), a.user?.id === e.user?.id)
9099
9104
  for (const o of this.state.messages) {
9100
9105
  if (o.role !== "user" || !o.attachments?.length) continue;
9101
- const c = a.messages.find((d) => d.role === "user" && d.id === o.id);
9106
+ const c = a.messages.find((l) => l.role === "user" && l.id === o.id);
9102
9107
  a.sessionId !== e.sessionId && !(a.sessionId === null && c) || (o.attachments = Kc(c?.attachments, o.attachments));
9103
9108
  }
9104
9109
  if (s !== void 0 && (this.model = s), n && JSON.stringify(n) !== JSON.stringify(this.sessionHistoryState)) {
@@ -9172,17 +9177,17 @@ class iu {
9172
9177
  }
9173
9178
  sendMessage(e, s = {}) {
9174
9179
  const n = e.trim();
9175
- s = { ...s, attachments: s.attachments?.map((d) => ({ ...d })) };
9180
+ s = { ...s, attachments: s.attachments?.map((l) => ({ ...l })) };
9176
9181
  const i = s.attachments ?? [];
9177
9182
  if (!n && i.length === 0) return Promise.resolve(null);
9178
9183
  this.pendingStop = null, this.stopError = null;
9179
9184
  const r = s.clientMessageId ?? (s.proactiveSuggestionQuestion && this.stagedProactiveSuggestionClientMessageId ? this.stagedProactiveSuggestionClientMessageId : crypto.randomUUID()), a = s.submittedAt ?? Date.now(), o = this.submissionGeneration;
9180
- this.pendingTransfers.set(r, i.flatMap((d) => d.id ? [d.id] : [])), this.submissionPreviews.set(r, { pending: !0, message: {
9185
+ this.pendingTransfers.set(r, i.flatMap((l) => l.id ? [l.id] : [])), this.submissionPreviews.set(r, { pending: !0, message: {
9181
9186
  id: r,
9182
9187
  role: "user",
9183
9188
  content: n,
9184
9189
  createdAt: "",
9185
- attachments: i.map((d) => ({ ...d }))
9190
+ attachments: i.map((l) => ({ ...l }))
9186
9191
  } });
9187
9192
  const c = this.sendMessageNow(n, { ...s, clientMessageId: r, submittedAt: a }, o);
9188
9193
  return this.emit("state", this.getState()), c.finally(() => {
@@ -9190,8 +9195,8 @@ class iu {
9190
9195
  });
9191
9196
  }
9192
9197
  async sendMessageNow(e, s, n) {
9193
- const i = e, r = s.clientMessageId, a = te((d) => {
9194
- n === this.submissionGeneration && this.reportOperationTiming(d);
9198
+ const i = e, r = s.clientMessageId, a = te((l) => {
9199
+ n === this.submissionGeneration && this.reportOperationTiming(l);
9195
9200
  }, {
9196
9201
  operation: "send",
9197
9202
  layer: "renderer",
@@ -9204,7 +9209,7 @@ class iu {
9204
9209
  if (n !== this.submissionGeneration) return null;
9205
9210
  try {
9206
9211
  if (!await a.measure("staging_ipc", async () => {
9207
- const l = await this.enqueueOperation(async () => this.destroyed || n !== this.submissionGeneration ? null : { result: this.adapter.dispatch({
9212
+ const d = await this.enqueueOperation(async () => this.destroyed || n !== this.submissionGeneration ? null : { result: this.adapter.dispatch({
9208
9213
  type: "conversation.stage",
9209
9214
  initiatedBy: s.initiatedBy,
9210
9215
  invocation: s.invocation,
@@ -9216,22 +9221,22 @@ class iu {
9216
9221
  attachments: o.length > 0 ? o.map(fi) : void 0,
9217
9222
  submittedAt: s.submittedAt
9218
9223
  }) });
9219
- return l ? (await l.result, l) : null;
9224
+ return d ? (await d.result, d) : null;
9220
9225
  }) || n !== this.submissionGeneration) return null;
9221
9226
  if (c = !0, o.length > 0) {
9222
9227
  if (!this.adapter.uploadAttachment)
9223
9228
  throw new Error("The runtime does not support attachments.");
9224
- const l = [];
9229
+ const d = [];
9225
9230
  for (const u of o) {
9226
9231
  if (u.sandboxPath || u.storageKey) {
9227
- l.push(u);
9232
+ d.push(u);
9228
9233
  continue;
9229
9234
  }
9230
9235
  const p = u.id ? this.attachmentFiles.get(u.id) : void 0;
9231
9236
  if (!p) throw new Error(`Attachment bytes are unavailable for ${u.name}`);
9232
- if (l.push(await a.measure("attachment_transfer", () => this.adapter.uploadAttachment(p, u, { clientMessageId: r }))), n !== this.submissionGeneration) return null;
9237
+ if (d.push(await a.measure("attachment_transfer", () => this.adapter.uploadAttachment(p, u, { clientMessageId: r }))), n !== this.submissionGeneration) return null;
9233
9238
  }
9234
- o = l;
9239
+ o = d;
9235
9240
  }
9236
9241
  if (n !== this.submissionGeneration || (await this.adapter.dispatch({
9237
9242
  type: "conversation.send",
@@ -9243,20 +9248,20 @@ class iu {
9243
9248
  proactiveSuggestionQuestion: s.proactiveSuggestionQuestion,
9244
9249
  attachments: o.length > 0 ? o.map(fi) : void 0
9245
9250
  }), n !== this.submissionGeneration)) return null;
9246
- for (const l of s.attachments ?? [])
9247
- l.id && this.attachmentFiles.delete(l.id);
9251
+ for (const d of s.attachments ?? [])
9252
+ d.id && this.attachmentFiles.delete(d.id);
9248
9253
  return r === this.stagedProactiveSuggestionClientMessageId && (this.stagedProactiveSuggestionClientMessageId = null), r;
9249
- } catch (d) {
9254
+ } catch (l) {
9250
9255
  if (n !== this.submissionGeneration) return null;
9251
- if ($o(d))
9256
+ if ($o(l))
9252
9257
  for (const u of s.attachments ?? [])
9253
9258
  u.id && this.attachmentFiles.delete(u.id);
9254
- const l = this.submissionPreviews.get(r);
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({
9259
+ const d = this.submissionPreviews.get(r);
9260
+ throw d && (d.pending = !1, d.error = Y(l), d.retry = !c && Y(l).code === "command_not_received" ? () => this.sendMessageNow(e, s, n) : void 0, this.emit("state", this.getState())), c && await this.adapter.dispatch({
9256
9261
  type: "conversation.fail_staged",
9257
9262
  clientMessageId: r,
9258
- message: Y(d).message
9259
- }), d;
9263
+ message: Y(l).message
9264
+ }), l;
9260
9265
  }
9261
9266
  }
9262
9267
  getModel() {
@@ -9295,8 +9300,8 @@ class iu {
9295
9300
  const e = this.getState(), s = this.cancelPendingSubmissions(!1), n = [...new Set([
9296
9301
  ...s,
9297
9302
  e.activeResponseUserMessageId,
9298
- e.messages.filter((d) => d.role === "user").slice(-1)[0]?.id
9299
- ].filter((d) => !!d))], i = te((d) => this.reportOperationTiming(d), {
9303
+ e.messages.filter((l) => l.role === "user").slice(-1)[0]?.id
9304
+ ].filter((l) => !!l))], i = te((l) => this.reportOperationTiming(l), {
9300
9305
  operation: "stop",
9301
9306
  layer: "renderer",
9302
9307
  requestId: crypto.randomUUID(),
@@ -9307,14 +9312,14 @@ class iu {
9307
9312
  const r = { userMessageIds: n, promise: Promise.resolve() };
9308
9313
  this.pendingStop = r;
9309
9314
  const a = !e.pendingMessageStatus && ["thinking", "steering", "queued", "stopping"].includes(this.state.activity?.phase ?? "") ? this.state.activity?.executionKey : void 0;
9310
- for (const d of n)
9311
- this.stopPreviews.set(d, s.includes(d) ? void 0 : a);
9315
+ for (const l of n)
9316
+ this.stopPreviews.set(l, s.includes(l) ? void 0 : a);
9312
9317
  const o = this.submissionGeneration;
9313
9318
  r.promise = i.measure("stop_ipc", () => this.adapter.dispatch({ type: "run.stop", ...s.length ? { clientMessageIds: s } : {} })).then(() => {
9314
- }, (d) => {
9315
- if (!(o !== this.submissionGeneration || n.every((l) => !this.stopPreviews.has(l)))) {
9316
- for (const l of n) this.stopPreviews.delete(l);
9317
- this.stopError = Y(d).message;
9319
+ }, (l) => {
9320
+ if (!(o !== this.submissionGeneration || n.every((d) => !this.stopPreviews.has(d)))) {
9321
+ for (const d of n) this.stopPreviews.delete(d);
9322
+ this.stopError = Y(l).message;
9318
9323
  }
9319
9324
  }).finally(() => {
9320
9325
  this.destroyed || o !== this.submissionGeneration || (this.pendingStop === r && (this.pendingStop = null), this.emit("state", this.getState()));
@@ -9509,8 +9514,8 @@ function ws(t) {
9509
9514
  "elapsedMs",
9510
9515
  "e2bEventSequence"
9511
9516
  ]) {
9512
- const d = t[c];
9513
- (typeof d == "string" || typeof d == "number" || typeof d == "boolean" || d === null) && (e[c] = d);
9517
+ const l = t[c];
9518
+ (typeof l == "string" || typeof l == "number" || typeof l == "boolean" || l === null) && (e[c] = l);
9514
9519
  }
9515
9520
  const s = t.content;
9516
9521
  typeof s == "string" && (e.contentLength = s.length);
@@ -9521,13 +9526,13 @@ function ws(t) {
9521
9526
  const r = (c) => {
9522
9527
  if (!c || typeof c != "object")
9523
9528
  return null;
9524
- const d = c, l = d.data, u = l && typeof l == "object" ? l : {}, p = Sr(c);
9529
+ const l = c, d = l.data, u = d && typeof d == "object" ? d : {}, p = Sr(c);
9525
9530
  return {
9526
- id: typeof d.id == "string" ? d.id : null,
9531
+ id: typeof l.id == "string" ? l.id : null,
9527
9532
  streamId: u.type === "message" && u.role === "assistant" && typeof u.id == "string" ? u.id : null,
9528
9533
  type: typeof u.type == "string" ? u.type : null,
9529
9534
  role: typeof u.role == "string" ? u.role : null,
9530
- sessionId: typeof d.sessionId == "string" ? d.sessionId : null,
9535
+ sessionId: typeof l.sessionId == "string" ? l.sessionId : null,
9531
9536
  runId: typeof u.runId == "string" ? u.runId : null,
9532
9537
  respondsToUserMessageId: typeof u.respondsToUserMessageId == "string" ? u.respondsToUserMessageId : null,
9533
9538
  status: typeof u.status == "string" ? u.status : null,
@@ -9538,19 +9543,19 @@ function ws(t) {
9538
9543
  };
9539
9544
  }, a = r(t.item);
9540
9545
  if (a?.id && (e.itemId = a.id, a.type && (e.itemType = a.type), a.role && (e.itemRole = a.role), a.sessionId && typeof e.sessionId != "string" && (e.sessionId = a.sessionId), a.runId && typeof e.runId != "string" && (e.runId = a.runId), a.respondsToUserMessageId && typeof e.respondsToUserMessageId != "string" && (e.respondsToUserMessageId = a.respondsToUserMessageId), a.status && (e.itemStatus = a.status), a.stage && (e.itemStage = a.stage), a.retryable && (e.itemRetryable = !0), a.visible && (e.visibleItemId = a.id, a.streamId && (e.visibleItemAliases = JSON.stringify([[a.streamId, a.id]])))), Array.isArray(t.items)) {
9541
- const c = t.items.map(r).filter((d) => d !== null && d.visible && !!d.id);
9542
- e.visibleItemIds = JSON.stringify(c.map((d) => d.id)), e.visibleItemAliases = JSON.stringify(c.flatMap((d) => d.streamId ? [[d.streamId, d.id]] : []));
9546
+ const c = t.items.map(r).filter((l) => l !== null && l.visible && !!l.id);
9547
+ e.visibleItemIds = JSON.stringify(c.map((l) => l.id)), e.visibleItemAliases = JSON.stringify(c.flatMap((l) => l.streamId ? [[l.streamId, l.id]] : []));
9543
9548
  }
9544
9549
  t.type === "chat.assistant_delta" && typeof t.itemId == "string" && (e.visibleItemId = t.itemId);
9545
9550
  const o = t.session;
9546
9551
  if (o && typeof o == "object") {
9547
9552
  const c = o;
9548
9553
  typeof c.id == "string" && (e.sessionId = c.id);
9549
- const d = c.metadata;
9550
- if (d && typeof d == "object") {
9551
- const l = d.composerPreload;
9552
- if (l && typeof l == "object") {
9553
- const u = l.runId;
9554
+ const l = c.metadata;
9555
+ if (l && typeof l == "object") {
9556
+ const d = l.composerPreload;
9557
+ if (d && typeof d == "object") {
9558
+ const u = d.runId;
9554
9559
  e.composerPreloaded = !0, typeof u == "string" && (e.preloadRunId = u);
9555
9560
  }
9556
9561
  }
@@ -9872,31 +9877,31 @@ class Ht {
9872
9877
  clientMessageId: h.userMessageId,
9873
9878
  sessionId: h.sessionId
9874
9879
  });
9875
- let k = h.contextPreparation ?? { pageContent: "", sessionTabs: [] };
9880
+ let _ = h.contextPreparation ?? { pageContent: "", sessionTabs: [] };
9876
9881
  if (h.contextPreparation === null) {
9877
9882
  await I.measure("first_frame", () => new Promise((f) => {
9878
9883
  if (document.visibilityState !== "visible") {
9879
9884
  setTimeout(f, 0);
9880
9885
  return;
9881
9886
  }
9882
- const y = () => {
9883
- cancelAnimationFrame(_), document.removeEventListener("visibilitychange", b), setTimeout(f, 0);
9884
- }, b = () => {
9885
- document.visibilityState !== "visible" && y();
9886
- }, _ = requestAnimationFrame(y);
9887
- document.addEventListener("visibilitychange", b);
9887
+ const b = () => {
9888
+ cancelAnimationFrame(w), document.removeEventListener("visibilitychange", y), setTimeout(f, 0);
9889
+ }, y = () => {
9890
+ document.visibilityState !== "visible" && b();
9891
+ }, w = requestAnimationFrame(b);
9892
+ document.addEventListener("visibilitychange", y);
9888
9893
  }));
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: [] };
9894
+ const S = h.context.page;
9895
+ if (oe().url !== S.url) throw Object.assign(new Error("The page changed before preparation completed. Send this message again."), { code: "context_preparation_interrupted", retryable: !1 });
9896
+ _ = { pageContent: await I.measure("page_capture", async () => Rn()), sessionTabs: [] };
9892
9897
  }
9893
9898
  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(() => {
9899
+ for (const S of v)
9900
+ if (!S.uploaded && (await this.attachmentPersistence.get(S.sourceId)?.catch(() => {
9896
9901
  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 });
9897
- }), !await hi(w.sourceId)))
9902
+ }), !await hi(S.sourceId)))
9898
9903
  throw Object.assign(new Error("Attachment files are unavailable. Attach the files again and send a new message."), { code: "attachment_source_unavailable", retryable: !1 });
9899
- return I.mark("context_ready"), { ...k, now: Date.now() };
9904
+ return I.mark("context_ready"), { ..._, now: Date.now() };
9900
9905
  },
9901
9906
  connectionId: () => this.socket instanceof L ? this.socket.connectionId : null,
9902
9907
  prepareUpload: this.options.prepareAttachmentUpload ?? (this.options.productVariant === "customer_embedded" ? (h) => this.prepareEmbedAttachmentUpload(h, n) : void 0),
@@ -9907,9 +9912,9 @@ class Ht {
9907
9912
  storageKey: I.storage_key ?? void 0,
9908
9913
  fileUrl: I.file_url ? new URL(I.file_url, this.options.backendUrl).toString() : void 0,
9909
9914
  lastUsedAt: Date.now()
9910
- }).catch((k) => V("web-sdk.attachments", "Failed to update persisted Product Agent attachment", {
9915
+ }).catch((_) => V("web-sdk.attachments", "Failed to update persisted Product Agent attachment", {
9911
9916
  attachmentId: h,
9912
- message: k instanceof Error ? k.message : String(k)
9917
+ message: _ instanceof Error ? _.message : String(_)
9913
9918
  }));
9914
9919
  },
9915
9920
  persistUpload: this.options.persistAttachmentUpload,
@@ -9936,17 +9941,17 @@ class Ht {
9936
9941
  }
9937
9942
  })
9938
9943
  });
9939
- const c = this.clientRuntime.engine.getState().slices.conversation, d = this.options.restorePersistedState === !1 || !this.authenticatedUserId ? null : os(i);
9944
+ const c = this.clientRuntime.engine.getState().slices.conversation, l = this.options.restorePersistedState === !1 || !this.authenticatedUserId ? null : os(i);
9940
9945
  if (this.authenticatedUserId && !c.submissionOrder.length && !Object.keys(c.operations).length) {
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];
9946
+ const h = this.queuedClientEvents.filter((_) => _.type === "chat.user_message"), v = l ? JSON.parse(l) : h.length ? Oo(c, h.map((_) => {
9947
+ const { type: S, ...f } = _, b = this.clientRuntime.engine.getState().slices.directory, y = b.clients[this.modelClientScopeId];
9943
9948
  return {
9944
- command: { type: w, request_id: k.clientMessageId, payload: JSON.parse(JSON.stringify(f)) },
9945
- requestedModel: k.model ?? null,
9949
+ command: { type: S, request_id: _.clientMessageId, payload: JSON.parse(JSON.stringify(f)) },
9950
+ requestedModel: _.model ?? null,
9946
9951
  clientScopeId: this.modelClientScopeId,
9947
- conversationScopeId: b,
9952
+ conversationScopeId: y,
9948
9953
  viewId: `sdk:${this.modelClientScopeId}`,
9949
- sessionId: k.sessionId ?? y.selections[b]?.sessionId ?? null,
9954
+ sessionId: _.sessionId ?? b.selections[y]?.sessionId ?? null,
9950
9955
  entrySurface: this.options.entrySurface,
9951
9956
  submittedAt: Date.now()
9952
9957
  };
@@ -9966,14 +9971,14 @@ class Ht {
9966
9971
  socket: {
9967
9972
  retain: async (h, v) => {
9968
9973
  const I = this.socket;
9969
- I instanceof L && await I.directoryRooms.retain(h, v).catch((k) => {
9970
- if (this.socket === I) throw k;
9974
+ I instanceof L && await I.directoryRooms.retain(h, v).catch((_) => {
9975
+ if (this.socket === I) throw _;
9971
9976
  });
9972
9977
  },
9973
9978
  release: async (h, v) => {
9974
9979
  const I = this.socket;
9975
- I instanceof L && await I.directoryRooms.release(h, v).catch((k) => {
9976
- if (this.socket === I) throw k;
9980
+ I instanceof L && await I.directoryRooms.release(h, v).catch((_) => {
9981
+ if (this.socket === I) throw _;
9977
9982
  });
9978
9983
  }
9979
9984
  },
@@ -9983,15 +9988,15 @@ class Ht {
9983
9988
  } },
9984
9989
  onError: (h) => this.handleDirectoryTransportError(h)
9985
9990
  });
9986
- const l = (h, v) => {
9991
+ const d = (h, v) => {
9987
9992
  if (this.firstResponseTimersByClientMessageId.size) {
9988
9993
  for (const I of h)
9989
9994
  (I.dataType === "run_status" || I.dataType === "run_error") && this.clearFirstResponseTimer(I.respondsToUserMessageId ?? null);
9990
9995
  for (const I of h)
9991
9996
  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);
9997
+ const _ = v ? this.clientRuntime.engine.getState().slices.conversation.sessions[v] : void 0;
9998
+ for (const S of I.respondsToUserMessageId ? $r(_, I.respondsToUserMessageId) : [])
9999
+ this.clearFirstResponseTimer(S, !0, v);
9995
10000
  }
9996
10001
  }
9997
10002
  };
@@ -10001,34 +10006,34 @@ class Ht {
10001
10006
  p = h.conversation, Io(v, h.conversation, this.operationTimingReporter, "sdk");
10002
10007
  const I = m !== h.directory.clients[this.modelClientScopeId];
10003
10008
  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);
10009
+ for (const S of Object.values(h.conversation.submissions)) {
10010
+ if (S.delivery === "accepted" && v.submissions[S.userMessageId]?.delivery !== "accepted") {
10011
+ const f = this.firstResponseTimersByClientMessageId.get(S.userMessageId);
10012
+ f && (f.sessionId = S.sessionId), this.emit("ack", { clientMessageId: S.userMessageId, sessionId: S.sessionId });
10013
+ const b = S.sessionId;
10014
+ b && this.getState().sessionId === b && this.directoryHttp.request(`/sessions/${encodeURIComponent(b)}/history`, { limit: 200 }).then((y) => {
10015
+ n() && this.getState().sessionId === b && this.state.status !== "closed" && vs(this.clientRuntime, this.modelClientScopeId, b, y.turns);
10016
+ }).catch((y) => {
10017
+ n() && this.getState().sessionId === b && this.handleDirectoryTransportError(y);
10013
10018
  });
10014
10019
  }
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);
10020
+ (S.cancelled || S.delivery === "failed") && this.clearFirstResponseTimer(S.userMessageId);
10021
+ }
10022
+ for (const [S, f] of Object.entries(h.directory.clients)) {
10023
+ if (!S.startsWith(`background:${this.modelClientScopeId}:`)) continue;
10024
+ const b = Ie(h.conversation, h.directory, f), y = b.sessionId ? h.conversation.sessions[b.sessionId] : void 0;
10025
+ if (this.firstResponseTimersByClientMessageId.size && (d(as(b, y?.queries.current, this.options.backendUrl).messages, b.sessionId), ["failed", "stopped"].includes(b.activity.phase)))
10026
+ for (const R of de(y?.execution)) this.clearFirstResponseTimer(R);
10027
+ const w = b.activity.phase === "completed" && de(y?.execution).some((R) => this.firstResponseTimersByClientMessageId.has(R));
10028
+ (I && b.sessionId === this.getState().sessionId || !w && ["completed", "failed", "stopped"].includes(b.activity.phase)) && this.directoryScope.detach(S);
10029
+ }
10030
+ const _ = this.getState();
10031
+ d(_.messages, _.sessionId);
10032
+ for (const S of _.messages) {
10033
+ const f = u.get(S.id);
10034
+ (!f || f.content !== S.content || f.loading !== S.loading) && this.emit("message", S), S.content.trim() && S.content !== f?.content && (S.role === "assistant" || S.dataType === "commentary_history") && S.content.startsWith(f?.content ?? "") && this.emit("delta", S.content.slice(f?.content.length ?? 0));
10035
+ }
10036
+ u = new Map(_.messages.map((S) => [S.id, S])), this.rebuildRuntimeInteractions(), this.emit("state", _);
10032
10037
  }), this.conversationObservation.wake();
10033
10038
  }
10034
10039
  async initializeDirectory() {
@@ -10132,21 +10137,21 @@ class Ht {
10132
10137
  this.tokenAbortController = r;
10133
10138
  const a = (async () => {
10134
10139
  let o = null;
10135
- const c = new Promise((d, l) => {
10140
+ const c = new Promise((l, d) => {
10136
10141
  o = window.setTimeout(() => {
10137
- r.abort(), l(new le("Pluno token provider timed out", !0));
10142
+ r.abort(), d(new le("Pluno token provider timed out", !0));
10138
10143
  }, sd);
10139
10144
  });
10140
10145
  try {
10141
- const d = await Promise.race([
10146
+ const l = await Promise.race([
10142
10147
  this.options.tokenProvider?.({ signal: r.signal, reason: e }) ?? Promise.resolve(""),
10143
10148
  c
10144
10149
  ]);
10145
10150
  if (r.signal.aborted || this.tokenAbortController !== r)
10146
10151
  throw new le("Pluno token request was cancelled", !0);
10147
- if (typeof d != "string" || !d.trim())
10152
+ if (typeof l != "string" || !l.trim())
10148
10153
  throw new le("Chat setup did not return a session. Contact your app administrator, then try again.", !1);
10149
- return this.token = d, this.tokenExpiresAtMs = md(d), d;
10154
+ return this.token = l, this.tokenExpiresAtMs = md(l), l;
10150
10155
  } finally {
10151
10156
  o !== null && window.clearTimeout(o);
10152
10157
  }
@@ -10245,14 +10250,14 @@ class Ht {
10245
10250
  this.setState({ status: "error", lastError: "Invalid tool-call envelope", lastErrorCode: "invalid_tool_call" });
10246
10251
  return;
10247
10252
  }
10248
- const d = this.handleServerEvent(c);
10249
- a instanceof L && c.type === "tool.call" && d === !0 && a.acceptMessage(o);
10253
+ const l = this.handleServerEvent(c);
10254
+ a instanceof L && c.type === "tool.call" && l === !0 && a.acceptMessage(o);
10250
10255
  }), a.addEventListener("sendfailure", (o) => {
10251
10256
  this.socket === a && (this.clearSocketPhaseTimers(), this.stopHeartbeat(), this.socket = null, this.setReconnectingState(), this.scheduleReconnect(), a.readyState !== WebSocket.CLOSED && a.readyState !== WebSocket.CLOSING && a.close());
10252
10257
  }), a.addEventListener("diagnosticpending", (o) => {
10253
10258
  if (this.clientRuntime.isDisposed || this.state.status === "closed") return;
10254
- const c = o.detail, d = new Set(c.map((l) => l.id));
10255
- this.pendingTransportDiagnostics = [...this.pendingTransportDiagnostics.filter((l) => !d.has(l.id)), ...c].slice(-20), this.flushClientDiagnostics();
10259
+ const c = o.detail, l = new Set(c.map((d) => d.id));
10260
+ this.pendingTransportDiagnostics = [...this.pendingTransportDiagnostics.filter((d) => !l.has(d.id)), ...c].slice(-20), this.flushClientDiagnostics();
10256
10261
  }), a.addEventListener("close", (o) => {
10257
10262
  this.socket === a && (this.clearSocketPhaseTimers(), this.stopHeartbeat(), this.socket = null, this.state.status !== "closed" && (V("web-sdk.agent", "Pluno socket closed; scheduling reconnect", {
10258
10263
  code: typeof o?.code == "number" ? o.code : null,
@@ -10398,14 +10403,14 @@ class Ht {
10398
10403
  sessionId: this.getState().sessionId
10399
10404
  });
10400
10405
  a.mark("submit");
10401
- const o = ys(this.clientRuntime, this.modelClientScopeId, r), c = this.submissionIntentRevision, d = this.authenticatedUserId;
10402
- if (s.initiatedBy || this.startFirstResponseTimer(r, s.submittedAt), d || await a.measure("authentication", () => this.waitForAuthentication()), this.clientRuntime.isDisposed || c !== this.submissionIntentRevision || d && d !== this.authenticatedUserId) return null;
10406
+ const o = ys(this.clientRuntime, this.modelClientScopeId, r), c = this.submissionIntentRevision, l = this.authenticatedUserId;
10407
+ if (s.initiatedBy || this.startFirstResponseTimer(r, s.submittedAt), l || await a.measure("authentication", () => this.waitForAuthentication()), this.clientRuntime.isDisposed || c !== this.submissionIntentRevision || l && l !== this.authenticatedUserId) return null;
10403
10408
  ys(this.clientRuntime, this.modelClientScopeId, r, o ?? null);
10404
- const l = this.clientRuntime.engine.getState().slices.conversation.submissions[r];
10405
- if (l && (l.content !== n || JSON.stringify(l.attachments.map((v) => v.sourceId)) !== JSON.stringify(i.map((v) => v.id ?? v.storageKey ?? v.sandboxPath)))) throw new Error("User-message identity cannot be reused with different input.");
10406
- const u = oe(), p = !l && !s.initiatedBy && this.options.capturePageContent !== !1 && this.lastUserMessagePageUrl !== u.url, m = this.clientRuntime.engine.getState().slices.directory.clients[this.modelClientScopeId];
10409
+ const d = this.clientRuntime.engine.getState().slices.conversation.submissions[r];
10410
+ if (d && (d.content !== n || JSON.stringify(d.attachments.map((v) => v.sourceId)) !== JSON.stringify(i.map((v) => v.id ?? v.storageKey ?? v.sandboxPath)))) throw new Error("User-message identity cannot be reused with different input.");
10411
+ const u = oe(), p = !d && !s.initiatedBy && this.options.capturePageContent !== !1 && this.lastUserMessagePageUrl !== u.url, m = this.clientRuntime.engine.getState().slices.directory.clients[this.modelClientScopeId];
10407
10412
  if (!m) throw new Error("Conversation selection is not initialized.");
10408
- l || await this.clientRuntime.engine.dispatch({
10413
+ d || await this.clientRuntime.engine.dispatch({
10409
10414
  ...this.directoryAuthority,
10410
10415
  type: "conversation.submission_stage",
10411
10416
  prepareContext: p,
@@ -10442,18 +10447,18 @@ class Ht {
10442
10447
  });
10443
10448
  const h = this.directoryAuthority;
10444
10449
  return this.clientRuntime.isDisposed ? null : new Promise((v, I) => {
10445
- let k = null, w = null;
10450
+ let _ = null, S = null;
10446
10451
  const f = () => {
10447
- const y = this.clientRuntime.engine.getState().slices.conversation.submissions[r];
10448
- if (!(y && !y.cancelled && y.delivery !== "accepted" && y.delivery !== "failed"))
10449
- if (k?.(), w?.(), y?.delivery === "failed" && !y.cancelled) I(new Error(y.error?.message ?? "Message delivery failed."));
10452
+ const b = this.clientRuntime.engine.getState().slices.conversation.submissions[r];
10453
+ if (!(b && !b.cancelled && b.delivery !== "accepted" && b.delivery !== "failed"))
10454
+ if (_?.(), S?.(), b?.delivery === "failed" && !b.cancelled) I(new Error(b.error?.message ?? "Message delivery failed."));
10450
10455
  else {
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);
10456
+ const y = b?.invocation === "user" && b.contextPreparation?.pageContent ? b.context.page?.url : null;
10457
+ b?.delivery === "accepted" && !b.cancelled && typeof y == "string" && c === this.submissionIntentRevision && h === this.directoryAuthority && this.clientRuntime.engine.getState().slices.directory.clients[this.modelClientScopeId] === m && (this.lastUserMessagePageUrl = y), v(b?.delivery === "accepted" && !b.cancelled ? r : null);
10453
10458
  }
10454
10459
  };
10455
- k = this.clientRuntime.engine.subscribe(f), w = this.clientRuntime.onDispose(() => {
10456
- k?.(), v(null);
10460
+ _ = this.clientRuntime.engine.subscribe(f), S = this.clientRuntime.onDispose(() => {
10461
+ _?.(), v(null);
10457
10462
  }), f();
10458
10463
  });
10459
10464
  }
@@ -10550,28 +10555,28 @@ class Ht {
10550
10555
  entrySurface: this.options.entrySurface,
10551
10556
  sessionId: this.getState().sessionId
10552
10557
  } }
10553
- }), new Promise((d, l) => {
10558
+ }), new Promise((l, d) => {
10554
10559
  let u, p;
10555
10560
  const g = () => {
10556
10561
  const m = this.clientRuntime.engine.getState().slices, h = m.conversation.operations[c], v = m.directory.authorityId !== a.authorityId || m.directory.clients[this.modelClientScopeId] !== o;
10557
10562
  if (!v && h && !["done", "failed"].includes(h.phase)) return;
10558
10563
  if (u?.(), p?.(), v || !h || h.phase === "failed") {
10559
- l(new Error(h?.error?.message ?? "Attachment preparation was cancelled."));
10564
+ d(new Error(h?.error?.message ?? "Attachment preparation was cancelled."));
10560
10565
  return;
10561
10566
  }
10562
- const k = h.result.attachment;
10563
- d(Ar({
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
10567
+ const _ = h.result.attachment;
10568
+ l(Ar({
10569
+ id: _.id,
10570
+ name: _.name,
10571
+ mimeType: _.mime_type,
10572
+ sizeBytes: _.size_bytes,
10573
+ storageKey: _.storage_key,
10574
+ sandboxPath: _.sandbox_path,
10575
+ fileUrl: _.file_url
10571
10576
  }, this.options.backendUrl));
10572
10577
  };
10573
10578
  u = this.clientRuntime.engine.subscribe(g), p = this.clientRuntime.onDispose(() => {
10574
- u?.(), l(new Error("Product Agent was disposed."));
10579
+ u?.(), d(new Error("Product Agent was disposed."));
10575
10580
  }), g();
10576
10581
  });
10577
10582
  }
@@ -10653,28 +10658,28 @@ class Ht {
10653
10658
  }
10654
10659
  getSessionHistoryState() {
10655
10660
  return this.clientRuntime.project("directory", { core: () => {
10656
- const e = this.clientRuntime.engine.getProjection().directory, s = e.queries[B(this.getDirectoryQuery())], n = As(this.options.entrySurface).map((l) => this.getDirectoryQuery(l)).map((l) => e.queries[B(l)]).filter((l) => l !== void 0), i = Object.values(e.optimisticEntries).reverse(), r = Fa(n), a = new Set(i.flatMap((l) => l.sessionId ? [l.sessionId] : [])), o = [...i.map((l) => l.id), ...r.filter((l) => !a.has(l))], c = Object.fromEntries([
10657
- ...i.map((l) => [l.id, {
10658
- id: l.id,
10661
+ const e = this.clientRuntime.engine.getProjection().directory, s = e.queries[B(this.getDirectoryQuery())], n = As(this.options.entrySurface).map((d) => this.getDirectoryQuery(d)).map((d) => e.queries[B(d)]).filter((d) => d !== void 0), i = Object.values(e.optimisticEntries).reverse(), r = Fa(n), a = new Set(i.flatMap((d) => d.sessionId ? [d.sessionId] : [])), o = [...i.map((d) => d.id), ...r.filter((d) => !a.has(d))], c = Object.fromEntries([
10662
+ ...i.map((d) => [d.id, {
10663
+ id: d.id,
10659
10664
  title: null,
10660
10665
  customTitle: null,
10661
- firstUserMessage: l.firstUserMessage,
10662
- currentPage: l.currentPage,
10663
- createdAt: l.createdAt,
10664
- updatedAt: l.createdAt,
10665
- lastActiveAt: l.createdAt,
10666
- isActive: l.sessionId ? e.activityBySessionId[l.sessionId] === !0 : l.isActive,
10666
+ firstUserMessage: d.firstUserMessage,
10667
+ currentPage: d.currentPage,
10668
+ createdAt: d.createdAt,
10669
+ updatedAt: d.createdAt,
10670
+ lastActiveAt: d.createdAt,
10671
+ isActive: d.sessionId ? e.activityBySessionId[d.sessionId] === !0 : d.isActive,
10667
10672
  isPinned: !1
10668
10673
  }]),
10669
- ...r.filter((l) => !a.has(l)).map((l) => [l, this.toSessionHistoryEntry(e.entities[l])])
10670
- ]), d = La(n);
10674
+ ...r.filter((d) => !a.has(d)).map((d) => [d, this.toSessionHistoryEntry(e.entities[d])])
10675
+ ]), l = La(n);
10671
10676
  return {
10672
10677
  key: `${this.options.clientId}:recent`,
10673
- status: d?.status ?? "not_requested",
10678
+ status: l?.status ?? "not_requested",
10674
10679
  data: n.length || i.length ? { entitiesById: c, ids: o, nextCursor: s?.cursor ?? null } : null,
10675
- error: d?.error?.message ?? null,
10680
+ error: l?.error?.message ?? null,
10676
10681
  requestId: e.requestSequence,
10677
- updatedAt: Math.max(...n.map((l) => l.updatedAt ?? 0), 0) || null
10682
+ updatedAt: Math.max(...n.map((d) => d.updatedAt ?? 0), 0) || null
10678
10683
  };
10679
10684
  } });
10680
10685
  }
@@ -10766,7 +10771,7 @@ class Ht {
10766
10771
  async actOnInteraction(e, s, n, i = {}) {
10767
10772
  const r = this.clientRuntime.engine.getState().slices.account.authority;
10768
10773
  if (!r) throw new Error("Product Agent is not authenticated.");
10769
- const a = this.getInteractions().find((d) => d.id === e), o = i.expectedSourceVersion === void 0 ? a?.sourceVersion ?? null : i.expectedSourceVersion, c = crypto.randomUUID();
10774
+ const a = this.getInteractions().find((l) => l.id === e), o = i.expectedSourceVersion === void 0 ? a?.sourceVersion ?? null : i.expectedSourceVersion, c = crypto.randomUUID();
10770
10775
  await no(this.clientRuntime, {
10771
10776
  clientScopeId: this.modelClientScopeId,
10772
10777
  interactionId: e,
@@ -10834,8 +10839,8 @@ class Ht {
10834
10839
  const e = Zr(() => Date.now());
10835
10840
  let s = !1, n = !1;
10836
10841
  const i = () => {
10837
- const l = this.options.runtimeAdapters?.featurePermissions, u = this.clientRuntime.engine.getState().slices.account.authority;
10838
- if (!l || u?.profile !== "main_web_chat" || this.clientRuntime.isDisposed) return;
10842
+ const d = this.options.runtimeAdapters?.featurePermissions, u = this.clientRuntime.engine.getState().slices.account.authority;
10843
+ if (!d || u?.profile !== "main_web_chat" || this.clientRuntime.isDisposed) return;
10839
10844
  if (s) {
10840
10845
  n = !0;
10841
10846
  return;
@@ -10843,7 +10848,7 @@ class Ht {
10843
10848
  s = !0;
10844
10849
  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;
10845
10850
  Promise.all(["notifications", "tab_grouping"].map(async (m) => {
10846
- const h = await l.getState(m, p);
10851
+ const h = await d.getState(m, p);
10847
10852
  if (g()) {
10848
10853
  if (!h.bridgeReady) return h;
10849
10854
  if (await this.clientRuntime.engine.dispatch({
@@ -10873,42 +10878,42 @@ class Ht {
10873
10878
  http: this.directoryHttp,
10874
10879
  now: () => Date.now(),
10875
10880
  authority: () => this.clientRuntime.engine.getState().slices.account.authority,
10876
- readAccount: async (l) => {
10881
+ readAccount: async (d) => {
10877
10882
  const u = this.clientRuntime.engine.getState().slices.account, p = this.options.accountLoader ? await this.options.accountLoader() : u.refusal ? null : this.options.initialAccount;
10878
10883
  if (!p) throw new Error("Account information is unavailable.");
10879
10884
  return i(), ro(p, {
10880
- id: l.userId,
10885
+ id: d.userId,
10881
10886
  email: this.state.user?.email ?? null,
10882
10887
  name: this.state.user?.name ?? null,
10883
10888
  isSuperuser: !1
10884
- }, l.communityId);
10889
+ }, d.communityId);
10885
10890
  },
10886
10891
  embedded: {
10887
- appearance: async (l) => {
10888
- const u = await this.directoryHttp.request("/bootstrap", { page_url: l.pageUrl }, void 0, "GET", "embed"), p = Wd(u);
10889
- return { kind: "appearance", origin: l.origin, value: p ? { accent: p.accentColor ?? "#7c3aed", colorScheme: p.colorScheme ?? "light", fontFamily: p.fontFamily ?? "inherit", scribbleStyle: p.scribbleStyle ?? !1 } : null };
10892
+ appearance: async (d) => {
10893
+ const u = await this.directoryHttp.request("/bootstrap", { page_url: d.pageUrl }, void 0, "GET", "embed"), p = Wd(u);
10894
+ return { kind: "appearance", origin: d.origin, value: p ? { accent: p.accentColor ?? "#7c3aed", colorScheme: p.colorScheme ?? "light", fontFamily: p.fontFamily ?? "inherit", scribbleStyle: p.scribbleStyle ?? !1 } : null };
10890
10895
  },
10891
- feedback: async (l) => (await this.directoryHttp.request("/feedback", {}, { message: l }, "POST", "embed")).success
10896
+ feedback: async (d) => (await this.directoryHttp.request("/feedback", {}, { message: d }, "POST", "embed")).success
10892
10897
  }
10893
10898
  });
10894
10899
  this.clientRuntime.installFeaturePorts({
10895
10900
  ...r,
10896
10901
  "stage7.wait": e.wait,
10897
- "stage7.device": async ({ feature: l, action: u, requestId: p }) => {
10902
+ "stage7.device": async ({ feature: d, action: u, requestId: p }) => {
10898
10903
  const g = this.options.runtimeAdapters?.featurePermissions;
10899
10904
  if (!g) return { fact: { permission: "unsupported", revision: Date.now(), snoozedUntil: null }, completedAt: Date.now() };
10900
- const m = this.clientRuntime.engine.getState().slices.interactions, h = m.promptActions[p], v = h?.expectedRevision ?? m.preferencePrompts[l].revision;
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);
10905
+ const m = this.clientRuntime.engine.getState().slices.interactions, h = m.promptActions[p], v = h?.expectedRevision ?? m.preferencePrompts[d].revision;
10906
+ u === "allow" && await g.enable(d, { requestId: p, expectedRevision: v, action: h?.action === "enable" ? "enable" : "allow" }), u === "not_now" && await g.dismiss(d, { requestId: p, expectedRevision: v, action: "not_now" });
10907
+ const I = await g.getState(d, this.getState().sessionId);
10903
10908
  if (!I.bridgeReady) throw new Error("The Pluno extension is reconnecting. Try again.");
10904
10909
  return { fact: {
10905
10910
  permission: I.permissionGranted === !0 ? "granted" : I.permissionNeeded ? "missing" : "unknown",
10906
- revision: Math.max(Date.now(), this.clientRuntime.engine.getState().slices.interactions.deviceFacts[l].revision + 1),
10911
+ revision: Math.max(Date.now(), this.clientRuntime.engine.getState().slices.interactions.deviceFacts[d].revision + 1),
10907
10912
  snoozedUntil: I.snoozedUntil ?? null
10908
10913
  }, completedAt: Date.now() };
10909
10914
  },
10910
- "stage7.platform": async (l) => {
10911
- const u = l.operation, p = u.kind === "connect" ? u.source : null;
10915
+ "stage7.platform": async (d) => {
10916
+ const u = d.operation, p = u.kind === "connect" ? u.source : null;
10912
10917
  if (u.kind === "saveHint")
10913
10918
  Br(localStorage, u.interactionId);
10914
10919
  else if (u.kind === "connect" && p?.payload.kind === "integration_auth") {
@@ -10930,7 +10935,7 @@ class Ht {
10930
10935
  channel: "whatsapp",
10931
10936
  managementUrl: u.managementUrl
10932
10937
  });
10933
- } else if (this.options.runtimeAdapters?.interactionEffect) await this.options.runtimeAdapters.interactionEffect(l);
10938
+ } else if (this.options.runtimeAdapters?.interactionEffect) await this.options.runtimeAdapters.interactionEffect(d);
10934
10939
  else throw new Error("Interaction effect is unavailable.");
10935
10940
  return { revision: 0, completedAt: Date.now() };
10936
10941
  }
@@ -10938,15 +10943,15 @@ class Ht {
10938
10943
  let a = "";
10939
10944
  const o = this.clientRuntime.engine.subscribe(() => {
10940
10945
  this.rebuildRuntimeInteractions();
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]);
10946
+ const d = this.clientRuntime.engine.getState().slices, p = d.directory.selections[d.directory.clients[this.modelClientScopeId]]?.sessionId, g = JSON.stringify([p, p ? d.conversation.sessions[p]?.execution : null]);
10942
10947
  g !== a && (a = g, i());
10943
10948
  }), c = this.options.runtimeAdapters?.featurePermissions?.subscribe?.(i);
10944
10949
  this.clientRuntime.onDispose(() => c?.()), eo(this.clientRuntime, () => Date.now());
10945
- const d = () => {
10946
- const l = this.clientRuntime.engine.getState().slices.account.authority;
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) });
10950
+ const l = () => {
10951
+ const d = this.clientRuntime.engine.getState().slices.account.authority;
10952
+ d?.profile === "main_web_chat" && this.options.entrySurface === "main_web_chat" && this.clientRuntime.engine.dispatch({ type: "stage7.device_hints", authority: d, now: Date.now(), hints: xs(localStorage) });
10948
10953
  };
10949
- window.addEventListener("storage", d), this.clientRuntime.onDispose(() => window.removeEventListener("storage", d)), this.clientRuntime.onDispose(() => {
10954
+ window.addEventListener("storage", l), this.clientRuntime.onDispose(() => window.removeEventListener("storage", l)), this.clientRuntime.onDispose(() => {
10950
10955
  e.dispose(), o(), this.options.runtimeAdapters?.featurePermissions?.dispose?.();
10951
10956
  });
10952
10957
  }
@@ -11027,8 +11032,8 @@ class Ht {
11027
11032
  ...n.sessionId ? { sessionId: n.sessionId } : {},
11028
11033
  ...s,
11029
11034
  ...s.renderedError?.runId ? { runId: s.renderedError.runId } : {}
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 });
11035
+ }, { errorDiagnostic: a, responseDiagnostics: o, renderedError: c, uiInvariant: l, timings: d, httpRequest: u, historyRefreshFailure: p, ...g } = r;
11036
+ for (const m of d ?? []) xe("client_event", "operation_timing", { ...m });
11032
11037
  if (xe("client_event", "runtime.health", {
11033
11038
  ...g,
11034
11039
  signalName: e,
@@ -11125,7 +11130,7 @@ class Ht {
11125
11130
  connectionAttemptId: i
11126
11131
  };
11127
11132
  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 = [
11128
- ...this.pendingTransportDiagnostics.filter((d) => d.id !== c.id),
11133
+ ...this.pendingTransportDiagnostics.filter((l) => l.id !== c.id),
11129
11134
  c
11130
11135
  ], this.pendingTransportDiagnostics.splice(0, Math.max(0, this.pendingTransportDiagnostics.length - 20)), this.flushClientDiagnostics());
11131
11136
  }
@@ -11186,12 +11191,12 @@ class Ht {
11186
11191
  if (!o.ok)
11187
11192
  throw new Error(`Client diagnostic upload failed (${o.status})`);
11188
11193
  const c = new Map(
11189
- s.map((l) => [l.id, l.occurrenceCount])
11190
- ), d = new Set(n.map((l) => l.id));
11194
+ s.map((d) => [d.id, d.occurrenceCount])
11195
+ ), l = new Set(n.map((d) => d.id));
11191
11196
  this.pendingTransportDiagnostics = this.pendingTransportDiagnostics.filter(
11192
- (l) => !c.has(l.id) || l.occurrenceCount > (c.get(l.id) ?? 0)
11197
+ (d) => !c.has(d.id) || d.occurrenceCount > (c.get(d.id) ?? 0)
11193
11198
  ), this.pendingHealthDiagnostics = this.pendingHealthDiagnostics.filter(
11194
- (l) => !d.has(l.id)
11199
+ (d) => !l.has(d.id)
11195
11200
  );
11196
11201
  } catch {
11197
11202
  this.scheduleClientDiagnosticsRetry();
@@ -11253,14 +11258,14 @@ class Ht {
11253
11258
  applyAuthenticatedDirectoryIdentity(e) {
11254
11259
  const s = ki(e);
11255
11260
  if (!s) return !1;
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;
11261
+ 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((d) => ["waiting", "running", "uncertain"].includes(d.phase) && (d.command.type === "run.stop" || d.command.type === "session.reset")).map((d) => d.command) : [], c = a && this.directoryAuthority.authorityId === `${this.options.clientId}:${this.options.runtimeCommunityId ?? this.options.productVariant}` ? this.state.sessionId : null;
11257
11262
  if (this.authenticatedUserId = s.id, this.directoryHttp.auth.community_id = n, xo(this.options.clientId, i), r) {
11258
- const l = this.directoryAuthority;
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();
11263
+ const d = this.directoryAuthority;
11264
+ this.directoryObservation.dispose(), this.conversationAdapterGeneration++, this.conversationObservation?.dispose(), this.directoryAuthority = { authorityId: i, generation: d.generation + 1 }, this.clientRuntime.engine.dispatch({ ...this.directoryAuthority, type: "directory.authority_replace", expectedGeneration: d.generation }), this.createDirectoryAdapters();
11260
11265
  const u = this.getModel();
11261
11266
  a || (this.pendingWidgetLifecycleEvents = []), this.resetForAuthenticationScopeChange(), c && (this.directoryConversationScopeId = `conversation:${this.modelClientScopeId}:${z()}`, this.clientRuntime.engine.dispatch({ type: "model.scope_navigate", clientScopeId: this.modelClientScopeId, sessionId: c }), this.directoryScope.bind(this.modelClientScopeId, this.directoryConversationScopeId, c).then(() => this.directoryScope.persist())), u && this.setModel(u);
11262
11267
  }
11263
- const d = {
11268
+ const l = {
11264
11269
  ...this.directoryAuthority,
11265
11270
  userId: s.id,
11266
11271
  communityId: n ?? null,
@@ -11271,13 +11276,13 @@ class Ht {
11271
11276
  personalChannel: !!this.options.runtimeAdapters?.personalChannelConnectionHandler
11272
11277
  }
11273
11278
  };
11274
- if (to(this.clientRuntime, d, Date.now()).then(async () => {
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();
11279
+ if (to(this.clientRuntime, l, Date.now()).then(async () => {
11280
+ this.options.entrySurface === "main_web_chat" && l.profile === "main_web_chat" && await this.clientRuntime.engine.dispatch({ type: "stage7.device_hints", authority: l, now: Date.now(), hints: xs(localStorage) }), await this.refreshStarterPromptsForCurrentUrl();
11276
11281
  }).catch(() => {
11277
11282
  }), r || a) {
11278
- const l = this.directoryAuthority;
11283
+ const d = this.directoryAuthority;
11279
11284
  this.initializeConversation().then(async () => {
11280
- if (this.clientRuntime.isDisposed || this.directoryAuthority !== l) return;
11285
+ if (this.clientRuntime.isDisposed || this.directoryAuthority !== d) return;
11281
11286
  let u = !1;
11282
11287
  for (const p of o) {
11283
11288
  const g = this.clientRuntime.engine.getState().slices.directory, m = g.clients[this.modelClientScopeId];
@@ -11286,7 +11291,7 @@ class Ht {
11286
11291
  u = !0;
11287
11292
  const h = o.filter((v) => v.type === "run.stop" && v.payload.sessionId === p.payload.sessionId).map((v) => String(v.payload.expectedUserMessageId));
11288
11293
  await this.clientRuntime.engine.dispatch({
11289
- ...l,
11294
+ ...d,
11290
11295
  type: "conversation.stop",
11291
11296
  clientScopeId: this.modelClientScopeId,
11292
11297
  conversationScopeId: m,
@@ -11294,7 +11299,7 @@ class Ht {
11294
11299
  reason: p.payload.reason,
11295
11300
  userMessageIds: h
11296
11301
  });
11297
- } else (p.type === "run.stop" || p.type === "session.reset") && await this.clientRuntime.engine.dispatch({ ...l, type: "conversation.operation", command: p });
11302
+ } else (p.type === "run.stop" || p.type === "session.reset") && await this.clientRuntime.engine.dispatch({ ...d, type: "conversation.operation", command: p });
11298
11303
  }
11299
11304
  });
11300
11305
  }
@@ -11460,8 +11465,8 @@ class Ht {
11460
11465
  return;
11461
11466
  }
11462
11467
  if (this.activeBrowserToolCalls.has(n)) return;
11463
- const c = i === "execute_code", d = i === "execute_code_in_browser_tab" && a !== null && typeof a == "object" && a.tabId === "local:current";
11464
- if (!c && !d || !Rl(a)) {
11468
+ const c = i === "execute_code", l = i === "execute_code_in_browser_tab" && a !== null && typeof a == "object" && a.tabId === "local:current";
11469
+ if (!c && !l || !Rl(a)) {
11465
11470
  this.send({
11466
11471
  type: "tool.result",
11467
11472
  sessionId: s,
@@ -11507,8 +11512,8 @@ class Ht {
11507
11512
  startedAtUrl: location.href,
11508
11513
  startedAtOrigin: location.origin
11509
11514
  }), this.installSessionBrowserApis();
11510
- let l = null, u;
11511
- l = await this.executeRuntimeHelper(), u = await wi(
11515
+ let d = null, u;
11516
+ d = await this.executeRuntimeHelper(), u = await wi(
11512
11517
  a,
11513
11518
  Od(e.runtimeContext, this.options.backendUrl)
11514
11519
  ).catch((p) => ({
@@ -11523,7 +11528,7 @@ class Ht {
11523
11528
  toolName: i,
11524
11529
  summary: a.summary,
11525
11530
  rawInput: ne(a),
11526
- rawOutput: ne(Jd(u, l))
11531
+ rawOutput: ne(Jd(u, d))
11527
11532
  }), Ai(this.options.clientId, this.activeBrowserToolCalls.values()));
11528
11533
  }
11529
11534
  startPageLifecycleRecovery() {
@@ -11701,8 +11706,8 @@ class Ht {
11701
11706
  })().catch((c) => {
11702
11707
  if (this.socket !== e || this.state.status === "closed") throw c;
11703
11708
  if (this.reportTransportDiagnostic("auth_refresh_failed", { ...r, ...this.connectionFailureDiagnostic(c, a) }), this.credentialRecoveryFailure = Ge(c), c instanceof A && ["unauthorized", "403", "update_required"].includes(c.code) || !Rs(c)) {
11704
- const d = c instanceof A ? c : new A(c instanceof le ? c.message : "Your session could not be refreshed. Try again.", this.options.productVariant === "customer_embedded" ? "connection_failed" : "unauthorized", !1);
11705
- throw this.stopAuthentication(d), d;
11709
+ const l = c instanceof A ? c : new A(c instanceof le ? c.message : "Your session could not be refreshed. Try again.", this.options.productVariant === "customer_embedded" ? "connection_failed" : "unauthorized", !1);
11710
+ throw this.stopAuthentication(l), l;
11706
11711
  }
11707
11712
  throw this.options.productVariant === "customer_embedded" && this.setState({ status: "reconnecting", lastError: vi, lastErrorCode: "connection_failed" }), this.scheduleReconnect(), c;
11708
11713
  }).finally(() => {
@@ -11782,31 +11787,31 @@ function vd() {
11782
11787
  throw I;
11783
11788
  }
11784
11789
  try {
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)) {
11787
- const y = {
11790
+ const I = g instanceof Request ? g : null, _ = Al(g, I), S = qr(m?.headers ?? I?.headers);
11791
+ if (!Me(_, S, m?.body)) {
11792
+ const b = {
11788
11793
  requestId: qs("fetch"),
11789
- url: fe(k, ks),
11794
+ url: fe(_, ks),
11790
11795
  method: (m?.method ?? I?.method ?? "GET").toUpperCase(),
11791
- requestHeaders: w,
11796
+ requestHeaders: S,
11792
11797
  requestBody: Ti(m?.body),
11793
11798
  resourceType: "fetch",
11794
11799
  startedAt: new Date(h).toISOString()
11795
11800
  };
11796
11801
  v.then(
11797
- (b) => {
11798
- El(b, y, h, e).catch(() => {
11802
+ (y) => {
11803
+ El(y, b, h, e).catch(() => {
11799
11804
  e({
11800
- ...y,
11801
- responseStatus: b.status,
11805
+ ...b,
11806
+ responseStatus: y.status,
11802
11807
  durationMs: Date.now() - h
11803
11808
  });
11804
11809
  });
11805
11810
  },
11806
- (b) => {
11811
+ (y) => {
11807
11812
  e({
11808
- ...y,
11809
- errorText: fe(b instanceof Error ? b.message : String(b)),
11813
+ ...b,
11814
+ errorText: fe(y instanceof Error ? y.message : String(y)),
11810
11815
  durationMs: Date.now() - h
11811
11816
  });
11812
11817
  }
@@ -11816,20 +11821,20 @@ function vd() {
11816
11821
  }
11817
11822
  return v;
11818
11823
  }, 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();
11824
+ const _ = n.call(this, g, m, h ?? !0, v ?? void 0, I ?? void 0), S = typeof m == "string" ? m : m.toString();
11820
11825
  return Es.set(this, {
11821
11826
  requestId: qs("xhr"),
11822
11827
  method: String(g ?? "GET").toUpperCase(),
11823
- url: fe(w, ks),
11828
+ url: fe(S, ks),
11824
11829
  requestHeaders: {},
11825
11830
  startedAtMs: Date.now(),
11826
11831
  startedAt: (/* @__PURE__ */ new Date()).toISOString(),
11827
- excluded: Me(w)
11828
- }), k;
11832
+ excluded: Me(S)
11833
+ }), _;
11829
11834
  }, c = function(g, m) {
11830
11835
  const h = i.call(this, g, m), v = Es.get(this);
11831
11836
  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) {
11837
+ }, l = function(g) {
11833
11838
  try {
11834
11839
  const m = Es.get(this);
11835
11840
  m && (m.excluded = m.excluded || Me(m.url, m.requestHeaders, g), m.requestBody = Ti(g), m.excluded || this.addEventListener(
@@ -11876,12 +11881,12 @@ function vd() {
11876
11881
  } catch {
11877
11882
  }
11878
11883
  try {
11879
- XMLHttpRequest.prototype.send = d;
11884
+ XMLHttpRequest.prototype.send = l;
11880
11885
  } catch {
11881
11886
  }
11882
- let l = null;
11887
+ let d = null;
11883
11888
  if (typeof PerformanceObserver < "u") {
11884
- l = new PerformanceObserver((p) => {
11889
+ d = new PerformanceObserver((p) => {
11885
11890
  for (const g of p.getEntries()) {
11886
11891
  const m = g;
11887
11892
  if (m.initiatorType === "fetch" || m.initiatorType === "xmlhttprequest" || Me(m.name))
@@ -11899,15 +11904,15 @@ function vd() {
11899
11904
  }
11900
11905
  });
11901
11906
  try {
11902
- l.observe({ type: "resource", buffered: !0 });
11907
+ d.observe({ type: "resource", buffered: !0 });
11903
11908
  } catch {
11904
- l.disconnect(), l = null;
11909
+ d.disconnect(), d = null;
11905
11910
  }
11906
11911
  }
11907
11912
  const u = {
11908
11913
  subscribers: t,
11909
11914
  destroy: () => {
11910
- l?.disconnect();
11915
+ d?.disconnect();
11911
11916
  try {
11912
11917
  window.fetch === a && (window.fetch = s);
11913
11918
  } catch {
@@ -11921,7 +11926,7 @@ function vd() {
11921
11926
  } catch {
11922
11927
  }
11923
11928
  try {
11924
- XMLHttpRequest.prototype.send === d && (XMLHttpRequest.prototype.send = r);
11929
+ XMLHttpRequest.prototype.send === l && (XMLHttpRequest.prototype.send = r);
11925
11930
  } catch {
11926
11931
  }
11927
11932
  }
@@ -12044,20 +12049,20 @@ async function wi(t, e) {
12044
12049
  info: console.info,
12045
12050
  warn: console.warn,
12046
12051
  error: console.error
12047
- }, c = (d) => (...l) => {
12048
- r.push({ level: d, args: l }), o[d](...l);
12052
+ }, c = (l) => (...d) => {
12053
+ r.push({ level: l, args: d }), o[l](...d);
12049
12054
  };
12050
12055
  console.log = c("log"), console.info = c("info"), console.warn = c("warn"), console.error = c("error");
12051
12056
  try {
12052
- const d = /* @__PURE__ */ Symbol("execute_code_timeout"), l = await Promise.race([
12057
+ const l = /* @__PURE__ */ Symbol("execute_code_timeout"), d = await Promise.race([
12053
12058
  new s("sandboxFiles", t.javascript)(e?.value),
12054
12059
  new Promise((u) => {
12055
- a = window.setTimeout(() => u(d), n);
12060
+ a = window.setTimeout(() => u(l), n);
12056
12061
  })
12057
12062
  ]);
12058
- return l === d ? xd(n) : {
12063
+ return d === l ? xd(n) : {
12059
12064
  ok: !0,
12060
- result: l,
12065
+ result: d,
12061
12066
  console: r,
12062
12067
  metadata: {
12063
12068
  durationMs: Date.now() - i,
@@ -12065,14 +12070,14 @@ async function wi(t, e) {
12065
12070
  origin: location.origin
12066
12071
  }
12067
12072
  };
12068
- } catch (d) {
12073
+ } catch (l) {
12069
12074
  return {
12070
12075
  ok: !1,
12071
12076
  console: r,
12072
12077
  exception: {
12073
- name: d instanceof Error ? d.name : "Error",
12074
- message: d instanceof Error ? d.message : String(d),
12075
- stack: d instanceof Error ? d.stack : void 0
12078
+ name: l instanceof Error ? l.name : "Error",
12079
+ message: l instanceof Error ? l.message : String(l),
12080
+ stack: l instanceof Error ? l.stack : void 0
12076
12081
  },
12077
12082
  metadata: {
12078
12083
  durationMs: Date.now() - i,
@@ -12100,14 +12105,14 @@ function Od(t, e) {
12100
12105
  upload: async (o) => {
12101
12106
  if (i(), !(o instanceof Blob))
12102
12107
  throw new TypeError("sandboxFiles.upload expects a File or Blob");
12103
- const c = o instanceof File && o.name ? o.name : "file", d = `?name=${encodeURIComponent(c)}&size_bytes=${o.size}`, l = await r(`/api/product-agent/attachments/sandbox-files${d}`, {
12108
+ const c = o instanceof File && o.name ? o.name : "file", l = `?name=${encodeURIComponent(c)}&size_bytes=${o.size}`, d = await r(`/api/product-agent/attachments/sandbox-files${l}`, {
12104
12109
  method: "PUT",
12105
12110
  headers: { Authorization: `Bearer ${s}` },
12106
12111
  body: o
12107
12112
  });
12108
- if (!l.ok)
12109
- throw new Error(`sandboxFiles.upload failed (${l.status})`);
12110
- return String((await l.json()).path);
12113
+ if (!d.ok)
12114
+ throw new Error(`sandboxFiles.upload failed (${d.status})`);
12115
+ return String((await d.json()).path);
12111
12116
  },
12112
12117
  download: async (o) => {
12113
12118
  i();
@@ -12117,9 +12122,9 @@ function Od(t, e) {
12117
12122
  );
12118
12123
  if (!c.ok)
12119
12124
  throw new Error(`sandboxFiles.download failed (${c.status})`);
12120
- const d = await c.blob(), u = (c.headers.get("content-disposition") ?? "").match(/filename="([^"]+)"/i)?.[1];
12121
- return new File([d], u || o.split("/").pop() || "file", {
12122
- type: d.type
12125
+ const l = await c.blob(), u = (c.headers.get("content-disposition") ?? "").match(/filename="([^"]+)"/i)?.[1];
12126
+ return new File([l], u || o.split("/").pop() || "file", {
12127
+ type: l.type
12123
12128
  });
12124
12129
  }
12125
12130
  }),
@@ -12209,12 +12214,12 @@ function Rn() {
12209
12214
  const o = t.map(([h, v]) => `${h}:
12210
12215
  ${v}`).join(`
12211
12216
 
12212
- `).trim().slice(0, 12e3), c = Ld(i, r).trim(), d = `Simplified DOM outline:
12213
- `, l = `
12217
+ `).trim().slice(0, 12e3), c = Ld(i, r).trim(), l = `Simplified DOM outline:
12218
+ `, d = `
12214
12219
 
12215
12220
  Visible page text:
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}`;
12221
+ `, u = 12e3 - l.length - d.length, p = Math.min(o.length, 7900), g = c.slice(0, u - p), m = o.slice(0, u - g.length);
12222
+ return `${l}${g}${d}${m}`;
12218
12223
  }
12219
12224
  function tt(t) {
12220
12225
  return t.innerText ?? t.textContent ?? "";
@@ -12320,22 +12325,22 @@ function Ld(t, e) {
12320
12325
  "data-test",
12321
12326
  "data-qa",
12322
12327
  "data-cy"
12323
- ], d = ["aria-label", "placeholder", "data-testid", "data-test", "data-qa", "data-cy"], { priorityElements: l, priorityTargets: u } = Fd(), p = new Set(t);
12328
+ ], l = ["aria-label", "placeholder", "data-testid", "data-test", "data-qa", "data-cy"], { priorityElements: d, priorityTargets: u } = Fd(), p = new Set(t);
12324
12329
  e && p.add(e);
12325
12330
  let g = 0;
12326
- const m = (w) => {
12327
- const f = w.getAttribute("role");
12331
+ const m = (S) => {
12332
+ const f = S.getAttribute("role");
12328
12333
  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")
12334
+ }, h = (S) => {
12335
+ const f = S.getAttribute("data-testid") || S.getAttribute("data-test") || S.getAttribute("data-qa") || S.getAttribute("data-cy") || "";
12336
+ return `${S.tagName.toLowerCase()}|${m(S)}|${f}`;
12337
+ }, v = (S, f, b) => {
12338
+ const y = (w, R) => {
12339
+ const T = w.tagName.toLowerCase(), C = window.getComputedStyle(w), E = d.has(w);
12340
+ if (g >= 1e3 && !E || b.has(w) || r.has(T) || w.matches(".pluno-pa-widget-host, [data-pluno-product-agent-widget]") || C.display === "none" || C.visibility === "hidden")
12336
12341
  return { lines: [], hasUsefulContent: !1, textPreview: "", containsTextElement: !1 };
12337
12342
  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();
12343
+ const q = m(w), O = _r(w), k = o.has(q) || ["button", "input", "textarea", "select", "iframe", "canvas"].includes(T) || T === "a" && w.hasAttribute("href"), x = Array.from(w.children).filter((D) => D instanceof HTMLElement), U = /* @__PURE__ */ new Map();
12339
12344
  for (const D of x) {
12340
12345
  const $ = h(D);
12341
12346
  U.set($, (U.get($) ?? 0) + 1);
@@ -12343,28 +12348,28 @@ function Ld(t, e) {
12343
12348
  const H = /* @__PURE__ */ new Map(), Fe = /* @__PURE__ */ new Map();
12344
12349
  for (const D of x) {
12345
12350
  const $ = h(D), ve = Fe.get($) ?? 0;
12346
- Fe.set($, ve + 1), (U.get($) ?? 0) > 8 && ve >= 6 && !l.has(D) && H.set($, (H.get($) ?? 0) + 1);
12351
+ Fe.set($, ve + 1), (U.get($) ?? 0) > 8 && ve >= 6 && !d.has(D) && H.set($, (H.get($) ?? 0) + 1);
12347
12352
  }
12348
12353
  const ot = /* @__PURE__ */ new Map(), qn = /* @__PURE__ */ new Set(), Kt = [], Cn = [];
12349
12354
  for (const D of x) {
12350
12355
  const $ = h(D), ve = U.get($) ?? 0, Mn = ot.get($) ?? 0;
12351
- if (ot.set($, Mn + 1), ve > 8 && Mn >= 6 && !l.has(D)) {
12356
+ if (ot.set($, Mn + 1), ve > 8 && Mn >= 6 && !d.has(D)) {
12352
12357
  qn.has($) || (Kt.push([`… ${H.get($) ?? 0} similar siblings omitted`]), qn.add($));
12353
12358
  continue;
12354
12359
  }
12355
- const Pn = b(D, R);
12360
+ const Pn = y(D, R);
12356
12361
  Cn.push(Pn), Kt.push(Pn.lines);
12357
12362
  }
12358
12363
  const Wt = [];
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(
12364
+ if (w.shadowRoot)
12365
+ for (const D of Array.from(w.shadowRoot.children))
12366
+ D instanceof HTMLElement && Wt.push(y(D, R + 1));
12367
+ const at = [...Cn, ...Wt], Gt = O.length > 0 || k || at.some((D) => D.hasUsefulContent), On = Be(
12363
12368
  [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 = [];
12369
+ ).slice(0, 180), jr = w.hasAttribute("contenteditable") && (O.length > 0 || !w.querySelector("[contenteditable]")), xn = l.some((D) => w.hasAttribute(D)) || !!q || jr, Jt = (w.getClientRects().length > 0 || C.display === "contents") && (s.has(T) || xn || E) && (Gt || E) && (!i.has(T) || Gt || xn || E), Qt = Jt ? 1 : 0, $e = [];
12365
12370
  if (Jt) {
12366
12371
  const D = at.some((ve) => ve.containsTextElement), $ = n.has(T) && !D ? On : O;
12367
- $e.push(wr(_, c, a, $.slice(0, 180)));
12372
+ $e.push(wr(w, c, a, $.slice(0, 180)));
12368
12373
  }
12369
12374
  for (const D of Kt)
12370
12375
  $e.push(...yt(D, Qt));
@@ -12386,16 +12391,16 @@ function Ld(t, e) {
12386
12391
  containsTextElement: n.has(T) || at.some((D) => D.containsTextElement)
12387
12392
  };
12388
12393
  };
12389
- return [`--- ${f} ---`, ...b(w, 0).lines].join(`
12394
+ return [`--- ${f} ---`, ...y(S, 0).lines].join(`
12390
12395
  `);
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
+ }, I = [], _ = Be(window.getSelection()?.toString() ?? "");
12397
+ _ && I.push(`--- selected text ---
12398
+ ${JSON.stringify(_)}`), u.length > 0 && I.push($d(u, s, c, a));
12399
+ for (const S of t.slice(0, 3))
12400
+ I.push(v(S, "active overlay DOM", /* @__PURE__ */ new Set()));
12396
12401
  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));
12402
+ const S = e || t.length ? "other visible DOM" : "visible DOM";
12403
+ I.push(v(document.body, S, p));
12399
12404
  }
12400
12405
  return I.join(`
12401
12406
 
@@ -12422,11 +12427,11 @@ function Fd() {
12422
12427
  const t = /* @__PURE__ */ new Set(), e = /* @__PURE__ */ new Map(), s = (o, c) => {
12423
12428
  if (!o)
12424
12429
  return;
12425
- const d = window.getComputedStyle(o);
12426
- if (d.display === "none" || d.visibility === "hidden")
12430
+ const l = window.getComputedStyle(o);
12431
+ if (l.display === "none" || l.visibility === "hidden")
12427
12432
  return;
12428
- const l = e.get(o) ?? /* @__PURE__ */ new Set();
12429
- l.add(c), e.set(o, l);
12433
+ const d = e.get(o) ?? /* @__PURE__ */ new Set();
12434
+ d.add(c), e.set(o, d);
12430
12435
  let u = o;
12431
12436
  for (; u; ) {
12432
12437
  t.add(u);
@@ -12450,11 +12455,11 @@ function Fd() {
12450
12455
  ], a = [document];
12451
12456
  for (let o = 0; o < a.length; o += 1) {
12452
12457
  const c = a[o];
12453
- for (const [d, l] of r)
12454
- for (const u of Array.from(c.querySelectorAll(d)))
12455
- s(u, l);
12456
- for (const d of Array.from(c.querySelectorAll("*")))
12457
- d.shadowRoot && a.push(d.shadowRoot);
12458
+ for (const [l, d] of r)
12459
+ for (const u of Array.from(c.querySelectorAll(l)))
12460
+ s(u, d);
12461
+ for (const l of Array.from(c.querySelectorAll("*")))
12462
+ l.shadowRoot && a.push(l.shadowRoot);
12458
12463
  }
12459
12464
  return {
12460
12465
  priorityElements: t,
@@ -12467,18 +12472,18 @@ function $d(t, e, s, n) {
12467
12472
  const a = [];
12468
12473
  let o = r.element;
12469
12474
  for (; o; ) {
12470
- const l = o.tagName.toLowerCase();
12471
- (o === r.element || e.has(l) || o.hasAttribute("id") || o.hasAttribute("role") || o.hasAttribute("aria-label")) && a.unshift(o);
12475
+ const d = o.tagName.toLowerCase();
12476
+ (o === r.element || e.has(d) || o.hasAttribute("id") || o.hasAttribute("role") || o.hasAttribute("aria-label")) && a.unshift(o);
12472
12477
  const u = o.getRootNode();
12473
12478
  o = o.parentElement ?? (u instanceof ShadowRoot && u.host instanceof HTMLElement ? u.host : null);
12474
12479
  }
12475
- const c = a.length > 6 ? [a[0], ...a.slice(-5)] : a, d = c.map((l, u) => wr(
12476
- l,
12480
+ const c = a.length > 6 ? [a[0], ...a.slice(-5)] : a, l = c.map((d, u) => wr(
12481
+ d,
12477
12482
  s,
12478
12483
  n,
12479
- u === c.length - 1 ? _r(l).slice(0, 180) : ""
12484
+ u === c.length - 1 ? _r(d).slice(0, 180) : ""
12480
12485
  ));
12481
- a.length > c.length && d.splice(1, 0, "…"), i.push(`${r.labels.join(", ")}: ${d.join(" > ")}`);
12486
+ a.length > c.length && l.splice(1, 0, "…"), i.push(`${r.labels.join(", ")}: ${l.join(" > ")}`);
12482
12487
  }
12483
12488
  return i.join(`
12484
12489
  `);
@@ -13192,13 +13197,13 @@ async function Tl(t) {
13192
13197
  const o = await Promise.race([e.read(), n]);
13193
13198
  if (o === "timeout")
13194
13199
  return;
13195
- const { done: c, value: d } = o;
13200
+ const { done: c, value: l } = o;
13196
13201
  if (c)
13197
13202
  return fe(r + i.decode());
13198
- const l = Sn - a;
13199
- if (d.byteLength > l)
13200
- return r += i.decode(d.subarray(0, Math.max(l, 0)), { stream: !0 }), e.cancel(), `${fe(r)}... [truncated]`;
13201
- a += d.byteLength, r += i.decode(d, { stream: !0 });
13203
+ const d = Sn - a;
13204
+ if (l.byteLength > d)
13205
+ return r += i.decode(l.subarray(0, Math.max(d, 0)), { stream: !0 }), e.cancel(), `${fe(r)}... [truncated]`;
13206
+ a += l.byteLength, r += i.decode(l, { stream: !0 });
13202
13207
  }
13203
13208
  } catch {
13204
13209
  e?.cancel();