@mgamadeus/ddd-agents 0.5.16 → 0.6.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 (109) hide show
  1. package/README.md +170 -6
  2. package/boundary.json +13 -0
  3. package/dist/chat.js +148 -773
  4. package/dist/chat.js.map +1 -1
  5. package/dist/chunks/{canvas-title-slot-context-DK4sfhkl.js → ConversationMarkdown-BsCjyhj4.js} +14 -43
  6. package/dist/chunks/ConversationMarkdown-BsCjyhj4.js.map +1 -0
  7. package/dist/chunks/{ConversationMessageInputComposerWidgets-B3Zf69rD.js → ConversationMessageInputComposerWidgets-CE8LpyXY.js} +10 -37
  8. package/dist/chunks/ConversationMessageInputComposerWidgets-CE8LpyXY.js.map +1 -0
  9. package/dist/chunks/VoiceBarsIcon-BIcURsBF.js +643 -0
  10. package/dist/chunks/VoiceBarsIcon-BIcURsBF.js.map +1 -0
  11. package/dist/chunks/{WebSearchResultsConversationWidget-887v8Wen.js → WebSearchResultsConversationWidget-DXhfSikV.js} +2 -2
  12. package/dist/chunks/{WebSearchResultsConversationWidget-887v8Wen.js.map → WebSearchResultsConversationWidget-DXhfSikV.js.map} +1 -1
  13. package/dist/chunks/browser-request-interception-BnzFbH0m.js +335 -0
  14. package/dist/chunks/browser-request-interception-BnzFbH0m.js.map +1 -0
  15. package/dist/chunks/{canvas-reducers-CwFA3rQ6.js → canvas-reducers-D-YxAR4B.js} +2 -2
  16. package/dist/chunks/{canvas-reducers-CwFA3rQ6.js.map → canvas-reducers-D-YxAR4B.js.map} +1 -1
  17. package/dist/chunks/canvas-title-slot-context-D6UXrkdJ.js +36 -0
  18. package/dist/chunks/canvas-title-slot-context-D6UXrkdJ.js.map +1 -0
  19. package/dist/chunks/{canvasBodies-C7qqThc9.js → canvasBodies-CQEBkIVw.js} +4 -4
  20. package/dist/chunks/{canvasBodies-C7qqThc9.js.map → canvasBodies-CQEBkIVw.js.map} +1 -1
  21. package/dist/chunks/{canvasStorage-i2wKVSBf.js → canvasStorage-BbEI3h-8.js} +2 -2
  22. package/dist/chunks/{canvasStorage-i2wKVSBf.js.map → canvasStorage-BbEI3h-8.js.map} +1 -1
  23. package/dist/chunks/format-agent-voice-call-duration-C-3hRc9p.js +10 -0
  24. package/dist/chunks/format-agent-voice-call-duration-C-3hRc9p.js.map +1 -0
  25. package/dist/chunks/{link-navigation-CNX8Am2L.js → link-navigation-BUcy5qWW.js} +2 -2
  26. package/dist/chunks/{link-navigation-CNX8Am2L.js.map → link-navigation-BUcy5qWW.js.map} +1 -1
  27. package/dist/chunks/{realtime-arrival-BTLE3jjt.js → realtime-arrival-BfsAPwqQ.js} +8 -3
  28. package/dist/chunks/realtime-arrival-BfsAPwqQ.js.map +1 -0
  29. package/dist/chunks/use-agents-chat-store-CuIkCz9v.js +34 -0
  30. package/dist/chunks/use-agents-chat-store-CuIkCz9v.js.map +1 -0
  31. package/dist/chunks/{widget-name-resolver-BVEuAsW5.js → widget-name-resolver-B9k-s_cF.js} +3 -3
  32. package/dist/chunks/{widget-name-resolver-BVEuAsW5.js.map → widget-name-resolver-B9k-s_cF.js.map} +1 -1
  33. package/dist/chunks/withPollingChangeSubscription-CnQnubfK.js.map +1 -1
  34. package/dist/client-testing.js +4 -4
  35. package/dist/client.js +14 -3
  36. package/dist/client.js.map +1 -1
  37. package/dist/files/i18n-keys.json +1128 -100
  38. package/dist/image-render.js +65 -38
  39. package/dist/image-render.js.map +1 -1
  40. package/dist/index.js +6 -6
  41. package/dist/kit.js +2 -2
  42. package/dist/preview.js +23 -26
  43. package/dist/preview.js.map +1 -1
  44. package/dist/provider.js +1 -1
  45. package/dist/renderer.js +25 -24
  46. package/dist/renderer.js.map +1 -1
  47. package/dist/styles.css +531 -93
  48. package/dist/types/client/AgentsConversationClient.d.ts +4 -1
  49. package/dist/types/client/http/createAgentsHttpConversationClient.d.ts +2 -1
  50. package/dist/types/entries/voice-admin.d.ts +7 -0
  51. package/dist/types/entries/voice.d.ts +24 -0
  52. package/dist/types/image-render/frozen-widget-requests.d.ts +11 -2
  53. package/dist/types/image-render/widget-image-google-map.d.ts +5 -0
  54. package/dist/types/image-render/widget-image-static-assets.d.ts +2 -0
  55. package/dist/types/preview/widget-preview-requests.d.ts +6 -5
  56. package/dist/types/request-interception/browser-request-interception.d.ts +48 -0
  57. package/dist/types/request-interception/intercepted-xml-http-request-upload.d.ts +15 -0
  58. package/dist/types/ui/account-realtime.d.ts +50 -11
  59. package/dist/types/voice/AgentVoiceCallBand/AgentVoiceCallBand.d.ts +49 -0
  60. package/dist/types/voice/AgentVoiceCallBand/agent-voice-call-outcome-title-text-key.d.ts +8 -0
  61. package/dist/types/voice/AgentVoiceCallCaptions/AgentVoiceCallCaptions.d.ts +15 -0
  62. package/dist/types/voice/AgentVoiceCallCaptions/saved-messages-of-agent-voice-chat.d.ts +12 -0
  63. package/dist/types/voice/AgentVoiceCallProvider/AgentVoiceCallProvider.d.ts +21 -0
  64. package/dist/types/voice/AgentVoiceCallProvider/agent-voice-call-context.d.ts +17 -0
  65. package/dist/types/voice/AgentVoiceChatStartButton/AgentVoiceChatStartButton.d.ts +15 -0
  66. package/dist/types/voice/AgentVoiceIcons/AgentVoiceIcons.d.ts +10 -0
  67. package/dist/types/voice/AgentVoiceIncomingCall/AgentVoiceIncomingCall.d.ts +28 -0
  68. package/dist/types/voice/AgentVoiceInputGlow/AgentVoiceInputGlow.d.ts +11 -0
  69. package/dist/types/voice/AgentVoiceInputGlow/agent-voice-input-glow-voice.d.ts +8 -0
  70. package/dist/types/voice/admin/AgentVoiceCallConversationLink/AgentVoiceCallConversationLink.d.ts +10 -0
  71. package/dist/types/voice/admin/AgentVoiceCallDetailScreen/AgentVoiceCallDetailScreen.d.ts +27 -0
  72. package/dist/types/voice/admin/AgentVoiceCallStateBadges/AgentVoiceCallStateBadges.d.ts +12 -0
  73. package/dist/types/voice/admin/AgentVoiceCallsScreen/AgentVoiceCallsScreen.d.ts +33 -0
  74. package/dist/types/voice/admin/agent-voice-admin-api.d.ts +59 -0
  75. package/dist/types/voice/admin/agent-voice-admin-format.d.ts +38 -0
  76. package/dist/types/voice/admin/agent-voice-admin-types.d.ts +110 -0
  77. package/dist/types/voice/agent-voice-api.d.ts +114 -0
  78. package/dist/types/voice/call/agent-voice-call-elapsed-seconds.d.ts +6 -0
  79. package/dist/types/voice/call/agent-voice-call-end-reasons.d.ts +3 -0
  80. package/dist/types/voice/call/agent-voice-call-store.d.ts +111 -0
  81. package/dist/types/voice/call/agent-voice-call-turn.d.ts +4 -0
  82. package/dist/types/voice/call/build-unsaved-agent-voice-call-lines.d.ts +14 -0
  83. package/dist/types/voice/call/format-agent-voice-call-duration.d.ts +2 -0
  84. package/dist/types/voice/call/use-agent-voice-call-elapsed-seconds.d.ts +3 -0
  85. package/dist/types/voice/call/use-agent-voice-call-server-end.d.ts +15 -0
  86. package/dist/types/voice/call/use-agent-voice-call.d.ts +12 -0
  87. package/dist/types/voice/call/use-follow-agent-voice-call-conversation.d.ts +9 -0
  88. package/dist/types/voice/ring/agent-voice-caller-label.d.ts +21 -0
  89. package/dist/types/voice/ring/agent-voice-incoming-ring-list.d.ts +10 -0
  90. package/dist/types/voice/ring/agent-voice-incoming-ring-store.d.ts +47 -0
  91. package/dist/types/voice/ring/agent-voice-ring-source.d.ts +75 -0
  92. package/dist/types/voice/ring/agent-voice-ring.d.ts +35 -0
  93. package/dist/types/voice/ring/answer-incoming-agent-voice-call.d.ts +13 -0
  94. package/dist/types/voice/ring/use-agent-voice-incoming-rings.d.ts +14 -0
  95. package/dist/types/voice/ring/use-agent-voice-ring-tone.d.ts +6 -0
  96. package/dist/ui.js +82 -19
  97. package/dist/ui.js.map +1 -1
  98. package/dist/voice-admin.js +738 -0
  99. package/dist/voice-admin.js.map +1 -0
  100. package/dist/voice.js +1586 -0
  101. package/dist/voice.js.map +1 -0
  102. package/dist/widgets.js +4 -4
  103. package/package.json +23 -4
  104. package/public-api.json +156 -0
  105. package/dist/chunks/ConversationMessageInputComposerWidgets-B3Zf69rD.js.map +0 -1
  106. package/dist/chunks/canvas-title-slot-context-DK4sfhkl.js.map +0 -1
  107. package/dist/chunks/realtime-arrival-BTLE3jjt.js.map +0 -1
  108. package/dist/chunks/widget-image-readiness-signal-C58JkCQA.js +0 -25
  109. package/dist/chunks/widget-image-readiness-signal-C58JkCQA.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"voice.js","sources":["../src/voice/agent-voice-api.ts","../src/voice/call/agent-voice-call-end-reasons.ts","../src/voice/call/agent-voice-call-store.ts","../src/voice/call/agent-voice-call-elapsed-seconds.ts","../src/voice/call/use-agent-voice-call-elapsed-seconds.ts","../src/voice/call/use-agent-voice-call.ts","../src/voice/call/agent-voice-call-turn.ts","../src/voice/call/use-agent-voice-call-server-end.ts","../src/voice/call/build-unsaved-agent-voice-call-lines.ts","../src/voice/ring/agent-voice-ring.ts","../src/voice/ring/agent-voice-ring-source.ts","../src/voice/ring/answer-incoming-agent-voice-call.ts","../src/voice/ring/agent-voice-incoming-ring-store.ts","../src/voice/ring/agent-voice-caller-label.ts","../src/voice/ring/use-agent-voice-ring-tone.ts","../src/voice/call/use-follow-agent-voice-call-conversation.ts","../src/voice/AgentVoiceCallProvider/agent-voice-call-context.ts","../src/voice/AgentVoiceCallProvider/AgentVoiceCallProvider.tsx","../src/voice/AgentVoiceChatStartButton/AgentVoiceChatStartButton.tsx","../src/voice/AgentVoiceIcons/AgentVoiceIcons.tsx","../src/voice/AgentVoiceCallBand/agent-voice-call-outcome-title-text-key.ts","../src/voice/AgentVoiceCallBand/AgentVoiceCallBand.tsx","../src/voice/AgentVoiceCallCaptions/saved-messages-of-agent-voice-chat.ts","../src/voice/AgentVoiceCallCaptions/AgentVoiceCallCaptions.tsx","../src/voice/AgentVoiceInputGlow/agent-voice-input-glow-voice.ts","../src/voice/AgentVoiceInputGlow/AgentVoiceInputGlow.tsx","../src/voice/ring/agent-voice-incoming-ring-list.ts","../src/voice/ring/use-agent-voice-incoming-rings.ts","../src/voice/AgentVoiceIncomingCall/AgentVoiceIncomingCall.tsx"],"sourcesContent":["/**\n * The adapter the application passes to `AgentVoiceCallProvider`, so the voice chat depends on no generated client:\n * one function per voice route of `AgentVoiceSessionsTrait` (`open`, `hangUp`, `deviceStatus`, the call state read,\n * `answer`, `decline`). Every function rejects with something `readAgentVoiceErrorCode` finds the route's error code in.\n */\nexport interface AgentVoiceApi {\n openSession(args: {\n agentSpaceId?: number;\n sdpOffer: string;\n conversationId?: number;\n callId?: number;\n }): Promise<{ callId: number; sdpAnswer: string; conversationId: number }>;\n hangUp(args: { callId: number; reason?: string }): Promise<void>;\n reportDeviceStatus(args: {\n callId: number;\n status: string;\n iceCandidateType?: string;\n roundTripTimeMs?: number;\n detail?: string;\n occurredAtUnixMs?: number;\n }): Promise<void>;\n readCallState(args: { callId: number }): Promise<{ callId: number; endedAt?: string; endReason?: string }>;\n answerRing(args: { callId: number; answerToken: string }): Promise<{ won: boolean; conversationId?: number }>;\n declineRing(args: { callId: number; answerToken: string }): Promise<void>;\n}\n\n/** A refused or broken request of the voice routes; `code` is the route's error code (`call_already_running`, …). */\nexport class AgentVoiceApiError extends Error {\n readonly code: string;\n readonly httpStatus: number | undefined;\n\n constructor(code: string, httpStatus?: number) {\n super(code);\n this.name = \"AgentVoiceApiError\";\n this.code = code;\n this.httpStatus = httpStatus;\n }\n}\n\nconst readString = (value: unknown): string | undefined => (typeof value === \"string\" && value !== \"\" ? value : undefined);\n\n/**\n * The error code of a rejected adapter call. The voice routes answer the code as the error message, so it is read\n * where the common request layers put it: `error` (the JSON error body itself), `data.error` (the body below a status),\n * `code`, or the message of an `Error`. Undefined when the failure names none (the network is down).\n */\nexport const readAgentVoiceErrorCode = (failure: unknown): string | undefined => {\n if (typeof failure !== \"object\" || failure === null) return undefined;\n const failureFields = failure as { error?: unknown; data?: unknown; code?: unknown; message?: unknown };\n const errorBody =\n typeof failureFields.data === \"object\" && failureFields.data !== null\n ? (failureFields.data as { error?: unknown })\n : undefined;\n return (\n readString(failureFields.error) ??\n readString(errorBody?.error) ??\n readString(failureFields.code) ??\n readString(failureFields.message)\n );\n};\n\n/** A request of the voice routes as the application's request layer receives it: path, method, JSON body. */\nexport interface AgentVoiceRequest {\n url: string;\n method?: \"GET\" | \"POST\";\n body?: unknown;\n}\n\n/**\n * The application's request layer as `createAgentVoiceApi` uses it. The call store runs outside React (the call\n * outlives the chat that shows it), so the layer answers a Promise per request and offers no hooks: `request` sends\n * with the application's origin, session and token refresh, resolves with the parsed JSON answer and rejects with the\n * failure (see `readAgentVoiceErrorCode`). `createAgentVoiceFetchBaseApi` is one over `fetch`.\n */\nexport interface AgentVoiceBaseApi {\n request: <Answer>(request: AgentVoiceRequest) => Promise<Answer>;\n}\n\nexport interface CreateAgentVoiceApiOptions {\n /** The application's request layer. */\n baseApi: AgentVoiceBaseApi;\n /** Where the application mounts the voice session routes, without a trailing slash (`/api/agents/voiceSession`). */\n apiPrefix: string;\n}\n\n/** Without trailing slashes (`/api/agents/voiceSession/` → `/api/agents/voiceSession`). */\nconst trimApiPrefix = (apiPrefix: string): string => apiPrefix.replace(/\\/+$/, \"\");\n\nconst callPath = (callId: number): string => `/${encodeURIComponent(String(callId))}`;\n\n/** The request of every operation, on `apiPrefix`, with the routes' own field names. Pure: nothing is sent. */\nexport const buildAgentVoiceRequests = (apiPrefix: string) => {\n const prefix = trimApiPrefix(apiPrefix);\n return {\n openSession: ({\n agentSpaceId,\n sdpOffer,\n conversationId,\n callId,\n }: Parameters<AgentVoiceApi[\"openSession\"]>[0]): AgentVoiceRequest => ({\n url: `${prefix}/open`,\n method: \"POST\",\n body: { agentSpaceId, sdpOffer, conversationId, callId },\n }),\n hangUp: ({ callId, reason }: Parameters<AgentVoiceApi[\"hangUp\"]>[0]): AgentVoiceRequest => ({\n url: `${prefix}${callPath(callId)}/hangUp`,\n method: \"POST\",\n body: { reason },\n }),\n reportDeviceStatus: ({\n callId,\n status,\n iceCandidateType,\n roundTripTimeMs,\n detail,\n occurredAtUnixMs,\n }: Parameters<AgentVoiceApi[\"reportDeviceStatus\"]>[0]): AgentVoiceRequest => ({\n url: `${prefix}${callPath(callId)}/deviceStatus`,\n method: \"POST\",\n body: { status, iceCandidateType, roundTripTimeMs, detail, occurredAtUnixMs },\n }),\n readCallState: ({ callId }: Parameters<AgentVoiceApi[\"readCallState\"]>[0]): AgentVoiceRequest => ({\n url: `${prefix}${callPath(callId)}`,\n }),\n answerRing: ({ callId, answerToken }: Parameters<AgentVoiceApi[\"answerRing\"]>[0]): AgentVoiceRequest => ({\n url: `${prefix}${callPath(callId)}/answer`,\n method: \"POST\",\n body: { answerToken },\n }),\n declineRing: ({ callId, answerToken }: Parameters<AgentVoiceApi[\"declineRing\"]>[0]): AgentVoiceRequest => ({\n url: `${prefix}${callPath(callId)}/decline`,\n method: \"POST\",\n body: { answerToken },\n }),\n };\n};\n\n/** What `open` answers: the call (its id), the provider's SDP answer and the conversation the call writes into. */\ninterface AgentVoiceOpenAnswer {\n agentVoiceCall?: { id?: number | null } | null;\n sdpAnswer?: string | null;\n conversationId?: number | null;\n}\n\ninterface AgentVoiceCallStateAnswer {\n callId?: number | null;\n endedAt?: string | null;\n endReason?: string | null;\n}\n\ninterface AgentVoiceRingAnswer {\n won?: boolean | null;\n conversationId?: number | null;\n}\n\n/** The code of an `open` answer without a call id or a conversation: nothing the call could go on with. */\nexport const AGENT_VOICE_ERROR_CODE_INVALID_OPEN_ANSWER = \"invalid_open_answer\";\n\n/**\n * The adapter for an application whose routes are the voice trait's own paths below `apiPrefix`, with the agent space\n * in the body of `open`:\n * `export const agentVoiceApi = createAgentVoiceApi({ baseApi, apiPrefix: \"/api/agents/voiceSession\" });`\n * An application whose `open` names its space another way (in the path) writes the six functions itself.\n */\nexport const createAgentVoiceApi = ({ baseApi, apiPrefix }: CreateAgentVoiceApiOptions): AgentVoiceApi => {\n const requests = buildAgentVoiceRequests(apiPrefix);\n return {\n openSession: async (args) => {\n const openAnswer = await baseApi.request<AgentVoiceOpenAnswer | null>(requests.openSession(args));\n const callId = openAnswer?.agentVoiceCall?.id ?? args.callId;\n const conversationId = openAnswer?.conversationId ?? args.conversationId;\n if (callId === undefined || conversationId === undefined)\n throw new AgentVoiceApiError(AGENT_VOICE_ERROR_CODE_INVALID_OPEN_ANSWER);\n // No SDP answer stays an empty one: the store ends the opened call on the server before it shows the failure.\n return { callId, sdpAnswer: openAnswer?.sdpAnswer ?? \"\", conversationId };\n },\n hangUp: async (args) => {\n await baseApi.request<unknown>(requests.hangUp(args));\n },\n reportDeviceStatus: async (args) => {\n await baseApi.request<unknown>(requests.reportDeviceStatus(args));\n },\n readCallState: async (args) => {\n const callState = await baseApi.request<AgentVoiceCallStateAnswer | null>(requests.readCallState(args));\n return {\n callId: callState?.callId ?? args.callId,\n endedAt: callState?.endedAt ?? undefined,\n endReason: callState?.endReason ?? undefined,\n };\n },\n answerRing: async (args) => {\n const ringAnswer = await baseApi.request<AgentVoiceRingAnswer | null>(requests.answerRing(args));\n return { won: ringAnswer?.won === true, conversationId: ringAnswer?.conversationId ?? undefined };\n },\n declineRing: async (args) => {\n await baseApi.request<unknown>(requests.declineRing(args));\n },\n };\n};\n\n/** What every request carries from the application: headers, credentials, mode, cache. */\nexport type AgentVoiceFetchOptions = Omit<RequestInit, \"method\" | \"body\">;\n\nexport interface CreateAgentVoiceFetchBaseApiOptions {\n /**\n * Request options every request carries (credentials, an authorization header). A function is called per request,\n * so it may hand out a fresh token. Default: none (the browser's defaults: same-origin credentials).\n */\n fetchOptions?: AgentVoiceFetchOptions | (() => AgentVoiceFetchOptions | Promise<AgentVoiceFetchOptions>);\n /** The fetch function. Default: the global `fetch`. */\n fetch?: typeof fetch;\n}\n\nconst readJsonBody = async (response: Response): Promise<unknown> => {\n const bodyText = await response.text();\n if (bodyText === \"\") return undefined;\n try {\n return JSON.parse(bodyText);\n } catch {\n return undefined;\n }\n};\n\n/**\n * A request layer over `fetch`: JSON out, JSON in; a refused request rejects with `AgentVoiceApiError`, its code the\n * `error` of the JSON error body (`http_<status>` without one).\n */\nexport const createAgentVoiceFetchBaseApi = (options: CreateAgentVoiceFetchBaseApiOptions = {}): AgentVoiceBaseApi => ({\n request: async <Answer,>(request: AgentVoiceRequest): Promise<Answer> => {\n const fetchFunction = options.fetch ?? globalThis.fetch.bind(globalThis);\n const fetchOptions = typeof options.fetchOptions === \"function\" ? await options.fetchOptions() : (options.fetchOptions ?? {});\n const headers = new Headers(fetchOptions.headers);\n if (!headers.has(\"Accept\")) headers.set(\"Accept\", \"application/json\");\n if (request.body !== undefined && !headers.has(\"Content-Type\")) headers.set(\"Content-Type\", \"application/json\");\n const response = await fetchFunction(request.url, {\n ...fetchOptions,\n headers,\n method: request.method ?? \"GET\",\n body: request.body === undefined ? undefined : JSON.stringify(request.body),\n });\n const responseBody = await readJsonBody(response);\n if (!response.ok) {\n throw new AgentVoiceApiError(readAgentVoiceErrorCode(responseBody) ?? `http_${response.status}`, response.status);\n }\n return responseBody as Answer;\n },\n});\n","/** The call's end reasons the band words differently (`AgentVoiceCall::END_REASON_*`). */\nexport const AGENT_VOICE_CALL_END_REASON_ENDED_BY_AGENT = \"ENDED_BY_AGENT\";\nexport const AGENT_VOICE_CALL_END_REASON_LIMIT_REACHED = \"LIMIT_REACHED\";\n","import { useSyncExternalStore } from \"react\";\nimport { type AgentVoiceApi, readAgentVoiceErrorCode } from \"../agent-voice-api\";\nimport { textKey } from \"../../provider/text-key\";\nimport { AGENT_VOICE_CALL_END_REASON_ENDED_BY_AGENT } from \"./agent-voice-call-end-reasons\";\n\n/**\n * The voice chat with the agent in the browser window (the owner starts it, or answers the agent's ring). The audio\n * runs peer to peer between the browser and the voice provider over WebRTC; the backend only relays the SDP handshake\n * (`openSession`) and its session worker writes every spoken sentence into the call's conversation, which the chat\n * shows live.\n *\n * Module-level on purpose: the call must outlive the chat that shows it (a closed chat window, a conversation switch, a\n * remount), and the account can hold only one call at a time anyway.\n */\n\nexport type AgentVoiceCallPhase = \"idle\" | \"connecting\" | \"live\" | \"ended\" | \"failed\";\n\nexport type AgentVoiceCallSpeaker = \"agent\" | \"owner\";\n\nexport interface AgentVoiceCallLine {\n /** Increasing within the call: the line's React key. */\n readonly id: number;\n readonly speaker: AgentVoiceCallSpeaker;\n readonly text: string;\n}\n\n/** The call keeps the recent conversation only; the chat beside it keeps everything. */\nconst MAX_CALL_LINES = 40;\n\nexport interface AgentVoiceCallSnapshot {\n readonly phase: AgentVoiceCallPhase;\n /** The agent space the call was started in, where the application has one. */\n readonly agentSpaceId?: number;\n /** The conversation the call writes its transcript into: known once `openSession` answered. */\n readonly conversationId?: number;\n readonly callId?: number;\n /** Set on `session.started`: the moment the call counts as connected. */\n readonly connectedAtMs?: number;\n readonly endedAtMs?: number;\n readonly isMuted: boolean;\n /** The microphone delivered only silence for several seconds while not muted: a wrong or muted input device. */\n readonly isMicrophoneSilent: boolean;\n /** The agent's words are arriving right now (an output transcript delta within `AGENT_SPEAKING_HOLD_MS`). */\n readonly isAgentSpeaking: boolean;\n /** The owner's words are arriving right now (an input transcript delta within `OWNER_SPEAKING_HOLD_MS`). */\n readonly isOwnerSpeaking: boolean;\n /** Who spoke last, from the transcript deltas: drives the status line and the glow. */\n readonly lastSpeaker?: AgentVoiceCallSpeaker;\n /** What was said in this call, oldest first: one line per turn of a speaker, assembled from the transcript deltas. */\n readonly lines: readonly AgentVoiceCallLine[];\n /** The text key of a sentence for the owner when the call failed (it may carry `%agentName%`). */\n readonly failureTextKey?: string;\n /**\n * Set when the SERVER ended the call (the agent hung up, a limit, the provider closed the session): the call's end\n * reason (`ENDED_BY_AGENT`, `LIMIT_REACHED`, …), or `PROVIDER_CLOSED` when the provider closed the session before the\n * call said why. Undefined when this browser ended the call. Picks the band's end text.\n */\n readonly endReason?: string;\n}\n\nconst SESSION_START_TIMEOUT_MS = 15_000;\nconst AUDIO_FLOW_CHECK_INTERVAL_MS = 1_000;\nconst AUDIO_FLOW_CHECK_ATTEMPTS = 10;\nconst LOG_PREFIX = \"[AgentVoiceCall]\";\n/** How long after a speaker's last transcript delta they still count as speaking (deltas arrive in bursts). */\nconst AGENT_SPEAKING_HOLD_MS = 900;\nconst OWNER_SPEAKING_HOLD_MS = 900;\n/** Below this `audioLevel` (0..1) for the whole window the input device delivers silence, not speech pauses. */\nconst SILENT_MICROPHONE_LEVEL = 0.01;\nconst SILENT_MICROPHONE_WINDOW_SAMPLES = 6;\n/** Once the agent has heard the owner in this call, a pause only counts as a silent microphone after this long. */\nconst SILENT_AFTER_HEARD_MS = 60_000;\nconst ICE_GATHERING_TIMEOUT_MS = 2_000;\nconst ICE_DISCONNECT_GRACE_MS = 5_000;\n/** The event channel of the voice provider. */\nconst DATA_CHANNEL_LABEL = \"oai-events\";\n// The end reasons the band words differently live in a module without React, so the band's title rule loads alone.\nexport {\n AGENT_VOICE_CALL_END_REASON_ENDED_BY_AGENT,\n AGENT_VOICE_CALL_END_REASON_LIMIT_REACHED,\n} from \"./agent-voice-call-end-reasons\";\nconst AGENT_VOICE_CALL_END_REASON_FAILED = \"FAILED\";\n/** The provider closed the session (`session.closed`) and the call did not name a reason yet. */\nconst PROVIDER_CLOSED_END_REASON = \"PROVIDER_CLOSED\";\n/**\n * After `session.closed`, the backend may still be writing the call's end (the worker hangs up first, then stamps the\n * call): one more look at the call state after this long, before the call is ended with the neutral reason.\n */\nconst SESSION_CLOSED_RECHECK_MS = 1_500;\nconst CONNECTION_DROPPED_TEXT_KEY = textKey(\"The connection to %agentName% dropped. Please try again.\");\n\n/** The sentence for the owner by the error code `openSession` was refused with. */\nconst OPEN_ERROR_TEXT_KEYS: Readonly<Record<string, string>> = {\n feature_not_available: textKey(\"Voice chats with %agentName% are not available here.\"),\n no_ai_budget: textKey(\"Your AI budget is used up, so %agentName% cannot talk right now.\"),\n daily_limit_reached: textKey(\"The time for voice chats with %agentName% is used up for today. Please try again tomorrow.\"),\n call_already_running: textKey(\"You are already in a voice chat with %agentName%. End it first, then start a new one.\"),\n conversation_not_found: textKey(\n \"This conversation cannot take a voice chat. Start a new chat and talk to %agentName% from there.\",\n ),\n provider_unavailable: textKey(\"The voice of %agentName% is not reachable right now. Please try again in a minute.\"),\n invalid_sdp: textKey(\"Your browser could not set up the voice chat. Please try again.\"),\n};\n\n/** No voice chat: also what a chat shows of a voice chat that runs in another agent space. */\nexport const IDLE_AGENT_VOICE_CALL: AgentVoiceCallSnapshot = {\n phase: \"idle\",\n isMuted: false,\n isMicrophoneSilent: false,\n isAgentSpeaking: false,\n isOwnerSpeaking: false,\n lines: [],\n};\n\nlet snapshot: AgentVoiceCallSnapshot = IDLE_AGENT_VOICE_CALL;\nconst listeners = new Set<() => void>();\n\nlet voiceApi: AgentVoiceApi | undefined;\nlet peerConnection: RTCPeerConnection | undefined;\nlet microphoneStream: MediaStream | undefined;\nlet remoteAudioElement: HTMLAudioElement | undefined;\nlet providerEventChannel: RTCDataChannel | undefined;\nlet audioFlowTimer: number | undefined;\nlet agentSpeakingTimer: number | undefined;\nlet ownerSpeakingTimer: number | undefined;\n/** When the owner's voice last reached the agent (a microphone level above the silence line, or an input transcript). */\nlet ownerLastHeardAtMs: number | undefined;\nlet sessionStartTimer: number | undefined;\nlet iceDisconnectTimer: number | undefined;\nlet mediaConnectedReported = false;\nlet pageHideListenerRegistered = false;\n/** The call-state read in flight, by call: the triggers (signal, data channel close, ICE) share one request. */\nlet callStateCheckInFlight: { callId: number; endedOnServer: Promise<boolean> } | undefined;\nlet sessionClosedRecheckTimer: number | undefined;\n\nconst replaceSnapshot = (nextSnapshot: AgentVoiceCallSnapshot) => {\n snapshot = nextSnapshot;\n listeners.forEach((listener) => listener());\n};\n\nconst updateSnapshot = (changes: Partial<AgentVoiceCallSnapshot>) => replaceSnapshot({ ...snapshot, ...changes });\n\nconst subscribe = (listener: () => void) => {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n};\n\nconst getSnapshot = () => snapshot;\n\n/**\n * The adapter the store sends its requests through. `AgentVoiceCallProvider` binds the one it was given; the binding\n * stays after the provider is gone, because a running call still has to end on the server.\n */\nexport const bindAgentVoiceApi = (api: AgentVoiceApi) => {\n voiceApi = api;\n};\n\n/** The bound adapter (undefined before a provider was mounted): answering and declining a ring go through it too. */\nexport const readBoundAgentVoiceApi = (): AgentVoiceApi | undefined => voiceApi;\n\n/** The call as it is now, outside React (a module that reacts to an event, a test). */\nexport const readAgentVoiceCallSnapshot = (): AgentVoiceCallSnapshot => snapshot;\n\n/** The call as the store holds it; it changes with the call, not with the clock (see `useAgentVoiceCall`). */\nexport const useAgentVoiceCallSnapshot = (): AgentVoiceCallSnapshot => useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n\n/**\n * One field of the call, for a component that must not re-render on every transcript delta (the chat window's shell,\n * the input's voice button). The selector must return a primitive so an unchanged value skips the render.\n */\nexport const useAgentVoiceCallValue = <Value extends string | number | boolean | undefined>(\n selectValue: (call: AgentVoiceCallSnapshot) => Value,\n): Value =>\n useSyncExternalStore(\n subscribe,\n () => selectValue(snapshot),\n () => selectValue(snapshot),\n );\n\nexport const isAgentVoiceCallActive = (phase: AgentVoiceCallPhase): boolean => phase === \"connecting\" || phase === \"live\";\n\n/**\n * Whether a chat of the agent space `agentSpaceId` shows this call: not when the call is known to run in another\n * agent space. A chat or a call that names no agent space is never held apart.\n */\nexport const isAgentVoiceCallShownInAgentSpace = (call: AgentVoiceCallSnapshot, agentSpaceId: number | undefined): boolean =>\n agentSpaceId === undefined || call.agentSpaceId === undefined || call.agentSpaceId === agentSpaceId;\n\n/**\n * Whether a voice chat is connecting or live; with `agentSpaceId`, whether one is that a chat of that agent space\n * shows. An input shows the start button in its send spot only while none is, and the glow and the captions while one is.\n */\nexport const useIsAgentVoiceCallActive = (agentSpaceId?: number): boolean =>\n useAgentVoiceCallValue((call) => isAgentVoiceCallActive(call.phase) && isAgentVoiceCallShownInAgentSpace(call, agentSpaceId));\n\n/** Put away the band of an ended or failed call (its Close): the chat is back to no call. */\nexport const dismissAgentVoiceCallOutcome = () => {\n if (isAgentVoiceCallActive(snapshot.phase)) return;\n replaceSnapshot(IDLE_AGENT_VOICE_CALL);\n};\n\nconst clearTimers = () => {\n window.clearTimeout(sessionStartTimer);\n window.clearTimeout(iceDisconnectTimer);\n window.clearInterval(audioFlowTimer);\n window.clearTimeout(agentSpeakingTimer);\n window.clearTimeout(ownerSpeakingTimer);\n window.clearTimeout(sessionClosedRecheckTimer);\n sessionStartTimer = undefined;\n iceDisconnectTimer = undefined;\n audioFlowTimer = undefined;\n sessionClosedRecheckTimer = undefined;\n};\n\nconst releaseMedia = () => {\n clearTimers();\n microphoneStream?.getTracks().forEach((track) => track.stop());\n providerEventChannel?.close();\n peerConnection?.close();\n if (remoteAudioElement) {\n remoteAudioElement.pause();\n remoteAudioElement.srcObject = null;\n }\n microphoneStream = undefined;\n providerEventChannel = undefined;\n peerConnection = undefined;\n remoteAudioElement = undefined;\n};\n\nconst reportDeviceStatus = (status: string, detail?: string) => {\n const callId = snapshot.callId;\n if (callId === undefined || !voiceApi) return;\n voiceApi.reportDeviceStatus({ callId, status, detail, occurredAtUnixMs: Date.now() }).catch(() => undefined);\n};\n\nconst sendHangUp = (callId: number | undefined, reason: string) => {\n if (callId === undefined || !voiceApi) return;\n voiceApi.hangUp({ callId, reason }).catch(() => undefined);\n};\n\n/** The provider's close of the WebRTC session is `session.close` on the data channel, sent before the REST hang-up. */\nconst sendSessionClose = () => {\n if (providerEventChannel?.readyState !== \"open\") return;\n providerEventChannel.send(JSON.stringify({ type: \"session.close\" }));\n};\n\nconst failCall = (failureTextKey: string, detail: string) => {\n if (!isAgentVoiceCallActive(snapshot.phase)) return;\n console.warn(LOG_PREFIX, \"call failed:\", detail);\n reportDeviceStatus(\"MEDIA_FAILED\", detail);\n sendSessionClose();\n sendHangUp(snapshot.callId, \"MEDIA_FAILED\");\n releaseMedia();\n updateSnapshot({\n phase: \"failed\",\n failureTextKey,\n endedAtMs: Date.now(),\n isAgentSpeaking: false,\n isOwnerSpeaking: false,\n });\n};\n\n/**\n * The SERVER ended the call (the call has `endedAt`; or the provider closed the session): end this browser's side\n * without telling the backend again: no hang-up request for a call the server already ended. Applies only while the\n * call is connecting or live AND the call id is this call's, so a late answer for an earlier call, or a second trigger\n * after the first one ended the call, changes nothing. `session.close` goes out unless the agent ended the call (its\n * worker already closed the session); a `FAILED` end shows the failure, every other end the call's end text.\n */\nexport const endAgentVoiceCallFromServer = (callId: number, endReason: string | undefined) => {\n if (!isAgentVoiceCallActive(snapshot.phase) || snapshot.callId !== callId) return;\n console.info(LOG_PREFIX, \"call ended by the server:\", endReason ?? \"unknown reason\");\n reportDeviceStatus(\"SERVER_END_SEEN\", endReason);\n if (endReason !== AGENT_VOICE_CALL_END_REASON_ENDED_BY_AGENT) sendSessionClose();\n releaseMedia();\n if (endReason === AGENT_VOICE_CALL_END_REASON_FAILED) {\n updateSnapshot({\n phase: \"failed\",\n failureTextKey: CONNECTION_DROPPED_TEXT_KEY,\n endedAtMs: Date.now(),\n isAgentSpeaking: false,\n isOwnerSpeaking: false,\n });\n return;\n }\n updateSnapshot({\n phase: \"ended\",\n endReason,\n endedAtMs: Date.now(),\n isAgentSpeaking: false,\n isOwnerSpeaking: false,\n });\n};\n\nconst readCallStateAndEndWhenEndedOnServer = async (callId: number): Promise<boolean> => {\n if (!voiceApi) return false;\n try {\n const callState = await voiceApi.readCallState({ callId });\n if (!callState?.endedAt) return false;\n endAgentVoiceCallFromServer(callId, callState.endReason ?? undefined);\n return true;\n } catch {\n // The read failed (network, 404): nothing is known, the caller keeps its own path.\n return false;\n }\n};\n\n/**\n * Read the call's state (`readCallState`) and end the call here when the server ended it. Resolves to whether it did.\n * One read at a time per call: the conversation's change signal, the data channel closing and the ICE watcher may all\n * ask at once.\n */\nexport const checkAgentVoiceCallEndedOnServer = (): Promise<boolean> => {\n const callId = snapshot.callId;\n if (callId === undefined || !isAgentVoiceCallActive(snapshot.phase)) return Promise.resolve(false);\n if (callStateCheckInFlight?.callId === callId) return callStateCheckInFlight.endedOnServer;\n const endedOnServer = readCallStateAndEndWhenEndedOnServer(callId).finally(() => {\n if (callStateCheckInFlight?.callId === callId) callStateCheckInFlight = undefined;\n });\n callStateCheckInFlight = { callId, endedOnServer };\n return endedOnServer;\n};\n\n/**\n * The provider closed the session. The call says why once the backend wrote the end: look now and once more shortly\n * after; without an answer the call ends with the neutral reason. Never the hang-up request.\n */\nconst endCallAfterProviderClosedSession = async () => {\n const callId = snapshot.callId;\n if (callId === undefined) {\n hangUpAgentVoiceCall(PROVIDER_CLOSED_END_REASON);\n return;\n }\n if (await checkAgentVoiceCallEndedOnServer()) return;\n window.clearTimeout(sessionClosedRecheckTimer);\n sessionClosedRecheckTimer = window.setTimeout(async () => {\n if (await checkAgentVoiceCallEndedOnServer()) return;\n endAgentVoiceCallFromServer(callId, PROVIDER_CLOSED_END_REASON);\n }, SESSION_CLOSED_RECHECK_MS);\n};\n\n/**\n * The media path dropped (ICE): first ask the server whether it ended the call, then this is the call's end, not a\n * failure; otherwise the failure path as before.\n */\nconst failCallUnlessEndedOnServer = async (connection: RTCPeerConnection, detail: string) => {\n if (await checkAgentVoiceCallEndedOnServer()) return;\n if (connection !== peerConnection) return;\n failCall(CONNECTION_DROPPED_TEXT_KEY, detail);\n};\n\n/** End the call from this browser. Safe to call in any phase. */\nexport const hangUpAgentVoiceCall = (reason: string = \"USER_ENDED\") => {\n if (!isAgentVoiceCallActive(snapshot.phase)) return;\n if (reason === \"USER_ENDED\") reportDeviceStatus(\"ENDED_BY_USER\");\n if (reason !== \"PROVIDER_CLOSED\") sendSessionClose();\n sendHangUp(snapshot.callId, reason);\n releaseMedia();\n updateSnapshot({\n phase: \"ended\",\n endedAtMs: Date.now(),\n isAgentSpeaking: false,\n isOwnerSpeaking: false,\n });\n};\n\nexport const toggleAgentVoiceCallMute = () => {\n const isMuted = !snapshot.isMuted;\n // The muted stretch is not silence: the one-minute clock starts again on unmute.\n if (!isMuted && ownerLastHeardAtMs !== undefined) ownerLastHeardAtMs = Date.now();\n microphoneStream?.getAudioTracks().forEach((track) => {\n track.enabled = !isMuted;\n });\n updateSnapshot({ isMuted });\n};\n\nconst appendTranscriptDelta = (speaker: AgentVoiceCallSpeaker, delta: unknown) => {\n if (typeof delta !== \"string\" || delta === \"\") return;\n // A new turn of this speaker starts a new line; a continuing turn grows the last one.\n const lastLine = snapshot.lines[snapshot.lines.length - 1];\n const lines =\n lastLine !== undefined && lastLine.speaker === speaker\n ? [...snapshot.lines.slice(0, -1), { ...lastLine, text: `${lastLine.text}${delta}` }]\n : [...snapshot.lines, { id: (lastLine?.id ?? 0) + 1, speaker, text: delta.trimStart() }].slice(-MAX_CALL_LINES);\n if (speaker === \"owner\") {\n ownerLastHeardAtMs = Date.now();\n updateSnapshot({ lines, lastSpeaker: speaker, isOwnerSpeaking: true });\n window.clearTimeout(ownerSpeakingTimer);\n ownerSpeakingTimer = window.setTimeout(() => updateSnapshot({ isOwnerSpeaking: false }), OWNER_SPEAKING_HOLD_MS);\n return;\n }\n updateSnapshot({ lines, lastSpeaker: speaker, isAgentSpeaking: true });\n window.clearTimeout(agentSpeakingTimer);\n agentSpeakingTimer = window.setTimeout(() => updateSnapshot({ isAgentSpeaking: false }), AGENT_SPEAKING_HOLD_MS);\n};\n\nconst readProviderEvent = (messageEvent: MessageEvent) => {\n let providerEvent: { type?: string; delta?: unknown };\n try {\n providerEvent = JSON.parse(String(messageEvent.data));\n } catch {\n return;\n }\n if (!providerEvent.type?.endsWith(\".delta\")) console.info(LOG_PREFIX, \"provider event\", providerEvent.type);\n switch (providerEvent.type) {\n case \"session.started\":\n if (snapshot.phase !== \"connecting\") return;\n window.clearTimeout(sessionStartTimer);\n updateSnapshot({ phase: \"live\", connectedAtMs: Date.now() });\n reportDeviceStatus(\"SESSION_STARTED_SEEN\");\n watchAudioFlow();\n return;\n case \"session.output_transcript.delta\":\n appendTranscriptDelta(\"agent\", providerEvent.delta);\n return;\n case \"session.input_transcript.delta\":\n appendTranscriptDelta(\"owner\", providerEvent.delta);\n return;\n case \"session.closed\":\n // The provider ended the session (the agent's hang-up, silence, the time cap, the budget): the server's end path.\n void endCallAfterProviderClosedSession();\n return;\n default:\n return;\n }\n};\n\n/**\n * The provider's session clock runs on input audio: report when the microphone's first bytes leave and the agent's\n * first bytes arrive (the start-up timeline of the call), and keep reading the microphone level for the whole call:\n * RTP packets flow even from a silent input device, so only the level tells that the agent hears nothing.\n */\nconst watchAudioFlow = () => {\n const connection = peerConnection;\n if (!connection) return;\n const microphoneTrack = microphoneStream?.getAudioTracks()[0];\n console.info(\n LOG_PREFIX,\n `microphone \"${microphoneTrack?.label}\" enabled=${microphoneTrack?.enabled} muted=${microphoneTrack?.muted} state=${microphoneTrack?.readyState}`,\n );\n let firstAudioSentReported = false;\n let firstAudioPlayedReported = false;\n let silentMicrophoneReported = false;\n let attempts = 0;\n const recentMicrophoneLevels: number[] = [];\n window.clearInterval(audioFlowTimer);\n audioFlowTimer = window.setInterval(async () => {\n if (connection !== peerConnection) return;\n attempts += 1;\n const stats = await connection.getStats();\n stats.forEach((report) => {\n if (report.type === \"outbound-rtp\" && report.kind === \"audio\" && report.bytesSent > 0 && !firstAudioSentReported) {\n firstAudioSentReported = true;\n reportDeviceStatus(\"FIRST_AUDIO_SENT\");\n }\n if (report.type === \"inbound-rtp\" && report.kind === \"audio\" && report.bytesReceived > 0 && !firstAudioPlayedReported) {\n firstAudioPlayedReported = true;\n reportDeviceStatus(\"FIRST_AUDIO_PLAYED\");\n }\n if (report.type === \"media-source\" && report.kind === \"audio\" && typeof report.audioLevel === \"number\") {\n recentMicrophoneLevels.push(report.audioLevel);\n if (report.audioLevel >= SILENT_MICROPHONE_LEVEL) ownerLastHeardAtMs = Date.now();\n if (recentMicrophoneLevels.length > SILENT_MICROPHONE_WINDOW_SAMPLES) recentMicrophoneLevels.shift();\n }\n });\n if (attempts === AUDIO_FLOW_CHECK_ATTEMPTS) {\n console.info(LOG_PREFIX, `audio flow sent=${firstAudioSentReported} played=${firstAudioPlayedReported}`);\n if (!firstAudioSentReported) reportDeviceStatus(\"MEDIA_FAILED\", \"no outbound audio bytes 10s after session.started\");\n }\n const loudestRecentLevel = Math.max(0, ...recentMicrophoneLevels);\n // Before the agent heard the owner once, a few silent seconds mean a wrong or muted device; after, only a long pause.\n const isSilentSinceStart =\n ownerLastHeardAtMs === undefined &&\n recentMicrophoneLevels.length === SILENT_MICROPHONE_WINDOW_SAMPLES &&\n loudestRecentLevel < SILENT_MICROPHONE_LEVEL;\n const isSilentSinceLastHeard = ownerLastHeardAtMs !== undefined && Date.now() - ownerLastHeardAtMs >= SILENT_AFTER_HEARD_MS;\n const isMicrophoneSilent = !snapshot.isMuted && (isSilentSinceStart || isSilentSinceLastHeard);\n if (isMicrophoneSilent !== snapshot.isMicrophoneSilent) {\n console.info(LOG_PREFIX, `microphone silent=${isMicrophoneSilent} loudest level=${loudestRecentLevel}`);\n updateSnapshot({ isMicrophoneSilent });\n }\n if (isMicrophoneSilent && !silentMicrophoneReported) {\n silentMicrophoneReported = true;\n reportDeviceStatus(\"INTERRUPTED\", `microphone \"${microphoneTrack?.label}\" silent, loudest level ${loudestRecentLevel}`);\n }\n }, AUDIO_FLOW_CHECK_INTERVAL_MS);\n};\n\nconst watchIceConnection = (connection: RTCPeerConnection) => {\n connection.oniceconnectionstatechange = () => {\n if (connection !== peerConnection) return;\n const iceConnectionState = connection.iceConnectionState;\n if (iceConnectionState === \"connected\" || iceConnectionState === \"completed\") {\n window.clearTimeout(iceDisconnectTimer);\n if (!mediaConnectedReported) {\n mediaConnectedReported = true;\n reportDeviceStatus(\"MEDIA_CONNECTED\");\n }\n } else if (iceConnectionState === \"disconnected\") {\n // A server-side end drops the media too: ask at once, and again before the grace runs out into a failure.\n void checkAgentVoiceCallEndedOnServer();\n window.clearTimeout(iceDisconnectTimer);\n iceDisconnectTimer = window.setTimeout(\n () => void failCallUnlessEndedOnServer(connection, \"ice disconnected for 5s\"),\n ICE_DISCONNECT_GRACE_MS,\n );\n } else if (iceConnectionState === \"failed\") {\n void failCallUnlessEndedOnServer(connection, \"ice failed\");\n }\n };\n};\n\n/** No trickle ICE on the provider side: the offer must carry the gathered candidates, capped at 2s. */\nconst waitForIceGathering = (connection: RTCPeerConnection) =>\n new Promise<void>((resolve) => {\n if (connection.iceGatheringState === \"complete\") {\n resolve();\n return;\n }\n const timer = window.setTimeout(resolve, ICE_GATHERING_TIMEOUT_MS);\n connection.addEventListener(\"icegatheringstatechange\", () => {\n if (connection.iceGatheringState === \"complete\") {\n window.clearTimeout(timer);\n resolve();\n }\n });\n });\n\nconst registerPageHideHangUp = () => {\n if (pageHideListenerRegistered) return;\n pageHideListenerRegistered = true;\n // Best-effort: the request may not leave before the tab is gone; the backend's reaper is the fallback.\n window.addEventListener(\"pagehide\", () => hangUpAgentVoiceCall(\"APP_BACKGROUNDED\"));\n};\n\nexport interface StartAgentVoiceCallParams {\n /** The agent space the call runs in, where the application has one; goes to `openSession` as it is. */\n agentSpaceId?: number;\n /** The chat's conversation the call continues; without one the backend creates a conversation for the call. */\n conversationId?: number;\n /** The rung call this browser already won through `answerRing` (see answerIncomingAgentVoiceCall.ts). */\n callId?: number;\n}\n\n/**\n * Start a voice chat (or attach to the answered call `callId`). Call it straight from the click: the microphone prompt\n * and the audio playback need the user's gesture. Does nothing while a call is connecting or live, and nothing before\n * an `AgentVoiceCallProvider` bound the adapter.\n */\nexport const startAgentVoiceCall = async (params: StartAgentVoiceCallParams = {}) => {\n const { agentSpaceId, conversationId, callId: answeredCallId } = params;\n if (isAgentVoiceCallActive(snapshot.phase)) return;\n const api = voiceApi;\n if (!api) {\n console.warn(LOG_PREFIX, \"no adapter bound: mount AgentVoiceCallProvider before starting a voice chat\");\n return;\n }\n mediaConnectedReported = false;\n ownerLastHeardAtMs = undefined;\n registerPageHideHangUp();\n replaceSnapshot({ ...IDLE_AGENT_VOICE_CALL, phase: \"connecting\", agentSpaceId, conversationId, callId: answeredCallId });\n\n try {\n microphoneStream = await navigator.mediaDevices.getUserMedia({\n audio: { echoCancellation: true, noiseSuppression: true, autoGainControl: true },\n });\n } catch {\n releaseMedia();\n // An answered call is already claimed on the backend: end it there too.\n sendHangUp(answeredCallId, \"MEDIA_FAILED\");\n updateSnapshot({\n phase: \"failed\",\n failureTextKey: textKey(\"%agentName% needs your microphone. Allow microphone access in your browser, then try again.\"),\n });\n return;\n }\n\n const connection = new RTCPeerConnection();\n peerConnection = connection;\n remoteAudioElement = new Audio();\n remoteAudioElement.autoplay = true;\n connection.ontrack = (trackEvent) => {\n if (remoteAudioElement) remoteAudioElement.srcObject = trackEvent.streams[0] ?? null;\n };\n microphoneStream.getTracks().forEach((track) => connection.addTrack(track, microphoneStream as MediaStream));\n const eventChannel = connection.createDataChannel(DATA_CHANNEL_LABEL);\n providerEventChannel = eventChannel;\n eventChannel.onmessage = readProviderEvent;\n // The provider closing the channel is a hint the server ended the call; this browser's own close\n // (releaseMedia) clears `providerEventChannel` first, so it is no hint.\n eventChannel.onclose = () => {\n if (eventChannel !== providerEventChannel) return;\n void checkAgentVoiceCallEndedOnServer();\n };\n watchIceConnection(connection);\n\n try {\n await connection.setLocalDescription(await connection.createOffer());\n await waitForIceGathering(connection);\n const sdpOffer = connection.localDescription?.sdp ?? \"\";\n const openAnswer = await api.openSession({ agentSpaceId, sdpOffer, conversationId, callId: answeredCallId });\n const callId: number | undefined = openAnswer.callId ?? undefined;\n // Hung up while `openSession` was in flight: the call exists on the server now, so end it there too.\n if (connection !== peerConnection) {\n sendHangUp(callId, \"USER_ENDED\");\n return;\n }\n updateSnapshot({ callId, conversationId: openAnswer.conversationId ?? conversationId });\n if (!openAnswer.sdpAnswer) {\n failCall(\n textKey(\"The voice of %agentName% is not reachable right now. Please try again in a minute.\"),\n \"open returned no SDP answer\",\n );\n return;\n }\n await connection.setRemoteDescription({ type: \"answer\", sdp: openAnswer.sdpAnswer });\n reportDeviceStatus(\"ANSWER_APPLIED\");\n sessionStartTimer = window.setTimeout(\n () => failCall(textKey(\"%agentName% could not join the voice chat. Please try again.\"), \"no session.started within 15s\"),\n SESSION_START_TIMEOUT_MS,\n );\n } catch (openError) {\n if (connection !== peerConnection) return;\n const errorCode = readAgentVoiceErrorCode(openError);\n // An own entry only: the code may be any text the request layer rejected with.\n const isKnownErrorCode = errorCode !== undefined && Object.prototype.hasOwnProperty.call(OPEN_ERROR_TEXT_KEYS, errorCode);\n releaseMedia();\n sendHangUp(answeredCallId, \"MEDIA_FAILED\");\n updateSnapshot({\n phase: \"failed\",\n failureTextKey: isKnownErrorCode\n ? OPEN_ERROR_TEXT_KEYS[errorCode]\n : textKey(\"The voice chat could not be started. Please try again.\"),\n endedAtMs: Date.now(),\n });\n }\n};\n","import type { AgentVoiceCallSnapshot } from \"./agent-voice-call-store\";\n\n/**\n * Whole seconds from the moment the call connected to its end, or to `nowMs` while it has not ended; 0 before it\n * connected, and never below 0 (a clock read before the connect moment).\n */\nexport const agentVoiceCallElapsedSecondsAt = (\n call: Pick<AgentVoiceCallSnapshot, \"connectedAtMs\" | \"endedAtMs\">,\n nowMs: number,\n): number => {\n if (call.connectedAtMs === undefined) return 0;\n return Math.max(0, Math.floor(((call.endedAtMs ?? nowMs) - call.connectedAtMs) / 1000));\n};\n","import { useEffect, useState } from \"react\";\nimport { agentVoiceCallElapsedSecondsAt } from \"./agent-voice-call-elapsed-seconds\";\nimport type { AgentVoiceCallSnapshot } from \"./agent-voice-call-store\";\n\n/** Seconds since the call connected, ticking while it is live; frozen at the end once it ended. */\nexport const useAgentVoiceCallElapsedSeconds = (call: AgentVoiceCallSnapshot): number => {\n const [nowMs, setNowMs] = useState(() => Date.now());\n useEffect(() => {\n if (call.phase !== \"live\") return;\n const timer = window.setInterval(() => setNowMs(Date.now()), 1000);\n return () => window.clearInterval(timer);\n }, [call.phase]);\n return agentVoiceCallElapsedSecondsAt(call, nowMs);\n};\n","import { useMemo } from \"react\";\nimport { type AgentVoiceCallSnapshot, useAgentVoiceCallSnapshot } from \"./agent-voice-call-store\";\nimport { useAgentVoiceCallElapsedSeconds } from \"./use-agent-voice-call-elapsed-seconds\";\n\n/** The call with its clock: what `useAgentVoiceCall()` returns. */\nexport interface AgentVoiceCall extends AgentVoiceCallSnapshot {\n /** Seconds since the call connected: ticking while it is live, frozen once it ended, 0 before it connected. */\n readonly elapsedSeconds: number;\n}\n\n/**\n * The voice chat as it is now: the phase, the call and its conversation, the spoken lines, mute, the end reason and\n * the elapsed seconds. It renders again every second while the call is live; a component that needs one field only\n * reads it with `useAgentVoiceCallValue`, one that needs no clock with `useAgentVoiceCallSnapshot`.\n */\nexport const useAgentVoiceCall = (): AgentVoiceCall => {\n const call = useAgentVoiceCallSnapshot();\n const elapsedSeconds = useAgentVoiceCallElapsedSeconds(call);\n return useMemo(() => ({ ...call, elapsedSeconds }), [call, elapsedSeconds]);\n};\n","import type { AgentVoiceCallSnapshot } from \"./agent-voice-call-store\";\n\n/** Whose turn it is on the line right now: the band's status line and the input glow read it. */\nexport type AgentVoiceCallTurn = \"connecting\" | \"muted\" | \"silentMicrophone\" | \"agent\" | \"owner\" | \"thinking\" | \"listening\";\n\nexport const turnOfAgentVoiceCall = (call: AgentVoiceCallSnapshot): AgentVoiceCallTurn => {\n if (call.phase === \"connecting\") return \"connecting\";\n if (call.isMuted) return \"muted\";\n if (call.isMicrophoneSilent) return \"silentMicrophone\";\n if (call.isAgentSpeaking) return \"agent\";\n if (call.isOwnerSpeaking) return \"owner\";\n // The owner said the last words and the agent has not started its answer yet.\n if (call.lastSpeaker === \"owner\") return \"thinking\";\n return \"listening\";\n};\n","import { useEffect } from \"react\";\nimport { useOptionalAgentsConversationClient } from \"../../client/AgentsConversationClientContext\";\nimport { checkAgentVoiceCallEndedOnServer, isAgentVoiceCallActive, useAgentVoiceCallValue } from \"./agent-voice-call-store\";\n\n/** The change signal fires for every transcript row too: at most one call-state read per this long. */\nconst CALL_STATE_READ_THROTTLE_MS = 1_200;\n\n/** How an application reports the changes of a conversation: `onChange` on every change; returns the unsubscribe. */\nexport type AgentVoiceConversationChangeSubscription = (conversationId: number, onChange: () => void) => () => void;\n\n/**\n * Ends the voice chat here when the SERVER ended the call (the agent hung up, a limit, the reaper): listens to the\n * change signal of the CALL's conversation, independent of the conversation the chat shows, while the call is active,\n * and on a signal reads the call's state. The backend writes the call's end before its call-end marker and the signal,\n * so the read after the signal sees the end. The signal is throttled here (one read per 1.2 s at most, the last signal\n * of a burst still read) and the store runs one read at a time.\n *\n * The signal comes from `subscribeToConversationChanges` when the application passes one, otherwise from the\n * conversation client in the React context (its `subscribeToConversationChanges`). Without\n * either nothing is listened to: the call still ends through the store's own triggers (the provider's `session.closed`,\n * the event channel closing, the media path dropping). `AgentVoiceCallProvider` mounts the hook.\n */\nexport const useAgentVoiceCallServerEnd = (subscribeToConversationChanges?: AgentVoiceConversationChangeSubscription) => {\n const conversationClient = useOptionalAgentsConversationClient();\n const isCallActive = useAgentVoiceCallValue((call) => isAgentVoiceCallActive(call.phase));\n const callConversationId = useAgentVoiceCallValue((call) => call.conversationId);\n const callId = useAgentVoiceCallValue((call) => call.callId);\n\n useEffect(() => {\n if (!isCallActive || callConversationId === undefined || callId === undefined) return;\n let lastReadAtMs = Number.NEGATIVE_INFINITY;\n let trailingReadTimer: number | undefined;\n const readCallState = () => {\n lastReadAtMs = Date.now();\n void checkAgentVoiceCallEndedOnServer();\n };\n const readCallStateThrottled = () => {\n const waitMs = lastReadAtMs + CALL_STATE_READ_THROTTLE_MS - Date.now();\n if (waitMs <= 0) {\n readCallState();\n return;\n }\n if (trailingReadTimer !== undefined) return;\n trailingReadTimer = window.setTimeout(() => {\n trailingReadTimer = undefined;\n readCallState();\n }, waitMs);\n };\n const unsubscribe =\n subscribeToConversationChanges !== undefined\n ? subscribeToConversationChanges(callConversationId, readCallStateThrottled)\n : conversationClient?.subscribeToConversationChanges?.(\n callConversationId,\n readCallStateThrottled,\n readCallStateThrottled,\n );\n return () => {\n window.clearTimeout(trailingReadTimer);\n unsubscribe?.();\n };\n }, [isCallActive, callConversationId, callId, subscribeToConversationChanges, conversationClient]);\n};\n","import type { AgentVoiceCallLine, AgentVoiceCallSpeaker } from \"./agent-voice-call-store\";\n\n/** A message the chat already holds from this call: who wrote it and its text. */\nexport interface SavedAgentVoiceCallMessage {\n readonly speaker: AgentVoiceCallSpeaker;\n readonly text: string;\n}\n\nconst SENTENCE_PATTERN = /[^.!?…]+[.!?…]*\\s*/g;\n\n/** Letters and digits only, lower case: the browser's transcript and the saved sentence differ in spacing and marks. */\nconst normalizeForMatching = (text: string): string => text.toLowerCase().replace(/[^\\p{L}\\p{N}]+/gu, \"\");\n\n/**\n * What was said in this call that the chat does not show yet: the call's lines with every sentence the backend has\n * already saved as a message taken out, so only the unsaved rest streams at the chat's end and gives way to the real\n * message once it arrives. Per speaker, the saved texts are read as one stream in order, and each sentence of the\n * speaker's lines is looked for from where the last found one ended: the backend may cut sentences elsewhere, and a\n * sentence said twice is matched twice. Lines with nothing unsaved left are dropped.\n */\nexport const buildUnsavedAgentVoiceCallLines = (\n lines: readonly AgentVoiceCallLine[],\n savedMessages: readonly SavedAgentVoiceCallMessage[],\n): AgentVoiceCallLine[] => {\n const savedStreamBySpeaker: Record<AgentVoiceCallSpeaker, string> = { agent: \"\", owner: \"\" };\n savedMessages.forEach((savedMessage) => {\n savedStreamBySpeaker[savedMessage.speaker] += normalizeForMatching(savedMessage.text);\n });\n const matchedUntilBySpeaker: Record<AgentVoiceCallSpeaker, number> = { agent: 0, owner: 0 };\n\n return lines.flatMap((line) => {\n const sentences = line.text.match(SENTENCE_PATTERN) ?? [];\n const unsavedSentences = sentences.filter((sentence) => {\n const normalizedSentence = normalizeForMatching(sentence);\n if (normalizedSentence === \"\") return false;\n const foundAt = savedStreamBySpeaker[line.speaker].indexOf(normalizedSentence, matchedUntilBySpeaker[line.speaker]);\n if (foundAt === -1) return true;\n matchedUntilBySpeaker[line.speaker] = foundAt + normalizedSentence.length;\n return false;\n });\n const unsavedText = unsavedSentences.join(\"\").trim();\n return unsavedText === \"\" ? [] : [{ ...line, text: unsavedText }];\n });\n};\n","import type { AgentRealtimeMessageDelivery } from \"../../ui/realtime-arrival\";\n\n/** The realtime message type of the agent ringing the owner's open clients. Its key is the call id. */\nexport const AGENT_VOICE_RING_MESSAGE_TYPE = \"agent.voice.ring\";\n\n/**\n * The agent ringing this account: what a client needs to show the ring and answer it. Written by the backend when the\n * agent starts a call to the owner, for every open client of the account; it ends for a client when the call was\n * answered or declined, when its deadline passed, or when the agent or the owner canceled.\n */\nexport interface AgentVoiceRing {\n callId: number;\n conversationId?: number | null;\n /** Single-use, bound to this call; redeemed by `answerRing` / `declineRing`. */\n answerToken: string;\n ringExpiresAt: string;\n ringExpiresAtUnixMs: number;\n /** A text key: the caller line of the incoming call. */\n callerLabelKey: string;\n /** What the application put into the ring for its own caller line (what tells an owner which space is calling). */\n callerContext: Readonly<Record<string, unknown>>;\n /**\n * The agent space of the call, where the ring names it: passed to `openSession` when the owner accepts. An\n * application whose `openSession` needs the space fills it in its ring source or sends it in the payload.\n */\n agentSpaceId?: number;\n}\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\n/**\n * The ring a realtime message carries; null for a message of another type or a payload that is not a ring (no call id,\n * no answer token, no deadline).\n */\nexport const readAgentVoiceRingOfRealtimeMessage = (message: AgentRealtimeMessageDelivery): AgentVoiceRing | null => {\n if (message.messageType !== AGENT_VOICE_RING_MESSAGE_TYPE) return null;\n let payload: unknown;\n try {\n payload = JSON.parse(message.payloadJson);\n } catch {\n return null;\n }\n if (!isRecord(payload)) return null;\n const { callId, conversationId, answerToken, ringExpiresAt, ringExpiresAtUnixMs, callerLabelKey, callerContext, agentSpaceId } =\n payload;\n if (typeof callId !== \"number\" || typeof answerToken !== \"string\" || typeof ringExpiresAtUnixMs !== \"number\") return null;\n return {\n callId,\n conversationId: typeof conversationId === \"number\" ? conversationId : null,\n answerToken,\n ringExpiresAt: typeof ringExpiresAt === \"string\" ? ringExpiresAt : \"\",\n ringExpiresAtUnixMs,\n callerLabelKey: typeof callerLabelKey === \"string\" ? callerLabelKey : \"\",\n callerContext: isRecord(callerContext) ? callerContext : {},\n agentSpaceId: typeof agentSpaceId === \"number\" ? agentSpaceId : undefined,\n };\n};\n\n/**\n * The ring this client shows: the newest one still inside its deadline and not already handled here (answered,\n * declined or let go in this client).\n */\nexport const pickRingingAgentVoiceCall = (\n rings: readonly AgentVoiceRing[],\n nowMs: number,\n handledCallIds: ReadonlySet<number>,\n): AgentVoiceRing | undefined =>\n rings\n .filter((ring) => ring.ringExpiresAtUnixMs > nowMs && !handledCallIds.has(ring.callId))\n .sort((left, right) => right.callId - left.callId)[0];\n","import type { AccountRealtimePoll } from \"../../ui/account-realtime\";\nimport type { AgentRealtimeMessageDelivery } from \"../../ui/realtime-arrival\";\nimport { type AgentVoiceRing, readAgentVoiceRingOfRealtimeMessage } from \"./agent-voice-ring\";\n\n/**\n * The stream of the agent's rings to this account. `AgentVoiceCallProvider` takes one; the incoming call subscribes\n * while it is mounted. `onRing` gets every ring that arrives (a replaced one again); `onRingCleared` is called when\n * the source learns that a ring ended before its deadline (answered on another client, declined, canceled). A source\n * that cannot learn it never calls it: the ring then goes at its deadline, and an Accept after the end is refused by\n * the backend.\n */\nexport interface AgentVoiceRingSource {\n subscribe(onRing: (ring: AgentVoiceRing) => void, onRingCleared: (callId: number) => void): () => void;\n}\n\n/**\n * Starts the account realtime poll (`createAccountRealtimePoll` of `./ui`) with the arrival hook the ring source hands in:\n * `onMessage => createAccountRealtimePoll({ readAccountRealtime: client.getAccountRealtimeMessages, onMessage })`.\n * For an application that wants the poll to run only while a ring can show: the ring source starts it with its first\n * subscriber and stops it with its last. An application that reads further message types from the same poll passes\n * the poll itself instead and subscribes to it beside the ring source.\n */\nexport type AgentVoiceAccountRealtimePollStarter = (\n onMessage: (message: AgentRealtimeMessageDelivery) => void,\n) => AccountRealtimePoll;\n\ninterface AgentVoiceRingSubscriber {\n onRing: (ring: AgentVoiceRing) => void;\n onRingCleared: (callId: number) => void;\n}\n\ninterface AgentVoiceKnownRing {\n ring: AgentVoiceRing;\n /** The subscribers the ring was handed to, as an arrival or when they came: only they are told its clear. */\n handedTo: Set<AgentVoiceRingSubscriber>;\n}\n\n/**\n * The ring source over the account realtime poll: every message of the type `agent.voice.ring` the poll delivers goes\n * to the subscribers as a ring, and a ring message the poll reports as cleared (a read found it gone: answered or\n * declined on another client, canceled, past its deadline) as a cleared ring. A subscriber is told `onRingCleared`\n * only for a ring it was handed, as an arrival or in the hand-over when it subscribed.\n *\n * It listens while somebody is subscribed. Given the poll itself, it subscribes to it with the first subscriber and\n * leaves it with the last; the poll stays the application's, which stops it. Given a function that starts the poll, it\n * starts the poll with the first subscriber and stops it with the last.\n */\nexport class AgentVoiceAccountRealtimeRingSource implements AgentVoiceRingSource {\n protected readonly accountRealtimePollOrStarter: AccountRealtimePoll | AgentVoiceAccountRealtimePollStarter;\n protected readonly subscribers = new Set<AgentVoiceRingSubscriber>();\n /** The rings delivered while it listens, by call: a subscriber that comes later still gets the ones in their deadline. */\n protected readonly knownRingsByCallId = new Map<number, AgentVoiceKnownRing>();\n /** The poll a starter created; this source stops it. Undefined for a poll of the application. */\n protected startedAccountRealtimePoll: AccountRealtimePoll | undefined;\n /** Set while it listens to the poll. */\n protected unsubscribeFromAccountRealtimePoll: (() => void) | undefined;\n\n constructor(accountRealtimePollOrStarter: AccountRealtimePoll | AgentVoiceAccountRealtimePollStarter) {\n this.accountRealtimePollOrStarter = accountRealtimePollOrStarter;\n }\n\n subscribe(onRing: (ring: AgentVoiceRing) => void, onRingCleared: (callId: number) => void): () => void {\n const subscriber: AgentVoiceRingSubscriber = { onRing, onRingCleared };\n this.subscribers.add(subscriber);\n const nowMs = Date.now();\n this.knownRingsByCallId.forEach((knownRing) => {\n if (knownRing.ring.ringExpiresAtUnixMs > nowMs) this.handRing(knownRing, subscriber);\n });\n if (this.unsubscribeFromAccountRealtimePoll === undefined) this.listenToAccountRealtimePoll();\n return () => {\n this.subscribers.delete(subscriber);\n if (this.subscribers.size === 0) this.leaveAccountRealtimePoll();\n };\n }\n\n /** Takes one message of the account's realtime messages; returns whether it was a ring. */\n acceptRealtimeMessage(message: AgentRealtimeMessageDelivery): boolean {\n const ring = readAgentVoiceRingOfRealtimeMessage(message);\n if (ring === null) return false;\n const knownRing: AgentVoiceKnownRing = { ring, handedTo: new Set() };\n this.knownRingsByCallId.set(ring.callId, knownRing);\n this.subscribers.forEach((subscriber) => this.handRing(knownRing, subscriber));\n return true;\n }\n\n /**\n * Takes one message the account's realtime messages hold no more; returns whether it was a ring. The clear goes to\n * the subscribers the ring of that call was handed to, and to nobody for a call this source holds no ring of.\n */\n acceptClearedRealtimeMessage(message: AgentRealtimeMessageDelivery): boolean {\n const ring = readAgentVoiceRingOfRealtimeMessage(message);\n if (ring === null) return false;\n const knownRing = this.knownRingsByCallId.get(ring.callId);\n this.knownRingsByCallId.delete(ring.callId);\n this.subscribers.forEach((subscriber) => {\n if (knownRing?.handedTo.has(subscriber)) subscriber.onRingCleared(ring.callId);\n });\n return true;\n }\n\n /** Hands a ring to a subscriber and notes it on the known ring. */\n protected handRing(knownRing: AgentVoiceKnownRing, subscriber: AgentVoiceRingSubscriber): void {\n knownRing.handedTo.add(subscriber);\n subscriber.onRing(knownRing.ring);\n }\n\n /**\n * The poll hands over the messages open now, then every arrival and every clear. A started poll delivers its\n * arrivals through the hook it was started with, so only the clears are subscribed there.\n */\n protected listenToAccountRealtimePoll(): void {\n const accountRealtimePollOrStarter = this.accountRealtimePollOrStarter;\n if (typeof accountRealtimePollOrStarter !== \"function\") {\n this.unsubscribeFromAccountRealtimePoll = accountRealtimePollOrStarter.subscribe({\n onMessage: (message) => {\n this.acceptRealtimeMessage(message);\n },\n onMessageCleared: (message) => {\n this.acceptClearedRealtimeMessage(message);\n },\n });\n return;\n }\n const startedAccountRealtimePoll = accountRealtimePollOrStarter((message) => {\n this.acceptRealtimeMessage(message);\n });\n this.startedAccountRealtimePoll = startedAccountRealtimePoll;\n this.unsubscribeFromAccountRealtimePoll = startedAccountRealtimePoll.subscribe({\n onMessageCleared: (message) => {\n this.acceptClearedRealtimeMessage(message);\n },\n });\n }\n\n protected leaveAccountRealtimePoll(): void {\n this.unsubscribeFromAccountRealtimePoll?.();\n this.unsubscribeFromAccountRealtimePoll = undefined;\n this.startedAccountRealtimePoll?.stop();\n this.startedAccountRealtimePoll = undefined;\n this.knownRingsByCallId.clear();\n }\n}\n\n/**\n * The ring source over the account realtime poll of `./ui`:\n * `createAgentVoiceRingSource(createAccountRealtimePoll({ readAccountRealtime, … }))`. A function that starts the poll\n * (`AgentVoiceAccountRealtimePollStarter`) is taken as well. An application with its own ring transport passes its own\n * `AgentVoiceRingSource` instead.\n */\nexport const createAgentVoiceRingSource = (\n accountRealtimePollOrStarter: AccountRealtimePoll | AgentVoiceAccountRealtimePollStarter,\n): AgentVoiceRingSource => new AgentVoiceAccountRealtimeRingSource(accountRealtimePollOrStarter);\n","import { readAgentVoiceErrorCode } from \"../agent-voice-api\";\nimport { readBoundAgentVoiceApi, startAgentVoiceCall } from \"../call/agent-voice-call-store\";\nimport { textKey } from \"../../provider/text-key\";\nimport type { AgentVoiceRing } from \"./agent-voice-ring\";\n\n/** Why the answer did not get the call: the sentence the band or the incoming call shows instead of the ring. */\nexport type AgentVoiceAnswerRefusal = \"answeredElsewhere\" | \"ringEnded\" | \"failed\";\n\nexport const AGENT_VOICE_ANSWER_REFUSAL_TEXT_KEYS: Readonly<Record<AgentVoiceAnswerRefusal, string>> = {\n answeredElsewhere: textKey(\"You already answered %agentName% on another device.\"),\n ringEnded: textKey(\"%agentName% stopped asking to talk.\"),\n failed: textKey(\"The voice chat could not start. Please try again.\"),\n};\n\n/**\n * Answering the agent's ring in the browser: `answerRing` with the ring's single-use token (the atomic first-wins\n * claim: two clients pressing at once get exactly one winner), then the same WebRTC start as the chat's voice button\n * with the call id, so `openSession` attaches to the claimed call. Returns undefined when this browser won and the\n * call is starting.\n */\nexport const answerIncomingAgentVoiceCall = async (ring: AgentVoiceRing): Promise<AgentVoiceAnswerRefusal | undefined> => {\n const api = readBoundAgentVoiceApi();\n if (!api) return \"failed\";\n let conversationIdOfAnswer: number | undefined;\n try {\n const ringAnswer = await api.answerRing({ callId: ring.callId, answerToken: ring.answerToken });\n if (!ringAnswer.won) return \"answeredElsewhere\";\n conversationIdOfAnswer = ringAnswer.conversationId;\n } catch (answerError) {\n const errorCode = readAgentVoiceErrorCode(answerError);\n if (errorCode === \"already_answered\") return \"answeredElsewhere\";\n if (errorCode === \"ring_expired\" || errorCode === \"call_not_found\") return \"ringEnded\";\n return \"failed\";\n }\n void startAgentVoiceCall({\n agentSpaceId: ring.agentSpaceId,\n conversationId: conversationIdOfAnswer ?? ring.conversationId ?? undefined,\n callId: ring.callId,\n });\n return undefined;\n};\n\n/** Decline in this browser: ends the ring for every open client of the account. */\nexport const declineIncomingAgentVoiceCall = (ring: AgentVoiceRing): Promise<void> => {\n const api = readBoundAgentVoiceApi();\n if (!api) return Promise.resolve();\n return api.declineRing({ callId: ring.callId, answerToken: ring.answerToken }).catch(() => undefined);\n};\n","import { useEffect, useSyncExternalStore } from \"react\";\nimport type { AgentVoiceCallerLabel } from \"./agent-voice-caller-label\";\nimport type { AgentVoiceRing } from \"./agent-voice-ring\";\nimport {\n type AgentVoiceAnswerRefusal,\n answerIncomingAgentVoiceCall,\n declineIncomingAgentVoiceCall,\n} from \"./answer-incoming-agent-voice-call\";\n\nconst REFUSAL_SHOWN_MS = 4_000;\n\n/**\n * The agent ringing this client, shared between the one listener (`AgentVoiceIncomingCall`, mounted once) and where\n * the ring is answered: the band over an open chat's input, or, with no chat in sight, the listener's own card.\n */\nexport interface AgentVoiceIncomingRingSnapshot {\n /** The ring this client shows, inside its deadline and not handled here yet. */\n readonly ring?: AgentVoiceRing;\n /** The caller line of `ring`, as the listener resolved it. */\n readonly callerLabel?: AgentVoiceCallerLabel;\n /** Calls answered, declined or let go in this client: never shown again, even before their ring is gone. */\n readonly handledCallIds: ReadonlySet<number>;\n readonly isAnswering: boolean;\n /** Why the last Accept did not get the call; shown for a few seconds. */\n readonly refusal?: AgentVoiceAnswerRefusal;\n /** How many chats show the ring in their band right now (presented); with none, the listener shows its card. */\n readonly bandHostCount: number;\n /** How many surfaces cover the chats right now; with any, the listener shows its card. */\n readonly ringCoverCount: number;\n}\n\nlet snapshot: AgentVoiceIncomingRingSnapshot = {\n handledCallIds: new Set(),\n isAnswering: false,\n bandHostCount: 0,\n ringCoverCount: 0,\n};\nconst listeners = new Set<() => void>();\nlet refusalTimer: number | undefined;\n\nconst updateSnapshot = (changes: Partial<AgentVoiceIncomingRingSnapshot>) => {\n snapshot = { ...snapshot, ...changes };\n listeners.forEach((listener) => listener());\n};\n\nconst subscribe = (listener: () => void) => {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n};\n\nconst getSnapshot = () => snapshot;\n\nexport const useAgentVoiceIncomingRing = (): AgentVoiceIncomingRingSnapshot =>\n useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n\n/** The incoming ring as it is now, outside React (a test). */\nexport const readAgentVoiceIncomingRingSnapshot = (): AgentVoiceIncomingRingSnapshot => snapshot;\n\n/** What the listener's own card shows (the ring, else a refused Accept) while no chat band can be seen. */\nexport const pickAgentVoiceIncomingCard = (\n state: Pick<AgentVoiceIncomingRingSnapshot, \"ring\" | \"refusal\" | \"bandHostCount\" | \"ringCoverCount\">,\n): \"ring\" | \"refusal\" | undefined => {\n if (state.bandHostCount > 0 && state.ringCoverCount === 0) return undefined;\n if (state.ring !== undefined) return \"ring\";\n return state.refusal !== undefined ? \"refusal\" : undefined;\n};\n\n/** The listener publishes the ring it picked with its caller line (undefined when nothing rings). */\nexport const publishAgentVoiceIncomingRing = (\n ring: AgentVoiceRing | undefined,\n callerLabel: AgentVoiceCallerLabel | undefined,\n) => {\n if (\n ring?.callId === snapshot.ring?.callId &&\n ring?.ringExpiresAtUnixMs === snapshot.ring?.ringExpiresAtUnixMs &&\n callerLabel?.text === snapshot.callerLabel?.text &&\n callerLabel?.detail === snapshot.callerLabel?.detail\n )\n return;\n updateSnapshot({ ring, callerLabel: ring === undefined ? undefined : callerLabel });\n};\n\nconst markHandled = (handledRing: AgentVoiceRing) => {\n const isShownRing = snapshot.ring?.callId === handledRing.callId;\n updateSnapshot({\n handledCallIds: new Set(snapshot.handledCallIds).add(handledRing.callId),\n ring: isShownRing ? undefined : snapshot.ring,\n callerLabel: isShownRing ? undefined : snapshot.callerLabel,\n });\n};\n\nconst showRefusal = (refusal: AgentVoiceAnswerRefusal | undefined) => {\n window.clearTimeout(refusalTimer);\n updateSnapshot({ refusal });\n if (refusal === undefined) return;\n refusalTimer = window.setTimeout(() => updateSnapshot({ refusal: undefined }), REFUSAL_SHOWN_MS);\n};\n\n/**\n * Accept: answers the ring and, when this client won, starts the call on the ring's own conversation and agent space\n * (the ring may come from another agent space than the one the client shows). The application learns the call's\n * conversation through `AgentVoiceCallProvider.onConversationOfCallChanged` and shows it.\n */\nexport const acceptAgentVoiceIncomingRing = async () => {\n const acceptedRing = snapshot.ring;\n if (!acceptedRing || snapshot.isAnswering) return;\n updateSnapshot({ isAnswering: true });\n const answerRefusal = await answerIncomingAgentVoiceCall(acceptedRing);\n markHandled(acceptedRing);\n updateSnapshot({ isAnswering: false });\n showRefusal(answerRefusal);\n};\n\n/**\n * Decline: ends the ring for every open client of the account. The backend writes the declined call into its\n * conversation once nothing rings any more.\n */\nexport const declineAgentVoiceIncomingRing = () => {\n const declinedRing = snapshot.ring;\n if (!declinedRing || snapshot.isAnswering) return;\n markHandled(declinedRing);\n void declineIncomingAgentVoiceCall(declinedRing);\n};\n\n/** A chat that shows the ring in its band, while hosting: the listener's card stays away unless a cover is open. */\nexport const useAgentVoiceRingBandHost = (isHosting: boolean) => {\n useEffect(() => {\n if (!isHosting) return;\n updateSnapshot({ bandHostCount: snapshot.bandHostCount + 1 });\n return () => updateSnapshot({ bandHostCount: snapshot.bandHostCount - 1 });\n }, [isHosting]);\n};\n\n/**\n * A surface that covers the chats while covering (a settings sheet over them): their bands are out of sight then, so\n * the listener shows its own card on top instead.\n */\nexport const useAgentVoiceRingCover = (isCovering: boolean) => {\n useEffect(() => {\n if (!isCovering) return;\n updateSnapshot({ ringCoverCount: snapshot.ringCoverCount + 1 });\n return () => updateSnapshot({ ringCoverCount: snapshot.ringCoverCount - 1 });\n }, [isCovering]);\n};\n","import { DEFAULT_AGENTS_TEXTS } from \"../../provider/environment\";\nimport { textKey } from \"../../provider/text-key\";\nimport type { AgentVoiceTranslateText } from \"../AgentVoiceCallProvider/agent-voice-call-context\";\nimport type { AgentVoiceRing } from \"./agent-voice-ring\";\n\n/**\n * The caller line of the incoming call. The ring carries a label KEY (`callerLabelKey`), never the text: the client\n * owns the text. Every key this bundle knows maps to a text key it renders through the text function;\n * an unknown key (a backend newer than this bundle) is shown as it came, its placeholders filled but untranslated:\n * never a raw string sent to the translator, which could never be registered as a key.\n */\nconst DEFAULT_CALLER_LABEL_TEXT_KEY = textKey(\"%agentName% wants to talk\");\n\n// In the browser window it is a voice chat with the agent, never a call: a key worded as a call reads as a voice chat.\nconst CALLER_LABEL_TEXT_KEYS_BY_KEY: Readonly<Record<string, string>> = {\n \"%agentName% is calling you\": DEFAULT_CALLER_LABEL_TEXT_KEY,\n \"%agentName% wants to talk\": DEFAULT_CALLER_LABEL_TEXT_KEY,\n};\n\n/** The caller line as the incoming call and the band show it. */\nexport interface AgentVoiceCallerLabel {\n /** Who is asking to talk, ready to show. */\n text: string;\n /** A second line under it: what tells an owner with several agent spaces which one is calling. */\n detail?: string;\n}\n\nexport interface AgentVoiceCallerLabelTextKey {\n labelTextKey: string;\n /** True for a key of this bundle (render through the text function), false for an unknown key of the backend. */\n isTranslatable: boolean;\n}\n\n/** The text key of a ring's caller line; a ring without a label key gets the bundle's own line. */\nexport const pickAgentVoiceCallerLabelTextKey = (callerLabelKey: string): AgentVoiceCallerLabelTextKey => {\n if (callerLabelKey === \"\") return { labelTextKey: DEFAULT_CALLER_LABEL_TEXT_KEY, isTranslatable: true };\n return Object.prototype.hasOwnProperty.call(CALLER_LABEL_TEXT_KEYS_BY_KEY, callerLabelKey)\n ? { labelTextKey: CALLER_LABEL_TEXT_KEYS_BY_KEY[callerLabelKey], isTranslatable: true }\n : { labelTextKey: callerLabelKey, isTranslatable: false };\n};\n\n/**\n * The caller line of a ring where the application resolves none: the ring's label key through `translate` (the voice\n * components' text function, which fills `%agentName%`), an unknown key with `agentName` filled in.\n */\nexport const buildAgentVoiceCallerLabel = (\n ring: AgentVoiceRing,\n translate: AgentVoiceTranslateText,\n agentName: string,\n): AgentVoiceCallerLabel => {\n const { labelTextKey, isTranslatable } = pickAgentVoiceCallerLabelTextKey(ring.callerLabelKey);\n // The package's untranslated default fills the placeholders of a key no translator knows.\n return { text: isTranslatable ? translate(labelTextKey) : DEFAULT_AGENTS_TEXTS.translate(labelTextKey, { agentName }) };\n};\n","import { useEffect } from \"react\";\n\nconst RING_BURST_SECONDS = 1.2;\nconst RING_PERIOD_MS = 3_000;\nconst RING_FREQUENCIES_HZ = [440, 480];\nconst RING_VOLUME = 0.06;\n\ntype NavigatorWithUserActivation = Navigator & { userActivation?: { hasBeenActive: boolean } };\n\n/**\n * A phone-like ring tone while `isRinging`, synthesized with Web Audio (no asset). Browsers block audio until the user\n * has interacted with the page (autoplay policy): without that interaction this plays nothing and the visual ring is\n * the whole signal.\n */\nexport const useAgentVoiceRingTone = (isRinging: boolean) => {\n useEffect(() => {\n if (!isRinging) return;\n const userActivation = (navigator as NavigatorWithUserActivation).userActivation;\n if (userActivation !== undefined && !userActivation.hasBeenActive) return;\n if (typeof AudioContext === \"undefined\") return;\n const audioContext = new AudioContext();\n if (audioContext.state === \"suspended\") void audioContext.resume().catch(() => undefined);\n\n const playRingBurst = () => {\n if (audioContext.state !== \"running\") return;\n const startsAt = audioContext.currentTime;\n const gain = audioContext.createGain();\n gain.gain.setValueAtTime(RING_VOLUME, startsAt);\n gain.gain.setValueAtTime(RING_VOLUME, startsAt + RING_BURST_SECONDS - 0.05);\n gain.gain.linearRampToValueAtTime(0, startsAt + RING_BURST_SECONDS);\n gain.connect(audioContext.destination);\n RING_FREQUENCIES_HZ.forEach((frequencyHz) => {\n const oscillator = audioContext.createOscillator();\n oscillator.frequency.value = frequencyHz;\n oscillator.connect(gain);\n oscillator.start(startsAt);\n oscillator.stop(startsAt + RING_BURST_SECONDS);\n });\n };\n playRingBurst();\n const ringTimer = window.setInterval(playRingBurst, RING_PERIOD_MS);\n\n return () => {\n window.clearInterval(ringTimer);\n void audioContext.close().catch(() => undefined);\n };\n }, [isRinging]);\n};\n","import { useEffect, useRef } from \"react\";\nimport { isAgentVoiceCallActive, useAgentVoiceCallValue } from \"./agent-voice-call-store\";\n\n/** What the application does when the call's conversation is known: show that conversation beside the call. */\nexport type AgentVoiceConversationOfCallChangedHandler = (conversationId: number, agentSpaceId: number | undefined) => void;\n\n/**\n * Once per call and conversation, tells the application which conversation the call writes into: the one the chat\n * continued, or the one the backend created when the call started from an empty chat or from the agent's ring. The\n * application switches its chat there, so the transcript shows up beside the call. `agentSpaceId` is the call's agent\n * space where the start or the ring named one.\n */\nexport const useFollowAgentVoiceCallConversation = (\n onConversationOfCallChanged: AgentVoiceConversationOfCallChangedHandler | undefined,\n) => {\n const callPhase = useAgentVoiceCallValue((call) => call.phase);\n const callId = useAgentVoiceCallValue((call) => call.callId);\n const callConversationId = useAgentVoiceCallValue((call) => call.conversationId);\n const callAgentSpaceId = useAgentVoiceCallValue((call) => call.agentSpaceId);\n const reportedCallAndConversationRef = useRef<string | undefined>(undefined);\n\n useEffect(() => {\n if (onConversationOfCallChanged === undefined) return;\n if (!isAgentVoiceCallActive(callPhase) || callId === undefined || callConversationId === undefined) return;\n const callAndConversation = `${callId}:${callConversationId}`;\n if (reportedCallAndConversationRef.current === callAndConversation) return;\n reportedCallAndConversationRef.current = callAndConversation;\n onConversationOfCallChanged(callConversationId, callAgentSpaceId);\n }, [callPhase, callId, callConversationId, callAgentSpaceId, onConversationOfCallChanged]);\n};\n","import { createContext, useCallback, useContext } from \"react\";\nimport { useAgentsTexts } from \"../../provider/AgentsProvider\";\nimport { type AgentsTexts, getAgentDisplayName } from \"../../provider/environment\";\nimport type { AgentVoiceRingSource } from \"../ring/agent-voice-ring-source\";\n\n/** What `AgentVoiceCallProvider` carries to the voice components below it. */\nexport interface AgentVoiceCallContextValue {\n ringSource: AgentVoiceRingSource | undefined;\n}\n\n/** Without a provider: no ring source (nothing rings). */\nexport const AgentVoiceCallContext = createContext<AgentVoiceCallContextValue>({ ringSource: undefined });\n\n/** The ring source of the provider above (undefined: the application has no ring transport). */\nexport const useAgentVoiceRingSource = (): AgentVoiceRingSource | undefined => useContext(AgentVoiceCallContext).ringSource;\n\n/** The text function of the voice components: a text key and what its `%placeholders%` are filled with. */\nexport type AgentVoiceTranslateText = (key: string, replacements?: Record<string, string | number>) => string;\n\n/**\n * The text function of the voice components: the texts of the environment around (`AgentsEnvironment.texts`, a\n * subtree's own over the app-wide ones) with `%agentName%` filled with the name the owner knows the agent by\n * (`AgentsEnvironment.agentDisplayName`).\n */\nexport const useAgentVoiceTranslateText = (): AgentVoiceTranslateText => {\n const texts: AgentsTexts = useAgentsTexts();\n return useCallback<AgentVoiceTranslateText>(\n (key, replacements) => texts.translate(key, { agentName: getAgentDisplayName(), ...replacements }),\n [texts],\n );\n};\n","import { type ReactNode, useEffect, useMemo } from \"react\";\nimport type { AgentVoiceApi } from \"../agent-voice-api\";\nimport { bindAgentVoiceApi } from \"../call/agent-voice-call-store\";\nimport { useAgentVoiceCallServerEnd } from \"../call/use-agent-voice-call-server-end\";\nimport {\n type AgentVoiceConversationOfCallChangedHandler,\n useFollowAgentVoiceCallConversation,\n} from \"../call/use-follow-agent-voice-call-conversation\";\nimport type { AgentVoiceRingSource } from \"../ring/agent-voice-ring-source\";\nimport { AgentVoiceCallContext } from \"./agent-voice-call-context\";\n\nexport interface AgentVoiceCallProviderProps {\n /** The adapter the call store and the ring send their requests through. */\n api: AgentVoiceApi;\n /** The stream of the agent's rings. Without one nothing rings in this client. */\n ringSource?: AgentVoiceRingSource;\n /** Called once per call when the conversation the call writes into is known: the application shows it. */\n onConversationOfCallChanged?: AgentVoiceConversationOfCallChangedHandler;\n children?: ReactNode;\n}\n\n/**\n * Mounted once, above every voice component: binds the adapter to the call store, carries the ring source, ends the\n * call here when the server ended it (the change signal of the call's conversation, from the conversation client in\n * the context above the provider) and reports the call's conversation. The call itself lives in the module's store,\n * not in the provider: it goes on when the provider re-renders or a chat below it closes. The voice components take\n * their texts from the environment around (`AgentsEnvironment.texts`), as every other component of the package.\n */\nexport const AgentVoiceCallProvider = (props: AgentVoiceCallProviderProps) => {\n const { api, ringSource, onConversationOfCallChanged, children } = props;\n\n useEffect(() => {\n bindAgentVoiceApi(api);\n }, [api]);\n useAgentVoiceCallServerEnd();\n useFollowAgentVoiceCallConversation(onConversationOfCallChanged);\n\n const contextValue = useMemo(() => ({ ringSource }), [ringSource]);\n return <AgentVoiceCallContext.Provider value={contextValue}>{children}</AgentVoiceCallContext.Provider>;\n};\n","import { startAgentVoiceCall, useIsAgentVoiceCallActive } from \"../call/agent-voice-call-store\";\nimport { VoiceBarsIcon } from \"../../chat/ConversationMessage/ConversationCallMarkerChip/VoiceBarsIcon/VoiceBarsIcon\";\nimport { useAgentVoiceTranslateText } from \"../AgentVoiceCallProvider/agent-voice-call-context\";\nimport styles from \"./AgentVoiceChatStartButton.module.scss\";\n\nexport interface AgentVoiceChatStartButtonProps {\n /** The chat's agent space, where the application has one. */\n agentSpaceId?: number;\n /** The chat's conversation the voice chat continues; without one the backend creates a conversation for it. */\n conversationId?: number;\n /** The owner may not start a voice chat here (the application's own gate). */\n disabled?: boolean;\n testId?: string;\n}\n\n/**\n * In a chat input's send spot while nothing is typed and no voice chat runs: starts a voice chat with the agent. An\n * input outside the chat uses it too; the application shows the call's conversation when the provider reports it\n * (`onConversationOfCallChanged`). Disabled while a voice chat is connecting or live.\n */\nexport const AgentVoiceChatStartButton = (props: AgentVoiceChatStartButtonProps) => {\n const { agentSpaceId, conversationId, disabled = false, testId = \"agent-voice-chat-start\" } = props;\n const translateText = useAgentVoiceTranslateText();\n const isCallActive = useIsAgentVoiceCallActive();\n const label = translateText(\"Talk to %agentName%\");\n\n return (\n <button\n type=\"button\"\n className={styles.startButton}\n onClick={() => void startAgentVoiceCall({ agentSpaceId, conversationId })}\n disabled={disabled || isCallActive}\n aria-label={label}\n title={label}\n data-testid={testId}\n >\n <VoiceBarsIcon size={18} />\n </button>\n );\n};\n","import type { ReactNode } from \"react\";\nimport styles from \"./AgentVoiceIcons.module.scss\";\n\n// The line icons of the band and the incoming call. The mark of a voice chat itself (five sound bars) is the chat's\n// own `VoiceBarsIcon`, the one its call markers show.\n\nexport interface AgentVoiceLineIconProps {\n /** Edge length in px; the icon takes the current text colour. */\n size?: number;\n}\n\nconst renderLineIcon = (size: number, paths: ReactNode) => (\n <svg className={styles.icon} width={size} height={size} viewBox=\"0 0 24 24\" aria-hidden focusable=\"false\">\n {paths}\n </svg>\n);\n\n/** The microphone: the band's Mute and the incoming call's Accept. */\nexport const AgentVoiceMicrophoneIcon = (props: AgentVoiceLineIconProps) =>\n renderLineIcon(\n props.size ?? 16,\n <path d=\"M12 3.5a3 3 0 0 0-3 3v5a3 3 0 0 0 6 0v-5a3 3 0 0 0-3-3ZM5.5 11.5a6.5 6.5 0 0 0 13 0M12 18v2.5\" />,\n );\n\n/** The receiver laid down: the band's End. */\nexport const AgentVoiceHangUpIcon = (props: AgentVoiceLineIconProps) =>\n renderLineIcon(\n props.size ?? 16,\n <path d=\"M3.5 14.5c4.7-4.7 12.3-4.7 17 0l-2.2 2.2-3.1-1.4v-2.4a9.6 9.6 0 0 0-6.4 0v2.4l-3.1 1.4-2.2-2.2Z\" />,\n );\n\n/** The cross: Decline and the band's Close. */\nexport const AgentVoiceCloseIcon = (props: AgentVoiceLineIconProps) =>\n renderLineIcon(props.size ?? 16, <path d=\"M6 6l12 12M18 6 6 18\" />);\n","import {\n AGENT_VOICE_CALL_END_REASON_ENDED_BY_AGENT,\n AGENT_VOICE_CALL_END_REASON_LIMIT_REACHED,\n} from \"../call/agent-voice-call-end-reasons\";\nimport type { AgentVoiceCallSnapshot } from \"../call/agent-voice-call-store\";\nimport { textKey } from \"../../provider/text-key\";\n\n/** An ended voice chat that was connected: who or what ended it (the call's end reason, when the server ended it). */\nexport const endedAgentVoiceCallTitleTextKey = (call: Pick<AgentVoiceCallSnapshot, \"endReason\">): string => {\n if (call.endReason === AGENT_VOICE_CALL_END_REASON_ENDED_BY_AGENT) return textKey(\"%agentName% ended the voice chat\");\n if (call.endReason === AGENT_VOICE_CALL_END_REASON_LIMIT_REACHED) return textKey(\"Voice chat limit reached\");\n return textKey(\"Voice chat ended\");\n};\n\n/**\n * The band's title after a voice chat (`phase` `ended` or `failed`): a failed one says so; an ended one that was\n * connected says who or what ended it; one hung up before it connected (nothing was said) was cancelled.\n */\nexport const agentVoiceCallOutcomeTitleTextKey = (\n call: Pick<AgentVoiceCallSnapshot, \"phase\" | \"connectedAtMs\" | \"endReason\">,\n): string => {\n if (call.phase === \"failed\") return textKey(\"Voice chat failed\");\n return call.connectedAtMs !== undefined ? endedAgentVoiceCallTitleTextKey(call) : textKey(\"Voice chat cancelled\");\n};\n","import { getAgentDisplayName } from \"../../provider/environment\";\nimport type { ReactNode } from \"react\";\nimport {\n type AgentVoiceCallSnapshot,\n dismissAgentVoiceCallOutcome,\n hangUpAgentVoiceCall,\n IDLE_AGENT_VOICE_CALL,\n isAgentVoiceCallActive,\n isAgentVoiceCallShownInAgentSpace,\n startAgentVoiceCall,\n toggleAgentVoiceCallMute,\n useAgentVoiceCallSnapshot,\n} from \"../call/agent-voice-call-store\";\nimport { type AgentVoiceCallTurn, turnOfAgentVoiceCall } from \"../call/agent-voice-call-turn\";\nimport { formatAgentVoiceCallDuration } from \"../call/format-agent-voice-call-duration\";\nimport { useAgentVoiceCallElapsedSeconds } from \"../call/use-agent-voice-call-elapsed-seconds\";\nimport { type AgentVoiceCallerLabel, buildAgentVoiceCallerLabel } from \"../ring/agent-voice-caller-label\";\nimport {\n acceptAgentVoiceIncomingRing,\n declineAgentVoiceIncomingRing,\n useAgentVoiceIncomingRing,\n useAgentVoiceRingBandHost,\n} from \"../ring/agent-voice-incoming-ring-store\";\nimport type { AgentVoiceRing } from \"../ring/agent-voice-ring\";\nimport { AGENT_VOICE_ANSWER_REFUSAL_TEXT_KEYS, type AgentVoiceAnswerRefusal } from \"../ring/answer-incoming-agent-voice-call\";\nimport { textKey } from \"../../provider/text-key\";\nimport { VoiceBarsIcon } from \"../../chat/ConversationMessage/ConversationCallMarkerChip/VoiceBarsIcon/VoiceBarsIcon\";\nimport { AgentVoiceCloseIcon, AgentVoiceHangUpIcon, AgentVoiceMicrophoneIcon } from \"../AgentVoiceIcons/AgentVoiceIcons\";\nimport { useAgentVoiceTranslateText } from \"../AgentVoiceCallProvider/agent-voice-call-context\";\nimport { agentVoiceCallOutcomeTitleTextKey } from \"./agent-voice-call-outcome-title-text-key\";\nimport styles from \"./AgentVoiceCallBand.module.scss\";\n\nconst TURN_STATUS_TEXT_KEYS: Readonly<Record<AgentVoiceCallTurn, string>> = {\n connecting: textKey(\"Connecting…\"),\n muted: textKey(\"You’re muted\"),\n silentMicrophone: textKey(\"I can’t hear you — is your microphone on?\"),\n agent: textKey(\"%agentName% is speaking\"),\n owner: textKey(\"You’re speaking\"),\n thinking: textKey(\"%agentName% is thinking\"),\n listening: textKey(\"%agentName% is listening\"),\n};\n\ninterface AgentVoiceBandActionProps {\n label: string;\n icon: ReactNode;\n onClick: () => void;\n testId: string;\n /** The label stays out of sight and only names the button (the band's Close). */\n iconOnly?: boolean;\n pressed?: boolean;\n variant?: \"end\" | \"accept\";\n disabled?: boolean;\n}\n\n/** A pill on the dark band. */\nconst AgentVoiceBandAction = (props: AgentVoiceBandActionProps) => {\n const { label, icon, onClick, testId, iconOnly = false, pressed, variant, disabled = false } = props;\n return (\n <button\n type=\"button\"\n className={styles.action}\n onClick={onClick}\n aria-pressed={pressed}\n disabled={disabled}\n data-variant={variant}\n data-icon-only={iconOnly || undefined}\n data-testid={testId}\n >\n {icon}\n <span className={styles.actionLabel}>{label}</span>\n </button>\n );\n};\n\nexport interface AgentVoiceCallIncomingRing {\n ring?: AgentVoiceRing;\n /** The caller line of `ring`; without one the band words the ring's own label key. */\n callerLabel?: AgentVoiceCallerLabel;\n isAnswering: boolean;\n /** Why the last Accept did not get the call. */\n refusal?: AgentVoiceAnswerRefusal;\n onAccept: () => void;\n /** Decline: lets the ring go. */\n onDecline: () => void;\n}\n\nexport interface AgentVoiceCallBandViewProps {\n call: AgentVoiceCallSnapshot;\n elapsedSeconds: number;\n /** Talk with the agent again after an ended or failed voice chat. */\n onStartVoiceChat: () => void;\n /** The agent ringing this client: while no voice chat runs, the band asks to talk. */\n incoming?: AgentVoiceCallIncomingRing;\n /** The application's avatar of the agent, before the name (while a call runs or the agent rings). */\n agentSpot?: ReactNode;\n}\n\n/**\n * The voice chat in the band over the chat input: before it, the agent asking to talk (Decline, Accept); during it,\n * who is on the line, for how long and whose turn it is, with Mute and End; after it, the outcome with the way to talk\n * again. Driven only by its props: the band feeds it the live call, a test or a showcase feeds it fixtures.\n */\nexport const AgentVoiceCallBandView = (props: AgentVoiceCallBandViewProps) => {\n const { call, elapsedSeconds, onStartVoiceChat, incoming, agentSpot } = props;\n const translateText = useAgentVoiceTranslateText();\n const duration = formatAgentVoiceCallDuration(elapsedSeconds);\n const agentName = getAgentDisplayName();\n const spot = agentSpot === undefined || agentSpot === null ? null : <div className={styles.spot}>{agentSpot}</div>;\n\n if (isAgentVoiceCallActive(call.phase)) {\n return (\n <div className={styles.band} data-testid=\"agent-voice-call-band\" data-phase={call.phase}>\n {/* Keyed by the phase: the words and buttons come in again as the call connects. */}\n <div key={call.phase} className={styles.content}>\n {spot}\n <div className={styles.who} aria-live=\"polite\">\n <span className={styles.title}>{agentName}</span>\n {call.phase === \"live\" && <span className={styles.time}>{duration}</span>}\n <span className={styles.status} data-testid=\"agent-voice-call-status\">\n {translateText(TURN_STATUS_TEXT_KEYS[turnOfAgentVoiceCall(call)])}\n </span>\n </div>\n <div className={styles.actions}>\n <AgentVoiceBandAction\n label={call.isMuted ? translateText(\"Unmute\") : translateText(\"Mute\")}\n icon={<AgentVoiceMicrophoneIcon />}\n onClick={toggleAgentVoiceCallMute}\n pressed={call.isMuted}\n disabled={call.phase !== \"live\"}\n testId=\"agent-voice-call-mute\"\n />\n <AgentVoiceBandAction\n label={translateText(\"End\")}\n icon={<AgentVoiceHangUpIcon />}\n onClick={() => hangUpAgentVoiceCall()}\n variant=\"end\"\n testId=\"agent-voice-call-end\"\n />\n </div>\n </div>\n </div>\n );\n }\n\n if (incoming?.ring) {\n const callerLabel = incoming.callerLabel ?? buildAgentVoiceCallerLabel(incoming.ring, translateText, agentName);\n return (\n <div className={styles.band} data-testid=\"agent-voice-call-band\" data-phase=\"incoming\">\n <div key=\"incoming\" className={styles.content}>\n {spot}\n <div className={styles.who} role=\"alert\">\n <span className={styles.title}>{callerLabel.text}</span>\n {callerLabel.detail ? <span className={styles.status}>{callerLabel.detail}</span> : null}\n </div>\n <div className={styles.actions}>\n <AgentVoiceBandAction\n label={translateText(\"Decline\")}\n icon={<AgentVoiceCloseIcon />}\n onClick={incoming.onDecline}\n variant=\"end\"\n disabled={incoming.isAnswering}\n testId=\"agent-voice-call-incoming-decline\"\n />\n <AgentVoiceBandAction\n label={translateText(\"Accept\")}\n icon={<VoiceBarsIcon size={16} />}\n onClick={incoming.onAccept}\n variant=\"accept\"\n disabled={incoming.isAnswering}\n testId=\"agent-voice-call-incoming-accept\"\n />\n </div>\n </div>\n </div>\n );\n }\n\n if (incoming?.refusal && call.phase === \"idle\") {\n return (\n <div className={styles.band} data-testid=\"agent-voice-call-band\" data-phase=\"refused\">\n <div key=\"refused\" className={styles.content}>\n <div className={styles.who} role=\"status\">\n <span className={styles.status} data-testid=\"agent-voice-call-incoming-refusal\">\n {translateText(AGENT_VOICE_ANSWER_REFUSAL_TEXT_KEYS[incoming.refusal])}\n </span>\n </div>\n </div>\n </div>\n );\n }\n\n if (call.phase !== \"ended\" && call.phase !== \"failed\") return null;\n // Hung up before `session.started`: nothing was said.\n const wasConnected = call.connectedAtMs !== undefined;\n const titleTextKey = agentVoiceCallOutcomeTitleTextKey(call);\n\n return (\n <div className={styles.band} data-testid=\"agent-voice-call-band\" data-phase={call.phase} data-end-reason={call.endReason}>\n <div key={call.phase} className={styles.content}>\n <div className={styles.who} aria-live=\"polite\">\n <span\n className={styles.title}\n data-testid={call.phase === \"ended\" && wasConnected ? \"agent-voice-call-ended-status\" : undefined}\n >\n {translateText(titleTextKey)}\n </span>\n {call.phase === \"ended\" && wasConnected && <span className={styles.time}>{duration}</span>}\n {call.phase === \"failed\" && call.failureTextKey && (\n <span className={styles.status} data-testid=\"agent-voice-call-failure\">\n {translateText(call.failureTextKey)}\n </span>\n )}\n </div>\n <div className={styles.actions}>\n <AgentVoiceBandAction\n label={call.phase === \"failed\" ? translateText(\"Try again\") : translateText(\"Talk with %agentName% again\")}\n icon={<VoiceBarsIcon size={16} />}\n onClick={onStartVoiceChat}\n variant=\"accept\"\n testId=\"agent-voice-call-start-again\"\n />\n <AgentVoiceBandAction\n label={translateText(\"Close\")}\n icon={<AgentVoiceCloseIcon />}\n onClick={dismissAgentVoiceCallOutcome}\n iconOnly\n testId=\"agent-voice-call-band-close\"\n />\n </div>\n </div>\n </div>\n );\n};\n\nexport interface AgentVoiceCallBandProps {\n /** The application's avatar of the agent for the call (it gets the call to show whose turn it is). */\n renderAgentSpot?: (call: AgentVoiceCallSnapshot) => ReactNode;\n /** The chat's agent space, where the application has one: a voice chat running in another one shows nothing here. */\n agentSpaceId?: number;\n /**\n * False while the chat that holds the band is out of sight (behind another surface): the band then hosts no ring,\n * and the incoming call shows its own card. Default true.\n */\n isPresented?: boolean;\n}\n\n/**\n * The band of the agent ringing this client and of the running (or just finished) voice chat; renders nothing while\n * there is none. While presented it is where the ring is answered, so the page-level incoming call stays away. \"Talk\n * again\" starts a voice chat in the ended call's agent space and conversation.\n */\nexport const AgentVoiceCallBand = (props: AgentVoiceCallBandProps) => {\n const { renderAgentSpot, agentSpaceId, isPresented = true } = props;\n const liveCall = useAgentVoiceCallSnapshot();\n const call = isAgentVoiceCallShownInAgentSpace(liveCall, agentSpaceId) ? liveCall : IDLE_AGENT_VOICE_CALL;\n const elapsedSeconds = useAgentVoiceCallElapsedSeconds(call);\n const { ring, callerLabel, isAnswering, refusal } = useAgentVoiceIncomingRing();\n useAgentVoiceRingBandHost(isPresented);\n\n return (\n <AgentVoiceCallBandView\n call={call}\n elapsedSeconds={elapsedSeconds}\n agentSpot={renderAgentSpot?.(call)}\n onStartVoiceChat={() =>\n void startAgentVoiceCall({ agentSpaceId: call.agentSpaceId ?? agentSpaceId, conversationId: call.conversationId })\n }\n incoming={{\n ring,\n callerLabel,\n isAnswering,\n refusal,\n onAccept: () => void acceptAgentVoiceIncomingRing(),\n onDecline: declineAgentVoiceIncomingRing,\n }}\n />\n );\n};\n","import type { ChatMessage } from \"../../chat/chat-message\";\nimport type { SavedAgentVoiceCallMessage } from \"../call/build-unsaved-agent-voice-call-lines\";\n\n/** What the rules below read of a chat message. */\ntype ChatMessageOfVoiceChat = Pick<ChatMessage, \"role\" | \"message\" | \"indexInConversation\">;\n\n/** The highest index in the conversation among `messages`; -1 for none, or when no message carries an index yet. */\nexport const highestIndexInConversationOf = (messages: readonly ChatMessageOfVoiceChat[]): number =>\n messages.reduce((highestIndex, message) => Math.max(highestIndex, message.indexInConversation ?? -1), -1);\n\n/**\n * What the chat holds of the voice chat: the agent's and the owner's text messages saved after the voice chat started\n * (an index above `highestIndexBeforeVoiceChat`), in the conversation's order, each as the speaker and the text.\n */\nexport const savedMessagesOfTheVoiceChat = (\n messages: readonly ChatMessageOfVoiceChat[],\n highestIndexBeforeVoiceChat: number,\n): SavedAgentVoiceCallMessage[] =>\n [...messages]\n .filter(\n (message) =>\n (message.role === \"ASSISTANT\" || message.role === \"USER\") &&\n typeof message.message === \"string\" &&\n (message.indexInConversation ?? -1) > highestIndexBeforeVoiceChat,\n )\n .sort((first, second) => (first.indexInConversation ?? 0) - (second.indexInConversation ?? 0))\n .map((message) => ({ speaker: message.role === \"ASSISTANT\" ? \"agent\" : \"owner\", text: message.message as string }));\n","import { useEffect, useMemo, useState } from \"react\";\nimport type { ChatMessage } from \"../../chat/chat-message\";\nimport {\n ConversationMessageUser,\n type ConversationMessageUserTheme,\n} from \"../../chat/ConversationMessage/ConversationMessageUser/ConversationMessageUser\";\nimport { ConversationMessageWidgets } from \"../../chat/ConversationMessage/ConversationMessageWidgets/ConversationMessageWidgets\";\nimport { type AgentsChatState, useAgentsChatSelector, useOptionalAgentsChatStore } from \"../../chat/store\";\nimport {\n type AgentVoiceCallSnapshot,\n isAgentVoiceCallActive,\n isAgentVoiceCallShownInAgentSpace,\n useAgentVoiceCallSnapshot,\n} from \"../call/agent-voice-call-store\";\nimport { buildUnsavedAgentVoiceCallLines } from \"../call/build-unsaved-agent-voice-call-lines\";\nimport { highestIndexInConversationOf, savedMessagesOfTheVoiceChat } from \"./saved-messages-of-agent-voice-chat\";\nimport styles from \"./AgentVoiceCallCaptions.module.scss\";\n\nconst NO_MESSAGES: ChatMessage[] = [];\nconst selectMessages = (state: AgentsChatState) => state.messages;\n\ninterface AgentVoiceCallCaptionLinesProps {\n call: AgentVoiceCallSnapshot;\n ownerMessageTheme: ConversationMessageUserTheme | undefined;\n}\n\n/** The lines of one voice chat: mounted while it is connecting or live, so every voice chat starts with its own count. */\nconst AgentVoiceCallCaptionLines = (props: AgentVoiceCallCaptionLinesProps) => {\n const { call, ownerMessageTheme } = props;\n const chatStore = useOptionalAgentsChatStore();\n const messages = useAgentsChatSelector(chatStore, selectMessages, null) ?? NO_MESSAGES;\n const [highestIndexBeforeVoiceChat, setHighestIndexBeforeVoiceChat] = useState<number | undefined>(undefined);\n\n // Taken once as the voice chat starts: what the chat held before was not said in it.\n useEffect(() => {\n if (highestIndexBeforeVoiceChat === undefined) setHighestIndexBeforeVoiceChat(highestIndexInConversationOf(messages));\n }, [highestIndexBeforeVoiceChat, messages]);\n\n const unsavedLines = useMemo(\n () =>\n highestIndexBeforeVoiceChat === undefined\n ? []\n : buildUnsavedAgentVoiceCallLines(call.lines, savedMessagesOfTheVoiceChat(messages, highestIndexBeforeVoiceChat)),\n [call.lines, messages, highestIndexBeforeVoiceChat],\n );\n\n return (\n <div className={styles.captions} data-testid=\"agent-voice-call-captions\">\n {unsavedLines.map((line) =>\n line.speaker === \"agent\" ? (\n <div key={line.id} className={styles.line} data-testid=\"agent-voice-call-caption-agent\">\n <ConversationMessageWidgets message={line.text} interactive={false} justDelivered={false} hideAssistantMeta />\n </div>\n ) : (\n <div key={line.id} className={styles.line} data-testid=\"agent-voice-call-caption-owner\">\n <ConversationMessageUser text={line.text} theme={ownerMessageTheme} />\n </div>\n ),\n )}\n </div>\n );\n};\n\nexport interface AgentVoiceCallCaptionsProps {\n /** The chat's agent space, where the application has one: a voice chat running in another one shows nothing here. */\n agentSpaceId?: number;\n /** The theme of the owner's line, as the chat renders the owner's messages. Default: the message component's own. */\n ownerMessageTheme?: ConversationMessageUserTheme;\n}\n\n/**\n * The end of the chat while a voice chat runs: what is being said that the chat does not hold yet, streamed from the\n * browser as the agent's prose and the owner's bubble (the chat's own message components), each sentence giving way\n * to the real message once the backend saved it. Sits inside the chat, after its message list (it reads the chat's\n * messages from the chat store in the context); outside one, every line of the call shows. Renders nothing while no\n * voice chat is connecting or live.\n */\nexport const AgentVoiceCallCaptions = (props: AgentVoiceCallCaptionsProps) => {\n const { agentSpaceId, ownerMessageTheme } = props;\n const call = useAgentVoiceCallSnapshot();\n if (!isAgentVoiceCallActive(call.phase) || !isAgentVoiceCallShownInAgentSpace(call, agentSpaceId)) return null;\n return <AgentVoiceCallCaptionLines call={call} ownerMessageTheme={ownerMessageTheme} />;\n};\n","import type { AgentVoiceCallTurn } from \"../call/agent-voice-call-turn\";\n\n/** Who is making sound right now, as the input glow draws it. */\nexport type AgentVoiceInputGlowVoice = \"agent\" | \"owner\" | \"thinking\" | \"quiet\";\n\n/**\n * The glow's voice of a call's turn: the agent or the owner while one of them speaks, the slow breath while the agent\n * thinks or the call connects, quiet for every other turn (listening, muted, a silent microphone).\n */\nexport const glowVoiceOfAgentVoiceCallTurn = (turn: AgentVoiceCallTurn): AgentVoiceInputGlowVoice => {\n if (turn === \"agent\") return \"agent\";\n if (turn === \"owner\") return \"owner\";\n if (turn === \"thinking\" || turn === \"connecting\") return \"thinking\";\n return \"quiet\";\n};\n","import { useEffect, useRef } from \"react\";\nimport { isAgentVoiceCallActive, useAgentVoiceCallValue, useIsAgentVoiceCallActive } from \"../call/agent-voice-call-store\";\nimport { turnOfAgentVoiceCall } from \"../call/agent-voice-call-turn\";\nimport { type AgentVoiceInputGlowVoice, glowVoiceOfAgentVoiceCallTurn } from \"./agent-voice-input-glow-voice\";\nimport styles from \"./AgentVoiceInputGlow.module.scss\";\n\n/** How far past the input the canvases reach: room for the loudest wave and its fade. Same as the canvases' inset in\n * the stylesheet. */\nconst CANVAS_PADDING_PX = 200;\n/** The glow's reach past the edge at rest. */\nconst REST_REACH_PX = 9;\n/** How much further the loudest syllable takes it. */\nconst LOUD_REACH_PX = 42;\n/** How finely the glow's edge follows the wave (CSS px). */\nconst EDGE_STEP_PX = 4;\n/** The burst when the field is clicked into: how long (s) and how much further it takes the glow. */\nconst BURST_SECONDS = 1;\nconst BURST_REACH_PX = 22;\n/** The agent's speaking pace: one word every this many ms sets the pulse of its syllables. */\nconst AGENT_MS_PER_WORD = 330;\nconst OWNER_MS_PER_SYLLABLE = 260;\n/**\n * The glow's shades, round the field: custom properties with their defaults. A property may be a relative colour a\n * canvas cannot read, so the page resolves it.\n */\nconst GLOW_COLOUR_PROPERTIES: readonly (readonly [property: string, defaultColour: string])[] = [\n [\"--agents-voice-glow-color-1\", \"#00495d\"],\n [\"--agents-voice-glow-color-2\", \"#29ecfa\"],\n [\"--agents-voice-glow-color-3\", \"#e0c9fd\"],\n [\"--agents-voice-glow-color-4\", \"#12ffff\"],\n [\"--agents-voice-glow-color-1\", \"#00495d\"],\n];\n\n/**\n * The glow itself: a soft light round the field in the agent's colours, flowing round it, that swells into a waveform\n * as the agent talks (the waves running out from the top middle in time with its syllables), the owner's smaller, from\n * the bottom edge; a slow breath while the agent thinks; a short even glow at rest. Clicking into the field bursts it\n * out. Two canvases behind the field: the glow close in, and a wider, fainter copy.\n */\nconst AgentVoiceInputGlowCanvases = () => {\n const voice = useAgentVoiceCallValue((call): AgentVoiceInputGlowVoice =>\n isAgentVoiceCallActive(call.phase) ? glowVoiceOfAgentVoiceCallTurn(turnOfAgentVoiceCall(call)) : \"quiet\",\n );\n const boxRef = useRef<HTMLDivElement>(null);\n const edgeCanvasRef = useRef<HTMLCanvasElement>(null);\n const haloCanvasRef = useRef<HTMLCanvasElement>(null);\n // Read by the drawing loop each frame, so a change of voice does not restart it.\n const voiceRef = useRef(voice);\n voiceRef.current = voice;\n const burstStartedAtSecondsRef = useRef(Number.NEGATIVE_INFINITY);\n\n useEffect(() => {\n const box = boxRef.current;\n const edgeCanvas = edgeCanvasRef.current;\n const haloCanvas = haloCanvasRef.current;\n const edgeContext = edgeCanvas?.getContext(\"2d\");\n const haloContext = haloCanvas?.getContext(\"2d\");\n const maskCanvas = document.createElement(\"canvas\");\n const maskContext = maskCanvas.getContext(\"2d\");\n if (!box || !edgeCanvas || !haloCanvas || !edgeContext || !haloContext || !maskContext) return;\n const prefersReducedMotion = window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches;\n\n const colourProbe = document.createElement(\"span\");\n box.appendChild(colourProbe);\n const glowColours = GLOW_COLOUR_PROPERTIES.map(([property, defaultColour]) => {\n colourProbe.style.color = `var(${property}, ${defaultColour})`;\n return getComputedStyle(colourProbe).color;\n });\n colourProbe.remove();\n\n // The field is the input the glow sits under: clicking into it bursts the glow out.\n const field = box.parentElement;\n const startBurst = () => {\n burstStartedAtSecondsRef.current = performance.now() / 1000;\n };\n field?.addEventListener(\"focusin\", startBurst);\n\n let width = 0;\n let height = 0;\n let pixelRatio = 1;\n const resizeCanvases = () => {\n const boxRect = box.getBoundingClientRect();\n width = boxRect.width;\n height = boxRect.height;\n pixelRatio = Math.min(2, window.devicePixelRatio || 1);\n [edgeCanvas, haloCanvas, maskCanvas].forEach((canvas) => {\n canvas.width = Math.round((width + CANVAS_PADDING_PX * 2) * pixelRatio);\n canvas.height = Math.round((height + CANVAS_PADDING_PX * 2) * pixelRatio);\n });\n };\n\n let loudness = 0;\n // -1: the sound comes from the top (the agent, above); 1: from the bottom (the owner).\n let soundSide = -1;\n let colourTurn = 0;\n let lastFrameSeconds = 0;\n let animationFrameId = 0;\n\n const drawFrame = (frameMs: number) => {\n const frameSeconds = frameMs / 1000;\n const frameDeltaSeconds = lastFrameSeconds ? Math.min(0.1, frameSeconds - lastFrameSeconds) : 0.016;\n lastFrameSeconds = frameSeconds;\n const currentVoice = voiceRef.current;\n\n const syllable = (periodMs: number) => Math.abs(Math.sin((Math.PI * frameMs) / periodMs));\n const targetLoudness =\n currentVoice === \"agent\"\n ? (0.5 + 0.5 * syllable(AGENT_MS_PER_WORD)) * (0.85 + 0.15 * Math.sin(frameSeconds * 23.7))\n : currentVoice === \"owner\"\n ? 0.42 * (0.55 + 0.45 * syllable(OWNER_MS_PER_SYLLABLE))\n : currentVoice === \"thinking\"\n ? 0.12 * (0.5 + 0.5 * Math.sin(frameSeconds * 2.4))\n : 0;\n // Quick to rise, slower to fall, as a level meter.\n const loudnessTimeConstant = targetLoudness > loudness ? 0.05 : 0.2;\n loudness += (targetLoudness - loudness) * (1 - Math.exp(-frameDeltaSeconds / loudnessTimeConstant));\n soundSide += ((currentVoice === \"owner\" ? 1 : -1) - soundSide) * (1 - Math.exp(-frameDeltaSeconds / 0.35));\n // The colours flow round the field, faster as the agent talks.\n colourTurn += frameDeltaSeconds * (0.1 + 0.4 * loudness);\n const burstProgress = (frameSeconds - burstStartedAtSecondsRef.current) / BURST_SECONDS;\n const burst =\n burstProgress >= 0 && burstProgress < 1 ? Math.pow(1 - burstProgress, 1.4) * Math.min(1, burstProgress / 0.06) : 0;\n\n const cornerRadius = Math.min(24, height / 2);\n // How far the glow reaches at x, up from the top edge or down from the bottom: waves running out both ways from\n // the middle, tall there and low at the sides.\n const reachAt = (x: number, isUpward: boolean) => {\n const distanceFromMiddle = Math.abs(x - width / 2);\n const nearMiddle = 0.12 + 0.88 * Math.exp(-((distanceFromMiddle / (width * 0.3)) ** 2));\n const wave =\n Math.abs(\n 0.6 * Math.sin(distanceFromMiddle * 0.01375 - frameSeconds * 3.2 + (isUpward ? 0 : 1.7)) +\n 0.4 * Math.sin(distanceFromMiddle * 0.0325 - frameSeconds * 5.1 + 1.3),\n ) *\n (0.65 + 0.35 * Math.sin(distanceFromMiddle * 0.00475 + frameSeconds * 1.05));\n const fromThisSide = isUpward ? (1 - soundSide) / 2 : (1 + soundSide) / 2;\n const loudReach = LOUD_REACH_PX * loudness * nearMiddle * wave * (0.25 + 0.75 * fromThisSide);\n const burstReach = BURST_REACH_PX * burst * (0.45 + 0.55 * Math.exp(-((distanceFromMiddle / (width * 0.6)) ** 2)));\n return REST_REACH_PX + loudReach + burstReach;\n };\n\n const canvasWidth = width + CANVAS_PADDING_PX * 2;\n const canvasHeight = height + CANVAS_PADDING_PX * 2;\n edgeContext.setTransform(pixelRatio, 0, 0, pixelRatio, 0, 0);\n edgeContext.globalCompositeOperation = \"source-over\";\n edgeContext.clearRect(0, 0, canvasWidth, canvasHeight);\n\n // One soft shape round the field, its top and bottom edges the waveform, filled with the glow's colours.\n const colourGradient = edgeContext.createConicGradient(\n colourTurn * Math.PI * 2,\n CANVAS_PADDING_PX + width / 2,\n CANVAS_PADDING_PX + height / 2,\n );\n glowColours.forEach((colour, index) => colourGradient.addColorStop(index / (glowColours.length - 1), colour));\n edgeContext.fillStyle = colourGradient;\n const topEdgePoints: [number, number][] = [];\n const bottomEdgePoints: [number, number][] = [];\n for (let x = -CANVAS_PADDING_PX; x <= width + CANVAS_PADDING_PX; x += EDGE_STEP_PX) {\n let fieldTop = height / 2;\n let fieldBottom = height / 2;\n if (x >= 0 && x <= width) {\n // The field's edge at x: straight along the middle, rounding off at the ends.\n const cornerInset = x < cornerRadius ? cornerRadius - x : x > width - cornerRadius ? x - (width - cornerRadius) : 0;\n const cornerDrop = cornerRadius - Math.sqrt(Math.max(0, cornerRadius ** 2 - cornerInset ** 2));\n fieldTop = cornerDrop;\n fieldBottom = height - cornerDrop;\n }\n // Past the ends, closing in the further out.\n const distancePastEnd = x < 0 ? -x : x > width ? x - width : 0;\n const closing = Math.exp(-distancePastEnd / 10);\n topEdgePoints.push([CANVAS_PADDING_PX + x, CANVAS_PADDING_PX + fieldTop - reachAt(x, true) * closing]);\n bottomEdgePoints.push([CANVAS_PADDING_PX + x, CANVAS_PADDING_PX + fieldBottom + reachAt(x, false) * closing]);\n }\n edgeContext.beginPath();\n topEdgePoints.forEach(([x, y], index) => (index ? edgeContext.lineTo(x, y) : edgeContext.moveTo(x, y)));\n [...bottomEdgePoints].reverse().forEach(([x, y]) => edgeContext.lineTo(x, y));\n edgeContext.closePath();\n edgeContext.fill();\n\n // Fading out from the edge: keep the glow only where a soft shadow of the field reaches.\n maskContext.setTransform(pixelRatio, 0, 0, pixelRatio, 0, 0);\n maskContext.clearRect(0, 0, canvasWidth, canvasHeight);\n maskContext.shadowColor = \"black\";\n maskContext.shadowBlur = ((REST_REACH_PX + LOUD_REACH_PX * loudness + BURST_REACH_PX * burst) * 1.5 + 10) * pixelRatio;\n maskContext.fillStyle = \"black\";\n maskContext.beginPath();\n maskContext.roundRect(CANVAS_PADDING_PX, CANVAS_PADDING_PX, width, height, cornerRadius);\n maskContext.fill();\n edgeContext.setTransform(1, 0, 0, 1, 0, 0);\n edgeContext.globalCompositeOperation = \"destination-in\";\n edgeContext.drawImage(maskCanvas, 0, 0);\n edgeContext.globalCompositeOperation = \"source-over\";\n\n // The wide light: the same glow, blurred wider by CSS.\n haloContext.setTransform(1, 0, 0, 1, 0, 0);\n haloContext.clearRect(0, 0, haloCanvas.width, haloCanvas.height);\n haloContext.drawImage(edgeCanvas, 0, 0);\n\n if (!prefersReducedMotion) animationFrameId = requestAnimationFrame(drawFrame);\n };\n\n const resizeObserver = new ResizeObserver(() => {\n resizeCanvases();\n if (prefersReducedMotion) drawFrame(0);\n });\n resizeObserver.observe(box);\n resizeCanvases();\n animationFrameId = requestAnimationFrame(drawFrame);\n return () => {\n cancelAnimationFrame(animationFrameId);\n resizeObserver.disconnect();\n field?.removeEventListener(\"focusin\", startBurst);\n };\n }, []);\n\n return (\n <div ref={boxRef} className={styles.glow} aria-hidden data-testid=\"agent-voice-input-glow\">\n <canvas ref={haloCanvasRef} className={styles.halo} />\n <canvas ref={edgeCanvasRef} className={styles.edge} />\n </div>\n );\n};\n\nexport interface AgentVoiceInputGlowProps {\n /** The chat's agent space, where the application has one: a voice chat running in another one glows nowhere here. */\n agentSpaceId?: number;\n}\n\n/**\n * The chat input's glow during a voice chat; renders nothing while no voice chat is connecting or live. Rendered as\n * the input's underlay: its box covers the input's whole box, under the field, and the field's own surface covers the\n * canvases' middle, so only what is past its edge shows. The field needs a positioned parent with its own stacking\n * context.\n */\nexport const AgentVoiceInputGlow = (props: AgentVoiceInputGlowProps) => {\n const { agentSpaceId } = props;\n const isCallActiveHere = useIsAgentVoiceCallActive(agentSpaceId);\n return isCallActiveHere ? <AgentVoiceInputGlowCanvases /> : null;\n};\n","import type { AgentVoiceRing } from \"./agent-voice-ring\";\n\n/** The held rings with `ring` at the end: a ring that arrives replaces the one of the same call, so a call rings once. */\nexport const withAgentVoiceIncomingRing = (\n heldRings: readonly AgentVoiceRing[],\n ring: AgentVoiceRing,\n): readonly AgentVoiceRing[] => [...heldRings.filter((heldRing) => heldRing.callId !== ring.callId), ring];\n\n/** The held rings without the ring of the call `callId`: a cleared ring goes at once. */\nexport const withoutAgentVoiceIncomingRingOfCall = (\n heldRings: readonly AgentVoiceRing[],\n callId: number,\n): readonly AgentVoiceRing[] => heldRings.filter((heldRing) => heldRing.callId !== callId);\n\n/**\n * The held rings whose deadline is after `nowMs`. The same list when none has passed its deadline, so a tick of the\n * clock that drops nothing changes nothing.\n */\nexport const agentVoiceIncomingRingsInDeadlineAt = (\n heldRings: readonly AgentVoiceRing[],\n nowMs: number,\n): readonly AgentVoiceRing[] => {\n const ringsInDeadline = heldRings.filter((heldRing) => heldRing.ringExpiresAtUnixMs > nowMs);\n return ringsInDeadline.length === heldRings.length ? heldRings : ringsInDeadline;\n};\n","import { useEffect, useState } from \"react\";\nimport {\n agentVoiceIncomingRingsInDeadlineAt,\n withAgentVoiceIncomingRing,\n withoutAgentVoiceIncomingRingOfCall,\n} from \"./agent-voice-incoming-ring-list\";\nimport type { AgentVoiceRing } from \"./agent-voice-ring\";\nimport type { AgentVoiceRingSource } from \"./agent-voice-ring-source\";\n\nconst NO_RINGS: readonly AgentVoiceRing[] = [];\n\nexport interface AgentVoiceIncomingRings {\n /** The rings that arrived and are still inside their deadline, one per call. */\n rings: readonly AgentVoiceRing[];\n /** The clock the deadlines were last read against: ticks every second while a ring is held. */\n nowMs: number;\n}\n\n/**\n * Listens for the agent's rings to this client while a ring source is given: a ring that arrives replaces the one of\n * the same call, a cleared one goes at once, and one whose deadline passed goes with the next tick of the clock. No\n * ring source (the application has no ring transport) or no ring: an empty list, and no clock running.\n */\nexport const useAgentVoiceIncomingRings = (ringSource: AgentVoiceRingSource | undefined): AgentVoiceIncomingRings => {\n const [rings, setRings] = useState<readonly AgentVoiceRing[]>(NO_RINGS);\n const [nowMs, setNowMs] = useState(() => Date.now());\n\n useEffect(() => {\n if (ringSource === undefined) return;\n const unsubscribe = ringSource.subscribe(\n (ring) => setRings((heldRings) => withAgentVoiceIncomingRing(heldRings, ring)),\n (callId) => setRings((heldRings) => withoutAgentVoiceIncomingRingOfCall(heldRings, callId)),\n );\n return () => {\n unsubscribe();\n setRings(NO_RINGS);\n };\n }, [ringSource]);\n\n const hasRings = rings.length > 0;\n useEffect(() => {\n if (!hasRings) return;\n setNowMs(Date.now());\n const clockTimer = window.setInterval(() => {\n const tickMs = Date.now();\n setNowMs(tickMs);\n setRings((heldRings) => agentVoiceIncomingRingsInDeadlineAt(heldRings, tickMs));\n }, 1_000);\n return () => window.clearInterval(clockTimer);\n }, [hasRings]);\n\n return { rings, nowMs };\n};\n","import { getAgentDisplayName } from \"../../provider/environment\";\nimport { type ReactNode, useEffect, useId } from \"react\";\nimport { isAgentVoiceCallActive, useAgentVoiceCallValue } from \"../call/agent-voice-call-store\";\nimport { type AgentVoiceCallerLabel, buildAgentVoiceCallerLabel } from \"../ring/agent-voice-caller-label\";\nimport {\n acceptAgentVoiceIncomingRing,\n declineAgentVoiceIncomingRing,\n pickAgentVoiceIncomingCard,\n publishAgentVoiceIncomingRing,\n useAgentVoiceIncomingRing,\n} from \"../ring/agent-voice-incoming-ring-store\";\nimport { type AgentVoiceRing, pickRingingAgentVoiceCall } from \"../ring/agent-voice-ring\";\nimport { AGENT_VOICE_ANSWER_REFUSAL_TEXT_KEYS } from \"../ring/answer-incoming-agent-voice-call\";\nimport { useAgentVoiceIncomingRings } from \"../ring/use-agent-voice-incoming-rings\";\nimport { useAgentVoiceRingTone } from \"../ring/use-agent-voice-ring-tone\";\nimport { VoiceBarsIcon } from \"../../chat/ConversationMessage/ConversationCallMarkerChip/VoiceBarsIcon/VoiceBarsIcon\";\nimport { AgentVoiceCloseIcon, AgentVoiceMicrophoneIcon } from \"../AgentVoiceIcons/AgentVoiceIcons\";\nimport { useAgentVoiceRingSource, useAgentVoiceTranslateText } from \"../AgentVoiceCallProvider/agent-voice-call-context\";\nimport styles from \"./AgentVoiceIncomingCall.module.scss\";\n\nexport interface AgentVoiceIncomingCallProps {\n /**\n * The application's own caller line for a ring (from what it put into the ring's `callerContext`): who is asking to\n * talk and, as `detail`, which of the owner's agent spaces it is. Undefined, or no resolver: the ring's label key\n * through the text function.\n */\n resolveCallerLabel?: (ring: AgentVoiceRing) => AgentVoiceCallerLabel | undefined;\n /** The application's avatar of the agent on the card. Default: the voice chat's mark. */\n renderAgentSpot?: () => ReactNode;\n}\n\n/**\n * The agent ringing the owner in the browser window: the one listener per client. While a ring is live it publishes it\n * (the band over an open chat's input offers Decline / Accept there) and plays the ring tone once the page had a user\n * interaction; with no chat band in sight (none open, or a surface covers them) it shows its own card with the same\n * choices, on top of the page. Accept answers the ring and, when this client won, starts the same WebRTC call as the\n * chat's voice button; Decline ends the ring for every open client. The ring goes when its deadline passed, when the\n * ring source reports it cleared, or when this client answered or declined it.\n *\n * A ring reaches every open client of the account, whatever the client shows: the caller line can name the calling\n * agent space (`resolveCallerLabel`), and Accept starts the call on the ring's own conversation.\n *\n * Mounted once, below `AgentVoiceCallProvider` and outside the chat, so it rings whether or not a chat is open. It\n * listens while the provider carries a ring source.\n */\nexport const AgentVoiceIncomingCall = (props: AgentVoiceIncomingCallProps) => {\n const { resolveCallerLabel, renderAgentSpot } = props;\n const translateText = useAgentVoiceTranslateText();\n const ringSource = useAgentVoiceRingSource();\n const isCallActive = useAgentVoiceCallValue((call) => isAgentVoiceCallActive(call.phase));\n const { ring, callerLabel, handledCallIds, isAnswering, refusal, bandHostCount, ringCoverCount } = useAgentVoiceIncomingRing();\n const { rings, nowMs } = useAgentVoiceIncomingRings(ringSource);\n\n const ringingCall = isCallActive ? undefined : pickRingingAgentVoiceCall(rings, nowMs, handledCallIds);\n const ringingCallerLabel =\n ringingCall === undefined\n ? undefined\n : (resolveCallerLabel?.(ringingCall) ?? buildAgentVoiceCallerLabel(ringingCall, translateText, getAgentDisplayName()));\n const ringingCallerLabelText = ringingCallerLabel?.text;\n const ringingCallerLabelDetail = ringingCallerLabel?.detail;\n useEffect(() => {\n publishAgentVoiceIncomingRing(\n ringingCall,\n ringingCallerLabelText === undefined ? undefined : { text: ringingCallerLabelText, detail: ringingCallerLabelDetail },\n );\n }, [ringingCall, ringingCallerLabelText, ringingCallerLabelDetail]);\n // The listener is gone: nothing it published rings on.\n useEffect(() => () => publishAgentVoiceIncomingRing(undefined, undefined), []);\n useAgentVoiceRingTone(ring !== undefined && !isAnswering);\n\n // A chat in sight shows the ring (and a refused answer) in its band.\n const card =\n ringSource !== undefined ? pickAgentVoiceIncomingCard({ ring, refusal, bandHostCount, ringCoverCount }) : undefined;\n const callerLabelId = useId();\n\n if (card === undefined) return null;\n if (ring === undefined) {\n if (refusal === undefined) return null;\n return (\n <div className={styles.incomingCall} role=\"status\" data-testid=\"agent-voice-incoming-call-refusal\">\n <span className={styles.detail}>{translateText(AGENT_VOICE_ANSWER_REFUSAL_TEXT_KEYS[refusal])}</span>\n </div>\n );\n }\n\n const shownCallerLabel = callerLabel ?? buildAgentVoiceCallerLabel(ring, translateText, getAgentDisplayName());\n return (\n <div\n className={styles.incomingCall}\n role=\"alertdialog\"\n aria-live=\"assertive\"\n aria-labelledby={callerLabelId}\n data-testid=\"agent-voice-incoming-call\"\n >\n <div className={styles.spot}>\n {renderAgentSpot ? (\n renderAgentSpot()\n ) : (\n <span className={styles.mark}>\n <VoiceBarsIcon size={24} />\n </span>\n )}\n </div>\n <div className={styles.caller} id={callerLabelId}>\n <span className={styles.label}>{shownCallerLabel.text}</span>\n {shownCallerLabel.detail ? (\n <span className={styles.detail} data-testid=\"agent-voice-incoming-call-detail\">\n {shownCallerLabel.detail}\n </span>\n ) : null}\n </div>\n <div className={styles.actions}>\n <button\n type=\"button\"\n className={styles.action}\n disabled={isAnswering}\n onClick={declineAgentVoiceIncomingRing}\n data-testid=\"agent-voice-incoming-call-decline\"\n >\n <AgentVoiceCloseIcon />\n <span>{translateText(\"Decline\")}</span>\n </button>\n <button\n type=\"button\"\n className={styles.action}\n data-variant=\"accept\"\n disabled={isAnswering}\n onClick={() => void acceptAgentVoiceIncomingRing()}\n data-testid=\"agent-voice-incoming-call-accept\"\n >\n <AgentVoiceMicrophoneIcon />\n <span>{translateText(\"Accept\")}</span>\n </button>\n </div>\n </div>\n );\n};\n"],"names":["status","detail","snapshot","liste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eAAY;AAAA,cAEZ,UAAA;AAAA,gBAAA,oBAAC,qBAAA,EAAoB;AAAA,gBACrB,oBAAC,QAAA,EAAM,UAAA,cAAc,SAAS,EAAA,CAAE;AAAA,cAAA;AAAA,YAAA;AAAA,UAAA;AAAA,UAElC;AAAA,YAAC;AAAA,YAAA;AAAA,cACC,MAAK;AAAA,cACL,WAAW,OAAO;AAAA,cAClB,gBAAa;AAAA,cACb,UAAU;AAAA,cACV,SAAS,MAAM,KAAK,6BAAA;AAAA,cACpB,eAAY;AAAA,cAEZ,UAAA;AAAA,gBAAA,oBAAC,0BAAA,EAAyB;AAAA,gBAC1B,oBAAC,QAAA,EAAM,UAAA,cAAc,QAAQ,EAAA,CAAE;AAAA,cAAA;AAAA,YAAA;AAAA,UAAA;AAAA,QACjC,EAAA,CACF;AAAA,MAAA;AAAA,IAAA;AAAA,EAAA;AAGN;"}
package/dist/widgets.js CHANGED
@@ -1,9 +1,9 @@
1
1
  "use client";
2
- import { a1 as useIsEmailWidgetRender } from "./chunks/WebSearchResultsConversationWidget-887v8Wen.js";
3
- import { ac, ad, ae, af, ae as ae2, ag, ah, ai, aj, ak, al, am, an, ao, ap, aq, ar, as, at, au, av, aw, ax, ay, az, aA, aB, aC, aD, aE, aF, aG, aH, aI, aJ, aK, aL, aM, aN, aO, aP, aQ, aR, aS, aT, aU, aV, aW, aX, aY, aZ, a_, a$, b0, b1, b2, b3, b4, b5 } from "./chunks/WebSearchResultsConversationWidget-887v8Wen.js";
2
+ import { a1 as useIsEmailWidgetRender } from "./chunks/WebSearchResultsConversationWidget-DXhfSikV.js";
3
+ import { ac, ad, ae, af, ae as ae2, ag, ah, ai, aj, ak, al, am, an, ao, ap, aq, ar, as, at, au, av, aw, ax, ay, az, aA, aB, aC, aD, aE, aF, aG, aH, aI, aJ, aK, aL, aM, aN, aO, aP, aQ, aR, aS, aT, aU, aV, aW, aX, aY, aZ, a_, a$, b0, b1, b2, b3, b4, b5 } from "./chunks/WebSearchResultsConversationWidget-DXhfSikV.js";
4
4
  import { jsx } from "react/jsx-runtime";
5
- import { r as StatusChip, s as Text, F as classNames } from "./chunks/link-navigation-CNX8Am2L.js";
6
- import { g, x } from "./chunks/link-navigation-CNX8Am2L.js";
5
+ import { r as StatusChip, s as Text, F as classNames } from "./chunks/link-navigation-BUcy5qWW.js";
6
+ import { g, x } from "./chunks/link-navigation-BUcy5qWW.js";
7
7
  import { useSyncExternalStore, useState, useEffect } from "react";
8
8
  const WidgetStatusChip = (props) => /* @__PURE__ */ jsx(StatusChip, { ...props });
9
9
  const widgetLabel = "agents_widgetLabel_WecWAw";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mgamadeus/ddd-agents",
3
- "version": "0.5.16",
3
+ "version": "0.6.0",
4
4
  "description": "The web frontend of the ddd-agents module: the agent chat, the widget renderer and the composed-view kit.",
5
5
  "keywords": [
6
6
  "ddd",
@@ -82,6 +82,14 @@
82
82
  "types": "./dist/types/entries/ui.d.ts",
83
83
  "import": "./dist/ui.js"
84
84
  },
85
+ "./voice": {
86
+ "types": "./dist/types/entries/voice.d.ts",
87
+ "import": "./dist/voice.js"
88
+ },
89
+ "./voice/admin": {
90
+ "types": "./dist/types/entries/voice-admin.d.ts",
91
+ "import": "./dist/voice-admin.js"
92
+ },
85
93
  "./styles.css": "./dist/styles.css",
86
94
  "./kit/ComposedViewConversationWidget.md": "./dist/files/kit/ComposedViewConversationWidget.md",
87
95
  "./widgets/ClockConversationWidget/ClockConversationWidget.md": "./dist/files/widgets/ClockConversationWidget/ClockConversationWidget.md",
@@ -159,6 +167,7 @@
159
167
  "files": [
160
168
  "dist",
161
169
  "public-api.json",
170
+ "boundary.json",
162
171
  "README.md",
163
172
  "LICENSE"
164
173
  ],
@@ -166,12 +175,14 @@
166
175
  "node": ">=20"
167
176
  },
168
177
  "peerDependencies": {
178
+ "@mgamadeus/ddd-admin-ui": ">=0.7.0 <1",
179
+ "@mgamadeus/ddd-web": ">=0.13.0 <1",
169
180
  "@types/google.maps": "^3.55.0",
170
181
  "apexcharts": "^3.41.0",
171
- "axios": "^0.28.0",
172
182
  "dompurify": "^3.4.0",
173
183
  "highlight.js": "^11.12.0",
174
184
  "katex": "^0.19.0",
185
+ "lucide-react": ">=0.550.0 <2",
175
186
  "mermaid": "^12.2.0",
176
187
  "react": "^19.2.0",
177
188
  "react-apexcharts": ">=1.4.0 <1.6.0",
@@ -184,11 +195,19 @@
184
195
  "unist-util-visit": "^5.0.0"
185
196
  },
186
197
  "peerDependenciesMeta": {
187
- "axios": {
198
+ "@mgamadeus/ddd-admin-ui": {
199
+ "optional": true
200
+ },
201
+ "@mgamadeus/ddd-web": {
202
+ "optional": true
203
+ },
204
+ "lucide-react": {
188
205
  "optional": true
189
206
  }
190
207
  },
191
208
  "devDependencies": {
209
+ "@mgamadeus/ddd-admin-ui": "^0.8.2",
210
+ "@mgamadeus/ddd-web": "^0.17.0",
192
211
  "@reduxjs/toolkit": "1.9.7",
193
212
  "@testing-library/dom": "10.4.0",
194
213
  "@testing-library/jest-dom": "6.9.1",
@@ -198,11 +217,11 @@
198
217
  "@types/react": "19.2.0",
199
218
  "@types/react-dom": "19.2.0",
200
219
  "apexcharts": "^3.41.0",
201
- "axios": "^0.28.0",
202
220
  "dompurify": "^3.4.0",
203
221
  "highlight.js": "^11.12.0",
204
222
  "jsdom": "29.1.1",
205
223
  "katex": "^0.19.0",
224
+ "lucide-react": "^1.55.0",
206
225
  "mdast-util-directive": "3.1.0",
207
226
  "mermaid": "^12.2.0",
208
227
  "react": "^19.2.0",