@gravity-rail/sdk 9.0.0 → 10.0.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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/realtime/types.ts","../src/realtime/login-token.ts","../src/realtime/socket-client.ts","../src/realtime/workspace-client.ts","../src/realtime/account-client.ts","../src/types/generated/account.ts","../src/realtime/editor-collaboration.ts","../src/realtime/operator-session-client.ts"],"sourcesContent":["/** Event received from a subscribed workspace realtime channel. */\nexport interface ChannelEvent {\n type: string;\n [key: string]: unknown;\n}\n\nexport type ChannelListener = (event: ChannelEvent) => void;\nexport type Unsubscribe = () => void;\n\n/**\n * What every realtime connection needs: where the API is, and who is asking.\n *\n * The account socket needs nothing more — its scope comes from the server's\n * grant map, not from the URL — so this is the base rather than a widening of\n * {@link RealtimeAuthSession}. A workspace session is assignable to it, which\n * is what lets one session object drive both clients during cutover.\n */\nexport interface RealtimeSessionBase {\n apiUrl: string;\n /**\n * The credential for one `login` frame, fetched once per connect attempt —\n * reconnects included — and never reused.\n *\n * In a browser this mints a single-use `gr_wst_` token same-origin (the\n * server refuses anything else from a browser handshake), so page script\n * never holds the account session. A non-browser client (Node, a CLI) may\n * return its bearer credential. Resolve `null` when no token can be had;\n * the client treats that attempt as failed and retries on its backoff.\n *\n * The provider's identity is part of the session: replacing it with a\n * different function reconnects the socket.\n */\n getLoginToken: RealtimeLoginTokenProvider;\n}\n\n/** Mints the token for one realtime `login` frame. See {@link RealtimeSessionBase}. */\nexport type RealtimeLoginTokenProvider = () => Promise<string | null>;\n\n/** Auth context for workspace realtime WebSocket connections. */\nexport interface RealtimeAuthSession extends RealtimeSessionBase {\n workspaceUuid: string;\n}\n\n/** Auth context for the account realtime WebSocket. No workspace, by design. */\nexport type AccountRealtimeSession = RealtimeSessionBase;\n\n/**\n * A workspace the server refused because its organization requires SSO or MFA\n * and the connection holds no valid org session for it. `authUrl` is the org\n * step-up route. `requirement` says which proof is missing. The frame's\n * `acr_values` is not read: it is fixed per requirement, so `requirement`\n * already says it.\n */\nexport interface OrgAuthRequirement {\n workspaceUuid: string;\n orgUuid: string;\n authUrl: string;\n requirement: 'sso' | 'mfa';\n}\n\n/** Read one step-up item off a server frame; null when a field is missing or mistyped. */\nexport function parseOrgAuthRequirement(value: unknown): OrgAuthRequirement | null {\n if (typeof value !== 'object' || value === null) return null;\n const item = value as Record<string, unknown>;\n const {\n workspace_uuid: workspaceUuid,\n org_uuid: orgUuid,\n auth_url: authUrl,\n requirement,\n } = item;\n if (\n typeof workspaceUuid !== 'string' ||\n typeof orgUuid !== 'string' ||\n typeof authUrl !== 'string' ||\n !workspaceUuid ||\n !orgUuid\n ) {\n return null;\n }\n return {\n workspaceUuid,\n orgUuid,\n authUrl,\n requirement: requirement === 'mfa' ? 'mfa' : 'sso',\n };\n}\n\n/** Read an `org_auth_required: [items]` list; malformed items are dropped. */\nexport function parseOrgAuthRequirements(value: unknown): OrgAuthRequirement[] {\n if (!Array.isArray(value)) return [];\n return value.flatMap((item) => {\n const parsed = parseOrgAuthRequirement(item);\n return parsed ? [parsed] : [];\n });\n}\n\n/** The server's reply to an `org_sessions` frame. */\nexport interface OrgSessionsUpdate {\n /** Orgs whose session this socket now holds. */\n orgUuids: string[];\n orgAuthRequired: OrgAuthRequirement[];\n}\n\nexport type OperatorSessionState = 'idle' | 'connecting' | 'connected' | 'error';\n\nexport type OperatorCallPhase =\n | 'idle'\n | 'connecting'\n | 'ready'\n | 'dialing'\n | 'live'\n | 'onHold'\n | 'ended'\n | 'failed';\n\n/** Phases where Hold / Forward / Hang up apply to an active phone leg. */\nexport function isActiveCallPhase(phase: OperatorCallPhase): boolean {\n return phase === 'dialing' || phase === 'live' || phase === 'onHold';\n}\n\n// ---------------------------------------------------------------------------\n// Activity Spine (docs/projects/active/activity-spine.md)\n// ---------------------------------------------------------------------------\n\n/**\n * The two activity lanes a client can watch.\n *\n * `activity` is the whole workspace's feed; `activity:me` is the connected\n * member's own private lane and open items, kept separate so a busy workspace\n * does not wake every operator's badge on every event.\n *\n * Both are named constants rather than interpolated strings because the server\n * matches them exactly — a typo would subscribe successfully to nothing.\n */\nexport const ACTIVITY_CHANNEL = 'activity' as const;\nexport const ACTIVITY_MEMBER_CHANNEL = 'activity:me' as const;\n\n/**\n * The account's own lane, on the account socket only.\n *\n * Carries two things the workspace lanes cannot: the account's\n * `account_private` rows (manager / DM / agent-job chats, member-targeted\n * routine runs, and the concierge lane, which has no workspace at all), and a\n * change to the account's own grants.\n */\nexport const ACCOUNT_ACTIVITY_CHANNEL = 'account:activity' as const;\n\nexport type ActivityChannelName =\n | typeof ACTIVITY_CHANNEL\n | typeof ACTIVITY_MEMBER_CHANNEL\n | typeof ACCOUNT_ACTIVITY_CHANNEL;\n\n/**\n * Operator presence, on the account socket only.\n *\n * The channel operator presence is **written** on. Presence state lives once,\n * at the account (`docs/projects/active/account-socket.md` § \"Presence,\n * migrated\"), and is projected into each chosen workspace's live set — so\n * going live is one command here rather than one per workspace socket.\n *\n * Unlike the activity lanes this one is bidirectional and does carry a\n * payload, because it is not an invalidation lane: `presence_confirmed`\n * reports the scope set the server actually honoured, which is the answer to\n * the command and is not re-fetchable from anywhere else.\n */\nexport const ACCOUNT_PRESENCE_CHANNEL = 'account:presence' as const;\n\n/** The workspace-scoped presence channel, on the per-workspace socket. */\nexport const PRESENCE_CHANNEL = 'presence' as const;\n\n/**\n * What an activity channel delivers — and deliberately all it delivers.\n *\n * **No event payloads travel over this socket.** The signal says *look again*;\n * the look goes through `POST /activity/query` (or `/counts` for a badge) under\n * the client's own session, where it is authorized against a freshly compiled\n * grant set and recorded as a bulk PHI access. A payload here would be an\n * authorization decision frozen at publish time by a producer that knows\n * nothing about who is listening — and a read that left no audit record.\n *\n * So: refetch on this, never render from it.\n */\nexport interface ActivityInvalidationEvent extends ChannelEvent {\n type: 'invalidate';\n data: {\n scope: 'workspace' | 'member' | 'account';\n reason: 'drain';\n };\n}\n\n/** Narrow a channel event to an activity invalidation. */\nexport function isActivityInvalidation(event: ChannelEvent): event is ActivityInvalidationEvent {\n if (event.type !== 'invalidate') return false;\n const data = (event as { data?: unknown }).data;\n if (typeof data !== 'object' || data === null) return false;\n const scope = (data as { scope?: unknown }).scope;\n return scope === 'workspace' || scope === 'member' || scope === 'account';\n}\n","import type { RealtimeLoginTokenProvider } from './types';\n\n/**\n * How long one connect attempt waits for its login token. A provider that\n * never settles (a hung mint request) must not hold the attempt open forever:\n * past this the attempt fails like any other and the caller's backoff applies.\n */\nexport const LOGIN_TOKEN_TIMEOUT_MS = 10_000;\n\n/**\n * Call `provider` once, bounded by {@link LOGIN_TOKEN_TIMEOUT_MS}.\n *\n * Resolves the token, or `null` when the provider throws, times out, or\n * returns anything but a non-empty string. Never rejects.\n */\nexport async function mintLoginToken(provider: RealtimeLoginTokenProvider): Promise<string | null> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n const token: unknown = await Promise.race([\n provider(),\n new Promise<null>((resolve) => {\n timer = setTimeout(() => resolve(null), LOGIN_TOKEN_TIMEOUT_MS);\n }),\n ]);\n return typeof token === 'string' && token.length > 0 ? token : null;\n } catch {\n return null;\n } finally {\n if (timer !== undefined) clearTimeout(timer);\n }\n}\n","/**\n * The realtime socket state machine, shared by both mounts.\n *\n * Two sockets speak the same protocol — `/api/v2/w/{wid}/ws/realtime` and\n * `/api/v2/ws/realtime` — and differ in exactly two places: the URL they open,\n * and the identity `protocol.init` hands back. Everything else (login,\n * heartbeat, reconnect with backoff, per-channel subscribe retry, listener\n * fan-out, deferred close) is one implementation here rather than two that\n * drift.\n *\n * That matters more than it sounds. The subscribe-retry and reconnect logic is\n * where the sharp edges live, and a second copy of it would be a second place\n * for a fix to be applied once.\n *\n * Protocol:\n * Client → Server: login, subscribe, unsubscribe, heartbeat, message\n * Server → Client: protocol.init, subscribed, subscribe_error, unsubscribed,\n * event, error\n */\n\nimport { mintLoginToken } from './login-token';\nimport {\n parseOrgAuthRequirement,\n parseOrgAuthRequirements,\n type ChannelEvent,\n type ChannelListener,\n type OrgAuthRequirement,\n type OrgSessionsUpdate,\n type RealtimeSessionBase,\n type Unsubscribe,\n} from './types';\n\nconst HEARTBEAT_INTERVAL_MS = 30_000;\nconst RECONNECT_DELAY_MS = 3_000;\nconst MAX_RECONNECT_ATTEMPTS = 5;\nconst CLOSE_DELAY_MS = 1_000;\nconst MAX_SUBSCRIBE_RETRY_DELAY_MS = 30_000;\n/** Close code and error code of a socket whose login credential ended (`lib/auth/realtime_credential_liveness.py`). */\nconst CREDENTIAL_REVOKED_CLOSE_CODE = 4001;\nconst CREDENTIAL_REVOKED_CODE = 'credential_revoked';\nconst CREDENTIAL_REVOKED_REASON = 'Credential revoked';\n\ninterface SocketState {\n ws: WebSocket | null;\n connected: boolean;\n connecting: boolean;\n /**\n * The last transport-or-server failure, or null once a connection succeeds.\n *\n * The state machine has always known this; it simply had no way to say so,\n * so every consumer hardcoded `error: null` and reported a healthy socket\n * through an outage. Two things set it: a server `error` frame (which is\n * how a rejected login is reported), and running out of reconnect\n * attempts — the point at which the client has genuinely given up and the\n * user needs to know, rather than each transient close on the way there.\n */\n lastError: string | null;\n listeners: Map<string, Set<ChannelListener>>;\n subscribedChannels: Set<string>;\n subscriptionRevision: number;\n subscriptionRetryChannels: Set<string>;\n subscriptionRetryAttempts: number;\n subscriptionRetryTimer: ReturnType<typeof setTimeout> | null;\n reconnectAttempts: number;\n reconnectTimer: ReturnType<typeof setTimeout> | null;\n heartbeatTimer: ReturnType<typeof setInterval> | null;\n closeTimer: ReturnType<typeof setTimeout> | null;\n intentionalClose: boolean;\n /**\n * The server refused this connection for want of an org session (an error\n * frame, then close 4003). Reconnecting with the same evidence is refused\n * again, so the client waits for {@link RealtimeSocketClient.retryAfterOrgAuth}.\n */\n orgAuthHalted: boolean;\n /**\n * The server ended the login credential (a signed-out session, a revoked\n * device): an `error` frame coded `credential_revoked`, or close 4001 with\n * the reason `Credential revoked`. Every reconnect would present the same\n * dead credential, so the client stops until a deliberate close or a new\n * session.\n */\n credentialRevoked: boolean;\n /**\n * Bumped by every connect attempt and every deliberate close. A connect\n * attempt awaits its login token before it opens a socket; if the\n * generation moved while it waited, a close or a newer attempt owns the\n * state and the stale attempt stops without touching it.\n */\n connectGeneration: number;\n}\n\nfunction createSocketState(): SocketState {\n return {\n ws: null,\n connected: false,\n connecting: false,\n lastError: null,\n listeners: new Map(),\n subscribedChannels: new Set(),\n subscriptionRevision: 0,\n subscriptionRetryChannels: new Set(),\n subscriptionRetryAttempts: 0,\n subscriptionRetryTimer: null,\n reconnectAttempts: 0,\n reconnectTimer: null,\n heartbeatTimer: null,\n closeTimer: null,\n intentionalClose: false,\n orgAuthHalted: false,\n credentialRevoked: false,\n connectGeneration: 0,\n };\n}\n\n/** The `protocol.init` frame, before either subclass narrows it. */\nexport interface ProtocolInitMessage {\n memberId?: unknown;\n accountUuid?: unknown;\n workspaceUuids?: unknown;\n}\n\nexport abstract class RealtimeSocketClient<TSession extends RealtimeSessionBase> {\n private session: TSession | null = null;\n private readonly getSessionFn: (() => TSession | null) | null;\n private readonly state: SocketState = createSocketState();\n private readonly connectionListeners = new Set<(connected: boolean) => void>();\n private readonly orgAuthListeners = new Set<(items: OrgAuthRequirement[]) => void>();\n private readonly orgSessionsListeners = new Set<(update: OrgSessionsUpdate) => void>();\n private readonly credentialRevokedListeners = new Set<() => void>();\n\n constructor(config?: TSession | (() => TSession | null)) {\n if (typeof config === 'function') {\n this.getSessionFn = config;\n } else {\n this.getSessionFn = null;\n if (config) {\n this.session = config;\n }\n }\n }\n\n /** The WebSocket URL this mount connects to. */\n protected abstract buildUrl(session: TSession): string;\n\n /**\n * Record whatever identity `protocol.init` carried for this mount.\n *\n * Called before the connection is announced, so a `onConnection` listener\n * that immediately reads the identity always sees the new one.\n */\n protected abstract readProtocolInit(msg: ProtocolInitMessage): void;\n\n /** Forget the identity on a deliberate close. See {@link closeConnection}. */\n protected abstract clearIdentity(): void;\n\n /**\n * Whether replacing `previous` with `next` invalidates the open socket.\n *\n * A different login-token provider always does — it stands for a different\n * identity; the rest is mount-specific — a workspace client changing\n * workspace is a different socket, and an account client has no such axis.\n */\n protected sessionRequiresReconnect(previous: TSession | null, next: TSession): boolean {\n return previous?.getLoginToken !== next.getLoginToken || previous?.apiUrl !== next.apiUrl;\n }\n\n protected resolveSession(): TSession | null {\n return this.session ?? this.getSessionFn?.() ?? null;\n }\n\n private notifyConnectionListeners(): void {\n for (const listener of this.connectionListeners) {\n listener(this.state.connected);\n }\n }\n\n private clearCloseTimer(): void {\n if (this.state.closeTimer) {\n clearTimeout(this.state.closeTimer);\n this.state.closeTimer = null;\n }\n }\n\n private clearSubscriptionRetry(channel?: string): void {\n if (channel) {\n this.state.subscriptionRetryChannels.delete(channel);\n } else {\n this.state.subscriptionRetryChannels.clear();\n }\n\n if (this.state.subscriptionRetryChannels.size > 0) return;\n\n if (this.state.subscriptionRetryTimer) {\n clearTimeout(this.state.subscriptionRetryTimer);\n this.state.subscriptionRetryTimer = null;\n }\n this.state.subscriptionRetryAttempts = 0;\n }\n\n private scheduleSubscriptionRetry(channels: string[]): void {\n for (const channel of channels) {\n if (this.state.listeners.has(channel) && !this.state.subscribedChannels.has(channel)) {\n this.state.subscriptionRetryChannels.add(channel);\n }\n }\n\n if (this.state.subscriptionRetryChannels.size === 0 || this.state.subscriptionRetryTimer) {\n return;\n }\n\n this.state.subscriptionRetryAttempts += 1;\n const delay = Math.min(\n RECONNECT_DELAY_MS * this.state.subscriptionRetryAttempts,\n MAX_SUBSCRIBE_RETRY_DELAY_MS\n );\n\n this.state.subscriptionRetryTimer = setTimeout(() => {\n this.state.subscriptionRetryTimer = null;\n const retryChannels = Array.from(this.state.subscriptionRetryChannels).filter(\n (channel) =>\n this.state.listeners.has(channel) && !this.state.subscribedChannels.has(channel)\n );\n\n for (const channel of this.state.subscriptionRetryChannels) {\n if (!retryChannels.includes(channel)) {\n this.state.subscriptionRetryChannels.delete(channel);\n }\n }\n\n if (retryChannels.length === 0) {\n this.state.subscriptionRetryAttempts = 0;\n return;\n }\n\n if (this.state.connected && this.state.ws?.readyState === WebSocket.OPEN) {\n this.state.ws.send(JSON.stringify({ type: 'subscribe', channels: retryChannels }));\n }\n }, delay);\n }\n\n setSession(session: TSession): void {\n const changed = this.sessionRequiresReconnect(this.session, session);\n\n this.session = session;\n // `connecting` with no `ws` is an attempt still minting its token under\n // the old session; closing bumps the generation so it stops there.\n if (changed && (this.state.ws || this.state.connecting)) {\n this.closeConnection();\n }\n // A revoked credential belonged to the old session.\n if (changed) this.state.credentialRevoked = false;\n if (this.state.listeners.size > 0) {\n this.ensureConnection();\n }\n }\n\n subscribe(channel: string, listener: ChannelListener): Unsubscribe {\n this.clearCloseTimer();\n\n let listeners = this.state.listeners.get(channel);\n if (!listeners) {\n listeners = new Set();\n this.state.listeners.set(channel, listeners);\n }\n listeners.add(listener);\n\n this.ensureConnection();\n\n if (\n this.state.connected &&\n this.state.ws?.readyState === WebSocket.OPEN &&\n !this.state.subscribedChannels.has(channel)\n ) {\n this.state.ws.send(JSON.stringify({ type: 'subscribe', channels: [channel] }));\n }\n\n return () => {\n const channelListeners = this.state.listeners.get(channel);\n channelListeners?.delete(listener);\n if (channelListeners && channelListeners.size === 0) {\n this.state.listeners.delete(channel);\n this.state.subscribedChannels.delete(channel);\n this.clearSubscriptionRetry(channel);\n if (this.state.connected && this.state.ws?.readyState === WebSocket.OPEN) {\n this.state.ws.send(JSON.stringify({ type: 'unsubscribe', channels: [channel] }));\n }\n }\n\n if (this.state.listeners.size === 0) {\n this.state.closeTimer = setTimeout(() => {\n if (this.state.listeners.size === 0) {\n this.closeConnection();\n }\n }, CLOSE_DELAY_MS);\n }\n };\n }\n\n /**\n * Hear every workspace the server refused for want of an org session: a\n * `subscribe_error` entry, an `error` frame with that code, a lapse notice,\n * or the list in an `org_sessions_updated` reply.\n */\n onOrgAuthRequired(listener: (items: OrgAuthRequirement[]) => void): () => void {\n this.orgAuthListeners.add(listener);\n return () => {\n this.orgAuthListeners.delete(listener);\n };\n }\n\n /** Hear the server's reply to an `org_sessions` frame. */\n onOrgSessionsUpdated(listener: (update: OrgSessionsUpdate) => void): () => void {\n this.orgSessionsListeners.add(listener);\n return () => {\n this.orgSessionsListeners.delete(listener);\n };\n }\n\n /**\n * Hear that the server ended this socket's login credential. The client\n * does not reconnect afterwards; the consumer decides what the person sees\n * (in the web app, the account check that leads to the login page).\n */\n onCredentialRevoked(listener: () => void): () => void {\n this.credentialRevokedListeners.add(listener);\n return () => {\n this.credentialRevokedListeners.delete(listener);\n };\n }\n\n /** Whether the server ended this socket's login credential. */\n isCredentialRevoked(): boolean {\n return this.state.credentialRevoked;\n }\n\n private markCredentialRevoked(message: string): void {\n if (this.state.credentialRevoked) return;\n this.state.credentialRevoked = true;\n this.state.lastError = message;\n if (this.state.reconnectTimer) {\n clearTimeout(this.state.reconnectTimer);\n this.state.reconnectTimer = null;\n }\n this.notifyConnectionListeners();\n for (const listener of this.credentialRevokedListeners) listener();\n }\n\n private emitOrgAuthRequired(items: OrgAuthRequirement[]): void {\n if (items.length === 0) return;\n for (const listener of this.orgAuthListeners) listener(items);\n }\n\n /** Send a control frame (one that is not a channel message) on the open socket. */\n sendFrame(frame: { type: string; [key: string]: unknown }): boolean {\n if (!this.state.connected || this.state.ws?.readyState !== WebSocket.OPEN) return false;\n this.state.ws.send(JSON.stringify(frame));\n return true;\n }\n\n /**\n * Try again after the person completed org sign-in: reconnect a socket the\n * server closed for it, or ask again for every channel it refused.\n */\n retryAfterOrgAuth(): void {\n this.state.orgAuthHalted = false;\n if (this.state.connected && this.state.ws?.readyState === WebSocket.OPEN) {\n const pending = Array.from(this.state.listeners.keys()).filter(\n (channel) => !this.state.subscribedChannels.has(channel)\n );\n if (pending.length > 0) {\n this.state.ws.send(JSON.stringify({ type: 'subscribe', channels: pending }));\n }\n return;\n }\n if (this.state.ws || this.state.connecting) return;\n this.state.reconnectAttempts = 0;\n this.ensureConnection();\n }\n\n send(channel: string, data: unknown): void {\n if (!this.state.connected || !this.state.ws) return;\n this.state.ws.send(JSON.stringify({ type: 'message', channel, data }));\n }\n\n onConnection(listener: (connected: boolean) => void): () => void {\n this.connectionListeners.add(listener);\n listener(this.state.connected);\n return () => {\n this.connectionListeners.delete(listener);\n };\n }\n\n isConnected(): boolean {\n return this.state.connected;\n }\n\n /**\n * Whether the server has acknowledged this channel subscription.\n *\n * This is stricter than having a local listener: it becomes true only after\n * a `subscribed` frame, returns to false on disconnect or server-driven\n * unsubscribe, and stays false while automatic subscribe retry is pending.\n * Consumers that must order a command after subscription admission should\n * observe {@link getSubscriptionRevision} and re-read this method.\n */\n isSubscribed(channel: string): boolean {\n return this.state.subscribedChannels.has(channel);\n }\n\n /**\n * Monotonic local revision of acknowledged subscription state.\n *\n * It increments when `subscribed` or `unsubscribed` changes the server-\n * acknowledged set. It is not a protocol sequence number and resets with a\n * new client instance; its purpose is external-store invalidation before a\n * consumer calls {@link isSubscribed} again.\n */\n getSubscriptionRevision(): number {\n return this.state.subscriptionRevision;\n }\n\n /**\n * A socket is open or opening and has not yet said `protocol.init`.\n *\n * Real state, read off the state machine. Consumers used to report a\n * literal `false` here and render \"Available\" over a socket that had never\n * connected; a toggle that cannot distinguish \"not live\" from \"cannot tell\n * yet\" is the shape of that bug.\n */\n isConnecting(): boolean {\n return this.state.connecting;\n }\n\n /** The last failure the socket gave up on, or null. See {@link SocketState.lastError}. */\n getLastError(): string | null {\n return this.state.lastError;\n }\n\n protected ensureConnection(): void {\n const session = this.resolveSession();\n if (!session) return;\n if (typeof window === 'undefined' || typeof WebSocket === 'undefined') return;\n if (this.state.ws || this.state.connecting) return;\n if (this.state.credentialRevoked) return;\n\n this.clearCloseTimer();\n this.state.connecting = true;\n this.state.intentionalClose = false;\n const generation = ++this.state.connectGeneration;\n // `connecting` is part of what consumers render, so entering it is a\n // change they have to hear about. Without this notify a `useSyncExternal`\n // store reading `isConnecting()` would only ever sample it on some later\n // unrelated transition.\n this.notifyConnectionListeners();\n\n void this.openSocket(session, generation);\n }\n\n /**\n * Mint this attempt's login token, then open the socket with it.\n *\n * A fresh token per attempt, reconnects included: a browser's token is\n * single-use and expires in seconds, so a token from an earlier attempt is\n * already spent.\n */\n private async openSocket(session: TSession, generation: number): Promise<void> {\n const token = await mintLoginToken(session.getLoginToken);\n if (generation !== this.state.connectGeneration) return;\n if (!token) {\n this.releaseUnopenedAttempt();\n return;\n }\n\n let ws: WebSocket;\n try {\n ws = new WebSocket(this.buildUrl(session));\n } catch {\n // A bad URL throws synchronously; without this the attempt would stay\n // `connecting` forever and every later `ensureConnection` would no-op.\n this.releaseUnopenedAttempt();\n return;\n }\n\n ws.onopen = () => {\n ws.send(JSON.stringify({ type: 'login', token }));\n };\n\n ws.onmessage = (event: MessageEvent) => {\n // Frames from a socket this client has already replaced belong to\n // nobody: acting on them would fold a stale connection's\n // subscription state into the live one.\n if (this.state.ws !== null && this.state.ws !== ws) return;\n try {\n const msg = JSON.parse(String(event.data)) as ProtocolInitMessage & {\n type?: string;\n channels?: string[];\n channel?: string;\n event?: ChannelEvent;\n errors?: unknown[];\n code?: unknown;\n org_auth_required?: unknown;\n org_uuids?: unknown;\n };\n\n if (msg.type === 'protocol.init' && !this.state.connected) {\n this.state.connected = true;\n this.readProtocolInit(msg);\n this.state.connecting = false;\n this.state.reconnectAttempts = 0;\n this.state.lastError = null;\n\n if (this.state.heartbeatTimer) clearInterval(this.state.heartbeatTimer);\n this.state.heartbeatTimer = setInterval(() => {\n if (this.state.ws?.readyState === WebSocket.OPEN) {\n this.state.ws.send(JSON.stringify({ type: 'heartbeat' }));\n }\n }, HEARTBEAT_INTERVAL_MS);\n\n if (this.state.listeners.size > 0) {\n ws.send(\n JSON.stringify({\n type: 'subscribe',\n channels: Array.from(this.state.listeners.keys()),\n })\n );\n }\n\n this.notifyConnectionListeners();\n return;\n }\n\n if (msg.type === 'subscribed' && Array.isArray(msg.channels)) {\n for (const ch of msg.channels) {\n this.state.subscribedChannels.add(ch);\n this.clearSubscriptionRetry(ch);\n }\n this.state.subscriptionRevision += 1;\n this.notifyConnectionListeners();\n return;\n }\n\n if (msg.type === 'subscribe_error' && Array.isArray(msg.errors)) {\n const retryableChannels: string[] = [];\n const orgRequired: OrgAuthRequirement[] = [];\n for (const rawError of msg.errors) {\n if (!rawError || typeof rawError !== 'object') continue;\n const error = rawError as {\n channel?: unknown;\n retryable?: unknown;\n code?: unknown;\n };\n if (typeof error.channel !== 'string') continue;\n if (error.code === 'org_auth_required') {\n // Not retryable: asking again with the same evidence is\n // refused again. The step-up path asks once it has new.\n this.clearSubscriptionRetry(error.channel);\n const requirement = parseOrgAuthRequirement(rawError);\n if (requirement) orgRequired.push(requirement);\n continue;\n }\n\n if (error.retryable === true) {\n retryableChannels.push(error.channel);\n } else {\n this.clearSubscriptionRetry(error.channel);\n }\n }\n this.scheduleSubscriptionRetry(retryableChannels);\n this.emitOrgAuthRequired(orgRequired);\n return;\n }\n\n if (msg.type === 'org_auth_required') {\n this.emitOrgAuthRequired(parseOrgAuthRequirements(msg.org_auth_required));\n return;\n }\n\n if (msg.type === 'org_sessions_updated') {\n const orgAuthRequired = parseOrgAuthRequirements(msg.org_auth_required);\n const orgUuids = Array.isArray(msg.org_uuids)\n ? msg.org_uuids.filter((value): value is string => typeof value === 'string')\n : [];\n for (const listener of this.orgSessionsListeners) {\n listener({ orgUuids, orgAuthRequired });\n }\n this.emitOrgAuthRequired(orgAuthRequired);\n return;\n }\n\n if (msg.type === 'unsubscribed' && Array.isArray(msg.channels)) {\n // The server also sends this unprompted when a grant change\n // revoked a subscription (account socket). Forgetting the\n // channel is what makes the client's next `subscribe` a real\n // re-authorization rather than a no-op against a stale set.\n for (const ch of msg.channels) {\n this.state.subscribedChannels.delete(ch);\n }\n this.state.subscriptionRevision += 1;\n this.notifyConnectionListeners();\n this.scheduleSubscriptionRetry(msg.channels);\n return;\n }\n\n if (msg.type === 'error' && msg.code === 'org_auth_required') {\n // A refusal for want of org sign-in, not a fault: it is routed to\n // the step-up, and the socket stays quiet until that finishes.\n this.state.orgAuthHalted = true;\n const requirement = parseOrgAuthRequirement(msg);\n if (requirement) this.emitOrgAuthRequired([requirement]);\n return;\n }\n\n if (msg.type === 'error' && msg.code === CREDENTIAL_REVOKED_CODE) {\n const message = (msg as { message?: unknown }).message;\n this.markCredentialRevoked(\n typeof message === 'string' && message ? message : CREDENTIAL_REVOKED_REASON\n );\n return;\n }\n\n if (msg.type === 'error') {\n // The server's own refusal — a rejected login, an unknown\n // message shape. Recorded rather than dropped: it is the one\n // failure the transport cannot tell the consumer about, because\n // the socket is open and will close looking like any other.\n const message = (msg as { message?: unknown }).message;\n this.state.lastError =\n typeof message === 'string' && message ? message : 'Realtime error';\n this.notifyConnectionListeners();\n return;\n }\n\n if (msg.type === 'event' && msg.channel && msg.event) {\n const channelListeners = this.state.listeners.get(msg.channel);\n if (channelListeners) {\n for (const channelListener of channelListeners) {\n try {\n channelListener(msg.event);\n } catch (err) {\n console.error('Channel listener error:', err);\n }\n }\n }\n }\n } catch {\n // Ignore malformed frames.\n }\n };\n\n ws.onclose = (event?: CloseEvent) => {\n // A close from a socket that is no longer this client's would\n // otherwise clear the REPLACEMENT connection's state: null its `ws`,\n // wipe its subscribed set, and stop its heartbeat — leaving a live\n // socket that believes it is subscribed to nothing and a client that\n // believes it is disconnected. Reachable whenever a `setSession`\n // replaced the socket while the old one's close was still in flight.\n if (this.state.ws !== null && this.state.ws !== ws) return;\n\n // The error frame is best effort; the close code and reason are not.\n if (\n event?.code === CREDENTIAL_REVOKED_CLOSE_CODE &&\n event.reason === CREDENTIAL_REVOKED_REASON\n ) {\n this.markCredentialRevoked(CREDENTIAL_REVOKED_REASON);\n }\n\n this.state.connected = false;\n this.state.connecting = false;\n this.state.ws = null;\n this.state.subscribedChannels.clear();\n this.clearSubscriptionRetry();\n\n if (this.state.heartbeatTimer) {\n clearInterval(this.state.heartbeatTimer);\n this.state.heartbeatTimer = null;\n }\n\n this.afterConnectionEnded();\n };\n\n ws.onerror = () => {\n // onclose will fire after this\n };\n\n this.state.ws = ws;\n }\n\n /**\n * End an attempt that never opened a socket. No `onclose` will run for it,\n * so the retry decision is made here, on the normal backoff.\n */\n private releaseUnopenedAttempt(): void {\n this.state.connecting = false;\n this.afterConnectionEnded();\n }\n\n /** Decide whether a connection that just ended (or never opened) retries. */\n private afterConnectionEnded(): void {\n const willRetry =\n !this.state.intentionalClose &&\n !this.state.orgAuthHalted &&\n !this.state.credentialRevoked &&\n this.state.listeners.size > 0 &&\n this.state.reconnectAttempts < MAX_RECONNECT_ATTEMPTS;\n\n if (\n !willRetry &&\n !this.state.intentionalClose &&\n !this.state.credentialRevoked &&\n this.state.listeners.size > 0\n ) {\n // Out of attempts with listeners still waiting: the client has\n // genuinely given up, which is the moment worth surfacing. Each\n // transient close on the way here is not — a socket that reconnects\n // in three seconds did not fail, and reporting it would train\n // people to ignore the indicator.\n this.state.lastError = 'Realtime connection lost';\n }\n\n this.notifyConnectionListeners();\n\n if (willRetry) {\n this.state.reconnectAttempts += 1;\n this.state.reconnectTimer = setTimeout(() => {\n this.ensureConnection();\n }, RECONNECT_DELAY_MS * this.state.reconnectAttempts);\n }\n }\n\n protected closeConnection(): void {\n this.state.intentionalClose = true;\n this.state.orgAuthHalted = false;\n // A deliberate close ends this identity's connection; a new session may\n // carry a live credential.\n this.state.credentialRevoked = false;\n this.state.connectGeneration += 1;\n this.clearCloseTimer();\n if (this.state.reconnectTimer) {\n clearTimeout(this.state.reconnectTimer);\n this.state.reconnectTimer = null;\n }\n if (this.state.heartbeatTimer) {\n clearInterval(this.state.heartbeatTimer);\n this.state.heartbeatTimer = null;\n }\n this.state.ws?.close();\n this.state.ws = null;\n this.state.connected = false;\n // Only a deliberate close forgets who we were; a transient `onclose`\n // leaves the identity in place because it is unchanged across a\n // reconnect, and the next `protocol.init` overwrites it anyway.\n this.clearIdentity();\n this.state.connecting = false;\n this.state.subscribedChannels.clear();\n this.clearSubscriptionRetry();\n this.notifyConnectionListeners();\n }\n}\n","/**\n * Unified workspace WebSocket client for real-time events.\n *\n * Mirrors `/api/v2/w/{wid}/ws/realtime`: log in with a token from the session's\n * `getLoginToken` provider (fresh per connect attempt),\n * subscribe to channels, receive AGUI events.\n *\n * The socket state machine — login, heartbeat, reconnect, subscribe retry —\n * lives in {@link RealtimeSocketClient}, shared with the account client. This\n * file is what is specific to the workspace mount: its URL, and the member id\n * `protocol.init` hands back.\n */\n\nimport { RealtimeSocketClient, type ProtocolInitMessage } from './socket-client';\nimport type { ChannelListener, RealtimeAuthSession, Unsubscribe } from './types';\n\n/** Build the workspace realtime WebSocket URL from session config. */\nexport function buildWorkspaceWsUrl(session: RealtimeAuthSession): string {\n const isSsl = session.apiUrl.startsWith('https');\n const host = session.apiUrl.replace(/^https?:\\/\\//, '');\n return `${isSsl ? 'wss' : 'ws'}://${host}/api/v2/w/${session.workspaceUuid}/ws/realtime`;\n}\n\nexport class WorkspaceRealtimeClient extends RealtimeSocketClient<RealtimeAuthSession> {\n private memberId: number | null = null;\n\n protected buildUrl(session: RealtimeAuthSession): string {\n return buildWorkspaceWsUrl(session);\n }\n\n protected readProtocolInit(msg: ProtocolInitMessage): void {\n this.memberId = typeof msg.memberId === 'number' ? msg.memberId : null;\n }\n\n protected clearIdentity(): void {\n this.memberId = null;\n }\n\n protected sessionRequiresReconnect(\n previous: RealtimeAuthSession | null,\n next: RealtimeAuthSession\n ): boolean {\n return (\n super.sessionRequiresReconnect(previous, next) ||\n previous?.workspaceUuid !== next.workspaceUuid\n );\n }\n\n /**\n * Member id the server authenticated this socket as, or null before\n * `protocol.init` arrives.\n *\n * Channels whose Redis key is workspace-wide can carry events addressed to\n * one member (presence acks, for example). Consumers compare the event's\n * addressee against this so a reply meant for another operator cannot be\n * applied locally.\n */\n getMemberId(): number | null {\n return this.memberId;\n }\n}\n\nconst defaultClient = new WorkspaceRealtimeClient();\n\nexport function initWorkspaceSocket(session: RealtimeAuthSession): void {\n defaultClient.setSession(session);\n}\n\nexport function subscribeWorkspaceChannel(channel: string, listener: ChannelListener): Unsubscribe {\n return defaultClient.subscribe(channel, listener);\n}\n\nexport function onWorkspaceSocketConnection(listener: (connected: boolean) => void): () => void {\n return defaultClient.onConnection(listener);\n}\n\nexport function isWorkspaceSocketConnected(): boolean {\n return defaultClient.isConnected();\n}\n","/**\n * Account WebSocket client — one socket per tab, rooted at the Account.\n *\n * Mirrors `/api/v2/ws/realtime`. No workspace in the URL and none in the\n * session: the login token is the whole identity, and what the socket may see comes\n * from the server's grant map, refreshed there.\n *\n * See `docs/projects/active/account-socket.md`. The point is not a second\n * socket — it is *one*. An operator covering four workspaces holds four\n * `WorkspaceRealtimeClient`s today, which is four connections, four\n * heartbeats, and no place to stand for \"what is happening across my estate\".\n * Workspace-scoped channels are reached here by qualifying their names, so the\n * same channel handlers serve both mounts and the per-workspace socket can be\n * deleted at cutover rather than lived alongside.\n *\n * ```ts\n * const client = new AccountRealtimeClient({ apiUrl, getLoginToken });\n * client.subscribe(workspaceChannel(wid, 'activity'), onInvalidate);\n * client.subscribe(ACCOUNT_ACTIVITY_CHANNEL, onInvalidate);\n * ```\n */\n\nimport { RealtimeSocketClient, type ProtocolInitMessage } from './socket-client';\nimport type { AccountRealtimeSession, ChannelListener, Unsubscribe } from './types';\n\n/** Build the account realtime WebSocket URL from session config. */\nexport function buildAccountWsUrl(session: AccountRealtimeSession): string {\n const isSsl = session.apiUrl.startsWith('https');\n const host = session.apiUrl.replace(/^https?:\\/\\//, '');\n return `${isSsl ? 'wss' : 'ws'}://${host}/api/v2/ws/realtime`;\n}\n\n/**\n * Qualify a workspace-scoped channel name for the account socket.\n *\n * `chat:42:monitor` in workspace `W` is `w/W/chat:42:monitor` here. Exported\n * as a function rather than left to callers' template strings for the reason\n * every channel name constant in this package exists: the server matches\n * exactly, so a typo subscribes successfully to nothing.\n */\nexport function workspaceChannel(workspaceUuid: string, channel: string): string {\n return `w/${workspaceUuid}/${channel}`;\n}\n\nexport class AccountRealtimeClient extends RealtimeSocketClient<AccountRealtimeSession> {\n private accountUuid: string | null = null;\n private workspaceUuids: readonly string[] = [];\n\n protected buildUrl(session: AccountRealtimeSession): string {\n return buildAccountWsUrl(session);\n }\n\n protected readProtocolInit(msg: ProtocolInitMessage): void {\n this.accountUuid = typeof msg.accountUuid === 'string' ? msg.accountUuid : null;\n this.workspaceUuids = Array.isArray(msg.workspaceUuids)\n ? msg.workspaceUuids.filter((value): value is string => typeof value === 'string')\n : [];\n }\n\n protected clearIdentity(): void {\n this.accountUuid = null;\n this.workspaceUuids = [];\n }\n\n /** Account uuid the server authenticated this socket as, or null. */\n getAccountUuid(): string | null {\n return this.accountUuid;\n }\n\n /**\n * Workspaces the server's grant map admitted at `protocol.init`.\n *\n * A **hint for rendering**, never an authorization decision: the server\n * re-checks its own map on every subscribe, and refreshes it on a floor, so\n * this snapshot can be stale in either direction. Use it to decide which\n * panes are worth opening, not which data a viewer may see.\n */\n getWorkspaceUuids(): readonly string[] {\n return this.workspaceUuids;\n }\n}\n\nconst defaultClient = new AccountRealtimeClient();\n\nexport function initAccountSocket(session: AccountRealtimeSession): void {\n defaultClient.setSession(session);\n}\n\nexport function subscribeAccountChannel(channel: string, listener: ChannelListener): Unsubscribe {\n return defaultClient.subscribe(channel, listener);\n}\n\nexport function onAccountSocketConnection(listener: (connected: boolean) => void): () => void {\n return defaultClient.onConnection(listener);\n}\n\nexport function isAccountSocketConnected(): boolean {\n return defaultClient.isConnected();\n}\n","/**\n * Generated by Orval, grouped by scripts/types-codegen/group_generated.ts\n * (group map from emit_openapi.py). Do not edit manually.\n * Group: account\n */\n\nimport type { SessionKind } from './session';\n\n/**\n * One Organization in which the Account has finance access.\n */\nexport interface AccountBillingOrganizationRef {\n id: number;\n name?: string | null;\n}\n\n/**\n * Base account response for non-admin endpoints.\n *\n * Note: With Verified Credential Architecture, if email/phone is set,\n * it's verified by construction. The *_verified_at timestamps record when.\n * Credentials are IMMUTABLE once set.\n */\nexport interface AccountResponse {\n id: number;\n uuid: string;\n loggedIn: boolean;\n avatarUrl: string | null;\n avatarIcon: AccountResponseAvatarIcon;\n avatarColor: AccountResponseAvatarColor;\n avatarSource: AccountResponseAvatarSource;\n avatarCustomized: boolean;\n avatarUseGravatar: boolean;\n email: string | null;\n phone: string | null;\n emailVerifiedAt: string | null;\n phoneVerifiedAt: string | null;\n name: string | null;\n createdAt: string;\n isSuperuser: boolean;\n enabled: boolean;\n signupWorkspaceId: number | null;\n tosAccepted: boolean;\n optedOut: boolean;\n locale: string | null;\n timezone: string | null;\n}\n\nexport type AccountResponseAvatarColor = typeof AccountResponseAvatarColor[keyof typeof AccountResponseAvatarColor];\n\n\nexport const AccountResponseAvatarColor = {\n teal: 'teal',\n sky: 'sky',\n blue: 'blue',\n indigo: 'indigo',\n violet: 'violet',\n fuchsia: 'fuchsia',\n slate: 'slate',\n} as const;\n\nexport type AccountResponseAvatarIcon = typeof AccountResponseAvatarIcon[keyof typeof AccountResponseAvatarIcon] | null;\n\n\nexport const AccountResponseAvatarIcon = {\n user: 'user',\n stethoscope: 'stethoscope',\n heart: 'heart',\n shield: 'shield',\n sparkles: 'sparkles',\n star: 'star',\n} as const;\n\nexport type AccountResponseAvatarSource = typeof AccountResponseAvatarSource[keyof typeof AccountResponseAvatarSource];\n\n\nexport const AccountResponseAvatarSource = {\n upload: 'upload',\n custom: 'custom',\n external: 'external',\n gravatar: 'gravatar',\n initials: 'initials',\n} as const;\n\nexport interface AdminAccountMembershipResponse {\n workspaceUuid: string;\n workspaceName: string;\n role: string;\n createdAt: string;\n tosAccepted: boolean;\n memberRoleId: number;\n memberId: number;\n glbLinked: boolean;\n}\n\n/**\n * Response for an account's organization membership.\n */\nexport interface AdminAccountOrgMembershipResponse {\n organizationId: number;\n organizationUuid: string;\n organizationName: string;\n organizationSlug: string;\n organizationLogoUrl: string | null;\n role: string;\n name: string | null;\n accountName: string | null;\n externalId: string | null;\n hasBillingAccess?: boolean;\n createdAt: string;\n updatedAt: string;\n}\n\n/**\n * Detailed account response for admin endpoints including related entities\n */\nexport interface AdminAccountResponse {\n id: number;\n uuid: string;\n loggedIn: boolean;\n avatarUrl: string | null;\n avatarIcon: AdminAccountResponseAvatarIcon;\n avatarColor: AdminAccountResponseAvatarColor;\n avatarSource: AdminAccountResponseAvatarSource;\n avatarCustomized: boolean;\n avatarUseGravatar: boolean;\n email: string | null;\n phone: string | null;\n emailVerifiedAt: string | null;\n phoneVerifiedAt: string | null;\n name: string | null;\n createdAt: string;\n isSuperuser: boolean;\n enabled: boolean;\n signupWorkspaceId: number | null;\n tosAccepted: boolean;\n optedOut: boolean;\n locale: string | null;\n timezone: string | null;\n billingOrganizations?: AccountBillingOrganizationRef[];\n pendingDeletion?: boolean;\n deletionRequestedAt?: string | null;\n}\n\nexport type AdminAccountResponseAvatarColor = typeof AdminAccountResponseAvatarColor[keyof typeof AdminAccountResponseAvatarColor];\n\n\nexport const AdminAccountResponseAvatarColor = {\n teal: 'teal',\n sky: 'sky',\n blue: 'blue',\n indigo: 'indigo',\n violet: 'violet',\n fuchsia: 'fuchsia',\n slate: 'slate',\n} as const;\n\nexport type AdminAccountResponseAvatarIcon = typeof AdminAccountResponseAvatarIcon[keyof typeof AdminAccountResponseAvatarIcon] | null;\n\n\nexport const AdminAccountResponseAvatarIcon = {\n user: 'user',\n stethoscope: 'stethoscope',\n heart: 'heart',\n shield: 'shield',\n sparkles: 'sparkles',\n star: 'star',\n} as const;\n\nexport type AdminAccountResponseAvatarSource = typeof AdminAccountResponseAvatarSource[keyof typeof AdminAccountResponseAvatarSource];\n\n\nexport const AdminAccountResponseAvatarSource = {\n upload: 'upload',\n custom: 'custom',\n external: 'external',\n gravatar: 'gravatar',\n initials: 'initials',\n} as const;\n\n/**\n * Admin request to create a user account.\n *\n * This is for superuser administration only. Accounts are global and not\n * tied to any organization. To add someone to an organization, use\n * workspace invitations instead.\n */\nexport interface AdminCreateAccountRequest {\n email?: string | null;\n phone?: string | null;\n name?: string | null;\n isSuperuser?: boolean;\n enabled?: boolean;\n locale?: string | null;\n timezone?: string | null;\n}\n\n/**\n * Admin request to update user account information.\n *\n * Note: Organization membership/role is managed via OrgMember, not Account fields.\n */\nexport interface AdminUpdateAccountRequest {\n name?: string | null;\n email?: string | null;\n phone?: string | null;\n isSuperuser?: boolean | null;\n enabled?: boolean | null;\n tosAccepted?: boolean | null;\n optedOut?: boolean | null;\n locale?: string | null;\n timezone?: string | null;\n}\n\n/**\n * Response model for when a new API key is created, including the full key.\n */\nexport interface ApiKeyCreatedResponse {\n id: number;\n uuid: string;\n name: string;\n keyPrefix: string;\n createdAt: string;\n expiresAt?: string | null;\n lastUsedAt?: string | null;\n enabled: boolean;\n scopes: string[];\n appId?: number | null;\n dataUseMode?: DataUseMode;\n key: string;\n}\n\n/**\n * Response model for API key information.\n */\nexport interface ApiKeyResponse {\n id: number;\n uuid: string;\n name: string;\n keyPrefix: string;\n createdAt: string;\n expiresAt?: string | null;\n lastUsedAt?: string | null;\n enabled: boolean;\n scopes: string[];\n appId?: number | null;\n dataUseMode?: DataUseMode;\n}\n\n/**\n * Response after canceling a credential change invitation.\n */\nexport interface CancelCredentialChangeInviteResponse {\n success: boolean;\n message: string;\n}\n\n/**\n * Response after canceling a credential change request.\n */\nexport interface CancelCredentialChangeResponse {\n success: boolean;\n message: string;\n}\n\n/**\n * Response after confirming a credential change invitation.\n */\nexport interface CredentialChangeInviteConfirmResponse {\n success: boolean;\n message: string;\n credentialType?: CredentialChangeInviteConfirmResponseCredentialType;\n}\n\nexport type CredentialChangeInviteConfirmResponseCredentialType = typeof CredentialChangeInviteConfirmResponseCredentialType[keyof typeof CredentialChangeInviteConfirmResponseCredentialType] | null;\n\n\nexport const CredentialChangeInviteConfirmResponseCredentialType = {\n email: 'email',\n phone: 'phone',\n} as const;\n\n/**\n * Response with details of a credential change invitation.\n *\n * Used for the confirmation page to show what change is being proposed.\n */\nexport interface CredentialChangeInviteDetailsResponse {\n id: number;\n credentialType: CredentialChangeInviteDetailsResponseCredentialType;\n newValue: string;\n workspaceName: string;\n workspaceUuid: string;\n initiatedByName: string | null;\n createdAt: string;\n expiresAt: string;\n isExpired: boolean;\n isValid: boolean;\n}\n\nexport type CredentialChangeInviteDetailsResponseCredentialType = typeof CredentialChangeInviteDetailsResponseCredentialType[keyof typeof CredentialChangeInviteDetailsResponseCredentialType];\n\n\nexport const CredentialChangeInviteDetailsResponseCredentialType = {\n email: 'email',\n phone: 'phone',\n} as const;\n\n/**\n * Response after creating a credential change invitation.\n */\nexport interface CredentialChangeInviteResponse {\n id: number;\n credentialType: CredentialChangeInviteResponseCredentialType;\n maskedNewValue: string;\n expiresAt: string;\n message: string;\n}\n\nexport type CredentialChangeInviteResponseCredentialType = typeof CredentialChangeInviteResponseCredentialType[keyof typeof CredentialChangeInviteResponseCredentialType];\n\n\nexport const CredentialChangeInviteResponseCredentialType = {\n email: 'email',\n phone: 'phone',\n} as const;\n\n/**\n * Response after requesting a credential change.\n */\nexport interface CredentialChangeRequestResponse {\n id: number;\n credentialType: CredentialChangeRequestResponseCredentialType;\n expiresAt: string;\n message: string;\n}\n\nexport type CredentialChangeRequestResponseCredentialType = typeof CredentialChangeRequestResponseCredentialType[keyof typeof CredentialChangeRequestResponseCredentialType];\n\n\nexport const CredentialChangeRequestResponseCredentialType = {\n email: 'email',\n phone: 'phone',\n} as const;\n\n/**\n * Response after verifying a credential change.\n */\nexport interface CredentialChangeVerifyResponse {\n success: boolean;\n message: string;\n credentialType?: CredentialChangeVerifyResponseCredentialType;\n}\n\nexport type CredentialChangeVerifyResponseCredentialType = typeof CredentialChangeVerifyResponseCredentialType[keyof typeof CredentialChangeVerifyResponseCredentialType] | null;\n\n\nexport const CredentialChangeVerifyResponseCredentialType = {\n email: 'email',\n phone: 'phone',\n} as const;\n\n/**\n * What a *credential* may carry (ADR-18 §1), not what a member may see.\n *\n * This is an axis on the connection, deliberately not a scope: scopes are\n * additive grants for cross-member access, and a member's own data is reached\n * with no scope at all, so no scope value can express \"this channel must not\n * carry PHI\". Computed at mint time and mutable afterwards **only toward**\n * :attr:`NO_PHI` — the same \"narrows, never widens\" doctrine as\n * ``scope_restriction`` and ``Device.enrollment_scope_ceiling``. Widening is a\n * re-consent, i.e. revoke and re-mint under lifted conditions.\n */\nexport type DataUseMode = typeof DataUseMode[keyof typeof DataUseMode];\n\n\nexport const DataUseMode = {\n unrestricted: 'unrestricted',\n no_phi: 'no_phi',\n} as const;\n\nexport interface LoginResponse {\n token: string;\n accountId: number;\n accountName?: string | null;\n accountUuid?: string | null;\n requiresTwoFactor?: boolean | null;\n availableTwoFactorMethods?: unknown[] | null;\n sessionKind?: SessionKind | 'widget' | null;\n expiresAt?: string | null;\n}\n\n/**\n * Response for a pending credential change invitation.\n */\nexport interface PendingCredentialChangeInviteResponse {\n id: number;\n credentialType: PendingCredentialChangeInviteResponseCredentialType;\n maskedNewValue: string;\n workspaceName: string;\n initiatedByName: string | null;\n createdAt: string;\n expiresAt: string;\n isExpired: boolean;\n status: string;\n}\n\nexport type PendingCredentialChangeInviteResponseCredentialType = typeof PendingCredentialChangeInviteResponseCredentialType[keyof typeof PendingCredentialChangeInviteResponseCredentialType];\n\n\nexport const PendingCredentialChangeInviteResponseCredentialType = {\n email: 'email',\n phone: 'phone',\n} as const;\n\n/**\n * Response for a pending credential change request.\n */\nexport interface PendingCredentialChangeResponse {\n id: number;\n credentialType: PendingCredentialChangeResponseCredentialType;\n maskedNewValue: string;\n createdAt: string;\n expiresAt: string;\n isExpired: boolean;\n attempts: number;\n}\n\nexport type PendingCredentialChangeResponseCredentialType = typeof PendingCredentialChangeResponseCredentialType[keyof typeof PendingCredentialChangeResponseCredentialType];\n\n\nexport const PendingCredentialChangeResponseCredentialType = {\n email: 'email',\n phone: 'phone',\n} as const;\n\n/**\n * Response model for recovery codes\n */\nexport interface RecoveryCodeResponse {\n /** List of recovery codes (only shown once) */\n codes: string[];\n /** When the codes were generated */\n generatedAt: string;\n warning?: string;\n}\n\nexport interface SendLoginCodeResponse {\n success: boolean;\n message?: string | null;\n}\n\n/**\n * Response for TOTP setup initiation\n */\nexport interface TOTPSetupResponse {\n /** Session ID for completing setup */\n setupId: string;\n /** Base32 encoded TOTP secret */\n secret: string;\n /** QR code URL for easy setup */\n qrCodeUrl: string;\n /** Manual entry key for authenticator apps */\n manualEntryKey: string;\n /** Issuer name for TOTP */\n issuer: string;\n}\n\n/**\n * Response model for 2FA method details\n */\nexport interface TwoFactorMethodResponse {\n id: number;\n methodType: string;\n name: string;\n enabled: boolean;\n createdAt: string;\n lastUsedAt?: string | null;\n}\n\n/**\n * Generic response for 2FA operations\n */\nexport interface TwoFactorOperationResponse {\n /** Whether the operation was successful */\n success: boolean;\n /** Human-readable message */\n message: string;\n /** ID of the affected 2FA method */\n methodId?: number | null;\n}\n\n/**\n * Response for overall 2FA status\n */\nexport interface TwoFactorStatusResponse {\n /** Whether any 2FA method is enabled */\n enabled: boolean;\n /** List of configured 2FA methods */\n methods: TwoFactorMethodResponse[];\n /** Number of unused recovery codes */\n recoveryCodesCount: number;\n /** When recovery codes were last generated */\n lastRecoveryCodesGenerated?: string | null;\n}\n\n/**\n * Update user information.\n *\n * Note: email and phone cannot be changed via this endpoint.\n * Use the credential change flow instead:\n * - POST /api/v2/account/request-credential-change\n * - POST /api/v2/account/verify-credential-change\n */\nexport interface UpdateAccountRequest {\n name?: string | null;\n tosAccepted?: boolean | null;\n optedOut?: boolean | null;\n locale?: string | null;\n timezone?: string | null;\n}\n\n/**\n * Authenticator selection criteria in WebAuthn creation options.\n */\nexport interface WebAuthnAuthenticatorSelection {\n userVerification: WebAuthnAuthenticatorSelectionUserVerification;\n residentKey: WebAuthnAuthenticatorSelectionResidentKey;\n}\n\nexport type WebAuthnAuthenticatorSelectionResidentKey = typeof WebAuthnAuthenticatorSelectionResidentKey[keyof typeof WebAuthnAuthenticatorSelectionResidentKey];\n\n\nexport const WebAuthnAuthenticatorSelectionResidentKey = {\n required: 'required',\n preferred: 'preferred',\n discouraged: 'discouraged',\n} as const;\n\nexport type WebAuthnAuthenticatorSelectionUserVerification = typeof WebAuthnAuthenticatorSelectionUserVerification[keyof typeof WebAuthnAuthenticatorSelectionUserVerification];\n\n\nexport const WebAuthnAuthenticatorSelectionUserVerification = {\n required: 'required',\n preferred: 'preferred',\n discouraged: 'discouraged',\n} as const;\n\n/**\n * Credential creation options passed to navigator.credentials.create().\n */\nexport interface WebAuthnCredentialCreationOptions {\n challenge: string;\n rp: WebAuthnRelyingParty;\n user: WebAuthnUserEntity;\n pubKeyCredParams: WebAuthnPubKeyCredParam[];\n excludeCredentials: WebAuthnCredentialDescriptor[];\n authenticatorSelection: WebAuthnAuthenticatorSelection;\n timeout: number;\n attestation: WebAuthnCredentialCreationOptionsAttestation;\n}\n\nexport type WebAuthnCredentialCreationOptionsAttestation = typeof WebAuthnCredentialCreationOptionsAttestation[keyof typeof WebAuthnCredentialCreationOptionsAttestation];\n\n\nexport const WebAuthnCredentialCreationOptionsAttestation = {\n none: 'none',\n indirect: 'indirect',\n direct: 'direct',\n enterprise: 'enterprise',\n} as const;\n\n/**\n * Descriptor for a registered WebAuthn credential.\n */\nexport interface WebAuthnCredentialDescriptor {\n id: string;\n type: 'public-key';\n}\n\n/**\n * A public-key credential parameter the authenticator may create.\n */\nexport interface WebAuthnPubKeyCredParam {\n alg: number;\n type: 'public-key';\n}\n\n/**\n * Response for WebAuthn registration initiation\n */\nexport interface WebAuthnRegistrationResponse {\n /** Session ID for completing setup */\n setupId: string;\n /** WebAuthn credential creation options */\n credentialCreationOptions: WebAuthnCredentialCreationOptions;\n}\n\n/**\n * Relying party entity in WebAuthn creation options.\n */\nexport interface WebAuthnRelyingParty {\n name: string;\n id: string;\n}\n\n/**\n * User entity in WebAuthn creation options.\n */\nexport interface WebAuthnUserEntity {\n /** Base64url-encoded user handle */\n id: string;\n name: string;\n displayName: string;\n}\n","import {\n AccountResponseAvatarColor,\n AccountResponseAvatarIcon,\n type AccountResponseAvatarColor as AvatarColor,\n type AccountResponseAvatarIcon as AvatarIcon,\n} from '../types/generated/account';\nimport type { ChannelEvent } from './types';\n\nexport type EditorCollaborationResource = 'workflow' | 'journey';\n\n/**\n * Stable server identities, not the transient React Flow node keys that a clean\n * editor replacement can regenerate. Workflow Tasks and notes use numeric ids;\n * Journey steps/routes/endings use their durable UUIDs.\n */\nexport type EditorCollaborationItemKind =\n | 'workflow'\n | 'task'\n | 'note'\n | 'journey'\n | 'step'\n | 'route'\n | 'ending'\n | 'enrollment'\n | 'goal'\n | 'connection'\n | 'wait'\n | 'action';\n\n/**\n * Journey item ids: `step`, `route`, `ending`, `enrollment` and `goal` use the\n * object's own UUID. A `wait` is the wait before a step, so its id is that\n * step's UUID. An `action` is one EventRule on a step or Ending, so its id is\n * that EventRule's UUID.\n */\nexport interface EditorCollaborationItem {\n kind: EditorCollaborationItemKind;\n id: number | string;\n}\n\n/** A person with the editor open, or the workspace Manager acting for one. */\nexport type EditorCollaboratorKind = 'member' | 'manager';\n\nexport interface EditorCollaborator {\n /** `manager` draws the Manager mark; its `memberId` is the person it acts for. */\n kind: EditorCollaboratorKind;\n memberId: number;\n name: string | null;\n /** The image to draw, if any; null means draw the icon or the initials. */\n avatarUrl: string | null;\n /** Null draws the Member's initials. */\n avatarIcon: AvatarIcon;\n /** Null on a server that predates the field; the client derives one. */\n avatarColor: AvatarColor | null;\n}\n\nexport interface CollaboratorsChangedEvent {\n type: 'collaborators.changed';\n collaborators: EditorCollaborator[];\n}\n\nexport interface EditorUpdatedEvent {\n type: 'editor.updated';\n editor: EditorCollaborator;\n items: EditorCollaborationItem[];\n /** One mounted browser editor, distinct from the Member using other tabs. */\n originId: string;\n updatedAt: string;\n}\n\nexport type EditorCollaborationEvent = CollaboratorsChangedEvent | EditorUpdatedEvent;\n\nexport function editorCollaborationChannel(\n resource: EditorCollaborationResource,\n resourceId: number\n): string {\n return `collaboration:${resource}:${resourceId}`;\n}\n\nexport function editorCollaborationItemKey(item: EditorCollaborationItem): string {\n return `${item.kind}:${String(item.id)}`;\n}\n\nfunction parseCollaborator(value: unknown): EditorCollaborator | null {\n if (typeof value !== 'object' || value === null) return null;\n const record = value as Record<string, unknown>;\n if (typeof record.memberId !== 'number' || !Number.isInteger(record.memberId)) return null;\n const name = record.name;\n const avatarUrl = record.avatarUrl;\n const avatarIcon = record.avatarIcon;\n const avatarColor = record.avatarColor;\n return {\n kind: record.kind === 'manager' ? 'manager' : 'member',\n memberId: record.memberId,\n name: typeof name === 'string' ? name : null,\n avatarUrl: typeof avatarUrl === 'string' ? avatarUrl : null,\n avatarIcon:\n typeof avatarIcon === 'string' && avatarIcon in AccountResponseAvatarIcon\n ? (avatarIcon as AvatarIcon)\n : null,\n avatarColor:\n typeof avatarColor === 'string' && avatarColor in AccountResponseAvatarColor\n ? (avatarColor as AvatarColor)\n : null,\n };\n}\n\nfunction parseItem(value: unknown): EditorCollaborationItem | null {\n if (typeof value !== 'object' || value === null) return null;\n const item = value as Record<string, unknown>;\n const kind = item.kind;\n const id = item.id;\n const validKind =\n kind === 'workflow' ||\n kind === 'task' ||\n kind === 'note' ||\n kind === 'journey' ||\n kind === 'step' ||\n kind === 'route' ||\n kind === 'ending' ||\n kind === 'enrollment' ||\n kind === 'goal' ||\n kind === 'connection' ||\n kind === 'wait' ||\n kind === 'action';\n if (!validKind) return null;\n if (typeof id !== 'number' && typeof id !== 'string') return null;\n if (!String(id)) return null;\n return { kind, id };\n}\n\n/** Narrow the untyped shared-socket envelope before it changes editor state. */\nexport function parseEditorCollaborationEvent(\n event: ChannelEvent\n): EditorCollaborationEvent | null {\n const data = (event as { data?: unknown }).data;\n if (typeof data !== 'object' || data === null) return null;\n const record = data as Record<string, unknown>;\n if (event.type === 'collaborators.changed') {\n if (!Array.isArray(record.collaborators)) return null;\n const collaborators = record.collaborators.flatMap((value) => {\n const parsed = parseCollaborator(value);\n return parsed ? [parsed] : [];\n });\n return { type: event.type, collaborators };\n }\n if (event.type === 'editor.updated') {\n const editor = parseCollaborator(record.editor);\n const rawItems = record.items;\n if (\n !editor ||\n !Array.isArray(rawItems) ||\n rawItems.length === 0 ||\n rawItems.length > 100 ||\n typeof record.originId !== 'string' ||\n typeof record.updatedAt !== 'string'\n ) {\n return null;\n }\n const items = rawItems.map(parseItem);\n if (items.some((item) => item === null)) return null;\n return {\n type: event.type,\n editor,\n items: items as EditorCollaborationItem[],\n originId: record.originId,\n updatedAt: record.updatedAt,\n };\n }\n return null;\n}\n","/**\n * Human operator session WebSocket client.\n *\n * Connects to `/api/v2/w/{wid}/operator/chats/{chatId}/session-ws` — AGUI\n * events, bidirectional PCM, and call control. No AI inference.\n */\n\nimport {\n base64ToFloat32Array,\n float32ArrayToBase64,\n SERVER_SAMPLE_RATE,\n TARGET_SAMPLE_RATE,\n} from '../audio/pcm';\nimport { mintLoginToken } from './login-token';\nimport {\n parseOrgAuthRequirement,\n type ChannelEvent,\n type OperatorCallPhase,\n type OperatorSessionState,\n type OrgAuthRequirement,\n type RealtimeAuthSession,\n} from './types';\n\nconst CONNECT_SUPERSEDED = 'Operator session connect superseded';\n\nexport interface OperatorSessionHandlers {\n onSessionStateChange?: (state: OperatorSessionState) => void;\n onCallPhaseChange?: (phase: OperatorCallPhase) => void;\n onAguiEvent?: (event: ChannelEvent) => void;\n onError?: (message: string) => void;\n /** The session was refused for want of an org session; the step-up path takes it from here. */\n onOrgAuthRequired?: (requirement: OrgAuthRequirement) => void;\n /**\n * Fired once when a logged-in session ends without `disconnect()`: the server\n * ended it (e.g. callee hung up, with the server's reason) or its socket closed\n * with no such notice (reason `'disconnect'`).\n */\n onSessionClosed?: (reason?: string) => void;\n}\n\nexport class OperatorSessionClient {\n private ws: WebSocket | null = null;\n private audioContext: AudioContext | null = null;\n private mediaStream: MediaStream | null = null;\n private processor: ScriptProcessorNode | null = null;\n private sessionState: OperatorSessionState = 'idle';\n private callPhase: OperatorCallPhase = 'idle';\n private nextPlaybackTime = 0;\n private playbackSources: AudioBufferSourceNode[] = [];\n private micActive = false;\n private onHold = false;\n private muted = false;\n private receivedRemoteAudio = false;\n private heartbeatTimer: ReturnType<typeof setInterval> | null = null;\n private sessionCloseNotified = false;\n private cancelPendingLogin: (() => void) | null = null;\n /** Bumped by every connect and disconnect; a stale connect stops at its next await. */\n private connectGeneration = 0;\n\n constructor(private handlers: OperatorSessionHandlers = {}) {}\n\n getSessionState(): OperatorSessionState {\n return this.sessionState;\n }\n\n getCallPhase(): OperatorCallPhase {\n return this.callPhase;\n }\n\n private setSessionState(next: OperatorSessionState): void {\n this.sessionState = next;\n this.handlers.onSessionStateChange?.(next);\n }\n\n private setCallPhase(next: OperatorCallPhase): void {\n this.callPhase = next;\n this.handlers.onCallPhaseChange?.(next);\n }\n\n private notifySessionClosed(reason?: string): void {\n if (this.sessionCloseNotified) return;\n this.sessionCloseNotified = true;\n this.handlers.onSessionClosed?.(reason);\n }\n\n async connect(session: RealtimeAuthSession, chatId: number): Promise<void> {\n if (typeof window === 'undefined' || typeof WebSocket === 'undefined') {\n throw new Error('Operator session WebSocket is not available in this environment');\n }\n\n const generation = ++this.connectGeneration;\n await this.closeSession();\n if (generation !== this.connectGeneration) {\n throw new Error(CONNECT_SUPERSEDED);\n }\n this.sessionCloseNotified = false;\n this.setSessionState('connecting');\n this.setCallPhase('connecting');\n\n const isSsl = session.apiUrl.startsWith('https');\n const host = session.apiUrl.replace(/^https?:\\/\\//, '');\n const wsUrl = `${isSsl ? 'wss' : 'ws'}://${host}/api/v2/w/${session.workspaceUuid}/operator/chats/${chatId}/session-ws`;\n\n // One token per connect: a browser's is single-use and expires in seconds.\n const token = await mintLoginToken(session.getLoginToken);\n if (generation !== this.connectGeneration) {\n throw new Error(CONNECT_SUPERSEDED);\n }\n if (!token) {\n this.setSessionState('error');\n this.setCallPhase('idle');\n throw new Error('Realtime login token unavailable');\n }\n\n await new Promise<void>((resolve, reject) => {\n const ws = new WebSocket(wsUrl);\n this.ws = ws;\n let loginSettled = false;\n let loggedIn = false;\n const settleLogin = (error?: Error) => {\n if (loginSettled) return;\n loginSettled = true;\n if (this.cancelPendingLogin === cancelLogin) this.cancelPendingLogin = null;\n if (error) {\n reject(error);\n } else {\n loggedIn = true;\n resolve();\n }\n };\n const cancelLogin = () => settleLogin(new Error(CONNECT_SUPERSEDED));\n this.cancelPendingLogin = cancelLogin;\n\n ws.onopen = () => {\n if (this.ws !== ws) return;\n ws.send(JSON.stringify({ type: 'login', token }));\n };\n\n ws.onmessage = (event) => {\n if (this.ws !== ws) return;\n try {\n const msg = JSON.parse(String(event.data)) as {\n type?: string;\n name?: string;\n value?: Record<string, unknown>;\n message?: string;\n code?: string;\n event?: ChannelEvent;\n };\n this.handleMessage(msg, () => settleLogin(), settleLogin);\n } catch {\n /* ignore malformed frames */\n }\n };\n\n ws.onerror = () => {\n if (this.ws !== ws) return;\n const message = 'Operator session WebSocket error';\n const wasConnecting = this.sessionState === 'connecting';\n this.setSessionState('error');\n if (wasConnecting) {\n this.setCallPhase('idle');\n settleLogin(new Error(message));\n } else {\n this.setCallPhase('failed');\n this.handlers.onError?.(message);\n }\n };\n\n ws.onclose = () => {\n if (this.ws !== ws) {\n settleLogin(new Error(CONNECT_SUPERSEDED));\n return;\n }\n this.ws = null;\n this.clearHeartbeat();\n this.stopMicrophone();\n this.stopPlayback();\n this.setSessionState('idle');\n this.setCallPhase('idle');\n if (loggedIn) {\n this.notifySessionClosed('disconnect');\n } else {\n settleLogin(new Error('Operator session closed before login'));\n }\n };\n });\n }\n\n private handleMessage(\n msg: {\n type?: string;\n name?: string;\n value?: Record<string, unknown>;\n message?: string;\n code?: string;\n event?: ChannelEvent;\n },\n resolveLogin: () => void,\n rejectLogin: (err: Error) => void\n ): void {\n if (msg.type === 'RUN_ERROR' || msg.type === 'error') {\n const message = msg.message ?? 'Operator session error';\n if (msg.code === 'org_auth_required') {\n const requirement = parseOrgAuthRequirement(msg);\n if (requirement) this.handlers.onOrgAuthRequired?.(requirement);\n }\n if (this.sessionState === 'connecting') {\n this.setSessionState('error');\n rejectLogin(new Error(message));\n } else {\n this.setCallPhase('failed');\n this.handlers.onError?.(message);\n }\n return;\n }\n\n if (msg.type === 'protocol.init' && this.sessionState === 'connecting') {\n return;\n }\n\n if (msg.type === 'CUSTOM' && msg.name === 'operator.session_ready') {\n this.setSessionState('connected');\n this.setCallPhase('ready');\n this.startHeartbeat();\n resolveLogin();\n return;\n }\n\n if (msg.type === 'event' && msg.event) {\n if (this.handleRemoteVoiceAudio(msg.event)) {\n return;\n }\n this.handlers.onAguiEvent?.(msg.event);\n return;\n }\n\n if (msg.type === 'CUSTOM' && msg.name === 'operator.call.started') {\n this.receivedRemoteAudio = false;\n this.setCallPhase('dialing');\n return;\n }\n\n if (msg.type === 'CUSTOM' && msg.name === 'operator.call.hold_failed') {\n if (this.callPhase === 'onHold') {\n this.handlers.onError?.('Hold music is unavailable. The call is still on hold.');\n }\n return;\n }\n\n if (msg.type === 'CUSTOM' && msg.name === 'operator.call.ended') {\n this.onHold = false;\n this.muted = false;\n this.receivedRemoteAudio = false;\n this.stopMicrophone();\n this.stopPlayback();\n const endSession = msg.value?.end_session === true;\n const reason = typeof msg.value?.reason === 'string' ? msg.value.reason : undefined;\n if (endSession) {\n this.setCallPhase('idle');\n this.notifySessionClosed(reason ?? 'peer_hangup');\n } else {\n this.setCallPhase('ready');\n }\n return;\n }\n }\n\n /** Play callee PCM from wrapped chat-stream events; returns true if handled. */\n private handleRemoteVoiceAudio(event: ChannelEvent): boolean {\n if (event.type !== 'CUSTOM' || event.name !== 'voice.audio') {\n return false;\n }\n if (this.onHold) return true;\n\n const value = event.value;\n if (!value || typeof value !== 'object') return true;\n\n const data = (value as Record<string, unknown>).data;\n if (typeof data !== 'string' || !data) return true;\n\n if (\n !this.receivedRemoteAudio &&\n (this.callPhase === 'dialing' || this.callPhase === 'live')\n ) {\n this.receivedRemoteAudio = true;\n this.setCallPhase('live');\n }\n void this.playPcm16(base64ToFloat32Array(data));\n return true;\n }\n\n private startHeartbeat(): void {\n this.clearHeartbeat();\n this.heartbeatTimer = setInterval(() => {\n if (this.ws?.readyState === WebSocket.OPEN) {\n this.ws.send(JSON.stringify({ type: 'heartbeat' }));\n }\n }, 30_000);\n }\n\n private clearHeartbeat(): void {\n if (this.heartbeatTimer) {\n clearInterval(this.heartbeatTimer);\n this.heartbeatTimer = null;\n }\n }\n\n private sendCustom(name: string, value: Record<string, unknown> = {}): void {\n if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {\n throw new Error('Operator session WebSocket is not connected');\n }\n this.ws.send(JSON.stringify({ type: 'CUSTOM', name, value }));\n }\n\n async placeCall(memberId: number): Promise<void> {\n if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {\n throw new Error('Operator session WebSocket is not connected');\n }\n if (this.sessionState !== 'connected') {\n throw new Error('Operator session is not ready');\n }\n await this.startMicrophone();\n this.sendCustom('operator.call.place', { member_id: memberId });\n }\n\n /**\n * Answer an inbound operator call the caller has already been routed to.\n *\n * Symmetric with {@link placeCall} but for the inbound direction: instead of\n * dialing an outbound leg it tells the backend to bridge the already-ringing\n * caller to this operator session. The backend (see\n * `lib/operator_session_handler.py::_answer_inbound_call`) registers the\n * audio bridge, marks the ring state `answered`, and replies with\n * `operator.call.started` — after which callee PCM arrives as `voice.audio`\n * events (played via {@link playPcm16}) and mic audio streams the other way,\n * exactly like an outbound call.\n *\n * Must be called once the session is ready (state `connected`). Starts the\n * microphone before sending so the operator's audio is flowing the instant\n * the bridge registers.\n */\n async answerCall(interactionId: string, answerToken: string): Promise<void> {\n if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {\n throw new Error('Operator session WebSocket is not connected');\n }\n if (this.sessionState !== 'connected') {\n throw new Error('Operator session is not ready');\n }\n await this.startMicrophone();\n this.sendCustom('operator.call.answer', {\n interaction_id: interactionId,\n answer_token: answerToken,\n });\n }\n\n /**\n * Join a live, escalated voice call on this chat.\n *\n * Unlike {@link answerCall} (a waiting caller whose ring poll redirects the\n * PSTN leg), the caller here is already on the AI media stream with the AI\n * paused for an escalation. The backend\n * (`lib/operator_session_handler.py::_join_live_call`) authorizes, attaches\n * this session as bridge side \"a\", and re-points the live caller leg onto\n * the bridge over Twilio REST — replacing the AI stream with the human one.\n * The server then sends `operator.call.started`, after which audio flows\n * exactly like an answered call.\n *\n * The chat id is carried by the session URL, so no argument is needed. Must\n * be called once the session is ready (state `connected`); starts the\n * microphone first so operator audio flows the instant the bridge attaches.\n */\n async joinCall(): Promise<void> {\n if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {\n throw new Error('Operator session WebSocket is not connected');\n }\n if (this.sessionState !== 'connected') {\n throw new Error('Operator session is not ready');\n }\n await this.startMicrophone();\n this.sendCustom('operator.call.join');\n }\n\n /**\n * Mute or unmute the operator's outbound microphone. Muting gates mic frames\n * locally (the caller stops hearing the operator) while callee audio keeps\n * playing — distinct from {@link setHold}, which is a two-way pause the\n * backend is told about. Purely client-side; no server round-trip.\n */\n setMuted(muted: boolean): void {\n this.muted = muted;\n }\n\n isMuted(): boolean {\n return this.muted;\n }\n\n hangUp(): void {\n try {\n this.sendCustom('operator.call.hangup');\n } catch {\n /* socket already closed */\n }\n this.onHold = false;\n this.receivedRemoteAudio = false;\n }\n\n forwardCall(phoneNumber: string): void {\n this.receivedRemoteAudio = false;\n this.setCallPhase('dialing');\n this.sendCustom('operator.call.forward', { phone_number: phoneNumber });\n }\n\n setHold(onHold: boolean): void {\n this.onHold = onHold;\n this.sendCustom('operator.call.hold', { on_hold: onHold });\n if (this.callPhase === 'live' || this.callPhase === 'onHold') {\n this.setCallPhase(onHold ? 'onHold' : 'live');\n }\n if (onHold) {\n this.stopPlayback();\n }\n }\n\n async startMicrophone(): Promise<void> {\n if (typeof window === 'undefined') return;\n if (!navigator.mediaDevices?.getUserMedia) {\n throw new Error('Microphone not available in this browser');\n }\n if (this.micActive) return;\n\n const ws = this.ws;\n const mediaStream = await navigator.mediaDevices.getUserMedia({\n audio: {\n echoCancellation: true,\n noiseSuppression: true,\n autoGainControl: true,\n },\n });\n if (this.ws !== ws) {\n for (const track of mediaStream.getTracks()) track.stop();\n throw new Error('Operator session WebSocket is not connected');\n }\n this.mediaStream = mediaStream;\n\n let audioContext: AudioContext | null = null;\n let processor: ScriptProcessorNode | null = null;\n try {\n const Ctx =\n window.AudioContext ??\n (window as unknown as { webkitAudioContext?: typeof AudioContext }).webkitAudioContext;\n if (!Ctx) throw new Error('Web Audio not supported');\n\n audioContext = new Ctx();\n this.audioContext = audioContext;\n if (audioContext.state === 'suspended') {\n await audioContext.resume();\n }\n if (this.ws !== ws) throw new Error('Operator session WebSocket is not connected');\n\n const source = audioContext.createMediaStreamSource(mediaStream);\n processor = audioContext.createScriptProcessor(4096, 1, 1);\n this.processor = processor;\n\n processor.onaudioprocess = (event) => {\n if (!this.ws || this.ws.readyState !== WebSocket.OPEN) return;\n if (this.onHold) return;\n if (this.muted) return;\n if (\n this.callPhase !== 'dialing' &&\n this.callPhase !== 'live' &&\n this.callPhase !== 'onHold'\n ) {\n return;\n }\n\n const input = event.inputBuffer.getChannelData(0);\n const copy = new Float32Array(input.length);\n copy.set(input);\n\n const sampleRate = this.audioContext?.sampleRate ?? TARGET_SAMPLE_RATE;\n let pcm = copy;\n if (sampleRate !== TARGET_SAMPLE_RATE) {\n const ratio = sampleRate / TARGET_SAMPLE_RATE;\n const newLen = Math.floor(copy.length / ratio);\n const down = new Float32Array(newLen);\n for (let i = 0; i < newLen; i += 1) {\n down[i] = copy[Math.floor(i * ratio)];\n }\n pcm = down;\n }\n\n this.ws.send(\n JSON.stringify({\n type: 'CUSTOM',\n name: 'voice.audio',\n value: {\n data: float32ArrayToBase64(pcm),\n format: 'pcm16',\n sample_rate: TARGET_SAMPLE_RATE,\n },\n })\n );\n };\n\n source.connect(processor);\n processor.connect(audioContext.destination);\n } catch (err) {\n if (processor && this.processor === processor) {\n processor.disconnect();\n this.processor = null;\n }\n for (const track of mediaStream.getTracks()) track.stop();\n if (this.mediaStream === mediaStream) this.mediaStream = null;\n if (audioContext && this.audioContext === audioContext) {\n this.audioContext = null;\n void audioContext.close().catch(() => undefined);\n }\n throw err;\n }\n this.micActive = true;\n }\n\n stopMicrophone(): void {\n this.processor?.disconnect();\n this.processor = null;\n for (const track of this.mediaStream?.getTracks() ?? []) {\n track.stop();\n }\n this.mediaStream = null;\n this.micActive = false;\n }\n\n private async playPcm16(samples: Float32Array): Promise<void> {\n if (typeof window === 'undefined') return;\n\n const Ctx =\n window.AudioContext ??\n (window as unknown as { webkitAudioContext?: typeof AudioContext }).webkitAudioContext;\n if (!Ctx) return;\n\n if (!this.audioContext || this.audioContext.state === 'closed') {\n this.audioContext = new Ctx();\n }\n if (this.audioContext.state === 'suspended') {\n await this.audioContext.resume();\n }\n\n const buffer = this.audioContext.createBuffer(1, samples.length, SERVER_SAMPLE_RATE);\n buffer.copyToChannel(new Float32Array(samples), 0);\n\n const source = this.audioContext.createBufferSource();\n source.buffer = buffer;\n source.connect(this.audioContext.destination);\n\n const now = this.audioContext.currentTime;\n const startAt = this.nextPlaybackTime < now + 0.02 ? now + 0.02 : this.nextPlaybackTime;\n source.start(startAt);\n this.nextPlaybackTime = startAt + buffer.duration;\n this.playbackSources.push(source);\n source.onended = () => {\n const idx = this.playbackSources.indexOf(source);\n if (idx >= 0) this.playbackSources.splice(idx, 1);\n };\n }\n\n private stopPlayback(): void {\n for (const src of this.playbackSources) {\n try {\n src.stop();\n } catch {\n /* already stopped */\n }\n }\n this.playbackSources = [];\n this.nextPlaybackTime = 0;\n }\n\n async disconnect(): Promise<void> {\n this.connectGeneration += 1;\n await this.closeSession();\n }\n\n private async closeSession(): Promise<void> {\n const cancelLogin = this.cancelPendingLogin;\n this.cancelPendingLogin = null;\n cancelLogin?.();\n if (\n this.callPhase === 'dialing' ||\n this.callPhase === 'live' ||\n this.callPhase === 'onHold'\n ) {\n this.hangUp();\n }\n this.clearHeartbeat();\n this.stopMicrophone();\n this.stopPlayback();\n const ws = this.ws;\n this.ws = null;\n ws?.close();\n if (this.audioContext && this.audioContext.state !== 'closed') {\n await this.audioContext.close().catch(() => undefined);\n }\n this.audioContext = null;\n this.onHold = false;\n this.muted = false;\n this.receivedRemoteA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ACnB,KAAK,cAAc,UACpB;AACC,WAAK,OAAO;AAAA,IACf;AACA,SAAK,eAAe;AACpB,SAAK,eAAe;AACpB,SAAK,aAAa;AAClB,UAAM,KAAK,KAAK;AAChB,SAAK,KAAK;AACV,QAAI,MAAM;AACV,QAAI,KAAK,gBAAgB,KAAK,aAAa,UAAU,UAAU;AAC5D,YAAM,KAAK,aAAa,MAAM,EAAE,MAAM,MAAM,MAAS;AAAA,IACxD;AACA,SAAK,eAAe;AACpB,SAAK,SAAS;AACd,SAAK,QAAQ;AACb,SAAK,sBAAsB;AAC3B,SAAK,gBAAgB,MAAM;AAC3B,SAAK,aAAa,MAAM;AAAA,EAC3B;AACH;","names":["defaultClient"]}
1
+ {"version":3,"sources":["../src/realtime/types.ts","../src/realtime/login-token.ts","../src/realtime/socket-client.ts","../src/realtime/workspace-client.ts","../src/realtime/account-client.ts","../src/types/generated/account.ts","../src/realtime/editor-collaboration.ts","../src/realtime/operator-session-client.ts"],"sourcesContent":["/** Event received from a subscribed workspace realtime channel. */\nexport interface ChannelEvent {\n type: string;\n [key: string]: unknown;\n}\n\nexport type ChannelListener = (event: ChannelEvent) => void;\nexport type Unsubscribe = () => void;\n\n/**\n * What every realtime connection needs: where the API is, and who is asking.\n *\n * The account socket needs nothing more — its scope comes from the server's\n * grant map, not from the URL — so this is the base rather than a widening of\n * {@link RealtimeAuthSession}. A workspace session is assignable to it, which\n * is what lets one session object drive both clients during cutover.\n */\nexport interface RealtimeSessionBase {\n apiUrl: string;\n /**\n * The credential for one `login` frame, fetched once per connect attempt —\n * reconnects included — and never reused.\n *\n * In a browser this mints a single-use `gr_wst_` token same-origin (the\n * server refuses anything else from a browser handshake), so page script\n * never holds the account session. A non-browser client (Node, a CLI) may\n * return its bearer credential. Resolve `null` when no token can be had;\n * the client treats that attempt as failed and retries on its backoff.\n *\n * The provider's identity is part of the session: replacing it with a\n * different function reconnects the socket.\n */\n getLoginToken: RealtimeLoginTokenProvider;\n}\n\n/** Mints the token for one realtime `login` frame. See {@link RealtimeSessionBase}. */\nexport type RealtimeLoginTokenProvider = () => Promise<string | null>;\n\n/** Auth context for workspace realtime WebSocket connections. */\nexport interface RealtimeAuthSession extends RealtimeSessionBase {\n workspaceUuid: string;\n}\n\n/** Auth context for the account realtime WebSocket. No workspace, by design. */\nexport type AccountRealtimeSession = RealtimeSessionBase;\n\n/**\n * A workspace the server refused because its organization requires SSO or MFA\n * and the connection holds no valid org session for it. `authUrl` is the org\n * step-up route. `requirement` says which proof is missing. The frame's\n * `acr_values` is not read: it is fixed per requirement, so `requirement`\n * already says it.\n */\nexport interface OrgAuthRequirement {\n workspaceUuid: string;\n orgUuid: string;\n authUrl: string;\n requirement: 'sso' | 'mfa';\n}\n\n/** Read one step-up item off a server frame; null when a field is missing or mistyped. */\nexport function parseOrgAuthRequirement(value: unknown): OrgAuthRequirement | null {\n if (typeof value !== 'object' || value === null) return null;\n const item = value as Record<string, unknown>;\n const {\n workspace_uuid: workspaceUuid,\n org_uuid: orgUuid,\n auth_url: authUrl,\n requirement,\n } = item;\n if (\n typeof workspaceUuid !== 'string' ||\n typeof orgUuid !== 'string' ||\n typeof authUrl !== 'string' ||\n !workspaceUuid ||\n !orgUuid\n ) {\n return null;\n }\n return {\n workspaceUuid,\n orgUuid,\n authUrl,\n requirement: requirement === 'mfa' ? 'mfa' : 'sso',\n };\n}\n\n/** Read an `org_auth_required: [items]` list; malformed items are dropped. */\nexport function parseOrgAuthRequirements(value: unknown): OrgAuthRequirement[] {\n if (!Array.isArray(value)) return [];\n return value.flatMap((item) => {\n const parsed = parseOrgAuthRequirement(item);\n return parsed ? [parsed] : [];\n });\n}\n\n/** The server's reply to an `org_sessions` frame. */\nexport interface OrgSessionsUpdate {\n /** Orgs whose session this socket now holds. */\n orgUuids: string[];\n orgAuthRequired: OrgAuthRequirement[];\n}\n\nexport type OperatorSessionState = 'idle' | 'connecting' | 'connected' | 'error';\n\nexport type OperatorCallPhase =\n | 'idle'\n | 'connecting'\n | 'ready'\n | 'dialing'\n | 'live'\n | 'onHold'\n | 'ended'\n | 'failed';\n\n/** Phases where Hold / Forward / Hang up apply to an active phone leg. */\nexport function isActiveCallPhase(phase: OperatorCallPhase): boolean {\n return phase === 'dialing' || phase === 'live' || phase === 'onHold';\n}\n\n// ---------------------------------------------------------------------------\n// Activity Spine (docs/projects/active/activity-spine.md)\n// ---------------------------------------------------------------------------\n\n/**\n * The two activity lanes a client can watch.\n *\n * `activity` is the whole workspace's feed; `activity:me` is the connected\n * member's own private lane and open items, kept separate so a busy workspace\n * does not wake every operator's badge on every event.\n *\n * Both are named constants rather than interpolated strings because the server\n * matches them exactly — a typo would subscribe successfully to nothing.\n */\nexport const ACTIVITY_CHANNEL = 'activity' as const;\nexport const ACTIVITY_MEMBER_CHANNEL = 'activity:me' as const;\n\n/**\n * The account's own lane, on the account socket only.\n *\n * Carries two things the workspace lanes cannot: the account's\n * `account_private` rows (manager / DM / agent-job chats, member-targeted\n * routine runs, and the concierge lane, which has no workspace at all), and a\n * change to the account's own grants.\n */\nexport const ACCOUNT_ACTIVITY_CHANNEL = 'account:activity' as const;\n\nexport type ActivityChannelName =\n | typeof ACTIVITY_CHANNEL\n | typeof ACTIVITY_MEMBER_CHANNEL\n | typeof ACCOUNT_ACTIVITY_CHANNEL;\n\n/**\n * Operator presence, on the account socket only.\n *\n * The channel operator presence is **written** on. Presence state lives once,\n * at the account (`docs/projects/active/account-socket.md` § \"Presence,\n * migrated\"), and is projected into each chosen workspace's live set — so\n * going live is one command here rather than one per workspace socket.\n *\n * Unlike the activity lanes this one is bidirectional and does carry a\n * payload, because it is not an invalidation lane: `presence_confirmed`\n * reports the scope set the server actually honoured, which is the answer to\n * the command and is not re-fetchable from anywhere else.\n */\nexport const ACCOUNT_PRESENCE_CHANNEL = 'account:presence' as const;\n\n/** The workspace-scoped presence channel, on the per-workspace socket. */\nexport const PRESENCE_CHANNEL = 'presence' as const;\n\n/**\n * What an activity channel delivers — and deliberately all it delivers.\n *\n * **No event payloads travel over this socket.** The signal says *look again*;\n * the look goes through `POST /activity/query` (or `/counts` for a badge) under\n * the client's own session, where it is authorized against a freshly compiled\n * grant set and recorded as a bulk PHI access. A payload here would be an\n * authorization decision frozen at publish time by a producer that knows\n * nothing about who is listening — and a read that left no audit record.\n *\n * So: refetch on this, never render from it.\n */\nexport interface ActivityInvalidationEvent extends ChannelEvent {\n type: 'invalidate';\n data: {\n scope: 'workspace' | 'member' | 'account';\n reason: 'drain';\n };\n}\n\n/** Narrow a channel event to an activity invalidation. */\nexport function isActivityInvalidation(event: ChannelEvent): event is ActivityInvalidationEvent {\n if (event.type !== 'invalidate') return false;\n const data = (event as { data?: unknown }).data;\n if (typeof data !== 'object' || data === null) return false;\n const scope = (data as { scope?: unknown }).scope;\n return scope === 'workspace' || scope === 'member' || scope === 'account';\n}\n","import type { RealtimeLoginTokenProvider } from './types';\n\n/**\n * How long one connect attempt waits for its login token. A provider that\n * never settles (a hung mint request) must not hold the attempt open forever:\n * past this the attempt fails like any other and the caller's backoff applies.\n */\nexport const LOGIN_TOKEN_TIMEOUT_MS = 10_000;\n\n/**\n * Call `provider` once, bounded by {@link LOGIN_TOKEN_TIMEOUT_MS}.\n *\n * Resolves the token, or `null` when the provider throws, times out, or\n * returns anything but a non-empty string. Never rejects.\n */\nexport async function mintLoginToken(provider: RealtimeLoginTokenProvider): Promise<string | null> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n const token: unknown = await Promise.race([\n provider(),\n new Promise<null>((resolve) => {\n timer = setTimeout(() => resolve(null), LOGIN_TOKEN_TIMEOUT_MS);\n }),\n ]);\n return typeof token === 'string' && token.length > 0 ? token : null;\n } catch {\n return null;\n } finally {\n if (timer !== undefined) clearTimeout(timer);\n }\n}\n","/**\n * The realtime socket state machine, shared by both mounts.\n *\n * Two sockets speak the same protocol — `/api/v2/w/{wid}/ws/realtime` and\n * `/api/v2/ws/realtime` — and differ in exactly two places: the URL they open,\n * and the identity `protocol.init` hands back. Everything else (login,\n * heartbeat, reconnect with backoff, per-channel subscribe retry, listener\n * fan-out, deferred close) is one implementation here rather than two that\n * drift.\n *\n * That matters more than it sounds. The subscribe-retry and reconnect logic is\n * where the sharp edges live, and a second copy of it would be a second place\n * for a fix to be applied once.\n *\n * Protocol:\n * Client → Server: login, subscribe, unsubscribe, heartbeat, message\n * Server → Client: protocol.init, subscribed, subscribe_error, unsubscribed,\n * event, error\n */\n\nimport { mintLoginToken } from './login-token';\nimport {\n parseOrgAuthRequirement,\n parseOrgAuthRequirements,\n type ChannelEvent,\n type ChannelListener,\n type OrgAuthRequirement,\n type OrgSessionsUpdate,\n type RealtimeSessionBase,\n type Unsubscribe,\n} from './types';\n\nconst HEARTBEAT_INTERVAL_MS = 30_000;\nconst RECONNECT_DELAY_MS = 3_000;\nconst MAX_RECONNECT_ATTEMPTS = 5;\nconst CLOSE_DELAY_MS = 1_000;\nconst MAX_SUBSCRIBE_RETRY_DELAY_MS = 30_000;\n/** Close code and error code of a socket whose login credential ended (`lib/auth/realtime_credential_liveness.py`). */\nconst CREDENTIAL_REVOKED_CLOSE_CODE = 4001;\nconst CREDENTIAL_REVOKED_CODE = 'credential_revoked';\nconst CREDENTIAL_REVOKED_REASON = 'Credential revoked';\n\ninterface SocketState {\n ws: WebSocket | null;\n connected: boolean;\n connecting: boolean;\n /**\n * The last transport-or-server failure, or null once a connection succeeds.\n *\n * The state machine has always known this; it simply had no way to say so,\n * so every consumer hardcoded `error: null` and reported a healthy socket\n * through an outage. Two things set it: a server `error` frame (which is\n * how a rejected login is reported), and running out of reconnect\n * attempts — the point at which the client has genuinely given up and the\n * user needs to know, rather than each transient close on the way there.\n */\n lastError: string | null;\n listeners: Map<string, Set<ChannelListener>>;\n subscribedChannels: Set<string>;\n subscriptionRevision: number;\n subscriptionRetryChannels: Set<string>;\n subscriptionRetryAttempts: number;\n subscriptionRetryTimer: ReturnType<typeof setTimeout> | null;\n reconnectAttempts: number;\n reconnectTimer: ReturnType<typeof setTimeout> | null;\n heartbeatTimer: ReturnType<typeof setInterval> | null;\n closeTimer: ReturnType<typeof setTimeout> | null;\n intentionalClose: boolean;\n /**\n * The server refused this connection for want of an org session (an error\n * frame, then close 4003). Reconnecting with the same evidence is refused\n * again, so the client waits for {@link RealtimeSocketClient.retryAfterOrgAuth}.\n */\n orgAuthHalted: boolean;\n /**\n * The server ended the login credential (a signed-out session, a revoked\n * device): an `error` frame coded `credential_revoked`, or close 4001 with\n * the reason `Credential revoked`. Every reconnect would present the same\n * dead credential, so the client stops until a deliberate close or a new\n * session.\n */\n credentialRevoked: boolean;\n /**\n * Bumped by every connect attempt and every deliberate close. A connect\n * attempt awaits its login token before it opens a socket; if the\n * generation moved while it waited, a close or a newer attempt owns the\n * state and the stale attempt stops without touching it.\n */\n connectGeneration: number;\n}\n\nfunction createSocketState(): SocketState {\n return {\n ws: null,\n connected: false,\n connecting: false,\n lastError: null,\n listeners: new Map(),\n subscribedChannels: new Set(),\n subscriptionRevision: 0,\n subscriptionRetryChannels: new Set(),\n subscriptionRetryAttempts: 0,\n subscriptionRetryTimer: null,\n reconnectAttempts: 0,\n reconnectTimer: null,\n heartbeatTimer: null,\n closeTimer: null,\n intentionalClose: false,\n orgAuthHalted: false,\n credentialRevoked: false,\n connectGeneration: 0,\n };\n}\n\n/** The `protocol.init` frame, before either subclass narrows it. */\nexport interface ProtocolInitMessage {\n memberId?: unknown;\n accountUuid?: unknown;\n workspaceUuids?: unknown;\n}\n\nexport abstract class RealtimeSocketClient<TSession extends RealtimeSessionBase> {\n private session: TSession | null = null;\n private readonly getSessionFn: (() => TSession | null) | null;\n private readonly state: SocketState = createSocketState();\n private readonly connectionListeners = new Set<(connected: boolean) => void>();\n private readonly orgAuthListeners = new Set<(items: OrgAuthRequirement[]) => void>();\n private readonly orgSessionsListeners = new Set<(update: OrgSessionsUpdate) => void>();\n private readonly credentialRevokedListeners = new Set<() => void>();\n\n constructor(config?: TSession | (() => TSession | null)) {\n if (typeof config === 'function') {\n this.getSessionFn = config;\n } else {\n this.getSessionFn = null;\n if (config) {\n this.session = config;\n }\n }\n }\n\n /** The WebSocket URL this mount connects to. */\n protected abstract buildUrl(session: TSession): string;\n\n /**\n * Record whatever identity `protocol.init` carried for this mount.\n *\n * Called before the connection is announced, so a `onConnection` listener\n * that immediately reads the identity always sees the new one.\n */\n protected abstract readProtocolInit(msg: ProtocolInitMessage): void;\n\n /** Forget the identity on a deliberate close. See {@link closeConnection}. */\n protected abstract clearIdentity(): void;\n\n /**\n * Whether replacing `previous` with `next` invalidates the open socket.\n *\n * A different login-token provider always does — it stands for a different\n * identity; the rest is mount-specific — a workspace client changing\n * workspace is a different socket, and an account client has no such axis.\n */\n protected sessionRequiresReconnect(previous: TSession | null, next: TSession): boolean {\n return previous?.getLoginToken !== next.getLoginToken || previous?.apiUrl !== next.apiUrl;\n }\n\n protected resolveSession(): TSession | null {\n return this.session ?? this.getSessionFn?.() ?? null;\n }\n\n private notifyConnectionListeners(): void {\n for (const listener of this.connectionListeners) {\n listener(this.state.connected);\n }\n }\n\n private clearCloseTimer(): void {\n if (this.state.closeTimer) {\n clearTimeout(this.state.closeTimer);\n this.state.closeTimer = null;\n }\n }\n\n private clearSubscriptionRetry(channel?: string): void {\n if (channel) {\n this.state.subscriptionRetryChannels.delete(channel);\n } else {\n this.state.subscriptionRetryChannels.clear();\n }\n\n if (this.state.subscriptionRetryChannels.size > 0) return;\n\n if (this.state.subscriptionRetryTimer) {\n clearTimeout(this.state.subscriptionRetryTimer);\n this.state.subscriptionRetryTimer = null;\n }\n this.state.subscriptionRetryAttempts = 0;\n }\n\n private scheduleSubscriptionRetry(channels: string[]): void {\n for (const channel of channels) {\n if (this.state.listeners.has(channel) && !this.state.subscribedChannels.has(channel)) {\n this.state.subscriptionRetryChannels.add(channel);\n }\n }\n\n if (this.state.subscriptionRetryChannels.size === 0 || this.state.subscriptionRetryTimer) {\n return;\n }\n\n this.state.subscriptionRetryAttempts += 1;\n const delay = Math.min(\n RECONNECT_DELAY_MS * this.state.subscriptionRetryAttempts,\n MAX_SUBSCRIBE_RETRY_DELAY_MS\n );\n\n this.state.subscriptionRetryTimer = setTimeout(() => {\n this.state.subscriptionRetryTimer = null;\n const retryChannels = Array.from(this.state.subscriptionRetryChannels).filter(\n (channel) =>\n this.state.listeners.has(channel) && !this.state.subscribedChannels.has(channel)\n );\n\n for (const channel of this.state.subscriptionRetryChannels) {\n if (!retryChannels.includes(channel)) {\n this.state.subscriptionRetryChannels.delete(channel);\n }\n }\n\n if (retryChannels.length === 0) {\n this.state.subscriptionRetryAttempts = 0;\n return;\n }\n\n if (this.state.connected && this.state.ws?.readyState === WebSocket.OPEN) {\n this.state.ws.send(JSON.stringify({ type: 'subscribe', channels: retryChannels }));\n }\n }, delay);\n }\n\n setSession(session: TSession): void {\n const changed = this.sessionRequiresReconnect(this.session, session);\n\n this.session = session;\n // `connecting` with no `ws` is an attempt still minting its token under\n // the old session; closing bumps the generation so it stops there.\n if (changed && (this.state.ws || this.state.connecting)) {\n this.closeConnection();\n }\n // A revoked credential belonged to the old session.\n if (changed) this.state.credentialRevoked = false;\n if (this.state.listeners.size > 0) {\n this.ensureConnection();\n }\n }\n\n subscribe(channel: string, listener: ChannelListener): Unsubscribe {\n this.clearCloseTimer();\n\n let listeners = this.state.listeners.get(channel);\n if (!listeners) {\n listeners = new Set();\n this.state.listeners.set(channel, listeners);\n }\n listeners.add(listener);\n\n this.ensureConnection();\n\n if (\n this.state.connected &&\n this.state.ws?.readyState === WebSocket.OPEN &&\n !this.state.subscribedChannels.has(channel)\n ) {\n this.state.ws.send(JSON.stringify({ type: 'subscribe', channels: [channel] }));\n }\n\n return () => {\n const channelListeners = this.state.listeners.get(channel);\n channelListeners?.delete(listener);\n if (channelListeners && channelListeners.size === 0) {\n this.state.listeners.delete(channel);\n this.state.subscribedChannels.delete(channel);\n this.clearSubscriptionRetry(channel);\n if (this.state.connected && this.state.ws?.readyState === WebSocket.OPEN) {\n this.state.ws.send(JSON.stringify({ type: 'unsubscribe', channels: [channel] }));\n }\n }\n\n if (this.state.listeners.size === 0) {\n this.state.closeTimer = setTimeout(() => {\n if (this.state.listeners.size === 0) {\n this.closeConnection();\n }\n }, CLOSE_DELAY_MS);\n }\n };\n }\n\n /**\n * Hear every workspace the server refused for want of an org session: a\n * `subscribe_error` entry, an `error` frame with that code, a lapse notice,\n * or the list in an `org_sessions_updated` reply.\n */\n onOrgAuthRequired(listener: (items: OrgAuthRequirement[]) => void): () => void {\n this.orgAuthListeners.add(listener);\n return () => {\n this.orgAuthListeners.delete(listener);\n };\n }\n\n /** Hear the server's reply to an `org_sessions` frame. */\n onOrgSessionsUpdated(listener: (update: OrgSessionsUpdate) => void): () => void {\n this.orgSessionsListeners.add(listener);\n return () => {\n this.orgSessionsListeners.delete(listener);\n };\n }\n\n /**\n * Hear that the server ended this socket's login credential. The client\n * does not reconnect afterwards; the consumer decides what the person sees\n * (in the web app, the account check that leads to the login page).\n */\n onCredentialRevoked(listener: () => void): () => void {\n this.credentialRevokedListeners.add(listener);\n return () => {\n this.credentialRevokedListeners.delete(listener);\n };\n }\n\n /** Whether the server ended this socket's login credential. */\n isCredentialRevoked(): boolean {\n return this.state.credentialRevoked;\n }\n\n private markCredentialRevoked(message: string): void {\n if (this.state.credentialRevoked) return;\n this.state.credentialRevoked = true;\n this.state.lastError = message;\n if (this.state.reconnectTimer) {\n clearTimeout(this.state.reconnectTimer);\n this.state.reconnectTimer = null;\n }\n this.notifyConnectionListeners();\n for (const listener of this.credentialRevokedListeners) listener();\n }\n\n private emitOrgAuthRequired(items: OrgAuthRequirement[]): void {\n if (items.length === 0) return;\n for (const listener of this.orgAuthListeners) listener(items);\n }\n\n /** Send a control frame (one that is not a channel message) on the open socket. */\n sendFrame(frame: { type: string; [key: string]: unknown }): boolean {\n if (!this.state.connected || this.state.ws?.readyState !== WebSocket.OPEN) return false;\n this.state.ws.send(JSON.stringify(frame));\n return true;\n }\n\n /**\n * Try again after the person completed org sign-in: reconnect a socket the\n * server closed for it, or ask again for every channel it refused.\n */\n retryAfterOrgAuth(): void {\n this.state.orgAuthHalted = false;\n if (this.state.connected && this.state.ws?.readyState === WebSocket.OPEN) {\n const pending = Array.from(this.state.listeners.keys()).filter(\n (channel) => !this.state.subscribedChannels.has(channel)\n );\n if (pending.length > 0) {\n this.state.ws.send(JSON.stringify({ type: 'subscribe', channels: pending }));\n }\n return;\n }\n if (this.state.ws || this.state.connecting) return;\n this.state.reconnectAttempts = 0;\n this.ensureConnection();\n }\n\n send(channel: string, data: unknown): void {\n if (!this.state.connected || !this.state.ws) return;\n this.state.ws.send(JSON.stringify({ type: 'message', channel, data }));\n }\n\n onConnection(listener: (connected: boolean) => void): () => void {\n this.connectionListeners.add(listener);\n listener(this.state.connected);\n return () => {\n this.connectionListeners.delete(listener);\n };\n }\n\n isConnected(): boolean {\n return this.state.connected;\n }\n\n /**\n * Whether the server has acknowledged this channel subscription.\n *\n * This is stricter than having a local listener: it becomes true only after\n * a `subscribed` frame, returns to false on disconnect or server-driven\n * unsubscribe, and stays false while automatic subscribe retry is pending.\n * Consumers that must order a command after subscription admission should\n * observe {@link getSubscriptionRevision} and re-read this method.\n */\n isSubscribed(channel: string): boolean {\n return this.state.subscribedChannels.has(channel);\n }\n\n /**\n * Monotonic local revision of acknowledged subscription state.\n *\n * It increments when `subscribed` or `unsubscribed` changes the server-\n * acknowledged set. It is not a protocol sequence number and resets with a\n * new client instance; its purpose is external-store invalidation before a\n * consumer calls {@link isSubscribed} again.\n */\n getSubscriptionRevision(): number {\n return this.state.subscriptionRevision;\n }\n\n /**\n * A socket is open or opening and has not yet said `protocol.init`.\n *\n * Real state, read off the state machine. Consumers used to report a\n * literal `false` here and render \"Available\" over a socket that had never\n * connected; a toggle that cannot distinguish \"not live\" from \"cannot tell\n * yet\" is the shape of that bug.\n */\n isConnecting(): boolean {\n return this.state.connecting;\n }\n\n /** The last failure the socket gave up on, or null. See {@link SocketState.lastError}. */\n getLastError(): string | null {\n return this.state.lastError;\n }\n\n protected ensureConnection(): void {\n const session = this.resolveSession();\n if (!session) return;\n if (typeof window === 'undefined' || typeof WebSocket === 'undefined') return;\n if (this.state.ws || this.state.connecting) return;\n if (this.state.credentialRevoked) return;\n\n this.clearCloseTimer();\n this.state.connecting = true;\n this.state.intentionalClose = false;\n const generation = ++this.state.connectGeneration;\n // `connecting` is part of what consumers render, so entering it is a\n // change they have to hear about. Without this notify a `useSyncExternal`\n // store reading `isConnecting()` would only ever sample it on some later\n // unrelated transition.\n this.notifyConnectionListeners();\n\n void this.openSocket(session, generation);\n }\n\n /**\n * Mint this attempt's login token, then open the socket with it.\n *\n * A fresh token per attempt, reconnects included: a browser's token is\n * single-use and expires in seconds, so a token from an earlier attempt is\n * already spent.\n */\n private async openSocket(session: TSession, generation: number): Promise<void> {\n const token = await mintLoginToken(session.getLoginToken);\n if (generation !== this.state.connectGeneration) return;\n if (!token) {\n this.releaseUnopenedAttempt();\n return;\n }\n\n let ws: WebSocket;\n try {\n ws = new WebSocket(this.buildUrl(session));\n } catch {\n // A bad URL throws synchronously; without this the attempt would stay\n // `connecting` forever and every later `ensureConnection` would no-op.\n this.releaseUnopenedAttempt();\n return;\n }\n\n ws.onopen = () => {\n ws.send(JSON.stringify({ type: 'login', token }));\n };\n\n ws.onmessage = (event: MessageEvent) => {\n // Frames from a socket this client has already replaced belong to\n // nobody: acting on them would fold a stale connection's\n // subscription state into the live one.\n if (this.state.ws !== null && this.state.ws !== ws) return;\n try {\n const msg = JSON.parse(String(event.data)) as ProtocolInitMessage & {\n type?: string;\n channels?: string[];\n channel?: string;\n event?: ChannelEvent;\n errors?: unknown[];\n code?: unknown;\n org_auth_required?: unknown;\n org_uuids?: unknown;\n };\n\n if (msg.type === 'protocol.init' && !this.state.connected) {\n this.state.connected = true;\n this.readProtocolInit(msg);\n this.state.connecting = false;\n this.state.reconnectAttempts = 0;\n this.state.lastError = null;\n\n if (this.state.heartbeatTimer) clearInterval(this.state.heartbeatTimer);\n this.state.heartbeatTimer = setInterval(() => {\n if (this.state.ws?.readyState === WebSocket.OPEN) {\n this.state.ws.send(JSON.stringify({ type: 'heartbeat' }));\n }\n }, HEARTBEAT_INTERVAL_MS);\n\n if (this.state.listeners.size > 0) {\n ws.send(\n JSON.stringify({\n type: 'subscribe',\n channels: Array.from(this.state.listeners.keys()),\n })\n );\n }\n\n this.notifyConnectionListeners();\n return;\n }\n\n if (msg.type === 'subscribed' && Array.isArray(msg.channels)) {\n for (const ch of msg.channels) {\n this.state.subscribedChannels.add(ch);\n this.clearSubscriptionRetry(ch);\n }\n this.state.subscriptionRevision += 1;\n this.notifyConnectionListeners();\n return;\n }\n\n if (msg.type === 'subscribe_error' && Array.isArray(msg.errors)) {\n const retryableChannels: string[] = [];\n const orgRequired: OrgAuthRequirement[] = [];\n for (const rawError of msg.errors) {\n if (!rawError || typeof rawError !== 'object') continue;\n const error = rawError as {\n channel?: unknown;\n retryable?: unknown;\n code?: unknown;\n };\n if (typeof error.channel !== 'string') continue;\n if (error.code === 'org_auth_required') {\n // Not retryable: asking again with the same evidence is\n // refused again. The step-up path asks once it has new.\n this.clearSubscriptionRetry(error.channel);\n const requirement = parseOrgAuthRequirement(rawError);\n if (requirement) orgRequired.push(requirement);\n continue;\n }\n\n if (error.retryable === true) {\n retryableChannels.push(error.channel);\n } else {\n this.clearSubscriptionRetry(error.channel);\n }\n }\n this.scheduleSubscriptionRetry(retryableChannels);\n this.emitOrgAuthRequired(orgRequired);\n return;\n }\n\n if (msg.type === 'org_auth_required') {\n this.emitOrgAuthRequired(parseOrgAuthRequirements(msg.org_auth_required));\n return;\n }\n\n if (msg.type === 'org_sessions_updated') {\n const orgAuthRequired = parseOrgAuthRequirements(msg.org_auth_required);\n const orgUuids = Array.isArray(msg.org_uuids)\n ? msg.org_uuids.filter((value): value is string => typeof value === 'string')\n : [];\n for (const listener of this.orgSessionsListeners) {\n listener({ orgUuids, orgAuthRequired });\n }\n this.emitOrgAuthRequired(orgAuthRequired);\n return;\n }\n\n if (msg.type === 'unsubscribed' && Array.isArray(msg.channels)) {\n // The server also sends this unprompted when a grant change\n // revoked a subscription (account socket). Forgetting the\n // channel is what makes the client's next `subscribe` a real\n // re-authorization rather than a no-op against a stale set.\n for (const ch of msg.channels) {\n this.state.subscribedChannels.delete(ch);\n }\n this.state.subscriptionRevision += 1;\n this.notifyConnectionListeners();\n this.scheduleSubscriptionRetry(msg.channels);\n return;\n }\n\n if (msg.type === 'error' && msg.code === 'org_auth_required') {\n // A refusal for want of org sign-in, not a fault: it is routed to\n // the step-up, and the socket stays quiet until that finishes.\n this.state.orgAuthHalted = true;\n const requirement = parseOrgAuthRequirement(msg);\n if (requirement) this.emitOrgAuthRequired([requirement]);\n return;\n }\n\n if (msg.type === 'error' && msg.code === CREDENTIAL_REVOKED_CODE) {\n const message = (msg as { message?: unknown }).message;\n this.markCredentialRevoked(\n typeof message === 'string' && message ? message : CREDENTIAL_REVOKED_REASON\n );\n return;\n }\n\n if (msg.type === 'error') {\n // The server's own refusal — a rejected login, an unknown\n // message shape. Recorded rather than dropped: it is the one\n // failure the transport cannot tell the consumer about, because\n // the socket is open and will close looking like any other.\n const message = (msg as { message?: unknown }).message;\n this.state.lastError =\n typeof message === 'string' && message ? message : 'Realtime error';\n this.notifyConnectionListeners();\n return;\n }\n\n if (msg.type === 'event' && msg.channel && msg.event) {\n const channelListeners = this.state.listeners.get(msg.channel);\n if (channelListeners) {\n for (const channelListener of channelListeners) {\n try {\n channelListener(msg.event);\n } catch (err) {\n console.error('Channel listener error:', err);\n }\n }\n }\n }\n } catch {\n // Ignore malformed frames.\n }\n };\n\n ws.onclose = (event?: CloseEvent) => {\n // A close from a socket that is no longer this client's would\n // otherwise clear the REPLACEMENT connection's state: null its `ws`,\n // wipe its subscribed set, and stop its heartbeat — leaving a live\n // socket that believes it is subscribed to nothing and a client that\n // believes it is disconnected. Reachable whenever a `setSession`\n // replaced the socket while the old one's close was still in flight.\n if (this.state.ws !== null && this.state.ws !== ws) return;\n\n // The error frame is best effort; the close code and reason are not.\n if (\n event?.code === CREDENTIAL_REVOKED_CLOSE_CODE &&\n event.reason === CREDENTIAL_REVOKED_REASON\n ) {\n this.markCredentialRevoked(CREDENTIAL_REVOKED_REASON);\n }\n\n this.state.connected = false;\n this.state.connecting = false;\n this.state.ws = null;\n this.state.subscribedChannels.clear();\n this.clearSubscriptionRetry();\n\n if (this.state.heartbeatTimer) {\n clearInterval(this.state.heartbeatTimer);\n this.state.heartbeatTimer = null;\n }\n\n this.afterConnectionEnded();\n };\n\n ws.onerror = () => {\n // onclose will fire after this\n };\n\n this.state.ws = ws;\n }\n\n /**\n * End an attempt that never opened a socket. No `onclose` will run for it,\n * so the retry decision is made here, on the normal backoff.\n */\n private releaseUnopenedAttempt(): void {\n this.state.connecting = false;\n this.afterConnectionEnded();\n }\n\n /** Decide whether a connection that just ended (or never opened) retries. */\n private afterConnectionEnded(): void {\n const willRetry =\n !this.state.intentionalClose &&\n !this.state.orgAuthHalted &&\n !this.state.credentialRevoked &&\n this.state.listeners.size > 0 &&\n this.state.reconnectAttempts < MAX_RECONNECT_ATTEMPTS;\n\n if (\n !willRetry &&\n !this.state.intentionalClose &&\n !this.state.credentialRevoked &&\n this.state.listeners.size > 0\n ) {\n // Out of attempts with listeners still waiting: the client has\n // genuinely given up, which is the moment worth surfacing. Each\n // transient close on the way here is not — a socket that reconnects\n // in three seconds did not fail, and reporting it would train\n // people to ignore the indicator.\n this.state.lastError = 'Realtime connection lost';\n }\n\n this.notifyConnectionListeners();\n\n if (willRetry) {\n this.state.reconnectAttempts += 1;\n this.state.reconnectTimer = setTimeout(() => {\n this.ensureConnection();\n }, RECONNECT_DELAY_MS * this.state.reconnectAttempts);\n }\n }\n\n protected closeConnection(): void {\n this.state.intentionalClose = true;\n this.state.orgAuthHalted = false;\n // A deliberate close ends this identity's connection; a new session may\n // carry a live credential.\n this.state.credentialRevoked = false;\n this.state.connectGeneration += 1;\n this.clearCloseTimer();\n if (this.state.reconnectTimer) {\n clearTimeout(this.state.reconnectTimer);\n this.state.reconnectTimer = null;\n }\n if (this.state.heartbeatTimer) {\n clearInterval(this.state.heartbeatTimer);\n this.state.heartbeatTimer = null;\n }\n this.state.ws?.close();\n this.state.ws = null;\n this.state.connected = false;\n // Only a deliberate close forgets who we were; a transient `onclose`\n // leaves the identity in place because it is unchanged across a\n // reconnect, and the next `protocol.init` overwrites it anyway.\n this.clearIdentity();\n this.state.connecting = false;\n this.state.subscribedChannels.clear();\n this.clearSubscriptionRetry();\n this.notifyConnectionListeners();\n }\n}\n","/**\n * Unified workspace WebSocket client for real-time events.\n *\n * Mirrors `/api/v2/w/{wid}/ws/realtime`: log in with a token from the session's\n * `getLoginToken` provider (fresh per connect attempt),\n * subscribe to channels, receive AGUI events.\n *\n * The socket state machine — login, heartbeat, reconnect, subscribe retry —\n * lives in {@link RealtimeSocketClient}, shared with the account client. This\n * file is what is specific to the workspace mount: its URL, and the member id\n * `protocol.init` hands back.\n */\n\nimport { RealtimeSocketClient, type ProtocolInitMessage } from './socket-client';\nimport type { ChannelListener, RealtimeAuthSession, Unsubscribe } from './types';\n\n/** Build the workspace realtime WebSocket URL from session config. */\nexport function buildWorkspaceWsUrl(session: RealtimeAuthSession): string {\n const isSsl = session.apiUrl.startsWith('https');\n const host = session.apiUrl.replace(/^https?:\\/\\//, '');\n return `${isSsl ? 'wss' : 'ws'}://${host}/api/v2/w/${session.workspaceUuid}/ws/realtime`;\n}\n\nexport class WorkspaceRealtimeClient extends RealtimeSocketClient<RealtimeAuthSession> {\n private memberId: number | null = null;\n\n protected buildUrl(session: RealtimeAuthSession): string {\n return buildWorkspaceWsUrl(session);\n }\n\n protected readProtocolInit(msg: ProtocolInitMessage): void {\n this.memberId = typeof msg.memberId === 'number' ? msg.memberId : null;\n }\n\n protected clearIdentity(): void {\n this.memberId = null;\n }\n\n protected sessionRequiresReconnect(\n previous: RealtimeAuthSession | null,\n next: RealtimeAuthSession\n ): boolean {\n return (\n super.sessionRequiresReconnect(previous, next) ||\n previous?.workspaceUuid !== next.workspaceUuid\n );\n }\n\n /**\n * Member id the server authenticated this socket as, or null before\n * `protocol.init` arrives.\n *\n * Channels whose Redis key is workspace-wide can carry events addressed to\n * one member (presence acks, for example). Consumers compare the event's\n * addressee against this so a reply meant for another operator cannot be\n * applied locally.\n */\n getMemberId(): number | null {\n return this.memberId;\n }\n}\n\nconst defaultClient = new WorkspaceRealtimeClient();\n\nexport function initWorkspaceSocket(session: RealtimeAuthSession): void {\n defaultClient.setSession(session);\n}\n\nexport function subscribeWorkspaceChannel(channel: string, listener: ChannelListener): Unsubscribe {\n return defaultClient.subscribe(channel, listener);\n}\n\nexport function onWorkspaceSocketConnection(listener: (connected: boolean) => void): () => void {\n return defaultClient.onConnection(listener);\n}\n\nexport function isWorkspaceSocketConnected(): boolean {\n return defaultClient.isConnected();\n}\n","/**\n * Account WebSocket client — one socket per tab, rooted at the Account.\n *\n * Mirrors `/api/v2/ws/realtime`. No workspace in the URL and none in the\n * session: the login token is the whole identity, and what the socket may see comes\n * from the server's grant map, refreshed there.\n *\n * See `docs/projects/active/account-socket.md`. The point is not a second\n * socket — it is *one*. An operator covering four workspaces holds four\n * `WorkspaceRealtimeClient`s today, which is four connections, four\n * heartbeats, and no place to stand for \"what is happening across my estate\".\n * Workspace-scoped channels are reached here by qualifying their names, so the\n * same channel handlers serve both mounts and the per-workspace socket can be\n * deleted at cutover rather than lived alongside.\n *\n * ```ts\n * const client = new AccountRealtimeClient({ apiUrl, getLoginToken });\n * client.subscribe(workspaceChannel(wid, 'activity'), onInvalidate);\n * client.subscribe(ACCOUNT_ACTIVITY_CHANNEL, onInvalidate);\n * ```\n */\n\nimport { RealtimeSocketClient, type ProtocolInitMessage } from './socket-client';\nimport type { AccountRealtimeSession, ChannelListener, Unsubscribe } from './types';\n\n/** Build the account realtime WebSocket URL from session config. */\nexport function buildAccountWsUrl(session: AccountRealtimeSession): string {\n const isSsl = session.apiUrl.startsWith('https');\n const host = session.apiUrl.replace(/^https?:\\/\\//, '');\n return `${isSsl ? 'wss' : 'ws'}://${host}/api/v2/ws/realtime`;\n}\n\n/**\n * Qualify a workspace-scoped channel name for the account socket.\n *\n * `chat:42:monitor` in workspace `W` is `w/W/chat:42:monitor` here. Exported\n * as a function rather than left to callers' template strings for the reason\n * every channel name constant in this package exists: the server matches\n * exactly, so a typo subscribes successfully to nothing.\n */\nexport function workspaceChannel(workspaceUuid: string, channel: string): string {\n return `w/${workspaceUuid}/${channel}`;\n}\n\nexport class AccountRealtimeClient extends RealtimeSocketClient<AccountRealtimeSession> {\n private accountUuid: string | null = null;\n private workspaceUuids: readonly string[] = [];\n\n protected buildUrl(session: AccountRealtimeSession): string {\n return buildAccountWsUrl(session);\n }\n\n protected readProtocolInit(msg: ProtocolInitMessage): void {\n this.accountUuid = typeof msg.accountUuid === 'string' ? msg.accountUuid : null;\n this.workspaceUuids = Array.isArray(msg.workspaceUuids)\n ? msg.workspaceUuids.filter((value): value is string => typeof value === 'string')\n : [];\n }\n\n protected clearIdentity(): void {\n this.accountUuid = null;\n this.workspaceUuids = [];\n }\n\n /** Account uuid the server authenticated this socket as, or null. */\n getAccountUuid(): string | null {\n return this.accountUuid;\n }\n\n /**\n * Workspaces the server's grant map admitted at `protocol.init`.\n *\n * A **hint for rendering**, never an authorization decision: the server\n * re-checks its own map on every subscribe, and refreshes it on a floor, so\n * this snapshot can be stale in either direction. Use it to decide which\n * panes are worth opening, not which data a viewer may see.\n */\n getWorkspaceUuids(): readonly string[] {\n return this.workspaceUuids;\n }\n}\n\nconst defaultClient = new AccountRealtimeClient();\n\nexport function initAccountSocket(session: AccountRealtimeSession): void {\n defaultClient.setSession(session);\n}\n\nexport function subscribeAccountChannel(channel: string, listener: ChannelListener): Unsubscribe {\n return defaultClient.subscribe(channel, listener);\n}\n\nexport function onAccountSocketConnection(listener: (connected: boolean) => void): () => void {\n return defaultClient.onConnection(listener);\n}\n\nexport function isAccountSocketConnected(): boolean {\n return defaultClient.isConnected();\n}\n","/**\n * Generated by Orval, grouped by scripts/types-codegen/group_generated.ts\n * (group map from emit_openapi.py). Do not edit manually.\n * Group: account\n */\n\nimport type { SessionKind } from './session';\n\n/**\n * One Organization in which the Account is an active Owner.\n */\nexport interface AccountBillingOrganizationRef {\n id: number;\n name?: string | null;\n}\n\n/**\n * Base account response for non-admin endpoints.\n *\n * Note: With Verified Credential Architecture, if email/phone is set,\n * it's verified by construction. The *_verified_at timestamps record when.\n * Credentials are IMMUTABLE once set.\n */\nexport interface AccountResponse {\n id: number;\n uuid: string;\n loggedIn: boolean;\n avatarUrl: string | null;\n avatarIcon: AccountResponseAvatarIcon;\n avatarColor: AccountResponseAvatarColor;\n avatarSource: AccountResponseAvatarSource;\n avatarCustomized: boolean;\n avatarUseGravatar: boolean;\n email: string | null;\n phone: string | null;\n emailVerifiedAt: string | null;\n phoneVerifiedAt: string | null;\n name: string | null;\n createdAt: string;\n isSuperuser: boolean;\n enabled: boolean;\n signupWorkspaceId: number | null;\n tosAccepted: boolean;\n optedOut: boolean;\n locale: string | null;\n timezone: string | null;\n}\n\nexport type AccountResponseAvatarColor = typeof AccountResponseAvatarColor[keyof typeof AccountResponseAvatarColor];\n\n\nexport const AccountResponseAvatarColor = {\n teal: 'teal',\n sky: 'sky',\n blue: 'blue',\n indigo: 'indigo',\n violet: 'violet',\n fuchsia: 'fuchsia',\n slate: 'slate',\n} as const;\n\nexport type AccountResponseAvatarIcon = typeof AccountResponseAvatarIcon[keyof typeof AccountResponseAvatarIcon] | null;\n\n\nexport const AccountResponseAvatarIcon = {\n user: 'user',\n stethoscope: 'stethoscope',\n heart: 'heart',\n shield: 'shield',\n sparkles: 'sparkles',\n star: 'star',\n} as const;\n\nexport type AccountResponseAvatarSource = typeof AccountResponseAvatarSource[keyof typeof AccountResponseAvatarSource];\n\n\nexport const AccountResponseAvatarSource = {\n upload: 'upload',\n custom: 'custom',\n external: 'external',\n gravatar: 'gravatar',\n initials: 'initials',\n} as const;\n\nexport interface AdminAccountMembershipResponse {\n workspaceUuid: string;\n workspaceName: string;\n role: string;\n createdAt: string;\n tosAccepted: boolean;\n memberRoleId: number;\n memberId: number;\n glbLinked: boolean;\n}\n\n/**\n * Response for an account's organization membership.\n */\nexport interface AdminAccountOrgMembershipResponse {\n organizationId: number;\n organizationUuid: string;\n organizationName: string;\n organizationSlug: string;\n organizationLogoUrl: string | null;\n role: string;\n name: string | null;\n accountName: string | null;\n externalId: string | null;\n hasBillingAccess?: boolean;\n createdAt: string;\n updatedAt: string;\n}\n\n/**\n * Detailed account response for admin endpoints including related entities\n */\nexport interface AdminAccountResponse {\n id: number;\n uuid: string;\n loggedIn: boolean;\n avatarUrl: string | null;\n avatarIcon: AdminAccountResponseAvatarIcon;\n avatarColor: AdminAccountResponseAvatarColor;\n avatarSource: AdminAccountResponseAvatarSource;\n avatarCustomized: boolean;\n avatarUseGravatar: boolean;\n email: string | null;\n phone: string | null;\n emailVerifiedAt: string | null;\n phoneVerifiedAt: string | null;\n name: string | null;\n createdAt: string;\n isSuperuser: boolean;\n enabled: boolean;\n signupWorkspaceId: number | null;\n tosAccepted: boolean;\n optedOut: boolean;\n locale: string | null;\n timezone: string | null;\n billingOrganizations?: AccountBillingOrganizationRef[];\n pendingDeletion?: boolean;\n deletionRequestedAt?: string | null;\n}\n\nexport type AdminAccountResponseAvatarColor = typeof AdminAccountResponseAvatarColor[keyof typeof AdminAccountResponseAvatarColor];\n\n\nexport const AdminAccountResponseAvatarColor = {\n teal: 'teal',\n sky: 'sky',\n blue: 'blue',\n indigo: 'indigo',\n violet: 'violet',\n fuchsia: 'fuchsia',\n slate: 'slate',\n} as const;\n\nexport type AdminAccountResponseAvatarIcon = typeof AdminAccountResponseAvatarIcon[keyof typeof AdminAccountResponseAvatarIcon] | null;\n\n\nexport const AdminAccountResponseAvatarIcon = {\n user: 'user',\n stethoscope: 'stethoscope',\n heart: 'heart',\n shield: 'shield',\n sparkles: 'sparkles',\n star: 'star',\n} as const;\n\nexport type AdminAccountResponseAvatarSource = typeof AdminAccountResponseAvatarSource[keyof typeof AdminAccountResponseAvatarSource];\n\n\nexport const AdminAccountResponseAvatarSource = {\n upload: 'upload',\n custom: 'custom',\n external: 'external',\n gravatar: 'gravatar',\n initials: 'initials',\n} as const;\n\n/**\n * Admin request to create a user account.\n *\n * This is for superuser administration only. Accounts are global and not\n * tied to any organization. To add someone to an organization, use\n * workspace invitations instead.\n */\nexport interface AdminCreateAccountRequest {\n email?: string | null;\n phone?: string | null;\n name?: string | null;\n isSuperuser?: boolean;\n enabled?: boolean;\n locale?: string | null;\n timezone?: string | null;\n}\n\n/**\n * Admin request to update user account information.\n *\n * Note: Organization membership/role is managed via OrgMember, not Account fields.\n */\nexport interface AdminUpdateAccountRequest {\n name?: string | null;\n email?: string | null;\n phone?: string | null;\n isSuperuser?: boolean | null;\n enabled?: boolean | null;\n tosAccepted?: boolean | null;\n optedOut?: boolean | null;\n locale?: string | null;\n timezone?: string | null;\n}\n\n/**\n * Response model for when a new API key is created, including the full key.\n */\nexport interface ApiKeyCreatedResponse {\n id: number;\n uuid: string;\n name: string;\n keyPrefix: string;\n createdAt: string;\n expiresAt?: string | null;\n lastUsedAt?: string | null;\n enabled: boolean;\n scopes: string[];\n appId?: number | null;\n dataUseMode?: DataUseMode;\n key: string;\n}\n\n/**\n * Response model for API key information.\n */\nexport interface ApiKeyResponse {\n id: number;\n uuid: string;\n name: string;\n keyPrefix: string;\n createdAt: string;\n expiresAt?: string | null;\n lastUsedAt?: string | null;\n enabled: boolean;\n scopes: string[];\n appId?: number | null;\n dataUseMode?: DataUseMode;\n}\n\n/**\n * Response after canceling a credential change invitation.\n */\nexport interface CancelCredentialChangeInviteResponse {\n success: boolean;\n message: string;\n}\n\n/**\n * Response after canceling a credential change request.\n */\nexport interface CancelCredentialChangeResponse {\n success: boolean;\n message: string;\n}\n\n/**\n * Response after confirming a credential change invitation.\n */\nexport interface CredentialChangeInviteConfirmResponse {\n success: boolean;\n message: string;\n credentialType?: CredentialChangeInviteConfirmResponseCredentialType;\n}\n\nexport type CredentialChangeInviteConfirmResponseCredentialType = typeof CredentialChangeInviteConfirmResponseCredentialType[keyof typeof CredentialChangeInviteConfirmResponseCredentialType] | null;\n\n\nexport const CredentialChangeInviteConfirmResponseCredentialType = {\n email: 'email',\n phone: 'phone',\n} as const;\n\n/**\n * Response with details of a credential change invitation.\n *\n * Used for the confirmation page to show what change is being proposed.\n */\nexport interface CredentialChangeInviteDetailsResponse {\n id: number;\n credentialType: CredentialChangeInviteDetailsResponseCredentialType;\n newValue: string;\n workspaceName: string;\n workspaceUuid: string;\n initiatedByName: string | null;\n createdAt: string;\n expiresAt: string;\n isExpired: boolean;\n isValid: boolean;\n}\n\nexport type CredentialChangeInviteDetailsResponseCredentialType = typeof CredentialChangeInviteDetailsResponseCredentialType[keyof typeof CredentialChangeInviteDetailsResponseCredentialType];\n\n\nexport const CredentialChangeInviteDetailsResponseCredentialType = {\n email: 'email',\n phone: 'phone',\n} as const;\n\n/**\n * Response after creating a credential change invitation.\n */\nexport interface CredentialChangeInviteResponse {\n id: number;\n credentialType: CredentialChangeInviteResponseCredentialType;\n maskedNewValue: string;\n expiresAt: string;\n message: string;\n}\n\nexport type CredentialChangeInviteResponseCredentialType = typeof CredentialChangeInviteResponseCredentialType[keyof typeof CredentialChangeInviteResponseCredentialType];\n\n\nexport const CredentialChangeInviteResponseCredentialType = {\n email: 'email',\n phone: 'phone',\n} as const;\n\n/**\n * Response after requesting a credential change.\n */\nexport interface CredentialChangeRequestResponse {\n id: number;\n credentialType: CredentialChangeRequestResponseCredentialType;\n expiresAt: string;\n message: string;\n}\n\nexport type CredentialChangeRequestResponseCredentialType = typeof CredentialChangeRequestResponseCredentialType[keyof typeof CredentialChangeRequestResponseCredentialType];\n\n\nexport const CredentialChangeRequestResponseCredentialType = {\n email: 'email',\n phone: 'phone',\n} as const;\n\n/**\n * Response after verifying a credential change.\n */\nexport interface CredentialChangeVerifyResponse {\n success: boolean;\n message: string;\n credentialType?: CredentialChangeVerifyResponseCredentialType;\n}\n\nexport type CredentialChangeVerifyResponseCredentialType = typeof CredentialChangeVerifyResponseCredentialType[keyof typeof CredentialChangeVerifyResponseCredentialType] | null;\n\n\nexport const CredentialChangeVerifyResponseCredentialType = {\n email: 'email',\n phone: 'phone',\n} as const;\n\n/**\n * What a *credential* may carry (ADR-18 §1), not what a member may see.\n *\n * This is an axis on the connection, deliberately not a scope: scopes are\n * additive grants for cross-member access, and a member's own data is reached\n * with no scope at all, so no scope value can express \"this channel must not\n * carry PHI\". Computed at mint time and mutable afterwards **only toward**\n * :attr:`NO_PHI` — the same \"narrows, never widens\" doctrine as\n * ``scope_restriction`` and ``Device.enrollment_scope_ceiling``. Widening is a\n * re-consent, i.e. revoke and re-mint under lifted conditions.\n */\nexport type DataUseMode = typeof DataUseMode[keyof typeof DataUseMode];\n\n\nexport const DataUseMode = {\n unrestricted: 'unrestricted',\n no_phi: 'no_phi',\n} as const;\n\nexport interface LoginResponse {\n token: string;\n accountId: number;\n accountName?: string | null;\n accountUuid?: string | null;\n requiresTwoFactor?: boolean | null;\n availableTwoFactorMethods?: unknown[] | null;\n sessionKind?: SessionKind | 'widget' | null;\n expiresAt?: string | null;\n}\n\n/**\n * Response for a pending credential change invitation.\n */\nexport interface PendingCredentialChangeInviteResponse {\n id: number;\n credentialType: PendingCredentialChangeInviteResponseCredentialType;\n maskedNewValue: string;\n workspaceName: string;\n initiatedByName: string | null;\n createdAt: string;\n expiresAt: string;\n isExpired: boolean;\n status: string;\n}\n\nexport type PendingCredentialChangeInviteResponseCredentialType = typeof PendingCredentialChangeInviteResponseCredentialType[keyof typeof PendingCredentialChangeInviteResponseCredentialType];\n\n\nexport const PendingCredentialChangeInviteResponseCredentialType = {\n email: 'email',\n phone: 'phone',\n} as const;\n\n/**\n * Response for a pending credential change request.\n */\nexport interface PendingCredentialChangeResponse {\n id: number;\n credentialType: PendingCredentialChangeResponseCredentialType;\n maskedNewValue: string;\n createdAt: string;\n expiresAt: string;\n isExpired: boolean;\n attempts: number;\n}\n\nexport type PendingCredentialChangeResponseCredentialType = typeof PendingCredentialChangeResponseCredentialType[keyof typeof PendingCredentialChangeResponseCredentialType];\n\n\nexport const PendingCredentialChangeResponseCredentialType = {\n email: 'email',\n phone: 'phone',\n} as const;\n\n/**\n * Response model for recovery codes\n */\nexport interface RecoveryCodeResponse {\n /** List of recovery codes (only shown once) */\n codes: string[];\n /** When the codes were generated */\n generatedAt: string;\n warning?: string;\n}\n\nexport interface SendLoginCodeResponse {\n success: boolean;\n message?: string | null;\n}\n\n/**\n * Response for TOTP setup initiation\n */\nexport interface TOTPSetupResponse {\n /** Session ID for completing setup */\n setupId: string;\n /** Base32 encoded TOTP secret */\n secret: string;\n /** QR code URL for easy setup */\n qrCodeUrl: string;\n /** Manual entry key for authenticator apps */\n manualEntryKey: string;\n /** Issuer name for TOTP */\n issuer: string;\n}\n\n/**\n * Response model for 2FA method details\n */\nexport interface TwoFactorMethodResponse {\n id: number;\n methodType: string;\n name: string;\n enabled: boolean;\n createdAt: string;\n lastUsedAt?: string | null;\n}\n\n/**\n * Generic response for 2FA operations\n */\nexport interface TwoFactorOperationResponse {\n /** Whether the operation was successful */\n success: boolean;\n /** Human-readable message */\n message: string;\n /** ID of the affected 2FA method */\n methodId?: number | null;\n}\n\n/**\n * Response for overall 2FA status\n */\nexport interface TwoFactorStatusResponse {\n /** Whether any 2FA method is enabled */\n enabled: boolean;\n /** List of configured 2FA methods */\n methods: TwoFactorMethodResponse[];\n /** Number of unused recovery codes */\n recoveryCodesCount: number;\n /** When recovery codes were last generated */\n lastRecoveryCodesGenerated?: string | null;\n}\n\n/**\n * Update user information.\n *\n * Note: email and phone cannot be changed via this endpoint.\n * Use the credential change flow instead:\n * - POST /api/v2/account/request-credential-change\n * - POST /api/v2/account/verify-credential-change\n */\nexport interface UpdateAccountRequest {\n name?: string | null;\n tosAccepted?: boolean | null;\n optedOut?: boolean | null;\n locale?: string | null;\n timezone?: string | null;\n}\n\n/**\n * Authenticator selection criteria in WebAuthn creation options.\n */\nexport interface WebAuthnAuthenticatorSelection {\n userVerification: WebAuthnAuthenticatorSelectionUserVerification;\n residentKey: WebAuthnAuthenticatorSelectionResidentKey;\n}\n\nexport type WebAuthnAuthenticatorSelectionResidentKey = typeof WebAuthnAuthenticatorSelectionResidentKey[keyof typeof WebAuthnAuthenticatorSelectionResidentKey];\n\n\nexport const WebAuthnAuthenticatorSelectionResidentKey = {\n required: 'required',\n preferred: 'preferred',\n discouraged: 'discouraged',\n} as const;\n\nexport type WebAuthnAuthenticatorSelectionUserVerification = typeof WebAuthnAuthenticatorSelectionUserVerification[keyof typeof WebAuthnAuthenticatorSelectionUserVerification];\n\n\nexport const WebAuthnAuthenticatorSelectionUserVerification = {\n required: 'required',\n preferred: 'preferred',\n discouraged: 'discouraged',\n} as const;\n\n/**\n * Credential creation options passed to navigator.credentials.create().\n */\nexport interface WebAuthnCredentialCreationOptions {\n challenge: string;\n rp: WebAuthnRelyingParty;\n user: WebAuthnUserEntity;\n pubKeyCredParams: WebAuthnPubKeyCredParam[];\n excludeCredentials: WebAuthnCredentialDescriptor[];\n authenticatorSelection: WebAuthnAuthenticatorSelection;\n timeout: number;\n attestation: WebAuthnCredentialCreationOptionsAttestation;\n}\n\nexport type WebAuthnCredentialCreationOptionsAttestation = typeof WebAuthnCredentialCreationOptionsAttestation[keyof typeof WebAuthnCredentialCreationOptionsAttestation];\n\n\nexport const WebAuthnCredentialCreationOptionsAttestation = {\n none: 'none',\n indirect: 'indirect',\n direct: 'direct',\n enterprise: 'enterprise',\n} as const;\n\n/**\n * Descriptor for a registered WebAuthn credential.\n */\nexport interface WebAuthnCredentialDescriptor {\n id: string;\n type: 'public-key';\n}\n\n/**\n * A public-key credential parameter the authenticator may create.\n */\nexport interface WebAuthnPubKeyCredParam {\n alg: number;\n type: 'public-key';\n}\n\n/**\n * Response for WebAuthn registration initiation\n */\nexport interface WebAuthnRegistrationResponse {\n /** Session ID for completing setup */\n setupId: string;\n /** WebAuthn credential creation options */\n credentialCreationOptions: WebAuthnCredentialCreationOptions;\n}\n\n/**\n * Relying party entity in WebAuthn creation options.\n */\nexport interface WebAuthnRelyingParty {\n name: string;\n id: string;\n}\n\n/**\n * User entity in WebAuthn creation options.\n */\nexport interface WebAuthnUserEntity {\n /** Base64url-encoded user handle */\n id: string;\n name: string;\n displayName: string;\n}\n","import {\n AccountResponseAvatarColor,\n AccountResponseAvatarIcon,\n type AccountResponseAvatarColor as AvatarColor,\n type AccountResponseAvatarIcon as AvatarIcon,\n} from '../types/generated/account';\nimport type { ChannelEvent } from './types';\n\nexport type EditorCollaborationResource = 'workflow' | 'journey';\n\n/**\n * Stable server identities, not the transient React Flow node keys that a clean\n * editor replacement can regenerate. Workflow Tasks and notes use numeric ids;\n * Journey steps/routes/endings use their durable UUIDs.\n */\nexport type EditorCollaborationItemKind =\n | 'workflow'\n | 'task'\n | 'note'\n | 'journey'\n | 'step'\n | 'route'\n | 'ending'\n | 'enrollment'\n | 'goal'\n | 'connection'\n | 'wait'\n | 'action';\n\n/**\n * Journey item ids: `step`, `route`, `ending`, `enrollment` and `goal` use the\n * object's own UUID. A `wait` is the wait before a step, so its id is that\n * step's UUID. An `action` is one EventRule on a step or Ending, so its id is\n * that EventRule's UUID.\n */\nexport interface EditorCollaborationItem {\n kind: EditorCollaborationItemKind;\n id: number | string;\n}\n\n/** A person with the editor open, or the workspace Manager acting for one. */\nexport type EditorCollaboratorKind = 'member' | 'manager';\n\nexport interface EditorCollaborator {\n /** `manager` draws the Manager mark; its `memberId` is the person it acts for. */\n kind: EditorCollaboratorKind;\n memberId: number;\n name: string | null;\n /** The image to draw, if any; null means draw the icon or the initials. */\n avatarUrl: string | null;\n /** Null draws the Member's initials. */\n avatarIcon: AvatarIcon;\n /** Null on a server that predates the field; the client derives one. */\n avatarColor: AvatarColor | null;\n}\n\nexport interface CollaboratorsChangedEvent {\n type: 'collaborators.changed';\n collaborators: EditorCollaborator[];\n}\n\nexport interface EditorUpdatedEvent {\n type: 'editor.updated';\n editor: EditorCollaborator;\n items: EditorCollaborationItem[];\n /** One mounted browser editor, distinct from the Member using other tabs. */\n originId: string;\n updatedAt: string;\n}\n\nexport type EditorCollaborationEvent = CollaboratorsChangedEvent | EditorUpdatedEvent;\n\nexport function editorCollaborationChannel(\n resource: EditorCollaborationResource,\n resourceId: number\n): string {\n return `collaboration:${resource}:${resourceId}`;\n}\n\nexport function editorCollaborationItemKey(item: EditorCollaborationItem): string {\n return `${item.kind}:${String(item.id)}`;\n}\n\nfunction parseCollaborator(value: unknown): EditorCollaborator | null {\n if (typeof value !== 'object' || value === null) return null;\n const record = value as Record<string, unknown>;\n if (typeof record.memberId !== 'number' || !Number.isInteger(record.memberId)) return null;\n const name = record.name;\n const avatarUrl = record.avatarUrl;\n const avatarIcon = record.avatarIcon;\n const avatarColor = record.avatarColor;\n return {\n kind: record.kind === 'manager' ? 'manager' : 'member',\n memberId: record.memberId,\n name: typeof name === 'string' ? name : null,\n avatarUrl: typeof avatarUrl === 'string' ? avatarUrl : null,\n avatarIcon:\n typeof avatarIcon === 'string' && avatarIcon in AccountResponseAvatarIcon\n ? (avatarIcon as AvatarIcon)\n : null,\n avatarColor:\n typeof avatarColor === 'string' && avatarColor in AccountResponseAvatarColor\n ? (avatarColor as AvatarColor)\n : null,\n };\n}\n\nfunction parseItem(value: unknown): EditorCollaborationItem | null {\n if (typeof value !== 'object' || value === null) return null;\n const item = value as Record<string, unknown>;\n const kind = item.kind;\n const id = item.id;\n const validKind =\n kind === 'workflow' ||\n kind === 'task' ||\n kind === 'note' ||\n kind === 'journey' ||\n kind === 'step' ||\n kind === 'route' ||\n kind === 'ending' ||\n kind === 'enrollment' ||\n kind === 'goal' ||\n kind === 'connection' ||\n kind === 'wait' ||\n kind === 'action';\n if (!validKind) return null;\n if (typeof id !== 'number' && typeof id !== 'string') return null;\n if (!String(id)) return null;\n return { kind, id };\n}\n\n/** Narrow the untyped shared-socket envelope before it changes editor state. */\nexport function parseEditorCollaborationEvent(\n event: ChannelEvent\n): EditorCollaborationEvent | null {\n const data = (event as { data?: unknown }).data;\n if (typeof data !== 'object' || data === null) return null;\n const record = data as Record<string, unknown>;\n if (event.type === 'collaborators.changed') {\n if (!Array.isArray(record.collaborators)) return null;\n const collaborators = record.collaborators.flatMap((value) => {\n const parsed = parseCollaborator(value);\n return parsed ? [parsed] : [];\n });\n return { type: event.type, collaborators };\n }\n if (event.type === 'editor.updated') {\n const editor = parseCollaborator(record.editor);\n const rawItems = record.items;\n if (\n !editor ||\n !Array.isArray(rawItems) ||\n rawItems.length === 0 ||\n rawItems.length > 100 ||\n typeof record.originId !== 'string' ||\n typeof record.updatedAt !== 'string'\n ) {\n return null;\n }\n const items = rawItems.map(parseItem);\n if (items.some((item) => item === null)) return null;\n return {\n type: event.type,\n editor,\n items: items as EditorCollaborationItem[],\n originId: record.originId,\n updatedAt: record.updatedAt,\n };\n }\n return null;\n}\n","/**\n * Human operator session WebSocket client.\n *\n * Connects to `/api/v2/w/{wid}/operator/chats/{chatId}/session-ws` — AGUI\n * events, bidirectional PCM, and call control. No AI inference.\n */\n\nimport {\n base64ToFloat32Array,\n float32ArrayToBase64,\n SERVER_SAMPLE_RATE,\n TARGET_SAMPLE_RATE,\n} from '../audio/pcm';\nimport { mintLoginToken } from './login-token';\nimport {\n parseOrgAuthRequirement,\n type ChannelEvent,\n type OperatorCallPhase,\n type OperatorSessionState,\n type OrgAuthRequirement,\n type RealtimeAuthSession,\n} from './types';\n\nconst CONNECT_SUPERSEDED = 'Operator session connect superseded';\n\nexport interface OperatorSessionHandlers {\n onSessionStateChange?: (state: OperatorSessionState) => void;\n onCallPhaseChange?: (phase: OperatorCallPhase) => void;\n onAguiEvent?: (event: ChannelEvent) => void;\n onError?: (message: string) => void;\n /** The session was refused for want of an org session; the step-up path takes it from here. */\n onOrgAuthRequired?: (requirement: OrgAuthRequirement) => void;\n /**\n * Fired once when a logged-in session ends without `disconnect()`: the server\n * ended it (e.g. callee hung up, with the server's reason) or its socket closed\n * with no such notice (reason `'disconnect'`).\n */\n onSessionClosed?: (reason?: string) => void;\n}\n\nexport class OperatorSessionClient {\n private ws: WebSocket | null = null;\n private audioContext: AudioContext | null = null;\n private mediaStream: MediaStream | null = null;\n private processor: ScriptProcessorNode | null = null;\n private sessionState: OperatorSessionState = 'idle';\n private callPhase: OperatorCallPhase = 'idle';\n private nextPlaybackTime = 0;\n private playbackSources: AudioBufferSourceNode[] = [];\n private micActive = false;\n private onHold = false;\n private muted = false;\n private receivedRemoteAudio = false;\n private heartbeatTimer: ReturnType<typeof setInterval> | null = null;\n private sessionCloseNotified = false;\n private cancelPendingLogin: (() => void) | null = null;\n /** Bumped by every connect and disconnect; a stale connect stops at its next await. */\n private connectGeneration = 0;\n\n constructor(private handlers: OperatorSessionHandlers = {}) {}\n\n getSessionState(): OperatorSessionState {\n return this.sessionState;\n }\n\n getCallPhase(): OperatorCallPhase {\n return this.callPhase;\n }\n\n private setSessionState(next: OperatorSessionState): void {\n this.sessionState = next;\n this.handlers.onSessionStateChange?.(next);\n }\n\n private setCallPhase(next: OperatorCallPhase): void {\n this.callPhase = next;\n this.handlers.onCallPhaseChange?.(next);\n }\n\n private notifySessionClosed(reason?: string): void {\n if (this.sessionCloseNotified) return;\n this.sessionCloseNotified = true;\n this.handlers.onSessionClosed?.(reason);\n }\n\n async connect(session: RealtimeAuthSession, chatId: number): Promise<void> {\n if (typeof window === 'undefined' || typeof WebSocket === 'undefined') {\n throw new Error('Operator session WebSocket is not available in this environment');\n }\n\n const generation = ++this.connectGeneration;\n await this.closeSession();\n if (generation !== this.connectGeneration) {\n throw new Error(CONNECT_SUPERSEDED);\n }\n this.sessionCloseNotified = false;\n this.setSessionState('connecting');\n this.setCallPhase('connecting');\n\n const isSsl = session.apiUrl.startsWith('https');\n const host = session.apiUrl.replace(/^https?:\\/\\//, '');\n const wsUrl = `${isSsl ? 'wss' : 'ws'}://${host}/api/v2/w/${session.workspaceUuid}/operator/chats/${chatId}/session-ws`;\n\n // One token per connect: a browser's is single-use and expires in seconds.\n const token = await mintLoginToken(session.getLoginToken);\n if (generation !== this.connectGeneration) {\n throw new Error(CONNECT_SUPERSEDED);\n }\n if (!token) {\n this.setSessionState('error');\n this.setCallPhase('idle');\n throw new Error('Realtime login token unavailable');\n }\n\n await new Promise<void>((resolve, reject) => {\n const ws = new WebSocket(wsUrl);\n this.ws = ws;\n let loginSettled = false;\n let loggedIn = false;\n const settleLogin = (error?: Error) => {\n if (loginSettled) return;\n loginSettled = true;\n if (this.cancelPendingLogin === cancelLogin) this.cancelPendingLogin = null;\n if (error) {\n reject(error);\n } else {\n loggedIn = true;\n resolve();\n }\n };\n const cancelLogin = () => settleLogin(new Error(CONNECT_SUPERSEDED));\n this.cancelPendingLogin = cancelLogin;\n\n ws.onopen = () => {\n if (this.ws !== ws) return;\n ws.send(JSON.stringify({ type: 'login', token }));\n };\n\n ws.onmessage = (event) => {\n if (this.ws !== ws) return;\n try {\n const msg = JSON.parse(String(event.data)) as {\n type?: string;\n name?: string;\n value?: Record<string, unknown>;\n message?: string;\n code?: string;\n event?: ChannelEvent;\n };\n this.handleMessage(msg, () => settleLogin(), settleLogin);\n } catch {\n /* ignore malformed frames */\n }\n };\n\n ws.onerror = () => {\n if (this.ws !== ws) return;\n const message = 'Operator session WebSocket error';\n const wasConnecting = this.sessionState === 'connecting';\n this.setSessionState('error');\n if (wasConnecting) {\n this.setCallPhase('idle');\n settleLogin(new Error(message));\n } else {\n this.setCallPhase('failed');\n this.handlers.onError?.(message);\n }\n };\n\n ws.onclose = () => {\n if (this.ws !== ws) {\n settleLogin(new Error(CONNECT_SUPERSEDED));\n return;\n }\n this.ws = null;\n this.clearHeartbeat();\n this.stopMicrophone();\n this.stopPlayback();\n this.setSessionState('idle');\n this.setCallPhase('idle');\n if (loggedIn) {\n this.notifySessionClosed('disconnect');\n } else {\n settleLogin(new Error('Operator session closed before login'));\n }\n };\n });\n }\n\n private handleMessage(\n msg: {\n type?: string;\n name?: string;\n value?: Record<string, unknown>;\n message?: string;\n code?: string;\n event?: ChannelEvent;\n },\n resolveLogin: () => void,\n rejectLogin: (err: Error) => void\n ): void {\n if (msg.type === 'RUN_ERROR' || msg.type === 'error') {\n const message = msg.message ?? 'Operator session error';\n if (msg.code === 'org_auth_required') {\n const requirement = parseOrgAuthRequirement(msg);\n if (requirement) this.handlers.onOrgAuthRequired?.(requirement);\n }\n if (this.sessionState === 'connecting') {\n this.setSessionState('error');\n rejectLogin(new Error(message));\n } else {\n this.setCallPhase('failed');\n this.handlers.onError?.(message);\n }\n return;\n }\n\n if (msg.type === 'protocol.init' && this.sessionState === 'connecting') {\n return;\n }\n\n if (msg.type === 'CUSTOM' && msg.name === 'operator.session_ready') {\n this.setSessionState('connected');\n this.setCallPhase('ready');\n this.startHeartbeat();\n resolveLogin();\n return;\n }\n\n if (msg.type === 'event' && msg.event) {\n if (this.handleRemoteVoiceAudio(msg.event)) {\n return;\n }\n this.handlers.onAguiEvent?.(msg.event);\n return;\n }\n\n if (msg.type === 'CUSTOM' && msg.name === 'operator.call.started') {\n this.receivedRemoteAudio = false;\n this.setCallPhase('dialing');\n return;\n }\n\n if (msg.type === 'CUSTOM' && msg.name === 'operator.call.hold_failed') {\n if (this.callPhase === 'onHold') {\n this.handlers.onError?.('Hold music is unavailable. The call is still on hold.');\n }\n return;\n }\n\n if (msg.type === 'CUSTOM' && msg.name === 'operator.call.ended') {\n this.onHold = false;\n this.muted = false;\n this.receivedRemoteAudio = false;\n this.stopMicrophone();\n this.stopPlayback();\n const endSession = msg.value?.end_session === true;\n const reason = typeof msg.value?.reason === 'string' ? msg.value.reason : undefined;\n if (endSession) {\n this.setCallPhase('idle');\n this.notifySessionClosed(reason ?? 'peer_hangup');\n } else {\n this.setCallPhase('ready');\n }\n return;\n }\n }\n\n /** Play callee PCM from wrapped chat-stream events; returns true if handled. */\n private handleRemoteVoiceAudio(event: ChannelEvent): boolean {\n if (event.type !== 'CUSTOM' || event.name !== 'voice.audio') {\n return false;\n }\n if (this.onHold) return true;\n\n const value = event.value;\n if (!value || typeof value !== 'object') return true;\n\n const data = (value as Record<string, unknown>).data;\n if (typeof data !== 'string' || !data) return true;\n\n if (\n !this.receivedRemoteAudio &&\n (this.callPhase === 'dialing' || this.callPhase === 'live')\n ) {\n this.receivedRemoteAudio = true;\n this.setCallPhase('live');\n }\n void this.playPcm16(base64ToFloat32Array(data));\n return true;\n }\n\n private startHeartbeat(): void {\n this.clearHeartbeat();\n this.heartbeatTimer = setInterval(() => {\n if (this.ws?.readyState === WebSocket.OPEN) {\n this.ws.send(JSON.stringify({ type: 'heartbeat' }));\n }\n }, 30_000);\n }\n\n private clearHeartbeat(): void {\n if (this.heartbeatTimer) {\n clearInterval(this.heartbeatTimer);\n this.heartbeatTimer = null;\n }\n }\n\n private sendCustom(name: string, value: Record<string, unknown> = {}): void {\n if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {\n throw new Error('Operator session WebSocket is not connected');\n }\n this.ws.send(JSON.stringify({ type: 'CUSTOM', name, value }));\n }\n\n async placeCall(memberId: number): Promise<void> {\n if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {\n throw new Error('Operator session WebSocket is not connected');\n }\n if (this.sessionState !== 'connected') {\n throw new Error('Operator session is not ready');\n }\n await this.startMicrophone();\n this.sendCustom('operator.call.place', { member_id: memberId });\n }\n\n /**\n * Answer an inbound operator call the caller has already been routed to.\n *\n * Symmetric with {@link placeCall} but for the inbound direction: instead of\n * dialing an outbound leg it tells the backend to bridge the already-ringing\n * caller to this operator session. The backend (see\n * `lib/operator_session_handler.py::_answer_inbound_call`) registers the\n * audio bridge, marks the ring state `answered`, and replies with\n * `operator.call.started` — after which callee PCM arrives as `voice.audio`\n * events (played via {@link playPcm16}) and mic audio streams the other way,\n * exactly like an outbound call.\n *\n * Must be called once the session is ready (state `connected`). Starts the\n * microphone before sending so the operator's audio is flowing the instant\n * the bridge registers.\n */\n async answerCall(interactionId: string, answerToken: string): Promise<void> {\n if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {\n throw new Error('Operator session WebSocket is not connected');\n }\n if (this.sessionState !== 'connected') {\n throw new Error('Operator session is not ready');\n }\n await this.startMicrophone();\n this.sendCustom('operator.call.answer', {\n interaction_id: interactionId,\n answer_token: answerToken,\n });\n }\n\n /**\n * Join a live, escalated voice call on this chat.\n *\n * Unlike {@link answerCall} (a waiting caller whose ring poll redirects the\n * PSTN leg), the caller here is already on the AI media stream with the AI\n * paused for an escalation. The backend\n * (`lib/operator_session_handler.py::_join_live_call`) authorizes, attaches\n * this session as bridge side \"a\", and re-points the live caller leg onto\n * the bridge over Twilio REST — replacing the AI stream with the human one.\n * The server then sends `operator.call.started`, after which audio flows\n * exactly like an answered call.\n *\n * The chat id is carried by the session URL, so no argument is needed. Must\n * be called once the session is ready (state `connected`); starts the\n * microphone first so operator audio flows the instant the bridge attaches.\n */\n async joinCall(): Promise<void> {\n if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {\n throw new Error('Operator session WebSocket is not connected');\n }\n if (this.sessionState !== 'connected') {\n throw new Error('Operator session is not ready');\n }\n await this.startMicrophone();\n this.sendCustom('operator.call.join');\n }\n\n /**\n * Mute or unmute the operator's outbound microphone. Muting gates mic frames\n * locally (the caller stops hearing the operator) while callee audio keeps\n * playing — distinct from {@link setHold}, which is a two-way pause the\n * backend is told about. Purely client-side; no server round-trip.\n */\n setMuted(muted: boolean): void {\n this.muted = muted;\n }\n\n isMuted(): boolean {\n return this.muted;\n }\n\n hangUp(): void {\n try {\n this.sendCustom('operator.call.hangup');\n } catch {\n /* socket already closed */\n }\n this.onHold = false;\n this.receivedRemoteAudio = false;\n }\n\n forwardCall(phoneNumber: string): void {\n this.receivedRemoteAudio = false;\n this.setCallPhase('dialing');\n this.sendCustom('operator.call.forward', { phone_number: phoneNumber });\n }\n\n setHold(onHold: boolean): void {\n this.onHold = onHold;\n this.sendCustom('operator.call.hold', { on_hold: onHold });\n if (this.callPhase === 'live' || this.callPhase === 'onHold') {\n this.setCallPhase(onHold ? 'onHold' : 'live');\n }\n if (onHold) {\n this.stopPlayback();\n }\n }\n\n async startMicrophone(): Promise<void> {\n if (typeof window === 'undefined') return;\n if (!navigator.mediaDevices?.getUserMedia) {\n throw new Error('Microphone not available in this browser');\n }\n if (this.micActive) return;\n\n const ws = this.ws;\n const mediaStream = await navigator.mediaDevices.getUserMedia({\n audio: {\n echoCancellation: true,\n noiseSuppression: true,\n autoGainControl: true,\n },\n });\n if (this.ws !== ws) {\n for (const track of mediaStream.getTracks()) track.stop();\n throw new Error('Operator session WebSocket is not connected');\n }\n this.mediaStream = mediaStream;\n\n let audioContext: AudioContext | null = null;\n let processor: ScriptProcessorNode | null = null;\n try {\n const Ctx =\n window.AudioContext ??\n (window as unknown as { webkitAudioContext?: typeof AudioContext }).webkitAudioContext;\n if (!Ctx) throw new Error('Web Audio not supported');\n\n audioContext = new Ctx();\n this.audioContext = audioContext;\n if (audioContext.state === 'suspended') {\n await audioContext.resume();\n }\n if (this.ws !== ws) throw new Error('Operator session WebSocket is not connected');\n\n const source = audioContext.createMediaStreamSource(mediaStream);\n processor = audioContext.createScriptProcessor(4096, 1, 1);\n this.processor = processor;\n\n processor.onaudioprocess = (event) => {\n if (!this.ws || this.ws.readyState !== WebSocket.OPEN) return;\n if (this.onHold) return;\n if (this.muted) return;\n if (\n this.callPhase !== 'dialing' &&\n this.callPhase !== 'live' &&\n this.callPhase !== 'onHold'\n ) {\n return;\n }\n\n const input = event.inputBuffer.getChannelData(0);\n const copy = new Float32Array(input.length);\n copy.set(input);\n\n const sampleRate = this.audioContext?.sampleRate ?? TARGET_SAMPLE_RATE;\n let pcm = copy;\n if (sampleRate !== TARGET_SAMPLE_RATE) {\n const ratio = sampleRate / TARGET_SAMPLE_RATE;\n const newLen = Math.floor(copy.length / ratio);\n const down = new Float32Array(newLen);\n for (let i = 0; i < newLen; i += 1) {\n down[i] = copy[Math.floor(i * ratio)];\n }\n pcm = down;\n }\n\n this.ws.send(\n JSON.stringify({\n type: 'CUSTOM',\n name: 'voice.audio',\n value: {\n data: float32ArrayToBase64(pcm),\n format: 'pcm16',\n sample_rate: TARGET_SAMPLE_RATE,\n },\n })\n );\n };\n\n source.connect(processor);\n processor.connect(audioContext.destination);\n } catch (err) {\n if (processor && this.processor === processor) {\n processor.disconnect();\n this.processor = null;\n }\n for (const track of mediaStream.getTracks()) track.stop();\n if (this.mediaStream === mediaStream) this.mediaStream = null;\n if (audioContext && this.audioContext === audioContext) {\n this.audioContext = null;\n void audioContext.close().catch(() => undefined);\n }\n throw err;\n }\n this.micActive = true;\n }\n\n stopMicrophone(): void {\n this.processor?.disconnect();\n this.processor = null;\n for (const track of this.mediaStream?.getTracks() ?? []) {\n track.stop();\n }\n this.mediaStream = null;\n this.micActive = false;\n }\n\n private async playPcm16(samples: Float32Array): Promise<void> {\n if (typeof window === 'undefined') return;\n\n const Ctx =\n window.AudioContext ??\n (window as unknown as { webkitAudioContext?: typeof AudioContext }).webkitAudioContext;\n if (!Ctx) return;\n\n if (!this.audioContext || this.audioContext.state === 'closed') {\n this.audioContext = new Ctx();\n }\n if (this.audioContext.state === 'suspended') {\n await this.audioContext.resume();\n }\n\n const buffer = this.audioContext.createBuffer(1, samples.length, SERVER_SAMPLE_RATE);\n buffer.copyToChannel(new Float32Array(samples), 0);\n\n const source = this.audioContext.createBufferSource();\n source.buffer = buffer;\n source.connect(this.audioContext.destination);\n\n const now = this.audioContext.currentTime;\n const startAt = this.nextPlaybackTime < now + 0.02 ? now + 0.02 : this.nextPlaybackTime;\n source.start(startAt);\n this.nextPlaybackTime = startAt + buffer.duration;\n this.playbackSources.push(source);\n source.onended = () => {\n const idx = this.playbackSources.indexOf(source);\n if (idx >= 0) this.playbackSources.splice(idx, 1);\n };\n }\n\n private stopPlayback(): void {\n for (const src of this.playbackSources) {\n try {\n src.stop();\n } catch {\n /* already stopped */\n }\n }\n this.playbackSources = [];\n this.nextPlaybackTime = 0;\n }\n\n async disconnect(): Promise<void> {\n this.connectGeneration += 1;\n await this.closeSession();\n }\n\n private async closeSession(): Promise<void> {\n const cancelLogin = this.cancelPendingLogin;\n this.cancelPendingLogin = null;\n cancelLogin?.();\n if (\n this.callPhase === 'dialing' ||\n this.callPhase === 'live' ||\n this.callPhase === 'onHold'\n ) {\n this.hangUp();\n }\n this.clearHeartbeat();\n this.stopMicrophone();\n this.stopPlayback();\n const ws = this.ws;\n this.ws = null;\n ws?.close();\n if (this.audioContext && this.audioContext.state !== 'closed') {\n await this.audioContext.close().catch(() => undefined);\n }\n this.audioContext = null;\n this.onHold = false;\n this.muted = false;\n this.receivedRemoteAudio = false;\n this.setSessionState('idle');\n this.setCallPhase('idle');\n }\n}\n"],"mappings":";;;;;;;;AA6DO,SAAS,wBAAwB,OAA2C;AAChF,MAAI,OAAO,UAAU,YAAY,UAAU,KAAM,QAAO;AACxD,QAAM,OAAO;AACb,QAAM;AAAA,IACH,gBAAgB;AAAA,IAChB,UAAU;AAAA,IACV,UAAU;AAAA,IACV;AAAA,EACH,IAAI;AACJ,MACG,OAAO,kBAAkB,YACzB,OAAO,YAAY,YACnB,OAAO,YAAY,YACnB,CAAC,iBACD,CAAC,SACF;AACC,WAAO;AAAA,EACV;AACA,SAAO;AAAA,IACJ;AAAA,IACA;AAAA,IACA;AAAA,IACA,aAAa,gBAAgB,QAAQ,QAAQ;AAAA,EAChD;AACH;AAGO,SAAS,yBAAyB,OAAsC;AAC5E,MAAI,CAAC,MAAM,QAAQ,KAAK,EAAG,QAAO,CAAC;AACnC,SAAO,MAAM,QAAQ,CAAC,SAAS;AAC5B,UAAM,SAAS,wBAAwB,IAAI;AAC3C,WAAO,SAAS,CAAC,MAAM,IAAI,CAAC;AAAA,EAC/B,CAAC;AACJ;AAsBO,SAAS,kBAAkB,OAAmC;AAClE,SAAO,UAAU,aAAa,UAAU,UAAU,UAAU;AAC/D;AAgBO,IAAM,mBAAmB;AACzB,IAAM,0BAA0B;AAUhC,IAAM,2BAA2B;AAoBjC,IAAM,2BAA2B;AAGjC,IAAM,mBAAmB;AAuBzB,SAAS,uBAAuB,OAAyD;AAC7F,MAAI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