@aintela/chat 0.14.2 → 0.14.4

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.
Files changed (27) hide show
  1. package/dist/components.js +4571 -4558
  2. package/dist/components.js.map +1 -1
  3. package/dist/{detachedRunActivity-C_TBbcmB.js → detachedRunActivity-Cf-RPK9j.js} +352 -254
  4. package/dist/detachedRunActivity-Cf-RPK9j.js.map +1 -0
  5. package/dist/index.js +1 -1
  6. package/dist/services.js +1 -1
  7. package/dist/src/components/AiChat/AiChatTypes.d.ts +2 -0
  8. package/dist/src/components/AiChat/ChatPane/AskUserDialog.d.ts +2 -2
  9. package/dist/src/components/AiChat/ChatPane/friendlyToolConfig.d.ts +2 -0
  10. package/dist/src/components/AiChat/ChatPane/parts/askUserPartStrings.test.d.ts +1 -0
  11. package/dist/src/components/AiChat/aiChatEngine.d.ts +11 -0
  12. package/dist/src/components/AiChat/stateConfiguration.d.ts +1 -1
  13. package/dist/src/components/Library/markdownExtended.streaming.test.d.ts +1 -0
  14. package/dist/src/models/Notification.d.ts +3 -1
  15. package/dist/src/services/interaction/reduceInteraction.d.ts +16 -0
  16. package/dist/src/services/servers/AgentGatewayWSAsync.d.ts +26 -0
  17. package/dist/src/services/servers/connectionSupervisor.credentials.test.d.ts +1 -0
  18. package/dist/src/services/servers/connectionSupervisor.d.ts +14 -1
  19. package/dist/src/services/servers/gatewayCredentials.wire.test.d.ts +0 -0
  20. package/dist/src/services/servers/gatewaySessionSwitch.test.d.ts +1 -0
  21. package/dist/src/utils/jwtExpiry.d.ts +6 -0
  22. package/dist/src/utils/jwtExpiry.test.d.ts +1 -0
  23. package/dist/tests/bench/markdownRender.bench.d.ts +1 -0
  24. package/dist/tests/bench/textSplit.bench.d.ts +1 -0
  25. package/dist/tests/fakes/fakeJwt.d.ts +4 -0
  26. package/package.json +3 -3
  27. package/dist/detachedRunActivity-C_TBbcmB.js.map +0 -1
@@ -1,16 +1,16 @@
1
- var we = Object.defineProperty;
2
- var be = (i, e, t) => e in i ? we(i, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : i[e] = t;
3
- var h = (i, e) => we(i, "name", { value: e, configurable: !0 });
4
- var a = (i, e, t) => be(i, typeof e != "symbol" ? e + "" : e, t);
5
- import { i as U, E as I, S as q, z as Se, C as L, j as Le, L as Pe, P as z, n as Fe, q as Ne, T as _e, o as Ue, s as te, B as qe } from "./serializer-CdIQS0hy.js";
6
- import { format as xe } from "date-fns";
7
- import We from "lodash";
8
- import { C as E, P as Be } from "./Prompt-DZb7OaPp.js";
9
- import { d as Ge } from "./environmentUtils-VZNTCzEE.js";
10
- import { r as ze } from "./httpSessionService-B2wgAfly.js";
1
+ var Ie = Object.defineProperty;
2
+ var Fe = (i, e, t) => e in i ? Ie(i, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : i[e] = t;
3
+ var h = (i, e) => Ie(i, "name", { value: e, configurable: !0 });
4
+ var a = (i, e, t) => Fe(i, typeof e != "symbol" ? e + "" : e, t);
5
+ import { i as _, E as I, S as U, z as Te, C as L, j as xe, L as Ne, P as z, n as _e, q as Ue, T as qe, o as Be, s as ne, B as We } from "./serializer-CdIQS0hy.js";
6
+ import { format as Ge } from "date-fns";
7
+ import ze from "lodash";
8
+ import { C as E, P as He } from "./Prompt-DZb7OaPp.js";
9
+ import { d as Qe } from "./environmentUtils-VZNTCzEE.js";
10
+ import { r as je } from "./httpSessionService-B2wgAfly.js";
11
11
  const K = {
12
12
  PROMPTS: "envision-prompts"
13
- }, He = 50, ne = class ne {
13
+ }, Je = 50, re = class re {
14
14
  getPrompts() {
15
15
  try {
16
16
  const e = localStorage.getItem(K.PROMPTS);
@@ -40,7 +40,7 @@ const K = {
40
40
  storePrompt(e) {
41
41
  try {
42
42
  const t = this.getPrompts().filter((s) => s.promptText !== e.promptText);
43
- t.unshift(e), localStorage.setItem(K.PROMPTS, JSON.stringify(t.slice(0, He)));
43
+ t.unshift(e), localStorage.setItem(K.PROMPTS, JSON.stringify(t.slice(0, Je)));
44
44
  } catch (t) {
45
45
  console.error("Error storing prompt:", t);
46
46
  }
@@ -53,16 +53,16 @@ const K = {
53
53
  }
54
54
  }
55
55
  };
56
- h(ne, "LocalStorageService");
57
- let Ie = ne;
58
- const Rt = /* @__PURE__ */ h((i) => {
56
+ h(re, "LocalStorageService");
57
+ let ye = re;
58
+ const xt = /* @__PURE__ */ h((i) => {
59
59
  const e = i.getPrompts(), t = e.length;
60
60
  if (t > 0) {
61
61
  const s = e[0].promptText, n = e[e.length - 1].promptText, r = e[0].created;
62
62
  return { promptState: t + "_" + s + "_" + n + "_" + r };
63
63
  } else
64
64
  return { promptState: "0" };
65
- }, "usePromptState"), ie = class ie {
65
+ }, "usePromptState"), oe = class oe {
66
66
  constructor() {
67
67
  a(this, "artifactGenerated", "artifactGenerated");
68
68
  a(this, "artifactSelected", "artifactSelected");
@@ -80,16 +80,22 @@ const Rt = /* @__PURE__ */ h((i) => {
80
80
  a(this, "gatewayFirstToken", "gatewayFirstToken");
81
81
  }
82
82
  };
83
- h(ie, "EventTypes");
84
- let X = ie;
85
- const d = new X(), re = class re {
83
+ h(oe, "EventTypes");
84
+ let V = oe;
85
+ const d = new V(), ae = class ae {
86
86
  constructor() {
87
87
  a(this, "listeners", {});
88
88
  }
89
89
  callListeners(e, ...t) {
90
90
  const s = this.listeners[e];
91
91
  if (s) {
92
- const n = s.map((r) => r(...t));
92
+ const n = s.map((r) => {
93
+ try {
94
+ return r(...t);
95
+ } catch (o) {
96
+ return Promise.reject(o);
97
+ }
98
+ });
93
99
  Promise.all(n).catch((r) => {
94
100
  console.error(`Lost error in one of the listeners of the event: ${e}, listeners: ${s.length}, error: ${r}`, s);
95
101
  });
@@ -236,24 +242,52 @@ const d = new X(), re = class re {
236
242
  this.removeListener(d.gatewayFirstToken, e);
237
243
  }
238
244
  };
239
- h(re, "EventBusService");
240
- let Te = re;
241
- const Qe = 2e3;
242
- function x(i) {
245
+ h(ae, "EventBusService");
246
+ let ve = ae;
247
+ const Z = 2e3;
248
+ function q(i) {
243
249
  i.parts === i.prev.parts && (i.parts = i.prev.parts.slice());
244
250
  }
245
- h(x, "ownParts");
251
+ h(q, "ownParts");
246
252
  function Q(i) {
247
253
  i.functionMap === i.prev.functionMap && (i.functionMap = new Map(i.functionMap));
248
254
  }
249
255
  h(Q, "ownFunctionMap");
250
- const je = /* @__PURE__ */ h((i) => i == I.FunctionCall || i == I.PartialFunctionCall, "isFunctionCall"), Je = /* @__PURE__ */ h((i) => i == I.FunctionResponse, "isFunctionResponse"), Oe = /* @__PURE__ */ h((i) => i.parts.length + 1 + "-" + i.prev.interactionId, "nextPartId");
251
- function Ke(i, e) {
256
+ const Ke = /* @__PURE__ */ h((i) => i == I.FunctionCall || i == I.PartialFunctionCall, "isFunctionCall"), Ye = /* @__PURE__ */ h((i) => i == I.FunctionResponse, "isFunctionResponse"), $e = /* @__PURE__ */ h((i) => i.parts.length + 1 + "-" + i.prev.interactionId, "nextPartId");
257
+ function Xe(i, e) {
252
258
  var t, s, n, r, o;
253
- return !!(!e || i.mustPush || i.mustPush === !1 && (i.eventType !== e.eventType || ((t = i.functionDetails) == null ? void 0 : t.id) !== ((s = e.functionDetails) == null ? void 0 : s.id)) || i.textAppendable && (((r = (n = e.thoughtDetails) == null ? void 0 : n.text) == null ? void 0 : r.length) ?? ((o = e.text) == null ? void 0 : o.length) ?? 0) > Qe);
259
+ return !!(!e || i.mustPush || i.mustPush === !1 && (i.eventType !== e.eventType || ((t = i.functionDetails) == null ? void 0 : t.id) !== ((s = e.functionDetails) == null ? void 0 : s.id)) || i.textAppendable && i.eventType !== I.Text && (((r = (n = e.thoughtDetails) == null ? void 0 : n.text) == null ? void 0 : r.length) ?? ((o = e.text) == null ? void 0 : o.length) ?? 0) > Z);
260
+ }
261
+ h(Xe, "opensNewPart");
262
+ const Ve = /* @__PURE__ */ h((i) => i === " " || i === " " || i === `
263
+ ` || i === "\r", "isBlank");
264
+ function Ze(i) {
265
+ let e = 0;
266
+ for (const t of i.split(`
267
+ `)) {
268
+ const s = t.trimStart();
269
+ (s.startsWith("```") || s.startsWith("~~~")) && e++;
270
+ }
271
+ return e;
272
+ }
273
+ h(Ze, "fenceLines");
274
+ function et(i, e) {
275
+ if (i.length + e.length <= Z) return -1;
276
+ const t = /* @__PURE__ */ h((s) => (s >= 0 ? e[s] : i[i.length + s]) ?? "", "at");
277
+ for (let s = e.length - 1; s >= 0; s--) {
278
+ if (Ve(e[s]) || t(s - 1) !== `
279
+ `) continue;
280
+ let n = s - 2;
281
+ if (t(n) === "\r" && n--, t(n) === `
282
+ `) {
283
+ if (i.length + s <= Z) return -1;
284
+ if (Ze(i + e.slice(0, s)) % 2 === 0) return s;
285
+ }
286
+ }
287
+ return -1;
254
288
  }
255
- h(Ke, "opensNewPart");
256
- function Ye(i, e) {
289
+ h(et, "splitAtBlockBoundary");
290
+ function tt(i, e) {
257
291
  const t = e.functionDetails.id, s = e.functionDetails.clientOutput, n = i.parts.findIndex((r) => {
258
292
  var o;
259
293
  return ((o = r.functionDetails) == null ? void 0 : o.id) === t;
@@ -268,18 +302,18 @@ function Ye(i, e) {
268
302
  parked: e.functionDetails.parked === !0 || r.functionDetails.parked === !0
269
303
  }
270
304
  };
271
- x(i), i.parts[n] = o, Q(i), i.functionMap.set(t, o);
305
+ q(i), i.parts[n] = o, Q(i), i.functionMap.set(t, o);
272
306
  } else {
273
307
  const r = {
274
308
  ...e,
275
- id: Oe(i),
309
+ id: $e(i),
276
310
  functionDetails: { ...e.functionDetails, silent: !0 }
277
311
  };
278
- x(i), i.parts.push(r), Q(i), i.functionMap.set(t, r);
312
+ q(i), i.parts.push(r), Q(i), i.functionMap.set(t, r);
279
313
  }
280
314
  }
281
- h(Ye, "foldClientOutput");
282
- function Xe(i, e, t, s, n) {
315
+ h(tt, "foldClientOutput");
316
+ function st(i, e, t, s, n) {
283
317
  var g;
284
318
  const r = i.parts.findIndex((m) => {
285
319
  var u;
@@ -312,22 +346,22 @@ function Xe(i, e, t, s, n) {
312
346
  parked: c.parked === !0 || l.parked === !0
313
347
  }
314
348
  };
315
- Q(i), i.functionMap.set(s, f), f.eventType === I.FunctionResponse && ((g = n == null ? void 0 : n.onFunctionResponse) == null || g.call(n, f.functionDetails)), r > -1 && (x(i), i.parts[r] = f);
349
+ Q(i), i.functionMap.set(s, f), f.eventType === I.FunctionResponse && ((g = n == null ? void 0 : n.onFunctionResponse) == null || g.call(n, f.functionDetails)), r > -1 && (q(i), i.parts[r] = f);
316
350
  }
317
- h(Xe, "foldFunctionEvent");
318
- function Ve(i, e, t, s) {
351
+ h(st, "foldFunctionEvent");
352
+ function Ee(i, e, t, s) {
319
353
  s && e.functionDetails && (Q(i), i.functionMap.set(s, e));
320
- const n = i.prev.parts[i.prev.parts.length - 1] ?? null;
321
- n && n.textAppendable && (x(i), i.parts[i.parts.length - 1] = { ...n, ended: /* @__PURE__ */ new Date() });
354
+ const n = i.parts[i.parts.length - 1] ?? null;
355
+ n && n.textAppendable && (q(i), i.parts[i.parts.length - 1] = { ...n, ended: /* @__PURE__ */ new Date() });
322
356
  const r = {
323
357
  ...e,
324
- id: Oe(i),
358
+ id: $e(i),
325
359
  partial: t.partial
326
360
  };
327
361
  i.parts = [...i.parts, r];
328
362
  }
329
- h(Ve, "openPart");
330
- function Ze(i, e, t, s) {
363
+ h(Ee, "openPart");
364
+ function Y(i, e, t, s) {
331
365
  const n = i.parts[i.parts.length - 1] ?? null;
332
366
  if (!n) return;
333
367
  const r = {
@@ -342,10 +376,10 @@ function Ze(i, e, t, s) {
342
376
  }
343
377
  } else
344
378
  r.text = e.text ?? "", r.textDetails.version++, e.thoughtDetails && (r.thoughtDetails = { ...e.thoughtDetails, text: e.thoughtDetails.text.trim() });
345
- x(i), i.parts[i.parts.length - 1] = r;
379
+ q(i), i.parts[i.parts.length - 1] = r;
346
380
  }
347
- h(Ze, "appendText");
348
- function et(i, e) {
381
+ h(Y, "appendText");
382
+ function nt(i, e) {
349
383
  if (!e || e.length === 0) return i;
350
384
  const t = i.slice();
351
385
  for (const s of e) {
@@ -354,10 +388,10 @@ function et(i, e) {
354
388
  }
355
389
  return t;
356
390
  }
357
- h(et, "mergeArtifacts");
358
- function tt(i, e, t) {
391
+ h(nt, "mergeArtifacts");
392
+ function it(i, e, t) {
359
393
  var c, l;
360
- const s = U.FlatParts(e == null ? void 0 : e.parts), n = i.parts[i.parts.length - 1] ?? null, r = {
394
+ const s = _.FlatParts(e == null ? void 0 : e.parts), n = i.parts[i.parts.length - 1] ?? null, r = {
361
395
  prev: i,
362
396
  parts: i.parts,
363
397
  functionMap: i.functionMap ?? /* @__PURE__ */ new Map()
@@ -365,20 +399,28 @@ function tt(i, e, t) {
365
399
  let o = !1;
366
400
  if (s) {
367
401
  if (s.eventType === I.FunctionClientOutput && !!((c = s.functionDetails) != null && c.id))
368
- Ye(r, s);
369
- else if (Ke(s, n)) {
370
- const g = je(s.eventType) || Je(s.eventType), m = g ? (l = s.functionDetails) == null ? void 0 : l.id : void 0;
402
+ tt(r, s);
403
+ else if (Xe(s, n)) {
404
+ const g = Ke(s.eventType) || Ye(s.eventType), m = g ? (l = s.functionDetails) == null ? void 0 : l.id : void 0;
371
405
  g && !m && console.error("Got isCall or isResponse without a callId", s);
372
406
  const u = m ? r.functionMap.get(m) : void 0;
373
- u && m && s.functionDetails ? Xe(r, s, u, m, t) : (Ve(r, s, e, m), o = !0);
407
+ u && m && s.functionDetails ? st(r, s, u, m, t) : (Ee(r, s, e, m), o = !0);
408
+ }
409
+ if (s.textAppendable) {
410
+ const g = r.parts[r.parts.length - 1], m = !o && e.partial && s.eventType === I.Text && (g == null ? void 0 : g.eventType) === I.Text && s.text ? et(g.text ?? "", s.text) : -1;
411
+ if (m >= 0) {
412
+ m > 0 && Y(r, { ...s, text: s.text.slice(0, m) }, e, !1);
413
+ const u = { ...s, text: s.text.slice(m) };
414
+ Ee(r, u, e, void 0), Y(r, u, e, !0);
415
+ } else
416
+ Y(r, s, e, o);
374
417
  }
375
- s.textAppendable && Ze(r, s, e, o);
376
418
  }
377
419
  return {
378
420
  ...i,
379
421
  version: i.version + 1,
380
422
  parts: r.parts,
381
- artifactData: et(i.artifactData ?? [], e.llmArtifacts),
423
+ artifactData: nt(i.artifactData ?? [], e.llmArtifacts),
382
424
  functionMap: r.functionMap,
383
425
  turn_complete: e.turn_complete,
384
426
  partial: e.partial,
@@ -386,8 +428,8 @@ function tt(i, e, t) {
386
428
  agent: e.agent ?? i.agent
387
429
  };
388
430
  }
389
- h(tt, "reduceInteraction");
390
- const oe = class oe {
431
+ h(it, "reduceInteraction");
432
+ const ce = class ce {
391
433
  constructor(e, t) {
392
434
  a(this, "interaction");
393
435
  a(this, "eventBusService");
@@ -399,15 +441,15 @@ const oe = class oe {
399
441
  * throttled subscribers cannot diverge from live state.
400
442
  */
401
443
  merge(e) {
402
- const t = tt(this.interaction, e, {
444
+ const t = it(this.interaction, e, {
403
445
  onFunctionResponse: /* @__PURE__ */ h((s) => this.eventBusService.gatewayEmitFunctionResponse(s), "onFunctionResponse")
404
446
  });
405
447
  return this.interaction = t, t;
406
448
  }
407
449
  };
408
- h(oe, "InteractionService");
409
- let j = oe;
410
- const ke = 4001, st = 4002, De = 4004, nt = 4100, H = 500, it = 2e4, rt = 1e3, ot = 0.2, _ = 300 * 1e3, at = 0.75, ct = 2e3, S = "[Connection]", ae = class ae {
450
+ h(ce, "InteractionService");
451
+ let j = ce;
452
+ const Re = 4001, rt = 4002, be = 4004, ot = 4100, H = 500, at = 2e4, ct = 1e3, lt = 0.2, N = 300 * 1e3, ht = 0.75, ut = 2e3, w = "[Connection]", le = class le {
411
453
  constructor(e) {
412
454
  a(this, "ports");
413
455
  a(this, "state");
@@ -464,7 +506,7 @@ const ke = 4001, st = 4002, De = 4004, nt = 4100, H = 500, it = 2e4, rt = 1e3, o
464
506
  if (this.inflight) return this.inflight;
465
507
  if (this.isUp && this.target.sessionId && !this.halted)
466
508
  return Promise.resolve(this.target.sessionId);
467
- } else this.target && (console.log(`${S} switching from session ${this.target.sessionId ?? "(new)"} to ${e ?? "(new)"}.`), this.close());
509
+ } else this.target && (console.log(`${w} switching from session ${this.target.sessionId ?? "(new)"} to ${e ?? "(new)"}.`), this.close());
468
510
  return this.halted = null, this.cancelRetry(), this.target = { sessionId: e, resume: (t == null ? void 0 : t.resume) === !0, prepare: t == null ? void 0 : t.prepare }, this.startIdleTick(), this.dial();
469
511
  }
470
512
  /**
@@ -474,9 +516,11 @@ const ke = 4001, st = 4002, De = 4004, nt = 4100, H = 500, it = 2e4, rt = 1e3, o
474
516
  */
475
517
  async ensure(e) {
476
518
  var t;
519
+ if (this.halted === "credentials-expired" && this.target)
520
+ return console.warn(`${w} send guard: halted on an expired credential — checking it again before the send.`), this.halted = null, this.target.resume = !0, this.dial();
477
521
  if (this.halted)
478
522
  throw new Error(`The connection was halted (${this.halted}); session ${((t = this.target) == null ? void 0 : t.sessionId) ?? e ?? "none"} cannot be redialled.`);
479
- return this.target ? this.inflight ? this.inflight : this.isUp && this.target.sessionId ? this.target.sessionId : (console.warn(`${S} send guard: socket is DOWN at send time (session ${this.target.sessionId ?? "(new)"}, status ${this.state.connectionStatus}) — redialling now instead of in ${this.wait}ms.`), this.cancelRetry(), this.target.resume = !0, this.dial()) : (console.warn(`${S} send guard: nothing supervised yet — opening session ${e ?? "(new)"} with the replay cursor.`), this.open(e, { resume: !0 }));
523
+ return this.target ? this.inflight ? this.inflight : this.isUp && this.target.sessionId ? this.target.sessionId : (console.warn(`${w} send guard: socket is DOWN at send time (session ${this.target.sessionId ?? "(new)"}, status ${this.state.connectionStatus}) — redialling now instead of in ${this.wait}ms.`), this.cancelRetry(), this.target.resume = !0, this.dial()) : (console.warn(`${w} send guard: nothing supervised yet — opening session ${e ?? "(new)"} with the replay cursor.`), this.open(e, { resume: !0 }));
480
524
  }
481
525
  /** Stop supervising: hang up, cancel any retry, stop the idle tick. Never throws. */
482
526
  close() {
@@ -485,7 +529,7 @@ const ke = 4001, st = 4002, De = 4004, nt = 4100, H = 500, it = 2e4, rt = 1e3, o
485
529
  try {
486
530
  this.ports.hangUp();
487
531
  } catch (t) {
488
- console.error(`${S} hangUp threw`, t);
532
+ console.error(`${w} hangUp threw`, t);
489
533
  }
490
534
  e && this.state.setConnectionStatus(E.Disconnected);
491
535
  }
@@ -501,12 +545,12 @@ const ke = 4001, st = 4002, De = 4004, nt = 4100, H = 500, it = 2e4, rt = 1e3, o
501
545
  * A close that lands while a dial is in flight is remembered and judged when that dial fails.
502
546
  */
503
547
  transportClosed(e, t) {
504
- if (e !== ke && (this.lastCloseCode = e, !!this.target)) {
548
+ if (e !== Re && (this.lastCloseCode = e, !!this.target)) {
505
549
  if (this.inflight) {
506
- console.log(`${S} socket closed (code=${e}) while a dial is in flight — judged when it settles.`);
550
+ console.log(`${w} socket closed (code=${e}) while a dial is in flight — judged when it settles.`);
507
551
  return;
508
552
  }
509
- this.state.connectionStatus === E.Connected && (console.warn(`${S} socket closed: code=${e} reason="${t}" (session ${this.target.sessionId ?? "(new)"}).`), this.state.setConnectionStatus(E.Disconnected), this.judge(e));
553
+ this.state.connectionStatus === E.Connected && (console.warn(`${w} socket closed: code=${e} reason="${t}" (session ${this.target.sessionId ?? "(new)"}).`), this.state.setConnectionStatus(E.Disconnected), this.judge(e));
510
554
  }
511
555
  }
512
556
  // ─── The dial ───────────────────────────────────────────────────────────
@@ -514,11 +558,15 @@ const ke = 4001, st = 4002, De = 4004, nt = 4100, H = 500, it = 2e4, rt = 1e3, o
514
558
  const e = this.target;
515
559
  this.lastCloseCode = null, this.state.setConnectionStatus(E.Connecting);
516
560
  const t = this.now();
517
- console.log(`${S} dialling session ${e.sessionId ?? "(new)"}${e.resume ? " with the replay cursor" : ""}${this.everConnected ? " (reconnect)" : ""}.`);
518
- const n = (async () => (e.prepare && await e.prepare(), this.ports.dial(e.sessionId, { resume: e.resume })))().then((r) => {
561
+ console.log(`${w} dialling session ${e.sessionId ?? "(new)"}${e.resume ? " with the replay cursor" : ""}${this.everConnected ? " (reconnect)" : ""}.`);
562
+ const n = (async () => {
563
+ if (this.ports.ensureCredentials && !await this.ports.ensureCredentials())
564
+ throw this.target === e && !this.halted && (this.state.setConnectionStatus(E.Disconnected), this.halt("credentials-expired", { sessionId: e.sessionId })), new Error("The access token has expired and could not be renewed — not dialling.");
565
+ return e.prepare && await e.prepare(), this.ports.dial(e.sessionId, { resume: e.resume });
566
+ })().then((r) => {
519
567
  var c, l;
520
568
  if (this.target !== e) {
521
- console.log(`${S} a dial for ${e.sessionId ?? "(new)"} resolved after it was abandoned — hanging up.`);
569
+ console.log(`${w} a dial for ${e.sessionId ?? "(new)"} resolved after it was abandoned — hanging up.`);
522
570
  try {
523
571
  this.ports.hangUp();
524
572
  } catch {
@@ -526,7 +574,7 @@ const ke = 4001, st = 4002, De = 4004, nt = 4100, H = 500, it = 2e4, rt = 1e3, o
526
574
  throw new Error("Connection attempt abandoned");
527
575
  }
528
576
  if (e.sessionId && r !== e.sessionId) {
529
- console.error(`${S} asked for session ${e.sessionId}, the server answered with ${r} — refusing the swap and halting.`);
577
+ console.error(`${w} asked for session ${e.sessionId}, the server answered with ${r} — refusing the swap and halting.`);
530
578
  try {
531
579
  this.ports.hangUp();
532
580
  } catch {
@@ -534,11 +582,11 @@ const ke = 4001, st = 4002, De = 4004, nt = 4100, H = 500, it = 2e4, rt = 1e3, o
534
582
  throw this.state.setConnectionStatus(E.Disconnected), this.halt("session-gone", { sessionId: e.sessionId, actualSessionId: r }), new Error(`Session ${e.sessionId} no longer exists on the server (it answered with ${r}).`);
535
583
  }
536
584
  const o = this.everConnected;
537
- return this.everConnected = !0, e.sessionId = r, e.resume = !0, e.prepare = void 0, this.wait = H, this.attempt = 0, this.state.setConnectionStatus(E.Connected), console.log(`${S} ${o ? "reconnected to" : "connected to"} session ${r} in ${this.now() - t}ms.`), (l = (c = this.ports).onConnected) == null || l.call(c, r, { reconnect: o }), r;
585
+ return this.everConnected = !0, e.sessionId = r, e.resume = !0, e.prepare = void 0, this.wait = H, this.attempt = 0, this.state.setConnectionStatus(E.Connected), console.log(`${w} ${o ? "reconnected to" : "connected to"} session ${r} in ${this.now() - t}ms.`), (l = (c = this.ports).onConnected) == null || l.call(c, r, { reconnect: o }), r;
538
586
  }).catch((r) => {
539
587
  if (this.target === e && !this.halted) {
540
588
  const o = this.lastCloseCode;
541
- console.error(`${S} dial of session ${e.sessionId ?? "(new)"} failed after ${this.now() - t}ms${o !== null ? ` (socket closed with ${o})` : ""}:`, r), this.state.setConnectionStatus(E.Disconnected), this.inflight === n && (this.inflight = null), this.judge(o);
589
+ console.error(`${w} dial of session ${e.sessionId ?? "(new)"} failed after ${this.now() - t}ms${o !== null ? ` (socket closed with ${o})` : ""}:`, r), this.state.setConnectionStatus(E.Disconnected), this.inflight === n && (this.inflight = null), this.judge(o);
542
590
  }
543
591
  throw r;
544
592
  }).finally(() => {
@@ -550,33 +598,33 @@ const ke = 4001, st = 4002, De = 4004, nt = 4100, H = 500, it = 2e4, rt = 1e3, o
550
598
  judge(e) {
551
599
  var s;
552
600
  const t = (s = this.target) == null ? void 0 : s.sessionId;
553
- if (e === st) return this.halt("attached-elsewhere", { sessionId: t, code: e });
554
- if (e === De) return this.halt("session-gone", { sessionId: t, code: e });
601
+ if (e === rt) return this.halt("attached-elsewhere", { sessionId: t, code: e });
602
+ if (e === be) return this.halt("session-gone", { sessionId: t, code: e });
555
603
  if (e === 1e3 || e === 1008) return this.halt("closed-by-server", { sessionId: t, code: e });
556
604
  this.scheduleRetry();
557
605
  }
558
606
  halt(e, t) {
559
607
  var s, n;
560
- this.halted = e, this.cancelRetry(), console.warn(`${S} halted (${e}) on session ${t.sessionId ?? "(new)"}${t.code !== void 0 ? `, close code ${t.code}` : ""} — no automatic redial; an explicit open() may try again.`);
608
+ this.halted = e, this.cancelRetry(), console.warn(`${w} halted (${e}) on session ${t.sessionId ?? "(new)"}${t.code !== void 0 ? `, close code ${t.code}` : ""} — no automatic redial; an explicit open() may try again.`);
561
609
  try {
562
610
  (n = (s = this.ports).onHalt) == null || n.call(s, e, t);
563
611
  } catch (r) {
564
- console.error(`${S} onHalt threw`, r);
612
+ console.error(`${w} onHalt threw`, r);
565
613
  }
566
614
  }
567
615
  scheduleRetry() {
568
616
  var t, s;
569
617
  if (!this.target || this.retryTimer || this.inflight) return;
570
618
  if (!this.state.sessionActive) {
571
- console.log(`${S} session idle — not redialling until activity resumes.`);
619
+ console.log(`${w} session idle — not redialling until activity resumes.`);
572
620
  return;
573
621
  }
574
622
  const e = this.jittered(this.wait);
575
- this.wait = Math.min(Math.floor(this.wait + this.wait * this.wait / rt), it), this.attempt += 1, console.warn(`${S} redialling session ${this.target.sessionId ?? "(new)"} in ${e}ms (then ${this.wait}ms, attempt ${this.attempt}).`);
623
+ this.wait = Math.min(Math.floor(this.wait + this.wait * this.wait / ct), at), this.attempt += 1, console.warn(`${w} redialling session ${this.target.sessionId ?? "(new)"} in ${e}ms (then ${this.wait}ms, attempt ${this.attempt}).`);
576
624
  try {
577
625
  (s = (t = this.ports).onRetryScheduled) == null || s.call(t, { sessionId: this.target.sessionId, delayMs: e, attempt: this.attempt });
578
626
  } catch (n) {
579
- console.error(`${S} onRetryScheduled threw`, n);
627
+ console.error(`${w} onRetryScheduled threw`, n);
580
628
  }
581
629
  this.retryTimer = setTimeout(() => {
582
630
  this.retryTimer = null, !(!this.target || this.halted) && (this.target.resume = !0, this.dial().catch(() => {
@@ -587,7 +635,7 @@ const ke = 4001, st = 4002, De = 4004, nt = 4100, H = 500, it = 2e4, rt = 1e3, o
587
635
  this.retryTimer && (clearTimeout(this.retryTimer), this.retryTimer = null);
588
636
  }
589
637
  jittered(e) {
590
- return Math.max(0, Math.round(e + e * ot * (Math.random() * 2 - 1)));
638
+ return Math.max(0, Math.round(e + e * lt * (Math.random() * 2 - 1)));
591
639
  }
592
640
  sameTarget(e) {
593
641
  var t;
@@ -595,7 +643,7 @@ const ke = 4001, st = 4002, De = 4004, nt = 4100, H = 500, it = 2e4, rt = 1e3, o
595
643
  }
596
644
  // ─── Idle ───────────────────────────────────────────────────────────────
597
645
  startIdleTick() {
598
- this.idleTimer || (this.idleTimer = setInterval(() => this.tick(), ct));
646
+ this.idleTimer || (this.idleTimer = setInterval(() => this.tick(), ut));
599
647
  }
600
648
  stopIdleTick() {
601
649
  this.idleTimer && (clearInterval(this.idleTimer), this.idleTimer = null);
@@ -612,25 +660,37 @@ const ke = 4001, st = 4002, De = 4004, nt = 4100, H = 500, it = 2e4, rt = 1e3, o
612
660
  if (!this.target) return;
613
661
  this.state.turnOpen && this.state.setLastActivity();
614
662
  const e = this.now() - this.state.lastActivity;
615
- if (e > _) {
663
+ if (e > N) {
616
664
  if (this.state.sessionActive && this.state.setIsSessionActive(!1), this.cancelRetry(), this.state.connectionStatus === E.Connected) {
617
- console.warn(`${S} idle for ${Math.round(e / 1e3)}s (limit ${_ / 1e3}s) — closing the socket (session ${this.target.sessionId ?? "(new)"}). Activity, or a send, redials it.`);
665
+ console.warn(`${w} idle for ${Math.round(e / 1e3)}s (limit ${N / 1e3}s) — closing the socket (session ${this.target.sessionId ?? "(new)"}). Activity, or a send, redials it.`);
618
666
  try {
619
667
  this.ports.hangUp();
620
668
  } catch (t) {
621
- console.error(`${S} hangUp threw`, t);
669
+ console.error(`${w} hangUp threw`, t);
622
670
  }
623
671
  this.state.setConnectionStatus(E.Disconnected);
624
672
  }
625
673
  return;
626
674
  }
627
- this.state.sessionActive || (console.log(`${S} activity resumed — the session is active again.`), this.state.setIsSessionActive(!0), this.wait = H, this.state.connectionStatus === E.Disconnected && !this.halted && !this.inflight && (this.target.resume = !0, this.dial().catch(() => {
628
- }))), e > _ * at ? this.idleWarningLogged || (this.idleWarningLogged = !0, console.warn(`${S} idle ${Math.round(e / 1e3)}s of ${_ / 1e3}s — the socket closes in about ${Math.round((_ - e) / 1e3)}s unless something happens.`)) : this.idleWarningLogged = !1;
675
+ this.state.sessionActive || (console.log(`${w} activity resumed — the session is active again.`), this.state.setIsSessionActive(!0), this.wait = H, this.state.connectionStatus === E.Disconnected && !this.halted && !this.inflight && (this.target.resume = !0, this.dial().catch(() => {
676
+ }))), e > N * ht ? this.idleWarningLogged || (this.idleWarningLogged = !0, console.warn(`${w} idle ${Math.round(e / 1e3)}s of ${N / 1e3}s — the socket closes in about ${Math.round((N - e) / 1e3)}s unless something happens.`)) : this.idleWarningLogged = !1;
629
677
  }
630
678
  };
631
- h(ae, "ConnectionSupervisor");
632
- let V = ae;
633
- const ce = class ce {
679
+ h(le, "ConnectionSupervisor");
680
+ let ee = le;
681
+ function dt(i, e = Date.now()) {
682
+ if (!i) return null;
683
+ const t = i.split(".")[1];
684
+ if (!t) return null;
685
+ try {
686
+ const s = t.replace(/-/g, "+").replace(/_/g, "/").padEnd(Math.ceil(t.length / 4) * 4, "="), n = JSON.parse(atob(s)).exp;
687
+ return typeof n == "number" ? n - e / 1e3 : null;
688
+ } catch {
689
+ return null;
690
+ }
691
+ }
692
+ h(dt, "secondsUntilJwtExpiry");
693
+ const he = class he {
634
694
  constructor(e) {
635
695
  a(this, "pending", null);
636
696
  a(this, "lastPublishedAt", 0);
@@ -662,8 +722,15 @@ const ce = class ce {
662
722
  this.trailing && (clearTimeout(this.trailing), this.trailing = null);
663
723
  }
664
724
  };
665
- h(ce, "ThrottledEmitter");
666
- let Z = ce;
725
+ h(he, "ThrottledEmitter");
726
+ let te = he;
727
+ function ft(i) {
728
+ return async () => {
729
+ const e = dt(i());
730
+ return e === null || e > 0 ? !0 : (console.warn(`[AgentGateway] the access token expired ${Math.round(-e)}s ago and the host gave no way to renew it — not dialling.`), !1);
731
+ };
732
+ }
733
+ h(ft, "builtInCredentialCheck");
667
734
  const y = class y {
668
735
  constructor(e, t, s, n, r, o, c, l, f, g, m) {
669
736
  a(this, "base_url");
@@ -714,7 +781,7 @@ const y = class y {
714
781
  */
715
782
  a(this, "everConnected", !1);
716
783
  /** Publishes the live message to the store; see ThrottledEmitter for the cadence rules. */
717
- a(this, "liveMessage", new Z({
784
+ a(this, "liveMessage", new te({
718
785
  windowMs: y.CURRENT_MSG_THROTTLE_MS,
719
786
  publish: /* @__PURE__ */ h((e) => {
720
787
  this.sessionState.setCurrentMessage(e), this.eventBusService.gatewayEmitMessage(e);
@@ -730,8 +797,9 @@ const y = class y {
730
797
  a(this, "runningRequests", /* @__PURE__ */ new Map());
731
798
  this.options = m ?? {}, this.user = e, this.config = r, this.rawJwt = e.access_token, this.base_url = n, this.eventBusService = t, this.sessionId = g, this.artifactService = s, this.sessionState = o.getState(), this.notificationPort = c, this.storageService = f, o.subscribe((u, p) => {
732
799
  this.sessionState = u, p.turnOpen && !u.turnOpen && this.flushAnnouncements();
733
- }), this.wsService = l, this.connection = new V({
800
+ }), this.wsService = l, this.connection = new ee({
734
801
  store: o,
802
+ ensureCredentials: this.options.ensureDialableToken ?? (this.options.getToken ? ft(this.options.getToken) : void 0),
735
803
  // A redial while a turn is open carries the turn's id: the server tells us if it cannot continue it.
736
804
  dial: /* @__PURE__ */ h((u, p) => this.wsService.connect(u, {
737
805
  ...p,
@@ -744,12 +812,12 @@ const y = class y {
744
812
  }, "onConnected"),
745
813
  onRetryScheduled: /* @__PURE__ */ h(({ delayMs: u, attempt: p }) => {
746
814
  var D;
747
- const w = Date.now(), C = ((D = this.sessionState.connectionOutage) == null ? void 0 : D.since) ?? w;
748
- this.sessionState.setConnectionOutage({ since: C, retryAt: w + u, attempt: p, halted: null }), w - C >= y.OUTAGE_CLOSES_TURN_AFTER_MS && this.closeOpenTurnWith(y.OUTAGE_TURN_MESSAGE);
815
+ const S = Date.now(), C = ((D = this.sessionState.connectionOutage) == null ? void 0 : D.since) ?? S;
816
+ this.sessionState.setConnectionOutage({ since: C, retryAt: S + u, attempt: p, halted: null }), S - C >= y.OUTAGE_CLOSES_TURN_AFTER_MS && this.closeOpenTurnWith(y.OUTAGE_TURN_MESSAGE);
749
817
  }, "onRetryScheduled"),
750
818
  onHalt: /* @__PURE__ */ h((u, p) => {
751
- const w = this.sessionState.connectionOutage;
752
- this.sessionState.setConnectionOutage({ since: (w == null ? void 0 : w.since) ?? Date.now(), retryAt: null, attempt: (w == null ? void 0 : w.attempt) ?? 0, halted: u }), this.notifyHalt(u, p), this.closeOpenTurnWith(y.HALT_TURN_MESSAGE[u]);
819
+ const S = this.sessionState.connectionOutage;
820
+ this.sessionState.setConnectionOutage({ since: (S == null ? void 0 : S.since) ?? Date.now(), retryAt: null, attempt: (S == null ? void 0 : S.attempt) ?? 0, halted: u }), this.notifyHalt(u, p), this.closeOpenTurnWith(y.HALT_TURN_MESSAGE[u]);
753
821
  }, "onHalt")
754
822
  }), this.wsService.onEvent = async (u) => {
755
823
  await this.Message(u);
@@ -789,14 +857,15 @@ const y = class y {
789
857
  if (!this.sessionState.turnOpen) return;
790
858
  const t = this.getCurrentInteractionId(), s = this.openTurns.size > 0 ? [...this.openTurns] : t ? [t] : [];
791
859
  for (const n of s)
792
- console.warn(`[AgentGateway] closing interaction ${n} from the client side: ${e}`), this.Message(q.createErrorEvent(e, n));
860
+ console.warn(`[AgentGateway] closing interaction ${n} from the client side: ${e}`), this.Message(U.createErrorEvent(e, n));
793
861
  }
794
862
  /** The supervisor gave up on its own (another tab holds the session, the session is gone, …): tell the user. */
795
863
  notifyHalt(e, t) {
796
864
  const s = {
797
865
  "attached-elsewhere": { message: "Esta sessão já está aberta em outra janela", kind: "session-attached-elsewhere" },
798
866
  "session-gone": { message: "A sessão não existe mais no servidor", kind: "session-gone" },
799
- "closed-by-server": { message: "O servidor encerrou a conexão", kind: "connection-closed" }
867
+ "closed-by-server": { message: "O servidor encerrou a conexão", kind: "connection-closed" },
868
+ "credentials-expired": { message: "Sua sessão expirou. Entre novamente para continuar", kind: "credentials-expired" }
800
869
  }, { message: n, kind: r } = s[e];
801
870
  try {
802
871
  this.notificationPort.pushNotification({
@@ -920,10 +989,10 @@ const y = class y {
920
989
  const n = this.interactionsServiceMap.get(t);
921
990
  if (n) {
922
991
  const o = n.interaction;
923
- o.interactionQuestion || (o.interactionQuestion = e.content ?? ""), o.origin ?? (o.origin = Se(e.origin));
992
+ o.interactionQuestion || (o.interactionQuestion = e.content ?? ""), o.origin ?? (o.origin = Te(e.origin));
924
993
  return;
925
994
  }
926
- this.openRemoteInteraction(t, e.content ?? "", Se(e.origin), !0);
995
+ this.openRemoteInteraction(t, e.content ?? "", Te(e.origin), !0);
927
996
  }
928
997
  /**
929
998
  * The server delivered messages this tab queued (AIA Issue 1651). Injected into the running turn — the frame lists
@@ -965,7 +1034,7 @@ const y = class y {
965
1034
  return t || (t = this.openRemoteInteraction(e.interactionId, "", void 0, !1)), t.merge(e);
966
1035
  }
967
1036
  getNewInteractionId() {
968
- const t = xe(/* @__PURE__ */ new Date(), "MMM_dd_HH_mm_ss");
1037
+ const t = Ge(/* @__PURE__ */ new Date(), "MMM_dd_HH_mm_ss");
969
1038
  return `${this.msg_order}_${t}`;
970
1039
  }
971
1040
  // ─── Inbound: server events ─────────────────────────────────────────────
@@ -1008,7 +1077,7 @@ const y = class y {
1008
1077
  });
1009
1078
  } catch (t) {
1010
1079
  if (this.getCurrentInteractionId()) {
1011
- const s = q.createErrorEvent("OnMessage error: " + t.toString(), this.getCurrentInteractionId() ?? "Empty Current"), n = this.updateMap(s);
1080
+ const s = U.createErrorEvent("OnMessage error: " + t.toString(), this.getCurrentInteractionId() ?? "Empty Current"), n = this.updateMap(s);
1012
1081
  if (console.error("Error event: ", JSON.stringify(s, void 0, 4)), !n) {
1013
1082
  console.error("Error event, could not update interaction: ", JSON.stringify(s, void 0, 4));
1014
1083
  return;
@@ -1100,7 +1169,29 @@ const y = class y {
1100
1169
  * session is never swapped for another.
1101
1170
  */
1102
1171
  async openConnection(e, t) {
1103
- return this.connection.open(e, t);
1172
+ return this.isSessionSwitch(e) && this.forgetSession(), this.connection.open(e, t);
1173
+ }
1174
+ /**
1175
+ * Opening `sessionId` leaves the session this gateway is on: a different id, or a fresh session (undefined) while
1176
+ * one is held. Re-opening the same session (a resume, a redial) is not a switch, and neither is the first open.
1177
+ */
1178
+ isSessionSwitch(e) {
1179
+ return this.sessionId === void 0 ? !1 : e === void 0 || e !== this.sessionId;
1180
+ }
1181
+ /**
1182
+ * Drop every piece of per-session turn state (AIA Issue 2261). The store's transcript is reset by the session
1183
+ * record's bind, but the gateway is not: a turn of the previous conversation still open here (an `ask_user` card
1184
+ * parked at its end, say) used to survive the switch, and the next conversation's first turn-complete handed the
1185
+ * live message over to it — conversation A's question rendered in B, under B's agent, with A's timestamp. The
1186
+ * status bubble of B's first send was a clone of A's interaction for the same reason, and a paused A merged B's
1187
+ * first message into A's interaction id. Nothing here belongs to the next session, so none of it is carried over.
1188
+ */
1189
+ forgetSession() {
1190
+ this.liveMessage.cancelPending(), this.openTurns.clear(), this.currentIS = null, this.suspendState = !1, this.interactionsMap.clear(), this.interactionsServiceMap.clear(), this.interactionCallIds.clear(), this.committedTurns.clear(), this.localInteractionIds.clear();
1191
+ const e = [...this.queuedMessages.keys()];
1192
+ this.queuedMessages.clear(), e.length > 0 && this.sessionState.removeQueuedMessages(e);
1193
+ for (const t of this.pendingAnnouncements) this.announceRequested.delete(t.key);
1194
+ this.pendingAnnouncements = [], this.sessionState.setLastToolEvent(null), this.sessionState.setCurrentMessage(null), this.sessionState.setTurnOpen(!1);
1104
1195
  }
1105
1196
  async closeConnection(e = !0) {
1106
1197
  try {
@@ -1145,15 +1236,21 @@ const y = class y {
1145
1236
  }
1146
1237
  // ─── Outbound: the user's turns ─────────────────────────────────────────
1147
1238
  async sendMessage(e, t) {
1148
- let s = this.getInteractions().length, n = U.createWaiting(!0, !0, "Overall", /* @__PURE__ */ new Date());
1239
+ let s = this.getInteractions().length, n = _.createWaiting(!0, !0, "Overall", /* @__PURE__ */ new Date());
1149
1240
  this.sendStatusMessage(e.data, [n], s.toString() + "1");
1150
1241
  try {
1151
1242
  const { promptAsString: r, json: o } = this.sessionState.onRenderPrompt ? this.sessionState.onRenderPrompt(e.data) : { promptAsString: e.data, json: void 0 };
1152
1243
  this.sessionState.onRenderPrompt && (e.data = o, e.friendlyMessage = r);
1153
- const c = await this.sendMessageInternal(e, t), l = Be.createPrompt(r ?? "", (o == null ? void 0 : o.toString()) ?? {});
1154
- this.storageService.storePrompt(l);
1155
- const f = U.fromText("Planejando próximos passos");
1156
- return this.sendStatusMessage(e.data, [n, f], s.toString() + "1"), c != null && c.success ? this.eventBusService.ChatEmitMessageSent(e.data, c.interaction) : this.eventBusService.ChatEmitMessageError((c == null ? void 0 : c.error) ?? ""), c;
1244
+ const c = await this.sendMessageInternal(e, t);
1245
+ try {
1246
+ const l = He.createPrompt(r ?? "", (o == null ? void 0 : o.toString()) ?? {});
1247
+ this.storageService.storePrompt(l);
1248
+ const f = _.fromText("Planejando próximos passos");
1249
+ this.sendStatusMessage(e.data, [n, f], s.toString() + "1"), c != null && c.success ? this.eventBusService.ChatEmitMessageSent(e.data, c.interaction) : this.eventBusService.ChatEmitMessageError((c == null ? void 0 : c.error) ?? "");
1250
+ } catch (l) {
1251
+ console.error("[AgentGateway] the message was sent, but what follows the send failed", l);
1252
+ }
1253
+ return c;
1157
1254
  } catch (r) {
1158
1255
  const o = r instanceof Error ? r.message : String(r ?? "");
1159
1256
  return this.liveMessage.cancelPending(), this.sessionState.setCurrentMessage(null), this.sessionState.setTurnOpen(this.openTurns.size > 0), this.eventBusService.ChatEmitMessageError(o), {
@@ -1164,7 +1261,7 @@ const y = class y {
1164
1261
  created: /* @__PURE__ */ new Date(),
1165
1262
  interactionId: "",
1166
1263
  partial: !1,
1167
- parts: [U.fromError(o)],
1264
+ parts: [_.fromError(o)],
1168
1265
  version: 0
1169
1266
  }
1170
1267
  };
@@ -1176,7 +1273,7 @@ const y = class y {
1176
1273
  const s = this.suspendState;
1177
1274
  this.suspendState = !1;
1178
1275
  const n = this.startInteraction(e.friendlyMessage ?? e.data, s);
1179
- if (this.localInteractionIds.add(n.interactionId), this.registerInteractionCallId(n.interactionId, t), (r = e.userUi) != null && r.name && n.parts.push(U.fromUserUi(e.userUi.name, e.userUi.args)), !this.wsService)
1276
+ if (this.localInteractionIds.add(n.interactionId), this.registerInteractionCallId(n.interactionId, t), (r = e.userUi) != null && r.name && n.parts.push(_.fromUserUi(e.userUi.name, e.userUi.args)), !this.wsService)
1180
1277
  throw "no wsService created";
1181
1278
  if (!((o = this.config.agentConfig) != null && o.id))
1182
1279
  throw "Agent not selected";
@@ -1249,7 +1346,7 @@ const y = class y {
1249
1346
  sendStatusMessage(e, t, s) {
1250
1347
  var r, o;
1251
1348
  let n;
1252
- ((o = (r = this.currentIS) == null ? void 0 : r.interaction) == null ? void 0 : o.turn_complete) === !1 && !this.currentIS.interaction.remote ? (n = We.cloneDeep(this.currentIS.interaction), n.parts.push(...t)) : n = {
1349
+ ((o = (r = this.currentIS) == null ? void 0 : r.interaction) == null ? void 0 : o.turn_complete) === !1 && !this.currentIS.interaction.remote ? (n = ze.cloneDeep(this.currentIS.interaction), n.parts.push(...t)) : n = {
1253
1350
  interactionId: "tmp" + s,
1254
1351
  created: /* @__PURE__ */ new Date(),
1255
1352
  partial: !0,
@@ -1396,61 +1493,62 @@ a(y, "OUTAGE_CLOSES_TURN_AFTER_MS", 6e4), a(y, "OUTAGE_TURN_MESSAGE", "Sem conex
1396
1493
  a(y, "NO_CONNECTION_MESSAGE", "Não foi possível obter conexão com o servidor"), a(y, "HALT_TURN_MESSAGE", {
1397
1494
  "attached-elsewhere": "Esta sessão está aberta em outra janela. A resposta foi interrompida.",
1398
1495
  "session-gone": "A sessão não existe mais no servidor. A resposta foi interrompida.",
1399
- "closed-by-server": "O servidor encerrou a conexão. A resposta foi interrompida."
1496
+ "closed-by-server": "O servidor encerrou a conexão. A resposta foi interrompida.",
1497
+ "credentials-expired": "Sua sessão expirou. Entre novamente para continuar. A resposta foi interrompida."
1400
1498
  });
1401
- let ye = y;
1402
- function lt(i) {
1403
- const e = new Pe();
1499
+ let Me = y;
1500
+ function gt(i) {
1501
+ const e = new Ne();
1404
1502
  e.author = "main", e.streamingParts = i.streamingParts, i.partialEventType ? e.eventType = i.partialEventType : e.eventType = i.functionName ? { fullName: z.StreamingFunctionCallUpdateContent, type: I.PartialFunctionCall } : i.partialReasoning ? { fullName: z.StreamingReasoningContent, type: I.Thought } : { fullName: z.StreamingTextContent, type: I.Text }, e.interactionId = i.iteractionId ?? "", e.mimeType = "text/plain", e.partial = !0, e.role = { label: "Assistant" }, e.timestamp = i.timeStamp ?? (/* @__PURE__ */ new Date()).getTime(), e.turnComplete = !1;
1405
1503
  const t = e.eventType.type;
1406
1504
  if (t == I.PartialFunctionCall) {
1407
- const s = new Fe();
1505
+ const s = new _e();
1408
1506
  s.choiceIndex = 0, s.callId = i.functionCallId, s.arguments = i.partialText, s.name = i.functionName, e.content = { items: [s], role: { label: "Assistant" } };
1409
1507
  } else if (t == I.Text)
1410
1508
  if (e.eventType.fullName == z.StreamingTextContent) {
1411
- const s = new Ne();
1509
+ const s = new Ue();
1412
1510
  s.text = i.partialText, e.content = { items: [s], role: { label: "Assistant" } };
1413
1511
  } else {
1414
- const s = new _e();
1512
+ const s = new qe();
1415
1513
  s.text = i.partialText, e.content = { items: [s], role: { label: "Assistant" } };
1416
1514
  }
1417
1515
  else if (t == I.Thought) {
1418
- const s = new Ue();
1516
+ const s = new Be();
1419
1517
  s.text = i.partialReasoning, e.content = { items: [s], role: { label: "Assistant" } };
1420
1518
  }
1421
1519
  return e;
1422
1520
  }
1423
- h(lt, "llmEventFromPartial");
1424
- function se(i) {
1425
- const e = i.partialEvent ? lt(i.partialEvent) : i.event;
1521
+ h(gt, "llmEventFromPartial");
1522
+ function ie(i) {
1523
+ const e = i.partialEvent ? gt(i.partialEvent) : i.event;
1426
1524
  if (e)
1427
1525
  return i.detachedRunId && (e.detachedRunId = i.detachedRunId, e.detachedRunName = i.detachedRunName), e;
1428
1526
  }
1429
- h(se, "llmEventFromFrame");
1430
- function $e(i) {
1527
+ h(ie, "llmEventFromFrame");
1528
+ function Le(i) {
1431
1529
  var e, t, s;
1432
1530
  return (((t = (e = i.content) == null ? void 0 : e.items) == null ? void 0 : t.length) ?? 0) > 0 || (((s = i.streamingParts) == null ? void 0 : s.length) ?? 0) > 0;
1433
1531
  }
1434
- h($e, "carriesContent");
1435
- function Re(i) {
1532
+ h(Le, "carriesContent");
1533
+ function Pe(i) {
1436
1534
  var t;
1437
1535
  if (i.type !== "InteractionStarted" || !((t = i.interaction) != null && t.interactionId)) return;
1438
1536
  if (i.interaction.detachedRunId || !i.detachedRunId) return i.interaction;
1439
- const e = Object.assign(new Le(), i.interaction);
1537
+ const e = Object.assign(new xe(), i.interaction);
1440
1538
  return e.detachedRunId = i.detachedRunId, e;
1441
1539
  }
1442
- h(Re, "interactionStartFromFrame");
1443
- const ht = 0.02;
1444
- function ut(i, e) {
1540
+ h(Pe, "interactionStartFromFrame");
1541
+ const pt = 0.02;
1542
+ function mt(i, e) {
1445
1543
  if (!e) return null;
1446
1544
  const t = (e.interactionsCompressed ?? 0) > 0 || (e.compressionRatio ?? 0) > 0;
1447
1545
  if (!i)
1448
- return t ? ve(e, e.size, e.size) : null;
1449
- const s = i.size - e.size, n = e.maxSize || i.maxSize || 0, r = n > 0 ? s / n >= ht : i.size > 0 && s / i.size >= 0.1;
1450
- return !t && !r ? null : ve(e, i.size, e.size, i.ratio);
1546
+ return t ? Ce(e, e.size, e.size) : null;
1547
+ const s = i.size - e.size, n = e.maxSize || i.maxSize || 0, r = n > 0 ? s / n >= pt : i.size > 0 && s / i.size >= 0.1;
1548
+ return !t && !r ? null : Ce(e, i.size, e.size, i.ratio);
1451
1549
  }
1452
- h(ut, "detectCompaction");
1453
- function ve(i, e, t, s) {
1550
+ h(mt, "detectCompaction");
1551
+ function Ce(i, e, t, s) {
1454
1552
  return {
1455
1553
  at: Date.now(),
1456
1554
  // Where the bar stood when it happened — the marker's position. The ratio
@@ -1462,8 +1560,8 @@ function ve(i, e, t, s) {
1462
1560
  interactionsCompressed: i.interactionsCompressed
1463
1561
  };
1464
1562
  }
1465
- h(ve, "entry");
1466
- const Ee = 4, dt = 3, ft = 20, F = class F {
1563
+ h(Ce, "entry");
1564
+ const Ae = 4, wt = 3, St = 20, F = class F {
1467
1565
  constructor() {
1468
1566
  a(this, "stats");
1469
1567
  a(this, "onFlush");
@@ -1499,14 +1597,14 @@ const Ee = 4, dt = 3, ft = 20, F = class F {
1499
1597
  record(e) {
1500
1598
  const t = Date.now();
1501
1599
  if (this.events.push([t, e.textLength]), this.stats.eventCount += 1, this.stats.totalTransfered += e.rawLength, e.sessionInformation && !e.fromDetachedRun) {
1502
- const r = ut(this.previousSessionInformation, e.sessionInformation);
1503
- r && (this.sessionCompactions.push(r), this.sessionCompactions.length > ft && this.sessionCompactions.shift()), this.previousSessionInformation = e.sessionInformation, this.stats.sessionInformation = e.sessionInformation, this.stats.sessionCompactions = this.sessionCompactions;
1600
+ const r = mt(this.previousSessionInformation, e.sessionInformation);
1601
+ r && (this.sessionCompactions.push(r), this.sessionCompactions.length > St && this.sessionCompactions.shift()), this.previousSessionInformation = e.sessionInformation, this.stats.sessionInformation = e.sessionInformation, this.stats.sessionCompactions = this.sessionCompactions;
1504
1602
  }
1505
1603
  this.stats.elapsed = (t - this.stats.startTime.getTime()) / 1e3;
1506
- const s = t - Ee * 1e3;
1604
+ const s = t - Ae * 1e3;
1507
1605
  for (; this.events.length > 0 && this.events[0][0] <= s; ) this.events.shift();
1508
1606
  const n = this.events.reduce((r, o) => r + o[1], 0);
1509
- this.stats.tokensPerSecond = n / dt / Ee, this.flushCoalesced();
1607
+ this.stats.tokensPerSecond = n / wt / Ae, this.flushCoalesced();
1510
1608
  }
1511
1609
  flushCoalesced() {
1512
1610
  if (!this.onFlush) return;
@@ -1522,12 +1620,12 @@ const Ee = 4, dt = 3, ft = 20, F = class F {
1522
1620
  }
1523
1621
  };
1524
1622
  h(F, "StreamStatsTracker"), a(F, "STATS_FLUSH_MS", 120);
1525
- let ee = F;
1526
- const gt = 5e3, pt = 3e4, Y = 1e4, le = class le {
1623
+ let se = F;
1624
+ const It = 5e3, Tt = 3e4, X = 1e4, ue = class ue {
1527
1625
  constructor(e = "ws://localhost:8000", t) {
1528
1626
  a(this, "ws", null);
1529
1627
  /** Frame counts, byte totals, the token-rate estimate and the compaction history — see StreamStatsTracker. */
1530
- a(this, "statsTracker", new ee());
1628
+ a(this, "statsTracker", new se());
1531
1629
  a(this, "baseUrl");
1532
1630
  /**
1533
1631
  * Optional callback that returns the current JWT. We re-evaluate it on every connect/reconnect
@@ -1575,7 +1673,7 @@ const gt = 5e3, pt = 3e4, Y = 1e4, le = class le {
1575
1673
  * the single-attach policy makes it undeliverable from here anyway.
1576
1674
  */
1577
1675
  a(this, "pendingAnswers", []);
1578
- this.baseUrl = e, this.getToken = t, this.firstTokenInteractions = /* @__PURE__ */ new Set(), this.streamingResponseSerializer = te(), console.log("SOCKET INSTACE", Ge()), this.lastActivity = (/* @__PURE__ */ new Date()).getTime();
1676
+ this.baseUrl = e, this.getToken = t, this.firstTokenInteractions = /* @__PURE__ */ new Set(), this.streamingResponseSerializer = ne(), console.log("SOCKET INSTACE", Qe()), this.lastActivity = (/* @__PURE__ */ new Date()).getTime();
1579
1677
  }
1580
1678
  get stats() {
1581
1679
  return this.statsTracker.stats;
@@ -1598,7 +1696,7 @@ const gt = 5e3, pt = 3e4, Y = 1e4, le = class le {
1598
1696
  */
1599
1697
  connect(e, t) {
1600
1698
  return new Promise(async (s, n) => {
1601
- var D, N;
1699
+ var D, x;
1602
1700
  t != null && t.resume || (this.lastSeq = -1);
1603
1701
  const r = (D = this.getToken) == null ? void 0 : D.call(this), o = [];
1604
1702
  r && o.push(`access_token=${encodeURIComponent(r)}`), e && this.lastSeq >= 0 && o.push(`lastSeq=${this.lastSeq}`), e && (t != null && t.resume) && t.openInteractionId && o.push(`openInteraction=${encodeURIComponent(t.openInteractionId)}`);
@@ -1623,7 +1721,7 @@ const gt = 5e3, pt = 3e4, Y = 1e4, le = class le {
1623
1721
  };
1624
1722
  const g = 200, m = 3e4, u = 8e3, p = this.ws;
1625
1723
  this.sessionId = void 0;
1626
- let w = 0, C = 0;
1724
+ let S = 0, C = 0;
1627
1725
  for (; ; ) {
1628
1726
  if (this.ws !== p) {
1629
1727
  n("Connection attempt superseded by a newer connect()");
@@ -1634,7 +1732,7 @@ const gt = 5e3, pt = 3e4, Y = 1e4, le = class le {
1634
1732
  n("Connection closed before a session id was received");
1635
1733
  return;
1636
1734
  }
1637
- if (p.readyState === WebSocket.CONNECTING && w >= m) {
1735
+ if (p.readyState === WebSocket.CONNECTING && S >= m) {
1638
1736
  try {
1639
1737
  p.close();
1640
1738
  } catch {
@@ -1646,9 +1744,9 @@ const gt = 5e3, pt = 3e4, Y = 1e4, le = class le {
1646
1744
  n(`Connected but no session id arrived within ${u / 1e3}s`);
1647
1745
  return;
1648
1746
  }
1649
- w % 2e3 === 0 && console.log("Aguardando session Id"), await this.sleep(g), w += g, p.readyState === WebSocket.OPEN && (C += g);
1747
+ S % 2e3 === 0 && console.log("Aguardando session Id"), await this.sleep(g), S += g, p.readyState === WebSocket.OPEN && (C += g);
1650
1748
  }
1651
- console.log(`[WebSocket] Session ${this.sessionId} proven${this.lastSeq >= 0 ? ` (replaying from lastSeq=${this.lastSeq})` : ""}.`), this.lastKnownSessionId = this.sessionId, (N = this.onOpen) == null || N.call(this), this.flushPendingAnswers(this.sessionId), s(this.sessionId);
1749
+ console.log(`[WebSocket] Session ${this.sessionId} proven${this.lastSeq >= 0 ? ` (replaying from lastSeq=${this.lastSeq})` : ""}.`), this.lastKnownSessionId = this.sessionId, (x = this.onOpen) == null || x.call(this), this.flushPendingAnswers(this.sessionId), s(this.sessionId);
1652
1750
  });
1653
1751
  }
1654
1752
  /** Drop the current socket without reporting it: handlers off, then close. */
@@ -1688,7 +1786,7 @@ const gt = 5e3, pt = 3e4, Y = 1e4, le = class le {
1688
1786
  case "Event":
1689
1787
  break;
1690
1788
  case "InteractionStarted": {
1691
- const r = Re(e);
1789
+ const r = Pe(e);
1692
1790
  r ? (n = this.onInteractionStarted) == null || n.call(this, r) : console.warn("[WebSocket] InteractionStarted frame without an interaction id");
1693
1791
  break;
1694
1792
  }
@@ -1700,8 +1798,8 @@ const gt = 5e3, pt = 3e4, Y = 1e4, le = class le {
1700
1798
  default:
1701
1799
  console.warn("[WebSocket] Unknown message type:", e.type);
1702
1800
  }
1703
- const s = se(e);
1704
- return s ? ($e(s) && this.emitFirstToken(s.interactionId), this.handleEvent(s, t), s) : null;
1801
+ const s = ie(e);
1802
+ return s ? (Le(s) && this.emitFirstToken(s.interactionId), this.handleEvent(s, t), s) : null;
1705
1803
  }
1706
1804
  emitFirstToken(e) {
1707
1805
  var t;
@@ -1820,21 +1918,21 @@ const gt = 5e3, pt = 3e4, Y = 1e4, le = class le {
1820
1918
  const e = Date.now();
1821
1919
  if (this.pingSentAt !== null) {
1822
1920
  const t = e - this.pingSentAt;
1823
- if (t >= Y) {
1921
+ if (t >= X) {
1824
1922
  this.failSocket(
1825
- nt,
1923
+ ot,
1826
1924
  `No frame received for ${Math.round(t / 1e3)}s after a Ping`
1827
1925
  );
1828
1926
  return;
1829
1927
  }
1830
- console.warn(`[WebSocket] Still no reply ${t}ms after the Ping (budget ${Y}ms, session ${this.sessionLabel}) — the peer may be gone.`);
1928
+ console.warn(`[WebSocket] Still no reply ${t}ms after the Ping (budget ${X}ms, session ${this.sessionLabel}) — the peer may be gone.`);
1831
1929
  return;
1832
1930
  }
1833
- e - this.lastActivity >= pt && this.ping();
1931
+ e - this.lastActivity >= Tt && this.ping();
1834
1932
  } catch (e) {
1835
1933
  console.error("Error on monitor", e);
1836
1934
  }
1837
- }, gt);
1935
+ }, It);
1838
1936
  }
1839
1937
  /**
1840
1938
  * Send a heartbeat ping and start the reply clock (unless one is already running).
@@ -1845,7 +1943,7 @@ const gt = 5e3, pt = 3e4, Y = 1e4, le = class le {
1845
1943
  AgentId: "",
1846
1944
  InteractionId: "",
1847
1945
  ModelId: ""
1848
- }), this.pingSentAt === null && (this.pingSentAt = Date.now(), console.log(`[WebSocket] Ping sent after ${Date.now() - this.lastActivity}ms of silence (session ${this.sessionLabel}); any frame within ${Y}ms answers it.`));
1946
+ }), this.pingSentAt === null && (this.pingSentAt = Date.now(), console.log(`[WebSocket] Ping sent after ${Date.now() - this.lastActivity}ms of silence (session ${this.sessionLabel}); any frame within ${X}ms answers it.`));
1849
1947
  }
1850
1948
  /**
1851
1949
  * Behave as if the peer vanished: the socket is closed and reported as an abnormal close (1006),
@@ -1880,7 +1978,7 @@ const gt = 5e3, pt = 3e4, Y = 1e4, le = class le {
1880
1978
  * Disconnect the WebSocket
1881
1979
  */
1882
1980
  disconnect() {
1883
- console.log(`[WebSocket] disconnect() (session ${this.sessionLabel})`), this.monitorInterval && (clearInterval(this.monitorInterval), this.monitorInterval = null), this.pingSentAt = null, this.firstTokenInteractions.clear(), this.lastKnownSessionId = void 0, this.lastSeq = -1, this.ws && (this.ws.close(ke, "Intentional disconnect"), this.ws = null);
1981
+ console.log(`[WebSocket] disconnect() (session ${this.sessionLabel})`), this.monitorInterval && (clearInterval(this.monitorInterval), this.monitorInterval = null), this.pingSentAt = null, this.firstTokenInteractions.clear(), this.lastKnownSessionId = void 0, this.lastSeq = -1, this.ws && (this.ws.close(Re, "Intentional disconnect"), this.ws = null);
1884
1982
  }
1885
1983
  /**
1886
1984
  * Check if connected
@@ -1890,7 +1988,7 @@ const gt = 5e3, pt = 3e4, Y = 1e4, le = class le {
1890
1988
  }
1891
1989
  async handleEvent(e, t) {
1892
1990
  var n, r, o, c;
1893
- const s = (r = (n = e.content) == null ? void 0 : n.items) == null ? void 0 : r.find((l) => l instanceof qe);
1991
+ const s = (r = (n = e.content) == null ? void 0 : n.items) == null ? void 0 : r.find((l) => l instanceof We);
1894
1992
  if (s) {
1895
1993
  (o = this.onBillingLimit) == null || o.call(this, {
1896
1994
  plan: s.plan ?? "team",
@@ -1907,7 +2005,7 @@ const gt = 5e3, pt = 3e4, Y = 1e4, le = class le {
1907
2005
  return;
1908
2006
  }
1909
2007
  try {
1910
- const l = q.parseFromTypedEvent(e);
2008
+ const l = U.parseFromTypedEvent(e);
1911
2009
  if (!l)
1912
2010
  throw "Server event was null";
1913
2011
  this.statsTracker.record({
@@ -1923,9 +2021,9 @@ const gt = 5e3, pt = 3e4, Y = 1e4, le = class le {
1923
2021
  }
1924
2022
  }
1925
2023
  };
1926
- h(le, "WebSocketConnecionV2");
1927
- let Me = le;
1928
- const he = class he {
2024
+ h(ue, "WebSocketConnecionV2");
2025
+ let ke = ue;
2026
+ const de = class de {
1929
2027
  constructor(e, t) {
1930
2028
  a(this, "cache", /* @__PURE__ */ new Map());
1931
2029
  a(this, "serverBaseUrl");
@@ -1933,7 +2031,7 @@ const he = class he {
1933
2031
  this.serverBaseUrl = e.replace(/\/$/, ""), this.accessToken = t;
1934
2032
  }
1935
2033
  get headers() {
1936
- return { Authorization: `Bearer ${ze(this.accessToken)}` };
2034
+ return { Authorization: `Bearer ${je(this.accessToken)}` };
1937
2035
  }
1938
2036
  async init() {
1939
2037
  }
@@ -1980,24 +2078,24 @@ const he = class he {
1980
2078
  }
1981
2079
  }
1982
2080
  };
1983
- h(he, "HttpArtifactService");
1984
- let Ce = he;
1985
- const ue = class ue extends Error {
2081
+ h(de, "HttpArtifactService");
2082
+ let Oe = de;
2083
+ const fe = class fe extends Error {
1986
2084
  constructor(e, t) {
1987
2085
  super(t ?? `GET detached-run frames answered ${e}`), this.status = e, this.name = "DetachedRunFramesHttpError";
1988
2086
  }
1989
2087
  };
1990
- h(ue, "DetachedRunFramesHttpError");
1991
- let P = ue;
1992
- function mt(i) {
2088
+ h(fe, "DetachedRunFramesHttpError");
2089
+ let P = fe;
2090
+ function yt(i) {
1993
2091
  if (i instanceof P) {
1994
2092
  const { status: e } = i;
1995
2093
  return { kind: e === 401 ? "unauthorized" : e === 403 ? "forbidden" : e === 404 || e === 410 ? "notFound" : "gaveUp", status: e, cause: i };
1996
2094
  }
1997
2095
  return { kind: "gaveUp", cause: i };
1998
2096
  }
1999
- h(mt, "toDetachedRunFollowError");
2000
- function wt(i) {
2097
+ h(yt, "toDetachedRunFollowError");
2098
+ function vt(i) {
2001
2099
  let e = "", t = [], s, n;
2002
2100
  const r = /* @__PURE__ */ h(() => {
2003
2101
  (t.length > 0 || s !== void 0) && i({ event: s, data: t.join(`
@@ -2028,12 +2126,12 @@ function wt(i) {
2028
2126
  }
2029
2127
  };
2030
2128
  }
2031
- h(wt, "createSseParser");
2032
- function St(i) {
2129
+ h(vt, "createSseParser");
2130
+ function Et(i) {
2033
2131
  return i >= 500 || i === 408 || i === 429;
2034
2132
  }
2035
- h(St, "retryable");
2036
- function It(i, e) {
2133
+ h(Et, "retryable");
2134
+ function Mt(i, e) {
2037
2135
  return new Promise((t) => {
2038
2136
  if (e != null && e.aborted) return t();
2039
2137
  const s = setTimeout(n, i);
@@ -2043,22 +2141,22 @@ function It(i, e) {
2043
2141
  h(n, "done"), e == null || e.addEventListener("abort", n, { once: !0 });
2044
2142
  });
2045
2143
  }
2046
- h(It, "sleep");
2047
- function Tt(i, e, t, s) {
2144
+ h(Mt, "sleep");
2145
+ function Ct(i, e, t, s) {
2048
2146
  const n = e === "session" ? "sessions" : "detached-runs";
2049
2147
  return `${i.replace(/\/+$/, "")}/${n}/${encodeURIComponent(t)}/frames?afterSeq=${s}`;
2050
2148
  }
2051
- h(Tt, "framesUrl");
2052
- async function yt(i) {
2053
- var N, v, M, fe, ge;
2054
- const { baseUrl: e, runId: t, signal: s, onFrame: n, onEnd: r, onOpen: o, onRetry: c } = i, l = i.resource ?? "detachedRun", f = i.fetchImpl ?? ((A, $) => fetch(A, $)), g = ((N = i.retry) == null ? void 0 : N.initialMs) ?? 500, m = ((v = i.retry) == null ? void 0 : v.maxMs) ?? 15e3, u = ((M = i.retry) == null ? void 0 : M.maxAttempts) ?? Number.POSITIVE_INFINITY;
2055
- let p = i.afterSeq ?? 0, w = 0, C = !1;
2149
+ h(Ct, "framesUrl");
2150
+ async function At(i) {
2151
+ var x, v, M, pe, me;
2152
+ const { baseUrl: e, runId: t, signal: s, onFrame: n, onEnd: r, onOpen: o, onRetry: c } = i, l = i.resource ?? "detachedRun", f = i.fetchImpl ?? ((A, $) => fetch(A, $)), g = ((x = i.retry) == null ? void 0 : x.initialMs) ?? 500, m = ((v = i.retry) == null ? void 0 : v.maxMs) ?? 15e3, u = ((M = i.retry) == null ? void 0 : M.maxAttempts) ?? Number.POSITIVE_INFINITY;
2153
+ let p = i.afterSeq ?? 0, S = 0, C = !1;
2056
2154
  async function D(A) {
2057
2155
  if (i.onUnauthorized)
2058
2156
  try {
2059
2157
  if (await i.onUnauthorized()) return !0;
2060
- } catch (O) {
2061
- console.warn(`[DetachedRunFrames] run ${t}: onUnauthorized threw`, O);
2158
+ } catch (k) {
2159
+ console.warn(`[DetachedRunFrames] run ${t}: onUnauthorized threw`, k);
2062
2160
  }
2063
2161
  if (!i.getToken) return !1;
2064
2162
  const $ = await i.getToken() ?? void 0;
@@ -2067,25 +2165,25 @@ async function yt(i) {
2067
2165
  for (h(D, "secondChance"); !(s != null && s.aborted); ) {
2068
2166
  let A;
2069
2167
  try {
2070
- const O = { Accept: "text/event-stream" }, J = await ((fe = i.getToken) == null ? void 0 : fe.call(i)) ?? void 0;
2071
- J && (O.Authorization = `Bearer ${J}`);
2072
- const k = await f(Tt(e, l, t, p), { method: "GET", headers: O, signal: s, cache: "no-store" });
2073
- if (k.status === 401) {
2168
+ const k = { Accept: "text/event-stream" }, J = await ((pe = i.getToken) == null ? void 0 : pe.call(i)) ?? void 0;
2169
+ J && (k.Authorization = `Bearer ${J}`);
2170
+ const O = await f(Ct(e, l, t, p), { method: "GET", headers: k, signal: s, cache: "no-store" });
2171
+ if (O.status === 401) {
2074
2172
  if (!C && await D(J)) {
2075
2173
  C = !0;
2076
2174
  continue;
2077
2175
  }
2078
2176
  throw new P(401);
2079
2177
  }
2080
- if (C = !1, !k.ok)
2081
- throw St(k.status) ? new Error(`GET detached-run frames answered ${k.status}`) : new P(k.status);
2082
- if (!k.body) throw new P(k.status, "The frames response has no readable body");
2178
+ if (C = !1, !O.ok)
2179
+ throw Et(O.status) ? new Error(`GET detached-run frames answered ${O.status}`) : new P(O.status);
2180
+ if (!O.body) throw new P(O.status, "The frames response has no readable body");
2083
2181
  o == null || o();
2084
- let W = !1;
2085
- const B = wt((T) => {
2182
+ let B = !1;
2183
+ const W = vt((T) => {
2086
2184
  if (T.event === "end") {
2087
2185
  const b = Number(T.data);
2088
- T.data !== "" && Number.isFinite(b) && b > p && (p = b), W = !0;
2186
+ T.data !== "" && Number.isFinite(b) && b > p && (p = b), B = !0;
2089
2187
  return;
2090
2188
  }
2091
2189
  if (T.event !== void 0 && T.event !== "message" || T.data === "") return;
@@ -2094,51 +2192,51 @@ async function yt(i) {
2094
2192
  if (R <= p) return;
2095
2193
  p = R;
2096
2194
  }
2097
- W = !1;
2098
- let me;
2195
+ B = !1;
2196
+ let Se;
2099
2197
  try {
2100
- me = JSON.parse(T.data);
2198
+ Se = JSON.parse(T.data);
2101
2199
  } catch (b) {
2102
2200
  console.warn(`[DetachedRunFrames] run ${t}: a frame that is not JSON was skipped (seq ${T.id ?? "?"})`, b);
2103
2201
  return;
2104
2202
  }
2105
- w = 0;
2203
+ S = 0;
2106
2204
  try {
2107
- n(me, R);
2205
+ n(Se, R);
2108
2206
  } catch (b) {
2109
2207
  console.error(`[DetachedRunFrames] run ${t}: onFrame threw on seq ${T.id ?? "?"}`, b);
2110
2208
  }
2111
- }), G = k.body.getReader(), pe = new TextDecoder();
2209
+ }), G = O.body.getReader(), we = new TextDecoder();
2112
2210
  try {
2113
2211
  for (; ; ) {
2114
2212
  const { done: T, value: R } = await G.read();
2115
2213
  if (T) break;
2116
- B.push(pe.decode(R, { stream: !0 }));
2214
+ W.push(we.decode(R, { stream: !0 }));
2117
2215
  }
2118
- B.push(pe.decode()), B.idle() || (W = !1), B.flush();
2216
+ W.push(we.decode()), W.idle() || (B = !1), W.flush();
2119
2217
  } finally {
2120
- (ge = G.releaseLock) == null || ge.call(G);
2218
+ (me = G.releaseLock) == null || me.call(G);
2121
2219
  }
2122
- if (W && l !== "session")
2220
+ if (B && l !== "session")
2123
2221
  return r == null || r(p), { reason: "end", lastSeq: p };
2124
2222
  A = new Error(l === "session" ? "The session frames stream closed" : "The frames stream closed before its end event");
2125
- } catch (O) {
2223
+ } catch (k) {
2126
2224
  if (s != null && s.aborted) break;
2127
- if (O instanceof P) throw O;
2128
- A = O;
2225
+ if (k instanceof P) throw k;
2226
+ A = k;
2129
2227
  }
2130
- if (w += 1, w >= u) throw A;
2131
- const $ = Math.min(g * 2 ** (w - 1), m);
2228
+ if (S += 1, S >= u) throw A;
2229
+ const $ = Math.min(g * 2 ** (S - 1), m);
2132
2230
  try {
2133
- c == null || c(A, w, $);
2231
+ c == null || c(A, S, $);
2134
2232
  } catch {
2135
2233
  }
2136
- await It($, s);
2234
+ await Mt($, s);
2137
2235
  }
2138
2236
  return { reason: "aborted", lastSeq: p };
2139
2237
  }
2140
- h(yt, "streamDetachedRunFrames");
2141
- const de = class de {
2238
+ h(At, "streamDetachedRunFrames");
2239
+ const ge = class ge {
2142
2240
  constructor(e) {
2143
2241
  a(this, "onEvent");
2144
2242
  a(this, "onError");
@@ -2153,7 +2251,7 @@ const de = class de {
2153
2251
  /** Following stopped for good — the run is gone, forbidden, the credentials failed twice, or retries ran out. */
2154
2252
  a(this, "onFollowError");
2155
2253
  a(this, "options");
2156
- a(this, "serializer", te());
2254
+ a(this, "serializer", ne());
2157
2255
  a(this, "firstTokens", /* @__PURE__ */ new Set());
2158
2256
  a(this, "runId");
2159
2257
  a(this, "controller", null);
@@ -2186,7 +2284,7 @@ const de = class de {
2186
2284
  const t = new AbortController();
2187
2285
  return this.controller = t, this.following = !0, new Promise((n, r) => {
2188
2286
  let o = !1;
2189
- yt({
2287
+ At({
2190
2288
  ...this.options,
2191
2289
  runId: e,
2192
2290
  afterSeq: this.lastSeq,
@@ -2209,7 +2307,7 @@ const de = class de {
2209
2307
  o || r(new Error("The frames stream stopped before it opened"));
2210
2308
  }).catch((c) => {
2211
2309
  var g, m, u;
2212
- const l = mt(c), f = l.kind === "notFound" ? De : l.kind === "forbidden" || l.kind === "unauthorized" ? 1008 : 1011;
2310
+ const l = yt(c), f = l.kind === "notFound" ? be : l.kind === "forbidden" || l.kind === "unauthorized" ? 1008 : 1011;
2213
2311
  console.error(`[DetachedRunFrames] run ${e}: following stopped (${l.kind})`, c);
2214
2312
  try {
2215
2313
  (g = this.onFollowError) == null || g.call(this, l);
@@ -2233,16 +2331,16 @@ const de = class de {
2233
2331
  return;
2234
2332
  }
2235
2333
  if (!t) return;
2236
- const s = Re(t);
2334
+ const s = Pe(t);
2237
2335
  if (s) {
2238
2336
  (r = this.onInteractionStarted) == null || r.call(this, s);
2239
2337
  return;
2240
2338
  }
2241
- const n = se(t);
2339
+ const n = ie(t);
2242
2340
  if (n) {
2243
- $e(n) && n.interactionId && !this.firstTokens.has(n.interactionId) && (this.firstTokens.add(n.interactionId), (o = this.onFirstToken) == null || o.call(this, n.interactionId));
2341
+ Le(n) && n.interactionId && !this.firstTokens.has(n.interactionId) && (this.firstTokens.add(n.interactionId), (o = this.onFirstToken) == null || o.call(this, n.interactionId));
2244
2342
  try {
2245
- const l = q.parseFromTypedEvent(n);
2343
+ const l = U.parseFromTypedEvent(n);
2246
2344
  (c = this.onEvent) == null || c.call(this, l).catch((f) => console.error("[DetachedRunFrames] onEvent failed", f));
2247
2345
  } catch (l) {
2248
2346
  console.error("[DetachedRunFrames] a frame could not be mapped to a server event", l);
@@ -2262,29 +2360,29 @@ const de = class de {
2262
2360
  return this.controller !== null;
2263
2361
  }
2264
2362
  };
2265
- h(de, "DetachedRunFramesTransport");
2266
- let Ae = de;
2267
- const vt = "todolistUpdated";
2268
- function bt(i, e = te()) {
2363
+ h(ge, "DetachedRunFramesTransport");
2364
+ let De = ge;
2365
+ const kt = "todolistUpdated";
2366
+ function Nt(i, e = ne()) {
2269
2367
  var n, r;
2270
2368
  let t;
2271
2369
  try {
2272
- const o = e.parse(i), c = o ? se(o) : void 0;
2273
- t = c ? q.parseFromTypedEvent(c) : void 0;
2370
+ const o = e.parse(i), c = o ? ie(o) : void 0;
2371
+ t = c ? U.parseFromTypedEvent(c) : void 0;
2274
2372
  } catch {
2275
2373
  return [];
2276
2374
  }
2277
2375
  if (!t) return [];
2278
2376
  const s = [];
2279
2377
  for (const o of t.parts ?? [])
2280
- if (o.eventType === I.ToolEvent && ((n = o.toolDetails) == null ? void 0 : n.eventName) === vt) {
2281
- const c = Et(o.toolDetails.eventData);
2378
+ if (o.eventType === I.ToolEvent && ((n = o.toolDetails) == null ? void 0 : n.eventName) === kt) {
2379
+ const c = Ot(o.toolDetails.eventData);
2282
2380
  c && s.push({ kind: "todo", todoList: c });
2283
2381
  } else (o.eventType === I.FunctionCall || o.eventType === I.PartialFunctionCall) && ((r = o.functionDetails) != null && r.name) ? s.push({ kind: "tool", name: o.functionDetails.name, interactionId: t.interactionId }) : o.eventType === I.Text && o.text && s.push({ kind: "text", text: o.text, partial: !!t.partial, interactionId: t.interactionId });
2284
2382
  return s;
2285
2383
  }
2286
- h(bt, "readDetachedRunActivity");
2287
- function Et(i) {
2384
+ h(Nt, "readDetachedRunActivity");
2385
+ function Ot(i) {
2288
2386
  if (!i) return null;
2289
2387
  try {
2290
2388
  const e = JSON.parse(i);
@@ -2293,26 +2391,26 @@ function Et(i) {
2293
2391
  return null;
2294
2392
  }
2295
2393
  }
2296
- h(Et, "parseTodoList");
2394
+ h(Ot, "parseTodoList");
2297
2395
  export {
2298
- ye as A,
2299
- V as C,
2396
+ Me as A,
2397
+ ee as C,
2300
2398
  P as D,
2301
- Te as E,
2302
- Ce as H,
2303
- _ as I,
2304
- Ie as L,
2305
- Qe as M,
2306
- vt as T,
2307
- at as W,
2308
- Ae as a,
2399
+ ve as E,
2400
+ Oe as H,
2401
+ N as I,
2402
+ ye as L,
2403
+ Z as M,
2404
+ kt as T,
2405
+ ht as W,
2406
+ De as a,
2309
2407
  j as b,
2310
- Me as c,
2311
- wt as d,
2312
- tt as e,
2313
- bt as r,
2314
- yt as s,
2315
- mt as t,
2316
- Rt as u
2408
+ ke as c,
2409
+ vt as d,
2410
+ it as e,
2411
+ Nt as r,
2412
+ At as s,
2413
+ yt as t,
2414
+ xt as u
2317
2415
  };
2318
- //# sourceMappingURL=detachedRunActivity-C_TBbcmB.js.map
2416
+ //# sourceMappingURL=detachedRunActivity-Cf-RPK9j.js.map