@aintela/chat 0.4.36 → 0.5.0

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 (68) hide show
  1. package/dist/components.js +7039 -7001
  2. package/dist/components.js.map +1 -1
  3. package/dist/hooks.js +1 -1
  4. package/dist/httpArtifactService-EEhF_mp9.js +1744 -0
  5. package/dist/httpArtifactService-EEhF_mp9.js.map +1 -0
  6. package/dist/{httpSessionService-CUujaUo6.js → httpSessionService-wBby4ggl.js} +51 -53
  7. package/dist/httpSessionService-wBby4ggl.js.map +1 -0
  8. package/dist/index.js +232 -227
  9. package/dist/models.js +1 -1
  10. package/dist/{serializer-DX-yGa_k.js → serializer-CC-nM3ig.js} +497 -498
  11. package/dist/serializer-CC-nM3ig.js.map +1 -0
  12. package/dist/services.js +12 -10
  13. package/dist/src/components/AiChat/ChatPane/CurrentMessage.d.ts +9 -9
  14. package/dist/src/components/AiChat/ChatPane/Message.d.ts +1 -3
  15. package/dist/src/components/AiChat/ChatPane/MessageAgent.d.ts +9 -8
  16. package/dist/src/components/AiChat/ChatPane/MessageScope.d.ts +32 -0
  17. package/dist/src/components/AiChat/ChatPane/MessageUser.d.ts +0 -1
  18. package/dist/src/components/AiChat/ChatPane/StickyQuestionHeader.d.ts +0 -1
  19. package/dist/src/components/AiChat/ChatPane/groupParts.d.ts +32 -0
  20. package/dist/src/components/AiChat/ChatPane/parts/ConnectionOutagePart.d.ts +9 -0
  21. package/dist/src/components/AiChat/ChatPane/parts/types.d.ts +6 -4
  22. package/dist/src/components/AiChat/ChatPane/reasoningHeadlines.d.ts +12 -8
  23. package/dist/src/components/AiChat/sessionStateManagerService.d.ts +36 -35
  24. package/dist/src/components/AiChat/stateConfiguration.d.ts +18 -0
  25. package/dist/src/components/index.d.ts +6 -2
  26. package/dist/src/interfaces/index.d.ts +0 -1
  27. package/dist/src/models/Interaction.d.ts +0 -9
  28. package/dist/src/models/InteractionPart.d.ts +4 -3
  29. package/dist/src/models/Notification.d.ts +7 -1
  30. package/dist/src/models/ServerEvent.d.ts +4 -0
  31. package/dist/src/models/index.d.ts +1 -1
  32. package/dist/src/services/WebSocketConnection/WebSocketConnectionV2.d.ts +28 -108
  33. package/dist/src/services/WebSocketConnection/closeCodes.d.ts +24 -0
  34. package/dist/src/services/WebSocketConnection/streamStats.d.ts +41 -0
  35. package/dist/src/services/WebSocketConnection/streamStats.test.d.ts +1 -0
  36. package/dist/src/services/WebSocketConnection/webSocketConnection.d.ts +15 -12
  37. package/dist/src/services/eventBusService.d.ts +28 -67
  38. package/dist/src/services/index.d.ts +2 -1
  39. package/dist/src/services/interaction/reduceInteraction.d.ts +28 -0
  40. package/dist/src/services/interactionService.d.ts +15 -32
  41. package/dist/src/services/interactionService.invariants.test.d.ts +1 -0
  42. package/dist/src/services/servers/AgentGatewayService.d.ts +3 -182
  43. package/dist/src/services/servers/AgentGatewayWSAsync.d.ts +145 -46
  44. package/dist/src/services/servers/connectionSupervisor.d.ts +173 -0
  45. package/dist/src/services/servers/connectionSupervisor.test.d.ts +1 -0
  46. package/dist/src/services/servers/connectionSupervisor.wire.test.d.ts +0 -0
  47. package/dist/src/services/servers/gatewayErrorClosesTurn.test.d.ts +1 -0
  48. package/dist/src/services/servers/gatewayFixes.test.d.ts +1 -0
  49. package/dist/src/services/servers/throttledEmit.test.d.ts +1 -0
  50. package/dist/src/services/servers/throttledEmitter.d.ts +38 -0
  51. package/dist/src/services/streamPipeline.characterization.test.d.ts +1 -0
  52. package/dist/src/services/wire/decodeFrame.d.ts +21 -0
  53. package/dist/src/services/wire/decodeFrame.test.d.ts +1 -0
  54. package/dist/tests/bench/streamPipeline.bench.d.ts +1 -0
  55. package/dist/tests/fakes/fakeRawWebSocket.d.ts +2 -0
  56. package/dist/tests/fakes/fakeWebSocket.d.ts +4 -3
  57. package/dist/tests/fakes/makeGateway.d.ts +7 -0
  58. package/dist/tests/wire/journey.d.ts +47 -0
  59. package/dist/{useChatSessions-BXYvvd4S.js → useChatSessions-C6sYF4U6.js} +2 -2
  60. package/dist/{useChatSessions-BXYvvd4S.js.map → useChatSessions-C6sYF4U6.js.map} +1 -1
  61. package/package.json +2 -1
  62. package/dist/httpArtifactService-GdGsaFKS.js +0 -1979
  63. package/dist/httpArtifactService-GdGsaFKS.js.map +0 -1
  64. package/dist/httpSessionService-CUujaUo6.js.map +0 -1
  65. package/dist/serializer-DX-yGa_k.js.map +0 -1
  66. package/dist/src/interfaces/IHeartbeatPort.d.ts +0 -4
  67. /package/dist/src/components/AiChat/{sessionStateManagerService.idle.test.d.ts → ChatPane/groupParts.test.d.ts} +0 -0
  68. /package/dist/src/{services/interactionServiceGrouping.test.d.ts → components/AiChat/ChatPane/parts/connectionOutagePart.test.d.ts} +0 -0
@@ -1,1979 +0,0 @@
1
- var at = Object.defineProperty;
2
- var St = (w, t, e) => t in w ? at(w, t, { enumerable: !0, configurable: !0, writable: !0, value: e }) : w[t] = e;
3
- var f = (w, t) => at(w, "name", { value: t, configurable: !0 });
4
- var i = (w, t, e) => St(w, typeof t != "symbol" ? t + "" : t, e);
5
- import { i as wt, a as yt, d as Tt } from "./environmentUtils-VZNTCzEE.js";
6
- import { I as _, E as C, j as Ct, S as gt, q as It, L as vt, P as U, l as Et, o as Mt, T as Dt, m as At, C as F } from "./serializer-DX-yGa_k.js";
7
- import { unified as Ot } from "unified";
8
- import kt from "remark-parse";
9
- import { toMarkdown as Nt } from "mdast-util-to-markdown";
10
- import { format as Pt } from "date-fns";
11
- import _t from "lodash";
12
- import { P as bt, C as k } from "./Prompt-DZb7OaPp.js";
13
- import { r as Rt } from "./httpSessionService-CUujaUo6.js";
14
- const W = {
15
- PROMPTS: "envision-prompts"
16
- }, Lt = 50, J = class J {
17
- getPrompts() {
18
- try {
19
- const t = localStorage.getItem(W.PROMPTS);
20
- return t ? JSON.parse(t).sort((s, o) => new Date(o.created).getTime() - new Date(s.created).getTime()) : [];
21
- } catch (t) {
22
- return console.error("Error loading prompts:", t), [];
23
- }
24
- }
25
- /**
26
- * Record a sent prompt, most recent first, de-duplicated by text.
27
- *
28
- * Asking the same thing again MOVES that entry to the top rather than adding
29
- * a second copy — the history is a list of distinct things you have asked,
30
- * and a repeated question spending two of the twelve visible rows costs a
31
- * suggestion for nothing. The repeat's own `id` and `created` win, because
32
- * what the list orders by is when you last asked.
33
- *
34
- * The dedupe used to look only at `prompts[0]`, and then unshifted anyway:
35
- * a consecutive repeat overwrote the older copy's id and timestamp AND
36
- * appended a new row, so the same text appeared twice with the same id.
37
- *
38
- * Matching is exact on `promptText` (`PromptUtils.createPrompt` has already
39
- * trimmed it). Two prompts differing only in case or inner whitespace stay
40
- * separate entries — that is deliberate, not an oversight: normalising them
41
- * would mean re-surfacing text the user never typed.
42
- */
43
- storePrompt(t) {
44
- try {
45
- const e = this.getPrompts().filter((s) => s.promptText !== t.promptText);
46
- e.unshift(t), localStorage.setItem(W.PROMPTS, JSON.stringify(e.slice(0, Lt)));
47
- } catch (e) {
48
- console.error("Error storing prompt:", e);
49
- }
50
- }
51
- clearAllPrompts() {
52
- try {
53
- localStorage.removeItem(W.PROMPTS);
54
- } catch (t) {
55
- console.error("Error clearing prompts:", t);
56
- }
57
- }
58
- };
59
- f(J, "LocalStorageService");
60
- let rt = J;
61
- const re = /* @__PURE__ */ f((w) => {
62
- const t = w.getPrompts(), e = t.length;
63
- if (e > 0) {
64
- const s = t[0].promptText, o = t[t.length - 1].promptText, n = t[0].created;
65
- return { promptState: e + "_" + s + "_" + o + "_" + n };
66
- } else
67
- return { promptState: "0" };
68
- }, "usePromptState"), Q = class Q {
69
- constructor() {
70
- i(this, "activityLost", "activityLost");
71
- i(this, "artifactGenerated", "artifactGenerated");
72
- i(this, "artifactSelected", "artifactSelected");
73
- i(this, "artifactDeleted", "artifactDeleted");
74
- i(this, "gatewayMessage", "gatewayMessage");
75
- i(this, "gatewayTurnComplete", "gatewayTurnComplete");
76
- i(this, "gatewayStreamError", "gatewayStreamError");
77
- i(this, "gatewayTurnOpen", "gatewayTurnOpen");
78
- i(this, "sessionCreated", "sessionCreated");
79
- i(this, "sessionUpdated", "sessionUpdated");
80
- i(this, "gatewayFunctionResponse", "gatewayFunctionResponse");
81
- i(this, "uiUnsavedPopoverToggle", "uiUnsavedPopoverToggle");
82
- i(this, "uiAskQuestion", "uiAskQuestion");
83
- i(this, "artifactsStorageUpdated", "artifactsStorageUpdated");
84
- i(this, "gatewayStreamEnded", "gatewayStreamEnded");
85
- i(this, "streamNewChunk", "streamNewChunk");
86
- i(this, "gatewayEndMessageData", "gatewayEndMessageData");
87
- i(this, "connectionStateChange", "connectionStateChange");
88
- i(this, "onMessageSent", "onMessageSent");
89
- i(this, "onMessageError", "onMessageError");
90
- i(this, "onToolEvent", "onToolEvent");
91
- i(this, "gatewayFirstToken", "gatewayFirstToken");
92
- }
93
- };
94
- f(Q, "EventTypes");
95
- let H = Q;
96
- const r = new H(), X = class X {
97
- constructor() {
98
- i(this, "listeners", {});
99
- i(this, "listenersCount", {});
100
- }
101
- callListeners(t, ...e) {
102
- const s = this.listeners[t];
103
- if (this.listenersCount[t] = this.listenersCount[t] + 1, s) {
104
- const o = s.map((n) => n(...e));
105
- Promise.all(o).catch((n) => {
106
- console.error(`Lost error in one of the listeners of the event: ${t}, listeners: ${s.length}, error: ${n}`, s);
107
- });
108
- }
109
- }
110
- addListener(t, e) {
111
- this.listeners[t] || (this.listeners[t] = [], this.listenersCount[t] = 0), this.listeners[t].push(e);
112
- }
113
- getEventState(t) {
114
- return this.listenersCount[t];
115
- }
116
- activityOnLost(t) {
117
- const e = r.activityLost;
118
- this.addListener(e, t);
119
- }
120
- activityEmitLost() {
121
- this.callListeners(r.activityLost);
122
- }
123
- /* typed artifact listeners */
124
- artifactOnGenerated(t) {
125
- const e = r.artifactGenerated;
126
- this.addListener(e, t);
127
- }
128
- artifactEmitGenerated(t) {
129
- this.callListeners(r.artifactGenerated, t);
130
- }
131
- artifactOffGenerated(t) {
132
- const e = r.artifactGenerated;
133
- this.listeners[e] && (this.listeners[e] = this.listeners[e].filter((s) => s !== t));
134
- }
135
- artifactOnSelected(t) {
136
- const e = r.artifactSelected;
137
- this.addListener(e, t);
138
- }
139
- artifactEmitSelected(t) {
140
- this.callListeners(r.artifactSelected, t);
141
- }
142
- artifactOffSelected(t) {
143
- const e = r.artifactSelected;
144
- this.listeners[e] && (this.listeners[e] = this.listeners[e].filter((s) => s !== t));
145
- }
146
- artifactOnDeleted(t) {
147
- const e = r.artifactDeleted;
148
- this.addListener(e, t);
149
- }
150
- artifactEmitDeleted(t) {
151
- this.callListeners(r.artifactDeleted, t);
152
- }
153
- artifactOffDeleted(t) {
154
- const e = r.artifactDeleted;
155
- this.listeners[e] && (this.listeners[e] = this.listeners[e].filter((s) => s !== t));
156
- }
157
- gatewayOnMessage(t) {
158
- const e = r.gatewayMessage;
159
- this.addListener(e, t);
160
- }
161
- gatewayOnTurnComplete(t) {
162
- const e = r.gatewayTurnComplete;
163
- this.addListener(e, t);
164
- }
165
- gatewayOnTurnOpen(t) {
166
- const e = r.gatewayTurnOpen;
167
- this.addListener(e, t);
168
- }
169
- gatewayOnStreamError(t) {
170
- const e = r.gatewayStreamError;
171
- this.addListener(e, t);
172
- }
173
- gatewayOnStreamEnded(t) {
174
- const e = r.gatewayStreamEnded;
175
- this.addListener(e, t);
176
- }
177
- gatewayOffStreamEnded(t) {
178
- const e = r.gatewayStreamEnded;
179
- this.listeners[e] && (this.listeners[e] = this.listeners[e].filter((s) => s !== t));
180
- }
181
- gatewayEmitStreamEnded(t, e) {
182
- this.callListeners(r.gatewayStreamEnded, t, e);
183
- }
184
- gatewayEmitMessage(t, e = null) {
185
- this.callListeners(r.gatewayMessage, t, e);
186
- }
187
- gatewayEmitTurnComplete(t, e) {
188
- this.callListeners(r.gatewayTurnComplete, t, e);
189
- }
190
- gatewayEmitStreamError(t) {
191
- this.callListeners(r.gatewayStreamError, t);
192
- }
193
- gatewayEmitTurnOpen(t) {
194
- this.callListeners(r.gatewayTurnOpen, t);
195
- }
196
- gatewayOffMessage(t) {
197
- const e = r.gatewayMessage;
198
- this.listeners[e] && (this.listeners[e] = this.listeners[e].filter((s) => s !== t));
199
- }
200
- gatewayOffTurnComplete(t) {
201
- const e = r.gatewayTurnComplete;
202
- this.listeners[e] && (this.listeners[e] = this.listeners[e].filter((s) => s !== t));
203
- }
204
- gatewayOffTurnOpen(t) {
205
- const e = r.gatewayTurnOpen;
206
- this.listeners[e] && (this.listeners[e] = this.listeners[e].filter((s) => s !== t));
207
- }
208
- gatewayOffStreamError(t) {
209
- const e = r.gatewayStreamError;
210
- this.listeners[e] && (this.listeners[e] = this.listeners[e].filter((s) => s !== t));
211
- }
212
- sessionOnCreated(t) {
213
- const e = r.sessionCreated;
214
- this.addListener(e, t);
215
- }
216
- chatOnMessageSent(t) {
217
- const e = r.onMessageSent;
218
- this.addListener(e, t);
219
- }
220
- chatOffMessageSent(t) {
221
- const e = r.onMessageSent;
222
- this.listeners[e] && (this.listeners[e] = this.listeners[e].filter((s) => s !== t));
223
- }
224
- ChatEmitMessageSent(t, e) {
225
- this.callListeners(r.onMessageSent, t, e);
226
- }
227
- chatOnMessageError(t) {
228
- const e = r.onMessageError;
229
- this.addListener(e, t);
230
- }
231
- chatOffMessageError(t) {
232
- const e = r.onMessageError;
233
- this.listeners[e] && (this.listeners[e] = this.listeners[e].filter((s) => s !== t));
234
- }
235
- ChatEmitMessageError(t) {
236
- this.callListeners(r.onMessageError, t);
237
- }
238
- sessionOnUpdated(t) {
239
- const e = r.sessionUpdated;
240
- this.addListener(e, t);
241
- }
242
- sessionEmitCreated(t) {
243
- this.callListeners(r.sessionCreated, t);
244
- }
245
- sessionEmitUpdated(t) {
246
- this.callListeners(r.sessionUpdated, t);
247
- }
248
- sessionOffCreated(t) {
249
- const e = r.sessionCreated;
250
- this.listeners[e] && (this.listeners[e] = this.listeners[e].filter((s) => s !== t));
251
- }
252
- sessionOffUpdated(t) {
253
- const e = r.sessionUpdated;
254
- this.listeners[e] && (this.listeners[e] = this.listeners[e].filter((s) => s !== t));
255
- }
256
- gatewayEmitFunctionResponse(t) {
257
- this.callListeners(r.gatewayFunctionResponse, t);
258
- }
259
- gatewayOffFunctionResponse(t) {
260
- const e = r.gatewayFunctionResponse;
261
- this.listeners[e] && (this.listeners[e] = this.listeners[e].filter((s) => s !== t));
262
- }
263
- gatewayOnFunctionResponse(t) {
264
- const e = r.gatewayFunctionResponse;
265
- this.addListener(e, t);
266
- }
267
- // UI events
268
- uiOnUnsavedPopoverToggle(t) {
269
- const e = r.uiUnsavedPopoverToggle;
270
- this.addListener(e, t);
271
- }
272
- uiEmitUnsavedPopoverToggle(t) {
273
- this.callListeners(r.uiUnsavedPopoverToggle, t);
274
- }
275
- uiOffUnsavedPopoverToggle(t) {
276
- const e = r.uiUnsavedPopoverToggle;
277
- this.listeners[e] && (this.listeners[e] = this.listeners[e].filter((s) => s !== t));
278
- }
279
- // "Re-ask this" — a `#ask-…` link in the transcript, carrying the link's TEXT as the question.
280
- // An event rather than component state because the prompt that must send it is not always
281
- // ChatPane's own: a host that passes `hidePromptInput` mounts its own `PromptV2` elsewhere in
282
- // its tree, and that instance cannot see ChatPane's `useState`. Whichever prompt is mounted
283
- // listens; ChatPane publishes only when its internal one is suppressed, so the question is
284
- // never sent twice.
285
- uiOnAskQuestion(t) {
286
- const e = r.uiAskQuestion;
287
- this.addListener(e, t);
288
- }
289
- uiEmitAskQuestion(t) {
290
- this.callListeners(r.uiAskQuestion, t);
291
- }
292
- uiOffAskQuestion(t) {
293
- const e = r.uiAskQuestion;
294
- this.listeners[e] && (this.listeners[e] = this.listeners[e].filter((s) => s !== t));
295
- }
296
- // Artifacts storage update events
297
- artifactsOnStorageUpdated(t) {
298
- const e = r.artifactsStorageUpdated;
299
- this.addListener(e, t);
300
- }
301
- artifactsEmitStorageUpdated() {
302
- this.callListeners(r.artifactsStorageUpdated);
303
- }
304
- artifactsOffStorageUpdated(t) {
305
- const e = r.artifactsStorageUpdated;
306
- this.listeners[e] && (this.listeners[e] = this.listeners[e].filter((s) => s !== t));
307
- }
308
- streamOnNewChunk(t) {
309
- const e = r.streamNewChunk;
310
- this.addListener(e, t);
311
- }
312
- streamEmitNewChunk(t) {
313
- this.callListeners(r.streamNewChunk, t);
314
- }
315
- streamOffNewChunk(t) {
316
- const e = r.streamNewChunk;
317
- this.listeners[e] && (this.listeners[e] = this.listeners[e].filter((s) => s !== t));
318
- }
319
- gatewayOnEndMessageData(t) {
320
- const e = r.gatewayEndMessageData;
321
- this.addListener(e, t);
322
- }
323
- gatewayEmitEndMessageData(t) {
324
- this.callListeners(r.gatewayEndMessageData, t);
325
- }
326
- gatewayOffEndMessageData(t) {
327
- const e = r.gatewayEndMessageData;
328
- this.listeners[e] && (this.listeners[e] = this.listeners[e].filter((s) => s !== t));
329
- }
330
- gatewayOnConnectionStateChange(t) {
331
- const e = r.connectionStateChange;
332
- this.addListener(e, t);
333
- }
334
- gatewayEmitConnectionStateChange(t) {
335
- this.callListeners(r.connectionStateChange, t);
336
- }
337
- gatewayOffConnectionStateChange(t) {
338
- const e = r.connectionStateChange;
339
- this.listeners[e] && (this.listeners[e] = this.listeners[e].filter((s) => s !== t));
340
- }
341
- gatewayOnToolEvent(t) {
342
- const e = r.onToolEvent;
343
- this.addListener(e, t);
344
- }
345
- gatewayEmitToolEvent(t, e, s) {
346
- this.callListeners(r.onToolEvent, t, e, s);
347
- }
348
- gatewayOffToolEvent(t) {
349
- const e = r.onToolEvent;
350
- this.listeners[e] && (this.listeners[e] = this.listeners[e].filter((s) => s !== t));
351
- }
352
- gatewayOnFirstToken(t) {
353
- const e = r.gatewayFirstToken;
354
- this.addListener(e, t);
355
- }
356
- gatewayEmitFirstToken(t) {
357
- this.callListeners(r.gatewayFirstToken, t);
358
- }
359
- gatewayOffFirstToken(t) {
360
- const e = r.gatewayFirstToken;
361
- this.listeners[e] && (this.listeners[e] = this.listeners[e].filter((s) => s !== t));
362
- }
363
- };
364
- f(X, "EventBusService");
365
- let K = X;
366
- const Y = class Y extends K {
367
- constructor() {
368
- super();
369
- }
370
- gatewayEmitConnectionStateChange(t) {
371
- console.log("MockEventBusService.gatewayEmitConnectionStateChange");
372
- }
373
- gatewayEmitMessage(t, e) {
374
- wt() ? process.stdout.write(`M${t.version}, `) : console.log("MockEventBusService.gatewayEmitMessage");
375
- }
376
- gatewayEmitTurnComplete(t, e) {
377
- console.log("MockEventBusService.gatewayEmitTurnComplete");
378
- }
379
- gatewayEmitTurnOpen(t) {
380
- console.log("MockEventBusService.gatewayEmitTurnOpen");
381
- }
382
- gatewayEmitFunctionResponse(t) {
383
- console.log("MockEventBusService.gatewayEmitFunctionResponse");
384
- }
385
- gatewayOnFunctionResponse(t) {
386
- console.log("MockEventBusService.gatewayOnFunctionResponse", t);
387
- }
388
- gatewayOffFunctionResponse(t) {
389
- console.log("MockEventBusService.gatewayOffFunctionResponse", t);
390
- }
391
- };
392
- f(Y, "MockEventBusService");
393
- let ct = Y;
394
- const Ut = 2e3, mt = {
395
- inline: "inline",
396
- block: "block"
397
- }, j = class j {
398
- constructor() {
399
- i(this, "parts", []);
400
- i(this, "isLastGroup", !1);
401
- i(this, "hasThoughts", !1);
402
- i(this, "lastWithThoughts", !1);
403
- /**
404
- * A run of CONSECUTIVE thought parts — one continuous piece of reasoning
405
- * that `merge` split at {@link MAX_CHAR_PER_TEXT_PART} to keep a very long
406
- * prose from dragging the browser down.
407
- *
408
- * The split is a rendering optimisation and must not be legible as one: the
409
- * reader gets a single "Pensando…" block whatever the chunk count, drawn by
410
- * the run's chrome, while each chunk stays its own memoized MessagePart —
411
- * which is where the CPU saving actually comes from.
412
- */
413
- i(this, "isThoughtRun", !1);
414
- i(this, "type", mt.inline);
415
- }
416
- };
417
- f(j, "InteractionPartGroup");
418
- let $ = j;
419
- const Z = class Z {
420
- constructor(t, e) {
421
- i(this, "interaction");
422
- i(this, "eventBusService");
423
- i(this, "parseTextIntoParts", /* @__PURE__ */ f((t) => {
424
- if (!t || t.trim().length == 0) return [];
425
- const e = Ot().use(kt).parse(t), s = [];
426
- let o = null;
427
- for (const n of e.children)
428
- n.type === "code" ? (o && (s.push(o), o = null), n.lang === "htmlCanvas" && s.push(`
429
- \`\`\`liveTsx
430
- ${n.value}
431
- \`\`\`
432
- `)) : (o || (o = ""), o += Nt(n));
433
- return o && s.push(o), s;
434
- }, "parseTextIntoParts"));
435
- this.interaction = t, this.eventBusService = e;
436
- }
437
- expandSubParts(t, e) {
438
- const s = this.parseTextIntoParts(t), o = [];
439
- let n = 0;
440
- for (const a of s) {
441
- const l = _.fromText(a);
442
- l.id = n + "_" + e, o.push(l), n++;
443
- }
444
- return o;
445
- }
446
- groupPartsByDisplayType(t, e = !0, s = !1) {
447
- var l, c, d;
448
- const o = [];
449
- let n = new $();
450
- for (let u = 0; u < t.length; u++) {
451
- const h = t[u];
452
- let m = !((((l = h.functionDetails) == null ? void 0 : l.isUi) ?? !1) || ((c = h.functionDetails) == null ? void 0 : c.cancelUi) !== !0 && (((d = h.functionDetails) == null ? void 0 : d.isAskUser) ?? !1)) && h.eventType !== C.Text && h.eventType !== C.Thought && (h.eventType === C.FunctionCall || h.eventType === C.PartialFunctionCall || h.eventType === C.FunctionResponse) && u < t.length - 1;
453
- if (!(!e && m && !s))
454
- if (m)
455
- h.eventType == C.Thought && (n.hasThoughts = !0), n.parts.push(h), n.isLastGroup = u === t.length - 1;
456
- else {
457
- n.parts.length > 0 && (o.push(n), n = new $());
458
- const M = h.eventType === C.Thought, T = o[o.length - 1];
459
- if (M && (T != null && T.isThoughtRun)) {
460
- T.parts.push(h), T.isLastGroup = u === t.length - 1;
461
- continue;
462
- }
463
- o.push({
464
- type: mt.block,
465
- parts: [h],
466
- isLastGroup: u === t.length - 1,
467
- hasThoughts: !1,
468
- lastWithThoughts: !1,
469
- isThoughtRun: M
470
- });
471
- }
472
- }
473
- n.parts.length > 0 && o.push(n);
474
- const a = o.filter((u) => u.hasThoughts);
475
- return a.length > 0 && (a[a.length - 1].lastWithThoughts = !0), o;
476
- }
477
- isFunctionCall(t) {
478
- return t == C.FunctionCall || t == C.PartialFunctionCall;
479
- }
480
- isFunctionResponse(t) {
481
- return t == C.FunctionResponse;
482
- }
483
- // Computes the next interaction from a server event. Pure with respect to
484
- // `prev` — no part or array on the prior tree is mutated; modified entities
485
- // are cloned. The service field `this.interaction` is replaced with the
486
- // new tree as the last step, so snapshots already handed out to throttled
487
- // subscribers can't diverge from the live state.
488
- merge(t) {
489
- var b, R, y, A, O, st, nt, it;
490
- const e = this.interaction, s = [], o = [], n = _.FlatParts(t == null ? void 0 : t.parts), a = e.parts[e.parts.length - 1] ?? null;
491
- let l = !1;
492
- n && (l = !a || n.mustPush || n.mustPush === !1 && (n.eventType !== (a == null ? void 0 : a.eventType) || ((b = n == null ? void 0 : n.functionDetails) == null ? void 0 : b.id) !== ((R = a.functionDetails) == null ? void 0 : R.id)));
493
- let c = e.parts, d = e.functionMap ?? /* @__PURE__ */ new Map(), u = !e.functionMap;
494
- const h = /* @__PURE__ */ f(() => {
495
- u || (d = new Map(d), u = !0);
496
- }, "cloneFunctionMap"), v = /* @__PURE__ */ f(() => {
497
- c === e.parts && (c = e.parts.slice());
498
- }, "clonePartsIfShared");
499
- if (!l && (c == null ? void 0 : c.length) > 0 && (n != null && n.textAppendable)) {
500
- const g = c[c.length - 1];
501
- (((A = (y = g.thoughtDetails) == null ? void 0 : y.text) == null ? void 0 : A.length) ?? ((O = g.text) == null ? void 0 : O.length) ?? 0) > Ut && (l = !0);
502
- }
503
- let m = !1;
504
- if ((n == null ? void 0 : n.eventType) === C.FunctionClientOutput && !!((st = n.functionDetails) != null && st.id) && n) {
505
- const g = n.functionDetails.id, I = n.functionDetails.clientOutput, D = c.findIndex((S) => {
506
- var p;
507
- return ((p = S.functionDetails) == null ? void 0 : p.id) === g;
508
- });
509
- if (D > -1) {
510
- const S = c[D], p = {
511
- ...S,
512
- functionDetails: {
513
- ...S.functionDetails,
514
- clientOutput: I ?? S.functionDetails.clientOutput,
515
- // Sticky true-wins: this event IS the park, and a later merge must not clear it.
516
- parked: n.functionDetails.parked === !0 || S.functionDetails.parked === !0
517
- }
518
- };
519
- v(), c[D] = p, h(), d.set(g, p), s.push(p);
520
- } else {
521
- const S = {
522
- ...n,
523
- id: c.length + 1 + "-" + e.interactionId,
524
- functionDetails: { ...n.functionDetails, silent: !0 }
525
- };
526
- v(), c = c === e.parts ? e.parts.slice() : c, c.push(S), h(), d.set(g, S);
527
- }
528
- } else if (l && n) {
529
- const g = this.isFunctionCall(n.eventType) || this.isFunctionResponse(n.eventType), I = g ? (nt = n.functionDetails) == null ? void 0 : nt.id : void 0;
530
- g && !I && console.error("Got isCall or isResponse without a callId", n);
531
- const D = I ? d.get(I) : void 0;
532
- if (D && I && n.functionDetails) {
533
- const S = c.findIndex((pt) => {
534
- var ot;
535
- return ((ot = pt.functionDetails) == null ? void 0 : ot.id) === I;
536
- }), p = S > -1 ? c[S] : D, L = {
537
- ...p,
538
- eventType: n.eventType,
539
- functionDetails: {
540
- id: p.functionDetails.id,
541
- name: n.functionDetails.name ?? p.functionDetails.name,
542
- // Take the parsed args from the incoming event when
543
- // present (the full FunctionCall carries them), fall
544
- // back to what was already on the part. Previously
545
- // this was `current.functionDetails!.args`
546
- // unconditionally, which silently dropped the parsed
547
- // args off every full FunctionCall fold because the
548
- // PartialFunctionCall stream only accumulates raw
549
- // JSON in `.text` — `.args` stayed undefined.
550
- args: n.functionDetails.args ?? p.functionDetails.args,
551
- response: n.functionDetails.response,
552
- status: n.functionDetails.status ?? "Composing",
553
- start: n.functionDetails.start ?? p.functionDetails.start,
554
- end: n.functionDetails.end ?? p.functionDetails.end,
555
- // true-wins: a UI call has multiple reps (streaming part with isUi, the
556
- // persisted FunctionCall, the result) and they interleave. `??` let a later
557
- // `false`/`undefined` rep clobber an earlier `true`; OR-ing keeps it sticky.
558
- isUi: n.functionDetails.isUi === !0 || p.functionDetails.isUi === !0,
559
- // Keep the call's friendly args summary when the result event (which has none) folds in.
560
- argsDescription: n.functionDetails.argsDescription ?? p.functionDetails.argsDescription,
561
- // The tool's client-only payload rides the RESULT event; keep it sticky so a
562
- // later rep without one can't clobber it. This is what a uiTool renderer reads.
563
- clientOutput: n.functionDetails.clientOutput ?? p.functionDetails.clientOutput,
564
- // Ask-user component ([KernelUIComponent]) — sticky like isUi/clientOutput. The
565
- // streaming final CALL carries it, but the PartialFunctionCall it folds onto (and a
566
- // later result rep) may not; dropping it strips the part's askUser classification so
567
- // the docked drawer never surfaces (issue #60 — esp. a no-arg tool like update_profile,
568
- // which has no name match to fall back on the way ask_user/askauth do).
569
- askUserComponent: n.functionDetails.askUserComponent ?? p.functionDetails.askUserComponent,
570
- isAskUser: n.functionDetails.isAskUser || p.functionDetails.isAskUser || !!(n.functionDetails.askUserComponent ?? p.functionDetails.askUserComponent),
571
- // Runtime "don't render" override rides the RESULT; true-wins sticky like isUi so it
572
- // survives folding onto the earlier call rep and suppresses drawer/uiTool classification.
573
- cancelUi: n.functionDetails.cancelUi === !0 || p.functionDetails.cancelUi === !0,
574
- parked: n.functionDetails.parked === !0 || p.functionDetails.parked === !0
575
- }
576
- };
577
- h(), d.set(I, L), L.eventType === C.FunctionResponse && this.eventBusService.gatewayEmitFunctionResponse(L.functionDetails), s.push(L), S > -1 && (v(), c[S] = L);
578
- } else {
579
- if (I && n.functionDetails && !D && (h(), d.set(I, n)), a && a.textAppendable) {
580
- const p = {
581
- ...a,
582
- ended: /* @__PURE__ */ new Date(),
583
- isStillWriting: !1
584
- };
585
- v(), c[c.length - 1] = p, s.push(p);
586
- }
587
- const S = {
588
- ...n,
589
- id: c.length + 1 + "-" + e.interactionId,
590
- isStillWriting: n.textAppendable,
591
- partial: t.partial
592
- };
593
- (it = S.functionDetails) != null && it.silent || s.push(S), c = [...c, S], m = !0;
594
- }
595
- }
596
- let T = c[c.length - 1] ?? null;
597
- if (T && n && n.textAppendable) {
598
- const g = {
599
- ...T,
600
- partial: t.partial,
601
- textDetails: T.textDetails ? { ...T.textDetails } : { version: 0 }
602
- };
603
- let I = !1;
604
- if (t.partial) {
605
- try {
606
- g.textDetails.version++, m || (g.text = (T.text ?? "") + (n.text ?? ""));
607
- } catch (D) {
608
- console.error("Error here", D.toString());
609
- }
610
- g.textLastChunk = n.text ?? "", g.isStillWriting = !0, I = !0, !m && n.thoughtDetails && g.thoughtDetails && (n.thoughtDetails.text.length >= 50 || n.thoughtDetails.text.length < 50 && n.thoughtDetails.text !== g.thoughtDetails.text) && (g.thoughtDetails = {
611
- ...g.thoughtDetails,
612
- text: g.thoughtDetails.text + n.thoughtDetails.text
613
- }, g.thoughtLastChunk = n.thoughtDetails.text);
614
- } else
615
- g.isStillWriting = !1, g.text = n.text ?? "", g.textDetails.version++, n.thoughtDetails && (g.thoughtDetails = {
616
- ...n.thoughtDetails,
617
- text: n.thoughtDetails.text.trim()
618
- }), I = !l;
619
- v(), c[c.length - 1] = g, T = g, I && s.push(g);
620
- }
621
- let E = e.artifactData ?? [];
622
- if (t.llmArtifacts && t.llmArtifacts.length > 0) {
623
- let g = !1;
624
- for (const I of t.llmArtifacts) {
625
- const D = I.toArtifact();
626
- g || (E = E.slice(), g = !0);
627
- const S = E.findIndex((p) => p.id === D.id);
628
- S === -1 ? E.push(D) : E[S] = D;
629
- }
630
- }
631
- const N = {
632
- ...e,
633
- version: e.version + 1,
634
- parts: c,
635
- artifactData: E,
636
- functionMap: d,
637
- turn_complete: t.turn_complete,
638
- partial: t.partial,
639
- asyncFinalResponse: t.asyncFinalResponse
640
- };
641
- return this.interaction = N, {
642
- updatedInteraction: N,
643
- updatedParts: s,
644
- newArtifacts: o,
645
- mainBranch: N,
646
- analyticsBranch: null,
647
- analyticsBranchPartsChanged: null,
648
- mainBranchPartsChanged: s
649
- };
650
- }
651
- };
652
- f(Z, "InteractionService");
653
- let x = Z;
654
- const Ft = 1200 * 1e3, P = class P {
655
- constructor(t, e, s, o, n, a, l, c, d, u = Ct.Interactive) {
656
- i(this, "base_production_url", yt() ?? "https://agent.tripapi.com.br");
657
- i(this, "base_url_local", "http://localagent:8000");
658
- i(this, "base_url");
659
- i(this, "isLocal", !1);
660
- i(this, "msg_order", 0);
661
- i(this, "lastPing", /* @__PURE__ */ new Date());
662
- i(this, "interactionsMap", /* @__PURE__ */ new Map());
663
- i(this, "interactionsServiceMap", /* @__PURE__ */ new Map());
664
- i(this, "user");
665
- i(this, "config");
666
- i(this, "currentIS", null);
667
- i(this, "server_session_id");
668
- i(this, "model_session_id");
669
- i(this, "runMode");
670
- i(this, "sessionState");
671
- i(this, "storageService");
672
- i(this, "notificationPort");
673
- i(this, "interactionCallIds", /* @__PURE__ */ new Map());
674
- i(this, "rawJwt");
675
- i(this, "sessionId");
676
- i(this, "isInited", !1);
677
- //Define all SSEServer methods here, use from SSEServer.ts
678
- i(this, "eventBusService");
679
- i(this, "artifactService");
680
- i(this, "onTurnOpen", /* @__PURE__ */ f((t) => {
681
- this.eventBusService.gatewayOnTurnOpen(t);
682
- }, "onTurnOpen"));
683
- i(this, "offTurnOpen", /* @__PURE__ */ f((t) => {
684
- this.eventBusService.gatewayOffTurnOpen(t);
685
- }, "offTurnOpen"));
686
- i(this, "onTurnComplete", /* @__PURE__ */ f((t) => {
687
- this.eventBusService.gatewayOnTurnComplete(t);
688
- }, "onTurnComplete"));
689
- i(this, "offTurnComplete", /* @__PURE__ */ f((t) => {
690
- this.eventBusService.gatewayOffTurnComplete(t);
691
- }, "offTurnComplete"));
692
- i(this, "onStreamError", /* @__PURE__ */ f((t) => {
693
- this.eventBusService.gatewayOnStreamError(t);
694
- }, "onStreamError"));
695
- i(this, "offStreamError", /* @__PURE__ */ f((t) => {
696
- this.eventBusService.gatewayOffStreamError(t);
697
- }, "offStreamError"));
698
- i(this, "onStreamEnded", /* @__PURE__ */ f((t) => {
699
- this.eventBusService.gatewayOnStreamEnded(t);
700
- }, "onStreamEnded"));
701
- i(this, "offStreamEnded", /* @__PURE__ */ f((t) => {
702
- this.eventBusService.gatewayOffStreamEnded(t);
703
- }, "offStreamEnded"));
704
- i(this, "onMessage", /* @__PURE__ */ f((t) => {
705
- this.eventBusService.gatewayOnMessage(t);
706
- }, "onMessage"));
707
- i(this, "offMessage", /* @__PURE__ */ f((t) => {
708
- this.eventBusService.gatewayOffMessage(t);
709
- }, "offMessage"));
710
- i(this, "onFirstToken", /* @__PURE__ */ f((t) => {
711
- this.eventBusService.gatewayOnFirstToken(t);
712
- }, "onFirstToken"));
713
- i(this, "offFirstToken", /* @__PURE__ */ f((t) => {
714
- this.eventBusService.gatewayOffFirstToken(t);
715
- }, "offFirstToken"));
716
- i(this, "onFunctionResponse", /* @__PURE__ */ f((t) => {
717
- this.eventBusService.gatewayOnFunctionResponse(t);
718
- }, "onFunctionResponse"));
719
- i(this, "offFunctionResponse", /* @__PURE__ */ f((t) => {
720
- this.eventBusService.gatewayOffFunctionResponse(t);
721
- }, "offFunctionResponse"));
722
- i(this, "toolSessionId", null);
723
- i(this, "pendingCurrentMessage", null);
724
- i(this, "lastCurrentMessageUpdate", 0);
725
- i(this, "runningRequests", /* @__PURE__ */ new Map());
726
- i(this, "lastToolInteraction", "");
727
- i(this, "subAgentInteractions", /* @__PURE__ */ new Map());
728
- i(this, "subAgentInteractionServices", /* @__PURE__ */ new Map());
729
- i(this, "lastThorttledTimeout", null);
730
- i(this, "lastPingStatus", !1);
731
- this.user = t, this.config = n, this.rawJwt = t.access_token, this.base_url = o, this.eventBusService = e, this.sessionId = d, this.runMode = u, this.artifactService = s, this.sessionState = a.getState(), this.notificationPort = l, this.storageService = c, a.subscribe((h, v) => {
732
- this.sessionState = h;
733
- });
734
- }
735
- onEndMessageData(t) {
736
- this.eventBusService.gatewayOnEndMessageData(t);
737
- }
738
- offEndMessageData(t) {
739
- this.eventBusService.gatewayOffEndMessageData(t);
740
- }
741
- /**
742
- * Send the user's answer to a parked `ask_user` tool call back to the agent.
743
- * Default no-op; the WebSocket gateway (AgentGatewayWSAsync) overrides it to emit
744
- * a ChatAction.AnswerHumanTool frame. Returns 'sent' when it went out immediately,
745
- * 'queued' when the socket was down and the answer will flush on reconnect.
746
- */
747
- answerHumanTool(t, e) {
748
- return console.warn("answerHumanTool: not supported by this gateway", t, e), "queued";
749
- }
750
- /**
751
- * The agent this gateway speaks to — the ONE truth for the conversation.
752
- * `sendMessageInternal` stamps every outbound frame's `AgentId` from it,
753
- * and the session manager binds/rebinds against it. Fixed at construction;
754
- * see {@link forceAgentContext} for the single exception (issue #59).
755
- */
756
- getAgentContext() {
757
- return this.config;
758
- }
759
- getModel() {
760
- return this.config.model;
761
- }
762
- setModel(t) {
763
- this.config = { ...this.config, model: t };
764
- }
765
- /**
766
- * Live update for the ordinary, non-identity slice of the context — the
767
- * dataset/customer the same agent works over. No "force" needed: swapping
768
- * datasets mid-conversation is routine and changes nothing about who is
769
- * answering.
770
- */
771
- setCustomer(t) {
772
- this.config = { ...this.config, customer: t };
773
- }
774
- /**
775
- * Replace the AGENT mid-conversation. The escape hatch for an agent picker,
776
- * and nothing else: the session already holds another agent's history, and
777
- * the server stamps `Session.AgentId` on the first turn only — so the
778
- * conversation keeps reporting the agent it STARTED as, however many times
779
- * this is called. Prefer a new engine (new key, see `engineKeyFor`) per
780
- * agent.
781
- *
782
- * Callers pass the FULL replacement context (the same shape the gateway was
783
- * constructed with). The `model` slice is preserved when the incoming
784
- * context omits it — the model is owned separately by {@link setModel} and
785
- * must not be clobbered by an agent-only change.
786
- */
787
- forceAgentContext(t) {
788
- this.config = {
789
- ...t,
790
- model: t.model ?? this.config.model
791
- };
792
- }
793
- getSessionId() {
794
- return this.sessionId;
795
- }
796
- getErrorEvent(t) {
797
- return {
798
- interaction_id: this.getCurrentInteractionId(),
799
- model_session_id: "",
800
- mime_type: "text/plain",
801
- partial: !1,
802
- serverError: t
803
- };
804
- }
805
- setSession(t, e) {
806
- (this.sessionId === void 0 || this.sessionId != t) && (this.sessionId = t, this.msg_order = this.sessionState.messages.length), e && (this.toolSessionId = e);
807
- }
808
- startInteraction(t, e, s) {
809
- if (e && this.currentIS)
810
- return this.currentIS.interaction.isSuspended = !1, this.currentIS.interaction.interactionQuestion += " + " + t, this.currentIS.interaction;
811
- this.msg_order += 1;
812
- let o = this.getNewInteractionId();
813
- s && (o = s);
814
- let n = {
815
- created: /* @__PURE__ */ new Date(),
816
- interactionId: o,
817
- artifactData: [],
818
- partial: !0,
819
- sessionId: this.sessionId,
820
- turn_complete: !1,
821
- parts: [],
822
- version: 0,
823
- functionMap: /* @__PURE__ */ new Map(),
824
- interactionQuestion: t
825
- };
826
- return this.interactionsMap.set(n.interactionId, n), this.currentIS = new x(n, this.eventBusService), this.interactionsServiceMap.set(n.interactionId, this.currentIS), n;
827
- }
828
- getInteractions() {
829
- return Array.from(this.interactionsMap.values());
830
- }
831
- getRecentInteractions(t = 1e3 * 60) {
832
- return Array.from(this.interactionsMap.values()).filter((e) => e.created.getTime() > Date.now() - t);
833
- }
834
- updateMap(t) {
835
- let e = this.interactionsServiceMap.get(t.interactionId);
836
- if (!e) {
837
- var s = this.startInteraction("Unknown", !1, t.interactionId);
838
- e = this.interactionsServiceMap.get(s.interactionId);
839
- }
840
- return e.merge(t);
841
- }
842
- getCurrentInteractionId() {
843
- return this.currentIS ? this.currentIS.interaction.interactionId : null;
844
- }
845
- getCurrentInteraction() {
846
- var t;
847
- return ((t = this.currentIS) == null ? void 0 : t.interaction) ?? null;
848
- }
849
- getInteraction(t) {
850
- return this.interactionsMap.get(t);
851
- }
852
- hasState() {
853
- return this.interactionsMap.size > 0;
854
- }
855
- buildAgentParams() {
856
- let t = `agent=${encodeURIComponent(this.config.agentConfig.name ?? "unset")}`;
857
- return this.config.customer && (t += `&customer_id=${encodeURIComponent(this.config.customer.dataSetId)}`, t += `&customer_name=${encodeURIComponent(this.config.customer.name)}`), t;
858
- }
859
- /**
860
- * Open the live connection. `options.resume` asks the transport to keep its replay cursor,
861
- * so the server sends back whatever was emitted while we were disconnected — see
862
- * WebSocketConnectionV2.connect.
863
- */
864
- openConnection(t, e) {
865
- throw "Not implemented";
866
- }
867
- async Error(t = void 0) {
868
- console.error("Stream error: ", t), await this.eventBusService.gatewayEmitStreamError(t ?? "");
869
- }
870
- hasServerSessionId() {
871
- return this.server_session_id != null && this.server_session_id != null;
872
- }
873
- async asyncLoadArtifact(t) {
874
- let e = null;
875
- const s = this.runningRequests.get(t);
876
- s ? (console.warn("GOT A running promise", t), e = s) : (e = this.artifactService.getArtifact(t), this.runningRequests.set(t, e));
877
- try {
878
- return await e;
879
- } catch (o) {
880
- return console.error("Error awating on HTML promise", o.toString()), null;
881
- } finally {
882
- this.runningRequests.delete(t);
883
- }
884
- }
885
- processComands(t) {
886
- switch (t.command) {
887
- case "open_turn":
888
- console.warn("[Stack:] author:", t.author), this.localOpen(t.interactionId, t.author);
889
- break;
890
- case "ignore":
891
- return !0;
892
- }
893
- return !1;
894
- }
895
- getOrCreateSubAgentInteraction(t, e, s) {
896
- let o = this.subAgentInteractions.get(t), n = this.subAgentInteractionServices.get(t);
897
- return (!o || !n) && (o = {
898
- created: /* @__PURE__ */ new Date(),
899
- interactionId: e,
900
- artifactData: [],
901
- partial: !0,
902
- turn_complete: !1,
903
- parts: [],
904
- version: 0,
905
- functionMap: /* @__PURE__ */ new Map(),
906
- interactionQuestion: s ?? t
907
- }, n = new x(o, this.eventBusService), this.subAgentInteractions.set(t, o), this.subAgentInteractionServices.set(t, n)), { interaction: o, service: n };
908
- }
909
- handleSubAgentEvent(t) {
910
- const e = t.subAgentId, { service: s } = this.getOrCreateSubAgentInteraction(e, t.interactionId, t.subAgentName);
911
- if (t.parts && t.parts.length > 0) {
912
- for (const a of t.parts)
913
- if (a.toolDetails) {
914
- this.localEmitToolEvent({ ...a.toolDetails, subAgentId: e });
915
- continue;
916
- }
917
- }
918
- const o = s.merge(t);
919
- if (!o) return;
920
- const n = t.turn_complete ?? !1;
921
- this.sessionState.setSubAgentMessage(e, o.updatedInteraction, t.subAgentName), n && this.sessionState.completeSubAgent(e);
922
- }
923
- async Message(t) {
924
- try {
925
- let e;
926
- if (typeof t == "object" && Object.keys(t).includes("mimeType"))
927
- e = t;
928
- else {
929
- console.error("Uknown message type", t);
930
- return;
931
- }
932
- if (e.subAgentId) {
933
- this.handleSubAgentEvent(e);
934
- return;
935
- }
936
- if (e.serverError && console.error("Stream error: ", e.serverError), e.endMessageData && this.eventBusService.gatewayEmitEndMessageData(e.endMessageData), e) {
937
- if (e.llmArtifacts && e.llmArtifacts.length > 0)
938
- for (const n of e.llmArtifacts) {
939
- const a = n.toArtifact();
940
- this.artifactService.addToCache(a), this.eventBusService.artifactEmitGenerated(a);
941
- }
942
- if (e.parts && e.parts.length > 0) {
943
- for (const n of e.parts)
944
- if (n.toolDetails) {
945
- this.localEmitToolEvent(n.toolDetails);
946
- continue;
947
- }
948
- }
949
- const s = this.updateMap(e);
950
- if (!s) {
951
- console.warn({
952
- message: "No updated interaction",
953
- type: "warning"
954
- }), console.error("No updated interaction");
955
- return;
956
- }
957
- this.localEmitMessage(s.updatedInteraction, s), e.turn_complete && this.turnComplete(e.interactionId, s.updatedInteraction, e.author, e.subAgentId), e.asyncFinalResponse && (e.turn_complete = !0, s.updatedInteraction.turn_complete == !0, this.finalResponse(e.interactionId, s.updatedInteraction, e.author, e.subAgentId));
958
- const o = e.artifactsDelta;
959
- o && o.forEach((n) => {
960
- const a = s.updatedInteraction.artifactData.filter((c) => c.id == n);
961
- let l = null;
962
- a && a.length > 0 && (l = a[0], l.loadingPromise = this.asyncLoadArtifact(n).then((c) => (c === null ? console.error("Error trying to load artifact id:", l == null ? void 0 : l.id, "Artifact is null") : this.eventBusService.artifactEmitGenerated(c), c)).catch((c) => (console.error("Error trying to load artifact id:", l == null ? void 0 : l.id, c.toString()), null)));
963
- });
964
- }
965
- } catch (e) {
966
- if (this.getCurrentInteractionId()) {
967
- const s = gt.createErrorEvent("OnMessage error: " + e.toString(), this.getCurrentInteractionId() ?? "Empty Current"), o = this.updateMap(s);
968
- if (console.error("Error event: ", JSON.stringify(s, void 0, 4)), !o) {
969
- console.error("Error event, could not update interaction: ", JSON.stringify(s, void 0, 4));
970
- return;
971
- }
972
- this.localEmitMessage(o.updatedInteraction);
973
- }
974
- }
975
- }
976
- hasOneCompleteInteraction() {
977
- var t;
978
- return this.interactionsMap.size > 0 && ((t = this.interactionsMap.values().next().value) == null ? void 0 : t.turn_complete) === !0;
979
- }
980
- localEmitToolEvent(t) {
981
- this.sessionState.setLastToolEvent(t), this.eventBusService.gatewayEmitToolEvent(t.eventName, t.eventData, t.sessionId);
982
- }
983
- registerInteractionCallId(t, e) {
984
- e != null && e.callId && this.interactionCallIds.set(t, e.callId);
985
- }
986
- localEmitFirstToken(t) {
987
- this.eventBusService.gatewayEmitFirstToken({
988
- interactionId: t,
989
- callId: this.interactionCallIds.get(t)
990
- });
991
- }
992
- doEmitMessage(t, e, s) {
993
- this.sessionState.setCurrentMessage(t), this.lastCurrentMessageUpdate = e, this.pendingCurrentMessage = null, this.eventBusService.gatewayEmitMessage(t, s);
994
- }
995
- localEmitMessage(t, e) {
996
- const s = (/* @__PURE__ */ new Date()).getTime(), o = s - this.lastCurrentMessageUpdate;
997
- t.partial === !1 || o >= P.CURRENT_MSG_THROTTLE_MS ? (this.lastThorttledTimeout && (clearTimeout(this.lastThorttledTimeout), this.lastThorttledTimeout = null), this.doEmitMessage(t, s, e), this.pendingCurrentMessage = null) : (this.pendingCurrentMessage = t, this.lastThorttledTimeout && clearTimeout(this.lastThorttledTimeout), this.lastThorttledTimeout = setTimeout(() => {
998
- var a, l;
999
- this.pendingCurrentMessage && (((a = this.pendingCurrentMessage) == null ? void 0 : a.version) ?? 0) > (((l = this.sessionState.currentMessage) == null ? void 0 : l.version) ?? 0) && (this.doEmitMessage(this.pendingCurrentMessage, s, e), this.lastThorttledTimeout = null);
1000
- }, P.CURRENT_MSG_THROTTLE_MS * 2));
1001
- }
1002
- localOpen(t, e) {
1003
- this.sessionState.setTurnOpen(!0), this.eventBusService.gatewayEmitTurnOpen(t ?? "");
1004
- }
1005
- /**
1006
- * Drop any throttled `currentMessage` emit still queued by
1007
- * `localEmitMessage`. The throttle's trailing edge is a `setTimeout` that
1008
- * calls `setCurrentMessage(...)`; if it fires *after* the turn has been
1009
- * committed (`setNewMessage` moved the interaction into `messages` and
1010
- * nulled `currentMessage`), it re-publishes the now-committed interaction
1011
- * as the live message — so the chat renders the turn twice: once in
1012
- * history (`MessageAgent` with `onGoing=false`, which drops Thought parts)
1013
- * and once as the live `currentMessage` (`onGoing=true`, which keeps them).
1014
- * That is the duplicated-bubble bug (the two copies even look different —
1015
- * only the live one shows the "thought" strip). Call this on turn commit.
1016
- */
1017
- cancelPendingCurrentMessage() {
1018
- this.lastThorttledTimeout && (clearTimeout(this.lastThorttledTimeout), this.lastThorttledTimeout = null), this.pendingCurrentMessage = null;
1019
- }
1020
- async turnComplete(t, e, s, o) {
1021
- this.cancelPendingCurrentMessage(), this.sessionState.setNewMessage(e), this.eventBusService.gatewayEmitTurnComplete(t, e), this.interactionCallIds.delete(t), this.sessionState.setLastToolEvent(null), this.localEmitToolEvent({
1022
- eventName: "todolistUpdated",
1023
- eventData: "",
1024
- subAgentId: o
1025
- }), this.sessionState.setTurnOpen(!1);
1026
- }
1027
- async handlePing() {
1028
- return Date.now() - this.lastPing.getTime() > Ft ? await this.ping() ? (this.lastPing = /* @__PURE__ */ new Date(), this.lastPingStatus = !0, !0) : (this.lastPingStatus = !1, !1) : (this.lastPingStatus = !0, !0);
1029
- }
1030
- async sendMessage(t, e) {
1031
- let s = this.getInteractions().length, o = _.createWaiting(!0, !0, "Overall", /* @__PURE__ */ new Date());
1032
- this.sendStatusMessage(t.data, [o], s.toString() + "1");
1033
- try {
1034
- const { promptAsString: n, json: a } = this.sessionState.onRenderPrompt ? this.sessionState.onRenderPrompt(t.data) : { promptAsString: t.data, json: void 0 };
1035
- this.sessionState.onRenderPrompt && (t.data = a, t.friendlyMessage = n);
1036
- const l = await this.sendMessageInternal(t, e), c = bt.createPrompt(n ?? "", (a == null ? void 0 : a.toString()) ?? {});
1037
- this.storageService.storePrompt(c);
1038
- const d = _.fromText("Planejando próximos passos");
1039
- return this.sendStatusMessage(t.data, [o, d], s.toString() + "1"), l != null && l.success ? this.eventBusService.ChatEmitMessageSent(t.data, l.interaction) : this.eventBusService.ChatEmitMessageError((l == null ? void 0 : l.error) ?? ""), l;
1040
- } catch (n) {
1041
- return this.eventBusService.ChatEmitMessageError((n == null ? void 0 : n.toString()) ?? ""), {
1042
- success: !1,
1043
- interaction: {
1044
- artifactData: [],
1045
- created: /* @__PURE__ */ new Date(),
1046
- interactionId: "",
1047
- partial: !1,
1048
- parts: [_.fromError((n == null ? void 0 : n.toString()) ?? "")],
1049
- version: 0
1050
- }
1051
- };
1052
- } finally {
1053
- this.clearStatus();
1054
- }
1055
- }
1056
- // `reset(user, config?)` is gone (issue #59): a fourth public door that took an
1057
- // AgentContext, with one implementation that only ever threw. Rebuild the engine
1058
- // instead — that is what "reset this conversation" means now.
1059
- async check() {
1060
- return !0;
1061
- }
1062
- startAndForget() {
1063
- }
1064
- forceReceiveMessage(t) {
1065
- t.partial = !0, t.turn_complete = !1, t.asyncFinalResponse = !1, t.interactionId = t.interactionId, this.eventBusService.gatewayEmitTurnOpen(t.interactionId), this.Message(t);
1066
- }
1067
- sendStatusMessage(t, e, s) {
1068
- var n, a;
1069
- let o;
1070
- ((a = (n = this.currentIS) == null ? void 0 : n.interaction) == null ? void 0 : a.turn_complete) === !1 ? (o = _t.cloneDeep(this.currentIS.interaction), o.parts.push(...e)) : o = {
1071
- interactionId: "tmp" + s,
1072
- created: /* @__PURE__ */ new Date(),
1073
- partial: !0,
1074
- turn_complete: !1,
1075
- version: 0,
1076
- parts: e,
1077
- interactionQuestion: t,
1078
- artifactData: []
1079
- }, this.localEmitMessage(o);
1080
- }
1081
- clearStatus() {
1082
- }
1083
- async ping() {
1084
- var t;
1085
- try {
1086
- const e = await fetch(this.base_url + "/ping"), s = await e.json();
1087
- return e.ok == !0 && ((t = s == null ? void 0 : s.debug) == null ? void 0 : t.id) != null;
1088
- } catch (e) {
1089
- return console.error("Error pinging server", e), !1;
1090
- }
1091
- }
1092
- getNewInteractionId() {
1093
- const e = Pt(/* @__PURE__ */ new Date(), "MMM_dd_HH_mm_ss");
1094
- return `${this.msg_order}_${e}`;
1095
- }
1096
- };
1097
- f(P, "AgentGatewayService"), i(P, "SUSPENSION_MSG", "SUSPEND"), // How often the streaming message re-renders. 150 ms made a reasoning highlight, or a burst of them, visibly lag the
1098
- // server (Ciro, 2026-10-07). The server already merges deltas over a 50 ms window (the SDK's DeltaCoalescer), so
1099
- // frames arrive at ~20/s per kind and 20 ms here costs little: it mostly stops adding a second delay on top.
1100
- i(P, "CURRENT_MSG_THROTTLE_MS", 20);
1101
- let z = P;
1102
- const $t = 0.02;
1103
- function xt(w, t) {
1104
- if (!t) return null;
1105
- const e = (t.interactionsCompressed ?? 0) > 0 || (t.compressionRatio ?? 0) > 0;
1106
- if (!w)
1107
- return e ? lt(t, t.size, t.size) : null;
1108
- const s = w.size - t.size, o = t.maxSize || w.maxSize || 0, n = o > 0 ? s / o >= $t : w.size > 0 && s / w.size >= 0.1;
1109
- return !e && !n ? null : lt(t, w.size, t.size, w.ratio);
1110
- }
1111
- f(xt, "detectCompaction");
1112
- function lt(w, t, e, s) {
1113
- return {
1114
- at: Date.now(),
1115
- // Where the bar stood when it happened — the marker's position. The ratio
1116
- // BEFORE the pass is the meaningful one: it is the fill the compaction
1117
- // reacted to, and it is also the only one that does not move afterwards.
1118
- ratio: s ?? w.ratio,
1119
- sizeBefore: t,
1120
- sizeAfter: e,
1121
- interactionsCompressed: w.interactionsCompressed
1122
- };
1123
- }
1124
- f(lt, "entry");
1125
- const B = 4001, Bt = 4002, ht = 4, Wt = 3, qt = 20, Gt = 500, Ht = 3e4, Kt = 2, zt = 0.2, q = 2, Jt = 5e3, Qt = 3e4, G = 1e4, Xt = 4100, V = class V {
1126
- constructor(t = "ws://localhost:8000", e) {
1127
- i(this, "ws", null);
1128
- i(this, "stats");
1129
- /**
1130
- * Compaction history for the whole CONNECTION, and the previous size reading it
1131
- * is derived from. Deliberately not inside `stats`: those are rebuilt on every
1132
- * interaction (see emitFirstToken), and a session's compaction history outlives
1133
- * any one turn — it is the thing the usage panel plots.
1134
- */
1135
- i(this, "sessionCompactions", []);
1136
- i(this, "previousSessionInformation");
1137
- i(this, "baseUrl");
1138
- /**
1139
- * Optional callback that returns the current JWT. We re-evaluate it on every connect/reconnect
1140
- * so that a refreshed token is picked up automatically. Browsers can't set the Authorization
1141
- * header on the WebSocket handshake, so we pass the JWT via the ?access_token= query string,
1142
- * which the .NET JwtBearer events handler reads in Program.cs.
1143
- */
1144
- i(this, "getToken");
1145
- i(this, "onEvent");
1146
- i(this, "onError");
1147
- i(this, "onOpen");
1148
- i(this, "onFirstToken");
1149
- i(this, "onSuspended");
1150
- i(this, "onPong");
1151
- i(this, "onClose");
1152
- /** Fired when an unexpected close triggers a reconnect attempt. */
1153
- i(this, "onReconnecting");
1154
- /** Fired the first time the socket reopens after an unexpected close. */
1155
- i(this, "onReconnected");
1156
- /**
1157
- * Fired when the server signals that we lost streaming events on resume — our
1158
- * `lastSeq` fell off the end of the in-memory replay buffer. Consumers should
1159
- * reset partial-streaming UI for this session and rely on persisted history.
1160
- */
1161
- i(this, "onRewindLost");
1162
- i(this, "sessionId");
1163
- i(this, "onNewPacket");
1164
- /**
1165
- * Stats can fire dozens of times per second during streaming. We
1166
- * coalesce to a fixed cadence so subscribers see steady,
1167
- * digestible updates instead of a per-packet firehose — the
1168
- * latter caused a "Maximum update depth exceeded" cascade in
1169
- * heavy v2 surfaces (RunProgressPanelV2 + StreamStatistics +
1170
- * ChatTranscript all subscribed to `statistics` and re-rendered
1171
- * on every packet, with their useEffect-driven setStates pushing
1172
- * React's nested-update counter past its threshold).
1173
- */
1174
- i(this, "statsFlushTimer", null);
1175
- i(this, "statsLastFlushed", 0);
1176
- i(this, "STATS_FLUSH_MS", 120);
1177
- i(this, "monitorInterval", null);
1178
- i(this, "streamingResponseSerializer");
1179
- i(this, "events");
1180
- i(this, "lastActivity");
1181
- /** When the outstanding heartbeat Ping went out; null while no reply is pending. */
1182
- i(this, "pingSentAt", null);
1183
- i(this, "firstTokenInteractions");
1184
- /** Last sessionId we successfully had — used to resume on reconnect. */
1185
- i(this, "lastKnownSessionId");
1186
- /** True when the consumer called `disconnect()` — suppresses auto-reconnect. */
1187
- i(this, "intentionalDisconnect", !1);
1188
- /** Number of reconnect attempts since the last clean open. */
1189
- i(this, "reconnectAttempts", 0);
1190
- i(this, "reconnectTimer", null);
1191
- /** True while we are in the middle of an unexpected-close → reconnect cycle. */
1192
- i(this, "isReconnecting", !1);
1193
- /** Internal flag set by `scheduleReconnect` so `connect()` does not reset the backoff state. */
1194
- i(this, "_internalReconnect", !1);
1195
- /**
1196
- * Highest server-assigned `seq` we have observed and processed. The next
1197
- * reconnect appends `?lastSeq={lastSeq}` so the server can replay anything
1198
- * we missed from the InteractionRun's in-memory buffer. -1 means "haven't
1199
- * seen any sequenced events yet" (fresh connection).
1200
- */
1201
- i(this, "lastSeq", -1);
1202
- /**
1203
- * Parked-tool answers that could not be sent because the socket was not OPEN
1204
- * (e.g. the connection idled out while the user was in an IdP sign-in popup).
1205
- * Keyed per tool call (last answer wins) and stamped with the session they
1206
- * belong to; flushed by `onopen` when the socket resumes THAT session. An
1207
- * answer for a session this instance is no longer attached to is dropped —
1208
- * the single-attach policy makes it undeliverable from here anyway.
1209
- */
1210
- i(this, "pendingAnswers", []);
1211
- /**
1212
- * True once *any* socket on this instance has received at least one packet.
1213
- * Used by `onclose` to distinguish a real mid-stream drop (we had a working
1214
- * channel) from a connect attempt that never produced traffic (server down,
1215
- * unreachable, etc.). The inner reconnect loop is only meant for the former
1216
- * — fresh-connect failures should be handed straight to the outer
1217
- * SessionStateManagerService.processRetryLoop instead of being retried
1218
- * twice in here. Sticky for the lifetime of this connection instance so
1219
- * that internal resume attempts keep their full inner-loop budget even
1220
- * when a replacement socket fails before delivering its first message.
1221
- * Cleared by `disconnect()`.
1222
- */
1223
- i(this, "hasEverReceivedPacket", !1);
1224
- this.baseUrl = t, this.getToken = e, this.events = [], this.firstTokenInteractions = /* @__PURE__ */ new Set(), this.streamingResponseSerializer = It(), console.log("SOCKET INSTACE", Tt()), this.stats = {
1225
- eventCount: 0,
1226
- unknonwCount: 0,
1227
- buffer: [],
1228
- startTime: /* @__PURE__ */ new Date(),
1229
- elapsed: 0,
1230
- unparsedCount: 0,
1231
- totalTransfered: 0,
1232
- tokensPerSecond: 0,
1233
- sessionCompactions: this.sessionCompactions
1234
- }, this.lastActivity = (/* @__PURE__ */ new Date()).getTime();
1235
- }
1236
- /**
1237
- * Connect to the WebSocket endpoint.
1238
- *
1239
- * `options.resume` keeps the replay cursor so the server can send back everything emitted
1240
- * while we were away (`?lastSeq=N`). Until it existed, only the socket's OWN
1241
- * `scheduleReconnect` could resume: every other caller landed in the "fresh connect" branch
1242
- * below, which discards `lastSeq`. A host that redials deliberately — a mobile app coming
1243
- * back to the foreground, say — therefore lost every frame emitted while it was suspended,
1244
- * silently, because the transcript looked intact right up to the gap.
1245
- */
1246
- connect(t, e) {
1247
- return new Promise(async (s, o) => {
1248
- var R;
1249
- this.intentionalDisconnect = !1;
1250
- const n = this._internalReconnect || (e == null ? void 0 : e.resume) === !0;
1251
- this._internalReconnect || this.cancelPendingReconnect(), n || (this.isReconnecting = !1, this.reconnectAttempts = 0, this.lastSeq = -1), this._internalReconnect = !1;
1252
- const a = (R = this.getToken) == null ? void 0 : R.call(this), l = [];
1253
- a && l.push(`access_token=${encodeURIComponent(a)}`), t && this.lastSeq >= 0 && l.push(`lastSeq=${this.lastSeq}`);
1254
- const c = l.length > 0 ? `?${l.join("&")}` : "", d = this.baseUrl.replace(/^http:\/\//, "ws://").replace(/^https:\/\//, "wss://"), u = `${d}/ws/connect/${t ?? ""}${c}`, h = `${d}/ws/connect/${t ?? ""}` + (n && t && this.lastSeq >= 0 ? ` (resume lastSeq=${this.lastSeq})` : "");
1255
- if (console.log("Connecting to ", h), this.ws) {
1256
- this.ws.onopen = null, this.ws.onmessage = null, this.ws.onerror = null, this.ws.onclose = null;
1257
- try {
1258
- this.ws.close();
1259
- } catch {
1260
- }
1261
- this.ws = null;
1262
- }
1263
- this.ws = new WebSocket(u), console.log("[WebSocket] Connecting to:", `${d}/ws/connect/${t ?? ""}`);
1264
- let v = !1;
1265
- this.ws.onopen = () => {
1266
- console.log("[WebSocket] Connected");
1267
- const y = this.isReconnecting;
1268
- this.isReconnecting = !1, this.reconnectAttempts = 0, this.ping(), this.monitor(), this.onOpen && this.onOpen(), y && console.log(`[WebSocket] Reconnected (session ${t ?? this.lastKnownSessionId ?? "none"}${this.lastSeq >= 0 ? `, replaying from lastSeq=${this.lastSeq}` : ", no replay cursor"}).`), y && this.onReconnected && this.onReconnected(t ?? this.lastKnownSessionId ?? ""), this.flushPendingAnswers(t ?? this.lastKnownSessionId);
1269
- }, this.ws.onmessage = (y) => {
1270
- try {
1271
- this.lastActivity = (/* @__PURE__ */ new Date()).getTime(), this.pingSentAt = null;
1272
- const A = this.streamingResponseSerializer.parse(y.data);
1273
- if (!A)
1274
- throw "Error parsing event JSON";
1275
- const O = this.handleMessage(A, y.data);
1276
- !v && (O != null && O.timestamp) && (v = !0, this.hasEverReceivedPacket = !0);
1277
- } catch (A) {
1278
- console.error("[WebSocket] Error parsing message:", A);
1279
- }
1280
- }, this.ws.onerror = (y) => {
1281
- console.error("[WebSocket] Error:", y), this.onError && this.onError("WebSocket error");
1282
- }, this.ws.onclose = (y) => {
1283
- console.log(`[WebSocket] Closed: code=${y.code} reason="${y.reason}" (session ${this.sessionLabel}, lastSeq=${this.lastSeq}, intentional=${this.intentionalDisconnect})`), this.monitorInterval && (clearInterval(this.monitorInterval), this.monitorInterval = null), this.pingSentAt = null;
1284
- const A = this.sessionId ?? this.lastKnownSessionId;
1285
- this.sessionId = void 0;
1286
- const O = v || this.hasEverReceivedPacket;
1287
- if (O && this.shouldAttemptReconnect(y.code)) {
1288
- this.scheduleReconnect(A, y.code, y.reason);
1289
- return;
1290
- }
1291
- console.warn(`[WebSocket] Inner reconnect declined for code=${y.code}: channelProven=${O}, codeRetryable=${this.shouldAttemptReconnect(y.code)}. Handing off to the outer state manager (session ${A ?? "none"}).`), this.isReconnecting = !1, this.reconnectAttempts = 0, this.onClose && this.onClose(y.code, y.reason);
1292
- };
1293
- const m = 200, M = 3e4, T = 8e3, E = this.ws;
1294
- this.sessionId = void 0;
1295
- let N = 0, b = 0;
1296
- for (; !this.sessionId; ) {
1297
- if (this.ws !== E) {
1298
- o("Connection attempt superseded by a newer connect()");
1299
- return;
1300
- }
1301
- if (E.readyState === WebSocket.CLOSING || E.readyState === WebSocket.CLOSED) {
1302
- o("Connection closed before a session id was received");
1303
- return;
1304
- }
1305
- if (E.readyState === WebSocket.CONNECTING && N >= M) {
1306
- try {
1307
- E.close();
1308
- } catch {
1309
- }
1310
- o(`Server did not accept the connection within ${M / 1e3}s`);
1311
- return;
1312
- }
1313
- if (E.readyState === WebSocket.OPEN && b >= T) {
1314
- o(`Connected but no session id arrived within ${T / 1e3}s`);
1315
- return;
1316
- }
1317
- N % 2e3 === 0 && console.log("Aguardando session Id"), await this.sleep(m), N += m, E.readyState === WebSocket.OPEN && (b += m);
1318
- }
1319
- console.log("SUCCESS - GOT SESSION ID", this.sessionId), this.lastKnownSessionId = this.sessionId, s(this.sessionId);
1320
- });
1321
- }
1322
- /**
1323
- * Returns true when the close code is something we believe a fresh connect
1324
- * (with the same sessionId) can recover from. We deliberately do NOT retry
1325
- * on:
1326
- * - 1000 normal closure
1327
- * - 1008 policy violation (auth rejected)
1328
- * - 4001 our own intentional disconnect
1329
- * - 4002 the session is attached elsewhere (another tab) — retrying just bounces
1330
- * Retried, on purpose:
1331
- * - 4003 the server's idle close ("reconnect on next interaction"): resuming is
1332
- * cheap and lossless, and while the user is present the outer loop would redial
1333
- * anyway; when they are gone the client's own idle timer closes first.
1334
- * - 4100 HEARTBEAT_TIMEOUT_CODE, our own dead-peer verdict.
1335
- */
1336
- shouldAttemptReconnect(t) {
1337
- return !(this.intentionalDisconnect || t === B || t === Bt || t === 1e3 || t === 1008);
1338
- }
1339
- cancelPendingReconnect() {
1340
- this.reconnectTimer && (console.log("[WebSocket] Cancelling the scheduled reconnect attempt."), clearTimeout(this.reconnectTimer), this.reconnectTimer = null);
1341
- }
1342
- computeBackoffDelay() {
1343
- const t = Gt * Math.pow(Kt, this.reconnectAttempts), e = Math.min(t, Ht), s = e * zt * (Math.random() * 2 - 1);
1344
- return Math.max(0, Math.round(e + s));
1345
- }
1346
- scheduleReconnect(t, e, s) {
1347
- var n, a;
1348
- if (this.intentionalDisconnect) return;
1349
- if (this.reconnectAttempts >= q) {
1350
- console.warn(
1351
- `[WebSocket] Reconnect exhausted after ${this.reconnectAttempts} attempts (last code=${e}, reason="${s}"). Handing off to outer state manager.`
1352
- ), this.isReconnecting = !1, this.reconnectAttempts = 0, this.cancelPendingReconnect(), (n = this.onClose) == null || n.call(this, e, s);
1353
- return;
1354
- }
1355
- this.isReconnecting = !0, this.reconnectAttempts += 1;
1356
- const o = this.computeBackoffDelay();
1357
- console.warn(
1358
- `[WebSocket] Unexpected close (code=${e}, reason="${s}"). Reconnect attempt #${this.reconnectAttempts}/${q} in ${o}ms (resume sessionId=${t ?? "none"}).`
1359
- ), (a = this.onReconnecting) == null || a.call(this, this.reconnectAttempts, o), this.cancelPendingReconnect(), this.reconnectTimer = setTimeout(async () => {
1360
- if (this.reconnectTimer = null, this.intentionalDisconnect) {
1361
- console.log("[WebSocket] Reconnect timer fired after an intentional disconnect — standing down.");
1362
- return;
1363
- }
1364
- console.log(`[WebSocket] Reconnect attempt #${this.reconnectAttempts}/${q} firing now (resume sessionId=${t ?? "none"}, lastSeq=${this.lastSeq}).`);
1365
- try {
1366
- this.ws && (this.ws.onopen = null, this.ws.onmessage = null, this.ws.onerror = null, this.ws.onclose = null, this.ws = null), this._internalReconnect = !0, await this.connect(t);
1367
- } catch (l) {
1368
- console.error("[WebSocket] Reconnect attempt failed:", l);
1369
- }
1370
- }, o);
1371
- }
1372
- async sleep(t) {
1373
- return new Promise((e) => setTimeout(e, t));
1374
- }
1375
- /** The session this instance believes it is on — for log lines, never for logic. */
1376
- get sessionLabel() {
1377
- return this.sessionId ?? this.lastKnownSessionId ?? "none";
1378
- }
1379
- /**
1380
- * Handle incoming messages from server
1381
- */
1382
- handleMessage(t, e) {
1383
- var l, c, d;
1384
- switch (typeof t.seq == "number" && t.seq > this.lastSeq && (this.lastSeq = t.seq), t.type) {
1385
- case "Pong":
1386
- if (this.sessionId = t.sessionId, this.lastKnownSessionId = t.sessionId ?? this.lastKnownSessionId, !t.sessionId) {
1387
- console.error("Pong response has no SESSION ID");
1388
- return;
1389
- }
1390
- t.accessToken && this.persistRefreshedAccessToken(t.accessToken), this.onPong && this.onPong(t.sessionId);
1391
- break;
1392
- case "Suspended":
1393
- this.onSuspended && this.onSuspended();
1394
- break;
1395
- case "Event":
1396
- break;
1397
- case "RewindLost":
1398
- console.warn(
1399
- `[WebSocket] RewindLost: lost events on resume, resuming from seq=${t.seq}`
1400
- ), typeof t.seq == "number" && (this.lastSeq = t.seq - 1), this.onRewindLost && t.sessionId && this.onRewindLost(t.sessionId, t.seq ?? -1);
1401
- break;
1402
- default:
1403
- console.warn("[WebSocket] Unknown message type:", t.type);
1404
- }
1405
- if (t.partialEvent) {
1406
- const u = t.partialEvent;
1407
- this.emitFirstToken(u == null ? void 0 : u.iteractionId);
1408
- const h = new vt();
1409
- if (h.author = "main", h.streamingParts = t.partialEvent.streamingParts, t.partialEvent.partialEventType ? h.eventType = t.partialEvent.partialEventType : h.eventType = u.functionName ? {
1410
- fullName: U.StreamingFunctionCallUpdateContent,
1411
- type: C.PartialFunctionCall
1412
- } : u.partialReasoning ? {
1413
- fullName: U.StreamingReasoningContent,
1414
- type: C.Thought
1415
- } : {
1416
- fullName: U.StreamingTextContent,
1417
- type: C.Text
1418
- }, h.interactionId = (u == null ? void 0 : u.iteractionId) ?? "", h.mimeType = "text/plain", h.partial = !0, h.eventType.type == C.PartialFunctionCall) {
1419
- var s = new Et();
1420
- s.choiceIndex = 0, s.callId = u.functionCallId, s.arguments = u.partialText, s.name = u.functionName, h.content = {
1421
- items: [s],
1422
- role: {
1423
- label: "Assistant"
1424
- }
1425
- };
1426
- } else if (h.eventType.type == C.Text)
1427
- if (h.eventType.fullName == U.StreamingTextContent) {
1428
- var o = new Mt();
1429
- o.text = u.partialText, h.content = {
1430
- items: [o],
1431
- role: {
1432
- label: "Assistant"
1433
- }
1434
- };
1435
- } else {
1436
- var n = new Dt();
1437
- n.text = u.partialText, h.content = {
1438
- items: [n],
1439
- role: {
1440
- label: "Assistant"
1441
- }
1442
- };
1443
- }
1444
- else if (h.eventType.type == C.Thought) {
1445
- var a = new At();
1446
- a.text = u.partialReasoning, h.content = {
1447
- items: [a],
1448
- role: {
1449
- label: "Assistant"
1450
- }
1451
- };
1452
- } else
1453
- t.event = void 0;
1454
- h.role = {
1455
- label: "Assistant"
1456
- }, h.timestamp = (u == null ? void 0 : u.timeStamp) ?? (/* @__PURE__ */ new Date()).getTime(), h.turnComplete = !1, t.event = h, t.partialEvent = void 0;
1457
- }
1458
- return t.event ? (t.subAgentId && (t.event.subAgentId = t.subAgentId, t.event.subAgentName = t.subAgentName), ((((c = (l = t.event.content) == null ? void 0 : l.items) == null ? void 0 : c.length) ?? 0) > 0 || (((d = t.event.streamingParts) == null ? void 0 : d.length) ?? 0) > 0) && this.emitFirstToken(t.event.interactionId), this.handleEvent(t.event, e), t.event) : null;
1459
- }
1460
- emitFirstToken(t) {
1461
- var e;
1462
- !t || this.firstTokenInteractions.has(t) || (this.stats = {
1463
- eventCount: 0,
1464
- unknonwCount: 0,
1465
- buffer: [],
1466
- startTime: /* @__PURE__ */ new Date(),
1467
- elapsed: 0,
1468
- unparsedCount: 0,
1469
- totalTransfered: 0,
1470
- tokensPerSecond: 0,
1471
- sessionCompactions: this.sessionCompactions
1472
- }, this.firstTokenInteractions.add(t), (e = this.onFirstToken) == null || e.call(this, t));
1473
- }
1474
- /**
1475
- * Mirror a server-side-refreshed JWT into the stored user record so the global
1476
- * fetch interceptor (packages/dashboard-app/.../EnvisionAuthProvider.tsx) picks
1477
- * it up on the next HTTP call. Idempotent — the same token is delivered on
1478
- * multiple consecutive Pong frames for listener-readiness, and we only write
1479
- * when it actually changed.
1480
- *
1481
- * Uses the same localStorage key the auth provider reads (`envision_user`).
1482
- * Done here in the WS layer rather than via a callback so consumers don't need
1483
- * to wire up token-handling boilerplate; React contexts that hold the user in
1484
- * memory will pick up the new token on the next refresh/render or via their
1485
- * own storage listeners.
1486
- */
1487
- persistRefreshedAccessToken(t) {
1488
- const e = "envision_user";
1489
- try {
1490
- const s = localStorage.getItem(e);
1491
- if (!s) {
1492
- console.warn("[WebSocket] WS-refreshed token received but no stored user — dropping");
1493
- return;
1494
- }
1495
- const o = JSON.parse(s);
1496
- if ((o == null ? void 0 : o.access_token) === t) return;
1497
- o.access_token = t, localStorage.setItem(e, JSON.stringify(o)), console.info("[WebSocket] Mirrored WS-refreshed JWT into stored user");
1498
- } catch (s) {
1499
- console.error("[WebSocket] Failed to persist WS-refreshed token", s);
1500
- }
1501
- }
1502
- closeStream() {
1503
- this.disconnect();
1504
- }
1505
- suspendStream() {
1506
- this.sendBaseMessage({
1507
- Action: F.Suspend,
1508
- AgentId: "",
1509
- InteractionId: "",
1510
- ModelId: ""
1511
- });
1512
- }
1513
- /**
1514
- * Send the user's answer to a parked ask_user tool call (ChatAction.AnswerHumanTool).
1515
- *
1516
- * Never throws on a dead socket: the parked tool answer is the one message whose loss
1517
- * strands the whole turn (the askauth popup case — the socket idles out while the user
1518
- * is at the IdP, the token comes back, and a plain send would throw into an unhandled
1519
- * rejection with the answer gone). When the socket is not OPEN the answer is queued and
1520
- * flushed by `onopen` on the next (re)connect of the same session.
1521
- *
1522
- * Returns 'sent' when it went out now, 'queued' when it will go out on reconnect.
1523
- */
1524
- answerHumanTool(t, e) {
1525
- const s = {
1526
- Action: F.AnswerHumanTool,
1527
- AgentId: "",
1528
- InteractionId: "",
1529
- ToolCallId: t,
1530
- Answer: e
1531
- };
1532
- if (this.ws && this.ws.readyState === WebSocket.OPEN)
1533
- try {
1534
- return this.sendBaseMessage(s), "sent";
1535
- } catch {
1536
- }
1537
- return this.queueAnswer(t, e), "queued";
1538
- }
1539
- queueAnswer(t, e) {
1540
- 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.`);
1541
- }
1542
- flushPendingAnswers(t) {
1543
- if (this.pendingAnswers.length === 0) return;
1544
- const e = this.pendingAnswers;
1545
- this.pendingAnswers = [];
1546
- for (const s of e) {
1547
- if (s.sessionId && t && s.sessionId !== t) {
1548
- console.warn(`[WebSocket] Dropping queued answer for tool call ${s.toolCallId} — it belongs to session ${s.sessionId}, reconnected to ${t}.`);
1549
- continue;
1550
- }
1551
- try {
1552
- this.sendBaseMessage({
1553
- Action: F.AnswerHumanTool,
1554
- AgentId: "",
1555
- InteractionId: "",
1556
- ToolCallId: s.toolCallId,
1557
- Answer: s.answer
1558
- }), console.info(`[WebSocket] Flushed queued answer for tool call ${s.toolCallId}.`);
1559
- } catch {
1560
- this.pendingAnswers.push(s);
1561
- }
1562
- }
1563
- }
1564
- /**
1565
- * Send a message to the agent
1566
- */
1567
- sendMessage(t) {
1568
- this.sendBaseMessage(t);
1569
- }
1570
- sendBaseMessage(t) {
1571
- if (this.lastActivity = (/* @__PURE__ */ new Date()).getTime(), !this.ws || this.ws.readyState !== WebSocket.OPEN)
1572
- throw new Error("WebSocket is not connected");
1573
- this.ws.send(JSON.stringify(t));
1574
- }
1575
- sendSuspendMessage(t) {
1576
- this.sendMessage(t);
1577
- }
1578
- /**
1579
- * Heartbeat: keep a quiet socket alive with a Ping every PING_INTERVAL_MS, and
1580
- * declare it dead when a Ping goes PONG_TIMEOUT_MS without ANY inbound frame.
1581
- * Started by `onopen`, stopped by `onclose`/`disconnect()`.
1582
- */
1583
- monitor() {
1584
- this.monitorInterval && clearInterval(this.monitorInterval), this.monitorInterval = setInterval(() => {
1585
- try {
1586
- if (!this.isConnected()) return;
1587
- const t = Date.now();
1588
- if (this.pingSentAt !== null) {
1589
- const e = t - this.pingSentAt;
1590
- if (e >= G) {
1591
- this.failSocket(
1592
- Xt,
1593
- `No frame received for ${Math.round(e / 1e3)}s after a Ping`
1594
- );
1595
- return;
1596
- }
1597
- console.warn(`[WebSocket] Still no reply ${e}ms after the Ping (budget ${G}ms, session ${this.sessionLabel}) — the peer may be gone.`);
1598
- return;
1599
- }
1600
- t - this.lastActivity >= Qt && this.ping();
1601
- } catch (t) {
1602
- console.error("Error on monitor", t);
1603
- }
1604
- }, Jt);
1605
- }
1606
- /**
1607
- * Send a heartbeat ping and start the reply clock (unless one is already running).
1608
- */
1609
- ping() {
1610
- this.sendBaseMessage({
1611
- Action: "Ping",
1612
- AgentId: "",
1613
- InteractionId: "",
1614
- ModelId: ""
1615
- }), this.pingSentAt === null && (this.pingSentAt = Date.now(), console.log(`[WebSocket] Ping sent after ${Date.now() - this.lastActivity}ms of silence (session ${this.sessionLabel}); any frame within ${G}ms answers it.`));
1616
- }
1617
- /**
1618
- * Declare the current socket dead and run the close path NOW, without waiting
1619
- * for the browser: for a half-open peer `onclose` can lag by minutes or never
1620
- * come, and the decision has already been made. The dead socket's own onclose
1621
- * handler is invoked with a client-local code, so the reconnect-vs-handoff
1622
- * logic that runs is exactly the one a server close would run. Handlers are
1623
- * detached first so a late real close event cannot run it a second time.
1624
- */
1625
- failSocket(t, e) {
1626
- const s = this.ws;
1627
- if (!s) return;
1628
- 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.`);
1629
- const o = s.onclose;
1630
- s.onopen = null, s.onmessage = null, s.onerror = null, s.onclose = null;
1631
- try {
1632
- s.close();
1633
- } catch {
1634
- }
1635
- o == null || o.call(s, { code: t, reason: e });
1636
- }
1637
- /**
1638
- * Disconnect the WebSocket
1639
- */
1640
- disconnect() {
1641
- console.warn("Chamou DISCONNECT!!!"), this.intentionalDisconnect = !0, this.cancelPendingReconnect(), this.isReconnecting = !1, this.reconnectAttempts = 0, this.monitorInterval && (clearInterval(this.monitorInterval), this.monitorInterval = null), this.pingSentAt = null, this.firstTokenInteractions.clear(), this.lastKnownSessionId = void 0, this.lastSeq = -1, this.hasEverReceivedPacket = !1, this.ws && (this.ws.close(B, "Intentional disconnect"), this.ws = null);
1642
- }
1643
- /**
1644
- * Check if connected
1645
- */
1646
- isConnected() {
1647
- return this.ws !== null && this.ws.readyState === WebSocket.OPEN;
1648
- }
1649
- /**
1650
- * Push the latest stats out to `onNewPacket`, but at most every
1651
- * `STATS_FLUSH_MS` ms. Subsequent packets within the window
1652
- * schedule a trailing flush so the UI eventually sees the final
1653
- * value without each individual packet causing a re-render.
1654
- */
1655
- flushStatsCoalesced() {
1656
- if (!this.onNewPacket) return;
1657
- const t = Date.now(), e = t - this.statsLastFlushed;
1658
- if (e >= this.STATS_FLUSH_MS) {
1659
- this.statsFlushTimer && (clearTimeout(this.statsFlushTimer), this.statsFlushTimer = null), this.statsLastFlushed = t, this.onNewPacket({ ...this.stats });
1660
- return;
1661
- }
1662
- this.statsFlushTimer || (this.statsFlushTimer = setTimeout(() => {
1663
- var s;
1664
- this.statsFlushTimer = null, this.statsLastFlushed = Date.now(), (s = this.onNewPacket) == null || s.call(this, { ...this.stats });
1665
- }, this.STATS_FLUSH_MS - e));
1666
- }
1667
- async handleEvent(t, e) {
1668
- var s;
1669
- try {
1670
- const o = gt.parseFromTypedEvent(t);
1671
- if (!o)
1672
- throw "Server event was null";
1673
- if (this.events.push([(/* @__PURE__ */ new Date()).getTime(), ((s = t.text) == null ? void 0 : s.length) ?? 0]), this.stats.eventCount += 1, this.stats.totalTransfered += e.length, o.session_information && !o.subAgentId) {
1674
- const c = xt(this.previousSessionInformation, o.session_information);
1675
- c && (this.sessionCompactions.push(c), this.sessionCompactions.length > qt && this.sessionCompactions.shift()), this.previousSessionInformation = o.session_information, this.stats.sessionInformation = o.session_information, this.stats.sessionCompactions = this.sessionCompactions;
1676
- }
1677
- this.stats.elapsed = (Date.now() - this.stats.startTime.getTime()) / 1e3;
1678
- const n = Date.now() - ht * 1e3, l = this.events.filter((c) => c[0] > n).reduce((c, d) => c += d[1], 0) / Wt;
1679
- this.stats.tokensPerSecond = l / ht, this.flushStatsCoalesced(), this.onEvent && this.onEvent(o).catch((c) => {
1680
- console.error("Lost error on on-event", c);
1681
- });
1682
- } catch (o) {
1683
- console.error("handleEvent error", o);
1684
- }
1685
- }
1686
- };
1687
- f(V, "WebSocketConnecionV2");
1688
- let ut = V;
1689
- const Yt = "envision_agent_sessionId", tt = class tt extends z {
1690
- constructor(e, s, o, n, a, l, c, d, u, h, v) {
1691
- super(e, s, o, n, a, l, c, u, v);
1692
- i(this, "suspendState", !1);
1693
- i(this, "wsService");
1694
- i(this, "root_url", "");
1695
- i(this, "hearBeatPort");
1696
- i(this, "connectionAttempts", 0);
1697
- /**
1698
- * True once a WS has successfully opened at least once in this gateway's
1699
- * lifetime. Gates the "Reiniciando a conexão" toast: a drop of a working
1700
- * connection is worth telling the user about, a failed initial dial is not
1701
- * (the Connecting state already covers it).
1702
- */
1703
- i(this, "everConnected", !1);
1704
- i(this, "statuses", ["CONNECTING", "OPEN", "CLOSED", "UNKNOWN"]);
1705
- i(this, "lastConnectionPromise", null);
1706
- i(this, "socketState", k.Disconnected);
1707
- i(this, "streamOpened", !1);
1708
- this.hearBeatPort = h, this.root_url = this.base_url, this.wsService = d, this.wsService.onEvent = async (m) => {
1709
- await super.Message(m);
1710
- }, this.wsService.onNewPacket = (m) => {
1711
- this.sessionState.setStatistics(m), this.eventBusService.streamEmitNewChunk(m);
1712
- }, this.wsService.onPong = (m) => {
1713
- }, this.wsService.onError = (m) => {
1714
- this.streamOpened = !1;
1715
- const M = {
1716
- data: this.getErrorEvent(m),
1717
- lastEventId: (/* @__PURE__ */ new Date()).getTime().toString(),
1718
- origin: "gatewayService"
1719
- };
1720
- console.error("Stream error:", m), this.everConnected && this.notificationPort.pushNotification({
1721
- message: "Reiniciando a conexão com o servidor",
1722
- type: "info",
1723
- // Tagged so a host can recognise this one and draw its own affordance (a progress bar glued
1724
- // to the page, say) instead of a toast, without matching on the copy.
1725
- kind: "connection-restarting"
1726
- }), super.Message(M);
1727
- }, this.wsService.onOpen = () => {
1728
- this.everConnected = !0, this.sessionState.setConnectionStatus(k.Connected);
1729
- }, this.wsService.onReconnected = (m) => {
1730
- this.sessionState.setConnectionStatus(k.Connected);
1731
- }, this.wsService.onFirstToken = (m) => {
1732
- this.localEmitFirstToken(m);
1733
- }, this.wsService.onClose = (m, M) => {
1734
- console.log(`[AgentGateway] transport closed (code=${m}, reason="${M}") — ${m != B ? "flipping to Disconnected so the state manager takes over the redial." : "our own disconnect, leaving the connection status alone."}`), m != B && this.sessionState.setConnectionStatus(k.Disconnected);
1735
- };
1736
- }
1737
- startStream(e) {
1738
- throw new Error("Method not implemented.");
1739
- }
1740
- isSuspended() {
1741
- return this.suspendState;
1742
- }
1743
- getStoredSessionId() {
1744
- const e = localStorage.getItem(Yt);
1745
- if (e)
1746
- return e;
1747
- }
1748
- isInteractionComplete(e) {
1749
- const s = this.interactionsMap.get(e);
1750
- return s == null ? void 0 : s.turn_complete;
1751
- }
1752
- isTurnCompleted(e) {
1753
- const s = this.interactionsMap.get(e);
1754
- return s == null ? void 0 : s.turn_complete;
1755
- }
1756
- async finalResponse(e, s, o) {
1757
- super.turnComplete(e, s, o);
1758
- }
1759
- stopStream(e = !0) {
1760
- e && this.sessionState.setTurnOpen(!1), this.wsService && this.wsService.closeStream();
1761
- }
1762
- async suspend() {
1763
- const e = this.wsService;
1764
- return new Promise(async (o, n) => {
1765
- let a = !1;
1766
- e.onSuspended = () => {
1767
- a = !0;
1768
- }, e.suspendStream();
1769
- try {
1770
- let d = 0;
1771
- for (; !a && d < 5e3; )
1772
- await this.sleep(100), d += 100;
1773
- if (a)
1774
- if (this.currentIS) {
1775
- const u = this.currentIS.interaction;
1776
- u.isSuspended = !0, this.sessionState.setCurrentMessage(u), this.sessionState.setTurnOpen(!1), o(!0);
1777
- } else
1778
- console.error("CurrentIS is null"), n("CurrentIS is null");
1779
- else
1780
- n("Timeout awaiting for suspension");
1781
- } finally {
1782
- this.suspendState = !0;
1783
- }
1784
- });
1785
- }
1786
- /**
1787
- * Forwards a parked-tool answer; 'queued' means the socket was down and it will flush on reconnect.
1788
- *
1789
- * Feature-detected rather than cast: a host may supply any `IWebSocketConnection` (the demo's fake
1790
- * gateway does), and a hard cast turned "this transport doesn't deliver answers" into a TypeError
1791
- * thrown from a click handler — with the answer lost either way.
1792
- */
1793
- answerHumanTool(e, s) {
1794
- var n;
1795
- const o = (n = this.wsService.answerHumanTool) == null ? void 0 : n.bind(this.wsService);
1796
- return o ? o(e, s) : (console.warn("[AgentGateway] transport cannot deliver parked-tool answers", e), "queued");
1797
- }
1798
- async cancelSuspend() {
1799
- var s;
1800
- const e = (s = this.currentIS) == null ? void 0 : s.interaction;
1801
- e && (e.isSuspended = !1, this.turnComplete(e.interactionId, e, "Main"));
1802
- }
1803
- async check() {
1804
- return !0;
1805
- }
1806
- async openConnection(e, s) {
1807
- return this.lastConnectionPromise ? this.lastConnectionPromise : this.socketState == k.Disconnected ? (this.lastConnectionPromise = new Promise((o, n) => {
1808
- this.wsService.connect(e, s).then((a) => {
1809
- this.sessionId = a, o(a);
1810
- }).catch((a) => {
1811
- n(a);
1812
- }).finally(() => {
1813
- this.lastConnectionPromise = null;
1814
- });
1815
- }), this.lastConnectionPromise) : Promise.resolve(this.sessionId);
1816
- }
1817
- async closeConnection(e = !0) {
1818
- try {
1819
- return this.stopStream(e), {
1820
- success: !0,
1821
- interaction: this.getCurrentInteraction()
1822
- };
1823
- } catch {
1824
- return {
1825
- success: !1,
1826
- interaction: this.getCurrentInteraction()
1827
- };
1828
- }
1829
- }
1830
- simulateDisconnect(e = 4500, s = "Debug simulated disconnect") {
1831
- const o = this.wsService;
1832
- o != null && o.ws && o.ws.close(e, s);
1833
- }
1834
- async sleep(e) {
1835
- return new Promise((s) => setTimeout(s, e));
1836
- }
1837
- /**
1838
- * Make sure the socket is OPEN before a send, redialling the SAME session when it is not.
1839
- *
1840
- * The socket can be down at send time for reasons the composer cannot see: the client's own
1841
- * idle close (5 min without input), the server's (6 min without a message, code 4003), a dead
1842
- * peer the heartbeat just detected, or a dial still in flight. Until this existed the send
1843
- * threw `WebSocket is not connected` AFTER the user's turn was already on the transcript — or
1844
- * the composer refused it outright — and the only way back was the 2 s heartbeat noticing
1845
- * mouse movement. A send IS the activity that reconnect was waiting for, so dial here.
1846
- *
1847
- * `resume: true` keeps the replay cursor: if the socket died mid-turn the server replays what
1848
- * we missed. `openConnection` de-duplicates against a dial already in flight (the state
1849
- * manager's retry loop, a host's own bind), so concurrent callers share one socket. A
1850
- * transport without `isConnected` semantics (the demo's fake gateway) is treated as up.
1851
- */
1852
- async ensureConnected() {
1853
- const e = this.sessionId;
1854
- if (this.wsService.isConnected()) {
1855
- console.log(`[AgentGateway] send guard: socket is open (session ${e ?? "none"}, status ${this.sessionState.connectionStatus}) — sending straight away.`);
1856
- return;
1857
- }
1858
- console.warn(`[AgentGateway] send guard: socket is DOWN at send time (session ${e ?? "none"}, status ${this.sessionState.connectionStatus}) — redialling with the replay cursor before sending.`), this.sessionState.setConnectionStatus(k.Connecting);
1859
- const s = Date.now();
1860
- try {
1861
- const o = await this.openConnection(e, { resume: !0 });
1862
- o !== e ? console.warn(`[AgentGateway] send guard: session ${e} could not be resumed; the server opened ${o} instead — this turn starts a new conversation.`) : console.log(`[AgentGateway] send guard: reconnected to ${o} in ${Date.now() - s}ms — sending now.`), this.sessionState.setConnectionStatus(k.Connected);
1863
- } catch (o) {
1864
- throw console.error(`[AgentGateway] send guard: redial FAILED after ${Date.now() - s}ms — the message was not sent.`, o), this.sessionState.setConnectionStatus(k.Disconnected), new Error(`Could not reconnect before sending: ${o}`);
1865
- }
1866
- }
1867
- // Send a message to the server over the socket
1868
- async sendMessageInternal(e, s, o) {
1869
- var l, c, d, u, h, v, m, M;
1870
- const n = this.suspendState;
1871
- this.suspendState = !1;
1872
- const a = this.startInteraction(e.friendlyMessage ?? e.data, n);
1873
- if (this.registerInteractionCallId(a.interactionId, s), (l = e.userUi) != null && l.name && a.parts.push(_.fromUserUi(e.userUi.name, e.userUi.args)), !this.wsService)
1874
- throw "no wsService created";
1875
- if (!this.sessionId)
1876
- throw "no session id set";
1877
- if (!((c = this.config.agentConfig) != null && c.id))
1878
- throw "Agent not selected";
1879
- return this.sessionState.setLastActivity(), await this.ensureConnected(), this.wsService.sendMessage({
1880
- Content: e.data,
1881
- SessionId: this.sessionId,
1882
- Action: F.SendMessage,
1883
- ModelId: this.config.model,
1884
- InteractionId: a.interactionId,
1885
- AgentId: (d = this.config.agentConfig) == null ? void 0 : d.id,
1886
- // Optional explicit C# class name on the server (e.g. "LlmAgentSessionReplay").
1887
- // When set, AgentBootStrapService.GetAgent dispatches to that class directly
1888
- // instead of looking up an Agent metadata row by AgentId. Plumbed through
1889
- // `agentContext.agentConfig.agentImplementation` so a host can run a turn
1890
- // against any registered LlmAgent variant without seeding a Mongo record.
1891
- AgentImplementation: (u = this.config.agentConfig) == null ? void 0 : u.agentImplementation,
1892
- Parameters: {
1893
- CustomerName: ((h = this.config.customer) == null ? void 0 : h.name) ?? "",
1894
- DataSet: ((v = this.config.customer) == null ? void 0 : v.dataSetId) ?? ""
1895
- },
1896
- // Forward image attachments as a structured payload (PascalCase
1897
- // keys to match the C# `Message.Images` / `MessageImage` model).
1898
- Images: (m = e.images) != null && m.length ? e.images.map((T) => ({ MimeType: T.mimeType, Data: T.data })) : void 0,
1899
- // Client-only UI representation for this turn (PascalCase to match the C# `Message.UserUi`
1900
- // model). The server persists it as a UserUiContent sibling and strips it from the model
1901
- // request; Content remains the only model-facing text.
1902
- UserUi: (M = e.userUi) != null && M.name ? { Name: e.userUi.name, Args: e.userUi.args } : void 0
1903
- }), this.localOpen(a.interactionId, "system"), Promise.resolve({
1904
- interaction: a,
1905
- success: !0
1906
- });
1907
- }
1908
- };
1909
- f(tt, "AgentGatewayWSAsync");
1910
- let dt = tt;
1911
- const et = class et {
1912
- constructor(t, e) {
1913
- i(this, "cache", /* @__PURE__ */ new Map());
1914
- i(this, "serverBaseUrl");
1915
- i(this, "accessToken");
1916
- this.serverBaseUrl = t.replace(/\/$/, ""), this.accessToken = e;
1917
- }
1918
- get headers() {
1919
- return { Authorization: `Bearer ${Rt(this.accessToken)}` };
1920
- }
1921
- async init() {
1922
- }
1923
- getArtifacts() {
1924
- return Array.from(this.cache.values());
1925
- }
1926
- async saveArtifact(t) {
1927
- this.cache.set(t.id, t);
1928
- }
1929
- saveArtifactToCache(t) {
1930
- this.cache.set(t.id, t);
1931
- }
1932
- async deleteArtifact(t) {
1933
- this.cache.delete(t);
1934
- }
1935
- addToCache(t) {
1936
- this.cache.set(t.id, t);
1937
- }
1938
- getArtifactWithCache(t) {
1939
- return this.cache.get(t) ?? null;
1940
- }
1941
- async getArtifact(t, e) {
1942
- if (this.cache.has(t)) return this.cache.get(t) ?? null;
1943
- try {
1944
- const s = await fetch(`${this.serverBaseUrl}/AdminArtifact/${t}`, {
1945
- headers: this.headers
1946
- });
1947
- if (!s.ok) return null;
1948
- const o = await s.json();
1949
- return this.cache.set(o.id, o), o;
1950
- } catch {
1951
- return null;
1952
- }
1953
- }
1954
- async clearAllArtifacts() {
1955
- this.cache.clear();
1956
- }
1957
- async getFileContent(t) {
1958
- try {
1959
- const e = await fetch(t, { headers: this.headers });
1960
- return e.ok ? await e.text() : null;
1961
- } catch {
1962
- return null;
1963
- }
1964
- }
1965
- };
1966
- f(et, "HttpArtifactService");
1967
- let ft = et;
1968
- export {
1969
- z as A,
1970
- K as E,
1971
- ft as H,
1972
- x as I,
1973
- rt as L,
1974
- ct as M,
1975
- ut as W,
1976
- dt as a,
1977
- re as u
1978
- };
1979
- //# sourceMappingURL=httpArtifactService-GdGsaFKS.js.map