@aintela/chat 0.8.0 → 0.10.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 (44) hide show
  1. package/dist/Memory-BUnmYGNv.js.map +1 -1
  2. package/dist/PersonaAvatar-tKaWpDeQ.js +199 -0
  3. package/dist/PersonaAvatar-tKaWpDeQ.js.map +1 -0
  4. package/dist/agent-team.d.ts +2 -0
  5. package/dist/agent-team.js +27 -0
  6. package/dist/agent-team.js.map +1 -0
  7. package/dist/components.js +8543 -8995
  8. package/dist/components.js.map +1 -1
  9. package/dist/{detachedRunActivity-RNg1JDDW.js → detachedRunActivity-DWOR3cAC.js} +227 -224
  10. package/dist/detachedRunActivity-DWOR3cAC.js.map +1 -0
  11. package/dist/hooks.js +1 -1
  12. package/dist/{httpSessionService-DLdoBZRW.js → httpSessionService-BIkDesYB.js} +32 -31
  13. package/dist/{httpSessionService-DLdoBZRW.js.map → httpSessionService-BIkDesYB.js.map} +1 -1
  14. package/dist/index.js +289 -278
  15. package/dist/index.js.map +1 -1
  16. package/dist/serializer-DvR3nOcf.js.map +1 -1
  17. package/dist/services.js +2 -2
  18. package/dist/src/agentTeam.d.ts +3 -0
  19. package/dist/src/components/AgentTeam/PersonaAvatar.d.ts +7 -1
  20. package/dist/src/components/AgentTeam/__tests__/personaFixtures.d.ts +3 -0
  21. package/dist/src/components/AgentTeam/agentRoles.d.ts +2 -2
  22. package/dist/src/components/AgentTeam/chatAgent.d.ts +1 -1
  23. package/dist/src/components/AgentTeam/personas.d.ts +65 -4
  24. package/dist/src/components/AiChat/AiChatContext.d.ts +9 -0
  25. package/dist/src/components/AiChat/AiChatTypes.d.ts +6 -0
  26. package/dist/src/components/AiChat/ChatPane/ChatTurn.d.ts +33 -0
  27. package/dist/src/components/AiChat/ChatPane/CurrentMessage.d.ts +6 -4
  28. package/dist/src/components/AiChat/ChatPane/parts/ReadOnlyGuard.d.ts +9 -0
  29. package/dist/src/components/AiChat/ChatPane/parts/uiPartStage.d.ts +15 -10
  30. package/dist/src/components/AiChat/ChatPane/parts/uiToolRegistry.d.ts +6 -0
  31. package/dist/src/components/AiChat/ChatPane/turnCommitKeepsUiTools.test.d.ts +1 -0
  32. package/dist/src/components/LlmResponseRender/EnvironmentContext.d.ts +7 -0
  33. package/dist/src/components/index.d.ts +1 -1
  34. package/dist/src/components/v2/SharedSessionTranscript.d.ts +76 -0
  35. package/dist/src/components/v2/index.d.ts +2 -0
  36. package/dist/src/models/ChatSession.d.ts +6 -0
  37. package/dist/src/models/Interaction.d.ts +1 -1
  38. package/dist/src/models/contexts.d.ts +6 -0
  39. package/dist/src/services/detachedRun/DetachedRunFramesTransport.d.ts +11 -0
  40. package/dist/src/services/detachedRun/streamDetachedRunFrames.d.ts +7 -0
  41. package/dist/{useChatSessions-DwqgYo79.js → useChatSessions-CyFKVtkk.js} +2 -2
  42. package/dist/{useChatSessions-DwqgYo79.js.map → useChatSessions-CyFKVtkk.js.map} +1 -1
  43. package/package.json +8 -1
  44. package/dist/detachedRunActivity-RNg1JDDW.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"detachedRunActivity-DWOR3cAC.js","sources":["../src/services/storageService.ts","../src/services/eventBusService.ts","../src/services/interaction/reduceInteraction.ts","../src/services/interactionService.ts","../src/services/WebSocketConnection/closeCodes.ts","../src/services/servers/connectionSupervisor.ts","../src/services/servers/throttledEmitter.ts","../src/services/servers/AgentGatewayWSAsync.ts","../src/services/wire/decodeFrame.ts","../src/utils/sessionCompaction.ts","../src/services/WebSocketConnection/streamStats.ts","../src/services/WebSocketConnection/WebSocketConnectionV2.ts","../src/services/httpArtifactService.ts","../src/services/detachedRun/streamDetachedRunFrames.ts","../src/services/detachedRun/DetachedRunFramesTransport.ts","../src/services/detachedRun/detachedRunActivity.ts"],"sourcesContent":["import type { Prompt } from '../models/Prompt';\n\n/**\n * Browser-local storage for the chat's PROMPT HISTORY, and nothing else.\n *\n * It used to also hold an artifacts-and-sections store (`envision-artifacts` /\n * `envision-sections`, seeded with default dashboard folders) — the envision-abi\n * dashboard's artifact organizer, inherited when the chat was extracted into\n * this library and never wired to anything here. The chat reads artifacts\n * through `IArtifactService` (HTTP + cache) instead. Removed with the rest of\n * the inherited dead weight; see the deleted `MockStorageService` too, which no\n * test ever used.\n */\nconst STORAGE_KEYS = {\n PROMPTS: 'envision-prompts',\n} as const;\n\n/** How many prompts the history keeps. Older ones fall off the end. */\nconst MAX_PROMPTS = 50;\n\n/**\n * The prompt-history port. Three methods, all of them live:\n * `storePrompt` on every sent turn, `getPrompts` for the two LastPrompts\n * surfaces, `clearAllPrompts` for the clear control.\n *\n * Keep it this small. It is injected into the gateway, so anything added here\n * has to be implemented by every test fake — and an 18-method interface that\n * fakes could not honestly satisfy is precisely how `sendMessage` came to throw\n * a TypeError in every gateway test without anyone noticing.\n */\nexport interface IStorageService {\n getPrompts(): Prompt[];\n storePrompt(prompt: Prompt): void;\n clearAllPrompts(): void;\n}\n\n/** The only implementation — no consumer has ever supplied its own. */\nexport class LocalStorageService implements IStorageService {\n getPrompts(): Prompt[] {\n try {\n const stored = localStorage.getItem(STORAGE_KEYS.PROMPTS);\n if (stored) {\n const prompts = JSON.parse(stored) as Prompt[];\n // Sort by created date, most recent first\n return prompts.sort((a, b) => new Date(b.created).getTime() - new Date(a.created).getTime());\n }\n return [];\n } catch (error) {\n console.error('Error loading prompts:', error);\n return [];\n }\n }\n\n /**\n * Record a sent prompt, most recent first, de-duplicated by text.\n *\n * Asking the same thing again MOVES that entry to the top rather than adding\n * a second copy — the history is a list of distinct things you have asked,\n * and a repeated question spending two of the twelve visible rows costs a\n * suggestion for nothing. The repeat's own `id` and `created` win, because\n * what the list orders by is when you last asked.\n *\n * The dedupe used to look only at `prompts[0]`, and then unshifted anyway:\n * a consecutive repeat overwrote the older copy's id and timestamp AND\n * appended a new row, so the same text appeared twice with the same id.\n *\n * Matching is exact on `promptText` (`PromptUtils.createPrompt` has already\n * trimmed it). Two prompts differing only in case or inner whitespace stay\n * separate entries — that is deliberate, not an oversight: normalising them\n * would mean re-surfacing text the user never typed.\n */\n storePrompt(prompt: Prompt): void {\n try {\n const prompts = this.getPrompts().filter((p) => p.promptText !== prompt.promptText);\n prompts.unshift(prompt);\n\n localStorage.setItem(STORAGE_KEYS.PROMPTS, JSON.stringify(prompts.slice(0, MAX_PROMPTS)));\n } catch (error) {\n console.error('Error storing prompt:', error);\n }\n }\n\n clearAllPrompts(): void {\n try {\n localStorage.removeItem(STORAGE_KEYS.PROMPTS);\n } catch (error) {\n console.error('Error clearing prompts:', error);\n }\n }\n}\n\n/**\n * A cheap change-signal over the stored prompts, so the LastPrompts surfaces\n * re-render when a freshly sent prompt lands. It is a digest, not state: the\n * count plus the first/last text and the newest timestamp.\n */\nexport const usePromptState = (storageService: IStorageService): { promptState: string } => {\n const prompts = storageService.getPrompts();\n const promptSize = prompts.length;\n if (promptSize > 0) {\n const firstPrompt = prompts[0].promptText;\n const lastPrompt = prompts[prompts.length - 1].promptText;\n const lastCreated = prompts[0].created;\n return { promptState: promptSize + \"_\" + firstPrompt + \"_\" + lastPrompt + \"_\" + lastCreated };\n }\n else {\n return { promptState: \"0\" };\n }\n};\n","\nimport { type EndMessageData } from \"@lib/models/EndMessageData\";\nimport type { Interaction } from \"../models/Interaction\";\nimport type { FunctionDetails } from \"../models/ServerEvent\";\nimport { type Artifact } from \"@lib/models/Artifact\";\n\nexport interface FirstTokenEventDetails {\n interactionId: string;\n callId?: string;\n}\n\n// Every channel below has at least one emitter in the library AND either a\n// subscriber here or a documented host-facing use (obtapp subscribes to\n// toolEvent / turnComplete / messageSent; artifactGenerated, endMessageData and\n// functionResponse are the host hooks the gateway publishes). Channels with\n// neither were removed in the stream-path cleanup — add one back only together\n// with its first consumer.\nexport class EventTypes {\n public artifactGenerated = \"artifactGenerated\";\n public artifactSelected = \"artifactSelected\";\n public gatewayMessage = \"gatewayMessage\";\n public gatewayTurnComplete = \"gatewayTurnComplete\";\n public gatewayStreamError = \"gatewayStreamError\";\n public gatewayConnected = \"gatewayConnected\";\n public gatewayTurnOpen = \"gatewayTurnOpen\";\n public gatewayFunctionResponse = \"gatewayFunctionResponse\";\n public uiAskQuestion = \"uiAskQuestion\";\n public gatewayEndMessageData = \"gatewayEndMessageData\";\n public onMessageSent = \"onMessageSent\";\n public onMessageError = \"onMessageError\";\n public onToolEvent = \"onToolEvent\";\n public gatewayFirstToken = \"gatewayFirstToken\";\n}\n\nexport const allEventTypes = new EventTypes();\n\ntype Listener = (...args: any) => Promise<void>;\n\nexport class EventBusService {\n protected listeners: { [methodName: string]: Listener[] } = {};\n\n protected callListeners(eventName: string, ...args: any[]) {\n const listeners = this.listeners[eventName];\n if (listeners) {\n const promisses = listeners.map(listener => listener(...args));\n Promise.all(promisses)\n .catch((error) => {\n console.error(`Lost error in one of the listeners of the event: ${eventName}, listeners: ${listeners.length}, error: ${error}`, listeners);\n });\n }\n }\n\n protected addListener(eventName: string, listener: Listener) {\n if (!this.listeners[eventName]) {\n this.listeners[eventName] = [];\n }\n this.listeners[eventName].push(listener);\n }\n\n protected removeListener(eventName: string, listener: Listener) {\n if (this.listeners[eventName]) {\n this.listeners[eventName] = this.listeners[eventName].filter(l => l !== listener);\n }\n }\n\n /* typed artifact listeners */\n public artifactOnGenerated(listener: (artifact: Artifact) => Promise<void>) {\n this.addListener(allEventTypes.artifactGenerated, listener);\n }\n\n public artifactEmitGenerated(artifact: Artifact) {\n this.callListeners(allEventTypes.artifactGenerated, artifact);\n }\n\n public artifactOffGenerated(listener: (artifact: Artifact) => Promise<void>) {\n this.removeListener(allEventTypes.artifactGenerated, listener);\n }\n\n public artifactOnSelected(listener: (artifact: Artifact | string) => Promise<void>) {\n this.addListener(allEventTypes.artifactSelected, listener);\n }\n\n public artifactEmitSelected(artifact: Artifact | string) {\n this.callListeners(allEventTypes.artifactSelected, artifact);\n }\n\n public artifactOffSelected(listener: (artifact: Artifact | string) => Promise<void>) {\n this.removeListener(allEventTypes.artifactSelected, listener);\n }\n\n public gatewayOnMessage(listener: (interaction: Interaction) => Promise<void>) {\n this.addListener(allEventTypes.gatewayMessage, listener);\n }\n\n public gatewayEmitMessage(agentInteraction: Interaction) {\n this.callListeners(allEventTypes.gatewayMessage, agentInteraction);\n }\n\n public gatewayOffMessage(listener: (interaction: Interaction) => Promise<void>) {\n this.removeListener(allEventTypes.gatewayMessage, listener);\n }\n\n public gatewayOnTurnComplete(listener: (interactionId: string, interaction: Interaction) => Promise<void>) {\n this.addListener(allEventTypes.gatewayTurnComplete, listener);\n }\n\n public gatewayEmitTurnComplete(interactionId: string, agentInteraction: Interaction) {\n this.callListeners(allEventTypes.gatewayTurnComplete, interactionId, agentInteraction);\n }\n\n public gatewayOffTurnComplete(listener: (interactionId: string, interaction: Interaction) => Promise<void>) {\n this.removeListener(allEventTypes.gatewayTurnComplete, listener);\n }\n\n public gatewayOnTurnOpen(listener: (interactionId: string) => Promise<void>) {\n this.addListener(allEventTypes.gatewayTurnOpen, listener);\n }\n\n public gatewayEmitTurnOpen(interactionId: string) {\n this.callListeners(allEventTypes.gatewayTurnOpen, interactionId);\n }\n\n public gatewayOffTurnOpen(listener: (interactionId: string) => Promise<void>) {\n this.removeListener(allEventTypes.gatewayTurnOpen, listener);\n }\n\n public gatewayOnStreamError(listener: (errorMessage: string) => Promise<void>) {\n this.addListener(allEventTypes.gatewayStreamError, listener);\n }\n\n public gatewayEmitStreamError(errorMessage: string) {\n this.callListeners(allEventTypes.gatewayStreamError, errorMessage);\n }\n\n public gatewayOffStreamError(listener: (errorMessage: string) => Promise<void>) {\n this.removeListener(allEventTypes.gatewayStreamError, listener);\n }\n\n /** The live socket is up and the session proven — on the first open and on every reconnect (`info.reconnect`). */\n public gatewayOnConnected(listener: (sessionId: string, info: { reconnect: boolean }) => Promise<void>) {\n this.addListener(allEventTypes.gatewayConnected, listener);\n }\n\n public gatewayEmitConnected(sessionId: string, info: { reconnect: boolean }) {\n this.callListeners(allEventTypes.gatewayConnected, sessionId, info);\n }\n\n public gatewayOffConnected(listener: (sessionId: string, info: { reconnect: boolean }) => Promise<void>) {\n this.removeListener(allEventTypes.gatewayConnected, listener);\n }\n\n public chatOnMessageSent(listener: (message: string, interaction: Interaction) => Promise<void>) {\n this.addListener(allEventTypes.onMessageSent, listener);\n }\n\n public chatOffMessageSent(listener: (...args: any[]) => Promise<void>) {\n this.removeListener(allEventTypes.onMessageSent, listener);\n }\n\n public ChatEmitMessageSent(message: string, interaction: Interaction) {\n this.callListeners(allEventTypes.onMessageSent, message, interaction);\n }\n\n public chatOnMessageError(listener: (error: string) => Promise<void>) {\n this.addListener(allEventTypes.onMessageError, listener);\n }\n\n public chatOffMessageError(listener: (...args: any[]) => Promise<void>) {\n this.removeListener(allEventTypes.onMessageError, listener);\n }\n\n public ChatEmitMessageError(error: string) {\n this.callListeners(allEventTypes.onMessageError, error);\n }\n\n public gatewayOnFunctionResponse(listener: (functionDetails: FunctionDetails) => Promise<void>) {\n this.addListener(allEventTypes.gatewayFunctionResponse, listener);\n }\n\n public gatewayEmitFunctionResponse(functionDetails: FunctionDetails) {\n this.callListeners(allEventTypes.gatewayFunctionResponse, functionDetails);\n }\n\n public gatewayOffFunctionResponse(listener: (functionDetails: FunctionDetails) => Promise<void>) {\n this.removeListener(allEventTypes.gatewayFunctionResponse, listener);\n }\n\n // \"Re-ask this\" — a `#ask-…` link in the transcript, carrying the link's TEXT as the question.\n // An event rather than component state because the prompt that must send it is not always\n // ChatPane's own: a host that passes `hidePromptInput` mounts its own `PromptV2` elsewhere in\n // its tree, and that instance cannot see ChatPane's `useState`. Whichever prompt is mounted\n // listens; ChatPane publishes only when its internal one is suppressed, so the question is\n // never sent twice.\n public uiOnAskQuestion(listener: (question: string) => Promise<void>) {\n this.addListener(allEventTypes.uiAskQuestion, listener);\n }\n\n public uiEmitAskQuestion(question: string) {\n this.callListeners(allEventTypes.uiAskQuestion, question);\n }\n\n public uiOffAskQuestion(listener: (question: string) => Promise<void>) {\n this.removeListener(allEventTypes.uiAskQuestion, listener);\n }\n\n public gatewayOnEndMessageData(listener: (data: EndMessageData) => Promise<void>) {\n this.addListener(allEventTypes.gatewayEndMessageData, listener);\n }\n\n public gatewayEmitEndMessageData(data: EndMessageData) {\n this.callListeners(allEventTypes.gatewayEndMessageData, data);\n }\n\n public gatewayOffEndMessageData(listener: (data: EndMessageData) => Promise<void>) {\n this.removeListener(allEventTypes.gatewayEndMessageData, listener);\n }\n\n public gatewayOnToolEvent(listener: (eventName: string, eventData: string, sessionId?: string) => Promise<void>) {\n this.addListener(allEventTypes.onToolEvent, listener);\n }\n\n public gatewayEmitToolEvent(eventName: string, eventData: string, sessionId?: string) {\n this.callListeners(allEventTypes.onToolEvent, eventName, eventData, sessionId);\n }\n\n public gatewayOffToolEvent(listener: (eventName: string, eventData: string, sessionId?: string) => Promise<void>) {\n this.removeListener(allEventTypes.onToolEvent, listener);\n }\n\n public gatewayOnFirstToken(listener: (details: FirstTokenEventDetails) => Promise<void>) {\n this.addListener(allEventTypes.gatewayFirstToken, listener);\n }\n\n public gatewayEmitFirstToken(details: FirstTokenEventDetails) {\n this.callListeners(allEventTypes.gatewayFirstToken, details);\n }\n\n public gatewayOffFirstToken(listener: (details: FirstTokenEventDetails) => Promise<void>) {\n this.removeListener(allEventTypes.gatewayFirstToken, listener);\n }\n\n}\n","import type { Artifact } from '@lib/models/Artifact';\nimport type { Interaction } from '../../models/Interaction';\nimport { type InteractionPart, InteractionPartUtils } from '../../models/InteractionPart';\nimport type { FunctionDetails, ServerEvent } from '../../models/ServerEvent';\nimport type { LlmArtifact } from '../../models/semanticKernelModel/models';\nimport { EventType } from '../../models/enums';\n\n/**\n * The cap on one text / thought part. The markdown renderer re-parses the LIVE\n * part's whole text on every tick, so the cost per tick is proportional to this,\n * not to the answer's length. A settled part is never re-parsed: it keeps its\n * object identity across reductions (see `appendText`), so `MessagePart`'s memo\n * holds for it.\n *\n * Soft: the check runs BEFORE a delta is appended, so a part ends up in\n * (cap, cap + one delta]. Since SDK v0.18 the server coalesces deltas into\n * ~50 ms / 4096-char frames, so a single delta can be larger than the cap.\n */\nexport const MAX_CHAR_PER_TEXT_PART = 2000;\n\nexport interface ReduceEffects {\n /** Called once per reduction that settles a tool RESULT onto its call (the fold). */\n onFunctionResponse?: (functionDetails: FunctionDetails) => void;\n}\n\n/**\n * Copy-on-write scratch state for one reduction. `parts` and `functionMap` start\n * as the previous tree's references and are copied the first time a step needs\n * to write — so a reduction that only appends to the live tail copies the array\n * once and touches no settled part.\n */\ninterface Draft {\n readonly prev: Interaction;\n parts: InteractionPart[];\n functionMap: Map<string, InteractionPart>;\n}\n\nfunction ownParts(d: Draft): void {\n if (d.parts === d.prev.parts) d.parts = d.prev.parts.slice();\n}\n\nfunction ownFunctionMap(d: Draft): void {\n if (d.functionMap === d.prev.functionMap) d.functionMap = new Map(d.functionMap);\n}\n\nconst isFunctionCall = (t: EventType): boolean => t == EventType.FunctionCall || t == EventType.PartialFunctionCall;\nconst isFunctionResponse = (t: EventType): boolean => t == EventType.FunctionResponse;\n\nconst nextPartId = (d: Draft): string => (d.parts.length + 1) + \"-\" + d.prev.interactionId;\n\n/**\n * Whether the incoming part opens a NEW part or lands on the last one.\n *\n * `mustPush` / `textAppendable` are client-side classifications made in\n * `InteractionPartUtils.FlatParts` (the server has no such concept): text,\n * thought and streamed-argument deltas append; everything else pushes. A delta\n * also pushes when its kind or its call id differs from the last part's — and\n * when the last part has already grown past the cap.\n */\nfunction opensNewPart(incoming: InteractionPart, last: InteractionPart | null): boolean {\n if (!last) return true;\n if (incoming.mustPush) return true;\n if (incoming.mustPush === false\n && (incoming.eventType !== last.eventType || incoming.functionDetails?.id !== last.functionDetails?.id)) {\n return true;\n }\n if (incoming.textAppendable) {\n const length = last.thoughtDetails?.text?.length ?? last.text?.length ?? 0;\n if (length > MAX_CHAR_PER_TEXT_PART) return true;\n }\n return false;\n}\n\n/**\n * Prefill fold (issue #60): a StreamingClientOutputContent pushed WHILE an ask-user tool is parked.\n * Seed clientOutput onto the parked call by callId WITHOUT closing it (no status change) — never a\n * standalone part. Independent of the push decision, so it always folds.\n */\nfunction foldClientOutput(d: Draft, incoming: InteractionPart): void {\n const callId = incoming.functionDetails!.id!;\n const clientOutput = incoming.functionDetails!.clientOutput;\n const currentIdx = d.parts.findIndex(p => p.functionDetails?.id === callId);\n if (currentIdx > -1) {\n const current = d.parts[currentIdx];\n const merged: InteractionPart = {\n ...current,\n functionDetails: {\n ...current.functionDetails!,\n clientOutput: clientOutput ?? current.functionDetails!.clientOutput,\n // Sticky true-wins: this event IS the park, and a later merge must not clear it.\n parked: incoming.functionDetails!.parked === true || current.functionDetails!.parked === true,\n },\n };\n ownParts(d);\n d.parts[currentIdx] = merged;\n ownFunctionMap(d);\n d.functionMap.set(callId, merged);\n }\n else {\n // The prefill beat its call event (rare ordering race). Stash a silent placeholder so the\n // later call fold finds it, seeds clientOutput, and renders normally.\n const placeholder: InteractionPart = {\n ...incoming,\n id: nextPartId(d),\n functionDetails: { ...incoming.functionDetails!, silent: true },\n };\n ownParts(d);\n d.parts.push(placeholder);\n ownFunctionMap(d);\n d.functionMap.set(callId, placeholder);\n }\n}\n\n/**\n * A call event whose id is already known folds onto the call's CURRENT part: the\n * settled call onto its streamed arguments, the result onto the call. The\n * presentation flags are sticky (true wins) because a UI call has several reps\n * (the streaming part with isUi, the settled call, the result) and they\n * interleave — `??` let a later rep clobber an earlier `true`.\n */\nfunction foldFunctionEvent(d: Draft, incoming: InteractionPart, existing: InteractionPart, callId: string, effects?: ReduceEffects): void {\n // Find the *current* state of this call in the draft — `appendText` accumulates streamed\n // arguments into a new clone each tick, but functionMap only remembers the version stored at\n // push time. Spread from `current` (live state) rather than `existing` (push-time snapshot) so\n // the computed part.id (the \"N-interactionId\" stamp React keys on) survives.\n const currentIdx = d.parts.findIndex(p => p.functionDetails?.id === callId);\n const current = currentIdx > -1 ? d.parts[currentIdx] : existing;\n const fd = incoming.functionDetails!;\n const cur = current.functionDetails!;\n\n const merged: InteractionPart = {\n ...current,\n eventType: incoming.eventType,\n functionDetails: {\n id: cur.id,\n name: fd.name ?? cur.name,\n // The settled FunctionCall carries the parsed args; the PartialFunctionCall stream it\n // folds onto only accumulated raw JSON in `.text`.\n args: fd.args ?? cur.args,\n response: fd.response,\n status: fd.status ?? 'Composing',\n start: fd.start ?? cur.start,\n end: fd.end ?? cur.end,\n isUi: fd.isUi === true || cur.isUi === true,\n // Keep the call's friendly args summary when the result event (which has none) folds in.\n argsDescription: fd.argsDescription ?? cur.argsDescription,\n // The tool's client-only payload rides the RESULT event; sticky so a later rep without\n // one can't clobber it. This is what a uiTool renderer reads.\n clientOutput: fd.clientOutput ?? cur.clientOutput,\n // Ask-user component ([KernelUIComponent]) — sticky like isUi/clientOutput. The streaming\n // final CALL carries it, the PartialFunctionCall it folds onto may not (issue #60).\n askUserComponent: fd.askUserComponent ?? cur.askUserComponent,\n isAskUser: fd.isAskUser || cur.isAskUser || !!(fd.askUserComponent ?? cur.askUserComponent),\n // Runtime \"don't render\" override rides the RESULT; sticky so it survives the fold.\n cancelUi: fd.cancelUi === true || cur.cancelUi === true,\n parked: fd.parked === true || cur.parked === true,\n },\n };\n\n ownFunctionMap(d);\n d.functionMap.set(callId, merged);\n\n if (merged.eventType === EventType.FunctionResponse) {\n effects?.onFunctionResponse?.(merged.functionDetails!);\n }\n\n if (currentIdx > -1) {\n ownParts(d);\n d.parts[currentIdx] = merged;\n }\n}\n\n/**\n * A part seen for the first time. A function call registers in functionMap so its\n * later reps fold; the previous live part, if text-appendable, is closed with an\n * `ended` stamp (on a CLONE — the previous tree's part stays untouched).\n */\nfunction openPart(d: Draft, incoming: InteractionPart, serverEvent: ServerEvent, callId: string | undefined): void {\n if (callId && incoming.functionDetails) {\n ownFunctionMap(d);\n d.functionMap.set(callId, incoming);\n }\n\n const last = d.prev.parts[d.prev.parts.length - 1] ?? null;\n if (last && last.textAppendable) {\n ownParts(d);\n d.parts[d.parts.length - 1] = { ...last, ended: new Date() };\n }\n\n const newPart: InteractionPart = {\n ...incoming,\n id: nextPartId(d),\n partial: serverEvent.partial,\n };\n d.parts = [...d.parts, newPart];\n}\n\n/**\n * Text append into the live tail. A partial delta is concatenated; a non-partial\n * event REPLACES the text (the rare whole-text event). Only the tail is cloned —\n * the settled parts before it keep their identity.\n *\n * `justPushedNew`: the part `openPart` just added is a COPY of the incoming part,\n * so it already carries this chunk in `text` and `thoughtDetails.text`; appending\n * again would double-count it (which it did: a 9k stream accumulated 14k).\n */\nfunction appendText(d: Draft, incoming: InteractionPart, serverEvent: ServerEvent, justPushedNew: boolean): void {\n const last = d.parts[d.parts.length - 1] ?? null;\n if (!last) return;\n\n const updated: InteractionPart = {\n ...last,\n partial: serverEvent.partial,\n textDetails: last.textDetails ? { ...last.textDetails } : { version: 0 },\n };\n\n if (serverEvent.partial) {\n updated.textDetails!.version++;\n if (!justPushedNew) {\n updated.text = (last.text ?? \"\") + (incoming.text ?? \"\");\n }\n if (!justPushedNew && incoming.thoughtDetails && updated.thoughtDetails) {\n // The `< 50` clause skips a short chunk equal to the whole accumulated thought — a\n // leftover from the double-count era that no streaming connector can trigger.\n // Kept until a test of its own says it can go.\n const chunk = incoming.thoughtDetails.text;\n if (chunk.length >= 50 || (chunk.length < 50 && chunk !== updated.thoughtDetails.text)) {\n updated.thoughtDetails = { ...updated.thoughtDetails, text: updated.thoughtDetails.text + chunk };\n }\n }\n }\n else {\n updated.text = incoming.text ?? \"\";\n updated.textDetails!.version++;\n if (incoming.thoughtDetails) {\n updated.thoughtDetails = { ...incoming.thoughtDetails, text: incoming.thoughtDetails.text.trim() };\n }\n }\n\n ownParts(d);\n d.parts[d.parts.length - 1] = updated;\n}\n\n/** Artifacts merge onto a copy-on-write array: same id replaces, new id appends. */\nfunction mergeArtifacts(prev: Artifact[], incoming: LlmArtifact[] | undefined): Artifact[] {\n if (!incoming || incoming.length === 0) return prev;\n const next = prev.slice();\n for (const llmArtifact of incoming) {\n const artifact = llmArtifact.toArtifact();\n const index = next.findIndex(a => a.id === artifact.id);\n if (index === -1) next.push(artifact);\n else next[index] = artifact;\n }\n return next;\n}\n\n/**\n * The next interaction after one server event. Pure with respect to `prev`: no\n * part or array on the prior tree is mutated, and every part the event did not\n * touch keeps its object identity in the result.\n *\n * Steps, in order: flatten the event to one part; decide push-or-append; fold a\n * parked prefill, fold a known call, or open a new part; append text to the live\n * tail; merge artifacts; assemble.\n */\nexport function reduceInteraction(prev: Interaction, serverEvent: ServerEvent, effects?: ReduceEffects): Interaction {\n const incoming = InteractionPartUtils.FlatParts(serverEvent?.parts);\n const last = prev.parts[prev.parts.length - 1] ?? null;\n\n const d: Draft = {\n prev,\n parts: prev.parts,\n functionMap: prev.functionMap ?? new Map<string, InteractionPart>(),\n };\n\n let justPushedNew = false;\n if (incoming) {\n const isClientOutputFold = incoming.eventType === EventType.FunctionClientOutput && !!incoming.functionDetails?.id;\n\n if (isClientOutputFold) {\n foldClientOutput(d, incoming);\n }\n else if (opensNewPart(incoming, last)) {\n const isFn = isFunctionCall(incoming.eventType) || isFunctionResponse(incoming.eventType);\n const callId = isFn ? incoming.functionDetails?.id : undefined;\n if (isFn && !callId) {\n console.error(\"Got isCall or isResponse without a callId\", incoming);\n }\n const existing = callId ? d.functionMap.get(callId) : undefined;\n\n if (existing && callId && incoming.functionDetails) {\n foldFunctionEvent(d, incoming, existing, callId, effects);\n }\n else {\n openPart(d, incoming, serverEvent, callId);\n justPushedNew = true;\n }\n }\n\n if (incoming.textAppendable) {\n appendText(d, incoming, serverEvent, justPushedNew);\n }\n }\n\n return {\n ...prev,\n version: prev.version + 1,\n parts: d.parts,\n artifactData: mergeArtifacts(prev.artifactData ?? [], serverEvent.llmArtifacts),\n functionMap: d.functionMap,\n turn_complete: serverEvent.turn_complete,\n partial: serverEvent.partial,\n asyncFinalResponse: serverEvent.asyncFinalResponse,\n agent: serverEvent.agent ?? prev.agent,\n };\n}\n","import { type Interaction } from \"../models/Interaction\";\nimport { type ServerEvent } from \"../models/ServerEvent\";\nimport { EventBusService } from \"./eventBusService\";\nimport { reduceInteraction } from \"./interaction/reduceInteraction\";\n\nexport { MAX_CHAR_PER_TEXT_PART, reduceInteraction } from \"./interaction/reduceInteraction\";\nexport type { ReduceEffects } from \"./interaction/reduceInteraction\";\n\n/**\n * The stateful face of {@link reduceInteraction}: holds the current tree for one\n * interaction and swaps it atomically after each event. Hosts drive the merge\n * through this (obtapp's part-stability tests do), so the constructor and\n * `merge` are a published contract; the logic lives in the reducer.\n */\nexport class InteractionService {\n interaction: Interaction;\n eventBusService: EventBusService;\n\n constructor(interaction: Interaction, eventBusService: EventBusService) {\n this.interaction = interaction;\n this.eventBusService = eventBusService;\n }\n\n /**\n * Computes the next interaction from a server event and makes it current.\n * Pure with respect to the previous tree: snapshots already handed out to\n * throttled subscribers cannot diverge from live state.\n */\n public merge(serverEvent: ServerEvent): Interaction {\n const next = reduceInteraction(this.interaction, serverEvent, {\n onFunctionResponse: (fd) => this.eventBusService.gatewayEmitFunctionResponse(fd),\n });\n this.interaction = next;\n return next;\n }\n}\n","/**\n * WebSocket close codes with a meaning in this protocol. The 4xxx range is application-defined;\n * the server (AIA-AgentsSdk, `SocketController` / `InteractionRunRegistry`) sends 4002 and 4003,\n * the client sends 4001 and reports 4100 to itself. 4004 is reserved for the server's \"session\n * not found\" verdict (not emitted yet — today an unknown session closes with 1001 after the\n * upgrade); the client already treats it as final.\n */\n\n/** Our own intentional disconnect. Never retried, never reported as a drop. */\nexport const APPLICATION_CLOSED_CODE = 4001;\n/**\n * The server rejected a duplicate attachment for the same session (single-attach policy): the user\n * already has another socket on it — usually another browser tab. Retrying just bounces, so the\n * supervisor halts and the host tells the user.\n */\nexport const SESSION_ALREADY_ATTACHED_CODE = 4002;\n/** The server closed an idle session (\"reconnect on next interaction\"). Resuming is cheap and lossless. */\nexport const SERVER_IDLE_CLOSE_CODE = 4003;\n/** The server no longer has this session. Final: a redial would only create a new conversation. */\nexport const SESSION_NOT_FOUND_CODE = 4004;\n/**\n * Client-local: the heartbeat declared the peer dead. Never goes on the wire (nobody is left to\n * receive it); reaches `onClose` so the supervisor can tell a detected dead peer from a server close.\n */\nexport const HEARTBEAT_TIMEOUT_CODE = 4100;\n","import { ConnectionState } from \"@lib/models/connectionState\";\nimport type { AiChatState, AiChatStore } from \"@lib/components/AiChat/stateConfiguration\";\nimport { APPLICATION_CLOSED_CODE, SESSION_ALREADY_ATTACHED_CODE, SESSION_NOT_FOUND_CODE } from \"../WebSocketConnection/closeCodes\";\n\n/**\n * The ONE owner of the live connection's lifecycle.\n *\n * Until 2026-10-07 two loops shared this job: the transport redialled a dropped socket twice\n * on its own (500 ms, 1 s), then \"handed off\" to `SessionStateManagerService`, whose 2 s\n * heartbeat redialled on a slower curve, closed idle sessions and wrote the store. The seam\n * between them is where every reconnect bug lived — budgets reset by an upgrade that was not a\n * connection, an outer redial buying two inner ones, two timers tearing down each other's\n * sockets. Now the transport dials once and reports how it ended; this class decides what\n * happens next.\n *\n * What it owns:\n * - dialling (one in flight at a time) and the resume cursor (every redial of a known session\n * asks the transport to keep it, so the server replays what was missed);\n * - ONE backoff curve for every failure, server down or session dropped alike;\n * - the close-code policy (see {@link ConnectionSupervisor.transportClosed});\n * - the idle close: the store's `lastActivity` is fed by human input and by sends, a streaming\n * turn refreshes it, and {@link IDLE_TIMEOUT} without it closes the socket until activity\n * returns;\n * - every `connectionStatus` write to the store.\n *\n * What it refuses to do: swap a session. A target with a session id is that session; if the\n * server answers a dial with another id, or says the session is gone, the supervisor halts and\n * tells the host instead of quietly starting a new conversation. Only a dial with NO id starts\n * fresh, and from its first success on, that id is the target too.\n */\n\n/** First retry delay. The curve is w ← min(⌊w + w²/BASE⌋, MAX): 500, 750, 1312, 3033, 12232, 20000, 20000… */\nexport const RETRY_INITIAL_WAIT_MS = 500;\nexport const RETRY_MAX_WAIT_MS = 20_000;\nexport const RETRY_BASE_MULTIPLIER = 1000;\n/** ±20 % on every retry delay, so a server restart does not get every tab back at the same millisecond. */\nexport const RETRY_JITTER = 0.2;\n\nexport const IDLE_TIMEOUT = 5 * 60 * 1000;\n/** The fraction of {@link IDLE_TIMEOUT} after which the UI shows the countdown (and the console says so once). */\nexport const WARNING_THRESHOLD = 0.75;\nexport const IDLE_TICK_MS = 2000;\n\n/** Why the supervisor stopped retrying on its own. An explicit `open()` clears it. */\nexport type HaltReason =\n /** 4002 — another socket (a second tab, usually) holds this session. Retrying would only bounce. */\n | 'attached-elsewhere'\n /** The server closed with 4004, or answered a dial for session A with session B: A is gone. */\n | 'session-gone'\n /** 1000 / 1008 — the server ended the conversation on purpose, or rejected our credentials. */\n | 'closed-by-server';\n\nexport interface ConnectionTarget {\n /** The session to be on. Undefined only until the first fresh dial succeeds. */\n sessionId?: string;\n /**\n * Whether the NEXT dial keeps the transport's replay cursor. Set by the caller for the first\n * dial (a host returning to the foreground), always true for the supervisor's own redials.\n */\n resume: boolean;\n /**\n * Something to do before each dial attempt until one succeeds — the session manager loads the\n * session record here, so a REST failure is retried on the same curve as a socket failure and a\n * late success still binds the record. Dropped after the first success: later redials resume\n * the socket, the record is already there.\n */\n prepare?: () => Promise<void>;\n}\n\nexport interface OpenOptions {\n resume?: boolean;\n prepare?: () => Promise<void>;\n}\n\nexport interface ConnectionSupervisorPorts {\n /** Dial once. Resolves with the session id the server answered with; rejects when the socket died first. */\n dial: (sessionId: string | undefined, options: { resume: boolean }) => Promise<string>;\n /** Close the socket we hold. Idempotent; the transport reports the close as {@link APPLICATION_CLOSED_CODE}. */\n hangUp: () => void;\n /**\n * The transport's own word on whether the socket is OPEN. The store says what the supervisor\n * last wrote; a socket that died without a close event yet (an idle close the store has not\n * caught up with, a dead peer the heartbeat is still timing) is what this catches.\n */\n isConnected?: () => boolean;\n store: AiChatStore;\n /** The socket is up and the session proven. `reconnect` is true for every success after the first. */\n onConnected?: (sessionId: string, info: { reconnect: boolean }) => void;\n /**\n * A redial was scheduled `delayMs` from now — the moment the UI can say \"reconnecting in N s\".\n * `attempt` counts consecutive failures since the last proven connection (1 = first redial).\n */\n onRetryScheduled?: (info: { sessionId?: string; delayMs: number; attempt: number }) => void;\n /** The supervisor gave up on its own; the host decides what to tell the user. */\n onHalt?: (reason: HaltReason, info: { sessionId?: string; code?: number; actualSessionId?: string }) => void;\n /** For tests. Defaults to `Date.now`. */\n now?: () => number;\n}\n\nconst LOG = '[Connection]';\n\nexport class ConnectionSupervisor {\n private readonly ports: ConnectionSupervisorPorts;\n private state: AiChatState;\n private readonly now: () => number;\n\n private target: ConnectionTarget | null = null;\n private inflight: Promise<string> | null = null;\n private retryTimer: ReturnType<typeof setTimeout> | null = null;\n private idleTimer: ReturnType<typeof setInterval> | null = null;\n private wait = RETRY_INITIAL_WAIT_MS;\n /** Consecutive failed attempts since the last proven connection. */\n private attempt = 0;\n private halted: HaltReason | null = null;\n /** The code of the last close the transport reported, consumed by the next dial failure. */\n private lastCloseCode: number | null = null;\n private everConnected = false;\n private idleWarningLogged = false;\n\n constructor(ports: ConnectionSupervisorPorts) {\n this.ports = ports;\n this.now = ports.now ?? (() => Date.now());\n this.state = ports.store.getState();\n ports.store.subscribe((state) => { this.state = state; });\n }\n\n // ─── Queries ────────────────────────────────────────────────────────────\n\n get sessionId(): string | undefined { return this.target?.sessionId; }\n get isSupervising(): boolean { return this.target !== null; }\n get haltReason(): HaltReason | null { return this.halted; }\n /** The delay the NEXT failure would wait. Exposed for tests and the console. */\n get nextWaitMs(): number { return this.wait; }\n get retryScheduled(): boolean { return this.retryTimer !== null; }\n /** Connected by the store AND by the transport. */\n private get isUp(): boolean {\n return this.state.connectionStatus === ConnectionState.Connected && (this.ports.isConnected?.() ?? true);\n }\n\n // ─── Commands ───────────────────────────────────────────────────────────\n\n /**\n * Be on `sessionId` (or on a fresh session when undefined). Resolves with the session id once\n * the first attempt succeeds, rejects when it fails — and keeps retrying in the background\n * either way, until {@link close} or a halt. Calling it for the session already targeted\n * joins the dial in flight or returns the open socket's id; calling it for a different session\n * hangs up the current one first.\n */\n open(sessionId?: string, options?: OpenOptions): Promise<string> {\n if (this.target && this.sameTarget(sessionId)) {\n if (this.inflight) return this.inflight;\n if (this.isUp && this.target.sessionId && !this.halted)\n return Promise.resolve(this.target.sessionId);\n } else if (this.target) {\n console.log(`${LOG} switching from session ${this.target.sessionId ?? '(new)'} to ${sessionId ?? '(new)'}.`);\n this.close();\n }\n\n this.halted = null;\n this.cancelRetry();\n this.target = { sessionId, resume: options?.resume === true, prepare: options?.prepare };\n this.startIdleTick();\n return this.dial();\n }\n\n /**\n * The send guard: make sure the socket is up before a frame goes out, dialling NOW (not at\n * the next scheduled retry) when it is not. `fallbackSessionId` is what to dial when nothing\n * was ever opened through here (a host that set the session on the gateway directly).\n */\n async ensure(fallbackSessionId?: string): Promise<string> {\n if (this.halted) {\n throw new Error(`The connection was halted (${this.halted}); session ${this.target?.sessionId ?? fallbackSessionId ?? 'none'} cannot be redialled.`);\n }\n if (!this.target) {\n console.warn(`${LOG} send guard: nothing supervised yet — opening session ${fallbackSessionId ?? '(new)'} with the replay cursor.`);\n return this.open(fallbackSessionId, { resume: true });\n }\n if (this.inflight) return this.inflight;\n if (this.isUp && this.target.sessionId)\n return this.target.sessionId;\n console.warn(`${LOG} send guard: socket is DOWN at send time (session ${this.target.sessionId ?? '(new)'}, ` +\n `status ${this.state.connectionStatus}) — redialling now instead of in ${this.wait}ms.`);\n this.cancelRetry();\n this.target.resume = true;\n return this.dial();\n }\n\n /** Stop supervising: hang up, cancel any retry, stop the idle tick. Never throws. */\n close(): void {\n const had = this.target;\n this.target = null;\n this.halted = null;\n this.cancelRetry();\n this.stopIdleTick();\n this.wait = RETRY_INITIAL_WAIT_MS;\n this.attempt = 0;\n try { this.ports.hangUp(); } catch (error) { console.error(`${LOG} hangUp threw`, error); }\n if (had) this.state.setConnectionStatus(ConnectionState.Disconnected);\n }\n\n // ─── Transport reports ──────────────────────────────────────────────────\n\n /**\n * The transport's socket closed. The code is the policy input:\n * - 4001: our own hang-up, nothing to do.\n * - 4002: attached elsewhere — halt, never bounce the other tab.\n * - 4004: the server no longer has the session — halt, the host tells the user.\n * - 1000 / 1008: closed on purpose / credentials rejected — halt.\n * - anything else (1001 going away, 1006 abnormal, 1011–1013 server trouble, 4003 the server's\n * idle close, 4100 our heartbeat's dead-peer verdict): retry on the curve, cursor kept.\n * A close that lands while a dial is in flight is remembered and judged when that dial fails.\n */\n transportClosed(code: number, reason: string): void {\n if (code === APPLICATION_CLOSED_CODE) return;\n this.lastCloseCode = code;\n if (!this.target) return;\n if (this.inflight) {\n console.log(`${LOG} socket closed (code=${code}) while a dial is in flight — judged when it settles.`);\n return;\n }\n if (this.state.connectionStatus !== ConnectionState.Connected) return;\n\n console.warn(`${LOG} socket closed: code=${code} reason=\"${reason}\" (session ${this.target.sessionId ?? '(new)'}).`);\n this.state.setConnectionStatus(ConnectionState.Disconnected);\n this.judge(code);\n }\n\n // ─── The dial ───────────────────────────────────────────────────────────\n\n private dial(): Promise<string> {\n const target = this.target!;\n this.lastCloseCode = null;\n this.state.setConnectionStatus(ConnectionState.Connecting);\n const startedAt = this.now();\n console.log(`${LOG} dialling session ${target.sessionId ?? '(new)'}` +\n `${target.resume ? ' with the replay cursor' : ''}` +\n `${this.everConnected ? ' (reconnect)' : ''}.`);\n\n const attempt = (async () => {\n if (target.prepare) await target.prepare();\n return this.ports.dial(target.sessionId, { resume: target.resume });\n })();\n\n const settled: Promise<string> = attempt\n .then((actual) => {\n if (this.target !== target) {\n // close() or a switch happened mid-dial: the socket we got is not wanted.\n console.log(`${LOG} a dial for ${target.sessionId ?? '(new)'} resolved after it was abandoned — hanging up.`);\n try { this.ports.hangUp(); } catch { /* already down */ }\n throw new Error('Connection attempt abandoned');\n }\n if (target.sessionId && actual !== target.sessionId) {\n // The rule: a requested session is never swapped for another. The server\n // opened a different one, which means ours is gone.\n console.error(`${LOG} asked for session ${target.sessionId}, the server answered with ${actual} — ` +\n `refusing the swap and halting.`);\n try { this.ports.hangUp(); } catch { /* already down */ }\n this.state.setConnectionStatus(ConnectionState.Disconnected);\n this.halt('session-gone', { sessionId: target.sessionId, actualSessionId: actual });\n throw new Error(`Session ${target.sessionId} no longer exists on the server (it answered with ${actual}).`);\n }\n const reconnect = this.everConnected;\n this.everConnected = true;\n target.sessionId = actual;\n target.resume = true;\n target.prepare = undefined;\n this.wait = RETRY_INITIAL_WAIT_MS;\n this.attempt = 0;\n this.state.setConnectionStatus(ConnectionState.Connected);\n console.log(`${LOG} ${reconnect ? 'reconnected to' : 'connected to'} session ${actual} in ${this.now() - startedAt}ms.`);\n this.ports.onConnected?.(actual, { reconnect });\n return actual;\n })\n .catch((error) => {\n if (this.target === target && !this.halted) {\n const code = this.lastCloseCode;\n console.error(`${LOG} dial of session ${target.sessionId ?? '(new)'} failed after ${this.now() - startedAt}ms` +\n `${code !== null ? ` (socket closed with ${code})` : ''}:`, error);\n this.state.setConnectionStatus(ConnectionState.Disconnected);\n // This attempt is over before it is judged, or scheduleRetry would see it as\n // still running and stand down.\n if (this.inflight === settled) this.inflight = null;\n this.judge(code);\n }\n throw error;\n })\n .finally(() => {\n if (this.inflight === settled) this.inflight = null;\n });\n this.inflight = settled;\n return settled;\n }\n\n /** Apply the close-code policy to a failure: halt, or schedule the next attempt. */\n private judge(code: number | null): void {\n const sessionId = this.target?.sessionId;\n if (code === SESSION_ALREADY_ATTACHED_CODE) return this.halt('attached-elsewhere', { sessionId, code });\n if (code === SESSION_NOT_FOUND_CODE) return this.halt('session-gone', { sessionId, code });\n if (code === 1000 || code === 1008) return this.halt('closed-by-server', { sessionId, code });\n this.scheduleRetry();\n }\n\n private halt(reason: HaltReason, info: { sessionId?: string; code?: number; actualSessionId?: string }): void {\n this.halted = reason;\n this.cancelRetry();\n console.warn(`${LOG} halted (${reason}) on session ${info.sessionId ?? '(new)'}` +\n `${info.code !== undefined ? `, close code ${info.code}` : ''} — no automatic redial; an explicit open() may try again.`);\n try { this.ports.onHalt?.(reason, info); }\n catch (error) { console.error(`${LOG} onHalt threw`, error); }\n }\n\n private scheduleRetry(): void {\n if (!this.target || this.retryTimer || this.inflight) return;\n if (!this.state.sessionActive) {\n // Idle: nobody is here to want the socket. The idle tick redials when activity returns.\n console.log(`${LOG} session idle — not redialling until activity resumes.`);\n return;\n }\n const delay = this.jittered(this.wait);\n this.wait = Math.min(Math.floor(this.wait + (this.wait * this.wait) / RETRY_BASE_MULTIPLIER), RETRY_MAX_WAIT_MS);\n this.attempt += 1;\n console.warn(`${LOG} redialling session ${this.target.sessionId ?? '(new)'} in ${delay}ms (then ${this.wait}ms, attempt ${this.attempt}).`);\n try { this.ports.onRetryScheduled?.({ sessionId: this.target.sessionId, delayMs: delay, attempt: this.attempt }); }\n catch (error) { console.error(`${LOG} onRetryScheduled threw`, error); }\n this.retryTimer = setTimeout(() => {\n this.retryTimer = null;\n if (!this.target || this.halted) return;\n this.target.resume = true;\n this.dial().catch(() => { /* judged inside dial() */ });\n }, delay);\n }\n\n private cancelRetry(): void {\n if (this.retryTimer) {\n clearTimeout(this.retryTimer);\n this.retryTimer = null;\n }\n }\n\n private jittered(ms: number): number {\n return Math.max(0, Math.round(ms + ms * RETRY_JITTER * (Math.random() * 2 - 1)));\n }\n\n private sameTarget(sessionId?: string): boolean {\n // A fresh target that has not been answered yet matches another fresh request; a known\n // session matches only itself.\n return this.target?.sessionId === sessionId;\n }\n\n // ─── Idle ───────────────────────────────────────────────────────────────\n\n private startIdleTick(): void {\n if (this.idleTimer) return;\n this.idleTimer = setInterval(() => this.tick(), IDLE_TICK_MS);\n }\n\n private stopIdleTick(): void {\n if (this.idleTimer) {\n clearInterval(this.idleTimer);\n this.idleTimer = null;\n }\n }\n\n /**\n * One idle check. Public so a test can drive it without the interval.\n *\n * A STREAMING TURN IS ACTIVITY: `lastActivity` is otherwise fed only by human input and sends,\n * and surfaces without a ChatPane never register the listeners, so a long agent turn used to\n * cross the window mid-stream and get its socket closed under it. Refreshing the clock while\n * the turn is open mirrors the server's own live-activity exemption.\n */\n tick(): void {\n if (!this.target) return;\n if (this.state.turnOpen) this.state.setLastActivity();\n\n const idle = this.now() - this.state.lastActivity;\n if (idle > IDLE_TIMEOUT) {\n if (this.state.sessionActive) this.state.setIsSessionActive(false);\n this.cancelRetry();\n if (this.state.connectionStatus === ConnectionState.Connected) {\n console.warn(`${LOG} idle for ${Math.round(idle / 1000)}s (limit ${IDLE_TIMEOUT / 1000}s) — closing the socket ` +\n `(session ${this.target.sessionId ?? '(new)'}). Activity, or a send, redials it.`);\n try { this.ports.hangUp(); } catch (error) { console.error(`${LOG} hangUp threw`, error); }\n this.state.setConnectionStatus(ConnectionState.Disconnected);\n }\n return;\n }\n\n if (!this.state.sessionActive) {\n console.log(`${LOG} activity resumed — the session is active again.`);\n this.state.setIsSessionActive(true);\n this.wait = RETRY_INITIAL_WAIT_MS;\n if (this.state.connectionStatus === ConnectionState.Disconnected && !this.halted && !this.inflight) {\n this.target.resume = true;\n this.dial().catch(() => { /* judged inside dial() */ });\n }\n }\n\n if (idle > IDLE_TIMEOUT * WARNING_THRESHOLD) {\n if (!this.idleWarningLogged) {\n this.idleWarningLogged = true;\n console.warn(`${LOG} idle ${Math.round(idle / 1000)}s of ${IDLE_TIMEOUT / 1000}s — the socket closes in about ` +\n `${Math.round((IDLE_TIMEOUT - idle) / 1000)}s unless something happens.`);\n }\n } else {\n this.idleWarningLogged = false;\n }\n }\n}\n","/**\n * Coalesces a stream of cumulative snapshots down to a bounded cadence.\n *\n * Exists ONLY for the partial-streaming firehose: text and reasoning deltas\n * reach the gateway dozens of times per second, and every publish re-renders\n * the live message. A snapshot flagged `partial === false` — a settled tool\n * result, the turn-complete signal — is rare and terminal-ish, so it publishes\n * immediately and drops any trailing timer: each snapshot is cumulative, so\n * nothing is lost by skipping the ones in between.\n *\n * Deferring a non-partial publish is exactly what once let a stale trailing\n * timer land AFTER the turn was committed and draw the message twice (see\n * {@link cancelPending}).\n */\nexport class ThrottledEmitter<T extends { version: number; partial: boolean }> {\n private pending: T | null = null;\n private lastPublishedAt = 0;\n private trailing: ReturnType<typeof setTimeout> | null = null;\n\n constructor(private readonly options: {\n windowMs: number;\n publish: (snapshot: T) => void;\n /** The version subscribers already hold; a trailing publish must be strictly newer. */\n publishedVersion: () => number;\n }) {}\n\n emit(snapshot: T): void {\n const now = Date.now();\n const elapsed = now - this.lastPublishedAt;\n const immediately = snapshot.partial === false || elapsed >= this.options.windowMs;\n\n if (immediately) {\n this.clearTrailing();\n this.publish(snapshot, now);\n return;\n }\n\n this.pending = snapshot;\n this.clearTrailing();\n this.trailing = setTimeout(() => {\n this.trailing = null;\n // Strict `>` so we never re-publish a version the immediate path already flushed.\n if (this.pending && this.pending.version > this.options.publishedVersion()) {\n this.publish(this.pending, now);\n }\n }, this.options.windowMs * 2);\n }\n\n /**\n * Drop a trailing publish still queued. Call on turn commit: once the store\n * has moved the interaction into history and nulled the live message, a late\n * trailing publish would set it live again — the duplicated-bubble bug.\n */\n cancelPending(): void {\n this.clearTrailing();\n this.pending = null;\n }\n\n private publish(snapshot: T, at: number): void {\n this.lastPublishedAt = at;\n this.pending = null;\n this.options.publish(snapshot);\n }\n\n private clearTrailing(): void {\n if (this.trailing) {\n clearTimeout(this.trailing);\n this.trailing = null;\n }\n }\n}\n","import { ServerEvent, type ToolEventDetails } from '../../models/ServerEvent';\nimport type { User } from '../../models/contexts';\nimport type { AgentContext } from '../../models/contexts';\nimport type { Customer } from '../../models/Customer';\nimport { ClientMessage } from '../../models/ClientMessage';\nimport { toInteractionOrigin, type Interaction, type InteractionOrigin } from '../../models/Interaction';\nimport type { EventBusService } from \"../eventBusService\";\nimport { InteractionService } from \"../interactionService\";\nimport { InteractionPartUtils, type InteractionPart } from '../../models/InteractionPart';\nimport type { SendMessageResponse } from '../../models/SendMessageResponse'\nimport type { IArtifactService } from '../interfaces/artifactService';\nimport type { Artifact } from '@lib/models/Artifact';\nimport { format as formatDate } from 'date-fns';\nimport type { AiChatState, AiChatStore } from '@lib/components/AiChat/stateConfiguration';\nimport type { INotificationPort } from '@lib/interfaces/INotificationPort';\nimport type { NotificationKind } from '@lib/models/Notification';\nimport _ from 'lodash';\nimport type { IStorageService } from '../storageService';\nimport { PromptUtils } from '@lib/models';\nimport { ConnectionState } from '@lib/models/connectionState';\nimport { ConnectionSupervisor, type HaltReason, type OpenOptions } from './connectionSupervisor';\nimport { ChatAction, EventType } from '@lib/models/enums';\nimport type { InteractionStart, InteractionStatistics } from '@lib/models/semanticKernelModel/models';\nimport type { IWebSocketConnection } from '../WebSocketConnection/webSocketConnection';\nimport { ThrottledEmitter } from './throttledEmitter';\n\nexport interface GatewaySendMessageOptions {\n callId?: string;\n}\n\n/**\n * What {@link AgentGatewayWSAsync.announceDetachedRun} did: `sent` — on the socket now; `queued` — a turn is open in\n * this tab (or the socket is down), it goes out when the chat is idle and connected; `duplicate` — this tab already\n * asked for this run's settle.\n */\nexport type AnnounceDetachedRunResult = 'sent' | 'queued' | 'duplicate';\n\n/** Construction-time switches of {@link AgentGatewayWSAsync}. */\nexport interface AgentGatewayOptions {\n /**\n * The gateway shows ONE detached run's own session as its transcript (AIA Issue 1548, `DetachedRunTranscript`).\n * Every frame on a run's session carries `detachedRunId`, which normally routes it to the run's box\n * ({@link AgentGatewayWSAsync.handleDetachedRunEvent}) instead of the conversation; in this mode those frames ARE\n * the conversation, and are treated as ordinary transcript frames.\n */\n transcriptOfDetachedRun?: boolean;\n}\n\n/**\n * The agent gateway: owns the live session's interactions, turns server events\n * into interaction trees (through {@link InteractionService} and the reducer),\n * publishes the live message to the store at a bounded cadence, and sends the\n * user's turns over the socket.\n *\n * One class. It was an abstract base plus this subclass for an SSE transport\n * that no longer exists; `AgentGatewayService` still resolves to this class for\n * hosts and the context types.\n */\nexport class AgentGatewayWSAsync {\n base_url: string;\n\n msg_order = 0;\n\n protected interactionsMap: Map<string, Interaction> = new Map();\n protected interactionsServiceMap: Map<string, InteractionService> = new Map();\n\n protected user: User;\n protected config: AgentContext;\n\n protected currentIS: InteractionService | null = null;\n\n protected sessionState: AiChatState;\n protected storageService: IStorageService;\n protected notificationPort: INotificationPort\n protected interactionCallIds: Map<string, string> = new Map();\n /** Interactions whose turn was committed (turn-complete or a server error); a second close is ignored. */\n protected committedTurns: Set<string> = new Set();\n /** Interactions this tab sent. An `InteractionStarted` for one of them announces what is already here. */\n protected localInteractionIds: Set<string> = new Set();\n /**\n * Turns open right now, local and remote. `turnOpen` in the store is \"any of these\": a remote turn finishing\n * must not unlock the composer under a local turn still streaming, nor the other way round.\n */\n protected openTurns: Set<string> = new Set();\n protected readonly options: AgentGatewayOptions;\n /** Announcements asked for in this tab, by `runId|settleKey` — a second request for the same settle is a no-op. */\n protected announceRequested: Set<string> = new Set();\n /** Announcements waiting for the chat to be idle (no open turn) and connected, in request order. */\n protected pendingAnnouncements: string[] = [];\n private flushingAnnouncements = false;\n\n protected rawJwt: string;\n protected sessionId?: string;\n\n eventBusService: EventBusService;\n artifactService: IArtifactService;\n\n protected wsService: IWebSocketConnection;\n /** The one owner of dial / redial / idle close / connection status. See ConnectionSupervisor. */\n private readonly connection: ConnectionSupervisor;\n\n suspendState: boolean = false;\n\n /**\n * True once a WS has successfully opened at least once in this gateway's\n * lifetime. Gates the \"Reiniciando a conexão\" toast: a drop of a working\n * connection is worth telling the user about, a failed initial dial is not\n * (the Connecting state already covers it).\n */\n private everConnected: boolean = false;\n\n // How often the streaming message re-renders. 150 ms made a reasoning highlight, or a burst of them, visibly lag the\n // server (Ciro, 2026-10-07). The server already merges deltas over a 50 ms window (the SDK's DeltaCoalescer), so\n // frames arrive at ~20/s per kind and 20 ms here costs little: it mostly stops adding a second delay on top.\n private static readonly CURRENT_MSG_THROTTLE_MS = 20;\n\n /**\n * How long an open turn survives a connection outage. While the supervisor is redialling the\n * turn stays open — a short blip resumes it from the replay cursor, and a server that comes back\n * (or another instance) closes it with an error if its run is gone. Past this, nobody can tell\n * us anything, and a turn that is still open is a composer that is still locked: the client\n * closes it itself, with an error part, so the user can go on.\n */\n public static readonly OUTAGE_CLOSES_TURN_AFTER_MS = 60_000;\n public static readonly OUTAGE_TURN_MESSAGE = 'Sem conexão com o servidor há mais de um minuto. A resposta foi interrompida.';\n /** What a send reports when the socket could not be brought up for it. */\n public static readonly NO_CONNECTION_MESSAGE = 'Não foi possível obter conexão com o servidor';\n public static readonly HALT_TURN_MESSAGE: Record<HaltReason, string> = {\n 'attached-elsewhere': 'Esta sessão está aberta em outra janela. A resposta foi interrompida.',\n 'session-gone': 'A sessão não existe mais no servidor. A resposta foi interrompida.',\n 'closed-by-server': 'O servidor encerrou a conexão. A resposta foi interrompida.',\n };\n\n /** Publishes the live message to the store; see ThrottledEmitter for the cadence rules. */\n private readonly liveMessage = new ThrottledEmitter<Interaction>({\n windowMs: AgentGatewayWSAsync.CURRENT_MSG_THROTTLE_MS,\n publish: (message) => {\n this.sessionState.setCurrentMessage(message);\n this.eventBusService.gatewayEmitMessage(message);\n },\n publishedVersion: () => this.sessionState.currentMessage?.version ?? 0,\n });\n\n constructor(user: User, eventBusService: EventBusService, artifactService: IArtifactService, baseUrl: string, config: AgentContext, sessionStore: AiChatStore, notificationPort: INotificationPort, ws: IWebSocketConnection, storageService: IStorageService, sessionId?: string, options?: AgentGatewayOptions) {\n this.options = options ?? {};\n this.user = user;\n this.config = config;\n this.rawJwt = user.access_token;\n this.base_url = baseUrl\n this.eventBusService = eventBusService;\n this.sessionId = sessionId;\n this.artifactService = artifactService\n\n this.sessionState = sessionStore.getState();\n this.notificationPort = notificationPort;\n this.storageService = storageService;\n\n sessionStore.subscribe((state, prev) => {\n this.sessionState = state;\n // The chat went idle: a queued announcement may go now. Every path that closes the last open turn\n // (turn-complete, an error, suspend, a client-side close) lands here.\n if (prev.turnOpen && !state.turnOpen) void this.flushAnnouncements();\n })\n\n this.wsService = ws;\n this.connection = new ConnectionSupervisor({\n store: sessionStore,\n // A redial while a turn is open carries the turn's id: the server tells us if it cannot continue it.\n dial: (sessionId, options) => this.wsService.connect(sessionId, {\n ...options,\n openInteractionId: options.resume && this.sessionState.turnOpen ? this.getCurrentInteractionId() ?? undefined : undefined,\n }),\n hangUp: () => this.wsService.closeStream(),\n isConnected: () => this.wsService.isConnected(),\n onConnected: (sessionId, info) => {\n this.sessionId = sessionId;\n this.sessionState.setConnectionOutage(null);\n this.eventBusService.gatewayEmitConnected(sessionId, info);\n void this.flushAnnouncements();\n },\n onRetryScheduled: ({ delayMs, attempt }) => {\n const now = Date.now();\n const since = this.sessionState.connectionOutage?.since ?? now;\n this.sessionState.setConnectionOutage({ since, retryAt: now + delayMs, attempt, halted: null });\n if (now - since >= AgentGatewayWSAsync.OUTAGE_CLOSES_TURN_AFTER_MS)\n this.closeOpenTurnWith(AgentGatewayWSAsync.OUTAGE_TURN_MESSAGE);\n },\n onHalt: (reason, info) => {\n const outage = this.sessionState.connectionOutage;\n this.sessionState.setConnectionOutage({ since: outage?.since ?? Date.now(), retryAt: null, attempt: outage?.attempt ?? 0, halted: reason });\n this.notifyHalt(reason, info);\n // Nothing will ever continue this turn: close it now rather than after the timeout.\n this.closeOpenTurnWith(AgentGatewayWSAsync.HALT_TURN_MESSAGE[reason]);\n },\n });\n this.wsService.onEvent = async (event) => {\n await this.Message(event);\n };\n\n this.wsService.onInteractionStarted = (start) => {\n this.interactionStarted(start);\n };\n\n this.wsService.onNewPacket = (stats: InteractionStatistics) => {\n this.sessionState.setStatistics(stats);\n }\n\n this.wsService.onError = (error) => {\n console.error('Stream error:', error);\n\n // Only announce \"restarting the connection\" when a previously-working\n // connection dropped. During the initial dial (cold server, auth still\n // settling) every failed attempt fired this toast, spamming the user\n // while the Connecting state already communicates the wait.\n if (this.everConnected) {\n // A host's notification port is UI code; if it throws (seen: a notistack import\n // resolving to nothing in a host with two copies), the error must not escape a\n // socket callback — the stream-error signal below still has to go out.\n try {\n this.notificationPort.pushNotification({\n message: \"Reiniciando a conexão com o servidor\",\n type: 'info',\n // Tagged so a host can recognise this one and draw its own affordance (a progress bar glued\n // to the page, say) instead of a toast, without matching on the copy.\n kind: 'connection-restarting',\n });\n } catch (notifyError) {\n console.error('[AgentGateway] notification port threw on connection-restarting', notifyError);\n }\n }\n\n // Published on the bus, not written into the transcript. The transport's\n // onError fires for every socket blip, including the ones the reconnect loop\n // is about to recover from; the turn stays open and resumes. (The previous\n // code built a pseudo-event here that `Message` rejected for lacking a\n // mimeType, so nothing ever heard about these at all.)\n this.eventBusService.gatewayEmitStreamError(error);\n };\n\n this.wsService.onOpen = () => {\n // Status is the supervisor's to write (it resolves the dial); this only arms the\n // \"restarting\" toast for the next drop.\n this.everConnected = true;\n };\n\n this.wsService.onBillingLimit = (notice) => {\n sessionStore.getState().setBillingLimit(notice);\n };\n this.wsService.onFirstToken = (interactionId) => {\n this.localEmitFirstToken(interactionId);\n };\n\n this.wsService.onClose = (code, reason) => {\n this.connection.transportClosed(code, reason);\n };\n }\n\n /**\n * The turn the user is waiting on will not continue: close it from the client side with an error\n * part, the same way a server error would. No-op when no turn is open.\n */\n private closeOpenTurnWith(message: string): void {\n if (!this.sessionState.turnOpen) return;\n // Every open turn: a remote one streaming beside the local one is cut off by the same outage.\n const current = this.getCurrentInteractionId();\n const open = this.openTurns.size > 0 ? [...this.openTurns] : current ? [current] : [];\n for (const interactionId of open) {\n console.warn(`[AgentGateway] closing interaction ${interactionId} from the client side: ${message}`);\n void this.Message(ServerEvent.createErrorEvent(message, interactionId));\n }\n }\n\n /** The supervisor gave up on its own (another tab holds the session, the session is gone, …): tell the user. */\n private notifyHalt(reason: HaltReason, info: { sessionId?: string; code?: number; actualSessionId?: string }): void {\n const copy: Record<HaltReason, { message: string; kind: NotificationKind }> = {\n 'attached-elsewhere': { message: 'Esta sessão já está aberta em outra janela', kind: 'session-attached-elsewhere' },\n 'session-gone': { message: 'A sessão não existe mais no servidor', kind: 'session-gone' },\n 'closed-by-server': { message: 'O servidor encerrou a conexão', kind: 'connection-closed' },\n };\n const { message, kind } = copy[reason];\n try {\n this.notificationPort.pushNotification({\n message,\n type: 'warning',\n kind,\n details: `session ${info.sessionId ?? 'none'}${info.code !== undefined ? `, close code ${info.code}` : ''}` +\n `${info.actualSessionId ? `, server answered with ${info.actualSessionId}` : ''}`,\n });\n } catch (notifyError) {\n console.error(`[AgentGateway] notification port threw on ${kind}`, notifyError);\n }\n }\n\n // ─── Agent context ──────────────────────────────────────────────────────\n\n /**\n * The agent this gateway speaks to — the ONE truth for the conversation.\n * `sendMessageInternal` stamps every outbound frame's `AgentId` from it,\n * and the session manager binds/rebinds against it. Fixed at construction;\n * see {@link forceAgentContext} for the single exception (issue #59).\n */\n public getAgentContext(): AgentContext {\n return this.config;\n }\n\n public getModel(): string | undefined {\n return this.config.model;\n }\n\n public setModel(modelId: string): void {\n this.config = { ...this.config, model: modelId };\n }\n\n /**\n * Live update for the ordinary, non-identity slice of the context — the\n * dataset/customer the same agent works over. No \"force\" needed: swapping\n * datasets mid-conversation is routine and changes nothing about who is\n * answering.\n */\n public setCustomer(customer: Customer): void {\n this.config = { ...this.config, customer };\n }\n\n /**\n * Replace the AGENT mid-conversation. The escape hatch for an agent picker,\n * and nothing else: the session already holds another agent's history, and\n * the server stamps `Session.AgentId` on the first turn only — so the\n * conversation keeps reporting the agent it STARTED as, however many times\n * this is called. Prefer a new engine (new key, see `engineKeyFor`) per\n * agent.\n *\n * Callers pass the FULL replacement context (the same shape the gateway was\n * constructed with). The `model` slice is preserved when the incoming\n * context omits it — the model is owned separately by {@link setModel} and\n * must not be clobbered by an agent-only change.\n */\n public forceAgentContext(config: AgentContext): void {\n this.config = {\n ...config,\n model: config.model ?? this.config.model,\n };\n }\n\n // ─── Session and interactions ───────────────────────────────────────────\n\n public getSessionId() {\n return this.sessionId;\n }\n\n public setSession(sessionId: string, _toolSessionId?: string) {\n if (this.sessionId === undefined || this.sessionId != sessionId) {\n this.sessionId = sessionId;\n this.msg_order = this.sessionState.messages.length;\n }\n }\n\n public startInteraction(interactionQuestion: string, wasSuspended?: boolean | undefined, idOverrideForTests?: string): Interaction {\n if (wasSuspended && this.currentIS) {\n this.currentIS.interaction.isSuspended = false;\n this.currentIS.interaction.interactionQuestion += \" + \" + interactionQuestion;\n return this.currentIS.interaction;\n }\n\n this.msg_order += 1;\n let newId = this.getNewInteractionId();\n if (idOverrideForTests)\n newId = idOverrideForTests;\n\n this.currentIS = this.registerInteraction(newId, interactionQuestion);\n return this.currentIS.interaction;\n }\n\n /** A new interaction and its merge service, in the maps. Who becomes current is the caller's decision. */\n private registerInteraction(interactionId: string, interactionQuestion: string, extra?: Partial<Interaction>): InteractionService {\n const interaction: Interaction = {\n created: new Date(),\n interactionId,\n artifactData: [],\n partial: true,\n sessionId: this.sessionId,\n turn_complete: false,\n parts: [],\n version: 0,\n functionMap: new Map(),\n interactionQuestion,\n ...extra,\n };\n this.interactionsMap.set(interactionId, interaction);\n const service = new InteractionService(interaction, this.eventBusService);\n this.interactionsServiceMap.set(interactionId, service);\n return service;\n }\n\n /** The current interaction's turn is still open — it owns the live message, and must stay current. */\n private currentTurnIsOpen(): boolean {\n const current = this.getCurrentInteractionId();\n return !!current && this.openTurns.has(current);\n }\n\n /**\n * A turn this tab did not send (AIA Issue 1548): a WhatsApp message, a platform wake turn, another tab's turn, a\n * detached run's briefing. It becomes the current interaction only when no open turn holds that place — a local\n * turn mid-stream keeps it, and with it the resume cursor, suspend and the client-side close; the remote turn\n * streams into its own interaction and takes over the live message when that turn ends.\n */\n private openRemoteInteraction(interactionId: string, question: string, origin: InteractionOrigin | undefined, announced: boolean): InteractionService {\n const service = this.registerInteraction(interactionId, question, { remote: true, ...(origin && { origin }) });\n if (!this.currentTurnIsOpen())\n this.currentIS = service;\n // Only an ANNOUNCED turn opens: a server that does not announce turns sends no promise that a turn-complete\n // follows (a replay can start mid-turn), and a turn that never closes is a composer that never unlocks.\n if (announced) {\n this.openTurns.add(interactionId);\n this.sessionState.setTurnOpen(true);\n this.eventBusService.gatewayEmitTurnOpen(interactionId);\n if (this.currentIS === service) this.localEmitMessage(service.interaction);\n }\n return service;\n }\n\n /**\n * An `InteractionStarted` frame. Opens a turn this tab did not send, with the text that started it as its\n * question; ignores one this tab sent (its interaction already exists) and one already known or committed.\n * Outside {@link AgentGatewayOptions.transcriptOfDetachedRun}, a detached run's turn is ignored too: it runs on\n * the run's own session, and its box — not this transcript — shows it.\n */\n public interactionStarted(start: InteractionStart): void {\n const interactionId = start.interactionId;\n if (!interactionId) return;\n if (start.detachedRunId && !this.options.transcriptOfDetachedRun) return;\n if (this.localInteractionIds.has(interactionId) || this.committedTurns.has(interactionId)) return;\n\n const existing = this.interactionsServiceMap.get(interactionId);\n if (existing) {\n // Its frames beat the announcement here (a resume that replayed from mid-turn): give it its question.\n const interaction = existing.interaction;\n if (!interaction.interactionQuestion) interaction.interactionQuestion = start.content ?? '';\n interaction.origin ??= toInteractionOrigin(start.origin);\n return;\n }\n\n this.openRemoteInteraction(interactionId, start.content ?? '', toInteractionOrigin(start.origin), true);\n }\n\n public getInteractions(): Interaction[] {\n return Array.from(this.interactionsMap.values());\n }\n\n public getCurrentInteractionId(): string | null {\n if (this.currentIS)\n return this.currentIS.interaction.interactionId\n else\n return null;\n }\n\n public getCurrentInteraction(): Interaction | null {\n return this.currentIS?.interaction ?? null;\n }\n\n protected updateMap(serverEvent: ServerEvent): Interaction | undefined {\n let interService = this.interactionsServiceMap.get(serverEvent.interactionId);\n if (!interService) {\n // Event for an interaction nobody announced — a server older than `InteractionStarted`, or a replay that\n // starts after the announcement. Create it *with* the event's interactionId so every later event of the\n // turn routes to the same merge target (a fresh id per event once made N events spawn N orphans). No\n // question: the \"Unknown\" bubble it used to get read as something the user had typed. And it does not\n // take the current place from an open turn — it used to, and the resume cursor, suspend and the\n // client-side close then pointed at the wrong turn.\n interService = this.openRemoteInteraction(serverEvent.interactionId, '', undefined, false);\n }\n\n return interService.merge(serverEvent);\n }\n\n protected getNewInteractionId(): string {\n const now = new Date()\n const date_formatted = formatDate(now, \"MMM_dd_HH_mm_ss\");\n return `${this.msg_order}_${date_formatted}`\n }\n\n // ─── Inbound: server events ─────────────────────────────────────────────\n\n public async Message(event: MessageEvent | ServerEvent) {\n try {\n let serverEvent: ServerEvent;\n\n if (typeof (event) == \"object\" && Object.keys(event).includes(\"mimeType\")) {\n serverEvent = event as ServerEvent;\n }\n else {\n console.error(\"Uknown message type\", event)\n return;\n }\n\n if (serverEvent.detachedRunId && !this.options.transcriptOfDetachedRun) {\n this.handleDetachedRunEvent(serverEvent);\n return;\n }\n\n if (serverEvent.serverError) {\n console.error(\"Stream error: \", serverEvent.serverError);\n }\n\n if (serverEvent.endMessageData) {\n this.eventBusService.gatewayEmitEndMessageData(serverEvent.endMessageData);\n }\n\n if (serverEvent.llmArtifacts && serverEvent.llmArtifacts.length > 0) {\n for (const llmArtifact of serverEvent.llmArtifacts) {\n const newArtifact = llmArtifact.toArtifact();\n this.artifactService.addToCache(newArtifact);\n this.eventBusService.artifactEmitGenerated(newArtifact);\n }\n }\n\n for (const part of serverEvent.parts ?? []) {\n if (part.toolDetails) {\n this.localEmitToolEvent(part.toolDetails);\n }\n }\n\n // A server error is the end of the turn it is about, whatever the flag says: an error that left\n // the turn open left the composer locked. Older servers send some of these without the flag,\n // and some without an interaction id at all (an answer the server could not deliver) — those\n // belong to the turn the user is waiting on.\n const isServerError = (serverEvent.parts ?? []).some((p) => p.eventType === EventType.ServerError);\n if (isServerError && !serverEvent.interactionId) {\n const current = this.getCurrentInteractionId();\n if (current) serverEvent.interactionId = current;\n }\n\n const merged = this.updateMap(serverEvent);\n if (!merged) {\n console.error(\"No updated interaction\");\n return;\n }\n\n // The live message belongs to the current turn while it is open; a remote turn streaming beside it keeps\n // its progress in its own interaction until it ends (or takes over the live message when the current\n // turn ends first).\n if (merged.interactionId === this.getCurrentInteractionId() || !this.currentTurnIsOpen())\n this.localEmitMessage(merged);\n\n // One commit per turn. The decoder sets `turn_complete` and `asyncFinalResponse`\n // from the same wire flag, and the previous code committed on each — so every\n // turn-complete frame ran turnComplete twice: two onTurnComplete callbacks to\n // the host, two todolistUpdated tool events, two bumps of the store's counter.\n // `committedTurns` keeps it to one when an error closed the turn and the server's own\n // turn-complete frame follows it (LlmAgent always sends one after its errors).\n if (serverEvent.turn_complete || serverEvent.asyncFinalResponse || isServerError) {\n if (!this.committedTurns.has(serverEvent.interactionId)) {\n this.committedTurns.add(serverEvent.interactionId);\n this.turnComplete(serverEvent.interactionId, merged, serverEvent.author, serverEvent.detachedRunId);\n }\n }\n\n const artifactsIds = serverEvent.artifactsDelta;\n if (artifactsIds) {\n artifactsIds.forEach((id) => {\n const artifactDatas = merged.artifactData.filter((a) => a.id == id);\n let artifactData: Partial<Artifact> | null = null;\n if (artifactDatas && artifactDatas.length > 0) {\n artifactData = artifactDatas[0]\n artifactData.loadingPromise = this.asyncLoadArtifact(id)\n .then((a) => {\n if (a === null) {\n console.error(\"Error trying to load artifact id:\", artifactData?.id, \"Artifact is null\");\n }\n else {\n this.eventBusService.artifactEmitGenerated(a);\n }\n return a;\n })\n .catch((error: any) => {\n console.error(\"Error trying to load artifact id:\", artifactData?.id, error.toString())\n return null;\n })\n }\n });\n }\n }\n catch (error: any) {\n if (this.getCurrentInteractionId()) {\n const errorEvent = ServerEvent.createErrorEvent(\"OnMessage error: \" + error.toString(), this.getCurrentInteractionId() ?? 'Empty Current')\n const updatedInteraction = this.updateMap(errorEvent);\n console.error(\"Error event: \", JSON.stringify(errorEvent, undefined, 4));\n if (!updatedInteraction) {\n console.error(\"Error event, could not update interaction: \", JSON.stringify(errorEvent, undefined, 4));\n return;\n }\n\n this.localEmitMessage(updatedInteraction);\n }\n }\n }\n\n protected detachedRunInteractions: Map<string, Interaction> = new Map();\n protected detachedRunInteractionServices: Map<string, InteractionService> = new Map();\n\n protected getOrCreateDetachedRunInteraction(detachedRunId: string, interactionId: string, detachedRunName?: string): { interaction: Interaction; service: InteractionService } {\n let interaction = this.detachedRunInteractions.get(detachedRunId);\n let service = this.detachedRunInteractionServices.get(detachedRunId);\n\n if (!interaction || !service) {\n interaction = {\n created: new Date(),\n interactionId: interactionId,\n artifactData: [],\n partial: true,\n turn_complete: false,\n parts: [],\n version: 0,\n functionMap: new Map(),\n interactionQuestion: detachedRunName ?? detachedRunId,\n };\n service = new InteractionService(interaction, this.eventBusService);\n this.detachedRunInteractions.set(detachedRunId, interaction);\n this.detachedRunInteractionServices.set(detachedRunId, service);\n }\n\n return { interaction, service };\n }\n\n protected handleDetachedRunEvent(serverEvent: ServerEvent) {\n const detachedRunId = serverEvent.detachedRunId!;\n const { service } = this.getOrCreateDetachedRunInteraction(detachedRunId, serverEvent.interactionId, serverEvent.detachedRunName);\n\n for (const part of serverEvent.parts ?? []) {\n if (part.toolDetails) {\n this.localEmitToolEvent({ ...part.toolDetails, detachedRunId });\n }\n }\n\n const merged = service.merge(serverEvent);\n if (!merged) return;\n\n this.sessionState.setDetachedRunMessage(detachedRunId, merged, serverEvent.detachedRunName);\n\n if (serverEvent.turn_complete ?? false) {\n this.sessionState.completeDetachedRun(detachedRunId);\n }\n }\n\n protected localEmitToolEvent(toolDetails: ToolEventDetails) {\n this.sessionState.setLastToolEvent(toolDetails);\n this.eventBusService.gatewayEmitToolEvent(toolDetails.eventName, toolDetails.eventData, toolDetails.sessionId);\n }\n\n protected registerInteractionCallId(interactionId: string, options?: GatewaySendMessageOptions) {\n if (options?.callId) {\n this.interactionCallIds.set(interactionId, options.callId);\n }\n }\n\n protected localEmitFirstToken(interactionId: string) {\n this.eventBusService.gatewayEmitFirstToken({\n interactionId,\n callId: this.interactionCallIds.get(interactionId),\n });\n }\n\n protected localEmitMessage(message: Interaction) {\n this.liveMessage.emit(message);\n }\n\n protected localOpen(interactionId: string, _author: string): void {\n if (interactionId) this.openTurns.add(interactionId);\n this.sessionState.setTurnOpen(true);\n this.eventBusService.gatewayEmitTurnOpen(interactionId ?? '');\n }\n\n protected async turnComplete(interactionId: string, agentInteraction: Interaction, _author: string, detachedRunId?: string): Promise<void> {\n this.openTurns.delete(interactionId);\n // A turn that did not own the live message (a remote one that ended under a local one still streaming):\n // committing it must not wipe the live message of the turn that does.\n const ownsLiveMessage = interactionId === this.getCurrentInteractionId();\n const liveOfAnotherTurn = ownsLiveMessage ? null : this.sessionState.currentMessage;\n // Must run before setNewMessage: a trailing throttle publish would\n // otherwise re-set `currentMessage` to this just-committed interaction\n // and duplicate it on screen. See ThrottledEmitter.cancelPending.\n if (ownsLiveMessage) this.liveMessage.cancelPending();\n this.sessionState.setNewMessage(agentInteraction);\n if (liveOfAnotherTurn && liveOfAnotherTurn.interactionId !== interactionId)\n this.sessionState.setCurrentMessage(liveOfAnotherTurn);\n else if (ownsLiveMessage)\n this.handOverLiveMessage();\n this.eventBusService.gatewayEmitTurnComplete(interactionId, agentInteraction)\n this.interactionCallIds.delete(interactionId);\n\n this.sessionState.setLastToolEvent(null);\n this.localEmitToolEvent({\n eventName: 'todolistUpdated',\n eventData: '',\n detachedRunId: detachedRunId\n })\n\n this.sessionState.setTurnOpen(this.openTurns.size > 0);\n }\n\n /**\n * The current turn ended while another is still open (a remote turn that started under it): that one becomes\n * current and its progress so far goes live at once.\n */\n private handOverLiveMessage(): void {\n for (const interactionId of this.openTurns) {\n const service = this.interactionsServiceMap.get(interactionId);\n if (!service) continue;\n this.currentIS = service;\n this.sessionState.setCurrentMessage(service.interaction);\n this.eventBusService.gatewayEmitMessage(service.interaction);\n return;\n }\n }\n\n // ─── Artifacts ──────────────────────────────────────────────────────────\n\n runningRequests = new Map<string, Promise<Artifact | null>>();\n\n public async asyncLoadArtifact(artifactId: string): Promise<Artifact | null> {\n let response: Promise<Artifact | null> | null = null;\n const runningPromise = this.runningRequests.get(artifactId);\n if (runningPromise) {\n console.warn(\"GOT A running promise\", artifactId);\n response = runningPromise\n }\n else {\n response = this.artifactService.getArtifact(artifactId);\n this.runningRequests.set(artifactId, response)\n }\n\n try {\n const realResponse = await response;\n return realResponse;\n }\n catch (error: any) {\n console.error(\"Error awating on HTML promise\", error.toString())\n return null;\n }\n finally {\n this.runningRequests.delete(artifactId);\n }\n }\n\n // ─── Connection ─────────────────────────────────────────────────────────\n\n /**\n * Be on `sessionId` (a fresh session when undefined). Resolves with the session id once the\n * first dial succeeds and rejects when it fails; the supervisor keeps redialling in the\n * background either way, with the replay cursor, until {@link closeConnection}. Concurrent\n * callers for the same session share the dial in flight. See ConnectionSupervisor for the\n * backoff, the idle close and the close-code policy — and for the rule that a requested\n * session is never swapped for another.\n */\n public async openConnection(sessionId?: string, options?: OpenOptions): Promise<string> {\n return this.connection.open(sessionId, options);\n }\n\n public async closeConnection(closeTurn: boolean = true): Promise<SendMessageResponse | null> {\n try {\n this.stopStream(closeTurn)\n\n return {\n success: true,\n interaction: this.getCurrentInteraction()!\n }\n }\n catch (error) {\n return {\n success: false,\n interaction: this.getCurrentInteraction()!\n }\n }\n }\n\n /** Hang up and stop supervising the connection. `closeTurn` also closes an open turn in the store. */\n public stopStream(closeTurn: boolean = true): void {\n if (closeTurn) {\n this.openTurns.clear();\n this.sessionState.setTurnOpen(false);\n }\n\n this.sessionState.setConnectionOutage(null);\n this.connection.close();\n }\n\n /**\n * Make sure the socket is OPEN before a send, redialling the SAME session when it is not.\n *\n * The socket can be down at send time for reasons the composer cannot see: the client's own\n * idle close (5 min without input), the server's (6 min without a message, code 4003), a dead\n * peer the heartbeat just detected, or a dial still in flight. Until this existed the send\n * threw `WebSocket is not connected` AFTER the user's turn was already on the transcript — or\n * the composer refused it outright. A send IS the activity that reconnect was waiting for, so\n * the supervisor dials now rather than at its next scheduled retry, replay cursor kept.\n */\n private async ensureConnected(): Promise<void> {\n const sessionId = this.sessionId;\n // Logged on EVERY send, including the happy path: the guard's whole job is to be\n // the thing that ran before the frame went out, and a guard you cannot see in the\n // console is one you cannot rule out when a send goes missing.\n if (this.wsService.isConnected()) {\n console.log(`[AgentGateway] send guard: socket is open (session ${sessionId ?? 'none'}, ` +\n `status ${this.sessionState.connectionStatus}) — sending straight away.`);\n return;\n }\n const startedAt = Date.now();\n try {\n const connectedSessionId = await this.connection.ensure(sessionId);\n console.log(`[AgentGateway] send guard: reconnected to ${connectedSessionId} ` +\n `in ${Date.now() - startedAt}ms — sending now.`);\n } catch (error) {\n console.error(`[AgentGateway] send guard: redial FAILED after ${Date.now() - startedAt}ms ` +\n `— the message was not sent.`, error);\n throw new Error(AgentGatewayWSAsync.NO_CONNECTION_MESSAGE, { cause: error });\n }\n }\n\n // ─── Outbound: the user's turns ─────────────────────────────────────────\n\n public async sendMessage(message: ClientMessage, options?: GatewaySendMessageOptions): Promise<SendMessageResponse> {\n let messageNumber = this.getInteractions().length;\n let totalTimer = InteractionPartUtils.createWaiting(true, true, \"Overall\", new Date());\n this.sendStatusMessage(message.data, [totalTimer], messageNumber.toString() + \"1\");\n\n try {\n const { promptAsString, json } = this.sessionState.onRenderPrompt ? this.sessionState.onRenderPrompt(message.data) : { promptAsString: message.data, json: undefined };\n\n if (this.sessionState.onRenderPrompt) {\n message.data = json;\n message.friendlyMessage = promptAsString;\n }\n const sendResponse = await this.sendMessageInternal(message, options)\n\n const prompt = PromptUtils.createPrompt(promptAsString ?? '', json?.toString() ?? {});\n this.storageService.storePrompt(prompt);\n\n const startingPart = InteractionPartUtils.fromText(\"Planejando próximos passos\")\n this.sendStatusMessage(message.data, [totalTimer, startingPart], messageNumber.toString() + \"1\");\n\n if (!sendResponse?.success) {\n this.eventBusService.ChatEmitMessageError(sendResponse?.error ?? '');\n }\n else {\n this.eventBusService.ChatEmitMessageSent(message.data, sendResponse.interaction);\n }\n\n return sendResponse;\n }\n catch (error) {\n const reason = error instanceof Error ? error.message : String(error ?? '');\n // The turn never left the client: take the status message (and its running \"Overall\"\n // clock) off the screen and close the turn the send opened, so the composer unlocks.\n this.liveMessage.cancelPending();\n this.sessionState.setCurrentMessage(null);\n this.sessionState.setTurnOpen(this.openTurns.size > 0);\n this.eventBusService.ChatEmitMessageError(reason);\n return {\n success: false,\n error: reason,\n interaction: {\n artifactData: [],\n created: new Date(),\n interactionId: \"\",\n partial: false,\n parts: [InteractionPartUtils.fromError(reason)],\n version: 0\n }\n }\n }\n }\n\n // Send a message to the server over the socket\n public async sendMessageInternal(message: ClientMessage, options?: GatewaySendMessageOptions): Promise<SendMessageResponse> {\n const wasSuspended = this.suspendState;\n this.suspendState = false;\n const interaction = this.startInteraction(message.friendlyMessage ?? message.data, wasSuspended);\n this.localInteractionIds.add(interaction.interactionId);\n this.registerInteractionCallId(interaction.interactionId, options);\n\n // Inject the user turn's UI representation as a part so the host component renders\n // immediately (live), identical to what ServerEvent reconstructs from the persisted\n // UserUiContent sibling on reload. The frame below carries the same {name,args} to the\n // server (stripped from the model request); Content stays the only model-facing text.\n if (message.userUi?.name)\n interaction.parts.push(InteractionPartUtils.fromUserUi(message.userUi.name, message.userUi.args));\n\n if (!this.wsService)\n throw \"no wsService created\";\n\n // No session id is not a reason to refuse: the send guard below dials a fresh session when\n // none was ever opened (the initial dial failed on a server that was down, say).\n\n if (!this.config.agentConfig?.id) {\n throw \"Agent not selected\"\n }\n\n // A send is user activity: reset the idle clock the state manager closes the socket on,\n // and do it BEFORE the redial — a heartbeat landing between \"reconnected\" and \"turn open\"\n // would otherwise see an expired idle window on a Connected socket and close what was\n // just opened, and the send would die on it.\n this.sessionState.setLastActivity();\n await this.ensureConnected();\n\n this.wsService.sendMessage({\n Content: message.data,\n SessionId: this.sessionId,\n Action: ChatAction.SendMessage,\n ModelId: this.config.model,\n InteractionId: interaction.interactionId,\n AgentId: this.config.agentConfig?.id,\n // Optional explicit C# class name on the server (e.g. \"LlmAgentSessionReplay\").\n // When set, AgentBootStrapService.GetAgent dispatches to that class directly\n // instead of looking up an Agent metadata row by AgentId. Plumbed through\n // `agentContext.agentConfig.agentImplementation` so a host can run a turn\n // against any registered LlmAgent variant without seeding a Mongo record.\n AgentImplementation: this.config.agentConfig?.agentImplementation,\n Parameters: {\n ...(this.config.parameters?.() ?? {}),\n \"CustomerName\": this.config.customer?.name ?? '',\n \"DataSet\": this.config.customer?.dataSetId ?? ''\n },\n // Forward image attachments as a structured payload (PascalCase\n // keys to match the C# `Message.Images` / `MessageImage` model).\n Images: message.images?.length\n ? message.images.map((img) => ({ MimeType: img.mimeType, Data: img.data }))\n : undefined,\n // Client-only UI representation for this turn (PascalCase to match the C# `Message.UserUi`\n // model). The server persists it as a UserUiContent sibling and strips it from the model\n // request; Content remains the only model-facing text.\n UserUi: message.userUi?.name\n ? { Name: message.userUi.name, Args: message.userUi.args }\n : undefined,\n })\n\n this.localOpen(interaction.interactionId, \"system\");\n\n return {\n interaction: interaction,\n success: true,\n };\n }\n\n public sendStatusMessage(question: string, parts: InteractionPart[], interactionId: string) {\n let interactionStatus: Interaction;\n // An unfinished current turn is continued (a suspended turn the user resumes) — unless it is a remote turn,\n // which a send from here does not continue: the status belongs on the turn being sent.\n if (this.currentIS?.interaction?.turn_complete === false && !this.currentIS.interaction.remote) {\n interactionStatus = _.cloneDeep(this.currentIS.interaction);\n interactionStatus.parts.push(...parts);\n }\n else {\n interactionStatus = {\n interactionId: \"tmp\" + interactionId,\n created: new Date(),\n partial: true,\n turn_complete: false,\n version: 0,\n parts: parts,\n interactionQuestion: question,\n artifactData: []\n }\n }\n\n this.localEmitMessage(interactionStatus);\n }\n\n /**\n * Send the user's answer to a parked `ask_user` tool call back to the agent, as a\n * ChatAction.AnswerHumanTool frame. 'sent' when it went out immediately, 'queued' when the\n * socket was down and the answer will flush on reconnect.\n *\n * Feature-detected rather than cast: a host may supply any `IWebSocketConnection` (the demo's fake\n * gateway does), and a hard cast turned \"this transport doesn't deliver answers\" into a TypeError\n * thrown from a click handler — with the answer lost either way.\n */\n public answerHumanTool(toolCallId: string, answer: string): 'sent' | 'queued' {\n const deliver = this.wsService.answerHumanTool?.bind(this.wsService);\n if (!deliver) {\n console.warn('[AgentGateway] transport cannot deliver parked-tool answers', toolCallId);\n return 'queued';\n }\n return deliver(toolCallId, answer);\n }\n\n // ─── Detached-run announcements ─────────────────────────────────────────\n\n /**\n * Ask the server to tell this conversation about a detached run of it that settled (AIA Issue 1548 §5): the\n * `AnnounceDetachedRun` socket action. The server claims every settled-and-unannounced run of the session at once\n * (two tabs asking, one wins) and starts an ordinary turn on this socket, `origin: platform`, in the host's words —\n * which arrives as any remote turn does (`InteractionStarted`).\n *\n * <p>Never over a turn: while one is open in this tab the request waits, and goes out when the chat is idle (and\n * the socket up). `settleKey` — the run's `settledAt` — scopes the dedupe: a repeated request for the same settle\n * is a no-op, a resumed run that settles anew is announced again.</p>\n */\n public async announceDetachedRun(runId: string, settleKey?: string | null): Promise<AnnounceDetachedRunResult> {\n const key = `${runId}|${settleKey ?? ''}`;\n if (this.announceRequested.has(key)) return 'duplicate';\n this.announceRequested.add(key);\n this.pendingAnnouncements.push(runId);\n await this.flushAnnouncements();\n return this.pendingAnnouncements.includes(runId) ? 'queued' : 'sent';\n }\n\n /** Send the queued announcements, oldest first, while the chat is idle and the socket is open. */\n private async flushAnnouncements(): Promise<void> {\n if (this.flushingAnnouncements) return;\n this.flushingAnnouncements = true;\n try {\n while (this.pendingAnnouncements.length > 0 && !this.sessionState.turnOpen) {\n const send = this.wsService.sendBaseMessage?.bind(this.wsService);\n if (!send) {\n console.warn('[AgentGateway] transport cannot send an AnnounceDetachedRun; the request stays queued');\n return;\n }\n if (!this.wsService.isConnected() || !this.sessionId) return; // the next connect flushes it\n const runId = this.pendingAnnouncements[0];\n try {\n send({\n Action: ChatAction.AnnounceDetachedRun,\n AgentId: this.config.agentConfig?.id ?? '',\n InteractionId: `announce_${runId}_${Date.now()}`,\n SessionId: this.sessionId,\n DetachedRunId: runId,\n });\n } catch (error) {\n console.warn(`[AgentGateway] AnnounceDetachedRun for run ${runId} could not be sent; it stays queued`, error);\n return;\n }\n this.pendingAnnouncements.shift();\n console.log(`[AgentGateway] asked for the announcement of run ${runId} (session ${this.sessionId}).`);\n }\n } finally {\n this.flushingAnnouncements = false;\n }\n }\n\n // ─── Suspend ────────────────────────────────────────────────────────────\n\n public async suspend(): Promise<boolean> {\n const localWsService = this.wsService;\n return new Promise<boolean>(async (resolve, reject) => {\n let success = false;\n localWsService.onSuspended = () => {\n success = true;\n }\n localWsService.suspendStream();\n\n const sleepTime = 100;\n const timeOut = 5000;\n let elapsed = 0;\n\n while (!success && elapsed < timeOut) {\n await this.sleep(sleepTime);\n elapsed += sleepTime\n }\n\n if (!success) {\n // Not suspended: the agent is still running, so the gateway must not say otherwise.\n // (A `finally` used to flip `suspendState` here even on the timeout, and the next\n // send then \"resumed\" a turn that had never stopped.)\n reject(\"Timeout awaiting for suspension\");\n return;\n }\n\n if (!this.currentIS) {\n console.error(\"CurrentIS is null\");\n reject(\"CurrentIS is null\")\n return;\n }\n\n const interaction = this.currentIS.interaction;\n interaction.isSuspended = true;\n this.openTurns.delete(interaction.interactionId);\n this.sessionState.setCurrentMessage(interaction);\n this.sessionState.setTurnOpen(this.openTurns.size > 0);\n this.suspendState = true;\n resolve(true);\n });\n }\n\n async sleep(ms: number) {\n return new Promise(resolve => setTimeout(resolve, ms));\n }\n}\n","import { InteractionStart, LlmEvent, PartType, StreamingFunctionCallUpdateContent, StreamingReasoningContent, StreamingResponse, StreamingTextContent, TextContent } from '@lib/models/semanticKernelModel/models';\nimport type { PartialLlmEvent } from '@lib/models/semanticKernelModel/models';\nimport { EventType } from '@lib/models/enums';\n\n/**\n * The server narrows a delta-only frame to `pe` (PartialEvent.cs): no envelope\n * fields beyond the interaction id, and one of `pt` (text, or the ARGUMENTS\n * fragment when `fn` is set), `pr` (reasoning). This widens it back to the\n * LlmEvent shape the ServerEvent mapper reads, so one mapper serves both the\n * narrowed and the full frame. Pure: builds a new event, mutates nothing.\n *\n * Kind is decided by presence, in this order: a function name → streamed\n * arguments; reasoning → thought; otherwise text, even when `pt` is empty.\n */\nexport function llmEventFromPartial(pe: PartialLlmEvent): LlmEvent {\n const event = new LlmEvent();\n event.author = \"main\";\n event.streamingParts = pe.streamingParts;\n if (pe.partialEventType) {\n event.eventType = pe.partialEventType;\n }\n else {\n event.eventType = pe.functionName\n ? { fullName: PartType.StreamingFunctionCallUpdateContent, type: EventType.PartialFunctionCall }\n : pe.partialReasoning\n ? { fullName: PartType.StreamingReasoningContent, type: EventType.Thought }\n : { fullName: PartType.StreamingTextContent, type: EventType.Text };\n }\n\n event.interactionId = pe.iteractionId ?? '';\n event.mimeType = \"text/plain\";\n event.partial = true;\n event.role = { label: \"Assistant\" };\n event.timestamp = pe.timeStamp ?? new Date().getTime();\n event.turnComplete = false;\n\n const kind = event.eventType.type;\n if (kind == EventType.PartialFunctionCall) {\n const callPart = new StreamingFunctionCallUpdateContent();\n callPart.choiceIndex = 0;\n callPart.callId = pe.functionCallId;\n callPart.arguments = pe.partialText;\n callPart.name = pe.functionName;\n event.content = { items: [callPart], role: { label: \"Assistant\" } };\n }\n else if (kind == EventType.Text) {\n // The wire wrapper distinguishes streaming vs final text — both map to EventType.Text in\n // the domain (the `partial` boolean carries the streaming distinction downstream).\n if (event.eventType.fullName == PartType.StreamingTextContent) {\n const streamTextPart = new StreamingTextContent();\n streamTextPart.text = pe.partialText;\n event.content = { items: [streamTextPart], role: { label: \"Assistant\" } };\n }\n else {\n const textPart = new TextContent();\n textPart.text = pe.partialText;\n event.content = { items: [textPart], role: { label: \"Assistant\" } };\n }\n }\n else if (kind == EventType.Thought) {\n const thoughtPart = new StreamingReasoningContent();\n thoughtPart.text = pe.partialReasoning;\n event.content = { items: [thoughtPart], role: { label: \"Assistant\" } };\n }\n return event;\n}\n\n/**\n * The LlmEvent carried by a frame, whichever form it took — the full `event`,\n * or the narrowed `pe` widened back. Control frames (Pong, Suspended,\n * RewindLost without a payload) yield nothing. The envelope's detached run identity\n * is stamped onto the event so the gateway can route it.\n */\nexport function llmEventFromFrame(frame: StreamingResponse): LlmEvent | undefined {\n const event = frame.partialEvent ? llmEventFromPartial(frame.partialEvent) : frame.event;\n if (!event) return undefined;\n if (frame.detachedRunId) {\n event.detachedRunId = frame.detachedRunId;\n event.detachedRunName = frame.detachedRunName;\n }\n return event;\n}\n\n/** True when the event carries any content item or streaming part — what counts as a first token. */\nexport function carriesContent(event: LlmEvent): boolean {\n return (event.content?.items?.length ?? 0) > 0 || (event.streamingParts?.length ?? 0) > 0;\n}\n\n/**\n * The turn an `InteractionStarted` frame announces (AIA Issue 1548), with the envelope's detached run id carried\n * onto it when the payload has none; undefined for any other frame, or one with no interaction id.\n */\nexport function interactionStartFromFrame(frame: StreamingResponse): InteractionStart | undefined {\n if (frame.type !== 'InteractionStarted' || !frame.interaction?.interactionId) return undefined;\n if (frame.interaction.detachedRunId || !frame.detachedRunId) return frame.interaction;\n const start = Object.assign(new InteractionStart(), frame.interaction);\n start.detachedRunId = frame.detachedRunId;\n return start;\n}\n","import type { SessionCompaction, SessionInformation } from '@lib/models/semanticKernelModel/models';\n\n/**\n * A drop smaller than this fraction of the budget is noise, not a compaction.\n *\n * `size` is an ESTIMATE the server recomputes per turn, so it can wobble by a\n * few tokens either way without anything being removed. 2% of the window is far\n * below any real pass (the compactor summarizes whole interactions) and far above\n * that wobble.\n */\nconst NOISE_FLOOR = 0.02;\n\n/**\n * Did a compaction happen between these two observations?\n *\n * **Why a drop and not an event.** The summarizing compactor (issue 681) runs\n * DETACHED on the run bus, so its pass emits nothing into the turn's event\n * stream — a panel that waited for a \"compacted\" event would show nothing at all\n * for the production path. What it cannot hide is the result: a session's\n * estimated size only ever falls when something removed events from it. So the\n * drop IS the signal, and an in-band compression event (the legacy trim, or the\n * probe) merely arrives carrying richer numbers to label it with.\n *\n * Returns null when nothing happened, which is the overwhelmingly common case.\n */\nexport function detectCompaction(\n previous: SessionInformation | undefined,\n next: SessionInformation | undefined,\n): SessionCompaction | null {\n if (!next) return null;\n\n // An in-band compression event says so outright — no inference needed.\n const declared = (next.interactionsCompressed ?? 0) > 0 || (next.compressionRatio ?? 0) > 0;\n\n if (!previous) {\n // First observation of this connection. Nothing to compare against, so only\n // a declared compression counts; a resumed session that is already large is\n // not a compaction that happened now.\n return declared ? entry(next, next.size, next.size) : null;\n }\n\n const dropped = previous.size - next.size;\n const budget = next.maxSize || previous.maxSize || 0;\n const significant = budget > 0\n ? dropped / budget >= NOISE_FLOOR\n // No budget reported (a host that never sends maxSize): fall back to a\n // relative drop, so the panel still works rather than silently never marking.\n : previous.size > 0 && dropped / previous.size >= 0.1;\n\n if (!declared && !significant) return null;\n\n return entry(next, previous.size, next.size, previous.ratio);\n}\n\nfunction entry(\n info: SessionInformation, sizeBefore: number, sizeAfter: number, ratioBefore?: number,\n): SessionCompaction {\n return {\n at: Date.now(),\n // Where the bar stood when it happened — the marker's position. The ratio\n // BEFORE the pass is the meaningful one: it is the fill the compaction\n // reacted to, and it is also the only one that does not move afterwards.\n ratio: ratioBefore ?? info.ratio,\n sizeBefore,\n sizeAfter,\n interactionsCompressed: info.interactionsCompressed,\n };\n}\n","import type { InteractionStatistics, SessionCompaction, SessionInformation } from '@lib/models/semanticKernelModel/models';\nimport { detectCompaction } from '@lib/utils/sessionCompaction';\n\nconst SLIDING_WINDOW_SIZE_SECONDS = 4;\nconst TOKEN_SIZE_AVG = 3;\n/** Markers past this add nothing a reader can distinguish; the oldest fall off. */\nconst MAX_TRACKED_COMPACTIONS = 20;\n\n/**\n * Per-connection stream statistics: frame counts, bytes, a tokens-per-second\n * estimate over a sliding window, the session-size reading and the compactions\n * inferred from it. Client-only — the server sends no stats payload.\n *\n * Two lifetimes live here on purpose. `stats` is rebuilt for every interaction\n * (see {@link resetForInteraction}); the compaction history spans the whole\n * connection, because it is the thing the usage panel plots across turns.\n *\n * Flushes to `onFlush` are coalesced to {@link STATS_FLUSH_MS}: stats can\n * change dozens of times per second during streaming, and a per-packet\n * firehose once drove heavy v2 surfaces (RunProgressPanelV2, StreamStatistics,\n * ChatTranscript all subscribed) into React's nested-update limit.\n */\nexport class StreamStatsTracker {\n static readonly STATS_FLUSH_MS = 120;\n\n stats: InteractionStatistics;\n onFlush?: (stats: InteractionStatistics) => void;\n\n private readonly sessionCompactions: SessionCompaction[] = [];\n private previousSessionInformation?: SessionInformation;\n /** [timestamp, text length] per frame, for the sliding-window rate. */\n private events: [number, number][] = [];\n private flushTimer: ReturnType<typeof setTimeout> | null = null;\n private lastFlushed = 0;\n\n constructor() {\n this.stats = this.fresh();\n }\n\n private fresh(): InteractionStatistics {\n return {\n eventCount: 0,\n unknonwCount: 0,\n buffer: [],\n startTime: new Date(),\n elapsed: 0,\n unparsedCount: 0,\n totalTransfered: 0,\n tokensPerSecond: 0,\n sessionCompactions: this.sessionCompactions,\n };\n }\n\n /** A new interaction started streaming: counters restart, the compaction history does not. */\n resetForInteraction(): void {\n this.stats = this.fresh();\n }\n\n /**\n * Account for one decoded frame. `sessionInformation` is only read off main-agent\n * frames — a detached run's reading describes a different session.\n */\n record(opts: { rawLength: number; textLength: number; sessionInformation?: SessionInformation; fromDetachedRun: boolean }): void {\n const now = Date.now();\n this.events.push([now, opts.textLength]);\n this.stats.eventCount += 1;\n this.stats.totalTransfered += opts.rawLength;\n\n if (opts.sessionInformation && !opts.fromDetachedRun) {\n // Before overwriting the reading, ask whether the session just SHRANK — that is the\n // only visible trace a detached compaction leaves (see detectCompaction). Capped: the\n // panel plots markers, not an audit log.\n const compaction = detectCompaction(this.previousSessionInformation, opts.sessionInformation);\n if (compaction) {\n this.sessionCompactions.push(compaction);\n if (this.sessionCompactions.length > MAX_TRACKED_COMPACTIONS) this.sessionCompactions.shift();\n }\n this.previousSessionInformation = opts.sessionInformation;\n this.stats.sessionInformation = opts.sessionInformation;\n this.stats.sessionCompactions = this.sessionCompactions;\n }\n\n this.stats.elapsed = (now - this.stats.startTime.getTime()) / 1000; // seconds\n const windowStart = now - (SLIDING_WINDOW_SIZE_SECONDS * 1000);\n // Frames older than the window never come back into it: drop them instead of filtering\n // the whole history on every frame (20k frames per journey made this O(n²)).\n while (this.events.length > 0 && this.events[0][0] <= windowStart) this.events.shift();\n const charsInWindow = this.events.reduce((sum, e) => sum + e[1], 0);\n this.stats.tokensPerSecond = (charsInWindow / TOKEN_SIZE_AVG) / SLIDING_WINDOW_SIZE_SECONDS;\n\n this.flushCoalesced();\n }\n\n private flushCoalesced(): void {\n if (!this.onFlush) return;\n const now = Date.now();\n const elapsed = now - this.lastFlushed;\n if (elapsed >= StreamStatsTracker.STATS_FLUSH_MS) {\n if (this.flushTimer) {\n clearTimeout(this.flushTimer);\n this.flushTimer = null;\n }\n this.lastFlushed = now;\n this.onFlush({ ...this.stats });\n return;\n }\n if (this.flushTimer) return;\n this.flushTimer = setTimeout(() => {\n this.flushTimer = null;\n this.lastFlushed = Date.now();\n this.onFlush?.({ ...this.stats });\n }, StreamStatsTracker.STATS_FLUSH_MS - elapsed);\n }\n}\n","import type { BillingLimitNotice } from '../../models/billingLimit';\nimport { BillingLimitContent } from '../../models/semanticKernelModel/models';\nimport { ServerEvent } from \"@lib/models/ServerEvent\";\nimport { getRandomUUID } from \"@lib/utils/envUtils\";\nimport { TypedJSON } from \"typedjson\";\nimport { type InteractionStart, type InteractionStatistics, type LlmEvent, StreamingResponse } from \"@lib/models/semanticKernelModel/models\";\nimport { carriesContent, interactionStartFromFrame, llmEventFromFrame } from \"../wire/decodeFrame\";\nimport { StreamStatsTracker } from \"./streamStats\";\nimport { createStreamingResponseSerializer } from \"@lib/models/semanticKernelModel/serializer\";\nimport { ChatAction } from \"@lib/models/enums\";\nimport { type ConnectOptions, type IWebSocketConnection, type IMessage, type IMessageBase } from \"./webSocketConnection\";\n\nimport {\n APPLICATION_CLOSED_CODE,\n HEARTBEAT_TIMEOUT_CODE,\n SESSION_ALREADY_ATTACHED_CODE,\n} from \"./closeCodes\";\n\nexport { APPLICATION_CLOSED_CODE, HEARTBEAT_TIMEOUT_CODE, SESSION_ALREADY_ATTACHED_CODE };\n\n// This class dials ONCE per `connect()` and never redials on its own. A socket that closes —\n// a server restart, a network blip, the heartbeat's dead-peer verdict — is reported through\n// `onClose` with its code, and the ConnectionSupervisor (owned by the gateway) decides whether\n// and when to dial again. Until 2026-10-07 a two-attempt loop lived here, racing the session\n// manager's slower one; every reconnect bug lived in the seam between them.\n//\n// What stays here is the wire: the dial URL (token, `?lastSeq=N` resume cursor), the\n// \"proven on the Pong\" rule (the upgrade is not a connection — the server can accept the\n// socket and close it a few ms later), the heartbeat, and the parked-answer queue.\n\n// Heartbeat. The monitor ticks every MONITOR_TICK_MS; after PING_INTERVAL_MS of\n// silence in both directions it sends a Ping, and a socket that produces NO\n// inbound frame for PONG_TIMEOUT_MS after that is declared dead (see failSocket).\n// Any frame counts, not just the Pong: the server serialises every outbound\n// frame through one FIFO channel, so a stream frame arriving after the Ping went\n// out proves the peer is alive even when the Pong itself is queued behind a burst.\n//\n// Why this exists: a half-open socket — laptop lid, network switch, a recycled\n// Cloud Run instance whose close frame never reached us — keeps readyState OPEN\n// indefinitely. Every send then succeeds locally and goes nowhere, and nothing\n// else in the client can tell: the store says Connected, the idle timer is kept\n// alive by the open turn, and the browser may take minutes (or forever) to fire\n// onclose. That was the \"message sent, never replied\" hang. Before this the\n// missing Pong was only logged (\"Ping pong stack broke\"), never acted on.\nconst MONITOR_TICK_MS = 5_000;\nconst PING_INTERVAL_MS = 30_000;\nconst PONG_TIMEOUT_MS = 10_000;\n\nexport class WebSocketConnecionV2 implements IWebSocketConnection {\n ws: WebSocket | null = null;\n /** Frame counts, byte totals, the token-rate estimate and the compaction history — see StreamStatsTracker. */\n private readonly statsTracker = new StreamStatsTracker();\n get stats(): InteractionStatistics { return this.statsTracker.stats; }\n baseUrl: string;\n /**\n * Optional callback that returns the current JWT. We re-evaluate it on every connect/reconnect\n * so that a refreshed token is picked up automatically. Browsers can't set the Authorization\n * header on the WebSocket handshake, so we pass the JWT via the ?access_token= query string,\n * which the .NET JwtBearer events handler reads in Program.cs.\n */\n getToken?: () => string | undefined;\n\n onEvent?: (event: MessageEvent | ServerEvent) => Promise<void>;\n onError?: (error: string) => void;\n onOpen?: () => void;\n onFirstToken?: (interactionId: string) => void;\n onSuspended?: () => void;\n onBillingLimit?: (notice: BillingLimitNotice) => void;\n onClose?: (code: number, reason: string) => void;\n /**\n * Fired when the server signals that we lost streaming events on resume — our\n * `lastSeq` fell off the end of the in-memory replay buffer. Consumers should\n * reset partial-streaming UI for this session and rely on persisted history.\n */\n onRewindLost?: (sessionId: string, resumingFromSeq: number) => void;\n onInteractionStarted?: (start: InteractionStart) => void;\n sessionId?: string\n /** Coalesced stats updates (see StreamStatsTracker.STATS_FLUSH_MS). */\n set onNewPacket(listener: ((stats: InteractionStatistics) => void) | undefined) { this.statsTracker.onFlush = listener; }\n get onNewPacket(): ((stats: InteractionStatistics) => void) | undefined { return this.statsTracker.onFlush; }\n monitorInterval: NodeJS.Timeout | null = null;\n streamingResponseSerializer: TypedJSON<StreamingResponse>;\n\n lastActivity: number;\n /** When the outstanding heartbeat Ping went out; null while no reply is pending. */\n private pingSentAt: number | null = null;\n firstTokenInteractions: Set<string>;\n\n /** Last sessionId we successfully had — stamps parked answers, labels log lines. */\n private lastKnownSessionId?: string;\n /**\n * Highest server-assigned `seq` we have observed and processed. The next\n * reconnect appends `?lastSeq={lastSeq}` so the server can replay anything\n * we missed from the InteractionRun's in-memory buffer. -1 means \"haven't\n * seen any sequenced events yet\" (fresh connection).\n */\n private lastSeq: number = -1;\n /**\n * Parked-tool answers that could not be sent because the socket was not OPEN\n * (e.g. the connection idled out while the user was in an IdP sign-in popup).\n * Keyed per tool call (last answer wins) and stamped with the session they\n * belong to; flushed by `onopen` when the socket resumes THAT session. An\n * answer for a session this instance is no longer attached to is dropped —\n * the single-attach policy makes it undeliverable from here anyway.\n */\n private pendingAnswers: Array<{ sessionId?: string; toolCallId: string; answer: string }> = [];\n\n constructor(baseUrl: string = 'ws://localhost:8000', getToken?: () => string | undefined) {\n this.baseUrl = baseUrl;\n this.getToken = getToken;\n\n this.firstTokenInteractions = new Set();\n\n this.streamingResponseSerializer = createStreamingResponseSerializer();\n\n console.log(\"SOCKET INSTACE\", getRandomUUID())\n\n this.lastActivity = new Date().getTime();\n }\n\n /**\n * Dial the endpoint once. Resolves with the session id the server's first Pong carries;\n * rejects when the socket closes, or times out, before that. A close AFTER the Pong is\n * reported through `onClose` only.\n *\n * `options.resume` keeps the replay cursor so the server can send back everything emitted\n * while we were away (`?lastSeq=N`). Without it the dial is fresh and the cursor is dropped:\n * a cursor from one conversation must never be presented to another.\n */\n connect(sessionId?: string, options?: ConnectOptions): Promise<string> {\n return new Promise<string>(async (resolve, reject) => {\n if (!options?.resume) this.lastSeq = -1;\n\n const token = this.getToken?.();\n const queryParts: string[] = [];\n if (token) queryParts.push(`access_token=${encodeURIComponent(token)}`);\n // Only attach lastSeq when we are actually resuming a known session,\n // otherwise the server has nothing to replay from.\n if (sessionId && this.lastSeq >= 0) {\n queryParts.push(`lastSeq=${this.lastSeq}`);\n }\n // The turn we are still waiting on: a server that cannot continue it says so, instead of silence.\n if (sessionId && options?.resume && options.openInteractionId) {\n queryParts.push(`openInteraction=${encodeURIComponent(options.openInteractionId)}`);\n }\n const querySuffix = queryParts.length > 0 ? `?${queryParts.join('&')}` : '';\n // Hosts pass `baseUrl` as the HTTP origin of the backend\n // (`AgentGatewayService.ping()` calls fetch() against it). The\n // WebSocket constructor only accepts ws:// or wss://, so convert\n // here. Empty baseUrl leaves the relative URL alone — the browser\n // will resolve it against the current page (useful when a reverse\n // proxy fronts both schemes on the same origin).\n const wsBase = this.baseUrl\n .replace(/^http:\\/\\//, 'ws://')\n .replace(/^https:\\/\\//, 'wss://');\n const wsUrl = `${wsBase}/ws/connect/${sessionId ?? ''}${querySuffix}`;\n // Avoid logging the access_token query string.\n console.log('[WebSocket] Connecting to', `${wsBase}/ws/connect/${sessionId ?? ''}` +\n (sessionId && this.lastSeq >= 0 ? ` (resume lastSeq=${this.lastSeq})` : ''));\n // Tear down any lingering previous socket before allocating a new one, handlers\n // first: a late close of the old socket must not be reported as the new one's.\n this.detachSocket();\n this.ws = new WebSocket(wsUrl);\n\n this.ws.onopen = () => {\n // The upgrade succeeded — NOT yet a connection. The server can accept the socket\n // and close it a few milliseconds later (a session it no longer knows closes with\n // 1001). The consumer hears about the open when the Pong brings the session id.\n console.log('[WebSocket] Socket open — waiting for the session id');\n this.ping();\n this.monitor();\n };\n\n this.ws.onmessage = (event) => {\n try {\n this.lastActivity = new Date().getTime();\n // Any inbound frame answers an outstanding Ping — see the heartbeat notes above.\n this.pingSentAt = null;\n const streamingResponse = this.streamingResponseSerializer.parse(event.data);\n if (!streamingResponse)\n throw \"Error parsing event JSON\";\n\n this.handleMessage(streamingResponse, event.data);\n } catch (error) {\n console.error('[WebSocket] Error parsing message:', error);\n }\n };\n\n this.ws.onerror = (error) => {\n console.error('[WebSocket] Error:', error);\n // Do not reject here — `onclose` always fires after `onerror`, and the wait loop\n // below turns it into the rejection.\n if (this.onError) this.onError('WebSocket error');\n };\n\n this.ws.onclose = (event) => {\n console.log(`[WebSocket] Closed: code=${event.code} reason=\"${event.reason}\" ` +\n `(session ${this.sessionLabel}, lastSeq=${this.lastSeq})`);\n // Stop the heartbeat for the dead socket — a new monitor will\n // be started by `onopen` on the replacement socket.\n if (this.monitorInterval) {\n clearInterval(this.monitorInterval);\n this.monitorInterval = null;\n }\n this.pingSentAt = null;\n this.sessionId = undefined;\n // Every close is reported, with its code: the supervisor's policy needs the\n // code, and it tells a dial that died from a connection that dropped by\n // whether this promise had already resolved.\n this.onClose?.(event.code, event.reason);\n };\n\n // Wait for the server's first Pong, which carries the sessionId.\n // Phase-aware instead of a single flat timeout:\n // CONNECTING — a scale-to-zero server holds the TCP/upgrade while the\n // instance boots, so be patient. Aborting here (the old flat 4s\n // timeout) tore down a dial that was about to succeed, which is\n // exactly the cold-start \"first attempt fails, second works\"\n // pattern — and each abort+redial multiplied connection attempts.\n // OPEN — the Pong answers the ping we send in onopen, so a short\n // budget is enough once the socket is up.\n // CLOSED/CLOSING — fail immediately; this socket will never deliver\n // a sessionId, and sitting out the timer just delays the supervisor\n // (and the user-facing state) for nothing.\n const waitTime = 200;\n const connectingTimeoutMs = 30_000;\n const openTimeoutMs = 8_000;\n const socket = this.ws;\n this.sessionId = undefined;\n let waitedMs = 0;\n let openWaitedMs = 0;\n for (;;) {\n // Checked BEFORE the session id: `this.sessionId` is shared, so a newer dial's\n // Pong would otherwise resolve this superseded one with the new socket's session.\n if (this.ws !== socket) {\n reject(\"Connection attempt superseded by a newer connect()\");\n return;\n }\n if (this.sessionId) break;\n if (socket.readyState === WebSocket.CLOSING || socket.readyState === WebSocket.CLOSED) {\n reject(\"Connection closed before a session id was received\");\n return;\n }\n if (socket.readyState === WebSocket.CONNECTING && waitedMs >= connectingTimeoutMs) {\n // Abort the stuck dial so it can't complete later and leak.\n try { socket.close(); } catch { /* already closing */ }\n reject(`Server did not accept the connection within ${connectingTimeoutMs / 1000}s`);\n return;\n }\n if (socket.readyState === WebSocket.OPEN && openWaitedMs >= openTimeoutMs) {\n reject(`Connected but no session id arrived within ${openTimeoutMs / 1000}s`);\n return;\n }\n if (waitedMs % 2000 === 0) console.log(\"Aguardando session Id\");\n await this.sleep(waitTime);\n waitedMs += waitTime;\n if (socket.readyState === WebSocket.OPEN) openWaitedMs += waitTime;\n }\n\n // PROVEN: the server answered with a session id. Only now does the consumer learn\n // the socket is up.\n console.log(`[WebSocket] Session ${this.sessionId} proven` +\n `${this.lastSeq >= 0 ? ` (replaying from lastSeq=${this.lastSeq})` : ''}.`);\n this.lastKnownSessionId = this.sessionId;\n this.onOpen?.();\n this.flushPendingAnswers(this.sessionId);\n resolve(this.sessionId);\n });\n }\n\n /** Drop the current socket without reporting it: handlers off, then close. */\n private detachSocket(): void {\n if (!this.ws) return;\n this.ws.onopen = null;\n this.ws.onmessage = null;\n this.ws.onerror = null;\n this.ws.onclose = null;\n try { this.ws.close(); } catch { /* already closing */ }\n this.ws = null;\n }\n\n async sleep(ms: number) {\n return new Promise(resolve => setTimeout(resolve, ms));\n }\n\n /** The session this instance believes it is on — for log lines, never for logic. */\n private get sessionLabel(): string {\n return this.sessionId ?? this.lastKnownSessionId ?? 'none';\n }\n\n /**\n * Handle incoming messages from server\n */\n handleMessage(streamingResponse: StreamingResponse, rawData: string) {\n // Track the highest server-assigned sequence number we have processed.\n // The server populates `seq` on every event coming out of an InteractionRun;\n // we ship it back as `?lastSeq=N` on reconnect so missed events are replayed.\n if (typeof streamingResponse.seq === 'number' && streamingResponse.seq > this.lastSeq) {\n this.lastSeq = streamingResponse.seq;\n }\n\n switch (streamingResponse.type) {\n case 'Pong':\n this.sessionId = streamingResponse.sessionId;\n this.lastKnownSessionId = streamingResponse.sessionId ?? this.lastKnownSessionId;\n\n if (!streamingResponse.sessionId) {\n console.error(\"Pong response has no SESSION ID\")\n return;\n }\n\n // Server-side WS auto-refresh: when the WS upgrade rode an expired\n // (or near-expiry) JWT, the server mints a fresh one and piggybacks\n // it on the next few Pong frames. Mirror it into the stored user so\n // the global fetch interceptor at packages/dashboard-app/.../EnvisionAuthProvider.tsx\n // stops sending the stale token. The token is delivered N times for\n // listener-readiness redundancy, so dedupe on equality.\n if (streamingResponse.accessToken) {\n this.persistRefreshedAccessToken(streamingResponse.accessToken);\n }\n\n break;\n case 'Suspended':\n // Heartbeat response\n if (this.onSuspended)\n this.onSuspended()\n break;\n\n case 'Event':\n //Do nothing we always process the event data if available\n break;\n case 'InteractionStarted': {\n // A turn announcing itself (AIA Issue 1548) — possibly one this tab did not send. No event rides it.\n const start = interactionStartFromFrame(streamingResponse);\n if (start) this.onInteractionStarted?.(start);\n else console.warn('[WebSocket] InteractionStarted frame without an interaction id');\n break;\n }\n case 'RewindLost':\n // The server's in-memory replay buffer didn't reach back as far as\n // our `lastSeq`. Reset our cursor to the new starting seq the server\n // is about to deliver from, and let the consumer purge any partial\n // streaming UI for this session.\n console.warn(\n `[WebSocket] RewindLost: lost events on resume, resuming from seq=${streamingResponse.seq}`\n );\n if (typeof streamingResponse.seq === 'number') {\n // Reset to one BELOW the new starting seq so that as we receive\n // the next event (the one with seq === resumingFromSeq) it is\n // not skipped by our `> lastSeq` guard above.\n this.lastSeq = streamingResponse.seq - 1;\n }\n if (this.onRewindLost && streamingResponse.sessionId) {\n this.onRewindLost(streamingResponse.sessionId, streamingResponse.seq ?? -1);\n }\n break;\n default:\n console.warn('[WebSocket] Unknown message type:', streamingResponse.type);\n }\n\n // A frame is either control (handled above) or carries one LlmEvent — as the full\n // `event`, or narrowed to `pe` for a delta. The decoder widens the latter back.\n const llmEvent = llmEventFromFrame(streamingResponse);\n if (llmEvent) {\n if (carriesContent(llmEvent)) {\n this.emitFirstToken(llmEvent.interactionId);\n }\n this.handleEvent(llmEvent, rawData);\n return llmEvent;\n }\n return null;\n }\n\n protected emitFirstToken(interactionId?: string) {\n if (!interactionId || this.firstTokenInteractions.has(interactionId)) return;\n this.statsTracker.resetForInteraction();\n this.firstTokenInteractions.add(interactionId);\n this.onFirstToken?.(interactionId);\n }\n\n /**\n * Mirror a server-side-refreshed JWT into the stored user record so the global\n * fetch interceptor (packages/dashboard-app/.../EnvisionAuthProvider.tsx) picks\n * it up on the next HTTP call. Idempotent — the same token is delivered on\n * multiple consecutive Pong frames for listener-readiness, and we only write\n * when it actually changed.\n *\n * Uses the same localStorage key the auth provider reads (`envision_user`).\n * Done here in the WS layer rather than via a callback so consumers don't need\n * to wire up token-handling boilerplate; React contexts that hold the user in\n * memory will pick up the new token on the next refresh/render or via their\n * own storage listeners.\n */\n private persistRefreshedAccessToken(newToken: string): void {\n const AUTH_STORAGE_KEY = 'envision_user';\n try {\n const raw = localStorage.getItem(AUTH_STORAGE_KEY);\n if (!raw) {\n console.warn('[WebSocket] WS-refreshed token received but no stored user — dropping');\n return;\n }\n const stored = JSON.parse(raw);\n if (stored?.access_token === newToken) return; // dedupe N-times redelivery\n\n stored.access_token = newToken;\n localStorage.setItem(AUTH_STORAGE_KEY, JSON.stringify(stored));\n console.info('[WebSocket] Mirrored WS-refreshed JWT into stored user');\n } catch (err) {\n console.error('[WebSocket] Failed to persist WS-refreshed token', err);\n }\n }\n\n closeStream() {\n this.disconnect();\n }\n\n suspendStream() {\n this.sendBaseMessage({\n Action: ChatAction.Suspend,\n AgentId: \"\",\n InteractionId: \"\",\n ModelId: \"\"\n })\n }\n\n /**\n * Send the user's answer to a parked ask_user tool call (ChatAction.AnswerHumanTool).\n *\n * Never throws on a dead socket: the parked tool answer is the one message whose loss\n * strands the whole turn (the askauth popup case — the socket idles out while the user\n * is at the IdP, the token comes back, and a plain send would throw into an unhandled\n * rejection with the answer gone). When the socket is not OPEN the answer is queued and\n * flushed by `onopen` on the next (re)connect of the same session.\n *\n * Returns 'sent' when it went out now, 'queued' when it will go out on reconnect.\n */\n answerHumanTool(toolCallId: string, answer: string): 'sent' | 'queued' {\n const message: IMessageBase = {\n Action: ChatAction.AnswerHumanTool,\n AgentId: \"\",\n InteractionId: \"\",\n ToolCallId: toolCallId,\n Answer: answer,\n };\n if (this.ws && this.ws.readyState === WebSocket.OPEN) {\n try {\n this.sendBaseMessage(message);\n return 'sent';\n } catch {\n // Raced a close between the readyState check and the send — fall through to queue.\n }\n }\n this.queueAnswer(toolCallId, answer);\n return 'queued';\n }\n\n private queueAnswer(toolCallId: string, answer: string): void {\n // Last answer wins per tool call (a retry must not deliver a stale answer first).\n this.pendingAnswers = this.pendingAnswers.filter(p => p.toolCallId !== toolCallId);\n this.pendingAnswers.push({ sessionId: this.sessionId ?? this.lastKnownSessionId, toolCallId, answer });\n console.warn(`[WebSocket] Socket not open — queued answer for tool call ${toolCallId}; will flush on reconnect.`);\n }\n\n private flushPendingAnswers(connectedSessionId?: string): void {\n if (this.pendingAnswers.length === 0) return;\n const pending = this.pendingAnswers;\n this.pendingAnswers = [];\n for (const entry of pending) {\n // An answer stamped for a DIFFERENT session is undeliverable from this socket\n // (single-attach policy) — drop it loudly rather than misroute it.\n if (entry.sessionId && connectedSessionId && entry.sessionId !== connectedSessionId) {\n console.warn(`[WebSocket] Dropping queued answer for tool call ${entry.toolCallId} — it belongs to session ${entry.sessionId}, reconnected to ${connectedSessionId}.`);\n continue;\n }\n try {\n this.sendBaseMessage({\n Action: ChatAction.AnswerHumanTool,\n AgentId: \"\",\n InteractionId: \"\",\n ToolCallId: entry.toolCallId,\n Answer: entry.answer,\n });\n console.info(`[WebSocket] Flushed queued answer for tool call ${entry.toolCallId}.`);\n } catch {\n this.pendingAnswers.push(entry); // socket died again — keep it for the next open\n }\n }\n }\n\n /**\n * Send a message to the agent\n */\n sendMessage(message: IMessage): void {\n this.sendBaseMessage(message);\n }\n\n sendBaseMessage(message: IMessageBase): void {\n this.lastActivity = new Date().getTime();\n if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {\n throw new Error('WebSocket is not connected');\n }\n\n this.ws.send(JSON.stringify(message));\n }\n\n /**\n * Heartbeat: keep a quiet socket alive with a Ping every PING_INTERVAL_MS, and\n * declare it dead when a Ping goes PONG_TIMEOUT_MS without ANY inbound frame.\n * Started by `onopen`, stopped by `onclose`/`disconnect()`.\n */\n monitor() {\n if (this.monitorInterval) clearInterval(this.monitorInterval);\n this.monitorInterval = setInterval(() => {\n try {\n if (!this.isConnected()) return;\n const now = Date.now();\n if (this.pingSentAt !== null) {\n const waited = now - this.pingSentAt;\n if (waited >= PONG_TIMEOUT_MS) {\n this.failSocket(HEARTBEAT_TIMEOUT_CODE,\n `No frame received for ${Math.round(waited / 1000)}s after a Ping`);\n return;\n }\n // The socket is ABOUT to be declared dead. Only ever a line or two per\n // episode (the tick is 5s, the budget 10s), and it is the warning the\n // console never gave before: from here, either a frame arrives or the\n // next tick kills the socket.\n console.warn(`[WebSocket] Still no reply ${waited}ms after the Ping ` +\n `(budget ${PONG_TIMEOUT_MS}ms, session ${this.sessionLabel}) — the peer may be gone.`);\n return;\n }\n if (now - this.lastActivity >= PING_INTERVAL_MS) this.ping();\n }\n catch (error) {\n console.error(\"Error on monitor\", error);\n }\n }, MONITOR_TICK_MS);\n }\n\n /**\n * Send a heartbeat ping and start the reply clock (unless one is already running).\n */\n ping(): void {\n this.sendBaseMessage({\n Action: \"Ping\",\n AgentId: \"\",\n InteractionId: \"\",\n ModelId: \"\"\n });\n if (this.pingSentAt === null) {\n this.pingSentAt = Date.now();\n console.log(`[WebSocket] Ping sent after ${Date.now() - this.lastActivity}ms of silence ` +\n `(session ${this.sessionLabel}); any frame within ${PONG_TIMEOUT_MS}ms answers it.`);\n }\n }\n\n /**\n * Behave as if the peer vanished: the socket is closed and reported as an abnormal close (1006),\n * exactly the path the heartbeat's dead-peer verdict takes. For demos and tests of the resume —\n * the supervisor redials with the replay cursor and the server replays what it buffered — on a\n * server that is still running; a real drop needs a cable pulled.\n */\n simulateDrop(): void {\n this.failSocket(1006, 'Simulated drop');\n }\n\n /**\n * Declare the current socket dead and run the close path NOW, without waiting\n * for the browser: for a half-open peer `onclose` can lag by minutes or never\n * come, and the decision has already been made. The dead socket's own onclose\n * handler is invoked with a client-local code, so the consumer sees exactly\n * what a server close would have produced. Handlers are detached first so a\n * late real close event cannot run it a second time.\n */\n private failSocket(code: number, reason: string): void {\n const socket = this.ws;\n if (!socket) return;\n console.warn(`[WebSocket] ${reason} — treating the socket as dead (code=${code}, ` +\n `session ${this.sessionLabel}). readyState was ${socket.readyState} (OPEN=${WebSocket.OPEN}), ` +\n `which is why nothing else noticed. Running the close path now.`);\n const onclose = socket.onclose;\n socket.onopen = null;\n socket.onmessage = null;\n socket.onerror = null;\n socket.onclose = null;\n try { socket.close(); } catch { /* already closing */ }\n onclose?.call(socket, { code, reason } as CloseEvent);\n }\n\n /**\n * Disconnect the WebSocket\n */\n disconnect(): void {\n console.log(`[WebSocket] disconnect() (session ${this.sessionLabel})`);\n if (this.monitorInterval) {\n clearInterval(this.monitorInterval);\n this.monitorInterval = null;\n }\n\n this.pingSentAt = null;\n this.firstTokenInteractions.clear();\n this.lastKnownSessionId = undefined;\n // Reset the resume cursor — the next connect is a fresh session by definition.\n this.lastSeq = -1;\n if (this.ws) {\n this.ws.close(APPLICATION_CLOSED_CODE, 'Intentional disconnect');\n this.ws = null;\n }\n }\n\n /**\n * Check if connected\n */\n isConnected(): boolean {\n return this.ws !== null && this.ws.readyState === WebSocket.OPEN;\n }\n\n async handleEvent(llmEvent: LlmEvent, rawData: string): Promise<void> {\n // An account notice (BillingLimit) is session state, not part of any turn — a connect notice has no interaction\n // at all. Hand it over and stop: it must never reach the interaction router.\n const billing = llmEvent.content?.items?.find((item) => item instanceof BillingLimitContent) as BillingLimitContent | undefined;\n if (billing) {\n this.onBillingLimit?.({\n plan: billing.plan ?? 'team',\n state: billing.state ?? 'ok',\n used: billing.used ?? 0,\n included: billing.included ?? 0,\n limitReached: billing.limitReached ?? false,\n canManage: billing.canManage ?? false,\n title: billing.title,\n message: billing.message,\n actionUrl: billing.actionUrl,\n interactionId: llmEvent.interactionId || undefined,\n });\n return;\n }\n try {\n const serverEvent = ServerEvent.parseFromTypedEvent(llmEvent)\n if (!serverEvent)\n throw \"Server event was null\";\n\n this.statsTracker.record({\n rawLength: rawData.length,\n textLength: llmEvent.text?.length ?? 0,\n sessionInformation: serverEvent.session_information,\n fromDetachedRun: !!serverEvent.detachedRunId,\n });\n\n if (this.onEvent) {\n this.onEvent(serverEvent)\n .catch((error) => {\n console.error(\"Lost error on on-event\", error)\n })\n }\n }\n catch (error) {\n console.error(\"handleEvent error\", error)\n }\n }\n\n}\n","import type { Artifact } from '../models/Artifact';\nimport type { IArtifactService } from './interfaces/artifactService';\nimport { resolveAccessToken, type AccessTokenProvider } from './accessTokenProvider';\n\n/**\n * Minimal IArtifactService for the replay demo. The replay path doesn't\n * generate artifacts — every persisted FunctionResultContent carries its\n * own payload — so most operations are in-memory pass-throughs. Hosts\n * that need full artifact handling supply their own implementation.\n */\nexport class HttpArtifactService implements IArtifactService {\n private cache = new Map<string, Artifact>();\n private serverBaseUrl: string;\n private accessToken: AccessTokenProvider;\n\n constructor(serverBaseUrl: string, accessToken: AccessTokenProvider) {\n this.serverBaseUrl = serverBaseUrl.replace(/\\/$/, '');\n this.accessToken = accessToken;\n }\n\n private get headers(): HeadersInit {\n return { Authorization: `Bearer ${resolveAccessToken(this.accessToken)}` };\n }\n\n async init(): Promise<void> { /* nothing to load up front */ }\n\n getArtifacts(): Artifact[] {\n return Array.from(this.cache.values());\n }\n\n async saveArtifact(artifact: Artifact): Promise<void> {\n this.cache.set(artifact.id, artifact);\n }\n\n saveArtifactToCache(artifact: Artifact): void {\n this.cache.set(artifact.id, artifact);\n }\n\n async deleteArtifact(artifactId: string): Promise<void> {\n this.cache.delete(artifactId);\n }\n\n addToCache(artifact: Artifact): void {\n this.cache.set(artifact.id, artifact);\n }\n\n getArtifactWithCache(artifactId: string): Artifact | null {\n return this.cache.get(artifactId) ?? null;\n }\n\n async getArtifact(artifactId: string, _useCache?: boolean): Promise<Artifact | null> {\n if (this.cache.has(artifactId)) return this.cache.get(artifactId) ?? null;\n try {\n const r = await fetch(`${this.serverBaseUrl}/AdminArtifact/${artifactId}`, {\n headers: this.headers,\n });\n if (!r.ok) return null;\n const a = (await r.json()) as Artifact;\n this.cache.set(a.id, a);\n return a;\n } catch {\n return null;\n }\n }\n\n async clearAllArtifacts(): Promise<void> {\n this.cache.clear();\n }\n\n async getFileContent(url: string): Promise<string | null> {\n try {\n const r = await fetch(url, { headers: this.headers });\n return r.ok ? await r.text() : null;\n } catch {\n return null;\n }\n }\n}\n","/**\n * Following a detached run's frames over server-sent events (AIA Issue 1548, phase 5).\n *\n * The SDK serves `GET {baseUrl}/detached-runs/{id}/frames?afterSeq=N` as `text/event-stream`: one event per frame —\n * `id: {seq}` + `data: {the frame exactly as the chat socket sends it}` — plus `event: end` + `data: {its seq}` for\n * every turn's end marker, and `: alive` comments in between to keep proxies from idling the request out.\n *\n * <p><b>An `end` event is advisory; the CLOSE is what ends the stream.</b> A resumed run's turns all live in one\n * session, each closed by its own end marker, and the server relays every one of them — it closes the response only\n * after an end that is the last thing saved for a run no longer active. So the reader records an end's seq (a\n * reconnect then asks from after it), keeps reading into the next turn, and decides on the close: a body that finished\n * right after an end is over; one that finished after frames past the last end (or with no end at all) dropped, and is\n * reconnected. Stopping at the first end froze a run opened in its second turn at the end of its first.</p>\n *\n * <p><b>`fetch`, not `EventSource`.</b> The route is behind a bearer token, and `EventSource` cannot send an\n * `Authorization` header. So the body is read as a stream and parsed here, and the reconnect `EventSource` would have\n * done is done here too: a connection that drops anywhere but right after an `end` is reopened from the last seq it delivered, on a bounded\n * backoff, until the caller aborts.</p>\n *\n * <p><b>The HTTP layer is the host's to supply.</b> A host with its own auth (a refresh on 401, a tenant header) passes\n * a fetch-compatible `fetchImpl`; a host with only a token passes `getToken`. Both may be given — the token is set as\n * the `Authorization` header and the host's fetch may override it.</p>\n *\n * <p><b>A 401 gets one second chance.</b> A long follow outlives a token: on a 401 the reader asks the host's\n * `onUnauthorized` to refresh (true ⇒ retry), or else re-reads `getToken` and retries if the token changed. A second\n * 401 in a row is final.</p>\n */\n\n/** The slice of `fetch` the reader uses. A host's authenticated wrapper around `window.fetch` fits it. */\nexport type DetachedRunFetch = (input: string, init: RequestInit) => Promise<Response>;\n\nexport interface DetachedRunFramesRetry {\n /** First delay after a dropped connection. Default 500 ms. */\n initialMs?: number;\n /** The ceiling the doubling stops at. Default 15 s. */\n maxMs?: number;\n /** Consecutive failed attempts before the reader gives up and rejects. Default: never gives up. */\n maxAttempts?: number;\n}\n\nexport interface StreamDetachedRunFramesOptions {\n /** The agents server the run lives on (the same base URL the chat socket dials). */\n baseUrl: string;\n /** The run — or, with `resource: 'session'`, the session — whose frames to follow. */\n runId: string;\n /**\n * Whose frames: a detached run's (`GET /detached-runs/{id}/frames`, the default) or a shared session's\n * (`GET /sessions/{id}/frames`, AIA Issue 1587). A session's stream has no last turn — the server never ends it —\n * so every close is a drop and is reconnected, and `onEnd` never fires.\n */\n resource?: 'detachedRun' | 'session';\n /** The HTTP layer. Default: the global `fetch`. */\n fetchImpl?: DetachedRunFetch;\n /** The bearer token, read before EVERY request so a refreshed token is picked up on a reconnect. */\n getToken?: () => string | undefined | null | Promise<string | undefined | null>;\n /** Deliver frames after this seq. Default 0 (the run's whole history). */\n afterSeq?: number;\n /** Stops the reader — the open request is cancelled and the promise resolves `aborted`. */\n signal?: AbortSignal;\n /** One frame, parsed from its `data:` JSON, with its seq (`id:`). Frames at or below the cursor are skipped. */\n onFrame: (frame: unknown, seq: number | undefined) => void;\n /**\n * The run's stream is over — the server closed it right after an `event: end` — and nothing will follow until the\n * run is resumed. An end the server keeps streaming past (a finished turn of a run still going) does not fire it.\n */\n onEnd?: (lastSeq: number) => void;\n /** A request was answered with a stream (every successful (re)connect). */\n onOpen?: () => void;\n /**\n * A request was answered 401. Refresh the credentials and resolve true to retry once with a fresh `getToken`;\n * false (or no hook) retries only when `getToken` already returns a different token.\n */\n onUnauthorized?: () => Promise<boolean>;\n /** A connection failed or dropped and will be retried in `retryInMs`. */\n onRetry?: (error: unknown, attempt: number, retryInMs: number) => void;\n retry?: DetachedRunFramesRetry;\n}\n\nexport interface DetachedRunFramesResult {\n /** `end`: the server closed the stream right after an end marker; `aborted`: the caller stopped it. */\n reason: 'end' | 'aborted';\n /** The highest seq delivered, end markers included — where a later follow resumes. */\n lastSeq: number;\n}\n\n/** An answer no retry will change: the run is not there, or the caller may not see it. */\nexport class DetachedRunFramesHttpError extends Error {\n constructor(public readonly status: number, message?: string) {\n super(message ?? `GET detached-run frames answered ${status}`);\n this.name = 'DetachedRunFramesHttpError';\n }\n}\n\n/** Why following a run stopped for good — what a page tells the reader. */\nexport interface DetachedRunFollowError {\n /** `notFound` 404/410 · `forbidden` 403 · `unauthorized` 401 (after the second chance) · `gaveUp` anything else. */\n kind: 'notFound' | 'forbidden' | 'gaveUp' | 'unauthorized';\n status?: number;\n cause?: unknown;\n}\n\n/** Classify what {@link streamDetachedRunFrames} rejected with. */\nexport function toDetachedRunFollowError(error: unknown): DetachedRunFollowError {\n if (error instanceof DetachedRunFramesHttpError) {\n const { status } = error;\n const kind = status === 401 ? 'unauthorized' : status === 403 ? 'forbidden' : status === 404 || status === 410 ? 'notFound' : 'gaveUp';\n return { kind, status, cause: error };\n }\n return { kind: 'gaveUp', cause: error };\n}\n\n/** One dispatched server-sent event. */\nexport interface SseEvent {\n event?: string;\n data: string;\n id?: string;\n}\n\n/**\n * A server-sent-events parser over text chunks that may split anywhere — mid-line, mid-field, between the `\\r` and\n * `\\n` of a CRLF. Fields per the HTML spec: `field: value` with one optional space after the colon, `data` lines joined\n * by `\\n`, a line starting with `:` is a comment, a blank line dispatches. An event with neither data nor a name is\n * dropped (that is what a lone comment block amounts to).\n */\nexport function createSseParser(onEvent: (event: SseEvent) => void): { push(chunk: string): void; flush(): void; idle(): boolean } {\n let buffer = '';\n let data: string[] = [];\n let eventName: string | undefined;\n let id: string | undefined;\n\n const dispatch = () => {\n if (data.length > 0 || eventName !== undefined)\n onEvent({ event: eventName, data: data.join('\\n'), id });\n data = [];\n eventName = undefined;\n id = undefined;\n };\n\n const line = (text: string) => {\n if (text === '') return dispatch();\n if (text.startsWith(':')) return;\n const colon = text.indexOf(':');\n const field = colon === -1 ? text : text.slice(0, colon);\n let value = colon === -1 ? '' : text.slice(colon + 1);\n if (value.startsWith(' ')) value = value.slice(1);\n if (field === 'data') data.push(value);\n else if (field === 'event') eventName = value;\n else if (field === 'id') id = value;\n };\n\n return {\n push(chunk: string) {\n buffer += chunk;\n for (;;) {\n const newline = buffer.search(/\\r\\n|\\r|\\n/);\n if (newline === -1) return;\n // A lone `\\r` at the very end may be the first half of a CRLF still in flight.\n if (buffer[newline] === '\\r' && newline === buffer.length - 1) return;\n const width = buffer.startsWith('\\r\\n', newline) ? 2 : 1;\n line(buffer.slice(0, newline));\n buffer = buffer.slice(newline + width);\n }\n },\n /** Nothing half-received: no partial line buffered, no event begun and not yet dispatched. */\n idle() {\n return buffer === '' && data.length === 0 && eventName === undefined && id === undefined;\n },\n flush() {\n // A stream that ends mid-event never dispatches it (the spec's rule); only a complete trailing line counts.\n if (buffer !== '') line(buffer.replace(/\\r$/, ''));\n buffer = '';\n },\n };\n}\n\nfunction retryable(status: number): boolean {\n return status >= 500 || status === 408 || status === 429;\n}\n\nfunction sleep(ms: number, signal?: AbortSignal): Promise<void> {\n return new Promise((resolve) => {\n if (signal?.aborted) return resolve();\n const timer = setTimeout(done, ms);\n function done() {\n clearTimeout(timer);\n signal?.removeEventListener('abort', done);\n resolve();\n }\n signal?.addEventListener('abort', done, { once: true });\n });\n}\n\nfunction framesUrl(baseUrl: string, resource: 'detachedRun' | 'session', id: string, afterSeq: number): string {\n const collection = resource === 'session' ? 'sessions' : 'detached-runs';\n return `${baseUrl.replace(/\\/+$/, '')}/${collection}/${encodeURIComponent(id)}/frames?afterSeq=${afterSeq}`;\n}\n\n/**\n * Follow a detached run's frames until the server ends the stream or `signal` aborts. Resolves with why it stopped\n * and the last seq delivered; rejects with {@link DetachedRunFramesHttpError} for an answer a retry will not change\n * (4xx other than 408/429), or with the last error once `retry.maxAttempts` consecutive attempts failed.\n */\nexport async function streamDetachedRunFrames(options: StreamDetachedRunFramesOptions): Promise<DetachedRunFramesResult> {\n const { baseUrl, runId, signal, onFrame, onEnd, onOpen, onRetry } = options;\n const resource = options.resource ?? 'detachedRun';\n const fetchImpl: DetachedRunFetch = options.fetchImpl ?? ((input, init) => fetch(input, init));\n const initialMs = options.retry?.initialMs ?? 500;\n const maxMs = options.retry?.maxMs ?? 15_000;\n const maxAttempts = options.retry?.maxAttempts ?? Number.POSITIVE_INFINITY;\n let lastSeq = options.afterSeq ?? 0;\n let attempt = 0;\n // Set after a 401 earned its one retry; cleared by the next request that is not a 401.\n let authRetried = false;\n\n /** After a 401: may the next request carry better credentials? */\n async function secondChance(usedToken: string | undefined): Promise<boolean> {\n if (options.onUnauthorized) {\n try {\n if (await options.onUnauthorized()) return true;\n } catch (error) {\n console.warn(`[DetachedRunFrames] run ${runId}: onUnauthorized threw`, error);\n }\n }\n if (!options.getToken) return false;\n const fresh = (await options.getToken()) ?? undefined;\n return !!fresh && fresh !== usedToken;\n }\n\n while (!signal?.aborted) {\n let failure: unknown;\n try {\n const headers: Record<string, string> = { Accept: 'text/event-stream' };\n const token = (await options.getToken?.()) ?? undefined;\n if (token) headers.Authorization = `Bearer ${token}`;\n\n const response = await fetchImpl(framesUrl(baseUrl, resource, runId, lastSeq), { method: 'GET', headers, signal, cache: 'no-store' });\n if (response.status === 401) {\n if (!authRetried && await secondChance(token)) {\n authRetried = true;\n continue;\n }\n throw new DetachedRunFramesHttpError(401);\n }\n authRetried = false;\n if (!response.ok) {\n if (!retryable(response.status)) throw new DetachedRunFramesHttpError(response.status);\n throw new Error(`GET detached-run frames answered ${response.status}`);\n }\n if (!response.body) throw new DetachedRunFramesHttpError(response.status, 'The frames response has no readable body');\n onOpen?.();\n\n // Whether the last event this connection delivered was an end marker: true when the body finishes ⇒ over.\n let atEnd = false;\n const parser = createSseParser((event) => {\n if (event.event === 'end') {\n // Advisory: the server may stream on into the next turn. Its seq moves the cursor, so a reconnect\n // asks from after it and the server does not relay it again.\n const endSeq = Number(event.data);\n if (event.data !== '' && Number.isFinite(endSeq) && endSeq > lastSeq) lastSeq = endSeq;\n atEnd = true;\n return;\n }\n if (event.event !== undefined && event.event !== 'message') return;\n if (event.data === '') return;\n const seq = event.id !== undefined && event.id !== '' ? Number(event.id) : undefined;\n if (seq !== undefined && Number.isFinite(seq)) {\n // A reconnect asks from the cursor, but a server that replays one too many must not double a delta.\n if (seq <= lastSeq) return;\n lastSeq = seq;\n }\n // A new frame past the last end: the turn goes on, and a close from here on is a drop.\n atEnd = false;\n let frame: unknown;\n try {\n frame = JSON.parse(event.data);\n } catch (error) {\n console.warn(`[DetachedRunFrames] run ${runId}: a frame that is not JSON was skipped (seq ${event.id ?? '?'})`, error);\n return;\n }\n // Progress: the next failure starts the backoff over.\n attempt = 0;\n try {\n onFrame(frame, seq);\n } catch (error) {\n console.error(`[DetachedRunFrames] run ${runId}: onFrame threw on seq ${event.id ?? '?'}`, error);\n }\n });\n\n const reader = response.body.getReader();\n const decoder = new TextDecoder();\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n parser.push(decoder.decode(value, { stream: true }));\n }\n parser.push(decoder.decode());\n // An event cut off by the close was the server still writing: whatever came before it, that is a drop.\n if (!parser.idle()) atEnd = false;\n parser.flush();\n } finally {\n reader.releaseLock?.();\n }\n\n if (atEnd && resource !== 'session') {\n onEnd?.(lastSeq);\n return { reason: 'end', lastSeq };\n }\n // Frames after the last end, or no end at all: the connection dropped mid-turn. A session's stream has no\n // last end — its close is always a drop (a proxy's idle cut, the server's request timeout).\n failure = new Error(resource === 'session' ? 'The session frames stream closed' : 'The frames stream closed before its end event');\n } catch (error) {\n if (signal?.aborted) break;\n if (error instanceof DetachedRunFramesHttpError) throw error;\n failure = error;\n }\n\n attempt += 1;\n if (attempt >= maxAttempts) throw failure;\n const delay = Math.min(initialMs * 2 ** (attempt - 1), maxMs);\n try { onRetry?.(failure, attempt, delay); } catch { /* a host's logger must not stop the follow */ }\n await sleep(delay, signal);\n }\n\n return { reason: 'aborted', lastSeq };\n}\n","import { ServerEvent } from '@lib/models/ServerEvent';\nimport type { InteractionStart, InteractionStatistics, StreamingResponse } from '@lib/models/semanticKernelModel/models';\nimport { createStreamingResponseSerializer } from '@lib/models/semanticKernelModel/serializer';\nimport { carriesContent, interactionStartFromFrame, llmEventFromFrame } from '../wire/decodeFrame';\nimport { SESSION_NOT_FOUND_CODE } from '../WebSocketConnection/closeCodes';\nimport type { ConnectOptions, IMessage, IWebSocketConnection } from '../WebSocketConnection/webSocketConnection';\nimport {\n streamDetachedRunFrames,\n toDetachedRunFollowError,\n type DetachedRunFetch,\n type DetachedRunFollowError,\n type DetachedRunFramesRetry,\n} from './streamDetachedRunFrames';\n\nexport interface DetachedRunFramesTransportOptions {\n /** The agents server the run lives on. */\n baseUrl: string;\n fetchImpl?: DetachedRunFetch;\n getToken?: () => string | undefined | null | Promise<string | undefined | null>;\n /** Refresh after a 401; true retries once (see `streamDetachedRunFrames`). */\n onUnauthorized?: () => Promise<boolean>;\n retry?: DetachedRunFramesRetry;\n /**\n * Whose frames `connect(id)` follows: a detached run's (default) or a shared session's (AIA Issue 1587) — see\n * `streamDetachedRunFrames`. A session's stream never ends, so {@link DetachedRunFramesTransport.onEnd} never fires.\n */\n resource?: 'detachedRun' | 'session';\n /**\n * Where a fresh `connect` starts following — read at that moment. A shared session's viewer draws the history\n * first (`GET /sessions/{id}`) and follows from its `lastSequence`, so it neither repeats nor misses a frame.\n * Default 0: the run's whole history.\n */\n initialAfterSeq?: () => number | undefined;\n}\n\n/**\n * A read-only {@link IWebSocketConnection} over a detached run's frames stream (AIA Issue 1548, phase 5) — what lets\n * the ordinary chat engine draw a run as a transcript, rendering exactly as the chat does.\n *\n * <p>`connect(runId)` follows `GET /detached-runs/{runId}/frames` and resolves with the run id once the server answers\n * with a stream; every frame then goes through the same decode as the socket's — `InteractionStarted` to\n * `onInteractionStarted`, everything else to `onEvent` as a `ServerEvent`. The reader reconnects a dropped stream from\n * the last seq on its own, so the gateway's supervisor sees one long connection; only an answer no retry will change\n * (404, 401/403) reaches it, as the close code it would have had on the socket.</p>\n *\n * <p>Nothing is ever sent: there is no prompt in a transcript. A turn's end marker the server streams past (a resumed\n * run going on into its next turn) is only a cursor move; {@link onEnd} fires when the server closes the stream right\n * after one. That end (the run stopped — it settled, or is waiting for an answer) is not a close either: the\n * transcript stays as it is, and {@link follow} picks the stream up again from the last seq when the host knows the\n * run moved on (it answered it).</p>\n */\nexport class DetachedRunFramesTransport implements IWebSocketConnection {\n onEvent?: (event: MessageEvent | ServerEvent) => Promise<void>;\n onError?: (error: string) => void;\n onOpen?: () => void;\n onFirstToken?: (interactionId: string) => void;\n onSuspended?: () => void;\n onClose?: (code: number, reason: string) => void;\n onNewPacket?: (stats: InteractionStatistics) => void;\n onInteractionStarted?: (start: InteractionStart) => void;\n /** The stream of the current follow is over: the server closed it right after an `event: end`. */\n onEnd?: (lastSeq: number) => void;\n /** Following stopped for good — the run is gone, forbidden, the credentials failed twice, or retries ran out. */\n onFollowError?: (error: DetachedRunFollowError) => void;\n\n private readonly options: DetachedRunFramesTransportOptions;\n private readonly serializer = createStreamingResponseSerializer();\n private readonly firstTokens = new Set<string>();\n private runId?: string;\n private controller: AbortController | null = null;\n private following = false;\n private lastSeq = 0;\n\n constructor(options: DetachedRunFramesTransportOptions) {\n this.options = options;\n }\n\n /** The highest seq delivered so far — where the next follow resumes. */\n get cursor(): number { return this.lastSeq; }\n\n /** Whether a follow is running (false after `end`, an abort or a fatal answer). */\n get isFollowing(): boolean { return this.following; }\n\n connect(runId?: string, options?: ConnectOptions): Promise<string> {\n if (!runId) return Promise.reject(new Error('DetachedRunFramesTransport: connect() needs the run id'));\n if (runId !== this.runId || !options?.resume) {\n this.lastSeq = this.options.initialAfterSeq?.() ?? 0;\n this.firstTokens.clear();\n }\n this.runId = runId;\n return this.start(runId);\n }\n\n /**\n * Follow again from the last seq — after the stream ended and the run was resumed (answered). A no-op while a\n * follow is running. Resolves once the server answers with the stream.\n */\n follow(): Promise<string> {\n if (!this.runId) return Promise.reject(new Error('DetachedRunFramesTransport: follow() before connect()'));\n if (this.following) return Promise.resolve(this.runId);\n return this.start(this.runId);\n }\n\n private start(runId: string): Promise<string> {\n this.controller?.abort();\n const controller = new AbortController();\n this.controller = controller;\n this.following = true;\n\n return new Promise<string>((resolve, reject) => {\n let opened = false;\n streamDetachedRunFrames({\n ...this.options,\n runId,\n afterSeq: this.lastSeq,\n signal: controller.signal,\n onOpen: () => {\n if (opened) return;\n opened = true;\n this.onOpen?.();\n resolve(runId);\n },\n onFrame: (frame, seq) => {\n if (typeof seq === 'number' && seq > this.lastSeq) this.lastSeq = seq;\n this.dispatch(frame);\n },\n onEnd: (lastSeq) => {\n this.lastSeq = Math.max(this.lastSeq, lastSeq);\n this.onEnd?.(this.lastSeq);\n },\n onRetry: (error, attempt, retryInMs) => {\n console.warn(`[DetachedRunFrames] run ${runId}: the stream failed (attempt ${attempt}); ` +\n `following again from seq ${this.lastSeq} in ${retryInMs}ms.`, error);\n },\n })\n .then(() => {\n if (!opened) reject(new Error('The frames stream stopped before it opened'));\n })\n .catch((error) => {\n const followError = toDetachedRunFollowError(error);\n const code = followError.kind === 'notFound' ? SESSION_NOT_FOUND_CODE\n : followError.kind === 'forbidden' || followError.kind === 'unauthorized' ? 1008\n : 1011;\n console.error(`[DetachedRunFrames] run ${runId}: following stopped (${followError.kind})`, error);\n try { this.onFollowError?.(followError); } catch (hostError) { console.error('[DetachedRunFrames] onFollowError threw', hostError); }\n this.onError?.(String(error?.message ?? error));\n // Reported as the socket would have closed, so the supervisor applies the same policy (a run that\n // is gone halts it, like a session that is gone); judged with the dial when it never opened.\n this.onClose?.(code, String(error?.message ?? ''));\n if (!opened) reject(error);\n })\n .finally(() => {\n if (this.controller === controller) this.following = false;\n });\n });\n }\n\n /** One frame, decoded exactly as the chat socket decodes it. A frame that fails to decode is skipped. */\n private dispatch(raw: unknown): void {\n let frame: StreamingResponse | undefined;\n try {\n frame = this.serializer.parse(raw as object);\n } catch (error) {\n console.warn('[DetachedRunFrames] a frame failed to decode', error);\n return;\n }\n if (!frame) return;\n\n const start = interactionStartFromFrame(frame);\n if (start) {\n this.onInteractionStarted?.(start);\n return;\n }\n\n const llmEvent = llmEventFromFrame(frame);\n if (!llmEvent) return;\n if (carriesContent(llmEvent) && llmEvent.interactionId && !this.firstTokens.has(llmEvent.interactionId)) {\n this.firstTokens.add(llmEvent.interactionId);\n this.onFirstToken?.(llmEvent.interactionId);\n }\n try {\n const serverEvent = ServerEvent.parseFromTypedEvent(llmEvent);\n this.onEvent?.(serverEvent).catch((error) => console.error('[DetachedRunFrames] onEvent failed', error));\n } catch (error) {\n console.error('[DetachedRunFrames] a frame could not be mapped to a server event', error);\n }\n }\n\n sendMessage(_message: IMessage): void {\n throw new Error('A detached-run transcript is read-only: answer the run through its own endpoint.');\n }\n\n suspendStream(): void { /* nothing to suspend: the run executes elsewhere */ }\n\n closeStream(): void {\n this.controller?.abort();\n this.controller = null;\n this.following = false;\n }\n\n isConnected(): boolean {\n return this.controller !== null;\n }\n}\n","import { EventType } from '@lib/models/enums';\nimport { ServerEvent } from '@lib/models/ServerEvent';\nimport type { TodoList } from '@lib/models/todoListModel';\nimport { createStreamingResponseSerializer } from '@lib/models/semanticKernelModel/serializer';\nimport { llmEventFromFrame } from '../wire/decodeFrame';\n\n/**\n * What one frame of a detached run says about its progress, as far as a task box reads it (AIA Issue 1548 §3b):\n * a tool it called, a piece of what it is writing, or its task list changing.\n */\nexport type DetachedRunActivitySignal =\n | { kind: 'tool'; name: string; interactionId: string }\n | { kind: 'text'; text: string; partial: boolean; interactionId: string }\n | { kind: 'todo'; todoList: TodoList };\n\n/** The tool event the agent emits whenever its task list changes; its data is the list as JSON. */\nexport const TODO_LIST_UPDATED_EVENT = 'todolistUpdated';\n\n/**\n * The progress signals in one frame of a run's stream, in order — decoded exactly as the chat decodes the frame.\n * Anything else (an announcement, reasoning, a tool's result) says nothing a one-line activity needs.\n */\nexport function readDetachedRunActivity(raw: unknown, serializer = createStreamingResponseSerializer()): DetachedRunActivitySignal[] {\n let event;\n try {\n const frame = serializer.parse(raw as object);\n const llmEvent = frame ? llmEventFromFrame(frame) : undefined;\n event = llmEvent ? ServerEvent.parseFromTypedEvent(llmEvent) : undefined;\n } catch {\n return [];\n }\n if (!event) return [];\n\n const signals: DetachedRunActivitySignal[] = [];\n for (const part of event.parts ?? []) {\n if (part.eventType === EventType.ToolEvent && part.toolDetails?.eventName === TODO_LIST_UPDATED_EVENT) {\n const todoList = parseTodoList(part.toolDetails.eventData);\n if (todoList) signals.push({ kind: 'todo', todoList });\n } else if ((part.eventType === EventType.FunctionCall || part.eventType === EventType.PartialFunctionCall) && part.functionDetails?.name) {\n signals.push({ kind: 'tool', name: part.functionDetails.name, interactionId: event.interactionId });\n } else if (part.eventType === EventType.Text && part.text) {\n signals.push({ kind: 'text', text: part.text, partial: !!event.partial, interactionId: event.interactionId });\n }\n }\n return signals;\n}\n\nfunction parseTodoList(data: string | undefined): TodoList | null {\n if (!data) return null;\n try {\n const parsed = JSON.parse(data) as TodoList;\n return parsed && Array.isArray(parsed.items) ? parsed : null;\n } catch {\n return null;\n }\n}\n"],"names":["STORAGE_KEYS","MAX_PROMPTS","_LocalStorageService","stored","a","b","error","prompt","prompts","p","__name","LocalStorageService","usePromptState","storageService","promptSize","firstPrompt","lastPrompt","lastCreated","_EventTypes","__publicField","EventTypes","allEventTypes","_EventBusService","eventName","args","listeners","promisses","listener","l","artifact","agentInteraction","interactionId","errorMessage","sessionId","info","message","interaction","functionDetails","question","data","eventData","details","EventBusService","MAX_CHAR_PER_TEXT_PART","ownParts","d","ownFunctionMap","isFunctionCall","t","EventType","isFunctionResponse","nextPartId","opensNewPart","incoming","last","_a","_b","_d","_c","_e","foldClientOutput","callId","clientOutput","currentIdx","current","merged","placeholder","foldFunctionEvent","existing","effects","fd","cur","openPart","serverEvent","newPart","appendText","justPushedNew","updated","chunk","mergeArtifacts","prev","next","llmArtifact","index","reduceInteraction","InteractionPartUtils","isFn","_InteractionService","eventBusService","InteractionService","APPLICATION_CLOSED_CODE","SESSION_ALREADY_ATTACHED_CODE","SESSION_NOT_FOUND_CODE","HEARTBEAT_TIMEOUT_CODE","RETRY_INITIAL_WAIT_MS","RETRY_MAX_WAIT_MS","RETRY_BASE_MULTIPLIER","RETRY_JITTER","IDLE_TIMEOUT","WARNING_THRESHOLD","IDLE_TICK_MS","LOG","_ConnectionSupervisor","ports","state","ConnectionState","options","fallbackSessionId","had","code","reason","target","startedAt","settled","actual","reconnect","delay","ms","idle","ConnectionSupervisor","_ThrottledEmitter","snapshot","now","elapsed","at","ThrottledEmitter","_AgentGatewayWSAsync","user","artifactService","baseUrl","config","sessionStore","notificationPort","ws","delayMs","attempt","since","outage","event","start","stats","notifyError","notice","open","ServerEvent","copy","kind","modelId","customer","_toolSessionId","interactionQuestion","wasSuspended","idOverrideForTests","newId","extra","service","origin","announced","toInteractionOrigin","interService","date_formatted","formatDate","newArtifact","part","isServerError","artifactsIds","id","artifactDatas","artifactData","errorEvent","updatedInteraction","detachedRunId","detachedRunName","toolDetails","_author","ownsLiveMessage","liveOfAnotherTurn","artifactId","response","runningPromise","closeTurn","connectedSessionId","messageNumber","totalTimer","promptAsString","json","sendResponse","PromptUtils","startingPart","ChatAction","_f","_g","_h","_i","img","_j","parts","interactionStatus","_","toolCallId","answer","deliver","runId","settleKey","key","send","localWsService","resolve","reject","success","sleepTime","timeOut","AgentGatewayWSAsync","llmEventFromPartial","pe","LlmEvent","PartType","callPart","StreamingFunctionCallUpdateContent","streamTextPart","StreamingTextContent","textPart","TextContent","thoughtPart","StreamingReasoningContent","llmEventFromFrame","frame","carriesContent","interactionStartFromFrame","InteractionStart","NOISE_FLOOR","detectCompaction","previous","declared","entry","dropped","budget","significant","sizeBefore","sizeAfter","ratioBefore","SLIDING_WINDOW_SIZE_SECONDS","TOKEN_SIZE_AVG","MAX_TRACKED_COMPACTIONS","_StreamStatsTracker","opts","compaction","windowStart","charsInWindow","sum","e","StreamStatsTracker","MONITOR_TICK_MS","PING_INTERVAL_MS","PONG_TIMEOUT_MS","_WebSocketConnecionV2","getToken","createStreamingResponseSerializer","getRandomUUID","token","queryParts","querySuffix","wsBase","wsUrl","streamingResponse","waitTime","connectingTimeoutMs","openTimeoutMs","socket","waitedMs","openWaitedMs","rawData","llmEvent","newToken","AUTH_STORAGE_KEY","raw","err","pending","waited","onclose","billing","item","BillingLimitContent","WebSocketConnecionV2","_HttpArtifactService","serverBaseUrl","accessToken","resolveAccessToken","_useCache","r","url","HttpArtifactService","_DetachedRunFramesHttpError","status","DetachedRunFramesHttpError","toDetachedRunFollowError","createSseParser","onEvent","buffer","dispatch","line","text","colon","field","value","newline","width","retryable","sleep","signal","timer","done","framesUrl","resource","afterSeq","collection","streamDetachedRunFrames","onFrame","onEnd","onOpen","onRetry","fetchImpl","input","init","initialMs","maxMs","maxAttempts","lastSeq","authRetried","secondChance","usedToken","fresh","failure","headers","atEnd","parser","endSeq","seq","reader","decoder","_DetachedRunFramesTransport","controller","opened","retryInMs","followError","hostError","_message","DetachedRunFramesTransport","TODO_LIST_UPDATED_EVENT","readDetachedRunActivity","serializer","signals","todoList","parseTodoList","parsed"],"mappings":";;;;;;;;;;AAaA,MAAMA,IAAe;AAAA,EACnB,SAAS;AACX,GAGMC,KAAc,IAmBPC,KAAN,MAAMA,GAA+C;AAAA,EAC1D,aAAuB;AACrB,QAAI;AACF,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