@aintela/chat 0.10.0 → 0.11.1

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 (28) hide show
  1. package/dist/components.js +5198 -5072
  2. package/dist/components.js.map +1 -1
  3. package/dist/{detachedRunActivity-DWOR3cAC.js → detachedRunActivity-CCrlilHK.js} +999 -913
  4. package/dist/detachedRunActivity-CCrlilHK.js.map +1 -0
  5. package/dist/hooks.js +1 -1
  6. package/dist/{httpSessionService-BIkDesYB.js → httpSessionService-BLiZMoLb.js} +117 -106
  7. package/dist/httpSessionService-BLiZMoLb.js.map +1 -0
  8. package/dist/index.js +4 -4
  9. package/dist/models.js +1 -1
  10. package/dist/{serializer-DvR3nOcf.js → serializer-DvfyE4_t.js} +488 -461
  11. package/dist/serializer-DvfyE4_t.js.map +1 -0
  12. package/dist/services.js +2 -2
  13. package/dist/src/components/AiChat/ChatPane/chatTurnLiveQuestion.test.d.ts +1 -0
  14. package/dist/src/components/AiChat/stateConfiguration.d.ts +19 -0
  15. package/dist/src/components/Library/markdownSafety.d.ts +7 -0
  16. package/dist/src/components/Library/markdownSafety.test.d.ts +1 -0
  17. package/dist/src/components/v2/PromptV2.d.ts +6 -0
  18. package/dist/src/models/Interaction.d.ts +5 -0
  19. package/dist/src/models/enums.d.ts +6 -1
  20. package/dist/src/models/semanticKernelModel/models.d.ts +10 -1
  21. package/dist/src/services/servers/AgentGatewayWSAsync.d.ts +31 -0
  22. package/dist/src/services/servers/gatewayQueueMessage.test.d.ts +1 -0
  23. package/dist/{useChatSessions-CyFKVtkk.js → useChatSessions-BI3bHoOh.js} +2 -2
  24. package/dist/{useChatSessions-CyFKVtkk.js.map → useChatSessions-BI3bHoOh.js.map} +1 -1
  25. package/package.json +3 -2
  26. package/dist/detachedRunActivity-DWOR3cAC.js.map +0 -1
  27. package/dist/httpSessionService-BIkDesYB.js.map +0 -1
  28. package/dist/serializer-DvR3nOcf.js.map +0 -1
@@ -1,22 +1,22 @@
1
- var wt = Object.defineProperty;
2
- var bt = (i, t, e) => t in i ? wt(i, t, { enumerable: !0, configurable: !0, writable: !0, value: e }) : i[t] = e;
3
- var h = (i, t) => wt(i, "name", { value: t, configurable: !0 });
4
- var o = (i, t, e) => bt(i, typeof t != "symbol" ? t + "" : t, e);
5
- import { i as N, E as I, S as x, z as St, C as U, j as Lt, L as Pt, P as z, n as Ft, q as _t, T as Nt, o as Ut, s as et, B as xt } from "./serializer-DvR3nOcf.js";
6
- import { format as qt } from "date-fns";
7
- import Wt from "lodash";
8
- import { C, P as Bt } from "./Prompt-DZb7OaPp.js";
9
- import { d as Gt } from "./environmentUtils-VZNTCzEE.js";
10
- import { r as zt } from "./httpSessionService-BIkDesYB.js";
11
- const Q = {
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 F, 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-DvfyE4_t.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-BLiZMoLb.js";
11
+ const K = {
12
12
  PROMPTS: "envision-prompts"
13
- }, Ht = 50, nt = class nt {
13
+ }, He = 50, ne = class ne {
14
14
  getPrompts() {
15
15
  try {
16
- const t = localStorage.getItem(Q.PROMPTS);
17
- return t ? JSON.parse(t).sort((s, n) => new Date(n.created).getTime() - new Date(s.created).getTime()) : [];
18
- } catch (t) {
19
- return console.error("Error loading prompts:", t), [];
16
+ const e = localStorage.getItem(K.PROMPTS);
17
+ return e ? JSON.parse(e).sort((s, n) => new Date(n.created).getTime() - new Date(s.created).getTime()) : [];
18
+ } catch (e) {
19
+ return console.error("Error loading prompts:", e), [];
20
20
  }
21
21
  }
22
22
  /**
@@ -37,161 +37,161 @@ const Q = {
37
37
  * separate entries — that is deliberate, not an oversight: normalising them
38
38
  * would mean re-surfacing text the user never typed.
39
39
  */
40
- storePrompt(t) {
40
+ storePrompt(e) {
41
41
  try {
42
- const e = this.getPrompts().filter((s) => s.promptText !== t.promptText);
43
- e.unshift(t), localStorage.setItem(Q.PROMPTS, JSON.stringify(e.slice(0, Ht)));
44
- } catch (e) {
45
- console.error("Error storing prompt:", e);
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)));
44
+ } catch (t) {
45
+ console.error("Error storing prompt:", t);
46
46
  }
47
47
  }
48
48
  clearAllPrompts() {
49
49
  try {
50
- localStorage.removeItem(Q.PROMPTS);
51
- } catch (t) {
52
- console.error("Error clearing prompts:", t);
50
+ localStorage.removeItem(K.PROMPTS);
51
+ } catch (e) {
52
+ console.error("Error clearing prompts:", e);
53
53
  }
54
54
  }
55
55
  };
56
- h(nt, "LocalStorageService");
57
- let It = nt;
58
- const Re = /* @__PURE__ */ h((i) => {
59
- const t = i.getPrompts(), e = t.length;
60
- if (e > 0) {
61
- const s = t[0].promptText, n = t[t.length - 1].promptText, r = t[0].created;
62
- return { promptState: e + "_" + s + "_" + n + "_" + r };
56
+ h(ne, "LocalStorageService");
57
+ let Ie = ne;
58
+ const Rt = /* @__PURE__ */ h((i) => {
59
+ const e = i.getPrompts(), t = e.length;
60
+ if (t > 0) {
61
+ const s = e[0].promptText, n = e[e.length - 1].promptText, r = e[0].created;
62
+ return { promptState: t + "_" + s + "_" + n + "_" + r };
63
63
  } else
64
64
  return { promptState: "0" };
65
- }, "usePromptState"), it = class it {
65
+ }, "usePromptState"), ie = class ie {
66
66
  constructor() {
67
- o(this, "artifactGenerated", "artifactGenerated");
68
- o(this, "artifactSelected", "artifactSelected");
69
- o(this, "gatewayMessage", "gatewayMessage");
70
- o(this, "gatewayTurnComplete", "gatewayTurnComplete");
71
- o(this, "gatewayStreamError", "gatewayStreamError");
72
- o(this, "gatewayConnected", "gatewayConnected");
73
- o(this, "gatewayTurnOpen", "gatewayTurnOpen");
74
- o(this, "gatewayFunctionResponse", "gatewayFunctionResponse");
75
- o(this, "uiAskQuestion", "uiAskQuestion");
76
- o(this, "gatewayEndMessageData", "gatewayEndMessageData");
77
- o(this, "onMessageSent", "onMessageSent");
78
- o(this, "onMessageError", "onMessageError");
79
- o(this, "onToolEvent", "onToolEvent");
80
- o(this, "gatewayFirstToken", "gatewayFirstToken");
67
+ a(this, "artifactGenerated", "artifactGenerated");
68
+ a(this, "artifactSelected", "artifactSelected");
69
+ a(this, "gatewayMessage", "gatewayMessage");
70
+ a(this, "gatewayTurnComplete", "gatewayTurnComplete");
71
+ a(this, "gatewayStreamError", "gatewayStreamError");
72
+ a(this, "gatewayConnected", "gatewayConnected");
73
+ a(this, "gatewayTurnOpen", "gatewayTurnOpen");
74
+ a(this, "gatewayFunctionResponse", "gatewayFunctionResponse");
75
+ a(this, "uiAskQuestion", "uiAskQuestion");
76
+ a(this, "gatewayEndMessageData", "gatewayEndMessageData");
77
+ a(this, "onMessageSent", "onMessageSent");
78
+ a(this, "onMessageError", "onMessageError");
79
+ a(this, "onToolEvent", "onToolEvent");
80
+ a(this, "gatewayFirstToken", "gatewayFirstToken");
81
81
  }
82
82
  };
83
- h(it, "EventTypes");
84
- let X = it;
85
- const d = new X(), rt = class rt {
83
+ h(ie, "EventTypes");
84
+ let X = ie;
85
+ const d = new X(), re = class re {
86
86
  constructor() {
87
- o(this, "listeners", {});
87
+ a(this, "listeners", {});
88
88
  }
89
- callListeners(t, ...e) {
90
- const s = this.listeners[t];
89
+ callListeners(e, ...t) {
90
+ const s = this.listeners[e];
91
91
  if (s) {
92
- const n = s.map((r) => r(...e));
92
+ const n = s.map((r) => r(...t));
93
93
  Promise.all(n).catch((r) => {
94
- console.error(`Lost error in one of the listeners of the event: ${t}, listeners: ${s.length}, error: ${r}`, s);
94
+ console.error(`Lost error in one of the listeners of the event: ${e}, listeners: ${s.length}, error: ${r}`, s);
95
95
  });
96
96
  }
97
97
  }
98
- addListener(t, e) {
99
- this.listeners[t] || (this.listeners[t] = []), this.listeners[t].push(e);
98
+ addListener(e, t) {
99
+ this.listeners[e] || (this.listeners[e] = []), this.listeners[e].push(t);
100
100
  }
101
- removeListener(t, e) {
102
- this.listeners[t] && (this.listeners[t] = this.listeners[t].filter((s) => s !== e));
101
+ removeListener(e, t) {
102
+ this.listeners[e] && (this.listeners[e] = this.listeners[e].filter((s) => s !== t));
103
103
  }
104
104
  /* typed artifact listeners */
105
- artifactOnGenerated(t) {
106
- this.addListener(d.artifactGenerated, t);
105
+ artifactOnGenerated(e) {
106
+ this.addListener(d.artifactGenerated, e);
107
107
  }
108
- artifactEmitGenerated(t) {
109
- this.callListeners(d.artifactGenerated, t);
108
+ artifactEmitGenerated(e) {
109
+ this.callListeners(d.artifactGenerated, e);
110
110
  }
111
- artifactOffGenerated(t) {
112
- this.removeListener(d.artifactGenerated, t);
111
+ artifactOffGenerated(e) {
112
+ this.removeListener(d.artifactGenerated, e);
113
113
  }
114
- artifactOnSelected(t) {
115
- this.addListener(d.artifactSelected, t);
114
+ artifactOnSelected(e) {
115
+ this.addListener(d.artifactSelected, e);
116
116
  }
117
- artifactEmitSelected(t) {
118
- this.callListeners(d.artifactSelected, t);
117
+ artifactEmitSelected(e) {
118
+ this.callListeners(d.artifactSelected, e);
119
119
  }
120
- artifactOffSelected(t) {
121
- this.removeListener(d.artifactSelected, t);
120
+ artifactOffSelected(e) {
121
+ this.removeListener(d.artifactSelected, e);
122
122
  }
123
- gatewayOnMessage(t) {
124
- this.addListener(d.gatewayMessage, t);
123
+ gatewayOnMessage(e) {
124
+ this.addListener(d.gatewayMessage, e);
125
125
  }
126
- gatewayEmitMessage(t) {
127
- this.callListeners(d.gatewayMessage, t);
126
+ gatewayEmitMessage(e) {
127
+ this.callListeners(d.gatewayMessage, e);
128
128
  }
129
- gatewayOffMessage(t) {
130
- this.removeListener(d.gatewayMessage, t);
129
+ gatewayOffMessage(e) {
130
+ this.removeListener(d.gatewayMessage, e);
131
131
  }
132
- gatewayOnTurnComplete(t) {
133
- this.addListener(d.gatewayTurnComplete, t);
132
+ gatewayOnTurnComplete(e) {
133
+ this.addListener(d.gatewayTurnComplete, e);
134
134
  }
135
- gatewayEmitTurnComplete(t, e) {
136
- this.callListeners(d.gatewayTurnComplete, t, e);
135
+ gatewayEmitTurnComplete(e, t) {
136
+ this.callListeners(d.gatewayTurnComplete, e, t);
137
137
  }
138
- gatewayOffTurnComplete(t) {
139
- this.removeListener(d.gatewayTurnComplete, t);
138
+ gatewayOffTurnComplete(e) {
139
+ this.removeListener(d.gatewayTurnComplete, e);
140
140
  }
141
- gatewayOnTurnOpen(t) {
142
- this.addListener(d.gatewayTurnOpen, t);
141
+ gatewayOnTurnOpen(e) {
142
+ this.addListener(d.gatewayTurnOpen, e);
143
143
  }
144
- gatewayEmitTurnOpen(t) {
145
- this.callListeners(d.gatewayTurnOpen, t);
144
+ gatewayEmitTurnOpen(e) {
145
+ this.callListeners(d.gatewayTurnOpen, e);
146
146
  }
147
- gatewayOffTurnOpen(t) {
148
- this.removeListener(d.gatewayTurnOpen, t);
147
+ gatewayOffTurnOpen(e) {
148
+ this.removeListener(d.gatewayTurnOpen, e);
149
149
  }
150
- gatewayOnStreamError(t) {
151
- this.addListener(d.gatewayStreamError, t);
150
+ gatewayOnStreamError(e) {
151
+ this.addListener(d.gatewayStreamError, e);
152
152
  }
153
- gatewayEmitStreamError(t) {
154
- this.callListeners(d.gatewayStreamError, t);
153
+ gatewayEmitStreamError(e) {
154
+ this.callListeners(d.gatewayStreamError, e);
155
155
  }
156
- gatewayOffStreamError(t) {
157
- this.removeListener(d.gatewayStreamError, t);
156
+ gatewayOffStreamError(e) {
157
+ this.removeListener(d.gatewayStreamError, e);
158
158
  }
159
159
  /** The live socket is up and the session proven — on the first open and on every reconnect (`info.reconnect`). */
160
- gatewayOnConnected(t) {
161
- this.addListener(d.gatewayConnected, t);
160
+ gatewayOnConnected(e) {
161
+ this.addListener(d.gatewayConnected, e);
162
162
  }
163
- gatewayEmitConnected(t, e) {
164
- this.callListeners(d.gatewayConnected, t, e);
163
+ gatewayEmitConnected(e, t) {
164
+ this.callListeners(d.gatewayConnected, e, t);
165
165
  }
166
- gatewayOffConnected(t) {
167
- this.removeListener(d.gatewayConnected, t);
166
+ gatewayOffConnected(e) {
167
+ this.removeListener(d.gatewayConnected, e);
168
168
  }
169
- chatOnMessageSent(t) {
170
- this.addListener(d.onMessageSent, t);
169
+ chatOnMessageSent(e) {
170
+ this.addListener(d.onMessageSent, e);
171
171
  }
172
- chatOffMessageSent(t) {
173
- this.removeListener(d.onMessageSent, t);
172
+ chatOffMessageSent(e) {
173
+ this.removeListener(d.onMessageSent, e);
174
174
  }
175
- ChatEmitMessageSent(t, e) {
176
- this.callListeners(d.onMessageSent, t, e);
175
+ ChatEmitMessageSent(e, t) {
176
+ this.callListeners(d.onMessageSent, e, t);
177
177
  }
178
- chatOnMessageError(t) {
179
- this.addListener(d.onMessageError, t);
178
+ chatOnMessageError(e) {
179
+ this.addListener(d.onMessageError, e);
180
180
  }
181
- chatOffMessageError(t) {
182
- this.removeListener(d.onMessageError, t);
181
+ chatOffMessageError(e) {
182
+ this.removeListener(d.onMessageError, e);
183
183
  }
184
- ChatEmitMessageError(t) {
185
- this.callListeners(d.onMessageError, t);
184
+ ChatEmitMessageError(e) {
185
+ this.callListeners(d.onMessageError, e);
186
186
  }
187
- gatewayOnFunctionResponse(t) {
188
- this.addListener(d.gatewayFunctionResponse, t);
187
+ gatewayOnFunctionResponse(e) {
188
+ this.addListener(d.gatewayFunctionResponse, e);
189
189
  }
190
- gatewayEmitFunctionResponse(t) {
191
- this.callListeners(d.gatewayFunctionResponse, t);
190
+ gatewayEmitFunctionResponse(e) {
191
+ this.callListeners(d.gatewayFunctionResponse, e);
192
192
  }
193
- gatewayOffFunctionResponse(t) {
194
- this.removeListener(d.gatewayFunctionResponse, t);
193
+ gatewayOffFunctionResponse(e) {
194
+ this.removeListener(d.gatewayFunctionResponse, e);
195
195
  }
196
196
  // "Re-ask this" — a `#ask-…` link in the transcript, carrying the link's TEXT as the question.
197
197
  // An event rather than component state because the prompt that must send it is not always
@@ -199,94 +199,94 @@ const d = new X(), rt = class rt {
199
199
  // its tree, and that instance cannot see ChatPane's `useState`. Whichever prompt is mounted
200
200
  // listens; ChatPane publishes only when its internal one is suppressed, so the question is
201
201
  // never sent twice.
202
- uiOnAskQuestion(t) {
203
- this.addListener(d.uiAskQuestion, t);
202
+ uiOnAskQuestion(e) {
203
+ this.addListener(d.uiAskQuestion, e);
204
204
  }
205
- uiEmitAskQuestion(t) {
206
- this.callListeners(d.uiAskQuestion, t);
205
+ uiEmitAskQuestion(e) {
206
+ this.callListeners(d.uiAskQuestion, e);
207
207
  }
208
- uiOffAskQuestion(t) {
209
- this.removeListener(d.uiAskQuestion, t);
208
+ uiOffAskQuestion(e) {
209
+ this.removeListener(d.uiAskQuestion, e);
210
210
  }
211
- gatewayOnEndMessageData(t) {
212
- this.addListener(d.gatewayEndMessageData, t);
211
+ gatewayOnEndMessageData(e) {
212
+ this.addListener(d.gatewayEndMessageData, e);
213
213
  }
214
- gatewayEmitEndMessageData(t) {
215
- this.callListeners(d.gatewayEndMessageData, t);
214
+ gatewayEmitEndMessageData(e) {
215
+ this.callListeners(d.gatewayEndMessageData, e);
216
216
  }
217
- gatewayOffEndMessageData(t) {
218
- this.removeListener(d.gatewayEndMessageData, t);
217
+ gatewayOffEndMessageData(e) {
218
+ this.removeListener(d.gatewayEndMessageData, e);
219
219
  }
220
- gatewayOnToolEvent(t) {
221
- this.addListener(d.onToolEvent, t);
220
+ gatewayOnToolEvent(e) {
221
+ this.addListener(d.onToolEvent, e);
222
222
  }
223
- gatewayEmitToolEvent(t, e, s) {
224
- this.callListeners(d.onToolEvent, t, e, s);
223
+ gatewayEmitToolEvent(e, t, s) {
224
+ this.callListeners(d.onToolEvent, e, t, s);
225
225
  }
226
- gatewayOffToolEvent(t) {
227
- this.removeListener(d.onToolEvent, t);
226
+ gatewayOffToolEvent(e) {
227
+ this.removeListener(d.onToolEvent, e);
228
228
  }
229
- gatewayOnFirstToken(t) {
230
- this.addListener(d.gatewayFirstToken, t);
229
+ gatewayOnFirstToken(e) {
230
+ this.addListener(d.gatewayFirstToken, e);
231
231
  }
232
- gatewayEmitFirstToken(t) {
233
- this.callListeners(d.gatewayFirstToken, t);
232
+ gatewayEmitFirstToken(e) {
233
+ this.callListeners(d.gatewayFirstToken, e);
234
234
  }
235
- gatewayOffFirstToken(t) {
236
- this.removeListener(d.gatewayFirstToken, t);
235
+ gatewayOffFirstToken(e) {
236
+ this.removeListener(d.gatewayFirstToken, e);
237
237
  }
238
238
  };
239
- h(rt, "EventBusService");
240
- let Tt = rt;
241
- const Jt = 2e3;
242
- function q(i) {
239
+ h(re, "EventBusService");
240
+ let Te = re;
241
+ const Qe = 2e3;
242
+ function x(i) {
243
243
  i.parts === i.prev.parts && (i.parts = i.prev.parts.slice());
244
244
  }
245
- h(q, "ownParts");
246
- function J(i) {
245
+ h(x, "ownParts");
246
+ function Q(i) {
247
247
  i.functionMap === i.prev.functionMap && (i.functionMap = new Map(i.functionMap));
248
248
  }
249
- h(J, "ownFunctionMap");
250
- const jt = /* @__PURE__ */ h((i) => i == I.FunctionCall || i == I.PartialFunctionCall, "isFunctionCall"), Kt = /* @__PURE__ */ h((i) => i == I.FunctionResponse, "isFunctionResponse"), Ot = /* @__PURE__ */ h((i) => i.parts.length + 1 + "-" + i.prev.interactionId, "nextPartId");
251
- function Qt(i, t) {
252
- var e, s, n, r, a;
253
- return !!(!t || i.mustPush || i.mustPush === !1 && (i.eventType !== t.eventType || ((e = i.functionDetails) == null ? void 0 : e.id) !== ((s = t.functionDetails) == null ? void 0 : s.id)) || i.textAppendable && (((r = (n = t.thoughtDetails) == null ? void 0 : n.text) == null ? void 0 : r.length) ?? ((a = t.text) == null ? void 0 : a.length) ?? 0) > Jt);
249
+ 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) {
252
+ 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);
254
254
  }
255
- h(Qt, "opensNewPart");
256
- function Yt(i, t) {
257
- const e = t.functionDetails.id, s = t.functionDetails.clientOutput, n = i.parts.findIndex((r) => {
258
- var a;
259
- return ((a = r.functionDetails) == null ? void 0 : a.id) === e;
255
+ h(Ke, "opensNewPart");
256
+ function Ye(i, e) {
257
+ const t = e.functionDetails.id, s = e.functionDetails.clientOutput, n = i.parts.findIndex((r) => {
258
+ var o;
259
+ return ((o = r.functionDetails) == null ? void 0 : o.id) === t;
260
260
  });
261
261
  if (n > -1) {
262
- const r = i.parts[n], a = {
262
+ const r = i.parts[n], o = {
263
263
  ...r,
264
264
  functionDetails: {
265
265
  ...r.functionDetails,
266
266
  clientOutput: s ?? r.functionDetails.clientOutput,
267
267
  // Sticky true-wins: this event IS the park, and a later merge must not clear it.
268
- parked: t.functionDetails.parked === !0 || r.functionDetails.parked === !0
268
+ parked: e.functionDetails.parked === !0 || r.functionDetails.parked === !0
269
269
  }
270
270
  };
271
- q(i), i.parts[n] = a, J(i), i.functionMap.set(e, a);
271
+ x(i), i.parts[n] = o, Q(i), i.functionMap.set(t, o);
272
272
  } else {
273
273
  const r = {
274
- ...t,
275
- id: Ot(i),
276
- functionDetails: { ...t.functionDetails, silent: !0 }
274
+ ...e,
275
+ id: Oe(i),
276
+ functionDetails: { ...e.functionDetails, silent: !0 }
277
277
  };
278
- q(i), i.parts.push(r), J(i), i.functionMap.set(e, r);
278
+ x(i), i.parts.push(r), Q(i), i.functionMap.set(t, r);
279
279
  }
280
280
  }
281
- h(Yt, "foldClientOutput");
282
- function Xt(i, t, e, s, n) {
283
- var p;
284
- const r = i.parts.findIndex((w) => {
281
+ h(Ye, "foldClientOutput");
282
+ function Xe(i, e, t, s, n) {
283
+ var g;
284
+ const r = i.parts.findIndex((m) => {
285
285
  var u;
286
- return ((u = w.functionDetails) == null ? void 0 : u.id) === s;
287
- }), a = r > -1 ? i.parts[r] : e, c = t.functionDetails, l = a.functionDetails, f = {
288
- ...a,
289
- eventType: t.eventType,
286
+ return ((u = m.functionDetails) == null ? void 0 : u.id) === s;
287
+ }), o = r > -1 ? i.parts[r] : t, c = e.functionDetails, l = o.functionDetails, f = {
288
+ ...o,
289
+ eventType: e.eventType,
290
290
  functionDetails: {
291
291
  id: l.id,
292
292
  name: c.name ?? l.name,
@@ -312,126 +312,126 @@ function Xt(i, t, e, s, n) {
312
312
  parked: c.parked === !0 || l.parked === !0
313
313
  }
314
314
  };
315
- J(i), i.functionMap.set(s, f), f.eventType === I.FunctionResponse && ((p = n == null ? void 0 : n.onFunctionResponse) == null || p.call(n, f.functionDetails)), r > -1 && (q(i), i.parts[r] = f);
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);
316
316
  }
317
- h(Xt, "foldFunctionEvent");
318
- function Vt(i, t, e, s) {
319
- s && t.functionDetails && (J(i), i.functionMap.set(s, t));
317
+ h(Xe, "foldFunctionEvent");
318
+ function Ve(i, e, t, s) {
319
+ s && e.functionDetails && (Q(i), i.functionMap.set(s, e));
320
320
  const n = i.prev.parts[i.prev.parts.length - 1] ?? null;
321
- n && n.textAppendable && (q(i), i.parts[i.parts.length - 1] = { ...n, ended: /* @__PURE__ */ new Date() });
321
+ n && n.textAppendable && (x(i), i.parts[i.parts.length - 1] = { ...n, ended: /* @__PURE__ */ new Date() });
322
322
  const r = {
323
- ...t,
324
- id: Ot(i),
325
- partial: e.partial
323
+ ...e,
324
+ id: Oe(i),
325
+ partial: t.partial
326
326
  };
327
327
  i.parts = [...i.parts, r];
328
328
  }
329
- h(Vt, "openPart");
330
- function Zt(i, t, e, s) {
329
+ h(Ve, "openPart");
330
+ function Ze(i, e, t, s) {
331
331
  const n = i.parts[i.parts.length - 1] ?? null;
332
332
  if (!n) return;
333
333
  const r = {
334
334
  ...n,
335
- partial: e.partial,
335
+ partial: t.partial,
336
336
  textDetails: n.textDetails ? { ...n.textDetails } : { version: 0 }
337
337
  };
338
- if (e.partial) {
339
- if (r.textDetails.version++, s || (r.text = (n.text ?? "") + (t.text ?? "")), !s && t.thoughtDetails && r.thoughtDetails) {
340
- const a = t.thoughtDetails.text;
341
- (a.length >= 50 || a.length < 50 && a !== r.thoughtDetails.text) && (r.thoughtDetails = { ...r.thoughtDetails, text: r.thoughtDetails.text + a });
338
+ if (t.partial) {
339
+ if (r.textDetails.version++, s || (r.text = (n.text ?? "") + (e.text ?? "")), !s && e.thoughtDetails && r.thoughtDetails) {
340
+ const o = e.thoughtDetails.text;
341
+ (o.length >= 50 || o.length < 50 && o !== r.thoughtDetails.text) && (r.thoughtDetails = { ...r.thoughtDetails, text: r.thoughtDetails.text + o });
342
342
  }
343
343
  } else
344
- r.text = t.text ?? "", r.textDetails.version++, t.thoughtDetails && (r.thoughtDetails = { ...t.thoughtDetails, text: t.thoughtDetails.text.trim() });
345
- q(i), i.parts[i.parts.length - 1] = r;
344
+ 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;
346
346
  }
347
- h(Zt, "appendText");
348
- function te(i, t) {
349
- if (!t || t.length === 0) return i;
350
- const e = i.slice();
351
- for (const s of t) {
352
- const n = s.toArtifact(), r = e.findIndex((a) => a.id === n.id);
353
- r === -1 ? e.push(n) : e[r] = n;
347
+ h(Ze, "appendText");
348
+ function et(i, e) {
349
+ if (!e || e.length === 0) return i;
350
+ const t = i.slice();
351
+ for (const s of e) {
352
+ const n = s.toArtifact(), r = t.findIndex((o) => o.id === n.id);
353
+ r === -1 ? t.push(n) : t[r] = n;
354
354
  }
355
- return e;
355
+ return t;
356
356
  }
357
- h(te, "mergeArtifacts");
358
- function ee(i, t, e) {
357
+ h(et, "mergeArtifacts");
358
+ function tt(i, e, t) {
359
359
  var c, l;
360
- const s = N.FlatParts(t == null ? void 0 : t.parts), n = i.parts[i.parts.length - 1] ?? null, r = {
360
+ const s = U.FlatParts(e == null ? void 0 : e.parts), n = i.parts[i.parts.length - 1] ?? null, r = {
361
361
  prev: i,
362
362
  parts: i.parts,
363
363
  functionMap: i.functionMap ?? /* @__PURE__ */ new Map()
364
364
  };
365
- let a = !1;
365
+ let o = !1;
366
366
  if (s) {
367
367
  if (s.eventType === I.FunctionClientOutput && !!((c = s.functionDetails) != null && c.id))
368
- Yt(r, s);
369
- else if (Qt(s, n)) {
370
- const p = jt(s.eventType) || Kt(s.eventType), w = p ? (l = s.functionDetails) == null ? void 0 : l.id : void 0;
371
- p && !w && console.error("Got isCall or isResponse without a callId", s);
372
- const u = w ? r.functionMap.get(w) : void 0;
373
- u && w && s.functionDetails ? Xt(r, s, u, w, e) : (Vt(r, s, t, w), a = !0);
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;
371
+ g && !m && console.error("Got isCall or isResponse without a callId", s);
372
+ 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);
374
374
  }
375
- s.textAppendable && Zt(r, s, t, a);
375
+ s.textAppendable && Ze(r, s, e, o);
376
376
  }
377
377
  return {
378
378
  ...i,
379
379
  version: i.version + 1,
380
380
  parts: r.parts,
381
- artifactData: te(i.artifactData ?? [], t.llmArtifacts),
381
+ artifactData: et(i.artifactData ?? [], e.llmArtifacts),
382
382
  functionMap: r.functionMap,
383
- turn_complete: t.turn_complete,
384
- partial: t.partial,
385
- asyncFinalResponse: t.asyncFinalResponse,
386
- agent: t.agent ?? i.agent
383
+ turn_complete: e.turn_complete,
384
+ partial: e.partial,
385
+ asyncFinalResponse: e.asyncFinalResponse,
386
+ agent: e.agent ?? i.agent
387
387
  };
388
388
  }
389
- h(ee, "reduceInteraction");
390
- const ot = class ot {
391
- constructor(t, e) {
392
- o(this, "interaction");
393
- o(this, "eventBusService");
394
- this.interaction = t, this.eventBusService = e;
389
+ h(tt, "reduceInteraction");
390
+ const oe = class oe {
391
+ constructor(e, t) {
392
+ a(this, "interaction");
393
+ a(this, "eventBusService");
394
+ this.interaction = e, this.eventBusService = t;
395
395
  }
396
396
  /**
397
397
  * Computes the next interaction from a server event and makes it current.
398
398
  * Pure with respect to the previous tree: snapshots already handed out to
399
399
  * throttled subscribers cannot diverge from live state.
400
400
  */
401
- merge(t) {
402
- const e = ee(this.interaction, t, {
401
+ merge(e) {
402
+ const t = tt(this.interaction, e, {
403
403
  onFunctionResponse: /* @__PURE__ */ h((s) => this.eventBusService.gatewayEmitFunctionResponse(s), "onFunctionResponse")
404
404
  });
405
- return this.interaction = e, e;
405
+ return this.interaction = t, t;
406
406
  }
407
407
  };
408
- h(ot, "InteractionService");
409
- let j = ot;
410
- const kt = 4001, se = 4002, Dt = 4004, ne = 4100, H = 500, ie = 2e4, re = 1e3, oe = 0.2, _ = 300 * 1e3, ae = 0.75, ce = 2e3, S = "[Connection]", at = class at {
411
- constructor(t) {
412
- o(this, "ports");
413
- o(this, "state");
414
- o(this, "now");
415
- o(this, "target", null);
416
- o(this, "inflight", null);
417
- o(this, "retryTimer", null);
418
- o(this, "idleTimer", null);
419
- o(this, "wait", H);
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 {
411
+ constructor(e) {
412
+ a(this, "ports");
413
+ a(this, "state");
414
+ a(this, "now");
415
+ a(this, "target", null);
416
+ a(this, "inflight", null);
417
+ a(this, "retryTimer", null);
418
+ a(this, "idleTimer", null);
419
+ a(this, "wait", H);
420
420
  /** Consecutive failed attempts since the last proven connection. */
421
- o(this, "attempt", 0);
422
- o(this, "halted", null);
421
+ a(this, "attempt", 0);
422
+ a(this, "halted", null);
423
423
  /** The code of the last close the transport reported, consumed by the next dial failure. */
424
- o(this, "lastCloseCode", null);
425
- o(this, "everConnected", !1);
426
- o(this, "idleWarningLogged", !1);
427
- this.ports = t, this.now = t.now ?? (() => Date.now()), this.state = t.store.getState(), t.store.subscribe((e) => {
428
- this.state = e;
424
+ a(this, "lastCloseCode", null);
425
+ a(this, "everConnected", !1);
426
+ a(this, "idleWarningLogged", !1);
427
+ this.ports = e, this.now = e.now ?? (() => Date.now()), this.state = e.store.getState(), e.store.subscribe((t) => {
428
+ this.state = t;
429
429
  });
430
430
  }
431
431
  // ─── Queries ────────────────────────────────────────────────────────────
432
432
  get sessionId() {
433
- var t;
434
- return (t = this.target) == null ? void 0 : t.sessionId;
433
+ var e;
434
+ return (e = this.target) == null ? void 0 : e.sessionId;
435
435
  }
436
436
  get isSupervising() {
437
437
  return this.target !== null;
@@ -448,8 +448,8 @@ const kt = 4001, se = 4002, Dt = 4004, ne = 4100, H = 500, ie = 2e4, re = 1e3, o
448
448
  }
449
449
  /** Connected by the store AND by the transport. */
450
450
  get isUp() {
451
- var t, e;
452
- return this.state.connectionStatus === C.Connected && (((e = (t = this.ports).isConnected) == null ? void 0 : e.call(t)) ?? !0);
451
+ var e, t;
452
+ return this.state.connectionStatus === E.Connected && (((t = (e = this.ports).isConnected) == null ? void 0 : t.call(e)) ?? !0);
453
453
  }
454
454
  // ─── Commands ───────────────────────────────────────────────────────────
455
455
  /**
@@ -459,35 +459,35 @@ const kt = 4001, se = 4002, Dt = 4004, ne = 4100, H = 500, ie = 2e4, re = 1e3, o
459
459
  * joins the dial in flight or returns the open socket's id; calling it for a different session
460
460
  * hangs up the current one first.
461
461
  */
462
- open(t, e) {
463
- if (this.target && this.sameTarget(t)) {
462
+ open(e, t) {
463
+ if (this.target && this.sameTarget(e)) {
464
464
  if (this.inflight) return this.inflight;
465
465
  if (this.isUp && this.target.sessionId && !this.halted)
466
466
  return Promise.resolve(this.target.sessionId);
467
- } else this.target && (console.log(`${S} switching from session ${this.target.sessionId ?? "(new)"} to ${t ?? "(new)"}.`), this.close());
468
- return this.halted = null, this.cancelRetry(), this.target = { sessionId: t, resume: (e == null ? void 0 : e.resume) === !0, prepare: e == null ? void 0 : e.prepare }, this.startIdleTick(), this.dial();
467
+ } else this.target && (console.log(`${S} switching from session ${this.target.sessionId ?? "(new)"} to ${e ?? "(new)"}.`), this.close());
468
+ 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
469
  }
470
470
  /**
471
471
  * The send guard: make sure the socket is up before a frame goes out, dialling NOW (not at
472
472
  * the next scheduled retry) when it is not. `fallbackSessionId` is what to dial when nothing
473
473
  * was ever opened through here (a host that set the session on the gateway directly).
474
474
  */
475
- async ensure(t) {
476
- var e;
475
+ async ensure(e) {
476
+ var t;
477
477
  if (this.halted)
478
- throw new Error(`The connection was halted (${this.halted}); session ${((e = this.target) == null ? void 0 : e.sessionId) ?? t ?? "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 ${t ?? "(new)"} with the replay cursor.`), this.open(t, { resume: !0 }));
478
+ 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 }));
480
480
  }
481
481
  /** Stop supervising: hang up, cancel any retry, stop the idle tick. Never throws. */
482
482
  close() {
483
- const t = this.target;
483
+ const e = this.target;
484
484
  this.target = null, this.halted = null, this.cancelRetry(), this.stopIdleTick(), this.wait = H, this.attempt = 0;
485
485
  try {
486
486
  this.ports.hangUp();
487
- } catch (e) {
488
- console.error(`${S} hangUp threw`, e);
487
+ } catch (t) {
488
+ console.error(`${S} hangUp threw`, t);
489
489
  }
490
- t && this.state.setConnectionStatus(C.Disconnected);
490
+ e && this.state.setConnectionStatus(E.Disconnected);
491
491
  }
492
492
  // ─── Transport reports ──────────────────────────────────────────────────
493
493
  /**
@@ -500,45 +500,45 @@ const kt = 4001, se = 4002, Dt = 4004, ne = 4100, H = 500, ie = 2e4, re = 1e3, o
500
500
  * idle close, 4100 our heartbeat's dead-peer verdict): retry on the curve, cursor kept.
501
501
  * A close that lands while a dial is in flight is remembered and judged when that dial fails.
502
502
  */
503
- transportClosed(t, e) {
504
- if (t !== kt && (this.lastCloseCode = t, !!this.target)) {
503
+ transportClosed(e, t) {
504
+ if (e !== ke && (this.lastCloseCode = e, !!this.target)) {
505
505
  if (this.inflight) {
506
- console.log(`${S} socket closed (code=${t}) while a dial is in flight — judged when it settles.`);
506
+ console.log(`${S} socket closed (code=${e}) while a dial is in flight — judged when it settles.`);
507
507
  return;
508
508
  }
509
- this.state.connectionStatus === C.Connected && (console.warn(`${S} socket closed: code=${t} reason="${e}" (session ${this.target.sessionId ?? "(new)"}).`), this.state.setConnectionStatus(C.Disconnected), this.judge(t));
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));
510
510
  }
511
511
  }
512
512
  // ─── The dial ───────────────────────────────────────────────────────────
513
513
  dial() {
514
- const t = this.target;
515
- this.lastCloseCode = null, this.state.setConnectionStatus(C.Connecting);
516
- const e = this.now();
517
- console.log(`${S} dialling session ${t.sessionId ?? "(new)"}${t.resume ? " with the replay cursor" : ""}${this.everConnected ? " (reconnect)" : ""}.`);
518
- const n = (async () => (t.prepare && await t.prepare(), this.ports.dial(t.sessionId, { resume: t.resume })))().then((r) => {
514
+ const e = this.target;
515
+ this.lastCloseCode = null, this.state.setConnectionStatus(E.Connecting);
516
+ 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) => {
519
519
  var c, l;
520
- if (this.target !== t) {
521
- console.log(`${S} a dial for ${t.sessionId ?? "(new)"} resolved after it was abandoned — hanging up.`);
520
+ if (this.target !== e) {
521
+ console.log(`${S} a dial for ${e.sessionId ?? "(new)"} resolved after it was abandoned — hanging up.`);
522
522
  try {
523
523
  this.ports.hangUp();
524
524
  } catch {
525
525
  }
526
526
  throw new Error("Connection attempt abandoned");
527
527
  }
528
- if (t.sessionId && r !== t.sessionId) {
529
- console.error(`${S} asked for session ${t.sessionId}, the server answered with ${r} — refusing the swap and halting.`);
528
+ 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.`);
530
530
  try {
531
531
  this.ports.hangUp();
532
532
  } catch {
533
533
  }
534
- throw this.state.setConnectionStatus(C.Disconnected), this.halt("session-gone", { sessionId: t.sessionId, actualSessionId: r }), new Error(`Session ${t.sessionId} no longer exists on the server (it answered with ${r}).`);
534
+ 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
535
  }
536
- const a = this.everConnected;
537
- return this.everConnected = !0, t.sessionId = r, t.resume = !0, t.prepare = void 0, this.wait = H, this.attempt = 0, this.state.setConnectionStatus(C.Connected), console.log(`${S} ${a ? "reconnected to" : "connected to"} session ${r} in ${this.now() - e}ms.`), (l = (c = this.ports).onConnected) == null || l.call(c, r, { reconnect: a }), r;
536
+ 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;
538
538
  }).catch((r) => {
539
- if (this.target === t && !this.halted) {
540
- const a = this.lastCloseCode;
541
- console.error(`${S} dial of session ${t.sessionId ?? "(new)"} failed after ${this.now() - e}ms${a !== null ? ` (socket closed with ${a})` : ""}:`, r), this.state.setConnectionStatus(C.Disconnected), this.inflight === n && (this.inflight = null), this.judge(a);
539
+ if (this.target === e && !this.halted) {
540
+ 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);
542
542
  }
543
543
  throw r;
544
544
  }).finally(() => {
@@ -547,55 +547,55 @@ const kt = 4001, se = 4002, Dt = 4004, ne = 4100, H = 500, ie = 2e4, re = 1e3, o
547
547
  return this.inflight = n, n;
548
548
  }
549
549
  /** Apply the close-code policy to a failure: halt, or schedule the next attempt. */
550
- judge(t) {
550
+ judge(e) {
551
551
  var s;
552
- const e = (s = this.target) == null ? void 0 : s.sessionId;
553
- if (t === se) return this.halt("attached-elsewhere", { sessionId: e, code: t });
554
- if (t === Dt) return this.halt("session-gone", { sessionId: e, code: t });
555
- if (t === 1e3 || t === 1008) return this.halt("closed-by-server", { sessionId: e, code: t });
552
+ 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 });
555
+ if (e === 1e3 || e === 1008) return this.halt("closed-by-server", { sessionId: t, code: e });
556
556
  this.scheduleRetry();
557
557
  }
558
- halt(t, e) {
558
+ halt(e, t) {
559
559
  var s, n;
560
- this.halted = t, this.cancelRetry(), console.warn(`${S} halted (${t}) on session ${e.sessionId ?? "(new)"}${e.code !== void 0 ? `, close code ${e.code}` : ""} — no automatic redial; an explicit open() may try again.`);
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.`);
561
561
  try {
562
- (n = (s = this.ports).onHalt) == null || n.call(s, t, e);
562
+ (n = (s = this.ports).onHalt) == null || n.call(s, e, t);
563
563
  } catch (r) {
564
564
  console.error(`${S} onHalt threw`, r);
565
565
  }
566
566
  }
567
567
  scheduleRetry() {
568
- var e, s;
568
+ var t, s;
569
569
  if (!this.target || this.retryTimer || this.inflight) return;
570
570
  if (!this.state.sessionActive) {
571
571
  console.log(`${S} session idle — not redialling until activity resumes.`);
572
572
  return;
573
573
  }
574
- const t = this.jittered(this.wait);
575
- this.wait = Math.min(Math.floor(this.wait + this.wait * this.wait / re), ie), this.attempt += 1, console.warn(`${S} redialling session ${this.target.sessionId ?? "(new)"} in ${t}ms (then ${this.wait}ms, attempt ${this.attempt}).`);
574
+ 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}).`);
576
576
  try {
577
- (s = (e = this.ports).onRetryScheduled) == null || s.call(e, { sessionId: this.target.sessionId, delayMs: t, attempt: this.attempt });
577
+ (s = (t = this.ports).onRetryScheduled) == null || s.call(t, { sessionId: this.target.sessionId, delayMs: e, attempt: this.attempt });
578
578
  } catch (n) {
579
579
  console.error(`${S} onRetryScheduled threw`, n);
580
580
  }
581
581
  this.retryTimer = setTimeout(() => {
582
582
  this.retryTimer = null, !(!this.target || this.halted) && (this.target.resume = !0, this.dial().catch(() => {
583
583
  }));
584
- }, t);
584
+ }, e);
585
585
  }
586
586
  cancelRetry() {
587
587
  this.retryTimer && (clearTimeout(this.retryTimer), this.retryTimer = null);
588
588
  }
589
- jittered(t) {
590
- return Math.max(0, Math.round(t + t * oe * (Math.random() * 2 - 1)));
589
+ jittered(e) {
590
+ return Math.max(0, Math.round(e + e * ot * (Math.random() * 2 - 1)));
591
591
  }
592
- sameTarget(t) {
593
- var e;
594
- return ((e = this.target) == null ? void 0 : e.sessionId) === t;
592
+ sameTarget(e) {
593
+ var t;
594
+ return ((t = this.target) == null ? void 0 : t.sessionId) === e;
595
595
  }
596
596
  // ─── Idle ───────────────────────────────────────────────────────────────
597
597
  startIdleTick() {
598
- this.idleTimer || (this.idleTimer = setInterval(() => this.tick(), ce));
598
+ this.idleTimer || (this.idleTimer = setInterval(() => this.tick(), ct));
599
599
  }
600
600
  stopIdleTick() {
601
601
  this.idleTimer && (clearInterval(this.idleTimer), this.idleTimer = null);
@@ -611,40 +611,40 @@ const kt = 4001, se = 4002, Dt = 4004, ne = 4100, H = 500, ie = 2e4, re = 1e3, o
611
611
  tick() {
612
612
  if (!this.target) return;
613
613
  this.state.turnOpen && this.state.setLastActivity();
614
- const t = this.now() - this.state.lastActivity;
615
- if (t > _) {
616
- if (this.state.sessionActive && this.state.setIsSessionActive(!1), this.cancelRetry(), this.state.connectionStatus === C.Connected) {
617
- console.warn(`${S} idle for ${Math.round(t / 1e3)}s (limit ${_ / 1e3}s) — closing the socket (session ${this.target.sessionId ?? "(new)"}). Activity, or a send, redials it.`);
614
+ const e = this.now() - this.state.lastActivity;
615
+ if (e > _) {
616
+ 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.`);
618
618
  try {
619
619
  this.ports.hangUp();
620
- } catch (e) {
621
- console.error(`${S} hangUp threw`, e);
620
+ } catch (t) {
621
+ console.error(`${S} hangUp threw`, t);
622
622
  }
623
- this.state.setConnectionStatus(C.Disconnected);
623
+ this.state.setConnectionStatus(E.Disconnected);
624
624
  }
625
625
  return;
626
626
  }
627
- this.state.sessionActive || (console.log(`${S} activity resumed — the session is active again.`), this.state.setIsSessionActive(!0), this.wait = H, this.state.connectionStatus === C.Disconnected && !this.halted && !this.inflight && (this.target.resume = !0, this.dial().catch(() => {
628
- }))), t > _ * ae ? this.idleWarningLogged || (this.idleWarningLogged = !0, console.warn(`${S} idle ${Math.round(t / 1e3)}s of ${_ / 1e3}s — the socket closes in about ${Math.round((_ - t) / 1e3)}s unless something happens.`)) : this.idleWarningLogged = !1;
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;
629
629
  }
630
630
  };
631
- h(at, "ConnectionSupervisor");
632
- let V = at;
633
- const ct = class ct {
634
- constructor(t) {
635
- o(this, "pending", null);
636
- o(this, "lastPublishedAt", 0);
637
- o(this, "trailing", null);
638
- this.options = t;
639
- }
640
- emit(t) {
641
- const e = Date.now(), s = e - this.lastPublishedAt;
642
- if (t.partial === !1 || s >= this.options.windowMs) {
643
- this.clearTrailing(), this.publish(t, e);
631
+ h(ae, "ConnectionSupervisor");
632
+ let V = ae;
633
+ const ce = class ce {
634
+ constructor(e) {
635
+ a(this, "pending", null);
636
+ a(this, "lastPublishedAt", 0);
637
+ a(this, "trailing", null);
638
+ this.options = e;
639
+ }
640
+ emit(e) {
641
+ const t = Date.now(), s = t - this.lastPublishedAt;
642
+ if (e.partial === !1 || s >= this.options.windowMs) {
643
+ this.clearTrailing(), this.publish(e, t);
644
644
  return;
645
645
  }
646
- this.pending = t, this.clearTrailing(), this.trailing = setTimeout(() => {
647
- this.trailing = null, this.pending && this.pending.version > this.options.publishedVersion() && this.publish(this.pending, e);
646
+ this.pending = e, this.clearTrailing(), this.trailing = setTimeout(() => {
647
+ this.trailing = null, this.pending && this.pending.version > this.options.publishedVersion() && this.publish(this.pending, t);
648
648
  }, this.options.windowMs * 2);
649
649
  }
650
650
  /**
@@ -655,95 +655,101 @@ const ct = class ct {
655
655
  cancelPending() {
656
656
  this.clearTrailing(), this.pending = null;
657
657
  }
658
- publish(t, e) {
659
- this.lastPublishedAt = e, this.pending = null, this.options.publish(t);
658
+ publish(e, t) {
659
+ this.lastPublishedAt = t, this.pending = null, this.options.publish(e);
660
660
  }
661
661
  clearTrailing() {
662
662
  this.trailing && (clearTimeout(this.trailing), this.trailing = null);
663
663
  }
664
664
  };
665
- h(ct, "ThrottledEmitter");
666
- let Z = ct;
665
+ h(ce, "ThrottledEmitter");
666
+ let Z = ce;
667
667
  const y = class y {
668
- constructor(t, e, s, n, r, a, c, l, f, p, w) {
669
- o(this, "base_url");
670
- o(this, "msg_order", 0);
671
- o(this, "interactionsMap", /* @__PURE__ */ new Map());
672
- o(this, "interactionsServiceMap", /* @__PURE__ */ new Map());
673
- o(this, "user");
674
- o(this, "config");
675
- o(this, "currentIS", null);
676
- o(this, "sessionState");
677
- o(this, "storageService");
678
- o(this, "notificationPort");
679
- o(this, "interactionCallIds", /* @__PURE__ */ new Map());
668
+ constructor(e, t, s, n, r, o, c, l, f, g, m) {
669
+ a(this, "base_url");
670
+ a(this, "msg_order", 0);
671
+ a(this, "interactionsMap", /* @__PURE__ */ new Map());
672
+ a(this, "interactionsServiceMap", /* @__PURE__ */ new Map());
673
+ a(this, "user");
674
+ a(this, "config");
675
+ a(this, "currentIS", null);
676
+ a(this, "sessionState");
677
+ a(this, "storageService");
678
+ a(this, "notificationPort");
679
+ a(this, "interactionCallIds", /* @__PURE__ */ new Map());
680
680
  /** Interactions whose turn was committed (turn-complete or a server error); a second close is ignored. */
681
- o(this, "committedTurns", /* @__PURE__ */ new Set());
681
+ a(this, "committedTurns", /* @__PURE__ */ new Set());
682
682
  /** Interactions this tab sent. An `InteractionStarted` for one of them announces what is already here. */
683
- o(this, "localInteractionIds", /* @__PURE__ */ new Set());
683
+ a(this, "localInteractionIds", /* @__PURE__ */ new Set());
684
684
  /**
685
685
  * Turns open right now, local and remote. `turnOpen` in the store is "any of these": a remote turn finishing
686
686
  * must not unlock the composer under a local turn still streaming, nor the other way round.
687
687
  */
688
- o(this, "openTurns", /* @__PURE__ */ new Set());
689
- o(this, "options");
688
+ a(this, "openTurns", /* @__PURE__ */ new Set());
689
+ /**
690
+ * Messages sent while a turn was open, by interaction id → the text the user typed, in send order (AIA Issue 1651).
691
+ * Mirrored to the store's `queuedMessages`. Leaves when the server announces the delivery, or when the turn ends
692
+ * without it (pause, error) and the text goes back to the composer.
693
+ */
694
+ a(this, "queuedMessages", /* @__PURE__ */ new Map());
695
+ a(this, "options");
690
696
  /** Announcements asked for in this tab, by `runId|settleKey` — a second request for the same settle is a no-op. */
691
- o(this, "announceRequested", /* @__PURE__ */ new Set());
697
+ a(this, "announceRequested", /* @__PURE__ */ new Set());
692
698
  /** Announcements waiting for the chat to be idle (no open turn) and connected, in request order. */
693
- o(this, "pendingAnnouncements", []);
694
- o(this, "flushingAnnouncements", !1);
695
- o(this, "rawJwt");
696
- o(this, "sessionId");
697
- o(this, "eventBusService");
698
- o(this, "artifactService");
699
- o(this, "wsService");
699
+ a(this, "pendingAnnouncements", []);
700
+ a(this, "flushingAnnouncements", !1);
701
+ a(this, "rawJwt");
702
+ a(this, "sessionId");
703
+ a(this, "eventBusService");
704
+ a(this, "artifactService");
705
+ a(this, "wsService");
700
706
  /** The one owner of dial / redial / idle close / connection status. See ConnectionSupervisor. */
701
- o(this, "connection");
702
- o(this, "suspendState", !1);
707
+ a(this, "connection");
708
+ a(this, "suspendState", !1);
703
709
  /**
704
710
  * True once a WS has successfully opened at least once in this gateway's
705
711
  * lifetime. Gates the "Reiniciando a conexão" toast: a drop of a working
706
712
  * connection is worth telling the user about, a failed initial dial is not
707
713
  * (the Connecting state already covers it).
708
714
  */
709
- o(this, "everConnected", !1);
715
+ a(this, "everConnected", !1);
710
716
  /** Publishes the live message to the store; see ThrottledEmitter for the cadence rules. */
711
- o(this, "liveMessage", new Z({
717
+ a(this, "liveMessage", new Z({
712
718
  windowMs: y.CURRENT_MSG_THROTTLE_MS,
713
- publish: /* @__PURE__ */ h((t) => {
714
- this.sessionState.setCurrentMessage(t), this.eventBusService.gatewayEmitMessage(t);
719
+ publish: /* @__PURE__ */ h((e) => {
720
+ this.sessionState.setCurrentMessage(e), this.eventBusService.gatewayEmitMessage(e);
715
721
  }, "publish"),
716
722
  publishedVersion: /* @__PURE__ */ h(() => {
717
- var t;
718
- return ((t = this.sessionState.currentMessage) == null ? void 0 : t.version) ?? 0;
723
+ var e;
724
+ return ((e = this.sessionState.currentMessage) == null ? void 0 : e.version) ?? 0;
719
725
  }, "publishedVersion")
720
726
  }));
721
- o(this, "detachedRunInteractions", /* @__PURE__ */ new Map());
722
- o(this, "detachedRunInteractionServices", /* @__PURE__ */ new Map());
727
+ a(this, "detachedRunInteractions", /* @__PURE__ */ new Map());
728
+ a(this, "detachedRunInteractionServices", /* @__PURE__ */ new Map());
723
729
  // ─── Artifacts ──────────────────────────────────────────────────────────
724
- o(this, "runningRequests", /* @__PURE__ */ new Map());
725
- this.options = w ?? {}, this.user = t, this.config = r, this.rawJwt = t.access_token, this.base_url = n, this.eventBusService = e, this.sessionId = p, this.artifactService = s, this.sessionState = a.getState(), this.notificationPort = c, this.storageService = f, a.subscribe((u, g) => {
726
- this.sessionState = u, g.turnOpen && !u.turnOpen && this.flushAnnouncements();
730
+ a(this, "runningRequests", /* @__PURE__ */ new Map());
731
+ 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
+ this.sessionState = u, p.turnOpen && !u.turnOpen && this.flushAnnouncements();
727
733
  }), this.wsService = l, this.connection = new V({
728
- store: a,
734
+ store: o,
729
735
  // A redial while a turn is open carries the turn's id: the server tells us if it cannot continue it.
730
- dial: /* @__PURE__ */ h((u, g) => this.wsService.connect(u, {
731
- ...g,
732
- openInteractionId: g.resume && this.sessionState.turnOpen ? this.getCurrentInteractionId() ?? void 0 : void 0
736
+ dial: /* @__PURE__ */ h((u, p) => this.wsService.connect(u, {
737
+ ...p,
738
+ openInteractionId: p.resume && this.sessionState.turnOpen ? this.getCurrentInteractionId() ?? void 0 : void 0
733
739
  }), "dial"),
734
740
  hangUp: /* @__PURE__ */ h(() => this.wsService.closeStream(), "hangUp"),
735
741
  isConnected: /* @__PURE__ */ h(() => this.wsService.isConnected(), "isConnected"),
736
- onConnected: /* @__PURE__ */ h((u, g) => {
737
- this.sessionId = u, this.sessionState.setConnectionOutage(null), this.eventBusService.gatewayEmitConnected(u, g), this.flushAnnouncements();
742
+ onConnected: /* @__PURE__ */ h((u, p) => {
743
+ this.sessionId = u, this.sessionState.setConnectionOutage(null), this.eventBusService.gatewayEmitConnected(u, p), this.flushAnnouncements();
738
744
  }, "onConnected"),
739
- onRetryScheduled: /* @__PURE__ */ h(({ delayMs: u, attempt: g }) => {
745
+ onRetryScheduled: /* @__PURE__ */ h(({ delayMs: u, attempt: p }) => {
740
746
  var D;
741
- const m = Date.now(), v = ((D = this.sessionState.connectionOutage) == null ? void 0 : D.since) ?? m;
742
- this.sessionState.setConnectionOutage({ since: v, retryAt: m + u, attempt: g, halted: null }), m - v >= y.OUTAGE_CLOSES_TURN_AFTER_MS && this.closeOpenTurnWith(y.OUTAGE_TURN_MESSAGE);
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);
743
749
  }, "onRetryScheduled"),
744
- onHalt: /* @__PURE__ */ h((u, g) => {
745
- const m = this.sessionState.connectionOutage;
746
- this.sessionState.setConnectionOutage({ since: (m == null ? void 0 : m.since) ?? Date.now(), retryAt: null, attempt: (m == null ? void 0 : m.attempt) ?? 0, halted: u }), this.notifyHalt(u, g), this.closeOpenTurnWith(y.HALT_TURN_MESSAGE[u]);
750
+ 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]);
747
753
  }, "onHalt")
748
754
  }), this.wsService.onEvent = async (u) => {
749
755
  await this.Message(u);
@@ -761,46 +767,46 @@ const y = class y {
761
767
  // to the page, say) instead of a toast, without matching on the copy.
762
768
  kind: "connection-restarting"
763
769
  });
764
- } catch (g) {
765
- console.error("[AgentGateway] notification port threw on connection-restarting", g);
770
+ } catch (p) {
771
+ console.error("[AgentGateway] notification port threw on connection-restarting", p);
766
772
  }
767
773
  this.eventBusService.gatewayEmitStreamError(u);
768
774
  }, this.wsService.onOpen = () => {
769
775
  this.everConnected = !0;
770
776
  }, this.wsService.onBillingLimit = (u) => {
771
- a.getState().setBillingLimit(u);
777
+ o.getState().setBillingLimit(u);
772
778
  }, this.wsService.onFirstToken = (u) => {
773
779
  this.localEmitFirstToken(u);
774
- }, this.wsService.onClose = (u, g) => {
775
- this.connection.transportClosed(u, g);
780
+ }, this.wsService.onClose = (u, p) => {
781
+ this.connection.transportClosed(u, p);
776
782
  };
777
783
  }
778
784
  /**
779
785
  * The turn the user is waiting on will not continue: close it from the client side with an error
780
786
  * part, the same way a server error would. No-op when no turn is open.
781
787
  */
782
- closeOpenTurnWith(t) {
788
+ closeOpenTurnWith(e) {
783
789
  if (!this.sessionState.turnOpen) return;
784
- const e = this.getCurrentInteractionId(), s = this.openTurns.size > 0 ? [...this.openTurns] : e ? [e] : [];
790
+ const t = this.getCurrentInteractionId(), s = this.openTurns.size > 0 ? [...this.openTurns] : t ? [t] : [];
785
791
  for (const n of s)
786
- console.warn(`[AgentGateway] closing interaction ${n} from the client side: ${t}`), this.Message(x.createErrorEvent(t, n));
792
+ console.warn(`[AgentGateway] closing interaction ${n} from the client side: ${e}`), this.Message(q.createErrorEvent(e, n));
787
793
  }
788
794
  /** The supervisor gave up on its own (another tab holds the session, the session is gone, …): tell the user. */
789
- notifyHalt(t, e) {
795
+ notifyHalt(e, t) {
790
796
  const s = {
791
797
  "attached-elsewhere": { message: "Esta sessão já está aberta em outra janela", kind: "session-attached-elsewhere" },
792
798
  "session-gone": { message: "A sessão não existe mais no servidor", kind: "session-gone" },
793
799
  "closed-by-server": { message: "O servidor encerrou a conexão", kind: "connection-closed" }
794
- }, { message: n, kind: r } = s[t];
800
+ }, { message: n, kind: r } = s[e];
795
801
  try {
796
802
  this.notificationPort.pushNotification({
797
803
  message: n,
798
804
  type: "warning",
799
805
  kind: r,
800
- details: `session ${e.sessionId ?? "none"}${e.code !== void 0 ? `, close code ${e.code}` : ""}${e.actualSessionId ? `, server answered with ${e.actualSessionId}` : ""}`
806
+ details: `session ${t.sessionId ?? "none"}${t.code !== void 0 ? `, close code ${t.code}` : ""}${t.actualSessionId ? `, server answered with ${t.actualSessionId}` : ""}`
801
807
  });
802
- } catch (a) {
803
- console.error(`[AgentGateway] notification port threw on ${r}`, a);
808
+ } catch (o) {
809
+ console.error(`[AgentGateway] notification port threw on ${r}`, o);
804
810
  }
805
811
  }
806
812
  // ─── Agent context ──────────────────────────────────────────────────────
@@ -816,8 +822,8 @@ const y = class y {
816
822
  getModel() {
817
823
  return this.config.model;
818
824
  }
819
- setModel(t) {
820
- this.config = { ...this.config, model: t };
825
+ setModel(e) {
826
+ this.config = { ...this.config, model: e };
821
827
  }
822
828
  /**
823
829
  * Live update for the ordinary, non-identity slice of the context — the
@@ -825,8 +831,8 @@ const y = class y {
825
831
  * datasets mid-conversation is routine and changes nothing about who is
826
832
  * answering.
827
833
  */
828
- setCustomer(t) {
829
- this.config = { ...this.config, customer: t };
834
+ setCustomer(e) {
835
+ this.config = { ...this.config, customer: e };
830
836
  }
831
837
  /**
832
838
  * Replace the AGENT mid-conversation. The escape hatch for an agent picker,
@@ -841,31 +847,31 @@ const y = class y {
841
847
  * context omits it — the model is owned separately by {@link setModel} and
842
848
  * must not be clobbered by an agent-only change.
843
849
  */
844
- forceAgentContext(t) {
850
+ forceAgentContext(e) {
845
851
  this.config = {
846
- ...t,
847
- model: t.model ?? this.config.model
852
+ ...e,
853
+ model: e.model ?? this.config.model
848
854
  };
849
855
  }
850
856
  // ─── Session and interactions ───────────────────────────────────────────
851
857
  getSessionId() {
852
858
  return this.sessionId;
853
859
  }
854
- setSession(t, e) {
855
- (this.sessionId === void 0 || this.sessionId != t) && (this.sessionId = t, this.msg_order = this.sessionState.messages.length);
860
+ setSession(e, t) {
861
+ (this.sessionId === void 0 || this.sessionId != e) && (this.sessionId = e, this.msg_order = this.sessionState.messages.length);
856
862
  }
857
- startInteraction(t, e, s) {
858
- if (e && this.currentIS)
859
- return this.currentIS.interaction.isSuspended = !1, this.currentIS.interaction.interactionQuestion += " + " + t, this.currentIS.interaction;
863
+ startInteraction(e, t, s) {
864
+ if (t && this.currentIS)
865
+ return this.currentIS.interaction.isSuspended = !1, this.currentIS.interaction.interactionQuestion += " + " + e, this.currentIS.interaction;
860
866
  this.msg_order += 1;
861
867
  let n = this.getNewInteractionId();
862
- return s && (n = s), this.currentIS = this.registerInteraction(n, t), this.currentIS.interaction;
868
+ return s && (n = s), this.currentIS = this.registerInteraction(n, e), this.currentIS.interaction;
863
869
  }
864
870
  /** A new interaction and its merge service, in the maps. Who becomes current is the caller's decision. */
865
- registerInteraction(t, e, s) {
871
+ registerInteraction(e, t, s) {
866
872
  const n = {
867
873
  created: /* @__PURE__ */ new Date(),
868
- interactionId: t,
874
+ interactionId: e,
869
875
  artifactData: [],
870
876
  partial: !0,
871
877
  sessionId: this.sessionId,
@@ -873,17 +879,17 @@ const y = class y {
873
879
  parts: [],
874
880
  version: 0,
875
881
  functionMap: /* @__PURE__ */ new Map(),
876
- interactionQuestion: e,
882
+ interactionQuestion: t,
877
883
  ...s
878
884
  };
879
- this.interactionsMap.set(t, n);
885
+ this.interactionsMap.set(e, n);
880
886
  const r = new j(n, this.eventBusService);
881
- return this.interactionsServiceMap.set(t, r), r;
887
+ return this.interactionsServiceMap.set(e, r), r;
882
888
  }
883
889
  /** The current interaction's turn is still open — it owns the live message, and must stay current. */
884
890
  currentTurnIsOpen() {
885
- const t = this.getCurrentInteractionId();
886
- return !!t && this.openTurns.has(t);
891
+ const e = this.getCurrentInteractionId();
892
+ return !!e && this.openTurns.has(e);
887
893
  }
888
894
  /**
889
895
  * A turn this tab did not send (AIA Issue 1548): a WhatsApp message, a platform wake turn, another tab's turn, a
@@ -891,9 +897,9 @@ const y = class y {
891
897
  * turn mid-stream keeps it, and with it the resume cursor, suspend and the client-side close; the remote turn
892
898
  * streams into its own interaction and takes over the live message when that turn ends.
893
899
  */
894
- openRemoteInteraction(t, e, s, n) {
895
- const r = this.registerInteraction(t, e, { remote: !0, ...s && { origin: s } });
896
- return this.currentTurnIsOpen() || (this.currentIS = r), n && (this.openTurns.add(t), this.sessionState.setTurnOpen(!0), this.eventBusService.gatewayEmitTurnOpen(t), this.currentIS === r && this.localEmitMessage(r.interaction)), r;
900
+ openRemoteInteraction(e, t, s, n) {
901
+ const r = this.registerInteraction(e, t, { remote: !0, ...s && { origin: s } });
902
+ return this.currentTurnIsOpen() || (this.currentIS = r), n && (this.openTurns.add(e), this.sessionState.setTurnOpen(!0), this.eventBusService.gatewayEmitTurnOpen(e), this.currentIS === r && this.localEmitMessage(r.interaction)), r;
897
903
  }
898
904
  /**
899
905
  * An `InteractionStarted` frame. Opens a turn this tab did not send, with the text that started it as its
@@ -901,16 +907,48 @@ const y = class y {
901
907
  * Outside {@link AgentGatewayOptions.transcriptOfDetachedRun}, a detached run's turn is ignored too: it runs on
902
908
  * the run's own session, and its box — not this transcript — shows it.
903
909
  */
904
- interactionStarted(t) {
905
- const e = t.interactionId;
906
- if (!e || t.detachedRunId && !this.options.transcriptOfDetachedRun || this.localInteractionIds.has(e) || this.committedTurns.has(e)) return;
907
- const s = this.interactionsServiceMap.get(e);
908
- if (s) {
909
- const n = s.interaction;
910
- n.interactionQuestion || (n.interactionQuestion = t.content ?? ""), n.origin ?? (n.origin = St(t.origin));
910
+ interactionStarted(e) {
911
+ var r;
912
+ const t = e.interactionId;
913
+ if (!t || e.detachedRunId && !this.options.transcriptOfDetachedRun) return;
914
+ const s = ((r = e.queuedInteractionIds) != null && r.length ? e.queuedInteractionIds : [t]).filter((o) => this.queuedMessages.has(o));
915
+ if (s.length > 0) {
916
+ this.queuedMessageDelivered(e, s);
917
+ return;
918
+ }
919
+ if (this.localInteractionIds.has(t) || this.committedTurns.has(t)) return;
920
+ const n = this.interactionsServiceMap.get(t);
921
+ if (n) {
922
+ const o = n.interaction;
923
+ o.interactionQuestion || (o.interactionQuestion = e.content ?? ""), o.origin ?? (o.origin = Se(e.origin));
911
924
  return;
912
925
  }
913
- this.openRemoteInteraction(e, t.content ?? "", St(t.origin), !0);
926
+ this.openRemoteInteraction(t, e.content ?? "", Se(e.origin), !0);
927
+ }
928
+ /**
929
+ * The server delivered messages this tab queued (AIA Issue 1651). Injected into the running turn — the frame lists
930
+ * the ids it absorbed — the turn so far is committed as the previous message's answer and everything the server
931
+ * streams from here belongs to the new one, which shows the user's text as its question. Queued too late for the
932
+ * running turn, they start the next one — the previous turn is already committed, so it simply opens.
933
+ */
934
+ queuedMessageDelivered(e, t) {
935
+ var l, f;
936
+ const s = e.interactionId, n = t.map((g) => this.queuedMessages.get(g)).join(`
937
+ `);
938
+ for (const g of t) this.queuedMessages.delete(g);
939
+ this.sessionState.removeQueuedMessages(t);
940
+ const r = (((l = e.queuedInteractionIds) == null ? void 0 : l.length) ?? 0) > 0, o = (f = this.currentIS) == null ? void 0 : f.interaction, c = this.registerInteraction(s, n);
941
+ if (this.localInteractionIds.add(s), r && o && this.openTurns.has(o.interactionId)) {
942
+ const g = o.interactionId;
943
+ this.openTurns.delete(g), this.committedTurns.add(g), this.liveMessage.cancelPending();
944
+ const m = { ...o, continuedBelow: !0 };
945
+ this.sessionState.setNewMessage(m), this.eventBusService.gatewayEmitTurnComplete(g, m), this.interactionCallIds.delete(g);
946
+ }
947
+ (r || !this.currentTurnIsOpen()) && (this.currentIS = c), this.openTurns.add(s), this.sessionState.setTurnOpen(!0), this.eventBusService.gatewayEmitTurnOpen(s), this.currentIS === c && (this.sessionState.setCurrentMessage(c.interaction), this.eventBusService.gatewayEmitMessage(c.interaction));
948
+ }
949
+ /** Hands every undelivered queued message back to the composer (the turn will not deliver them). */
950
+ restoreQueuedMessages() {
951
+ this.queuedMessages.size !== 0 && (this.queuedMessages.clear(), this.sessionState.restoreQueuedMessages());
914
952
  }
915
953
  getInteractions() {
916
954
  return Array.from(this.interactionsMap.values());
@@ -919,58 +957,58 @@ const y = class y {
919
957
  return this.currentIS ? this.currentIS.interaction.interactionId : null;
920
958
  }
921
959
  getCurrentInteraction() {
922
- var t;
923
- return ((t = this.currentIS) == null ? void 0 : t.interaction) ?? null;
960
+ var e;
961
+ return ((e = this.currentIS) == null ? void 0 : e.interaction) ?? null;
924
962
  }
925
- updateMap(t) {
926
- let e = this.interactionsServiceMap.get(t.interactionId);
927
- return e || (e = this.openRemoteInteraction(t.interactionId, "", void 0, !1)), e.merge(t);
963
+ updateMap(e) {
964
+ let t = this.interactionsServiceMap.get(e.interactionId);
965
+ return t || (t = this.openRemoteInteraction(e.interactionId, "", void 0, !1)), t.merge(e);
928
966
  }
929
967
  getNewInteractionId() {
930
- const e = qt(/* @__PURE__ */ new Date(), "MMM_dd_HH_mm_ss");
931
- return `${this.msg_order}_${e}`;
968
+ const t = xe(/* @__PURE__ */ new Date(), "MMM_dd_HH_mm_ss");
969
+ return `${this.msg_order}_${t}`;
932
970
  }
933
971
  // ─── Inbound: server events ─────────────────────────────────────────────
934
- async Message(t) {
972
+ async Message(e) {
935
973
  try {
936
- let e;
937
- if (typeof t == "object" && Object.keys(t).includes("mimeType"))
938
- e = t;
974
+ let t;
975
+ if (typeof e == "object" && Object.keys(e).includes("mimeType"))
976
+ t = e;
939
977
  else {
940
- console.error("Uknown message type", t);
978
+ console.error("Uknown message type", e);
941
979
  return;
942
980
  }
943
- if (e.detachedRunId && !this.options.transcriptOfDetachedRun) {
944
- this.handleDetachedRunEvent(e);
981
+ if (t.detachedRunId && !this.options.transcriptOfDetachedRun) {
982
+ this.handleDetachedRunEvent(t);
945
983
  return;
946
984
  }
947
- if (e.serverError && console.error("Stream error: ", e.serverError), e.endMessageData && this.eventBusService.gatewayEmitEndMessageData(e.endMessageData), e.llmArtifacts && e.llmArtifacts.length > 0)
948
- for (const a of e.llmArtifacts) {
949
- const c = a.toArtifact();
985
+ if (t.serverError && console.error("Stream error: ", t.serverError), t.endMessageData && this.eventBusService.gatewayEmitEndMessageData(t.endMessageData), t.llmArtifacts && t.llmArtifacts.length > 0)
986
+ for (const o of t.llmArtifacts) {
987
+ const c = o.toArtifact();
950
988
  this.artifactService.addToCache(c), this.eventBusService.artifactEmitGenerated(c);
951
989
  }
952
- for (const a of e.parts ?? [])
953
- a.toolDetails && this.localEmitToolEvent(a.toolDetails);
954
- const s = (e.parts ?? []).some((a) => a.eventType === I.ServerError);
955
- if (s && !e.interactionId) {
956
- const a = this.getCurrentInteractionId();
957
- a && (e.interactionId = a);
990
+ for (const o of t.parts ?? [])
991
+ o.toolDetails && this.localEmitToolEvent(o.toolDetails);
992
+ const s = (t.parts ?? []).some((o) => o.eventType === I.ServerError);
993
+ if (s && !t.interactionId) {
994
+ const o = this.getCurrentInteractionId();
995
+ o && (t.interactionId = o);
958
996
  }
959
- const n = this.updateMap(e);
997
+ const n = this.updateMap(t);
960
998
  if (!n) {
961
999
  console.error("No updated interaction");
962
1000
  return;
963
1001
  }
964
- (n.interactionId === this.getCurrentInteractionId() || !this.currentTurnIsOpen()) && this.localEmitMessage(n), (e.turn_complete || e.asyncFinalResponse || s) && (this.committedTurns.has(e.interactionId) || (this.committedTurns.add(e.interactionId), this.turnComplete(e.interactionId, n, e.author, e.detachedRunId)));
965
- const r = e.artifactsDelta;
966
- r && r.forEach((a) => {
967
- const c = n.artifactData.filter((f) => f.id == a);
1002
+ (n.interactionId === this.getCurrentInteractionId() || !this.currentTurnIsOpen()) && this.localEmitMessage(n), (t.turn_complete || t.asyncFinalResponse || s) && (this.committedTurns.has(t.interactionId) || (this.committedTurns.add(t.interactionId), this.turnComplete(t.interactionId, n, t.author, t.detachedRunId), s && this.openTurns.size === 0 && this.restoreQueuedMessages()));
1003
+ const r = t.artifactsDelta;
1004
+ r && r.forEach((o) => {
1005
+ const c = n.artifactData.filter((f) => f.id == o);
968
1006
  let l = null;
969
- c && c.length > 0 && (l = c[0], l.loadingPromise = this.asyncLoadArtifact(a).then((f) => (f === null ? console.error("Error trying to load artifact id:", l == null ? void 0 : l.id, "Artifact is null") : this.eventBusService.artifactEmitGenerated(f), f)).catch((f) => (console.error("Error trying to load artifact id:", l == null ? void 0 : l.id, f.toString()), null)));
1007
+ c && c.length > 0 && (l = c[0], l.loadingPromise = this.asyncLoadArtifact(o).then((f) => (f === null ? console.error("Error trying to load artifact id:", l == null ? void 0 : l.id, "Artifact is null") : this.eventBusService.artifactEmitGenerated(f), f)).catch((f) => (console.error("Error trying to load artifact id:", l == null ? void 0 : l.id, f.toString()), null)));
970
1008
  });
971
- } catch (e) {
1009
+ } catch (t) {
972
1010
  if (this.getCurrentInteractionId()) {
973
- const s = x.createErrorEvent("OnMessage error: " + e.toString(), this.getCurrentInteractionId() ?? "Empty Current"), n = this.updateMap(s);
1011
+ const s = q.createErrorEvent("OnMessage error: " + t.toString(), this.getCurrentInteractionId() ?? "Empty Current"), n = this.updateMap(s);
974
1012
  if (console.error("Error event: ", JSON.stringify(s, void 0, 4)), !n) {
975
1013
  console.error("Error event, could not update interaction: ", JSON.stringify(s, void 0, 4));
976
1014
  return;
@@ -979,49 +1017,49 @@ const y = class y {
979
1017
  }
980
1018
  }
981
1019
  }
982
- getOrCreateDetachedRunInteraction(t, e, s) {
983
- let n = this.detachedRunInteractions.get(t), r = this.detachedRunInteractionServices.get(t);
1020
+ getOrCreateDetachedRunInteraction(e, t, s) {
1021
+ let n = this.detachedRunInteractions.get(e), r = this.detachedRunInteractionServices.get(e);
984
1022
  return (!n || !r) && (n = {
985
1023
  created: /* @__PURE__ */ new Date(),
986
- interactionId: e,
1024
+ interactionId: t,
987
1025
  artifactData: [],
988
1026
  partial: !0,
989
1027
  turn_complete: !1,
990
1028
  parts: [],
991
1029
  version: 0,
992
1030
  functionMap: /* @__PURE__ */ new Map(),
993
- interactionQuestion: s ?? t
994
- }, r = new j(n, this.eventBusService), this.detachedRunInteractions.set(t, n), this.detachedRunInteractionServices.set(t, r)), { interaction: n, service: r };
1031
+ interactionQuestion: s ?? e
1032
+ }, r = new j(n, this.eventBusService), this.detachedRunInteractions.set(e, n), this.detachedRunInteractionServices.set(e, r)), { interaction: n, service: r };
995
1033
  }
996
- handleDetachedRunEvent(t) {
997
- const e = t.detachedRunId, { service: s } = this.getOrCreateDetachedRunInteraction(e, t.interactionId, t.detachedRunName);
998
- for (const r of t.parts ?? [])
999
- r.toolDetails && this.localEmitToolEvent({ ...r.toolDetails, detachedRunId: e });
1000
- const n = s.merge(t);
1001
- n && (this.sessionState.setDetachedRunMessage(e, n, t.detachedRunName), (t.turn_complete ?? !1) && this.sessionState.completeDetachedRun(e));
1034
+ handleDetachedRunEvent(e) {
1035
+ const t = e.detachedRunId, { service: s } = this.getOrCreateDetachedRunInteraction(t, e.interactionId, e.detachedRunName);
1036
+ for (const r of e.parts ?? [])
1037
+ r.toolDetails && this.localEmitToolEvent({ ...r.toolDetails, detachedRunId: t });
1038
+ const n = s.merge(e);
1039
+ n && (this.sessionState.setDetachedRunMessage(t, n, e.detachedRunName), (e.turn_complete ?? !1) && this.sessionState.completeDetachedRun(t));
1002
1040
  }
1003
- localEmitToolEvent(t) {
1004
- this.sessionState.setLastToolEvent(t), this.eventBusService.gatewayEmitToolEvent(t.eventName, t.eventData, t.sessionId);
1041
+ localEmitToolEvent(e) {
1042
+ this.sessionState.setLastToolEvent(e), this.eventBusService.gatewayEmitToolEvent(e.eventName, e.eventData, e.sessionId);
1005
1043
  }
1006
- registerInteractionCallId(t, e) {
1007
- e != null && e.callId && this.interactionCallIds.set(t, e.callId);
1044
+ registerInteractionCallId(e, t) {
1045
+ t != null && t.callId && this.interactionCallIds.set(e, t.callId);
1008
1046
  }
1009
- localEmitFirstToken(t) {
1047
+ localEmitFirstToken(e) {
1010
1048
  this.eventBusService.gatewayEmitFirstToken({
1011
- interactionId: t,
1012
- callId: this.interactionCallIds.get(t)
1049
+ interactionId: e,
1050
+ callId: this.interactionCallIds.get(e)
1013
1051
  });
1014
1052
  }
1015
- localEmitMessage(t) {
1016
- this.liveMessage.emit(t);
1053
+ localEmitMessage(e) {
1054
+ this.liveMessage.emit(e);
1017
1055
  }
1018
- localOpen(t, e) {
1019
- t && this.openTurns.add(t), this.sessionState.setTurnOpen(!0), this.eventBusService.gatewayEmitTurnOpen(t ?? "");
1056
+ localOpen(e, t) {
1057
+ e && this.openTurns.add(e), this.sessionState.setTurnOpen(!0), this.eventBusService.gatewayEmitTurnOpen(e ?? "");
1020
1058
  }
1021
- async turnComplete(t, e, s, n) {
1022
- this.openTurns.delete(t);
1023
- const r = t === this.getCurrentInteractionId(), a = r ? null : this.sessionState.currentMessage;
1024
- r && this.liveMessage.cancelPending(), this.sessionState.setNewMessage(e), a && a.interactionId !== t ? this.sessionState.setCurrentMessage(a) : r && this.handOverLiveMessage(), this.eventBusService.gatewayEmitTurnComplete(t, e), this.interactionCallIds.delete(t), this.sessionState.setLastToolEvent(null), this.localEmitToolEvent({
1059
+ async turnComplete(e, t, s, n) {
1060
+ this.openTurns.delete(e);
1061
+ const r = e === this.getCurrentInteractionId(), o = r ? null : this.sessionState.currentMessage;
1062
+ r && this.liveMessage.cancelPending(), this.sessionState.setNewMessage(t), o && o.interactionId !== e ? this.sessionState.setCurrentMessage(o) : r && this.handOverLiveMessage(), this.eventBusService.gatewayEmitTurnComplete(e, t), this.interactionCallIds.delete(e), this.sessionState.setLastToolEvent(null), this.localEmitToolEvent({
1025
1063
  eventName: "todolistUpdated",
1026
1064
  eventData: "",
1027
1065
  detachedRunId: n
@@ -1032,24 +1070,24 @@ const y = class y {
1032
1070
  * current and its progress so far goes live at once.
1033
1071
  */
1034
1072
  handOverLiveMessage() {
1035
- for (const t of this.openTurns) {
1036
- const e = this.interactionsServiceMap.get(t);
1037
- if (e) {
1038
- this.currentIS = e, this.sessionState.setCurrentMessage(e.interaction), this.eventBusService.gatewayEmitMessage(e.interaction);
1073
+ for (const e of this.openTurns) {
1074
+ const t = this.interactionsServiceMap.get(e);
1075
+ if (t) {
1076
+ this.currentIS = t, this.sessionState.setCurrentMessage(t.interaction), this.eventBusService.gatewayEmitMessage(t.interaction);
1039
1077
  return;
1040
1078
  }
1041
1079
  }
1042
1080
  }
1043
- async asyncLoadArtifact(t) {
1044
- let e = null;
1045
- const s = this.runningRequests.get(t);
1046
- s ? (console.warn("GOT A running promise", t), e = s) : (e = this.artifactService.getArtifact(t), this.runningRequests.set(t, e));
1081
+ async asyncLoadArtifact(e) {
1082
+ let t = null;
1083
+ const s = this.runningRequests.get(e);
1084
+ s ? (console.warn("GOT A running promise", e), t = s) : (t = this.artifactService.getArtifact(e), this.runningRequests.set(e, t));
1047
1085
  try {
1048
- return await e;
1086
+ return await t;
1049
1087
  } catch (n) {
1050
1088
  return console.error("Error awating on HTML promise", n.toString()), null;
1051
1089
  } finally {
1052
- this.runningRequests.delete(t);
1090
+ this.runningRequests.delete(e);
1053
1091
  }
1054
1092
  }
1055
1093
  // ─── Connection ─────────────────────────────────────────────────────────
@@ -1061,12 +1099,12 @@ const y = class y {
1061
1099
  * backoff, the idle close and the close-code policy — and for the rule that a requested
1062
1100
  * session is never swapped for another.
1063
1101
  */
1064
- async openConnection(t, e) {
1065
- return this.connection.open(t, e);
1102
+ async openConnection(e, t) {
1103
+ return this.connection.open(e, t);
1066
1104
  }
1067
- async closeConnection(t = !0) {
1105
+ async closeConnection(e = !0) {
1068
1106
  try {
1069
- return this.stopStream(t), {
1107
+ return this.stopStream(e), {
1070
1108
  success: !0,
1071
1109
  interaction: this.getCurrentInteraction()
1072
1110
  };
@@ -1078,8 +1116,8 @@ const y = class y {
1078
1116
  }
1079
1117
  }
1080
1118
  /** Hang up and stop supervising the connection. `closeTurn` also closes an open turn in the store. */
1081
- stopStream(t = !0) {
1082
- t && (this.openTurns.clear(), this.sessionState.setTurnOpen(!1)), this.sessionState.setConnectionOutage(null), this.connection.close();
1119
+ stopStream(e = !0) {
1120
+ e && (this.openTurns.clear(), this.sessionState.setTurnOpen(!1), this.restoreQueuedMessages()), this.sessionState.setConnectionOutage(null), this.connection.close();
1083
1121
  }
1084
1122
  /**
1085
1123
  * Make sure the socket is OPEN before a send, redialling the SAME session when it is not.
@@ -1092,97 +1130,133 @@ const y = class y {
1092
1130
  * the supervisor dials now rather than at its next scheduled retry, replay cursor kept.
1093
1131
  */
1094
1132
  async ensureConnected() {
1095
- const t = this.sessionId;
1133
+ const e = this.sessionId;
1096
1134
  if (this.wsService.isConnected()) {
1097
- console.log(`[AgentGateway] send guard: socket is open (session ${t ?? "none"}, status ${this.sessionState.connectionStatus}) — sending straight away.`);
1135
+ console.log(`[AgentGateway] send guard: socket is open (session ${e ?? "none"}, status ${this.sessionState.connectionStatus}) — sending straight away.`);
1098
1136
  return;
1099
1137
  }
1100
- const e = Date.now();
1138
+ const t = Date.now();
1101
1139
  try {
1102
- const s = await this.connection.ensure(t);
1103
- console.log(`[AgentGateway] send guard: reconnected to ${s} in ${Date.now() - e}ms — sending now.`);
1140
+ const s = await this.connection.ensure(e);
1141
+ console.log(`[AgentGateway] send guard: reconnected to ${s} in ${Date.now() - t}ms — sending now.`);
1104
1142
  } catch (s) {
1105
- throw console.error(`[AgentGateway] send guard: redial FAILED after ${Date.now() - e}ms — the message was not sent.`, s), new Error(y.NO_CONNECTION_MESSAGE, { cause: s });
1143
+ throw console.error(`[AgentGateway] send guard: redial FAILED after ${Date.now() - t}ms — the message was not sent.`, s), new Error(y.NO_CONNECTION_MESSAGE, { cause: s });
1106
1144
  }
1107
1145
  }
1108
1146
  // ─── Outbound: the user's turns ─────────────────────────────────────────
1109
- async sendMessage(t, e) {
1110
- let s = this.getInteractions().length, n = N.createWaiting(!0, !0, "Overall", /* @__PURE__ */ new Date());
1111
- this.sendStatusMessage(t.data, [n], s.toString() + "1");
1147
+ async sendMessage(e, t) {
1148
+ let s = this.getInteractions().length, n = U.createWaiting(!0, !0, "Overall", /* @__PURE__ */ new Date());
1149
+ this.sendStatusMessage(e.data, [n], s.toString() + "1");
1112
1150
  try {
1113
- const { promptAsString: r, json: a } = this.sessionState.onRenderPrompt ? this.sessionState.onRenderPrompt(t.data) : { promptAsString: t.data, json: void 0 };
1114
- this.sessionState.onRenderPrompt && (t.data = a, t.friendlyMessage = r);
1115
- const c = await this.sendMessageInternal(t, e), l = Bt.createPrompt(r ?? "", (a == null ? void 0 : a.toString()) ?? {});
1151
+ const { promptAsString: r, json: o } = this.sessionState.onRenderPrompt ? this.sessionState.onRenderPrompt(e.data) : { promptAsString: e.data, json: void 0 };
1152
+ 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()) ?? {});
1116
1154
  this.storageService.storePrompt(l);
1117
- const f = N.fromText("Planejando próximos passos");
1118
- return this.sendStatusMessage(t.data, [n, f], s.toString() + "1"), c != null && c.success ? this.eventBusService.ChatEmitMessageSent(t.data, c.interaction) : this.eventBusService.ChatEmitMessageError((c == null ? void 0 : c.error) ?? ""), c;
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;
1119
1157
  } catch (r) {
1120
- const a = r instanceof Error ? r.message : String(r ?? "");
1121
- return this.liveMessage.cancelPending(), this.sessionState.setCurrentMessage(null), this.sessionState.setTurnOpen(this.openTurns.size > 0), this.eventBusService.ChatEmitMessageError(a), {
1158
+ const o = r instanceof Error ? r.message : String(r ?? "");
1159
+ return this.liveMessage.cancelPending(), this.sessionState.setCurrentMessage(null), this.sessionState.setTurnOpen(this.openTurns.size > 0), this.eventBusService.ChatEmitMessageError(o), {
1122
1160
  success: !1,
1123
- error: a,
1161
+ error: o,
1124
1162
  interaction: {
1125
1163
  artifactData: [],
1126
1164
  created: /* @__PURE__ */ new Date(),
1127
1165
  interactionId: "",
1128
1166
  partial: !1,
1129
- parts: [N.fromError(a)],
1167
+ parts: [U.fromError(o)],
1130
1168
  version: 0
1131
1169
  }
1132
1170
  };
1133
1171
  }
1134
1172
  }
1135
1173
  // Send a message to the server over the socket
1136
- async sendMessageInternal(t, e) {
1137
- var r, a, c, l, f, p, w, u, g, m;
1174
+ async sendMessageInternal(e, t) {
1175
+ var r, o;
1138
1176
  const s = this.suspendState;
1139
1177
  this.suspendState = !1;
1140
- const n = this.startInteraction(t.friendlyMessage ?? t.data, s);
1141
- if (this.localInteractionIds.add(n.interactionId), this.registerInteractionCallId(n.interactionId, e), (r = t.userUi) != null && r.name && n.parts.push(N.fromUserUi(t.userUi.name, t.userUi.args)), !this.wsService)
1178
+ 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)
1142
1180
  throw "no wsService created";
1143
- if (!((a = this.config.agentConfig) != null && a.id))
1181
+ if (!((o = this.config.agentConfig) != null && o.id))
1144
1182
  throw "Agent not selected";
1145
- return this.sessionState.setLastActivity(), await this.ensureConnected(), this.wsService.sendMessage({
1183
+ return this.sessionState.setLastActivity(), await this.ensureConnected(), this.wsService.sendMessage(this.messageFrame(F.SendMessage, e, n.interactionId)), this.localOpen(n.interactionId, "system"), {
1184
+ interaction: n,
1185
+ success: !0
1186
+ };
1187
+ }
1188
+ /**
1189
+ * Send a message while a turn is open (AIA Issue 1651): the `QueueMessage` action. The server queues it on the
1190
+ * running turn, which reads it after its next tool round — or right away, when the model would otherwise end the
1191
+ * turn — and announces the delivery with an `InteractionStarted`; {@link queuedMessageDelivered} then moves the
1192
+ * live message onto it. Until then it waits in the store's `queuedMessages`. With no turn open this is a plain
1193
+ * {@link sendMessage}. Text only: images ride a turn of their own.
1194
+ */
1195
+ async queueMessage(e) {
1196
+ var r;
1197
+ if (this.openTurns.size === 0) return this.sendMessage(e);
1198
+ const t = e.friendlyMessage ?? e.data;
1199
+ this.msg_order += 1;
1200
+ const s = this.getNewInteractionId(), n = {
1201
+ interactionId: s,
1202
+ created: /* @__PURE__ */ new Date(),
1203
+ partial: !0,
1204
+ turn_complete: !1,
1205
+ version: 0,
1206
+ parts: [],
1207
+ interactionQuestion: t,
1208
+ artifactData: []
1209
+ };
1210
+ this.queuedMessages.set(s, t), this.sessionState.addQueuedMessage({ interactionId: s, text: t });
1211
+ try {
1212
+ if (!((r = this.config.agentConfig) != null && r.id)) throw new Error("Agent not selected");
1213
+ return this.sessionState.setLastActivity(), await this.ensureConnected(), this.wsService.sendMessage(this.messageFrame(F.QueueMessage, { ...e, images: void 0, userUi: void 0 }, s)), this.eventBusService.ChatEmitMessageSent(e.data, n), { success: !0, interaction: n };
1214
+ } catch (o) {
1215
+ const c = o instanceof Error ? o.message : String(o ?? "");
1216
+ return this.queuedMessages.delete(s), this.sessionState.removeQueuedMessages([s]), this.eventBusService.ChatEmitMessageError(c), { success: !1, error: c, interaction: n };
1217
+ }
1218
+ }
1219
+ /** The socket frame for a user message — {@link sendMessageInternal}'s and {@link queueMessage}'s. */
1220
+ messageFrame(e, t, s) {
1221
+ var n, r, o, c, l, f, g, m;
1222
+ return {
1146
1223
  Content: t.data,
1147
1224
  SessionId: this.sessionId,
1148
- Action: U.SendMessage,
1225
+ Action: e,
1149
1226
  ModelId: this.config.model,
1150
- InteractionId: n.interactionId,
1151
- AgentId: (c = this.config.agentConfig) == null ? void 0 : c.id,
1227
+ InteractionId: s,
1228
+ AgentId: ((n = this.config.agentConfig) == null ? void 0 : n.id) ?? "",
1152
1229
  // Optional explicit C# class name on the server (e.g. "LlmAgentSessionReplay").
1153
1230
  // When set, AgentBootStrapService.GetAgent dispatches to that class directly
1154
1231
  // instead of looking up an Agent metadata row by AgentId. Plumbed through
1155
1232
  // `agentContext.agentConfig.agentImplementation` so a host can run a turn
1156
1233
  // against any registered LlmAgent variant without seeding a Mongo record.
1157
- AgentImplementation: (l = this.config.agentConfig) == null ? void 0 : l.agentImplementation,
1234
+ AgentImplementation: (r = this.config.agentConfig) == null ? void 0 : r.agentImplementation,
1158
1235
  Parameters: {
1159
- ...((p = (f = this.config).parameters) == null ? void 0 : p.call(f)) ?? {},
1160
- CustomerName: ((w = this.config.customer) == null ? void 0 : w.name) ?? "",
1161
- DataSet: ((u = this.config.customer) == null ? void 0 : u.dataSetId) ?? ""
1236
+ ...((c = (o = this.config).parameters) == null ? void 0 : c.call(o)) ?? {},
1237
+ CustomerName: ((l = this.config.customer) == null ? void 0 : l.name) ?? "",
1238
+ DataSet: ((f = this.config.customer) == null ? void 0 : f.dataSetId) ?? ""
1162
1239
  },
1163
1240
  // Forward image attachments as a structured payload (PascalCase
1164
1241
  // keys to match the C# `Message.Images` / `MessageImage` model).
1165
- Images: (g = t.images) != null && g.length ? t.images.map((v) => ({ MimeType: v.mimeType, Data: v.data })) : void 0,
1242
+ Images: (g = t.images) != null && g.length ? t.images.map((u) => ({ MimeType: u.mimeType, Data: u.data })) : void 0,
1166
1243
  // Client-only UI representation for this turn (PascalCase to match the C# `Message.UserUi`
1167
1244
  // model). The server persists it as a UserUiContent sibling and strips it from the model
1168
1245
  // request; Content remains the only model-facing text.
1169
1246
  UserUi: (m = t.userUi) != null && m.name ? { Name: t.userUi.name, Args: t.userUi.args } : void 0
1170
- }), this.localOpen(n.interactionId, "system"), {
1171
- interaction: n,
1172
- success: !0
1173
1247
  };
1174
1248
  }
1175
- sendStatusMessage(t, e, s) {
1176
- var r, a;
1249
+ sendStatusMessage(e, t, s) {
1250
+ var r, o;
1177
1251
  let n;
1178
- ((a = (r = this.currentIS) == null ? void 0 : r.interaction) == null ? void 0 : a.turn_complete) === !1 && !this.currentIS.interaction.remote ? (n = Wt.cloneDeep(this.currentIS.interaction), n.parts.push(...e)) : 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 = {
1179
1253
  interactionId: "tmp" + s,
1180
1254
  created: /* @__PURE__ */ new Date(),
1181
1255
  partial: !0,
1182
1256
  turn_complete: !1,
1183
1257
  version: 0,
1184
- parts: e,
1185
- interactionQuestion: t,
1258
+ parts: t,
1259
+ interactionQuestion: e,
1186
1260
  artifactData: []
1187
1261
  }, this.localEmitMessage(n);
1188
1262
  }
@@ -1195,10 +1269,10 @@ const y = class y {
1195
1269
  * gateway does), and a hard cast turned "this transport doesn't deliver answers" into a TypeError
1196
1270
  * thrown from a click handler — with the answer lost either way.
1197
1271
  */
1198
- answerHumanTool(t, e) {
1272
+ answerHumanTool(e, t) {
1199
1273
  var n;
1200
1274
  const s = (n = this.wsService.answerHumanTool) == null ? void 0 : n.bind(this.wsService);
1201
- return s ? s(t, e) : (console.warn("[AgentGateway] transport cannot deliver parked-tool answers", t), "queued");
1275
+ return s ? s(e, t) : (console.warn("[AgentGateway] transport cannot deliver parked-tool answers", e), "queued");
1202
1276
  }
1203
1277
  // ─── Detached-run announcements ─────────────────────────────────────────
1204
1278
  /**
@@ -1211,18 +1285,18 @@ const y = class y {
1211
1285
  * the socket up). `settleKey` — the run's `settledAt` — scopes the dedupe: a repeated request for the same settle
1212
1286
  * is a no-op, a resumed run that settles anew is announced again.</p>
1213
1287
  */
1214
- async announceDetachedRun(t, e) {
1215
- const s = `${t}|${e ?? ""}`;
1216
- return this.announceRequested.has(s) ? "duplicate" : (this.announceRequested.add(s), this.pendingAnnouncements.push(t), await this.flushAnnouncements(), this.pendingAnnouncements.includes(t) ? "queued" : "sent");
1288
+ async announceDetachedRun(e, t) {
1289
+ const s = `${e}|${t ?? ""}`;
1290
+ return this.announceRequested.has(s) ? "duplicate" : (this.announceRequested.add(s), this.pendingAnnouncements.push(e), await this.flushAnnouncements(), this.pendingAnnouncements.includes(e) ? "queued" : "sent");
1217
1291
  }
1218
1292
  /** Send the queued announcements, oldest first, while the chat is idle and the socket is open. */
1219
1293
  async flushAnnouncements() {
1220
- var t, e;
1294
+ var e, t;
1221
1295
  if (!this.flushingAnnouncements) {
1222
1296
  this.flushingAnnouncements = !0;
1223
1297
  try {
1224
1298
  for (; this.pendingAnnouncements.length > 0 && !this.sessionState.turnOpen; ) {
1225
- const s = (t = this.wsService.sendBaseMessage) == null ? void 0 : t.bind(this.wsService);
1299
+ const s = (e = this.wsService.sendBaseMessage) == null ? void 0 : e.bind(this.wsService);
1226
1300
  if (!s) {
1227
1301
  console.warn("[AgentGateway] transport cannot send an AnnounceDetachedRun; the request stays queued");
1228
1302
  return;
@@ -1231,8 +1305,8 @@ const y = class y {
1231
1305
  const n = this.pendingAnnouncements[0];
1232
1306
  try {
1233
1307
  s({
1234
- Action: U.AnnounceDetachedRun,
1235
- AgentId: ((e = this.config.agentConfig) == null ? void 0 : e.id) ?? "",
1308
+ Action: F.AnnounceDetachedRun,
1309
+ AgentId: ((t = this.config.agentConfig) == null ? void 0 : t.id) ?? "",
1236
1310
  InteractionId: `announce_${n}_${Date.now()}`,
1237
1311
  SessionId: this.sessionId,
1238
1312
  DetachedRunId: n
@@ -1250,15 +1324,15 @@ const y = class y {
1250
1324
  }
1251
1325
  // ─── Suspend ────────────────────────────────────────────────────────────
1252
1326
  async suspend() {
1253
- const t = this.wsService;
1254
- return new Promise(async (e, s) => {
1327
+ const e = this.wsService;
1328
+ return new Promise(async (t, s) => {
1255
1329
  let n = !1;
1256
- t.onSuspended = () => {
1330
+ e.onSuspended = () => {
1257
1331
  n = !0;
1258
- }, t.suspendStream();
1259
- const r = 100, a = 5e3;
1332
+ }, e.suspendStream();
1333
+ const r = 100, o = 5e3;
1260
1334
  let c = 0;
1261
- for (; !n && c < a; )
1335
+ for (; !n && c < o; )
1262
1336
  await this.sleep(r), c += r;
1263
1337
  if (!n) {
1264
1338
  s("Timeout awaiting for suspension");
@@ -1269,104 +1343,116 @@ const y = class y {
1269
1343
  return;
1270
1344
  }
1271
1345
  const l = this.currentIS.interaction;
1272
- l.isSuspended = !0, this.openTurns.delete(l.interactionId), this.sessionState.setCurrentMessage(l), this.sessionState.setTurnOpen(this.openTurns.size > 0), this.suspendState = !0, e(!0);
1346
+ l.isSuspended = !0, this.openTurns.delete(l.interactionId), this.sessionState.setCurrentMessage(l), this.sessionState.setTurnOpen(this.openTurns.size > 0), this.suspendState = !0, this.restoreQueuedMessages(), t(!0);
1273
1347
  });
1274
1348
  }
1275
- async sleep(t) {
1276
- return new Promise((e) => setTimeout(e, t));
1349
+ /**
1350
+ * Stop the running turn for good: the server cancels the run (what was queued on it comes back to the composer, as
1351
+ * on a pause) and the turn closes with what it had streamed, instead of waiting suspended for a "Continue". The
1352
+ * next message starts a turn of its own. Rejects, like {@link suspend}, when the server did not confirm.
1353
+ */
1354
+ async stop() {
1355
+ var s;
1356
+ const e = await this.suspend();
1357
+ this.suspendState = !1;
1358
+ const t = (s = this.currentIS) == null ? void 0 : s.interaction;
1359
+ return t && (t.isSuspended = !1), t && !this.committedTurns.has(t.interactionId) && (this.committedTurns.add(t.interactionId), this.liveMessage.cancelPending(), this.sessionState.setNewMessage(t), this.eventBusService.gatewayEmitTurnComplete(t.interactionId, t)), this.sessionState.setTurnOpen(this.openTurns.size > 0), e;
1360
+ }
1361
+ async sleep(e) {
1362
+ return new Promise((t) => setTimeout(t, e));
1277
1363
  }
1278
1364
  };
1279
1365
  h(y, "AgentGatewayWSAsync"), // How often the streaming message re-renders. 150 ms made a reasoning highlight, or a burst of them, visibly lag the
1280
1366
  // server (Ciro, 2026-10-07). The server already merges deltas over a 50 ms window (the SDK's DeltaCoalescer), so
1281
1367
  // frames arrive at ~20/s per kind and 20 ms here costs little: it mostly stops adding a second delay on top.
1282
- o(y, "CURRENT_MSG_THROTTLE_MS", 20), /**
1368
+ a(y, "CURRENT_MSG_THROTTLE_MS", 20), /**
1283
1369
  * How long an open turn survives a connection outage. While the supervisor is redialling the
1284
1370
  * turn stays open — a short blip resumes it from the replay cursor, and a server that comes back
1285
1371
  * (or another instance) closes it with an error if its run is gone. Past this, nobody can tell
1286
1372
  * us anything, and a turn that is still open is a composer that is still locked: the client
1287
1373
  * closes it itself, with an error part, so the user can go on.
1288
1374
  */
1289
- o(y, "OUTAGE_CLOSES_TURN_AFTER_MS", 6e4), o(y, "OUTAGE_TURN_MESSAGE", "Sem conexão com o servidor há mais de um minuto. A resposta foi interrompida."), /** What a send reports when the socket could not be brought up for it. */
1290
- o(y, "NO_CONNECTION_MESSAGE", "Não foi possível obter conexão com o servidor"), o(y, "HALT_TURN_MESSAGE", {
1375
+ a(y, "OUTAGE_CLOSES_TURN_AFTER_MS", 6e4), a(y, "OUTAGE_TURN_MESSAGE", "Sem conexão com o servidor há mais de um minuto. A resposta foi interrompida."), /** What a send reports when the socket could not be brought up for it. */
1376
+ a(y, "NO_CONNECTION_MESSAGE", "Não foi possível obter conexão com o servidor"), a(y, "HALT_TURN_MESSAGE", {
1291
1377
  "attached-elsewhere": "Esta sessão está aberta em outra janela. A resposta foi interrompida.",
1292
1378
  "session-gone": "A sessão não existe mais no servidor. A resposta foi interrompida.",
1293
1379
  "closed-by-server": "O servidor encerrou a conexão. A resposta foi interrompida."
1294
1380
  });
1295
- let yt = y;
1296
- function le(i) {
1297
- const t = new Pt();
1298
- t.author = "main", t.streamingParts = i.streamingParts, i.partialEventType ? t.eventType = i.partialEventType : t.eventType = i.functionName ? { fullName: z.StreamingFunctionCallUpdateContent, type: I.PartialFunctionCall } : i.partialReasoning ? { fullName: z.StreamingReasoningContent, type: I.Thought } : { fullName: z.StreamingTextContent, type: I.Text }, t.interactionId = i.iteractionId ?? "", t.mimeType = "text/plain", t.partial = !0, t.role = { label: "Assistant" }, t.timestamp = i.timeStamp ?? (/* @__PURE__ */ new Date()).getTime(), t.turnComplete = !1;
1299
- const e = t.eventType.type;
1300
- if (e == I.PartialFunctionCall) {
1301
- const s = new Ft();
1302
- s.choiceIndex = 0, s.callId = i.functionCallId, s.arguments = i.partialText, s.name = i.functionName, t.content = { items: [s], role: { label: "Assistant" } };
1303
- } else if (e == I.Text)
1304
- if (t.eventType.fullName == z.StreamingTextContent) {
1305
- const s = new _t();
1306
- s.text = i.partialText, t.content = { items: [s], role: { label: "Assistant" } };
1381
+ let ye = y;
1382
+ function lt(i) {
1383
+ const e = new Pe();
1384
+ 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;
1385
+ const t = e.eventType.type;
1386
+ if (t == I.PartialFunctionCall) {
1387
+ const s = new Fe();
1388
+ s.choiceIndex = 0, s.callId = i.functionCallId, s.arguments = i.partialText, s.name = i.functionName, e.content = { items: [s], role: { label: "Assistant" } };
1389
+ } else if (t == I.Text)
1390
+ if (e.eventType.fullName == z.StreamingTextContent) {
1391
+ const s = new Ne();
1392
+ s.text = i.partialText, e.content = { items: [s], role: { label: "Assistant" } };
1307
1393
  } else {
1308
- const s = new Nt();
1309
- s.text = i.partialText, t.content = { items: [s], role: { label: "Assistant" } };
1394
+ const s = new _e();
1395
+ s.text = i.partialText, e.content = { items: [s], role: { label: "Assistant" } };
1310
1396
  }
1311
- else if (e == I.Thought) {
1312
- const s = new Ut();
1313
- s.text = i.partialReasoning, t.content = { items: [s], role: { label: "Assistant" } };
1397
+ else if (t == I.Thought) {
1398
+ const s = new Ue();
1399
+ s.text = i.partialReasoning, e.content = { items: [s], role: { label: "Assistant" } };
1314
1400
  }
1315
- return t;
1401
+ return e;
1316
1402
  }
1317
- h(le, "llmEventFromPartial");
1318
- function st(i) {
1319
- const t = i.partialEvent ? le(i.partialEvent) : i.event;
1320
- if (t)
1321
- return i.detachedRunId && (t.detachedRunId = i.detachedRunId, t.detachedRunName = i.detachedRunName), t;
1403
+ h(lt, "llmEventFromPartial");
1404
+ function se(i) {
1405
+ const e = i.partialEvent ? lt(i.partialEvent) : i.event;
1406
+ if (e)
1407
+ return i.detachedRunId && (e.detachedRunId = i.detachedRunId, e.detachedRunName = i.detachedRunName), e;
1322
1408
  }
1323
- h(st, "llmEventFromFrame");
1324
- function $t(i) {
1325
- var t, e, s;
1326
- return (((e = (t = i.content) == null ? void 0 : t.items) == null ? void 0 : e.length) ?? 0) > 0 || (((s = i.streamingParts) == null ? void 0 : s.length) ?? 0) > 0;
1409
+ h(se, "llmEventFromFrame");
1410
+ function $e(i) {
1411
+ var e, t, s;
1412
+ 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;
1327
1413
  }
1328
- h($t, "carriesContent");
1329
- function Rt(i) {
1330
- var e;
1331
- if (i.type !== "InteractionStarted" || !((e = i.interaction) != null && e.interactionId)) return;
1414
+ h($e, "carriesContent");
1415
+ function Re(i) {
1416
+ var t;
1417
+ if (i.type !== "InteractionStarted" || !((t = i.interaction) != null && t.interactionId)) return;
1332
1418
  if (i.interaction.detachedRunId || !i.detachedRunId) return i.interaction;
1333
- const t = Object.assign(new Lt(), i.interaction);
1334
- return t.detachedRunId = i.detachedRunId, t;
1419
+ const e = Object.assign(new Le(), i.interaction);
1420
+ return e.detachedRunId = i.detachedRunId, e;
1335
1421
  }
1336
- h(Rt, "interactionStartFromFrame");
1337
- const he = 0.02;
1338
- function ue(i, t) {
1339
- if (!t) return null;
1340
- const e = (t.interactionsCompressed ?? 0) > 0 || (t.compressionRatio ?? 0) > 0;
1422
+ h(Re, "interactionStartFromFrame");
1423
+ const ht = 0.02;
1424
+ function ut(i, e) {
1425
+ if (!e) return null;
1426
+ const t = (e.interactionsCompressed ?? 0) > 0 || (e.compressionRatio ?? 0) > 0;
1341
1427
  if (!i)
1342
- return e ? vt(t, t.size, t.size) : null;
1343
- const s = i.size - t.size, n = t.maxSize || i.maxSize || 0, r = n > 0 ? s / n >= he : i.size > 0 && s / i.size >= 0.1;
1344
- return !e && !r ? null : vt(t, i.size, t.size, i.ratio);
1428
+ return t ? ve(e, e.size, e.size) : null;
1429
+ 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;
1430
+ return !t && !r ? null : ve(e, i.size, e.size, i.ratio);
1345
1431
  }
1346
- h(ue, "detectCompaction");
1347
- function vt(i, t, e, s) {
1432
+ h(ut, "detectCompaction");
1433
+ function ve(i, e, t, s) {
1348
1434
  return {
1349
1435
  at: Date.now(),
1350
1436
  // Where the bar stood when it happened — the marker's position. The ratio
1351
1437
  // BEFORE the pass is the meaningful one: it is the fill the compaction
1352
1438
  // reacted to, and it is also the only one that does not move afterwards.
1353
1439
  ratio: s ?? i.ratio,
1354
- sizeBefore: t,
1355
- sizeAfter: e,
1440
+ sizeBefore: e,
1441
+ sizeAfter: t,
1356
1442
  interactionsCompressed: i.interactionsCompressed
1357
1443
  };
1358
1444
  }
1359
- h(vt, "entry");
1360
- const Et = 4, de = 3, fe = 20, P = class P {
1445
+ h(ve, "entry");
1446
+ const Ee = 4, dt = 3, ft = 20, P = class P {
1361
1447
  constructor() {
1362
- o(this, "stats");
1363
- o(this, "onFlush");
1364
- o(this, "sessionCompactions", []);
1365
- o(this, "previousSessionInformation");
1448
+ a(this, "stats");
1449
+ a(this, "onFlush");
1450
+ a(this, "sessionCompactions", []);
1451
+ a(this, "previousSessionInformation");
1366
1452
  /** [timestamp, text length] per frame, for the sliding-window rate. */
1367
- o(this, "events", []);
1368
- o(this, "flushTimer", null);
1369
- o(this, "lastFlushed", 0);
1453
+ a(this, "events", []);
1454
+ a(this, "flushTimer", null);
1455
+ a(this, "lastFlushed", 0);
1370
1456
  this.stats = this.fresh();
1371
1457
  }
1372
1458
  fresh() {
@@ -1390,76 +1476,76 @@ const Et = 4, de = 3, fe = 20, P = class P {
1390
1476
  * Account for one decoded frame. `sessionInformation` is only read off main-agent
1391
1477
  * frames — a detached run's reading describes a different session.
1392
1478
  */
1393
- record(t) {
1394
- const e = Date.now();
1395
- if (this.events.push([e, t.textLength]), this.stats.eventCount += 1, this.stats.totalTransfered += t.rawLength, t.sessionInformation && !t.fromDetachedRun) {
1396
- const r = ue(this.previousSessionInformation, t.sessionInformation);
1397
- r && (this.sessionCompactions.push(r), this.sessionCompactions.length > fe && this.sessionCompactions.shift()), this.previousSessionInformation = t.sessionInformation, this.stats.sessionInformation = t.sessionInformation, this.stats.sessionCompactions = this.sessionCompactions;
1479
+ record(e) {
1480
+ const t = Date.now();
1481
+ if (this.events.push([t, e.textLength]), this.stats.eventCount += 1, this.stats.totalTransfered += e.rawLength, e.sessionInformation && !e.fromDetachedRun) {
1482
+ const r = ut(this.previousSessionInformation, e.sessionInformation);
1483
+ 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;
1398
1484
  }
1399
- this.stats.elapsed = (e - this.stats.startTime.getTime()) / 1e3;
1400
- const s = e - Et * 1e3;
1485
+ this.stats.elapsed = (t - this.stats.startTime.getTime()) / 1e3;
1486
+ const s = t - Ee * 1e3;
1401
1487
  for (; this.events.length > 0 && this.events[0][0] <= s; ) this.events.shift();
1402
- const n = this.events.reduce((r, a) => r + a[1], 0);
1403
- this.stats.tokensPerSecond = n / de / Et, this.flushCoalesced();
1488
+ const n = this.events.reduce((r, o) => r + o[1], 0);
1489
+ this.stats.tokensPerSecond = n / dt / Ee, this.flushCoalesced();
1404
1490
  }
1405
1491
  flushCoalesced() {
1406
1492
  if (!this.onFlush) return;
1407
- const t = Date.now(), e = t - this.lastFlushed;
1408
- if (e >= P.STATS_FLUSH_MS) {
1409
- this.flushTimer && (clearTimeout(this.flushTimer), this.flushTimer = null), this.lastFlushed = t, this.onFlush({ ...this.stats });
1493
+ const e = Date.now(), t = e - this.lastFlushed;
1494
+ if (t >= P.STATS_FLUSH_MS) {
1495
+ this.flushTimer && (clearTimeout(this.flushTimer), this.flushTimer = null), this.lastFlushed = e, this.onFlush({ ...this.stats });
1410
1496
  return;
1411
1497
  }
1412
1498
  this.flushTimer || (this.flushTimer = setTimeout(() => {
1413
1499
  var s;
1414
1500
  this.flushTimer = null, this.lastFlushed = Date.now(), (s = this.onFlush) == null || s.call(this, { ...this.stats });
1415
- }, P.STATS_FLUSH_MS - e));
1501
+ }, P.STATS_FLUSH_MS - t));
1416
1502
  }
1417
1503
  };
1418
- h(P, "StreamStatsTracker"), o(P, "STATS_FLUSH_MS", 120);
1419
- let tt = P;
1420
- const ge = 5e3, pe = 3e4, Y = 1e4, lt = class lt {
1421
- constructor(t = "ws://localhost:8000", e) {
1422
- o(this, "ws", null);
1504
+ h(P, "StreamStatsTracker"), a(P, "STATS_FLUSH_MS", 120);
1505
+ let ee = P;
1506
+ const gt = 5e3, pt = 3e4, Y = 1e4, le = class le {
1507
+ constructor(e = "ws://localhost:8000", t) {
1508
+ a(this, "ws", null);
1423
1509
  /** Frame counts, byte totals, the token-rate estimate and the compaction history — see StreamStatsTracker. */
1424
- o(this, "statsTracker", new tt());
1425
- o(this, "baseUrl");
1510
+ a(this, "statsTracker", new ee());
1511
+ a(this, "baseUrl");
1426
1512
  /**
1427
1513
  * Optional callback that returns the current JWT. We re-evaluate it on every connect/reconnect
1428
1514
  * so that a refreshed token is picked up automatically. Browsers can't set the Authorization
1429
1515
  * header on the WebSocket handshake, so we pass the JWT via the ?access_token= query string,
1430
1516
  * which the .NET JwtBearer events handler reads in Program.cs.
1431
1517
  */
1432
- o(this, "getToken");
1433
- o(this, "onEvent");
1434
- o(this, "onError");
1435
- o(this, "onOpen");
1436
- o(this, "onFirstToken");
1437
- o(this, "onSuspended");
1438
- o(this, "onBillingLimit");
1439
- o(this, "onClose");
1518
+ a(this, "getToken");
1519
+ a(this, "onEvent");
1520
+ a(this, "onError");
1521
+ a(this, "onOpen");
1522
+ a(this, "onFirstToken");
1523
+ a(this, "onSuspended");
1524
+ a(this, "onBillingLimit");
1525
+ a(this, "onClose");
1440
1526
  /**
1441
1527
  * Fired when the server signals that we lost streaming events on resume — our
1442
1528
  * `lastSeq` fell off the end of the in-memory replay buffer. Consumers should
1443
1529
  * reset partial-streaming UI for this session and rely on persisted history.
1444
1530
  */
1445
- o(this, "onRewindLost");
1446
- o(this, "onInteractionStarted");
1447
- o(this, "sessionId");
1448
- o(this, "monitorInterval", null);
1449
- o(this, "streamingResponseSerializer");
1450
- o(this, "lastActivity");
1531
+ a(this, "onRewindLost");
1532
+ a(this, "onInteractionStarted");
1533
+ a(this, "sessionId");
1534
+ a(this, "monitorInterval", null);
1535
+ a(this, "streamingResponseSerializer");
1536
+ a(this, "lastActivity");
1451
1537
  /** When the outstanding heartbeat Ping went out; null while no reply is pending. */
1452
- o(this, "pingSentAt", null);
1453
- o(this, "firstTokenInteractions");
1538
+ a(this, "pingSentAt", null);
1539
+ a(this, "firstTokenInteractions");
1454
1540
  /** Last sessionId we successfully had — stamps parked answers, labels log lines. */
1455
- o(this, "lastKnownSessionId");
1541
+ a(this, "lastKnownSessionId");
1456
1542
  /**
1457
1543
  * Highest server-assigned `seq` we have observed and processed. The next
1458
1544
  * reconnect appends `?lastSeq={lastSeq}` so the server can replay anything
1459
1545
  * we missed from the InteractionRun's in-memory buffer. -1 means "haven't
1460
1546
  * seen any sequenced events yet" (fresh connection).
1461
1547
  */
1462
- o(this, "lastSeq", -1);
1548
+ a(this, "lastSeq", -1);
1463
1549
  /**
1464
1550
  * Parked-tool answers that could not be sent because the socket was not OPEN
1465
1551
  * (e.g. the connection idled out while the user was in an IdP sign-in popup).
@@ -1468,15 +1554,15 @@ const ge = 5e3, pe = 3e4, Y = 1e4, lt = class lt {
1468
1554
  * answer for a session this instance is no longer attached to is dropped —
1469
1555
  * the single-attach policy makes it undeliverable from here anyway.
1470
1556
  */
1471
- o(this, "pendingAnswers", []);
1472
- this.baseUrl = t, this.getToken = e, this.firstTokenInteractions = /* @__PURE__ */ new Set(), this.streamingResponseSerializer = et(), console.log("SOCKET INSTACE", Gt()), this.lastActivity = (/* @__PURE__ */ new Date()).getTime();
1557
+ a(this, "pendingAnswers", []);
1558
+ 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();
1473
1559
  }
1474
1560
  get stats() {
1475
1561
  return this.statsTracker.stats;
1476
1562
  }
1477
1563
  /** Coalesced stats updates (see StreamStatsTracker.STATS_FLUSH_MS). */
1478
- set onNewPacket(t) {
1479
- this.statsTracker.onFlush = t;
1564
+ set onNewPacket(e) {
1565
+ this.statsTracker.onFlush = e;
1480
1566
  }
1481
1567
  get onNewPacket() {
1482
1568
  return this.statsTracker.onFlush;
@@ -1490,59 +1576,59 @@ const ge = 5e3, pe = 3e4, Y = 1e4, lt = class lt {
1490
1576
  * while we were away (`?lastSeq=N`). Without it the dial is fresh and the cursor is dropped:
1491
1577
  * a cursor from one conversation must never be presented to another.
1492
1578
  */
1493
- connect(t, e) {
1579
+ connect(e, t) {
1494
1580
  return new Promise(async (s, n) => {
1495
- var D, F;
1496
- e != null && e.resume || (this.lastSeq = -1);
1497
- const r = (D = this.getToken) == null ? void 0 : D.call(this), a = [];
1498
- r && a.push(`access_token=${encodeURIComponent(r)}`), t && this.lastSeq >= 0 && a.push(`lastSeq=${this.lastSeq}`), t && (e != null && e.resume) && e.openInteractionId && a.push(`openInteraction=${encodeURIComponent(e.openInteractionId)}`);
1499
- const c = a.length > 0 ? `?${a.join("&")}` : "", l = this.baseUrl.replace(/^http:\/\//, "ws://").replace(/^https:\/\//, "wss://"), f = `${l}/ws/connect/${t ?? ""}${c}`;
1500
- console.log("[WebSocket] Connecting to", `${l}/ws/connect/${t ?? ""}` + (t && this.lastSeq >= 0 ? ` (resume lastSeq=${this.lastSeq})` : "")), this.detachSocket(), this.ws = new WebSocket(f), this.ws.onopen = () => {
1581
+ var D, N;
1582
+ t != null && t.resume || (this.lastSeq = -1);
1583
+ const r = (D = this.getToken) == null ? void 0 : D.call(this), o = [];
1584
+ 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)}`);
1585
+ const c = o.length > 0 ? `?${o.join("&")}` : "", l = this.baseUrl.replace(/^http:\/\//, "ws://").replace(/^https:\/\//, "wss://"), f = `${l}/ws/connect/${e ?? ""}${c}`;
1586
+ console.log("[WebSocket] Connecting to", `${l}/ws/connect/${e ?? ""}` + (e && this.lastSeq >= 0 ? ` (resume lastSeq=${this.lastSeq})` : "")), this.detachSocket(), this.ws = new WebSocket(f), this.ws.onopen = () => {
1501
1587
  console.log("[WebSocket] Socket open — waiting for the session id"), this.ping(), this.monitor();
1502
- }, this.ws.onmessage = (E) => {
1588
+ }, this.ws.onmessage = (v) => {
1503
1589
  try {
1504
1590
  this.lastActivity = (/* @__PURE__ */ new Date()).getTime(), this.pingSentAt = null;
1505
- const M = this.streamingResponseSerializer.parse(E.data);
1591
+ const M = this.streamingResponseSerializer.parse(v.data);
1506
1592
  if (!M)
1507
1593
  throw "Error parsing event JSON";
1508
- this.handleMessage(M, E.data);
1594
+ this.handleMessage(M, v.data);
1509
1595
  } catch (M) {
1510
1596
  console.error("[WebSocket] Error parsing message:", M);
1511
1597
  }
1512
- }, this.ws.onerror = (E) => {
1513
- console.error("[WebSocket] Error:", E), this.onError && this.onError("WebSocket error");
1514
- }, this.ws.onclose = (E) => {
1598
+ }, this.ws.onerror = (v) => {
1599
+ console.error("[WebSocket] Error:", v), this.onError && this.onError("WebSocket error");
1600
+ }, this.ws.onclose = (v) => {
1515
1601
  var M;
1516
- console.log(`[WebSocket] Closed: code=${E.code} reason="${E.reason}" (session ${this.sessionLabel}, lastSeq=${this.lastSeq})`), this.monitorInterval && (clearInterval(this.monitorInterval), this.monitorInterval = null), this.pingSentAt = null, this.sessionId = void 0, (M = this.onClose) == null || M.call(this, E.code, E.reason);
1602
+ console.log(`[WebSocket] Closed: code=${v.code} reason="${v.reason}" (session ${this.sessionLabel}, lastSeq=${this.lastSeq})`), this.monitorInterval && (clearInterval(this.monitorInterval), this.monitorInterval = null), this.pingSentAt = null, this.sessionId = void 0, (M = this.onClose) == null || M.call(this, v.code, v.reason);
1517
1603
  };
1518
- const p = 200, w = 3e4, u = 8e3, g = this.ws;
1604
+ const g = 200, m = 3e4, u = 8e3, p = this.ws;
1519
1605
  this.sessionId = void 0;
1520
- let m = 0, v = 0;
1606
+ let w = 0, C = 0;
1521
1607
  for (; ; ) {
1522
- if (this.ws !== g) {
1608
+ if (this.ws !== p) {
1523
1609
  n("Connection attempt superseded by a newer connect()");
1524
1610
  return;
1525
1611
  }
1526
1612
  if (this.sessionId) break;
1527
- if (g.readyState === WebSocket.CLOSING || g.readyState === WebSocket.CLOSED) {
1613
+ if (p.readyState === WebSocket.CLOSING || p.readyState === WebSocket.CLOSED) {
1528
1614
  n("Connection closed before a session id was received");
1529
1615
  return;
1530
1616
  }
1531
- if (g.readyState === WebSocket.CONNECTING && m >= w) {
1617
+ if (p.readyState === WebSocket.CONNECTING && w >= m) {
1532
1618
  try {
1533
- g.close();
1619
+ p.close();
1534
1620
  } catch {
1535
1621
  }
1536
- n(`Server did not accept the connection within ${w / 1e3}s`);
1622
+ n(`Server did not accept the connection within ${m / 1e3}s`);
1537
1623
  return;
1538
1624
  }
1539
- if (g.readyState === WebSocket.OPEN && v >= u) {
1625
+ if (p.readyState === WebSocket.OPEN && C >= u) {
1540
1626
  n(`Connected but no session id arrived within ${u / 1e3}s`);
1541
1627
  return;
1542
1628
  }
1543
- m % 2e3 === 0 && console.log("Aguardando session Id"), await this.sleep(p), m += p, g.readyState === WebSocket.OPEN && (v += p);
1629
+ w % 2e3 === 0 && console.log("Aguardando session Id"), await this.sleep(g), w += g, p.readyState === WebSocket.OPEN && (C += g);
1544
1630
  }
1545
- console.log(`[WebSocket] Session ${this.sessionId} proven${this.lastSeq >= 0 ? ` (replaying from lastSeq=${this.lastSeq})` : ""}.`), this.lastKnownSessionId = this.sessionId, (F = this.onOpen) == null || F.call(this), this.flushPendingAnswers(this.sessionId), s(this.sessionId);
1631
+ 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);
1546
1632
  });
1547
1633
  }
1548
1634
  /** Drop the current socket without reporting it: handlers off, then close. */
@@ -1556,8 +1642,8 @@ const ge = 5e3, pe = 3e4, Y = 1e4, lt = class lt {
1556
1642
  this.ws = null;
1557
1643
  }
1558
1644
  }
1559
- async sleep(t) {
1560
- return new Promise((e) => setTimeout(e, t));
1645
+ async sleep(e) {
1646
+ return new Promise((t) => setTimeout(t, e));
1561
1647
  }
1562
1648
  /** The session this instance believes it is on — for log lines, never for logic. */
1563
1649
  get sessionLabel() {
@@ -1566,15 +1652,15 @@ const ge = 5e3, pe = 3e4, Y = 1e4, lt = class lt {
1566
1652
  /**
1567
1653
  * Handle incoming messages from server
1568
1654
  */
1569
- handleMessage(t, e) {
1655
+ handleMessage(e, t) {
1570
1656
  var n;
1571
- switch (typeof t.seq == "number" && t.seq > this.lastSeq && (this.lastSeq = t.seq), t.type) {
1657
+ switch (typeof e.seq == "number" && e.seq > this.lastSeq && (this.lastSeq = e.seq), e.type) {
1572
1658
  case "Pong":
1573
- if (this.sessionId = t.sessionId, this.lastKnownSessionId = t.sessionId ?? this.lastKnownSessionId, !t.sessionId) {
1659
+ if (this.sessionId = e.sessionId, this.lastKnownSessionId = e.sessionId ?? this.lastKnownSessionId, !e.sessionId) {
1574
1660
  console.error("Pong response has no SESSION ID");
1575
1661
  return;
1576
1662
  }
1577
- t.accessToken && this.persistRefreshedAccessToken(t.accessToken);
1663
+ e.accessToken && this.persistRefreshedAccessToken(e.accessToken);
1578
1664
  break;
1579
1665
  case "Suspended":
1580
1666
  this.onSuspended && this.onSuspended();
@@ -1582,24 +1668,24 @@ const ge = 5e3, pe = 3e4, Y = 1e4, lt = class lt {
1582
1668
  case "Event":
1583
1669
  break;
1584
1670
  case "InteractionStarted": {
1585
- const r = Rt(t);
1671
+ const r = Re(e);
1586
1672
  r ? (n = this.onInteractionStarted) == null || n.call(this, r) : console.warn("[WebSocket] InteractionStarted frame without an interaction id");
1587
1673
  break;
1588
1674
  }
1589
1675
  case "RewindLost":
1590
1676
  console.warn(
1591
- `[WebSocket] RewindLost: lost events on resume, resuming from seq=${t.seq}`
1592
- ), typeof t.seq == "number" && (this.lastSeq = t.seq - 1), this.onRewindLost && t.sessionId && this.onRewindLost(t.sessionId, t.seq ?? -1);
1677
+ `[WebSocket] RewindLost: lost events on resume, resuming from seq=${e.seq}`
1678
+ ), typeof e.seq == "number" && (this.lastSeq = e.seq - 1), this.onRewindLost && e.sessionId && this.onRewindLost(e.sessionId, e.seq ?? -1);
1593
1679
  break;
1594
1680
  default:
1595
- console.warn("[WebSocket] Unknown message type:", t.type);
1681
+ console.warn("[WebSocket] Unknown message type:", e.type);
1596
1682
  }
1597
- const s = st(t);
1598
- return s ? ($t(s) && this.emitFirstToken(s.interactionId), this.handleEvent(s, e), s) : null;
1683
+ const s = se(e);
1684
+ return s ? ($e(s) && this.emitFirstToken(s.interactionId), this.handleEvent(s, t), s) : null;
1599
1685
  }
1600
- emitFirstToken(t) {
1601
- var e;
1602
- !t || this.firstTokenInteractions.has(t) || (this.statsTracker.resetForInteraction(), this.firstTokenInteractions.add(t), (e = this.onFirstToken) == null || e.call(this, t));
1686
+ emitFirstToken(e) {
1687
+ var t;
1688
+ !e || this.firstTokenInteractions.has(e) || (this.statsTracker.resetForInteraction(), this.firstTokenInteractions.add(e), (t = this.onFirstToken) == null || t.call(this, e));
1603
1689
  }
1604
1690
  /**
1605
1691
  * Mirror a server-side-refreshed JWT into the stored user record so the global
@@ -1614,17 +1700,17 @@ const ge = 5e3, pe = 3e4, Y = 1e4, lt = class lt {
1614
1700
  * memory will pick up the new token on the next refresh/render or via their
1615
1701
  * own storage listeners.
1616
1702
  */
1617
- persistRefreshedAccessToken(t) {
1618
- const e = "envision_user";
1703
+ persistRefreshedAccessToken(e) {
1704
+ const t = "envision_user";
1619
1705
  try {
1620
- const s = localStorage.getItem(e);
1706
+ const s = localStorage.getItem(t);
1621
1707
  if (!s) {
1622
1708
  console.warn("[WebSocket] WS-refreshed token received but no stored user — dropping");
1623
1709
  return;
1624
1710
  }
1625
1711
  const n = JSON.parse(s);
1626
- if ((n == null ? void 0 : n.access_token) === t) return;
1627
- n.access_token = t, localStorage.setItem(e, JSON.stringify(n)), console.info("[WebSocket] Mirrored WS-refreshed JWT into stored user");
1712
+ if ((n == null ? void 0 : n.access_token) === e) return;
1713
+ n.access_token = e, localStorage.setItem(t, JSON.stringify(n)), console.info("[WebSocket] Mirrored WS-refreshed JWT into stored user");
1628
1714
  } catch (s) {
1629
1715
  console.error("[WebSocket] Failed to persist WS-refreshed token", s);
1630
1716
  }
@@ -1634,7 +1720,7 @@ const ge = 5e3, pe = 3e4, Y = 1e4, lt = class lt {
1634
1720
  }
1635
1721
  suspendStream() {
1636
1722
  this.sendBaseMessage({
1637
- Action: U.Suspend,
1723
+ Action: F.Suspend,
1638
1724
  AgentId: "",
1639
1725
  InteractionId: "",
1640
1726
  ModelId: ""
@@ -1651,36 +1737,36 @@ const ge = 5e3, pe = 3e4, Y = 1e4, lt = class lt {
1651
1737
  *
1652
1738
  * Returns 'sent' when it went out now, 'queued' when it will go out on reconnect.
1653
1739
  */
1654
- answerHumanTool(t, e) {
1740
+ answerHumanTool(e, t) {
1655
1741
  const s = {
1656
- Action: U.AnswerHumanTool,
1742
+ Action: F.AnswerHumanTool,
1657
1743
  AgentId: "",
1658
1744
  InteractionId: "",
1659
- ToolCallId: t,
1660
- Answer: e
1745
+ ToolCallId: e,
1746
+ Answer: t
1661
1747
  };
1662
1748
  if (this.ws && this.ws.readyState === WebSocket.OPEN)
1663
1749
  try {
1664
1750
  return this.sendBaseMessage(s), "sent";
1665
1751
  } catch {
1666
1752
  }
1667
- return this.queueAnswer(t, e), "queued";
1753
+ return this.queueAnswer(e, t), "queued";
1668
1754
  }
1669
- queueAnswer(t, e) {
1670
- this.pendingAnswers = this.pendingAnswers.filter((s) => s.toolCallId !== t), this.pendingAnswers.push({ sessionId: this.sessionId ?? this.lastKnownSessionId, toolCallId: t, answer: e }), console.warn(`[WebSocket] Socket not open — queued answer for tool call ${t}; will flush on reconnect.`);
1755
+ queueAnswer(e, t) {
1756
+ this.pendingAnswers = this.pendingAnswers.filter((s) => s.toolCallId !== e), this.pendingAnswers.push({ sessionId: this.sessionId ?? this.lastKnownSessionId, toolCallId: e, answer: t }), console.warn(`[WebSocket] Socket not open — queued answer for tool call ${e}; will flush on reconnect.`);
1671
1757
  }
1672
- flushPendingAnswers(t) {
1758
+ flushPendingAnswers(e) {
1673
1759
  if (this.pendingAnswers.length === 0) return;
1674
- const e = this.pendingAnswers;
1760
+ const t = this.pendingAnswers;
1675
1761
  this.pendingAnswers = [];
1676
- for (const s of e) {
1677
- if (s.sessionId && t && s.sessionId !== t) {
1678
- console.warn(`[WebSocket] Dropping queued answer for tool call ${s.toolCallId} — it belongs to session ${s.sessionId}, reconnected to ${t}.`);
1762
+ for (const s of t) {
1763
+ if (s.sessionId && e && s.sessionId !== e) {
1764
+ console.warn(`[WebSocket] Dropping queued answer for tool call ${s.toolCallId} — it belongs to session ${s.sessionId}, reconnected to ${e}.`);
1679
1765
  continue;
1680
1766
  }
1681
1767
  try {
1682
1768
  this.sendBaseMessage({
1683
- Action: U.AnswerHumanTool,
1769
+ Action: F.AnswerHumanTool,
1684
1770
  AgentId: "",
1685
1771
  InteractionId: "",
1686
1772
  ToolCallId: s.toolCallId,
@@ -1694,13 +1780,13 @@ const ge = 5e3, pe = 3e4, Y = 1e4, lt = class lt {
1694
1780
  /**
1695
1781
  * Send a message to the agent
1696
1782
  */
1697
- sendMessage(t) {
1698
- this.sendBaseMessage(t);
1783
+ sendMessage(e) {
1784
+ this.sendBaseMessage(e);
1699
1785
  }
1700
- sendBaseMessage(t) {
1786
+ sendBaseMessage(e) {
1701
1787
  if (this.lastActivity = (/* @__PURE__ */ new Date()).getTime(), !this.ws || this.ws.readyState !== WebSocket.OPEN)
1702
1788
  throw new Error("WebSocket is not connected");
1703
- this.ws.send(JSON.stringify(t));
1789
+ this.ws.send(JSON.stringify(e));
1704
1790
  }
1705
1791
  /**
1706
1792
  * Heartbeat: keep a quiet socket alive with a Ping every PING_INTERVAL_MS, and
@@ -1711,24 +1797,24 @@ const ge = 5e3, pe = 3e4, Y = 1e4, lt = class lt {
1711
1797
  this.monitorInterval && clearInterval(this.monitorInterval), this.monitorInterval = setInterval(() => {
1712
1798
  try {
1713
1799
  if (!this.isConnected()) return;
1714
- const t = Date.now();
1800
+ const e = Date.now();
1715
1801
  if (this.pingSentAt !== null) {
1716
- const e = t - this.pingSentAt;
1717
- if (e >= Y) {
1802
+ const t = e - this.pingSentAt;
1803
+ if (t >= Y) {
1718
1804
  this.failSocket(
1719
- ne,
1720
- `No frame received for ${Math.round(e / 1e3)}s after a Ping`
1805
+ nt,
1806
+ `No frame received for ${Math.round(t / 1e3)}s after a Ping`
1721
1807
  );
1722
1808
  return;
1723
1809
  }
1724
- console.warn(`[WebSocket] Still no reply ${e}ms after the Ping (budget ${Y}ms, session ${this.sessionLabel}) — the peer may be gone.`);
1810
+ console.warn(`[WebSocket] Still no reply ${t}ms after the Ping (budget ${Y}ms, session ${this.sessionLabel}) — the peer may be gone.`);
1725
1811
  return;
1726
1812
  }
1727
- t - this.lastActivity >= pe && this.ping();
1728
- } catch (t) {
1729
- console.error("Error on monitor", t);
1813
+ e - this.lastActivity >= pt && this.ping();
1814
+ } catch (e) {
1815
+ console.error("Error on monitor", e);
1730
1816
  }
1731
- }, ge);
1817
+ }, gt);
1732
1818
  }
1733
1819
  /**
1734
1820
  * Send a heartbeat ping and start the reply clock (unless one is already running).
@@ -1758,23 +1844,23 @@ const ge = 5e3, pe = 3e4, Y = 1e4, lt = class lt {
1758
1844
  * what a server close would have produced. Handlers are detached first so a
1759
1845
  * late real close event cannot run it a second time.
1760
1846
  */
1761
- failSocket(t, e) {
1847
+ failSocket(e, t) {
1762
1848
  const s = this.ws;
1763
1849
  if (!s) return;
1764
- 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.`);
1850
+ console.warn(`[WebSocket] ${t} — treating the socket as dead (code=${e}, session ${this.sessionLabel}). readyState was ${s.readyState} (OPEN=${WebSocket.OPEN}), which is why nothing else noticed. Running the close path now.`);
1765
1851
  const n = s.onclose;
1766
1852
  s.onopen = null, s.onmessage = null, s.onerror = null, s.onclose = null;
1767
1853
  try {
1768
1854
  s.close();
1769
1855
  } catch {
1770
1856
  }
1771
- n == null || n.call(s, { code: t, reason: e });
1857
+ n == null || n.call(s, { code: e, reason: t });
1772
1858
  }
1773
1859
  /**
1774
1860
  * Disconnect the WebSocket
1775
1861
  */
1776
1862
  disconnect() {
1777
- 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(kt, "Intentional disconnect"), this.ws = null);
1863
+ 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);
1778
1864
  }
1779
1865
  /**
1780
1866
  * Check if connected
@@ -1782,11 +1868,11 @@ const ge = 5e3, pe = 3e4, Y = 1e4, lt = class lt {
1782
1868
  isConnected() {
1783
1869
  return this.ws !== null && this.ws.readyState === WebSocket.OPEN;
1784
1870
  }
1785
- async handleEvent(t, e) {
1786
- var n, r, a, c;
1787
- const s = (r = (n = t.content) == null ? void 0 : n.items) == null ? void 0 : r.find((l) => l instanceof xt);
1871
+ async handleEvent(e, t) {
1872
+ var n, r, o, c;
1873
+ const s = (r = (n = e.content) == null ? void 0 : n.items) == null ? void 0 : r.find((l) => l instanceof qe);
1788
1874
  if (s) {
1789
- (a = this.onBillingLimit) == null || a.call(this, {
1875
+ (o = this.onBillingLimit) == null || o.call(this, {
1790
1876
  plan: s.plan ?? "team",
1791
1877
  state: s.state ?? "ok",
1792
1878
  used: s.used ?? 0,
@@ -1796,17 +1882,17 @@ const ge = 5e3, pe = 3e4, Y = 1e4, lt = class lt {
1796
1882
  title: s.title,
1797
1883
  message: s.message,
1798
1884
  actionUrl: s.actionUrl,
1799
- interactionId: t.interactionId || void 0
1885
+ interactionId: e.interactionId || void 0
1800
1886
  });
1801
1887
  return;
1802
1888
  }
1803
1889
  try {
1804
- const l = x.parseFromTypedEvent(t);
1890
+ const l = q.parseFromTypedEvent(e);
1805
1891
  if (!l)
1806
1892
  throw "Server event was null";
1807
1893
  this.statsTracker.record({
1808
- rawLength: e.length,
1809
- textLength: ((c = t.text) == null ? void 0 : c.length) ?? 0,
1894
+ rawLength: t.length,
1895
+ textLength: ((c = e.text) == null ? void 0 : c.length) ?? 0,
1810
1896
  sessionInformation: l.session_information,
1811
1897
  fromDetachedRun: !!l.detachedRunId
1812
1898
  }), this.onEvent && this.onEvent(l).catch((f) => {
@@ -1817,42 +1903,42 @@ const ge = 5e3, pe = 3e4, Y = 1e4, lt = class lt {
1817
1903
  }
1818
1904
  }
1819
1905
  };
1820
- h(lt, "WebSocketConnecionV2");
1821
- let Ct = lt;
1822
- const ht = class ht {
1823
- constructor(t, e) {
1824
- o(this, "cache", /* @__PURE__ */ new Map());
1825
- o(this, "serverBaseUrl");
1826
- o(this, "accessToken");
1827
- this.serverBaseUrl = t.replace(/\/$/, ""), this.accessToken = e;
1906
+ h(le, "WebSocketConnecionV2");
1907
+ let Me = le;
1908
+ const he = class he {
1909
+ constructor(e, t) {
1910
+ a(this, "cache", /* @__PURE__ */ new Map());
1911
+ a(this, "serverBaseUrl");
1912
+ a(this, "accessToken");
1913
+ this.serverBaseUrl = e.replace(/\/$/, ""), this.accessToken = t;
1828
1914
  }
1829
1915
  get headers() {
1830
- return { Authorization: `Bearer ${zt(this.accessToken)}` };
1916
+ return { Authorization: `Bearer ${ze(this.accessToken)}` };
1831
1917
  }
1832
1918
  async init() {
1833
1919
  }
1834
1920
  getArtifacts() {
1835
1921
  return Array.from(this.cache.values());
1836
1922
  }
1837
- async saveArtifact(t) {
1838
- this.cache.set(t.id, t);
1923
+ async saveArtifact(e) {
1924
+ this.cache.set(e.id, e);
1839
1925
  }
1840
- saveArtifactToCache(t) {
1841
- this.cache.set(t.id, t);
1926
+ saveArtifactToCache(e) {
1927
+ this.cache.set(e.id, e);
1842
1928
  }
1843
- async deleteArtifact(t) {
1844
- this.cache.delete(t);
1929
+ async deleteArtifact(e) {
1930
+ this.cache.delete(e);
1845
1931
  }
1846
- addToCache(t) {
1847
- this.cache.set(t.id, t);
1932
+ addToCache(e) {
1933
+ this.cache.set(e.id, e);
1848
1934
  }
1849
- getArtifactWithCache(t) {
1850
- return this.cache.get(t) ?? null;
1935
+ getArtifactWithCache(e) {
1936
+ return this.cache.get(e) ?? null;
1851
1937
  }
1852
- async getArtifact(t, e) {
1853
- if (this.cache.has(t)) return this.cache.get(t) ?? null;
1938
+ async getArtifact(e, t) {
1939
+ if (this.cache.has(e)) return this.cache.get(e) ?? null;
1854
1940
  try {
1855
- const s = await fetch(`${this.serverBaseUrl}/AdminArtifact/${t}`, {
1941
+ const s = await fetch(`${this.serverBaseUrl}/AdminArtifact/${e}`, {
1856
1942
  headers: this.headers
1857
1943
  });
1858
1944
  if (!s.ok) return null;
@@ -1865,94 +1951,94 @@ const ht = class ht {
1865
1951
  async clearAllArtifacts() {
1866
1952
  this.cache.clear();
1867
1953
  }
1868
- async getFileContent(t) {
1954
+ async getFileContent(e) {
1869
1955
  try {
1870
- const e = await fetch(t, { headers: this.headers });
1871
- return e.ok ? await e.text() : null;
1956
+ const t = await fetch(e, { headers: this.headers });
1957
+ return t.ok ? await t.text() : null;
1872
1958
  } catch {
1873
1959
  return null;
1874
1960
  }
1875
1961
  }
1876
1962
  };
1877
- h(ht, "HttpArtifactService");
1878
- let Mt = ht;
1879
- const ut = class ut extends Error {
1880
- constructor(t, e) {
1881
- super(e ?? `GET detached-run frames answered ${t}`), this.status = t, this.name = "DetachedRunFramesHttpError";
1963
+ h(he, "HttpArtifactService");
1964
+ let Ce = he;
1965
+ const ue = class ue extends Error {
1966
+ constructor(e, t) {
1967
+ super(t ?? `GET detached-run frames answered ${e}`), this.status = e, this.name = "DetachedRunFramesHttpError";
1882
1968
  }
1883
1969
  };
1884
- h(ut, "DetachedRunFramesHttpError");
1885
- let L = ut;
1886
- function me(i) {
1970
+ h(ue, "DetachedRunFramesHttpError");
1971
+ let L = ue;
1972
+ function mt(i) {
1887
1973
  if (i instanceof L) {
1888
- const { status: t } = i;
1889
- return { kind: t === 401 ? "unauthorized" : t === 403 ? "forbidden" : t === 404 || t === 410 ? "notFound" : "gaveUp", status: t, cause: i };
1974
+ const { status: e } = i;
1975
+ return { kind: e === 401 ? "unauthorized" : e === 403 ? "forbidden" : e === 404 || e === 410 ? "notFound" : "gaveUp", status: e, cause: i };
1890
1976
  }
1891
1977
  return { kind: "gaveUp", cause: i };
1892
1978
  }
1893
- h(me, "toDetachedRunFollowError");
1894
- function we(i) {
1895
- let t = "", e = [], s, n;
1979
+ h(mt, "toDetachedRunFollowError");
1980
+ function wt(i) {
1981
+ let e = "", t = [], s, n;
1896
1982
  const r = /* @__PURE__ */ h(() => {
1897
- (e.length > 0 || s !== void 0) && i({ event: s, data: e.join(`
1898
- `), id: n }), e = [], s = void 0, n = void 0;
1899
- }, "dispatch"), a = /* @__PURE__ */ h((c) => {
1983
+ (t.length > 0 || s !== void 0) && i({ event: s, data: t.join(`
1984
+ `), id: n }), t = [], s = void 0, n = void 0;
1985
+ }, "dispatch"), o = /* @__PURE__ */ h((c) => {
1900
1986
  if (c === "") return r();
1901
1987
  if (c.startsWith(":")) return;
1902
1988
  const l = c.indexOf(":"), f = l === -1 ? c : c.slice(0, l);
1903
- let p = l === -1 ? "" : c.slice(l + 1);
1904
- p.startsWith(" ") && (p = p.slice(1)), f === "data" ? e.push(p) : f === "event" ? s = p : f === "id" && (n = p);
1989
+ let g = l === -1 ? "" : c.slice(l + 1);
1990
+ g.startsWith(" ") && (g = g.slice(1)), f === "data" ? t.push(g) : f === "event" ? s = g : f === "id" && (n = g);
1905
1991
  }, "line");
1906
1992
  return {
1907
1993
  push(c) {
1908
- for (t += c; ; ) {
1909
- const l = t.search(/\r\n|\r|\n/);
1910
- if (l === -1 || t[l] === "\r" && l === t.length - 1) return;
1911
- const f = t.startsWith(`\r
1994
+ for (e += c; ; ) {
1995
+ const l = e.search(/\r\n|\r|\n/);
1996
+ if (l === -1 || e[l] === "\r" && l === e.length - 1) return;
1997
+ const f = e.startsWith(`\r
1912
1998
  `, l) ? 2 : 1;
1913
- a(t.slice(0, l)), t = t.slice(l + f);
1999
+ o(e.slice(0, l)), e = e.slice(l + f);
1914
2000
  }
1915
2001
  },
1916
2002
  /** Nothing half-received: no partial line buffered, no event begun and not yet dispatched. */
1917
2003
  idle() {
1918
- return t === "" && e.length === 0 && s === void 0 && n === void 0;
2004
+ return e === "" && t.length === 0 && s === void 0 && n === void 0;
1919
2005
  },
1920
2006
  flush() {
1921
- t !== "" && a(t.replace(/\r$/, "")), t = "";
2007
+ e !== "" && o(e.replace(/\r$/, "")), e = "";
1922
2008
  }
1923
2009
  };
1924
2010
  }
1925
- h(we, "createSseParser");
1926
- function Se(i) {
2011
+ h(wt, "createSseParser");
2012
+ function St(i) {
1927
2013
  return i >= 500 || i === 408 || i === 429;
1928
2014
  }
1929
- h(Se, "retryable");
1930
- function Ie(i, t) {
1931
- return new Promise((e) => {
1932
- if (t != null && t.aborted) return e();
2015
+ h(St, "retryable");
2016
+ function It(i, e) {
2017
+ return new Promise((t) => {
2018
+ if (e != null && e.aborted) return t();
1933
2019
  const s = setTimeout(n, i);
1934
2020
  function n() {
1935
- clearTimeout(s), t == null || t.removeEventListener("abort", n), e();
2021
+ clearTimeout(s), e == null || e.removeEventListener("abort", n), t();
1936
2022
  }
1937
- h(n, "done"), t == null || t.addEventListener("abort", n, { once: !0 });
2023
+ h(n, "done"), e == null || e.addEventListener("abort", n, { once: !0 });
1938
2024
  });
1939
2025
  }
1940
- h(Ie, "sleep");
1941
- function Te(i, t, e, s) {
1942
- const n = t === "session" ? "sessions" : "detached-runs";
1943
- return `${i.replace(/\/+$/, "")}/${n}/${encodeURIComponent(e)}/frames?afterSeq=${s}`;
2026
+ h(It, "sleep");
2027
+ function Tt(i, e, t, s) {
2028
+ const n = e === "session" ? "sessions" : "detached-runs";
2029
+ return `${i.replace(/\/+$/, "")}/${n}/${encodeURIComponent(t)}/frames?afterSeq=${s}`;
1944
2030
  }
1945
- h(Te, "framesUrl");
1946
- async function ye(i) {
1947
- var F, E, M, ft, gt;
1948
- const { baseUrl: t, runId: e, signal: s, onFrame: n, onEnd: r, onOpen: a, onRetry: c } = i, l = i.resource ?? "detachedRun", f = i.fetchImpl ?? ((A, $) => fetch(A, $)), p = ((F = i.retry) == null ? void 0 : F.initialMs) ?? 500, w = ((E = i.retry) == null ? void 0 : E.maxMs) ?? 15e3, u = ((M = i.retry) == null ? void 0 : M.maxAttempts) ?? Number.POSITIVE_INFINITY;
1949
- let g = i.afterSeq ?? 0, m = 0, v = !1;
2031
+ h(Tt, "framesUrl");
2032
+ async function yt(i) {
2033
+ var N, v, M, fe, ge;
2034
+ 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;
2035
+ let p = i.afterSeq ?? 0, w = 0, C = !1;
1950
2036
  async function D(A) {
1951
2037
  if (i.onUnauthorized)
1952
2038
  try {
1953
2039
  if (await i.onUnauthorized()) return !0;
1954
2040
  } catch (O) {
1955
- console.warn(`[DetachedRunFrames] run ${e}: onUnauthorized threw`, O);
2041
+ console.warn(`[DetachedRunFrames] run ${t}: onUnauthorized threw`, O);
1956
2042
  }
1957
2043
  if (!i.getToken) return !1;
1958
2044
  const $ = await i.getToken() ?? void 0;
@@ -1961,99 +2047,99 @@ async function ye(i) {
1961
2047
  for (h(D, "secondChance"); !(s != null && s.aborted); ) {
1962
2048
  let A;
1963
2049
  try {
1964
- const O = { Accept: "text/event-stream" }, K = await ((ft = i.getToken) == null ? void 0 : ft.call(i)) ?? void 0;
1965
- K && (O.Authorization = `Bearer ${K}`);
1966
- const k = await f(Te(t, l, e, g), { method: "GET", headers: O, signal: s, cache: "no-store" });
2050
+ const O = { Accept: "text/event-stream" }, J = await ((fe = i.getToken) == null ? void 0 : fe.call(i)) ?? void 0;
2051
+ J && (O.Authorization = `Bearer ${J}`);
2052
+ const k = await f(Tt(e, l, t, p), { method: "GET", headers: O, signal: s, cache: "no-store" });
1967
2053
  if (k.status === 401) {
1968
- if (!v && await D(K)) {
1969
- v = !0;
2054
+ if (!C && await D(J)) {
2055
+ C = !0;
1970
2056
  continue;
1971
2057
  }
1972
2058
  throw new L(401);
1973
2059
  }
1974
- if (v = !1, !k.ok)
1975
- throw Se(k.status) ? new Error(`GET detached-run frames answered ${k.status}`) : new L(k.status);
2060
+ if (C = !1, !k.ok)
2061
+ throw St(k.status) ? new Error(`GET detached-run frames answered ${k.status}`) : new L(k.status);
1976
2062
  if (!k.body) throw new L(k.status, "The frames response has no readable body");
1977
- a == null || a();
2063
+ o == null || o();
1978
2064
  let W = !1;
1979
- const B = we((T) => {
2065
+ const B = wt((T) => {
1980
2066
  if (T.event === "end") {
1981
2067
  const b = Number(T.data);
1982
- T.data !== "" && Number.isFinite(b) && b > g && (g = b), W = !0;
2068
+ T.data !== "" && Number.isFinite(b) && b > p && (p = b), W = !0;
1983
2069
  return;
1984
2070
  }
1985
2071
  if (T.event !== void 0 && T.event !== "message" || T.data === "") return;
1986
2072
  const R = T.id !== void 0 && T.id !== "" ? Number(T.id) : void 0;
1987
2073
  if (R !== void 0 && Number.isFinite(R)) {
1988
- if (R <= g) return;
1989
- g = R;
2074
+ if (R <= p) return;
2075
+ p = R;
1990
2076
  }
1991
2077
  W = !1;
1992
- let mt;
2078
+ let me;
1993
2079
  try {
1994
- mt = JSON.parse(T.data);
2080
+ me = JSON.parse(T.data);
1995
2081
  } catch (b) {
1996
- console.warn(`[DetachedRunFrames] run ${e}: a frame that is not JSON was skipped (seq ${T.id ?? "?"})`, b);
2082
+ console.warn(`[DetachedRunFrames] run ${t}: a frame that is not JSON was skipped (seq ${T.id ?? "?"})`, b);
1997
2083
  return;
1998
2084
  }
1999
- m = 0;
2085
+ w = 0;
2000
2086
  try {
2001
- n(mt, R);
2087
+ n(me, R);
2002
2088
  } catch (b) {
2003
- console.error(`[DetachedRunFrames] run ${e}: onFrame threw on seq ${T.id ?? "?"}`, b);
2089
+ console.error(`[DetachedRunFrames] run ${t}: onFrame threw on seq ${T.id ?? "?"}`, b);
2004
2090
  }
2005
- }), G = k.body.getReader(), pt = new TextDecoder();
2091
+ }), G = k.body.getReader(), pe = new TextDecoder();
2006
2092
  try {
2007
2093
  for (; ; ) {
2008
2094
  const { done: T, value: R } = await G.read();
2009
2095
  if (T) break;
2010
- B.push(pt.decode(R, { stream: !0 }));
2096
+ B.push(pe.decode(R, { stream: !0 }));
2011
2097
  }
2012
- B.push(pt.decode()), B.idle() || (W = !1), B.flush();
2098
+ B.push(pe.decode()), B.idle() || (W = !1), B.flush();
2013
2099
  } finally {
2014
- (gt = G.releaseLock) == null || gt.call(G);
2100
+ (ge = G.releaseLock) == null || ge.call(G);
2015
2101
  }
2016
2102
  if (W && l !== "session")
2017
- return r == null || r(g), { reason: "end", lastSeq: g };
2103
+ return r == null || r(p), { reason: "end", lastSeq: p };
2018
2104
  A = new Error(l === "session" ? "The session frames stream closed" : "The frames stream closed before its end event");
2019
2105
  } catch (O) {
2020
2106
  if (s != null && s.aborted) break;
2021
2107
  if (O instanceof L) throw O;
2022
2108
  A = O;
2023
2109
  }
2024
- if (m += 1, m >= u) throw A;
2025
- const $ = Math.min(p * 2 ** (m - 1), w);
2110
+ if (w += 1, w >= u) throw A;
2111
+ const $ = Math.min(g * 2 ** (w - 1), m);
2026
2112
  try {
2027
- c == null || c(A, m, $);
2113
+ c == null || c(A, w, $);
2028
2114
  } catch {
2029
2115
  }
2030
- await Ie($, s);
2116
+ await It($, s);
2031
2117
  }
2032
- return { reason: "aborted", lastSeq: g };
2118
+ return { reason: "aborted", lastSeq: p };
2033
2119
  }
2034
- h(ye, "streamDetachedRunFrames");
2035
- const dt = class dt {
2036
- constructor(t) {
2037
- o(this, "onEvent");
2038
- o(this, "onError");
2039
- o(this, "onOpen");
2040
- o(this, "onFirstToken");
2041
- o(this, "onSuspended");
2042
- o(this, "onClose");
2043
- o(this, "onNewPacket");
2044
- o(this, "onInteractionStarted");
2120
+ h(yt, "streamDetachedRunFrames");
2121
+ const de = class de {
2122
+ constructor(e) {
2123
+ a(this, "onEvent");
2124
+ a(this, "onError");
2125
+ a(this, "onOpen");
2126
+ a(this, "onFirstToken");
2127
+ a(this, "onSuspended");
2128
+ a(this, "onClose");
2129
+ a(this, "onNewPacket");
2130
+ a(this, "onInteractionStarted");
2045
2131
  /** The stream of the current follow is over: the server closed it right after an `event: end`. */
2046
- o(this, "onEnd");
2132
+ a(this, "onEnd");
2047
2133
  /** Following stopped for good — the run is gone, forbidden, the credentials failed twice, or retries ran out. */
2048
- o(this, "onFollowError");
2049
- o(this, "options");
2050
- o(this, "serializer", et());
2051
- o(this, "firstTokens", /* @__PURE__ */ new Set());
2052
- o(this, "runId");
2053
- o(this, "controller", null);
2054
- o(this, "following", !1);
2055
- o(this, "lastSeq", 0);
2056
- this.options = t;
2134
+ a(this, "onFollowError");
2135
+ a(this, "options");
2136
+ a(this, "serializer", te());
2137
+ a(this, "firstTokens", /* @__PURE__ */ new Set());
2138
+ a(this, "runId");
2139
+ a(this, "controller", null);
2140
+ a(this, "following", !1);
2141
+ a(this, "lastSeq", 0);
2142
+ this.options = e;
2057
2143
  }
2058
2144
  /** The highest seq delivered so far — where the next follow resumes. */
2059
2145
  get cursor() {
@@ -2063,9 +2149,9 @@ const dt = class dt {
2063
2149
  get isFollowing() {
2064
2150
  return this.following;
2065
2151
  }
2066
- connect(t, e) {
2152
+ connect(e, t) {
2067
2153
  var s, n;
2068
- return t ? ((t !== this.runId || !(e != null && e.resume)) && (this.lastSeq = ((n = (s = this.options).initialAfterSeq) == null ? void 0 : n.call(s)) ?? 0, this.firstTokens.clear()), this.runId = t, this.start(t)) : Promise.reject(new Error("DetachedRunFramesTransport: connect() needs the run id"));
2154
+ return e ? ((e !== this.runId || !(t != null && t.resume)) && (this.lastSeq = ((n = (s = this.options).initialAfterSeq) == null ? void 0 : n.call(s)) ?? 0, this.firstTokens.clear()), this.runId = e, this.start(e)) : Promise.reject(new Error("DetachedRunFramesTransport: connect() needs the run id"));
2069
2155
  }
2070
2156
  /**
2071
2157
  * Follow again from the last seq — after the stream ended and the run was resumed (answered). A no-op while a
@@ -2074,20 +2160,20 @@ const dt = class dt {
2074
2160
  follow() {
2075
2161
  return this.runId ? this.following ? Promise.resolve(this.runId) : this.start(this.runId) : Promise.reject(new Error("DetachedRunFramesTransport: follow() before connect()"));
2076
2162
  }
2077
- start(t) {
2163
+ start(e) {
2078
2164
  var s;
2079
2165
  (s = this.controller) == null || s.abort();
2080
- const e = new AbortController();
2081
- return this.controller = e, this.following = !0, new Promise((n, r) => {
2082
- let a = !1;
2083
- ye({
2166
+ const t = new AbortController();
2167
+ return this.controller = t, this.following = !0, new Promise((n, r) => {
2168
+ let o = !1;
2169
+ yt({
2084
2170
  ...this.options,
2085
- runId: t,
2171
+ runId: e,
2086
2172
  afterSeq: this.lastSeq,
2087
- signal: e.signal,
2173
+ signal: t.signal,
2088
2174
  onOpen: /* @__PURE__ */ h(() => {
2089
2175
  var c;
2090
- a || (a = !0, (c = this.onOpen) == null || c.call(this), n(t));
2176
+ o || (o = !0, (c = this.onOpen) == null || c.call(this), n(e));
2091
2177
  }, "onOpen"),
2092
2178
  onFrame: /* @__PURE__ */ h((c, l) => {
2093
2179
  typeof l == "number" && l > this.lastSeq && (this.lastSeq = l), this.dispatch(c);
@@ -2097,116 +2183,116 @@ const dt = class dt {
2097
2183
  this.lastSeq = Math.max(this.lastSeq, c), (l = this.onEnd) == null || l.call(this, this.lastSeq);
2098
2184
  }, "onEnd"),
2099
2185
  onRetry: /* @__PURE__ */ h((c, l, f) => {
2100
- console.warn(`[DetachedRunFrames] run ${t}: the stream failed (attempt ${l}); following again from seq ${this.lastSeq} in ${f}ms.`, c);
2186
+ console.warn(`[DetachedRunFrames] run ${e}: the stream failed (attempt ${l}); following again from seq ${this.lastSeq} in ${f}ms.`, c);
2101
2187
  }, "onRetry")
2102
2188
  }).then(() => {
2103
- a || r(new Error("The frames stream stopped before it opened"));
2189
+ o || r(new Error("The frames stream stopped before it opened"));
2104
2190
  }).catch((c) => {
2105
- var p, w, u;
2106
- const l = me(c), f = l.kind === "notFound" ? Dt : l.kind === "forbidden" || l.kind === "unauthorized" ? 1008 : 1011;
2107
- console.error(`[DetachedRunFrames] run ${t}: following stopped (${l.kind})`, c);
2191
+ var g, m, u;
2192
+ const l = mt(c), f = l.kind === "notFound" ? De : l.kind === "forbidden" || l.kind === "unauthorized" ? 1008 : 1011;
2193
+ console.error(`[DetachedRunFrames] run ${e}: following stopped (${l.kind})`, c);
2108
2194
  try {
2109
- (p = this.onFollowError) == null || p.call(this, l);
2110
- } catch (g) {
2111
- console.error("[DetachedRunFrames] onFollowError threw", g);
2195
+ (g = this.onFollowError) == null || g.call(this, l);
2196
+ } catch (p) {
2197
+ console.error("[DetachedRunFrames] onFollowError threw", p);
2112
2198
  }
2113
- (w = this.onError) == null || w.call(this, String((c == null ? void 0 : c.message) ?? c)), (u = this.onClose) == null || u.call(this, f, String((c == null ? void 0 : c.message) ?? "")), a || r(c);
2199
+ (m = this.onError) == null || m.call(this, String((c == null ? void 0 : c.message) ?? c)), (u = this.onClose) == null || u.call(this, f, String((c == null ? void 0 : c.message) ?? "")), o || r(c);
2114
2200
  }).finally(() => {
2115
- this.controller === e && (this.following = !1);
2201
+ this.controller === t && (this.following = !1);
2116
2202
  });
2117
2203
  });
2118
2204
  }
2119
2205
  /** One frame, decoded exactly as the chat socket decodes it. A frame that fails to decode is skipped. */
2120
- dispatch(t) {
2121
- var r, a, c;
2122
- let e;
2206
+ dispatch(e) {
2207
+ var r, o, c;
2208
+ let t;
2123
2209
  try {
2124
- e = this.serializer.parse(t);
2210
+ t = this.serializer.parse(e);
2125
2211
  } catch (l) {
2126
2212
  console.warn("[DetachedRunFrames] a frame failed to decode", l);
2127
2213
  return;
2128
2214
  }
2129
- if (!e) return;
2130
- const s = Rt(e);
2215
+ if (!t) return;
2216
+ const s = Re(t);
2131
2217
  if (s) {
2132
2218
  (r = this.onInteractionStarted) == null || r.call(this, s);
2133
2219
  return;
2134
2220
  }
2135
- const n = st(e);
2221
+ const n = se(t);
2136
2222
  if (n) {
2137
- $t(n) && n.interactionId && !this.firstTokens.has(n.interactionId) && (this.firstTokens.add(n.interactionId), (a = this.onFirstToken) == null || a.call(this, n.interactionId));
2223
+ $e(n) && n.interactionId && !this.firstTokens.has(n.interactionId) && (this.firstTokens.add(n.interactionId), (o = this.onFirstToken) == null || o.call(this, n.interactionId));
2138
2224
  try {
2139
- const l = x.parseFromTypedEvent(n);
2225
+ const l = q.parseFromTypedEvent(n);
2140
2226
  (c = this.onEvent) == null || c.call(this, l).catch((f) => console.error("[DetachedRunFrames] onEvent failed", f));
2141
2227
  } catch (l) {
2142
2228
  console.error("[DetachedRunFrames] a frame could not be mapped to a server event", l);
2143
2229
  }
2144
2230
  }
2145
2231
  }
2146
- sendMessage(t) {
2232
+ sendMessage(e) {
2147
2233
  throw new Error("A detached-run transcript is read-only: answer the run through its own endpoint.");
2148
2234
  }
2149
2235
  suspendStream() {
2150
2236
  }
2151
2237
  closeStream() {
2152
- var t;
2153
- (t = this.controller) == null || t.abort(), this.controller = null, this.following = !1;
2238
+ var e;
2239
+ (e = this.controller) == null || e.abort(), this.controller = null, this.following = !1;
2154
2240
  }
2155
2241
  isConnected() {
2156
2242
  return this.controller !== null;
2157
2243
  }
2158
2244
  };
2159
- h(dt, "DetachedRunFramesTransport");
2160
- let At = dt;
2161
- const ve = "todolistUpdated";
2162
- function be(i, t = et()) {
2245
+ h(de, "DetachedRunFramesTransport");
2246
+ let Ae = de;
2247
+ const vt = "todolistUpdated";
2248
+ function bt(i, e = te()) {
2163
2249
  var n, r;
2164
- let e;
2250
+ let t;
2165
2251
  try {
2166
- const a = t.parse(i), c = a ? st(a) : void 0;
2167
- e = c ? x.parseFromTypedEvent(c) : void 0;
2252
+ const o = e.parse(i), c = o ? se(o) : void 0;
2253
+ t = c ? q.parseFromTypedEvent(c) : void 0;
2168
2254
  } catch {
2169
2255
  return [];
2170
2256
  }
2171
- if (!e) return [];
2257
+ if (!t) return [];
2172
2258
  const s = [];
2173
- for (const a of e.parts ?? [])
2174
- if (a.eventType === I.ToolEvent && ((n = a.toolDetails) == null ? void 0 : n.eventName) === ve) {
2175
- const c = Ee(a.toolDetails.eventData);
2259
+ for (const o of t.parts ?? [])
2260
+ if (o.eventType === I.ToolEvent && ((n = o.toolDetails) == null ? void 0 : n.eventName) === vt) {
2261
+ const c = Et(o.toolDetails.eventData);
2176
2262
  c && s.push({ kind: "todo", todoList: c });
2177
- } else (a.eventType === I.FunctionCall || a.eventType === I.PartialFunctionCall) && ((r = a.functionDetails) != null && r.name) ? s.push({ kind: "tool", name: a.functionDetails.name, interactionId: e.interactionId }) : a.eventType === I.Text && a.text && s.push({ kind: "text", text: a.text, partial: !!e.partial, interactionId: e.interactionId });
2263
+ } 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 });
2178
2264
  return s;
2179
2265
  }
2180
- h(be, "readDetachedRunActivity");
2181
- function Ee(i) {
2266
+ h(bt, "readDetachedRunActivity");
2267
+ function Et(i) {
2182
2268
  if (!i) return null;
2183
2269
  try {
2184
- const t = JSON.parse(i);
2185
- return t && Array.isArray(t.items) ? t : null;
2270
+ const e = JSON.parse(i);
2271
+ return e && Array.isArray(e.items) ? e : null;
2186
2272
  } catch {
2187
2273
  return null;
2188
2274
  }
2189
2275
  }
2190
- h(Ee, "parseTodoList");
2276
+ h(Et, "parseTodoList");
2191
2277
  export {
2192
- yt as A,
2278
+ ye as A,
2193
2279
  V as C,
2194
2280
  L as D,
2195
- Tt as E,
2196
- Mt as H,
2281
+ Te as E,
2282
+ Ce as H,
2197
2283
  _ as I,
2198
- It as L,
2199
- Jt as M,
2200
- ve as T,
2201
- ae as W,
2202
- At as a,
2284
+ Ie as L,
2285
+ Qe as M,
2286
+ vt as T,
2287
+ at as W,
2288
+ Ae as a,
2203
2289
  j as b,
2204
- Ct as c,
2205
- we as d,
2206
- ee as e,
2207
- be as r,
2208
- ye as s,
2209
- me as t,
2210
- Re as u
2290
+ Me as c,
2291
+ wt as d,
2292
+ tt as e,
2293
+ bt as r,
2294
+ yt as s,
2295
+ mt as t,
2296
+ Rt as u
2211
2297
  };
2212
- //# sourceMappingURL=detachedRunActivity-DWOR3cAC.js.map
2298
+ //# sourceMappingURL=detachedRunActivity-CCrlilHK.js.map