@aintela/chat 0.4.5 → 0.4.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,23 +1,23 @@
1
- var it = Object.defineProperty;
2
- var mt = (w, t, e) => t in w ? it(w, t, { enumerable: !0, configurable: !0, writable: !0, value: e }) : w[t] = e;
3
- var f = (w, t) => it(w, "name", { value: t, configurable: !0 });
4
- var i = (w, t, e) => mt(w, typeof t != "symbol" ? t + "" : t, e);
5
- import { i as St, a as wt, d as Tt } from "./environmentUtils-VZNTCzEE.js";
6
- import { I as N, E as y, j as yt, S as ft, q as Ct, L as It, P as L, l as vt, o as Et, T as Mt, m as Dt, C as U } from "./serializer-CdUT_OO2.js";
7
- import { unified as Ot } from "unified";
1
+ var at = Object.defineProperty;
2
+ var St = (w, t, e) => t in w ? at(w, t, { enumerable: !0, configurable: !0, writable: !0, value: e }) : w[t] = e;
3
+ var f = (w, t) => at(w, "name", { value: t, configurable: !0 });
4
+ var i = (w, t, e) => St(w, typeof t != "symbol" ? t + "" : t, e);
5
+ import { i as wt, a as yt, d as Tt } from "./environmentUtils-VZNTCzEE.js";
6
+ import { I as _, E as C, j as Ct, S as gt, q as It, L as vt, P as U, l as Et, o as Mt, T as Dt, m as Ot, C as F } from "./serializer-CdUT_OO2.js";
7
+ import { unified as At } from "unified";
8
8
  import kt from "remark-parse";
9
- import { toMarkdown as At } from "mdast-util-to-markdown";
10
- import { format as Pt } from "date-fns";
11
- import Nt from "lodash";
12
- import { P as _t, C as F } from "./Prompt-DZb7OaPp.js";
13
- import { r as bt } from "./httpSessionService-BnNVSRID.js";
9
+ import { toMarkdown as Pt } from "mdast-util-to-markdown";
10
+ import { format as Nt } from "date-fns";
11
+ import _t from "lodash";
12
+ import { P as bt, C as k } from "./Prompt-DZb7OaPp.js";
13
+ import { r as Rt } from "./httpSessionService-BnNVSRID.js";
14
14
  const W = {
15
15
  PROMPTS: "envision-prompts"
16
- }, Rt = 50, z = class z {
16
+ }, Lt = 50, J = class J {
17
17
  getPrompts() {
18
18
  try {
19
19
  const t = localStorage.getItem(W.PROMPTS);
20
- return t ? JSON.parse(t).sort((s, a) => new Date(a.created).getTime() - new Date(s.created).getTime()) : [];
20
+ return t ? JSON.parse(t).sort((s, o) => new Date(o.created).getTime() - new Date(s.created).getTime()) : [];
21
21
  } catch (t) {
22
22
  return console.error("Error loading prompts:", t), [];
23
23
  }
@@ -43,7 +43,7 @@ const W = {
43
43
  storePrompt(t) {
44
44
  try {
45
45
  const e = this.getPrompts().filter((s) => s.promptText !== t.promptText);
46
- e.unshift(t), localStorage.setItem(W.PROMPTS, JSON.stringify(e.slice(0, Rt)));
46
+ e.unshift(t), localStorage.setItem(W.PROMPTS, JSON.stringify(e.slice(0, Lt)));
47
47
  } catch (e) {
48
48
  console.error("Error storing prompt:", e);
49
49
  }
@@ -56,16 +56,16 @@ const W = {
56
56
  }
57
57
  }
58
58
  };
59
- f(z, "LocalStorageService");
60
- let at = z;
61
- const ne = /* @__PURE__ */ f((w) => {
59
+ f(J, "LocalStorageService");
60
+ let rt = J;
61
+ const re = /* @__PURE__ */ f((w) => {
62
62
  const t = w.getPrompts(), e = t.length;
63
63
  if (e > 0) {
64
- const s = t[0].promptText, a = t[t.length - 1].promptText, n = t[0].created;
65
- return { promptState: e + "_" + s + "_" + a + "_" + n };
64
+ const s = t[0].promptText, o = t[t.length - 1].promptText, n = t[0].created;
65
+ return { promptState: e + "_" + s + "_" + o + "_" + n };
66
66
  } else
67
67
  return { promptState: "0" };
68
- }, "usePromptState"), K = class K {
68
+ }, "usePromptState"), X = class X {
69
69
  constructor() {
70
70
  i(this, "activityLost", "activityLost");
71
71
  i(this, "artifactGenerated", "artifactGenerated");
@@ -90,9 +90,9 @@ const ne = /* @__PURE__ */ f((w) => {
90
90
  i(this, "gatewayFirstToken", "gatewayFirstToken");
91
91
  }
92
92
  };
93
- f(K, "EventTypes");
94
- let $ = K;
95
- const c = new $(), J = class J {
93
+ f(X, "EventTypes");
94
+ let H = X;
95
+ const c = new H(), Y = class Y {
96
96
  constructor() {
97
97
  i(this, "listeners", {});
98
98
  i(this, "listenersCount", {});
@@ -100,8 +100,8 @@ const c = new $(), J = class J {
100
100
  callListeners(t, ...e) {
101
101
  const s = this.listeners[t];
102
102
  if (this.listenersCount[t] = this.listenersCount[t] + 1, s) {
103
- const a = s.map((n) => n(...e));
104
- Promise.all(a).catch((n) => {
103
+ const o = s.map((n) => n(...e));
104
+ Promise.all(o).catch((n) => {
105
105
  console.error(`Lost error in one of the listeners of the event: ${t}, listeners: ${s.length}, error: ${n}`, s);
106
106
  });
107
107
  }
@@ -343,9 +343,9 @@ const c = new $(), J = class J {
343
343
  this.listeners[e] && (this.listeners[e] = this.listeners[e].filter((s) => s !== t));
344
344
  }
345
345
  };
346
- f(J, "EventBusService");
347
- let q = J;
348
- const X = class X extends q {
346
+ f(Y, "EventBusService");
347
+ let K = Y;
348
+ const j = class j extends K {
349
349
  constructor() {
350
350
  super();
351
351
  }
@@ -353,7 +353,7 @@ const X = class X extends q {
353
353
  console.log("MockEventBusService.gatewayEmitConnectionStateChange");
354
354
  }
355
355
  gatewayEmitMessage(t, e) {
356
- St() ? process.stdout.write(`M${t.version}, `) : console.log("MockEventBusService.gatewayEmitMessage");
356
+ wt() ? process.stdout.write(`M${t.version}, `) : console.log("MockEventBusService.gatewayEmitMessage");
357
357
  }
358
358
  gatewayEmitTurnComplete(t, e) {
359
359
  console.log("MockEventBusService.gatewayEmitTurnComplete");
@@ -371,12 +371,12 @@ const X = class X extends q {
371
371
  console.log("MockEventBusService.gatewayOffFunctionResponse", t);
372
372
  }
373
373
  };
374
- f(X, "MockEventBusService");
375
- let ot = X;
376
- const Ft = 2e3, gt = {
374
+ f(j, "MockEventBusService");
375
+ let ct = j;
376
+ const Ut = 2e3, mt = {
377
377
  inline: "inline",
378
378
  block: "block"
379
- }, Y = class Y {
379
+ }, Q = class Q {
380
380
  constructor() {
381
381
  i(this, "parts", []);
382
382
  i(this, "isLastGroup", !1);
@@ -393,74 +393,74 @@ const Ft = 2e3, gt = {
393
393
  * which is where the CPU saving actually comes from.
394
394
  */
395
395
  i(this, "isThoughtRun", !1);
396
- i(this, "type", gt.inline);
396
+ i(this, "type", mt.inline);
397
397
  }
398
398
  };
399
- f(Y, "InteractionPartGroup");
400
- let x = Y;
401
- const j = class j {
399
+ f(Q, "InteractionPartGroup");
400
+ let $ = Q;
401
+ const Z = class Z {
402
402
  constructor(t, e) {
403
403
  i(this, "interaction");
404
404
  i(this, "eventBusService");
405
405
  i(this, "parseTextIntoParts", /* @__PURE__ */ f((t) => {
406
406
  if (!t || t.trim().length == 0) return [];
407
- const e = Ot().use(kt).parse(t), s = [];
408
- let a = null;
407
+ const e = At().use(kt).parse(t), s = [];
408
+ let o = null;
409
409
  for (const n of e.children)
410
- n.type === "code" ? (a && (s.push(a), a = null), n.lang === "htmlCanvas" && s.push(`
410
+ n.type === "code" ? (o && (s.push(o), o = null), n.lang === "htmlCanvas" && s.push(`
411
411
  \`\`\`liveTsx
412
412
  ${n.value}
413
413
  \`\`\`
414
- `)) : (a || (a = ""), a += At(n));
415
- return a && s.push(a), s;
414
+ `)) : (o || (o = ""), o += Pt(n));
415
+ return o && s.push(o), s;
416
416
  }, "parseTextIntoParts"));
417
417
  this.interaction = t, this.eventBusService = e;
418
418
  }
419
419
  expandSubParts(t, e) {
420
- const s = this.parseTextIntoParts(t), a = [];
420
+ const s = this.parseTextIntoParts(t), o = [];
421
421
  let n = 0;
422
- for (const o of s) {
423
- const l = N.fromText(o);
424
- l.id = n + "_" + e, a.push(l), n++;
422
+ for (const a of s) {
423
+ const l = _.fromText(a);
424
+ l.id = n + "_" + e, o.push(l), n++;
425
425
  }
426
- return a;
426
+ return o;
427
427
  }
428
428
  groupPartsByDisplayType(t, e = !0, s = !1) {
429
429
  var l, r, d;
430
- const a = [];
431
- let n = new x();
430
+ const o = [];
431
+ let n = new $();
432
432
  for (let u = 0; u < t.length; u++) {
433
433
  const h = t[u];
434
- let p = !((((l = h.functionDetails) == null ? void 0 : l.isUi) ?? !1) || ((r = h.functionDetails) == null ? void 0 : r.cancelUi) !== !0 && (((d = h.functionDetails) == null ? void 0 : d.isAskUser) ?? !1)) && h.eventType !== y.Text && h.eventType !== y.Thought && (h.eventType === y.FunctionCall || h.eventType === y.PartialFunctionCall || h.eventType === y.FunctionResponse) && u < t.length - 1;
435
- if (!(!e && p && !s))
436
- if (p)
437
- h.eventType == y.Thought && (n.hasThoughts = !0), n.parts.push(h), n.isLastGroup = u === t.length - 1;
434
+ let m = !((((l = h.functionDetails) == null ? void 0 : l.isUi) ?? !1) || ((r = h.functionDetails) == null ? void 0 : r.cancelUi) !== !0 && (((d = h.functionDetails) == null ? void 0 : d.isAskUser) ?? !1)) && h.eventType !== C.Text && h.eventType !== C.Thought && (h.eventType === C.FunctionCall || h.eventType === C.PartialFunctionCall || h.eventType === C.FunctionResponse) && u < t.length - 1;
435
+ if (!(!e && m && !s))
436
+ if (m)
437
+ h.eventType == C.Thought && (n.hasThoughts = !0), n.parts.push(h), n.isLastGroup = u === t.length - 1;
438
438
  else {
439
- n.parts.length > 0 && (a.push(n), n = new x());
440
- const D = h.eventType === y.Thought, T = a[a.length - 1];
441
- if (D && (T != null && T.isThoughtRun)) {
439
+ n.parts.length > 0 && (o.push(n), n = new $());
440
+ const M = h.eventType === C.Thought, T = o[o.length - 1];
441
+ if (M && (T != null && T.isThoughtRun)) {
442
442
  T.parts.push(h), T.isLastGroup = u === t.length - 1;
443
443
  continue;
444
444
  }
445
- a.push({
446
- type: gt.block,
445
+ o.push({
446
+ type: mt.block,
447
447
  parts: [h],
448
448
  isLastGroup: u === t.length - 1,
449
449
  hasThoughts: !1,
450
450
  lastWithThoughts: !1,
451
- isThoughtRun: D
451
+ isThoughtRun: M
452
452
  });
453
453
  }
454
454
  }
455
- n.parts.length > 0 && a.push(n);
456
- const o = a.filter((u) => u.hasThoughts);
457
- return o.length > 0 && (o[o.length - 1].lastWithThoughts = !0), a;
455
+ n.parts.length > 0 && o.push(n);
456
+ const a = o.filter((u) => u.hasThoughts);
457
+ return a.length > 0 && (a[a.length - 1].lastWithThoughts = !0), o;
458
458
  }
459
459
  isFunctionCall(t) {
460
- return t == y.FunctionCall || t == y.PartialFunctionCall;
460
+ return t == C.FunctionCall || t == C.PartialFunctionCall;
461
461
  }
462
462
  isFunctionResponse(t) {
463
- return t == y.FunctionResponse;
463
+ return t == C.FunctionResponse;
464
464
  }
465
465
  // Computes the next interaction from a server event. Pure with respect to
466
466
  // `prev` — no part or array on the prior tree is mutated; modified entities
@@ -468,10 +468,10 @@ ${n.value}
468
468
  // new tree as the last step, so snapshots already handed out to throttled
469
469
  // subscribers can't diverge from the live state.
470
470
  merge(t) {
471
- var _, b, C, O, A, tt, et, st;
472
- const e = this.interaction, s = [], a = [], n = N.FlatParts(t == null ? void 0 : t.parts), o = e.parts[e.parts.length - 1] ?? null;
471
+ var b, R, y, O, A, st, nt, it;
472
+ const e = this.interaction, s = [], o = [], n = _.FlatParts(t == null ? void 0 : t.parts), a = e.parts[e.parts.length - 1] ?? null;
473
473
  let l = !1;
474
- n && (l = !o || n.mustPush || n.mustPush === !1 && (n.eventType !== (o == null ? void 0 : o.eventType) || ((_ = n == null ? void 0 : n.functionDetails) == null ? void 0 : _.id) !== ((b = o.functionDetails) == null ? void 0 : b.id)));
474
+ n && (l = !a || n.mustPush || n.mustPush === !1 && (n.eventType !== (a == null ? void 0 : a.eventType) || ((b = n == null ? void 0 : n.functionDetails) == null ? void 0 : b.id) !== ((R = a.functionDetails) == null ? void 0 : R.id)));
475
475
  let r = e.parts, d = e.functionMap ?? /* @__PURE__ */ new Map(), u = !e.functionMap;
476
476
  const h = /* @__PURE__ */ f(() => {
477
477
  u || (d = new Map(d), u = !0);
@@ -480,16 +480,16 @@ ${n.value}
480
480
  }, "clonePartsIfShared");
481
481
  if (!l && (r == null ? void 0 : r.length) > 0 && (n != null && n.textAppendable)) {
482
482
  const g = r[r.length - 1];
483
- (((O = (C = g.thoughtDetails) == null ? void 0 : C.text) == null ? void 0 : O.length) ?? ((A = g.text) == null ? void 0 : A.length) ?? 0) > Ft && (l = !0);
483
+ (((O = (y = g.thoughtDetails) == null ? void 0 : y.text) == null ? void 0 : O.length) ?? ((A = g.text) == null ? void 0 : A.length) ?? 0) > Ut && (l = !0);
484
484
  }
485
- let p = !1;
486
- if ((n == null ? void 0 : n.eventType) === y.FunctionClientOutput && !!((tt = n.functionDetails) != null && tt.id) && n) {
487
- const g = n.functionDetails.id, I = n.functionDetails.clientOutput, M = r.findIndex((S) => {
488
- var m;
489
- return ((m = S.functionDetails) == null ? void 0 : m.id) === g;
485
+ let m = !1;
486
+ if ((n == null ? void 0 : n.eventType) === C.FunctionClientOutput && !!((st = n.functionDetails) != null && st.id) && n) {
487
+ const g = n.functionDetails.id, I = n.functionDetails.clientOutput, D = r.findIndex((S) => {
488
+ var p;
489
+ return ((p = S.functionDetails) == null ? void 0 : p.id) === g;
490
490
  });
491
- if (M > -1) {
492
- const S = r[M], m = {
491
+ if (D > -1) {
492
+ const S = r[D], p = {
493
493
  ...S,
494
494
  functionDetails: {
495
495
  ...S.functionDetails,
@@ -498,7 +498,7 @@ ${n.value}
498
498
  parked: n.functionDetails.parked === !0 || S.functionDetails.parked === !0
499
499
  }
500
500
  };
501
- v(), r[M] = m, h(), d.set(g, m), s.push(m);
501
+ v(), r[D] = p, h(), d.set(g, p), s.push(p);
502
502
  } else {
503
503
  const S = {
504
504
  ...n,
@@ -508,19 +508,19 @@ ${n.value}
508
508
  v(), r = r === e.parts ? e.parts.slice() : r, r.push(S), h(), d.set(g, S);
509
509
  }
510
510
  } else if (l && n) {
511
- const g = this.isFunctionCall(n.eventType) || this.isFunctionResponse(n.eventType), I = g ? (et = n.functionDetails) == null ? void 0 : et.id : void 0;
511
+ const g = this.isFunctionCall(n.eventType) || this.isFunctionResponse(n.eventType), I = g ? (nt = n.functionDetails) == null ? void 0 : nt.id : void 0;
512
512
  g && !I && console.error("Got isCall or isResponse without a callId", n);
513
- const M = I ? d.get(I) : void 0;
514
- if (M && I && n.functionDetails) {
513
+ const D = I ? d.get(I) : void 0;
514
+ if (D && I && n.functionDetails) {
515
515
  const S = r.findIndex((pt) => {
516
- var nt;
517
- return ((nt = pt.functionDetails) == null ? void 0 : nt.id) === I;
518
- }), m = S > -1 ? r[S] : M, R = {
519
- ...m,
516
+ var ot;
517
+ return ((ot = pt.functionDetails) == null ? void 0 : ot.id) === I;
518
+ }), p = S > -1 ? r[S] : D, L = {
519
+ ...p,
520
520
  eventType: n.eventType,
521
521
  functionDetails: {
522
- id: m.functionDetails.id,
523
- name: n.functionDetails.name ?? m.functionDetails.name,
522
+ id: p.functionDetails.id,
523
+ name: n.functionDetails.name ?? p.functionDetails.name,
524
524
  // Take the parsed args from the incoming event when
525
525
  // present (the full FunctionCall carries them), fall
526
526
  // back to what was already on the part. Previously
@@ -529,42 +529,42 @@ ${n.value}
529
529
  // args off every full FunctionCall fold because the
530
530
  // PartialFunctionCall stream only accumulates raw
531
531
  // JSON in `.text` — `.args` stayed undefined.
532
- args: n.functionDetails.args ?? m.functionDetails.args,
532
+ args: n.functionDetails.args ?? p.functionDetails.args,
533
533
  response: n.functionDetails.response,
534
534
  status: n.functionDetails.status ?? "Composing",
535
- start: n.functionDetails.start ?? m.functionDetails.start,
536
- end: n.functionDetails.end ?? m.functionDetails.end,
535
+ start: n.functionDetails.start ?? p.functionDetails.start,
536
+ end: n.functionDetails.end ?? p.functionDetails.end,
537
537
  // true-wins: a UI call has multiple reps (streaming part with isUi, the
538
538
  // persisted FunctionCall, the result) and they interleave. `??` let a later
539
539
  // `false`/`undefined` rep clobber an earlier `true`; OR-ing keeps it sticky.
540
- isUi: n.functionDetails.isUi === !0 || m.functionDetails.isUi === !0,
540
+ isUi: n.functionDetails.isUi === !0 || p.functionDetails.isUi === !0,
541
541
  // Keep the call's friendly args summary when the result event (which has none) folds in.
542
- argsDescription: n.functionDetails.argsDescription ?? m.functionDetails.argsDescription,
542
+ argsDescription: n.functionDetails.argsDescription ?? p.functionDetails.argsDescription,
543
543
  // The tool's client-only payload rides the RESULT event; keep it sticky so a
544
544
  // later rep without one can't clobber it. This is what a uiTool renderer reads.
545
- clientOutput: n.functionDetails.clientOutput ?? m.functionDetails.clientOutput,
545
+ clientOutput: n.functionDetails.clientOutput ?? p.functionDetails.clientOutput,
546
546
  // Ask-user component ([KernelUIComponent]) — sticky like isUi/clientOutput. The
547
547
  // streaming final CALL carries it, but the PartialFunctionCall it folds onto (and a
548
548
  // later result rep) may not; dropping it strips the part's askUser classification so
549
549
  // the docked drawer never surfaces (issue #60 — esp. a no-arg tool like update_profile,
550
550
  // which has no name match to fall back on the way ask_user/askauth do).
551
- askUserComponent: n.functionDetails.askUserComponent ?? m.functionDetails.askUserComponent,
552
- isAskUser: n.functionDetails.isAskUser || m.functionDetails.isAskUser || !!(n.functionDetails.askUserComponent ?? m.functionDetails.askUserComponent),
551
+ askUserComponent: n.functionDetails.askUserComponent ?? p.functionDetails.askUserComponent,
552
+ isAskUser: n.functionDetails.isAskUser || p.functionDetails.isAskUser || !!(n.functionDetails.askUserComponent ?? p.functionDetails.askUserComponent),
553
553
  // Runtime "don't render" override rides the RESULT; true-wins sticky like isUi so it
554
554
  // survives folding onto the earlier call rep and suppresses drawer/uiTool classification.
555
- cancelUi: n.functionDetails.cancelUi === !0 || m.functionDetails.cancelUi === !0,
556
- parked: n.functionDetails.parked === !0 || m.functionDetails.parked === !0
555
+ cancelUi: n.functionDetails.cancelUi === !0 || p.functionDetails.cancelUi === !0,
556
+ parked: n.functionDetails.parked === !0 || p.functionDetails.parked === !0
557
557
  }
558
558
  };
559
- h(), d.set(I, R), R.eventType === y.FunctionResponse && this.eventBusService.gatewayEmitFunctionResponse(R.functionDetails), s.push(R), S > -1 && (v(), r[S] = R);
559
+ h(), d.set(I, L), L.eventType === C.FunctionResponse && this.eventBusService.gatewayEmitFunctionResponse(L.functionDetails), s.push(L), S > -1 && (v(), r[S] = L);
560
560
  } else {
561
- if (I && n.functionDetails && !M && (h(), d.set(I, n)), o && o.textAppendable) {
562
- const m = {
563
- ...o,
561
+ if (I && n.functionDetails && !D && (h(), d.set(I, n)), a && a.textAppendable) {
562
+ const p = {
563
+ ...a,
564
564
  ended: /* @__PURE__ */ new Date(),
565
565
  isStillWriting: !1
566
566
  };
567
- v(), r[r.length - 1] = m, s.push(m);
567
+ v(), r[r.length - 1] = p, s.push(p);
568
568
  }
569
569
  const S = {
570
570
  ...n,
@@ -572,7 +572,7 @@ ${n.value}
572
572
  isStillWriting: n.textAppendable,
573
573
  partial: t.partial
574
574
  };
575
- (st = S.functionDetails) != null && st.silent || s.push(S), r = [...r, S], p = !0;
575
+ (it = S.functionDetails) != null && it.silent || s.push(S), r = [...r, S], m = !0;
576
576
  }
577
577
  }
578
578
  let T = r[r.length - 1] ?? null;
@@ -585,11 +585,11 @@ ${n.value}
585
585
  let I = !1;
586
586
  if (t.partial) {
587
587
  try {
588
- g.textDetails.version++, p || (g.text = (T.text ?? "") + (n.text ?? ""));
589
- } catch (M) {
590
- console.error("Error here", M.toString());
588
+ g.textDetails.version++, m || (g.text = (T.text ?? "") + (n.text ?? ""));
589
+ } catch (D) {
590
+ console.error("Error here", D.toString());
591
591
  }
592
- g.textLastChunk = n.text ?? "", g.isStillWriting = !0, I = !0, !p && n.thoughtDetails && g.thoughtDetails && (n.thoughtDetails.text.length >= 50 || n.thoughtDetails.text.length < 50 && n.thoughtDetails.text !== g.thoughtDetails.text) && (g.thoughtDetails = {
592
+ g.textLastChunk = n.text ?? "", g.isStillWriting = !0, I = !0, !m && n.thoughtDetails && g.thoughtDetails && (n.thoughtDetails.text.length >= 50 || n.thoughtDetails.text.length < 50 && n.thoughtDetails.text !== g.thoughtDetails.text) && (g.thoughtDetails = {
593
593
  ...g.thoughtDetails,
594
594
  text: g.thoughtDetails.text + n.thoughtDetails.text
595
595
  }, g.thoughtLastChunk = n.thoughtDetails.text);
@@ -604,13 +604,13 @@ ${n.value}
604
604
  if (t.llmArtifacts && t.llmArtifacts.length > 0) {
605
605
  let g = !1;
606
606
  for (const I of t.llmArtifacts) {
607
- const M = I.toArtifact();
607
+ const D = I.toArtifact();
608
608
  g || (E = E.slice(), g = !0);
609
- const S = E.findIndex((m) => m.id === M.id);
610
- S === -1 ? E.push(M) : E[S] = M;
609
+ const S = E.findIndex((p) => p.id === D.id);
610
+ S === -1 ? E.push(D) : E[S] = D;
611
611
  }
612
612
  }
613
- const k = {
613
+ const P = {
614
614
  ...e,
615
615
  version: e.version + 1,
616
616
  parts: r,
@@ -620,22 +620,22 @@ ${n.value}
620
620
  partial: t.partial,
621
621
  asyncFinalResponse: t.asyncFinalResponse
622
622
  };
623
- return this.interaction = k, {
624
- updatedInteraction: k,
623
+ return this.interaction = P, {
624
+ updatedInteraction: P,
625
625
  updatedParts: s,
626
- newArtifacts: a,
627
- mainBranch: k,
626
+ newArtifacts: o,
627
+ mainBranch: P,
628
628
  analyticsBranch: null,
629
629
  analyticsBranchPartsChanged: null,
630
630
  mainBranchPartsChanged: s
631
631
  };
632
632
  }
633
633
  };
634
- f(j, "InteractionService");
635
- let B = j;
636
- const Lt = 1200 * 1e3, P = class P {
637
- constructor(t, e, s, a, n, o, l, r, d, u = yt.Interactive) {
638
- i(this, "base_production_url", wt() ?? "https://agent.tripapi.com.br");
634
+ f(Z, "InteractionService");
635
+ let x = Z;
636
+ const Ft = 1200 * 1e3, N = class N {
637
+ constructor(t, e, s, o, n, a, l, r, d, u = Ct.Interactive) {
638
+ i(this, "base_production_url", yt() ?? "https://agent.tripapi.com.br");
639
639
  i(this, "base_url_local", "http://localagent:8000");
640
640
  i(this, "base_url");
641
641
  i(this, "isLocal", !1);
@@ -710,7 +710,7 @@ const Lt = 1200 * 1e3, P = class P {
710
710
  i(this, "subAgentInteractionServices", /* @__PURE__ */ new Map());
711
711
  i(this, "lastThorttledTimeout", null);
712
712
  i(this, "lastPingStatus", !1);
713
- this.user = t, this.config = n, this.rawJwt = t.access_token, this.base_url = a, this.eventBusService = e, this.sessionId = d, this.runMode = u, this.artifactService = s, this.sessionState = o.getState(), this.notificationPort = l, this.storageService = r, o.subscribe((h, v) => {
713
+ this.user = t, this.config = n, this.rawJwt = t.access_token, this.base_url = o, this.eventBusService = e, this.sessionId = d, this.runMode = u, this.artifactService = s, this.sessionState = a.getState(), this.notificationPort = l, this.storageService = r, a.subscribe((h, v) => {
714
714
  this.sessionState = h;
715
715
  });
716
716
  }
@@ -791,11 +791,11 @@ const Lt = 1200 * 1e3, P = class P {
791
791
  if (e && this.currentIS)
792
792
  return this.currentIS.interaction.isSuspended = !1, this.currentIS.interaction.interactionQuestion += " + " + t, this.currentIS.interaction;
793
793
  this.msg_order += 1;
794
- let a = this.getNewInteractionId();
795
- s && (a = s);
794
+ let o = this.getNewInteractionId();
795
+ s && (o = s);
796
796
  let n = {
797
797
  created: /* @__PURE__ */ new Date(),
798
- interactionId: a,
798
+ interactionId: o,
799
799
  artifactData: [],
800
800
  partial: !0,
801
801
  sessionId: this.sessionId,
@@ -805,7 +805,7 @@ const Lt = 1200 * 1e3, P = class P {
805
805
  functionMap: /* @__PURE__ */ new Map(),
806
806
  interactionQuestion: t
807
807
  };
808
- return this.interactionsMap.set(n.interactionId, n), this.currentIS = new B(n, this.eventBusService), this.interactionsServiceMap.set(n.interactionId, this.currentIS), n;
808
+ return this.interactionsMap.set(n.interactionId, n), this.currentIS = new x(n, this.eventBusService), this.interactionsServiceMap.set(n.interactionId, this.currentIS), n;
809
809
  }
810
810
  getInteractions() {
811
811
  return Array.from(this.interactionsMap.values());
@@ -858,8 +858,8 @@ const Lt = 1200 * 1e3, P = class P {
858
858
  s ? (console.warn("GOT A running promise", t), e = s) : (e = this.artifactService.getArtifact(t), this.runningRequests.set(t, e));
859
859
  try {
860
860
  return await e;
861
- } catch (a) {
862
- return console.error("Error awating on HTML promise", a.toString()), null;
861
+ } catch (o) {
862
+ return console.error("Error awating on HTML promise", o.toString()), null;
863
863
  } finally {
864
864
  this.runningRequests.delete(t);
865
865
  }
@@ -875,8 +875,8 @@ const Lt = 1200 * 1e3, P = class P {
875
875
  return !1;
876
876
  }
877
877
  getOrCreateSubAgentInteraction(t, e, s) {
878
- let a = this.subAgentInteractions.get(t), n = this.subAgentInteractionServices.get(t);
879
- return (!a || !n) && (a = {
878
+ let o = this.subAgentInteractions.get(t), n = this.subAgentInteractionServices.get(t);
879
+ return (!o || !n) && (o = {
880
880
  created: /* @__PURE__ */ new Date(),
881
881
  interactionId: e,
882
882
  artifactData: [],
@@ -886,21 +886,21 @@ const Lt = 1200 * 1e3, P = class P {
886
886
  version: 0,
887
887
  functionMap: /* @__PURE__ */ new Map(),
888
888
  interactionQuestion: s ?? t
889
- }, n = new B(a, this.eventBusService), this.subAgentInteractions.set(t, a), this.subAgentInteractionServices.set(t, n)), { interaction: a, service: n };
889
+ }, n = new x(o, this.eventBusService), this.subAgentInteractions.set(t, o), this.subAgentInteractionServices.set(t, n)), { interaction: o, service: n };
890
890
  }
891
891
  handleSubAgentEvent(t) {
892
892
  const e = t.subAgentId, { service: s } = this.getOrCreateSubAgentInteraction(e, t.interactionId, t.subAgentName);
893
893
  if (t.parts && t.parts.length > 0) {
894
- for (const o of t.parts)
895
- if (o.toolDetails) {
896
- this.localEmitToolEvent({ ...o.toolDetails, subAgentId: e });
894
+ for (const a of t.parts)
895
+ if (a.toolDetails) {
896
+ this.localEmitToolEvent({ ...a.toolDetails, subAgentId: e });
897
897
  continue;
898
898
  }
899
899
  }
900
- const a = s.merge(t);
901
- if (!a) return;
900
+ const o = s.merge(t);
901
+ if (!o) return;
902
902
  const n = t.turn_complete ?? !1;
903
- this.sessionState.setSubAgentMessage(e, a.updatedInteraction, t.subAgentName), n && this.sessionState.completeSubAgent(e);
903
+ this.sessionState.setSubAgentMessage(e, o.updatedInteraction, t.subAgentName), n && this.sessionState.completeSubAgent(e);
904
904
  }
905
905
  async Message(t) {
906
906
  try {
@@ -918,8 +918,8 @@ const Lt = 1200 * 1e3, P = class P {
918
918
  if (e.serverError && console.error("Stream error: ", e.serverError), e.endMessageData && this.eventBusService.gatewayEmitEndMessageData(e.endMessageData), e) {
919
919
  if (e.llmArtifacts && e.llmArtifacts.length > 0)
920
920
  for (const n of e.llmArtifacts) {
921
- const o = n.toArtifact();
922
- this.artifactService.addToCache(o), this.eventBusService.artifactEmitGenerated(o);
921
+ const a = n.toArtifact();
922
+ this.artifactService.addToCache(a), this.eventBusService.artifactEmitGenerated(a);
923
923
  }
924
924
  if (e.parts && e.parts.length > 0) {
925
925
  for (const n of e.parts)
@@ -937,21 +937,21 @@ const Lt = 1200 * 1e3, P = class P {
937
937
  return;
938
938
  }
939
939
  this.localEmitMessage(s.updatedInteraction, s), e.turn_complete && this.turnComplete(e.interactionId, s.updatedInteraction, e.author, e.subAgentId), e.asyncFinalResponse && (e.turn_complete = !0, s.updatedInteraction.turn_complete == !0, this.finalResponse(e.interactionId, s.updatedInteraction, e.author, e.subAgentId));
940
- const a = e.artifactsDelta;
941
- a && a.forEach((n) => {
942
- const o = s.updatedInteraction.artifactData.filter((r) => r.id == n);
940
+ const o = e.artifactsDelta;
941
+ o && o.forEach((n) => {
942
+ const a = s.updatedInteraction.artifactData.filter((r) => r.id == n);
943
943
  let l = null;
944
- o && o.length > 0 && (l = o[0], l.loadingPromise = this.asyncLoadArtifact(n).then((r) => (r === null ? console.error("Error trying to load artifact id:", l == null ? void 0 : l.id, "Artifact is null") : this.eventBusService.artifactEmitGenerated(r), r)).catch((r) => (console.error("Error trying to load artifact id:", l == null ? void 0 : l.id, r.toString()), null)));
944
+ a && a.length > 0 && (l = a[0], l.loadingPromise = this.asyncLoadArtifact(n).then((r) => (r === null ? console.error("Error trying to load artifact id:", l == null ? void 0 : l.id, "Artifact is null") : this.eventBusService.artifactEmitGenerated(r), r)).catch((r) => (console.error("Error trying to load artifact id:", l == null ? void 0 : l.id, r.toString()), null)));
945
945
  });
946
946
  }
947
947
  } catch (e) {
948
948
  if (this.getCurrentInteractionId()) {
949
- const s = ft.createErrorEvent("OnMessage error: " + e.toString(), this.getCurrentInteractionId() ?? "Empty Current"), a = this.updateMap(s);
950
- if (console.error("Error event: ", JSON.stringify(s, void 0, 4)), !a) {
949
+ const s = gt.createErrorEvent("OnMessage error: " + e.toString(), this.getCurrentInteractionId() ?? "Empty Current"), o = this.updateMap(s);
950
+ if (console.error("Error event: ", JSON.stringify(s, void 0, 4)), !o) {
951
951
  console.error("Error event, could not update interaction: ", JSON.stringify(s, void 0, 4));
952
952
  return;
953
953
  }
954
- this.localEmitMessage(a.updatedInteraction);
954
+ this.localEmitMessage(o.updatedInteraction);
955
955
  }
956
956
  }
957
957
  }
@@ -975,11 +975,11 @@ const Lt = 1200 * 1e3, P = class P {
975
975
  this.sessionState.setCurrentMessage(t), this.lastCurrentMessageUpdate = e, this.pendingCurrentMessage = null, this.eventBusService.gatewayEmitMessage(t, s);
976
976
  }
977
977
  localEmitMessage(t, e) {
978
- const s = (/* @__PURE__ */ new Date()).getTime(), a = s - this.lastCurrentMessageUpdate;
979
- t.partial === !1 || a >= P.CURRENT_MSG_THROTTLE_MS ? (this.lastThorttledTimeout && (clearTimeout(this.lastThorttledTimeout), this.lastThorttledTimeout = null), this.doEmitMessage(t, s, e), this.pendingCurrentMessage = null) : (this.pendingCurrentMessage = t, this.lastThorttledTimeout && clearTimeout(this.lastThorttledTimeout), this.lastThorttledTimeout = setTimeout(() => {
980
- var o, l;
981
- this.pendingCurrentMessage && (((o = this.pendingCurrentMessage) == null ? void 0 : o.version) ?? 0) > (((l = this.sessionState.currentMessage) == null ? void 0 : l.version) ?? 0) && (this.doEmitMessage(this.pendingCurrentMessage, s, e), this.lastThorttledTimeout = null);
982
- }, P.CURRENT_MSG_THROTTLE_MS * 2));
978
+ const s = (/* @__PURE__ */ new Date()).getTime(), o = s - this.lastCurrentMessageUpdate;
979
+ t.partial === !1 || o >= N.CURRENT_MSG_THROTTLE_MS ? (this.lastThorttledTimeout && (clearTimeout(this.lastThorttledTimeout), this.lastThorttledTimeout = null), this.doEmitMessage(t, s, e), this.pendingCurrentMessage = null) : (this.pendingCurrentMessage = t, this.lastThorttledTimeout && clearTimeout(this.lastThorttledTimeout), this.lastThorttledTimeout = setTimeout(() => {
980
+ var a, l;
981
+ this.pendingCurrentMessage && (((a = this.pendingCurrentMessage) == null ? void 0 : a.version) ?? 0) > (((l = this.sessionState.currentMessage) == null ? void 0 : l.version) ?? 0) && (this.doEmitMessage(this.pendingCurrentMessage, s, e), this.lastThorttledTimeout = null);
982
+ }, N.CURRENT_MSG_THROTTLE_MS * 2));
983
983
  }
984
984
  localOpen(t, e) {
985
985
  this.sessionState.setTurnOpen(!0), this.eventBusService.gatewayEmitTurnOpen(t ?? "");
@@ -999,26 +999,26 @@ const Lt = 1200 * 1e3, P = class P {
999
999
  cancelPendingCurrentMessage() {
1000
1000
  this.lastThorttledTimeout && (clearTimeout(this.lastThorttledTimeout), this.lastThorttledTimeout = null), this.pendingCurrentMessage = null;
1001
1001
  }
1002
- async turnComplete(t, e, s, a) {
1002
+ async turnComplete(t, e, s, o) {
1003
1003
  this.cancelPendingCurrentMessage(), this.sessionState.setNewMessage(e), this.eventBusService.gatewayEmitTurnComplete(t, e), this.interactionCallIds.delete(t), this.sessionState.setLastToolEvent(null), this.localEmitToolEvent({
1004
1004
  eventName: "todolistUpdated",
1005
1005
  eventData: "",
1006
- subAgentId: a
1006
+ subAgentId: o
1007
1007
  }), this.sessionState.setTurnOpen(!1);
1008
1008
  }
1009
1009
  async handlePing() {
1010
- return Date.now() - this.lastPing.getTime() > Lt ? await this.ping() ? (this.lastPing = /* @__PURE__ */ new Date(), this.lastPingStatus = !0, !0) : (this.lastPingStatus = !1, !1) : (this.lastPingStatus = !0, !0);
1010
+ return Date.now() - this.lastPing.getTime() > Ft ? await this.ping() ? (this.lastPing = /* @__PURE__ */ new Date(), this.lastPingStatus = !0, !0) : (this.lastPingStatus = !1, !1) : (this.lastPingStatus = !0, !0);
1011
1011
  }
1012
1012
  async sendMessage(t, e) {
1013
- let s = this.getInteractions().length, a = N.createWaiting(!0, !0, "Overall", /* @__PURE__ */ new Date());
1014
- this.sendStatusMessage(t.data, [a], s.toString() + "1");
1013
+ let s = this.getInteractions().length, o = _.createWaiting(!0, !0, "Overall", /* @__PURE__ */ new Date());
1014
+ this.sendStatusMessage(t.data, [o], s.toString() + "1");
1015
1015
  try {
1016
- const { promptAsString: n, json: o } = this.sessionState.onRenderPrompt ? this.sessionState.onRenderPrompt(t.data) : { promptAsString: t.data, json: void 0 };
1017
- this.sessionState.onRenderPrompt && (t.data = o, t.friendlyMessage = n);
1018
- const l = await this.sendMessageInternal(t, e), r = _t.createPrompt(n ?? "", (o == null ? void 0 : o.toString()) ?? {});
1016
+ const { promptAsString: n, json: a } = this.sessionState.onRenderPrompt ? this.sessionState.onRenderPrompt(t.data) : { promptAsString: t.data, json: void 0 };
1017
+ this.sessionState.onRenderPrompt && (t.data = a, t.friendlyMessage = n);
1018
+ const l = await this.sendMessageInternal(t, e), r = bt.createPrompt(n ?? "", (a == null ? void 0 : a.toString()) ?? {});
1019
1019
  this.storageService.storePrompt(r);
1020
- const d = N.fromText("Planejando próximos passos");
1021
- return this.sendStatusMessage(t.data, [a, d], s.toString() + "1"), l != null && l.success ? this.eventBusService.ChatEmitMessageSent(t.data, l.interaction) : this.eventBusService.ChatEmitMessageError((l == null ? void 0 : l.error) ?? ""), l;
1020
+ const d = _.fromText("Planejando próximos passos");
1021
+ return this.sendStatusMessage(t.data, [o, d], s.toString() + "1"), l != null && l.success ? this.eventBusService.ChatEmitMessageSent(t.data, l.interaction) : this.eventBusService.ChatEmitMessageError((l == null ? void 0 : l.error) ?? ""), l;
1022
1022
  } catch (n) {
1023
1023
  return this.eventBusService.ChatEmitMessageError((n == null ? void 0 : n.toString()) ?? ""), {
1024
1024
  success: !1,
@@ -1027,7 +1027,7 @@ const Lt = 1200 * 1e3, P = class P {
1027
1027
  created: /* @__PURE__ */ new Date(),
1028
1028
  interactionId: "",
1029
1029
  partial: !1,
1030
- parts: [N.fromError((n == null ? void 0 : n.toString()) ?? "")],
1030
+ parts: [_.fromError((n == null ? void 0 : n.toString()) ?? "")],
1031
1031
  version: 0
1032
1032
  }
1033
1033
  };
@@ -1047,9 +1047,9 @@ const Lt = 1200 * 1e3, P = class P {
1047
1047
  t.partial = !0, t.turn_complete = !1, t.asyncFinalResponse = !1, t.interactionId = t.interactionId, this.eventBusService.gatewayEmitTurnOpen(t.interactionId), this.Message(t);
1048
1048
  }
1049
1049
  sendStatusMessage(t, e, s) {
1050
- var n, o;
1051
- let a;
1052
- ((o = (n = this.currentIS) == null ? void 0 : n.interaction) == null ? void 0 : o.turn_complete) === !1 ? (a = Nt.cloneDeep(this.currentIS.interaction), a.parts.push(...e)) : a = {
1050
+ var n, a;
1051
+ let o;
1052
+ ((a = (n = this.currentIS) == null ? void 0 : n.interaction) == null ? void 0 : a.turn_complete) === !1 ? (o = _t.cloneDeep(this.currentIS.interaction), o.parts.push(...e)) : o = {
1053
1053
  interactionId: "tmp" + s,
1054
1054
  created: /* @__PURE__ */ new Date(),
1055
1055
  partial: !0,
@@ -1058,7 +1058,7 @@ const Lt = 1200 * 1e3, P = class P {
1058
1058
  parts: e,
1059
1059
  interactionQuestion: t,
1060
1060
  artifactData: []
1061
- }, this.localEmitMessage(a);
1061
+ }, this.localEmitMessage(o);
1062
1062
  }
1063
1063
  clearStatus() {
1064
1064
  }
@@ -1072,23 +1072,23 @@ const Lt = 1200 * 1e3, P = class P {
1072
1072
  }
1073
1073
  }
1074
1074
  getNewInteractionId() {
1075
- const e = Pt(/* @__PURE__ */ new Date(), "MMM_dd_HH_mm_ss");
1075
+ const e = Nt(/* @__PURE__ */ new Date(), "MMM_dd_HH_mm_ss");
1076
1076
  return `${this.msg_order}_${e}`;
1077
1077
  }
1078
1078
  };
1079
- f(P, "AgentGatewayService"), i(P, "SUSPENSION_MSG", "SUSPEND"), i(P, "CURRENT_MSG_THROTTLE_MS", 150);
1080
- let G = P;
1081
- const Ut = 0.02;
1079
+ f(N, "AgentGatewayService"), i(N, "SUSPENSION_MSG", "SUSPEND"), i(N, "CURRENT_MSG_THROTTLE_MS", 150);
1080
+ let z = N;
1081
+ const $t = 0.02;
1082
1082
  function xt(w, t) {
1083
1083
  if (!t) return null;
1084
1084
  const e = (t.interactionsCompressed ?? 0) > 0 || (t.compressionRatio ?? 0) > 0;
1085
1085
  if (!w)
1086
- return e ? rt(t, t.size, t.size) : null;
1087
- const s = w.size - t.size, a = t.maxSize || w.maxSize || 0, n = a > 0 ? s / a >= Ut : w.size > 0 && s / w.size >= 0.1;
1088
- return !e && !n ? null : rt(t, w.size, t.size, w.ratio);
1086
+ return e ? lt(t, t.size, t.size) : null;
1087
+ const s = w.size - t.size, o = t.maxSize || w.maxSize || 0, n = o > 0 ? s / o >= $t : w.size > 0 && s / w.size >= 0.1;
1088
+ return !e && !n ? null : lt(t, w.size, t.size, w.ratio);
1089
1089
  }
1090
1090
  f(xt, "detectCompaction");
1091
- function rt(w, t, e, s) {
1091
+ function lt(w, t, e, s) {
1092
1092
  return {
1093
1093
  at: Date.now(),
1094
1094
  // Where the bar stood when it happened — the marker's position. The ratio
@@ -1100,8 +1100,8 @@ function rt(w, t, e, s) {
1100
1100
  interactionsCompressed: w.interactionsCompressed
1101
1101
  };
1102
1102
  }
1103
- f(rt, "entry");
1104
- const H = 4001, Bt = 4002, ct = 4, Wt = 3, $t = 20, qt = 500, Gt = 3e4, Ht = 2, zt = 0.2, lt = 2, Q = class Q {
1103
+ f(lt, "entry");
1104
+ const B = 4001, Bt = 4002, ht = 4, Wt = 3, qt = 20, Gt = 500, Ht = 3e4, Kt = 2, zt = 0.2, q = 2, Jt = 5e3, Xt = 3e4, G = 1e4, Yt = 4100, V = class V {
1105
1105
  constructor(t = "ws://localhost:8000", e) {
1106
1106
  i(this, "ws", null);
1107
1107
  i(this, "stats");
@@ -1157,7 +1157,8 @@ const H = 4001, Bt = 4002, ct = 4, Wt = 3, $t = 20, qt = 500, Gt = 3e4, Ht = 2,
1157
1157
  i(this, "streamingResponseSerializer");
1158
1158
  i(this, "events");
1159
1159
  i(this, "lastActivity");
1160
- i(this, "pingPongStack");
1160
+ /** When the outstanding heartbeat Ping went out; null while no reply is pending. */
1161
+ i(this, "pingSentAt", null);
1161
1162
  i(this, "firstTokenInteractions");
1162
1163
  /** Last sessionId we successfully had — used to resume on reconnect. */
1163
1164
  i(this, "lastKnownSessionId");
@@ -1199,7 +1200,7 @@ const H = 4001, Bt = 4002, ct = 4, Wt = 3, $t = 20, qt = 500, Gt = 3e4, Ht = 2,
1199
1200
  * Cleared by `disconnect()`.
1200
1201
  */
1201
1202
  i(this, "hasEverReceivedPacket", !1);
1202
- this.baseUrl = t, this.getToken = e, this.pingPongStack = [], this.events = [], this.firstTokenInteractions = /* @__PURE__ */ new Set(), this.streamingResponseSerializer = Ct(), console.log("SOCKET INSTACE", Tt()), this.stats = {
1203
+ this.baseUrl = t, this.getToken = e, this.events = [], this.firstTokenInteractions = /* @__PURE__ */ new Set(), this.streamingResponseSerializer = It(), console.log("SOCKET INSTACE", Tt()), this.stats = {
1203
1204
  eventCount: 0,
1204
1205
  unknonwCount: 0,
1205
1206
  buffer: [],
@@ -1222,13 +1223,13 @@ const H = 4001, Bt = 4002, ct = 4, Wt = 3, $t = 20, qt = 500, Gt = 3e4, Ht = 2,
1222
1223
  * silently, because the transcript looked intact right up to the gap.
1223
1224
  */
1224
1225
  connect(t, e) {
1225
- return new Promise(async (s, a) => {
1226
- var b;
1226
+ return new Promise(async (s, o) => {
1227
+ var R;
1227
1228
  this.intentionalDisconnect = !1;
1228
1229
  const n = this._internalReconnect || (e == null ? void 0 : e.resume) === !0;
1229
- n || (this.cancelPendingReconnect(), this.isReconnecting = !1, this.reconnectAttempts = 0, this.lastSeq = -1), this._internalReconnect = !1;
1230
- const o = (b = this.getToken) == null ? void 0 : b.call(this), l = [];
1231
- o && l.push(`access_token=${encodeURIComponent(o)}`), t && this.lastSeq >= 0 && l.push(`lastSeq=${this.lastSeq}`);
1230
+ this._internalReconnect || this.cancelPendingReconnect(), n || (this.isReconnecting = !1, this.reconnectAttempts = 0, this.lastSeq = -1), this._internalReconnect = !1;
1231
+ const a = (R = this.getToken) == null ? void 0 : R.call(this), l = [];
1232
+ a && l.push(`access_token=${encodeURIComponent(a)}`), t && this.lastSeq >= 0 && l.push(`lastSeq=${this.lastSeq}`);
1232
1233
  const r = l.length > 0 ? `?${l.join("&")}` : "", d = this.baseUrl.replace(/^http:\/\//, "ws://").replace(/^https:\/\//, "wss://"), u = `${d}/ws/connect/${t ?? ""}${r}`, h = `${d}/ws/connect/${t ?? ""}` + (n && t && this.lastSeq >= 0 ? ` (resume lastSeq=${this.lastSeq})` : "");
1233
1234
  if (console.log("Connecting to ", h), this.ws) {
1234
1235
  this.ws.onopen = null, this.ws.onmessage = null, this.ws.onerror = null, this.ws.onclose = null;
@@ -1242,55 +1243,57 @@ const H = 4001, Bt = 4002, ct = 4, Wt = 3, $t = 20, qt = 500, Gt = 3e4, Ht = 2,
1242
1243
  let v = !1;
1243
1244
  this.ws.onopen = () => {
1244
1245
  console.log("[WebSocket] Connected");
1245
- const C = this.isReconnecting;
1246
- this.isReconnecting = !1, this.reconnectAttempts = 0, this.pingPongStack.push((/* @__PURE__ */ new Date()).getTime()), this.ping(), this.monitor(), this.onOpen && this.onOpen(), C && this.onReconnected && this.onReconnected(t ?? this.lastKnownSessionId ?? ""), this.flushPendingAnswers(t ?? this.lastKnownSessionId);
1247
- }, this.ws.onmessage = (C) => {
1246
+ const y = this.isReconnecting;
1247
+ this.isReconnecting = !1, this.reconnectAttempts = 0, this.ping(), this.monitor(), this.onOpen && this.onOpen(), y && console.log(`[WebSocket] Reconnected (session ${t ?? this.lastKnownSessionId ?? "none"}${this.lastSeq >= 0 ? `, replaying from lastSeq=${this.lastSeq}` : ", no replay cursor"}).`), y && this.onReconnected && this.onReconnected(t ?? this.lastKnownSessionId ?? ""), this.flushPendingAnswers(t ?? this.lastKnownSessionId);
1248
+ }, this.ws.onmessage = (y) => {
1248
1249
  try {
1249
- this.lastActivity = (/* @__PURE__ */ new Date()).getTime();
1250
- const O = this.streamingResponseSerializer.parse(C.data);
1250
+ this.lastActivity = (/* @__PURE__ */ new Date()).getTime(), this.pingSentAt = null;
1251
+ const O = this.streamingResponseSerializer.parse(y.data);
1251
1252
  if (!O)
1252
1253
  throw "Error parsing event JSON";
1253
- const A = this.handleMessage(O, C.data);
1254
+ const A = this.handleMessage(O, y.data);
1254
1255
  !v && (A != null && A.timestamp) && (v = !0, this.hasEverReceivedPacket = !0);
1255
1256
  } catch (O) {
1256
1257
  console.error("[WebSocket] Error parsing message:", O);
1257
1258
  }
1258
- }, this.ws.onerror = (C) => {
1259
- console.error("[WebSocket] Error:", C), this.onError && this.onError("WebSocket error");
1260
- }, this.ws.onclose = (C) => {
1261
- console.log("[WebSocket] Closed:", C.code, C.reason), this.monitorInterval && (clearInterval(this.monitorInterval), this.monitorInterval = null), this.pingPongStack = [];
1259
+ }, this.ws.onerror = (y) => {
1260
+ console.error("[WebSocket] Error:", y), this.onError && this.onError("WebSocket error");
1261
+ }, this.ws.onclose = (y) => {
1262
+ console.log(`[WebSocket] Closed: code=${y.code} reason="${y.reason}" (session ${this.sessionLabel}, lastSeq=${this.lastSeq}, intentional=${this.intentionalDisconnect})`), this.monitorInterval && (clearInterval(this.monitorInterval), this.monitorInterval = null), this.pingSentAt = null;
1262
1263
  const O = this.sessionId ?? this.lastKnownSessionId;
1263
- if (this.sessionId = void 0, (v || this.hasEverReceivedPacket) && this.shouldAttemptReconnect(C.code)) {
1264
- this.scheduleReconnect(O, C.code, C.reason);
1264
+ this.sessionId = void 0;
1265
+ const A = v || this.hasEverReceivedPacket;
1266
+ if (A && this.shouldAttemptReconnect(y.code)) {
1267
+ this.scheduleReconnect(O, y.code, y.reason);
1265
1268
  return;
1266
1269
  }
1267
- this.isReconnecting = !1, this.reconnectAttempts = 0, this.onClose && this.onClose(C.code, C.reason);
1270
+ console.warn(`[WebSocket] Inner reconnect declined for code=${y.code}: channelProven=${A}, codeRetryable=${this.shouldAttemptReconnect(y.code)}. Handing off to the outer state manager (session ${O ?? "none"}).`), this.isReconnecting = !1, this.reconnectAttempts = 0, this.onClose && this.onClose(y.code, y.reason);
1268
1271
  };
1269
- const p = 200, D = 3e4, T = 8e3, E = this.ws;
1272
+ const m = 200, M = 3e4, T = 8e3, E = this.ws;
1270
1273
  this.sessionId = void 0;
1271
- let k = 0, _ = 0;
1274
+ let P = 0, b = 0;
1272
1275
  for (; !this.sessionId; ) {
1273
1276
  if (this.ws !== E) {
1274
- a("Connection attempt superseded by a newer connect()");
1277
+ o("Connection attempt superseded by a newer connect()");
1275
1278
  return;
1276
1279
  }
1277
1280
  if (E.readyState === WebSocket.CLOSING || E.readyState === WebSocket.CLOSED) {
1278
- a("Connection closed before a session id was received");
1281
+ o("Connection closed before a session id was received");
1279
1282
  return;
1280
1283
  }
1281
- if (E.readyState === WebSocket.CONNECTING && k >= D) {
1284
+ if (E.readyState === WebSocket.CONNECTING && P >= M) {
1282
1285
  try {
1283
1286
  E.close();
1284
1287
  } catch {
1285
1288
  }
1286
- a(`Server did not accept the connection within ${D / 1e3}s`);
1289
+ o(`Server did not accept the connection within ${M / 1e3}s`);
1287
1290
  return;
1288
1291
  }
1289
- if (E.readyState === WebSocket.OPEN && _ >= T) {
1290
- a(`Connected but no session id arrived within ${T / 1e3}s`);
1292
+ if (E.readyState === WebSocket.OPEN && b >= T) {
1293
+ o(`Connected but no session id arrived within ${T / 1e3}s`);
1291
1294
  return;
1292
1295
  }
1293
- k % 2e3 === 0 && console.log("Aguardando session Id"), await this.sleep(p), k += p, E.readyState === WebSocket.OPEN && (_ += p);
1296
+ P % 2e3 === 0 && console.log("Aguardando session Id"), await this.sleep(m), P += m, E.readyState === WebSocket.OPEN && (b += m);
1294
1297
  }
1295
1298
  console.log("SUCCESS - GOT SESSION ID", this.sessionId), this.lastKnownSessionId = this.sessionId, s(this.sessionId);
1296
1299
  });
@@ -1302,43 +1305,56 @@ const H = 4001, Bt = 4002, ct = 4, Wt = 3, $t = 20, qt = 500, Gt = 3e4, Ht = 2,
1302
1305
  * - 1000 normal closure
1303
1306
  * - 1008 policy violation (auth rejected)
1304
1307
  * - 4001 our own intentional disconnect
1305
- * - 4000-4099 reserved for app-level fatal codes from the server
1308
+ * - 4002 the session is attached elsewhere (another tab) — retrying just bounces
1309
+ * Retried, on purpose:
1310
+ * - 4003 the server's idle close ("reconnect on next interaction"): resuming is
1311
+ * cheap and lossless, and while the user is present the outer loop would redial
1312
+ * anyway; when they are gone the client's own idle timer closes first.
1313
+ * - 4100 HEARTBEAT_TIMEOUT_CODE, our own dead-peer verdict.
1306
1314
  */
1307
1315
  shouldAttemptReconnect(t) {
1308
- return !(this.intentionalDisconnect || t === H || t === Bt || t === 1e3 || t === 1008);
1316
+ return !(this.intentionalDisconnect || t === B || t === Bt || t === 1e3 || t === 1008);
1309
1317
  }
1310
1318
  cancelPendingReconnect() {
1311
- this.reconnectTimer && (clearTimeout(this.reconnectTimer), this.reconnectTimer = null);
1319
+ this.reconnectTimer && (console.log("[WebSocket] Cancelling the scheduled reconnect attempt."), clearTimeout(this.reconnectTimer), this.reconnectTimer = null);
1312
1320
  }
1313
1321
  computeBackoffDelay() {
1314
- const t = qt * Math.pow(Ht, this.reconnectAttempts), e = Math.min(t, Gt), s = e * zt * (Math.random() * 2 - 1);
1322
+ const t = Gt * Math.pow(Kt, this.reconnectAttempts), e = Math.min(t, Ht), s = e * zt * (Math.random() * 2 - 1);
1315
1323
  return Math.max(0, Math.round(e + s));
1316
1324
  }
1317
1325
  scheduleReconnect(t, e, s) {
1318
- var n, o;
1326
+ var n, a;
1319
1327
  if (this.intentionalDisconnect) return;
1320
- if (this.reconnectAttempts >= lt) {
1328
+ if (this.reconnectAttempts >= q) {
1321
1329
  console.warn(
1322
1330
  `[WebSocket] Reconnect exhausted after ${this.reconnectAttempts} attempts (last code=${e}, reason="${s}"). Handing off to outer state manager.`
1323
1331
  ), this.isReconnecting = !1, this.reconnectAttempts = 0, this.cancelPendingReconnect(), (n = this.onClose) == null || n.call(this, e, s);
1324
1332
  return;
1325
1333
  }
1326
1334
  this.isReconnecting = !0, this.reconnectAttempts += 1;
1327
- const a = this.computeBackoffDelay();
1335
+ const o = this.computeBackoffDelay();
1328
1336
  console.warn(
1329
- `[WebSocket] Unexpected close (code=${e}, reason="${s}"). Reconnect attempt #${this.reconnectAttempts}/${lt} in ${a}ms (resume sessionId=${t ?? "none"}).`
1330
- ), (o = this.onReconnecting) == null || o.call(this, this.reconnectAttempts, a), this.cancelPendingReconnect(), this.reconnectTimer = setTimeout(async () => {
1331
- if (this.reconnectTimer = null, !this.intentionalDisconnect)
1332
- try {
1333
- this.ws && (this.ws.onopen = null, this.ws.onmessage = null, this.ws.onerror = null, this.ws.onclose = null, this.ws = null), this._internalReconnect = !0, await this.connect(t);
1334
- } catch (l) {
1335
- console.error("[WebSocket] Reconnect attempt failed:", l);
1336
- }
1337
- }, a);
1337
+ `[WebSocket] Unexpected close (code=${e}, reason="${s}"). Reconnect attempt #${this.reconnectAttempts}/${q} in ${o}ms (resume sessionId=${t ?? "none"}).`
1338
+ ), (a = this.onReconnecting) == null || a.call(this, this.reconnectAttempts, o), this.cancelPendingReconnect(), this.reconnectTimer = setTimeout(async () => {
1339
+ if (this.reconnectTimer = null, this.intentionalDisconnect) {
1340
+ console.log("[WebSocket] Reconnect timer fired after an intentional disconnect — standing down.");
1341
+ return;
1342
+ }
1343
+ console.log(`[WebSocket] Reconnect attempt #${this.reconnectAttempts}/${q} firing now (resume sessionId=${t ?? "none"}, lastSeq=${this.lastSeq}).`);
1344
+ try {
1345
+ this.ws && (this.ws.onopen = null, this.ws.onmessage = null, this.ws.onerror = null, this.ws.onclose = null, this.ws = null), this._internalReconnect = !0, await this.connect(t);
1346
+ } catch (l) {
1347
+ console.error("[WebSocket] Reconnect attempt failed:", l);
1348
+ }
1349
+ }, o);
1338
1350
  }
1339
1351
  async sleep(t) {
1340
1352
  return new Promise((e) => setTimeout(e, t));
1341
1353
  }
1354
+ /** The session this instance believes it is on — for log lines, never for logic. */
1355
+ get sessionLabel() {
1356
+ return this.sessionId ?? this.lastKnownSessionId ?? "none";
1357
+ }
1342
1358
  /**
1343
1359
  * Handle incoming messages from server
1344
1360
  */
@@ -1350,7 +1366,7 @@ const H = 4001, Bt = 4002, ct = 4, Wt = 3, $t = 20, qt = 500, Gt = 3e4, Ht = 2,
1350
1366
  console.error("Pong response has no SESSION ID");
1351
1367
  return;
1352
1368
  }
1353
- t.accessToken && this.persistRefreshedAccessToken(t.accessToken), this.pingPongStack.pop() || console.warn("Ping pong order broke, on Pong receive"), this.onPong && this.onPong(t.sessionId);
1369
+ t.accessToken && this.persistRefreshedAccessToken(t.accessToken), this.onPong && this.onPong(t.sessionId);
1354
1370
  break;
1355
1371
  case "Suspended":
1356
1372
  this.onSuspended && this.onSuspended();
@@ -1368,35 +1384,35 @@ const H = 4001, Bt = 4002, ct = 4, Wt = 3, $t = 20, qt = 500, Gt = 3e4, Ht = 2,
1368
1384
  if (t.partialEvent) {
1369
1385
  const u = t.partialEvent;
1370
1386
  this.emitFirstToken(u == null ? void 0 : u.iteractionId);
1371
- const h = new It();
1387
+ const h = new vt();
1372
1388
  if (h.author = "main", h.streamingParts = t.partialEvent.streamingParts, t.partialEvent.partialEventType ? h.eventType = t.partialEvent.partialEventType : h.eventType = u.functionName ? {
1373
- fullName: L.StreamingFunctionCallUpdateContent,
1374
- type: y.PartialFunctionCall
1389
+ fullName: U.StreamingFunctionCallUpdateContent,
1390
+ type: C.PartialFunctionCall
1375
1391
  } : u.partialReasoning ? {
1376
- fullName: L.StreamingReasoningContent,
1377
- type: y.Thought
1392
+ fullName: U.StreamingReasoningContent,
1393
+ type: C.Thought
1378
1394
  } : {
1379
- fullName: L.StreamingTextContent,
1380
- type: y.Text
1381
- }, h.interactionId = (u == null ? void 0 : u.iteractionId) ?? "", h.mimeType = "text/plain", h.partial = !0, h.eventType.type == y.PartialFunctionCall) {
1382
- var s = new vt();
1395
+ fullName: U.StreamingTextContent,
1396
+ type: C.Text
1397
+ }, h.interactionId = (u == null ? void 0 : u.iteractionId) ?? "", h.mimeType = "text/plain", h.partial = !0, h.eventType.type == C.PartialFunctionCall) {
1398
+ var s = new Et();
1383
1399
  s.choiceIndex = 0, s.callId = u.functionCallId, s.arguments = u.partialText, s.name = u.functionName, h.content = {
1384
1400
  items: [s],
1385
1401
  role: {
1386
1402
  label: "Assistant"
1387
1403
  }
1388
1404
  };
1389
- } else if (h.eventType.type == y.Text)
1390
- if (h.eventType.fullName == L.StreamingTextContent) {
1391
- var a = new Et();
1392
- a.text = u.partialText, h.content = {
1393
- items: [a],
1405
+ } else if (h.eventType.type == C.Text)
1406
+ if (h.eventType.fullName == U.StreamingTextContent) {
1407
+ var o = new Mt();
1408
+ o.text = u.partialText, h.content = {
1409
+ items: [o],
1394
1410
  role: {
1395
1411
  label: "Assistant"
1396
1412
  }
1397
1413
  };
1398
1414
  } else {
1399
- var n = new Mt();
1415
+ var n = new Dt();
1400
1416
  n.text = u.partialText, h.content = {
1401
1417
  items: [n],
1402
1418
  role: {
@@ -1404,10 +1420,10 @@ const H = 4001, Bt = 4002, ct = 4, Wt = 3, $t = 20, qt = 500, Gt = 3e4, Ht = 2,
1404
1420
  }
1405
1421
  };
1406
1422
  }
1407
- else if (h.eventType.type == y.Thought) {
1408
- var o = new Dt();
1409
- o.text = u.partialReasoning, h.content = {
1410
- items: [o],
1423
+ else if (h.eventType.type == C.Thought) {
1424
+ var a = new Ot();
1425
+ a.text = u.partialReasoning, h.content = {
1426
+ items: [a],
1411
1427
  role: {
1412
1428
  label: "Assistant"
1413
1429
  }
@@ -1455,9 +1471,9 @@ const H = 4001, Bt = 4002, ct = 4, Wt = 3, $t = 20, qt = 500, Gt = 3e4, Ht = 2,
1455
1471
  console.warn("[WebSocket] WS-refreshed token received but no stored user — dropping");
1456
1472
  return;
1457
1473
  }
1458
- const a = JSON.parse(s);
1459
- if ((a == null ? void 0 : a.access_token) === t) return;
1460
- a.access_token = t, localStorage.setItem(e, JSON.stringify(a)), console.info("[WebSocket] Mirrored WS-refreshed JWT into stored user");
1474
+ const o = JSON.parse(s);
1475
+ if ((o == null ? void 0 : o.access_token) === t) return;
1476
+ o.access_token = t, localStorage.setItem(e, JSON.stringify(o)), console.info("[WebSocket] Mirrored WS-refreshed JWT into stored user");
1461
1477
  } catch (s) {
1462
1478
  console.error("[WebSocket] Failed to persist WS-refreshed token", s);
1463
1479
  }
@@ -1467,7 +1483,7 @@ const H = 4001, Bt = 4002, ct = 4, Wt = 3, $t = 20, qt = 500, Gt = 3e4, Ht = 2,
1467
1483
  }
1468
1484
  suspendStream() {
1469
1485
  this.sendBaseMessage({
1470
- Action: U.Suspend,
1486
+ Action: F.Suspend,
1471
1487
  AgentId: "",
1472
1488
  InteractionId: "",
1473
1489
  ModelId: ""
@@ -1486,7 +1502,7 @@ const H = 4001, Bt = 4002, ct = 4, Wt = 3, $t = 20, qt = 500, Gt = 3e4, Ht = 2,
1486
1502
  */
1487
1503
  answerHumanTool(t, e) {
1488
1504
  const s = {
1489
- Action: U.AnswerHumanTool,
1505
+ Action: F.AnswerHumanTool,
1490
1506
  AgentId: "",
1491
1507
  InteractionId: "",
1492
1508
  ToolCallId: t,
@@ -1513,7 +1529,7 @@ const H = 4001, Bt = 4002, ct = 4, Wt = 3, $t = 20, qt = 500, Gt = 3e4, Ht = 2,
1513
1529
  }
1514
1530
  try {
1515
1531
  this.sendBaseMessage({
1516
- Action: U.AnswerHumanTool,
1532
+ Action: F.AnswerHumanTool,
1517
1533
  AgentId: "",
1518
1534
  InteractionId: "",
1519
1535
  ToolCallId: s.toolCallId,
@@ -1538,19 +1554,36 @@ const H = 4001, Bt = 4002, ct = 4, Wt = 3, $t = 20, qt = 500, Gt = 3e4, Ht = 2,
1538
1554
  sendSuspendMessage(t) {
1539
1555
  this.sendMessage(t);
1540
1556
  }
1557
+ /**
1558
+ * Heartbeat: keep a quiet socket alive with a Ping every PING_INTERVAL_MS, and
1559
+ * declare it dead when a Ping goes PONG_TIMEOUT_MS without ANY inbound frame.
1560
+ * Started by `onopen`, stopped by `onclose`/`disconnect()`.
1561
+ */
1541
1562
  monitor() {
1542
- const t = this, e = this.pingPongStack, s = 3e4;
1543
- this.monitorInterval = setInterval(() => {
1563
+ this.monitorInterval && clearInterval(this.monitorInterval), this.monitorInterval = setInterval(() => {
1544
1564
  try {
1545
- const a = (/* @__PURE__ */ new Date()).getTime() - this.lastActivity;
1546
- t.isConnected() && a >= s - 200 && (e.length > 0 && console.warn("Ping pong stack broke here, on pinging"), e.push((/* @__PURE__ */ new Date()).getTime()), t.ping());
1547
- } catch (a) {
1548
- console.error("Error on monitor", a);
1565
+ if (!this.isConnected()) return;
1566
+ const t = Date.now();
1567
+ if (this.pingSentAt !== null) {
1568
+ const e = t - this.pingSentAt;
1569
+ if (e >= G) {
1570
+ this.failSocket(
1571
+ Yt,
1572
+ `No frame received for ${Math.round(e / 1e3)}s after a Ping`
1573
+ );
1574
+ return;
1575
+ }
1576
+ console.warn(`[WebSocket] Still no reply ${e}ms after the Ping (budget ${G}ms, session ${this.sessionLabel}) — the peer may be gone.`);
1577
+ return;
1578
+ }
1579
+ t - this.lastActivity >= Xt && this.ping();
1580
+ } catch (t) {
1581
+ console.error("Error on monitor", t);
1549
1582
  }
1550
- }, s);
1583
+ }, Jt);
1551
1584
  }
1552
1585
  /**
1553
- * Send a heartbeat ping
1586
+ * Send a heartbeat ping and start the reply clock (unless one is already running).
1554
1587
  */
1555
1588
  ping() {
1556
1589
  this.sendBaseMessage({
@@ -1558,13 +1591,33 @@ const H = 4001, Bt = 4002, ct = 4, Wt = 3, $t = 20, qt = 500, Gt = 3e4, Ht = 2,
1558
1591
  AgentId: "",
1559
1592
  InteractionId: "",
1560
1593
  ModelId: ""
1561
- });
1594
+ }), 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 ${G}ms answers it.`));
1595
+ }
1596
+ /**
1597
+ * Declare the current socket dead and run the close path NOW, without waiting
1598
+ * for the browser: for a half-open peer `onclose` can lag by minutes or never
1599
+ * come, and the decision has already been made. The dead socket's own onclose
1600
+ * handler is invoked with a client-local code, so the reconnect-vs-handoff
1601
+ * logic that runs is exactly the one a server close would run. Handlers are
1602
+ * detached first so a late real close event cannot run it a second time.
1603
+ */
1604
+ failSocket(t, e) {
1605
+ const s = this.ws;
1606
+ if (!s) return;
1607
+ console.warn(`[WebSocket] ${e} — treating the socket as dead (code=${t}, session ${this.sessionLabel}). readyState was ${s.readyState} (OPEN=${WebSocket.OPEN}), which is why nothing else noticed. Running the close path now.`);
1608
+ const o = s.onclose;
1609
+ s.onopen = null, s.onmessage = null, s.onerror = null, s.onclose = null;
1610
+ try {
1611
+ s.close();
1612
+ } catch {
1613
+ }
1614
+ o == null || o.call(s, { code: t, reason: e });
1562
1615
  }
1563
1616
  /**
1564
1617
  * Disconnect the WebSocket
1565
1618
  */
1566
1619
  disconnect() {
1567
- console.warn("Chamou DISCONNECT!!!"), this.intentionalDisconnect = !0, this.cancelPendingReconnect(), this.isReconnecting = !1, this.reconnectAttempts = 0, this.monitorInterval && (clearInterval(this.monitorInterval), this.monitorInterval = null), this.pingPongStack = [], this.firstTokenInteractions.clear(), this.lastKnownSessionId = void 0, this.lastSeq = -1, this.hasEverReceivedPacket = !1, this.ws && (this.ws.close(H, "Intentional disconnect"), this.ws = null);
1620
+ console.warn("Chamou DISCONNECT!!!"), this.intentionalDisconnect = !0, this.cancelPendingReconnect(), this.isReconnecting = !1, this.reconnectAttempts = 0, this.monitorInterval && (clearInterval(this.monitorInterval), this.monitorInterval = null), this.pingSentAt = null, this.firstTokenInteractions.clear(), this.lastKnownSessionId = void 0, this.lastSeq = -1, this.hasEverReceivedPacket = !1, this.ws && (this.ws.close(B, "Intentional disconnect"), this.ws = null);
1568
1621
  }
1569
1622
  /**
1570
1623
  * Check if connected
@@ -1593,28 +1646,28 @@ const H = 4001, Bt = 4002, ct = 4, Wt = 3, $t = 20, qt = 500, Gt = 3e4, Ht = 2,
1593
1646
  async handleEvent(t, e) {
1594
1647
  var s;
1595
1648
  try {
1596
- const a = ft.parseFromTypedEvent(t);
1597
- if (!a)
1649
+ const o = gt.parseFromTypedEvent(t);
1650
+ if (!o)
1598
1651
  throw "Server event was null";
1599
- if (this.events.push([(/* @__PURE__ */ new Date()).getTime(), ((s = t.text) == null ? void 0 : s.length) ?? 0]), this.stats.eventCount += 1, this.stats.totalTransfered += e.length, a.session_information && !a.subAgentId) {
1600
- const r = xt(this.previousSessionInformation, a.session_information);
1601
- r && (this.sessionCompactions.push(r), this.sessionCompactions.length > $t && this.sessionCompactions.shift()), this.previousSessionInformation = a.session_information, this.stats.sessionInformation = a.session_information, this.stats.sessionCompactions = this.sessionCompactions;
1652
+ if (this.events.push([(/* @__PURE__ */ new Date()).getTime(), ((s = t.text) == null ? void 0 : s.length) ?? 0]), this.stats.eventCount += 1, this.stats.totalTransfered += e.length, o.session_information && !o.subAgentId) {
1653
+ const r = xt(this.previousSessionInformation, o.session_information);
1654
+ r && (this.sessionCompactions.push(r), this.sessionCompactions.length > qt && this.sessionCompactions.shift()), this.previousSessionInformation = o.session_information, this.stats.sessionInformation = o.session_information, this.stats.sessionCompactions = this.sessionCompactions;
1602
1655
  }
1603
1656
  this.stats.elapsed = (Date.now() - this.stats.startTime.getTime()) / 1e3;
1604
- const n = Date.now() - ct * 1e3, l = this.events.filter((r) => r[0] > n).reduce((r, d) => r += d[1], 0) / Wt;
1605
- this.stats.tokensPerSecond = l / ct, this.flushStatsCoalesced(), this.onEvent && this.onEvent(a).catch((r) => {
1657
+ const n = Date.now() - ht * 1e3, l = this.events.filter((r) => r[0] > n).reduce((r, d) => r += d[1], 0) / Wt;
1658
+ this.stats.tokensPerSecond = l / ht, this.flushStatsCoalesced(), this.onEvent && this.onEvent(o).catch((r) => {
1606
1659
  console.error("Lost error on on-event", r);
1607
1660
  });
1608
- } catch (a) {
1609
- console.error("handleEvent error", a);
1661
+ } catch (o) {
1662
+ console.error("handleEvent error", o);
1610
1663
  }
1611
1664
  }
1612
1665
  };
1613
- f(Q, "WebSocketConnecionV2");
1614
- let ht = Q;
1615
- const Kt = "envision_agent_sessionId", Z = class Z extends G {
1616
- constructor(e, s, a, n, o, l, r, d, u, h, v) {
1617
- super(e, s, a, n, o, l, r, u, v);
1666
+ f(V, "WebSocketConnecionV2");
1667
+ let ut = V;
1668
+ const jt = "envision_agent_sessionId", tt = class tt extends z {
1669
+ constructor(e, s, o, n, a, l, r, d, u, h, v) {
1670
+ super(e, s, o, n, a, l, r, u, v);
1618
1671
  i(this, "suspendState", !1);
1619
1672
  i(this, "wsService");
1620
1673
  i(this, "root_url", "");
@@ -1629,35 +1682,35 @@ const Kt = "envision_agent_sessionId", Z = class Z extends G {
1629
1682
  i(this, "everConnected", !1);
1630
1683
  i(this, "statuses", ["CONNECTING", "OPEN", "CLOSED", "UNKNOWN"]);
1631
1684
  i(this, "lastConnectionPromise", null);
1632
- i(this, "socketState", F.Disconnected);
1685
+ i(this, "socketState", k.Disconnected);
1633
1686
  i(this, "streamOpened", !1);
1634
- this.hearBeatPort = h, this.root_url = this.base_url, this.wsService = d, this.wsService.onEvent = async (p) => {
1635
- await super.Message(p);
1636
- }, this.wsService.onNewPacket = (p) => {
1637
- this.sessionState.setStatistics(p), this.eventBusService.streamEmitNewChunk(p);
1638
- }, this.wsService.onPong = (p) => {
1639
- }, this.wsService.onError = (p) => {
1687
+ this.hearBeatPort = h, this.root_url = this.base_url, this.wsService = d, this.wsService.onEvent = async (m) => {
1688
+ await super.Message(m);
1689
+ }, this.wsService.onNewPacket = (m) => {
1690
+ this.sessionState.setStatistics(m), this.eventBusService.streamEmitNewChunk(m);
1691
+ }, this.wsService.onPong = (m) => {
1692
+ }, this.wsService.onError = (m) => {
1640
1693
  this.streamOpened = !1;
1641
- const D = {
1642
- data: this.getErrorEvent(p),
1694
+ const M = {
1695
+ data: this.getErrorEvent(m),
1643
1696
  lastEventId: (/* @__PURE__ */ new Date()).getTime().toString(),
1644
1697
  origin: "gatewayService"
1645
1698
  };
1646
- console.error("Stream error:", p), this.everConnected && this.notificationPort.pushNotification({
1699
+ console.error("Stream error:", m), this.everConnected && this.notificationPort.pushNotification({
1647
1700
  message: "Reiniciando a conexão com o servidor",
1648
1701
  type: "info",
1649
1702
  // Tagged so a host can recognise this one and draw its own affordance (a progress bar glued
1650
1703
  // to the page, say) instead of a toast, without matching on the copy.
1651
1704
  kind: "connection-restarting"
1652
- }), super.Message(D);
1705
+ }), super.Message(M);
1653
1706
  }, this.wsService.onOpen = () => {
1654
- this.everConnected = !0, this.sessionState.setConnectionStatus(F.Connected);
1655
- }, this.wsService.onReconnected = (p) => {
1656
- this.sessionState.setConnectionStatus(F.Connected);
1657
- }, this.wsService.onFirstToken = (p) => {
1658
- this.localEmitFirstToken(p);
1659
- }, this.wsService.onClose = (p, D) => {
1660
- p != H && this.sessionState.setConnectionStatus(F.Disconnected);
1707
+ this.everConnected = !0, this.sessionState.setConnectionStatus(k.Connected);
1708
+ }, this.wsService.onReconnected = (m) => {
1709
+ this.sessionState.setConnectionStatus(k.Connected);
1710
+ }, this.wsService.onFirstToken = (m) => {
1711
+ this.localEmitFirstToken(m);
1712
+ }, this.wsService.onClose = (m, M) => {
1713
+ console.log(`[AgentGateway] transport closed (code=${m}, reason="${M}") — ${m != B ? "flipping to Disconnected so the state manager takes over the redial." : "our own disconnect, leaving the connection status alone."}`), m != B && this.sessionState.setConnectionStatus(k.Disconnected);
1661
1714
  };
1662
1715
  }
1663
1716
  startStream(e) {
@@ -1667,7 +1720,7 @@ const Kt = "envision_agent_sessionId", Z = class Z extends G {
1667
1720
  return this.suspendState;
1668
1721
  }
1669
1722
  getStoredSessionId() {
1670
- const e = localStorage.getItem(Kt);
1723
+ const e = localStorage.getItem(jt);
1671
1724
  if (e)
1672
1725
  return e;
1673
1726
  }
@@ -1679,27 +1732,27 @@ const Kt = "envision_agent_sessionId", Z = class Z extends G {
1679
1732
  const s = this.interactionsMap.get(e);
1680
1733
  return s == null ? void 0 : s.turn_complete;
1681
1734
  }
1682
- async finalResponse(e, s, a) {
1683
- super.turnComplete(e, s, a);
1735
+ async finalResponse(e, s, o) {
1736
+ super.turnComplete(e, s, o);
1684
1737
  }
1685
1738
  stopStream(e = !0) {
1686
1739
  e && this.sessionState.setTurnOpen(!1), this.wsService && this.wsService.closeStream();
1687
1740
  }
1688
1741
  async suspend() {
1689
1742
  const e = this.wsService;
1690
- return new Promise(async (a, n) => {
1691
- let o = !1;
1743
+ return new Promise(async (o, n) => {
1744
+ let a = !1;
1692
1745
  e.onSuspended = () => {
1693
- o = !0;
1746
+ a = !0;
1694
1747
  }, e.suspendStream();
1695
1748
  try {
1696
1749
  let d = 0;
1697
- for (; !o && d < 5e3; )
1750
+ for (; !a && d < 5e3; )
1698
1751
  await this.sleep(100), d += 100;
1699
- if (o)
1752
+ if (a)
1700
1753
  if (this.currentIS) {
1701
1754
  const u = this.currentIS.interaction;
1702
- u.isSuspended = !0, this.sessionState.setCurrentMessage(u), this.sessionState.setTurnOpen(!1), a(!0);
1755
+ u.isSuspended = !0, this.sessionState.setCurrentMessage(u), this.sessionState.setTurnOpen(!1), o(!0);
1703
1756
  } else
1704
1757
  console.error("CurrentIS is null"), n("CurrentIS is null");
1705
1758
  else
@@ -1718,8 +1771,8 @@ const Kt = "envision_agent_sessionId", Z = class Z extends G {
1718
1771
  */
1719
1772
  answerHumanTool(e, s) {
1720
1773
  var n;
1721
- const a = (n = this.wsService.answerHumanTool) == null ? void 0 : n.bind(this.wsService);
1722
- return a ? a(e, s) : (console.warn("[AgentGateway] transport cannot deliver parked-tool answers", e), "queued");
1774
+ const o = (n = this.wsService.answerHumanTool) == null ? void 0 : n.bind(this.wsService);
1775
+ return o ? o(e, s) : (console.warn("[AgentGateway] transport cannot deliver parked-tool answers", e), "queued");
1723
1776
  }
1724
1777
  async cancelSuspend() {
1725
1778
  var s;
@@ -1730,11 +1783,11 @@ const Kt = "envision_agent_sessionId", Z = class Z extends G {
1730
1783
  return !0;
1731
1784
  }
1732
1785
  async openConnection(e, s) {
1733
- return this.lastConnectionPromise ? this.lastConnectionPromise : this.socketState == F.Disconnected ? (this.lastConnectionPromise = new Promise((a, n) => {
1734
- this.wsService.connect(e, s).then((o) => {
1735
- this.sessionId = o, a(o);
1736
- }).catch((o) => {
1737
- n(o);
1786
+ return this.lastConnectionPromise ? this.lastConnectionPromise : this.socketState == k.Disconnected ? (this.lastConnectionPromise = new Promise((o, n) => {
1787
+ this.wsService.connect(e, s).then((a) => {
1788
+ this.sessionId = a, o(a);
1789
+ }).catch((a) => {
1790
+ n(a);
1738
1791
  }).finally(() => {
1739
1792
  this.lastConnectionPromise = null;
1740
1793
  });
@@ -1754,30 +1807,60 @@ const Kt = "envision_agent_sessionId", Z = class Z extends G {
1754
1807
  }
1755
1808
  }
1756
1809
  simulateDisconnect(e = 4500, s = "Debug simulated disconnect") {
1757
- const a = this.wsService;
1758
- a != null && a.ws && a.ws.close(e, s);
1810
+ const o = this.wsService;
1811
+ o != null && o.ws && o.ws.close(e, s);
1759
1812
  }
1760
1813
  async sleep(e) {
1761
1814
  return new Promise((s) => setTimeout(s, e));
1762
1815
  }
1763
- // Send a message to the server via HTTP POST
1764
- async sendMessageInternal(e, s, a) {
1765
- var l, r, d, u, h, v, p, D;
1816
+ /**
1817
+ * Make sure the socket is OPEN before a send, redialling the SAME session when it is not.
1818
+ *
1819
+ * The socket can be down at send time for reasons the composer cannot see: the client's own
1820
+ * idle close (5 min without input), the server's (6 min without a message, code 4003), a dead
1821
+ * peer the heartbeat just detected, or a dial still in flight. Until this existed the send
1822
+ * threw `WebSocket is not connected` AFTER the user's turn was already on the transcript — or
1823
+ * the composer refused it outright — and the only way back was the 2 s heartbeat noticing
1824
+ * mouse movement. A send IS the activity that reconnect was waiting for, so dial here.
1825
+ *
1826
+ * `resume: true` keeps the replay cursor: if the socket died mid-turn the server replays what
1827
+ * we missed. `openConnection` de-duplicates against a dial already in flight (the state
1828
+ * manager's retry loop, a host's own bind), so concurrent callers share one socket. A
1829
+ * transport without `isConnected` semantics (the demo's fake gateway) is treated as up.
1830
+ */
1831
+ async ensureConnected() {
1832
+ const e = this.sessionId;
1833
+ if (this.wsService.isConnected()) {
1834
+ console.log(`[AgentGateway] send guard: socket is open (session ${e ?? "none"}, status ${this.sessionState.connectionStatus}) — sending straight away.`);
1835
+ return;
1836
+ }
1837
+ console.warn(`[AgentGateway] send guard: socket is DOWN at send time (session ${e ?? "none"}, status ${this.sessionState.connectionStatus}) — redialling with the replay cursor before sending.`), this.sessionState.setConnectionStatus(k.Connecting);
1838
+ const s = Date.now();
1839
+ try {
1840
+ const o = await this.openConnection(e, { resume: !0 });
1841
+ o !== e ? console.warn(`[AgentGateway] send guard: session ${e} could not be resumed; the server opened ${o} instead — this turn starts a new conversation.`) : console.log(`[AgentGateway] send guard: reconnected to ${o} in ${Date.now() - s}ms — sending now.`), this.sessionState.setConnectionStatus(k.Connected);
1842
+ } catch (o) {
1843
+ throw console.error(`[AgentGateway] send guard: redial FAILED after ${Date.now() - s}ms — the message was not sent.`, o), this.sessionState.setConnectionStatus(k.Disconnected), new Error(`Could not reconnect before sending: ${o}`);
1844
+ }
1845
+ }
1846
+ // Send a message to the server over the socket
1847
+ async sendMessageInternal(e, s, o) {
1848
+ var l, r, d, u, h, v, m, M;
1766
1849
  const n = this.suspendState;
1767
1850
  this.suspendState = !1;
1768
- const o = this.startInteraction(e.friendlyMessage ?? e.data, n);
1769
- if (this.registerInteractionCallId(o.interactionId, s), (l = e.userUi) != null && l.name && o.parts.push(N.fromUserUi(e.userUi.name, e.userUi.args)), !this.wsService)
1851
+ const a = this.startInteraction(e.friendlyMessage ?? e.data, n);
1852
+ if (this.registerInteractionCallId(a.interactionId, s), (l = e.userUi) != null && l.name && a.parts.push(_.fromUserUi(e.userUi.name, e.userUi.args)), !this.wsService)
1770
1853
  throw "no wsService created";
1771
1854
  if (!this.sessionId)
1772
1855
  throw "no session id set";
1773
1856
  if (!((r = this.config.agentConfig) != null && r.id))
1774
1857
  throw "Agent not selected";
1775
- return this.wsService.sendMessage({
1858
+ return this.sessionState.setLastActivity(), await this.ensureConnected(), this.wsService.sendMessage({
1776
1859
  Content: e.data,
1777
1860
  SessionId: this.sessionId,
1778
- Action: U.SendMessage,
1861
+ Action: F.SendMessage,
1779
1862
  ModelId: this.config.model,
1780
- InteractionId: o.interactionId,
1863
+ InteractionId: a.interactionId,
1781
1864
  AgentId: (d = this.config.agentConfig) == null ? void 0 : d.id,
1782
1865
  // Optional explicit C# class name on the server (e.g. "LlmAgentSessionReplay").
1783
1866
  // When set, AgentBootStrapService.GetAgent dispatches to that class directly
@@ -1791,20 +1874,20 @@ const Kt = "envision_agent_sessionId", Z = class Z extends G {
1791
1874
  },
1792
1875
  // Forward image attachments as a structured payload (PascalCase
1793
1876
  // keys to match the C# `Message.Images` / `MessageImage` model).
1794
- Images: (p = e.images) != null && p.length ? e.images.map((T) => ({ MimeType: T.mimeType, Data: T.data })) : void 0,
1877
+ Images: (m = e.images) != null && m.length ? e.images.map((T) => ({ MimeType: T.mimeType, Data: T.data })) : void 0,
1795
1878
  // Client-only UI representation for this turn (PascalCase to match the C# `Message.UserUi`
1796
1879
  // model). The server persists it as a UserUiContent sibling and strips it from the model
1797
1880
  // request; Content remains the only model-facing text.
1798
- UserUi: (D = e.userUi) != null && D.name ? { Name: e.userUi.name, Args: e.userUi.args } : void 0
1799
- }), this.localOpen(o.interactionId, "system"), Promise.resolve({
1800
- interaction: o,
1881
+ UserUi: (M = e.userUi) != null && M.name ? { Name: e.userUi.name, Args: e.userUi.args } : void 0
1882
+ }), this.localOpen(a.interactionId, "system"), Promise.resolve({
1883
+ interaction: a,
1801
1884
  success: !0
1802
1885
  });
1803
1886
  }
1804
1887
  };
1805
- f(Z, "AgentGatewayWSAsync");
1806
- let ut = Z;
1807
- const V = class V {
1888
+ f(tt, "AgentGatewayWSAsync");
1889
+ let dt = tt;
1890
+ const et = class et {
1808
1891
  constructor(t, e) {
1809
1892
  i(this, "cache", /* @__PURE__ */ new Map());
1810
1893
  i(this, "serverBaseUrl");
@@ -1812,7 +1895,7 @@ const V = class V {
1812
1895
  this.serverBaseUrl = t.replace(/\/$/, ""), this.accessToken = e;
1813
1896
  }
1814
1897
  get headers() {
1815
- return { Authorization: `Bearer ${bt(this.accessToken)}` };
1898
+ return { Authorization: `Bearer ${Rt(this.accessToken)}` };
1816
1899
  }
1817
1900
  async init() {
1818
1901
  }
@@ -1841,8 +1924,8 @@ const V = class V {
1841
1924
  headers: this.headers
1842
1925
  });
1843
1926
  if (!s.ok) return null;
1844
- const a = await s.json();
1845
- return this.cache.set(a.id, a), a;
1927
+ const o = await s.json();
1928
+ return this.cache.set(o.id, o), o;
1846
1929
  } catch {
1847
1930
  return null;
1848
1931
  }
@@ -1859,17 +1942,17 @@ const V = class V {
1859
1942
  }
1860
1943
  }
1861
1944
  };
1862
- f(V, "HttpArtifactService");
1863
- let dt = V;
1945
+ f(et, "HttpArtifactService");
1946
+ let ft = et;
1864
1947
  export {
1865
- G as A,
1866
- q as E,
1867
- dt as H,
1868
- B as I,
1869
- at as L,
1870
- ot as M,
1871
- ht as W,
1872
- ut as a,
1873
- ne as u
1948
+ z as A,
1949
+ K as E,
1950
+ ft as H,
1951
+ x as I,
1952
+ rt as L,
1953
+ ct as M,
1954
+ ut as W,
1955
+ dt as a,
1956
+ re as u
1874
1957
  };
1875
- //# sourceMappingURL=httpArtifactService-CqEs3x-Q.js.map
1958
+ //# sourceMappingURL=httpArtifactService-CO7Kl4xr.js.map