@arbidocs/react 0.5.184 → 0.5.186

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.
@@ -103,6 +103,13 @@ async function startDmCall(arbi, peer) {
103
103
  }
104
104
  return startChatCall(arbi, { chatExtId, title: peer.name ?? null, ring: [peer] });
105
105
  }
106
+ function startWorkspaceCall(arbi, opts) {
107
+ return startCall(arbi, {
108
+ context: { workspaceExtId: opts.workspaceExtId },
109
+ title: opts.title,
110
+ ring: opts.ring
111
+ });
112
+ }
106
113
  function startContactsCall(arbi, opts) {
107
114
  return startCall(arbi, { context: {}, title: opts.title, ring: opts.ring, invites: opts.invites });
108
115
  }
@@ -221,6 +228,7 @@ export {
221
228
  startChatCall,
222
229
  startContactsCall,
223
230
  startDmCall,
224
- startThreadCall
231
+ startThreadCall,
232
+ startWorkspaceCall
225
233
  };
226
234
  //# sourceMappingURL=actions.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/calls/actions.ts"],
4
- "sourcesContent": ["/**\n * Call actions \u2014 usable outside React (buttons, notification actions, the WS\n * ringer). One call system: every call has a random key K made in the\n * creator's browser (see `@arbidocs/client` call-keys):\n *\n * - start (thread / chat / contacts): generate K, create the call with K\n * sealed to ourselves and to the people picked, show the pre-join; on\n * join, ring them. Nobody else is rung: a thread call rings only the\n * members picked, never the whole workspace. Unregistered contacts get a\n * personal invite link by e-mail instead (register, then straight into the\n * call \u2014 there are no anonymous guests);\n * - accept a ring: open K from the ring's sealed blob and join at once;\n * - open a call (link / calendar event / notification): K from the link fragment,\n * else our sealed copy on the server.\n *\n * A thread call is get-or-create: if the thread already has a running call we\n * hold the key for, we join that one instead of starting another.\n */\n\nimport { buildCallLink, type CallPeer } from '@arbidocs/client'\nimport { CallApiError, type Arbi, type calls } from '@arbidocs/sdk/browser'\nimport { notify } from '../notifications/notify-store'\nimport {\n callSession,\n DEFAULT_JOIN_CHOICES,\n type ActiveCall,\n type IncomingCall,\n type JoinChoices,\n} from './session'\n\nexport type { CallPeer }\n\n/** `https://<host>/call/<id>#k=\u2026&v=\u2026` \u2014 the shareable link. */\nexport function callLink(callExtId: string, key: Uint8Array, linkVersion: number): string {\n return buildCallLink(window.location.origin, callExtId, key, linkVersion)\n}\n\nfunction alreadyInCall(callExtId?: string): boolean {\n const active = callSession.getState().active\n if (!active || active.callExtId === callExtId) return false\n notify.warning('You are already in a call. Leave it first.')\n return true\n}\n\nfunction fail(err: unknown, what = 'start the call') {\n console.error(`[calls] failed to ${what}`, err)\n const message = err instanceof Error ? err.message : 'Unknown error'\n notify.error(`Could not ${what}: ${message}`)\n}\n\n/** Where a call belongs, for the active call (and the in-call chat). */\nfunction callContext(\n call: Pick<\n calls.CallResponse,\n | 'chat_ext_id'\n | 'log_conversation_ext_id'\n | 'meeting_conversation_ext_id'\n | 'locked_workspace_ext_id'\n >\n): Pick<\n ActiveCall,\n 'chatExtId' | 'logConversationExtId' | 'meetingConversationExtId' | 'lockedWorkspaceExtId'\n> {\n return {\n chatExtId: call.chat_ext_id ?? null,\n logConversationExtId: call.log_conversation_ext_id ?? null,\n meetingConversationExtId: call.meeting_conversation_ext_id ?? null,\n lockedWorkspaceExtId: call.locked_workspace_ext_id ?? null,\n }\n}\n\n/** An unregistered contact who gets a personal invite link by e-mail. */\nexport interface CallInviteContact {\n contactExtId: string\n /** The name they are invited under; encrypted under K. */\n name: string\n}\n\n/**\n * Mail each contact a personal invite link: an ARBI registration link that, once they have an\n * account, opens `/call/<id>?i=<token>#k=\u2026` and admits them straight into the call. Best effort: a\n * failure for one contact is reported and does not stop the others. Resolves to how many went out.\n */\nasync function sendInviteLinks(\n arbi: Arbi,\n callExtId: string,\n key: Uint8Array,\n linkVersion: number,\n invites: CallInviteContact[]\n): Promise<number> {\n let sent = 0\n for (const invite of invites) {\n try {\n await arbi.calls.inviteLinks.create(callExtId, {\n contact_ext_id: invite.contactExtId,\n link: callLink(callExtId, key, linkVersion),\n })\n sent += 1\n } catch (err) {\n fail(err, `invite ${invite.name || 'a contact'}`)\n }\n }\n if (sent) notify.success(`Sent ${sent} ${sent === 1 ? 'invitation' : 'invitations'}`)\n return sent\n}\n\n/**\n * Create a call and open its pre-join. `ring` are invited now (K sealed to each) and rung when we\n * join; `invites` get a personal invite link by e-mail straight away.\n */\nasync function startCall(\n arbi: Arbi,\n opts: {\n context: { chatExtId?: string | null; threadExtId?: string | null }\n title?: string | null\n ring: CallPeer[]\n invites?: CallInviteContact[]\n }\n): Promise<boolean> {\n if (alreadyInCall()) return false\n try {\n const {\n call,\n key,\n title,\n sealedKeys: ringOnJoin,\n } = await arbi.calls.start({ ...opts.context, title: opts.title, invitees: opts.ring })\n callSession.setActiveCall({\n callExtId: call.external_id,\n key,\n linkVersion: call.link_version,\n title,\n isCreator: call.is_creator,\n ...callContext(call),\n phase: 'prejoin',\n tokenResponse: null,\n choices: null,\n knock: null,\n ringOnJoin: Object.keys(ringOnJoin).length ? ringOnJoin : null,\n })\n if (opts.invites?.length) {\n void sendInviteLinks(arbi, call.external_id, key, call.link_version, opts.invites)\n }\n return true\n } catch (err) {\n fail(err)\n return false\n }\n}\n\n/**\n * A thread call (shared threads only): locked to the thread's workspace and logged in the thread.\n * Get-or-create: a running call on the thread is joined. Only `ring` (the members picked) are rung.\n */\nexport function startThreadCall(\n arbi: Arbi,\n opts: {\n threadExtId: string\n title?: string | null\n ring: CallPeer[]\n }\n): Promise<boolean> {\n return startCall(arbi, {\n context: { threadExtId: opts.threadExtId },\n title: opts.title,\n ring: opts.ring,\n })\n}\n\n/** A chat's call (a DM or a group): the chat is its meeting chat. `ring` are rung when we join. */\nexport function startChatCall(\n arbi: Arbi,\n opts: {\n chatExtId: string\n title?: string | null\n ring: CallPeer[]\n }\n): Promise<boolean> {\n return startCall(arbi, {\n context: { chatExtId: opts.chatExtId },\n title: opts.title,\n ring: opts.ring,\n })\n}\n\n/** Call a person: the call of our direct chat (made if missing), ringing them. */\nexport async function startDmCall(\n arbi: Arbi,\n peer: CallPeer & { name?: string | null }\n): Promise<boolean> {\n if (alreadyInCall()) return false\n if (!peer.encryption_public_key) {\n fail(new Error('This person cannot receive encrypted calls'))\n return false\n }\n let chatExtId: string\n try {\n chatExtId = (await arbi.chats.openDirect(peer.external_id)).external_id\n } catch (err) {\n fail(err)\n return false\n }\n return startChatCall(arbi, { chatExtId, title: peer.name ?? null, ring: [peer] })\n}\n\n/**\n * A contacts call (\"New call\"): registered contacts are rung, unregistered ones get a personal invite\n * link. Its meeting chat is made on first use.\n */\nexport function startContactsCall(\n arbi: Arbi,\n opts: {\n title?: string | null\n ring: CallPeer[]\n invites: CallInviteContact[]\n }\n): Promise<boolean> {\n return startCall(arbi, { context: {}, title: opts.title, ring: opts.ring, invites: opts.invites })\n}\n\n/**\n * Open a call by id (link, upcoming list, notification) into the pre-join.\n * `key` comes from the link fragment; without it we use our sealed copy.\n * `inviteToken` (a personal invite link's `?i=`) is redeemed on join: straight in, no lobby.\n */\nexport async function openCall(\n arbi: Arbi,\n opts: {\n callExtId: string\n key?: Uint8Array | null\n linkVersion?: number | null\n inviteToken?: string | null\n }\n): Promise<boolean> {\n if (alreadyInCall(opts.callExtId)) return false\n try {\n const { call, key, title } = await arbi.calls.open(opts.callExtId, opts.key)\n callSession.setActiveCall({\n callExtId: call.external_id,\n key,\n linkVersion: opts.linkVersion ?? call.link_version,\n title,\n isCreator: call.is_creator,\n ...callContext(call),\n phase: 'prejoin',\n tokenResponse: null,\n choices: null,\n knock: null,\n ringOnJoin: null,\n inviteToken: opts.inviteToken ?? null,\n })\n return true\n } catch (err) {\n fail(err, 'open the call')\n return false\n }\n}\n\n/** Answer a ring: open K from the ring and join straight away (no pre-join). */\nexport async function acceptRing(arbi: Arbi, ring: IncomingCall): Promise<boolean> {\n // Accepting while in another call switches to the new one.\n const current = callSession.getState().active\n if (current && current.callExtId !== ring.call_ext_id) callSession.endActiveCall()\n try {\n const { key, token, title } = await arbi.calls.answer(ring)\n callSession.setActiveCall({\n callExtId: ring.call_ext_id,\n key,\n linkVersion: ring.link_version,\n title: title || ring.caller_name,\n isCreator: false,\n chatExtId: ring.chat_ext_id ?? null,\n logConversationExtId: ring.log_conversation_ext_id ?? null,\n meetingConversationExtId: ring.meeting_conversation_ext_id ?? null,\n lockedWorkspaceExtId: ring.context === 'thread' ? (ring.workspace_ext_id ?? null) : null,\n phase: 'connected',\n tokenResponse: token,\n choices: DEFAULT_JOIN_CHOICES,\n knock: null,\n ringOnJoin: null,\n })\n return true\n } catch (err) {\n fail(err, 'join the call')\n callSession.removeIncomingCall(ring.call_ext_id)\n return false\n }\n}\n\nexport function declineRing(arbi: Arbi, ring: IncomingCall): void {\n callSession.removeIncomingCall(ring.call_ext_id)\n arbi.calls\n .decline(ring.call_ext_id)\n .catch((err: unknown) => console.warn('[calls] decline failed', err))\n}\n\nconst KNOCK_POLL_MS = 2_000\n\n/**\n * Wait in the lobby: poll a knock until it is admitted (\u2192 token), denied or\n * expired (\u2192 throws). `signal` aborts the wait (the user gave up).\n */\nasync function waitForAdmission(\n arbi: Arbi,\n callExtId: string,\n knock: Pick<calls.CallKnockResponse, 'knock_id'>,\n signal: AbortSignal\n): Promise<calls.CallTokenResponse> {\n for (;;) {\n if (signal.aborted) throw new DOMException('Stopped waiting', 'AbortError')\n await new Promise((resolve) => setTimeout(resolve, KNOCK_POLL_MS))\n if (signal.aborted) throw new DOMException('Stopped waiting', 'AbortError')\n const state = await arbi.calls.pollKnock(callExtId, knock.knock_id)\n if (state.status === 'admitted' && state.token) return state.token\n if (state.status === 'denied') throw new CallApiError('The host declined your request.', 403)\n if (state.status === 'expired') throw new CallApiError('Nobody let you in. Try again.', 410)\n }\n}\n\n/**\n * Pre-join done: get a token (or knock when the policy says so), connect, and\n * ring whoever this call was started for.\n */\nexport async function joinFromPreJoin(arbi: Arbi, choices: JoinChoices): Promise<void> {\n const active = callSession.getState().active\n if (!active) return\n const { callExtId, linkVersion, inviteToken } = active\n const update = (patch: Partial<ActiveCall>) => callSession.updateActiveCall(callExtId, patch)\n try {\n let tokenResponse: calls.CallTokenResponse\n try {\n // A personal invite link admits its account straight in (no lobby).\n tokenResponse = await arbi.calls.token(callExtId, linkVersion, inviteToken)\n } catch (err) {\n if (!(err instanceof CallApiError && err.code === 'knock_required')) throw err\n // Knock as the signed-in user (the server names me to the hosts from my account); the\n // token comes at once when the policy lets us straight in.\n const knock = await arbi.calls.knock(callExtId, linkVersion)\n if (knock.status === 'admitted' && knock.token) tokenResponse = knock.token\n else {\n const controller = new AbortController()\n update({ phase: 'knocking', choices, knock: { abort: () => controller.abort() } })\n tokenResponse = await waitForAdmission(arbi, callExtId, knock, controller.signal)\n }\n }\n if (callSession.getState().active?.callExtId !== callExtId) return // left meanwhile\n update({ phase: 'connected', tokenResponse, choices, knock: null })\n const ring = active.ringOnJoin\n if (ring && Object.keys(ring).length) {\n update({ ringOnJoin: null })\n await arbi.calls\n .ring(callExtId, ring, linkVersion)\n .catch((err: unknown) => console.warn('[calls] ring failed', err))\n }\n } catch (err) {\n if (err instanceof DOMException && err.name === 'AbortError') return\n // A webinar's audience before go-live: \"Starting soon\", joining by itself once it is live.\n if (err instanceof CallApiError && err.code === 'webinar_not_live') {\n update({ phase: 'webinar-waiting', choices, knock: null })\n return\n }\n fail(err, 'join the call')\n if (callSession.getState().active?.callExtId === callExtId) {\n callSession.endActiveCall()\n }\n }\n}\n"],
5
- "mappings": "AAmBA,SAAS,qBAAoC;AAC7C,SAAS,oBAA2C;AACpD,SAAS,cAAc;AACvB;AAAA,EACE;AAAA,EACA;AAAA,OAIK;AAKA,SAAS,SAAS,WAAmB,KAAiB,aAA6B;AACxF,SAAO,cAAc,OAAO,SAAS,QAAQ,WAAW,KAAK,WAAW;AAC1E;AAEA,SAAS,cAAc,WAA6B;AAClD,QAAM,SAAS,YAAY,SAAS,EAAE;AACtC,MAAI,CAAC,UAAU,OAAO,cAAc,UAAW,QAAO;AACtD,SAAO,QAAQ,4CAA4C;AAC3D,SAAO;AAC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AW,MAAM,EAAE,EAAE,CAAC;AACjF,wBAAgB,MAAM,iBAAiB,MAAM,WAAW,OAAO,WAAW,MAAM;AAAA,MAClF;AAAA,IACF;AACA,QAAI,YAAY,SAAS,EAAE,QAAQ,cAAc,UAAW;AAC5D,WAAO,EAAE,OAAO,aAAa,eAAe,SAAS,OAAO,KAAK,CAAC;AAClE,UAAM,OAAO,OAAO;AACpB,QAAI,QAAQ,OAAO,KAAK,IAAI,EAAE,QAAQ;AACpC,aAAO,EAAE,YAAY,KAAK,CAAC;AAC3B,YAAM,KAAK,MACR,KAAK,WAAW,MAAM,WAAW,EACjC,MAAM,CAAC,QAAiB,QAAQ,KAAK,uBAAuB,GAAG,CAAC;AAAA,IACrE;AAAA,EACF,SAAS,KAAK;AACZ,QAAI,eAAe,gBAAgB,IAAI,SAAS,aAAc;AAE9D,QAAI,eAAe,gBAAgB,IAAI,SAAS,oBAAoB;AAClE,aAAO,EAAE,OAAO,mBAAmB,SAAS,OAAO,KAAK,CAAC;AACzD;AAAA,IACF;AACA,SAAK,KAAK,eAAe;AACzB,QAAI,YAAY,SAAS,EAAE,QAAQ,cAAc,WAAW;AAC1D,kBAAY,cAAc;AAAA,IAC5B;AAAA,EACF;AACF;",
4
+ "sourcesContent": ["/**\n * Call actions \u2014 usable outside React (buttons, notification actions, the WS\n * ringer). One call system: every call has a random key K made in the\n * creator's browser (see `@arbidocs/client` call-keys):\n *\n * - start (thread / chat / contacts): generate K, create the call with K\n * sealed to ourselves and to the people picked, show the pre-join; on\n * join, ring them. Nobody else is rung: a thread call rings only the\n * members picked, never the whole workspace. Unregistered contacts get a\n * personal invite link by e-mail instead (register, then straight into the\n * call \u2014 there are no anonymous guests);\n * - accept a ring: open K from the ring's sealed blob and join at once;\n * - open a call (link / calendar event / notification): K from the link fragment,\n * else our sealed copy on the server.\n *\n * A thread call is get-or-create: if the thread already has a running call we\n * hold the key for, we join that one instead of starting another.\n */\n\nimport { buildCallLink, type CallPeer } from '@arbidocs/client'\nimport { CallApiError, type Arbi, type calls } from '@arbidocs/sdk/browser'\nimport { notify } from '../notifications/notify-store'\nimport {\n callSession,\n DEFAULT_JOIN_CHOICES,\n type ActiveCall,\n type IncomingCall,\n type JoinChoices,\n} from './session'\n\nexport type { CallPeer }\n\n/** `https://<host>/call/<id>#k=\u2026&v=\u2026` \u2014 the shareable link. */\nexport function callLink(callExtId: string, key: Uint8Array, linkVersion: number): string {\n return buildCallLink(window.location.origin, callExtId, key, linkVersion)\n}\n\nfunction alreadyInCall(callExtId?: string): boolean {\n const active = callSession.getState().active\n if (!active || active.callExtId === callExtId) return false\n notify.warning('You are already in a call. Leave it first.')\n return true\n}\n\nfunction fail(err: unknown, what = 'start the call') {\n console.error(`[calls] failed to ${what}`, err)\n const message = err instanceof Error ? err.message : 'Unknown error'\n notify.error(`Could not ${what}: ${message}`)\n}\n\n/** Where a call belongs, for the active call (and the in-call chat). */\nfunction callContext(\n call: Pick<\n calls.CallResponse,\n | 'chat_ext_id'\n | 'log_conversation_ext_id'\n | 'meeting_conversation_ext_id'\n | 'locked_workspace_ext_id'\n >\n): Pick<\n ActiveCall,\n 'chatExtId' | 'logConversationExtId' | 'meetingConversationExtId' | 'lockedWorkspaceExtId'\n> {\n return {\n chatExtId: call.chat_ext_id ?? null,\n logConversationExtId: call.log_conversation_ext_id ?? null,\n meetingConversationExtId: call.meeting_conversation_ext_id ?? null,\n lockedWorkspaceExtId: call.locked_workspace_ext_id ?? null,\n }\n}\n\n/** An unregistered contact who gets a personal invite link by e-mail. */\nexport interface CallInviteContact {\n contactExtId: string\n /** The name they are invited under; encrypted under K. */\n name: string\n}\n\n/**\n * Mail each contact a personal invite link: an ARBI registration link that, once they have an\n * account, opens `/call/<id>?i=<token>#k=\u2026` and admits them straight into the call. Best effort: a\n * failure for one contact is reported and does not stop the others. Resolves to how many went out.\n */\nasync function sendInviteLinks(\n arbi: Arbi,\n callExtId: string,\n key: Uint8Array,\n linkVersion: number,\n invites: CallInviteContact[]\n): Promise<number> {\n let sent = 0\n for (const invite of invites) {\n try {\n await arbi.calls.inviteLinks.create(callExtId, {\n contact_ext_id: invite.contactExtId,\n link: callLink(callExtId, key, linkVersion),\n })\n sent += 1\n } catch (err) {\n fail(err, `invite ${invite.name || 'a contact'}`)\n }\n }\n if (sent) notify.success(`Sent ${sent} ${sent === 1 ? 'invitation' : 'invitations'}`)\n return sent\n}\n\n/**\n * Create a call and open its pre-join. `ring` are invited now (K sealed to each) and rung when we\n * join; `invites` get a personal invite link by e-mail straight away.\n */\nasync function startCall(\n arbi: Arbi,\n opts: {\n context: {\n chatExtId?: string | null\n threadExtId?: string | null\n workspaceExtId?: string | null\n }\n title?: string | null\n ring: CallPeer[]\n invites?: CallInviteContact[]\n }\n): Promise<boolean> {\n if (alreadyInCall()) return false\n try {\n const {\n call,\n key,\n title,\n sealedKeys: ringOnJoin,\n } = await arbi.calls.start({ ...opts.context, title: opts.title, invitees: opts.ring })\n callSession.setActiveCall({\n callExtId: call.external_id,\n key,\n linkVersion: call.link_version,\n title,\n isCreator: call.is_creator,\n ...callContext(call),\n phase: 'prejoin',\n tokenResponse: null,\n choices: null,\n knock: null,\n ringOnJoin: Object.keys(ringOnJoin).length ? ringOnJoin : null,\n })\n if (opts.invites?.length) {\n void sendInviteLinks(arbi, call.external_id, key, call.link_version, opts.invites)\n }\n return true\n } catch (err) {\n fail(err)\n return false\n }\n}\n\n/**\n * A thread call (shared threads only): locked to the thread's workspace and logged in the thread.\n * Get-or-create: a running call on the thread is joined. Only `ring` (the members picked) are rung.\n */\nexport function startThreadCall(\n arbi: Arbi,\n opts: {\n threadExtId: string\n title?: string | null\n ring: CallPeer[]\n }\n): Promise<boolean> {\n return startCall(arbi, {\n context: { threadExtId: opts.threadExtId },\n title: opts.title,\n ring: opts.ring,\n })\n}\n\n/** A chat's call (a DM or a group): the chat is its meeting chat. `ring` are rung when we join. */\nexport function startChatCall(\n arbi: Arbi,\n opts: {\n chatExtId: string\n title?: string | null\n ring: CallPeer[]\n }\n): Promise<boolean> {\n return startCall(arbi, {\n context: { chatExtId: opts.chatExtId },\n title: opts.title,\n ring: opts.ring,\n })\n}\n\n/** Call a person: the call of our direct chat (made if missing), ringing them. */\nexport async function startDmCall(\n arbi: Arbi,\n peer: CallPeer & { name?: string | null }\n): Promise<boolean> {\n if (alreadyInCall()) return false\n if (!peer.encryption_public_key) {\n fail(new Error('This person cannot receive encrypted calls'))\n return false\n }\n let chatExtId: string\n try {\n chatExtId = (await arbi.chats.openDirect(peer.external_id)).external_id\n } catch (err) {\n fail(err)\n return false\n }\n return startChatCall(arbi, { chatExtId, title: peer.name ?? null, ring: [peer] })\n}\n\n/** A workspace room with a private, participant-scoped meeting conversation. */\nexport function startWorkspaceCall(\n arbi: Arbi,\n opts: { workspaceExtId: string; title?: string | null; ring: CallPeer[] }\n): Promise<boolean> {\n return startCall(arbi, {\n context: { workspaceExtId: opts.workspaceExtId },\n title: opts.title,\n ring: opts.ring,\n })\n}\n\n/**\n * A contacts call (\"New call\"): registered contacts are rung, unregistered ones get a personal invite\n * link. Its meeting chat is made on first use.\n */\nexport function startContactsCall(\n arbi: Arbi,\n opts: {\n title?: string | null\n ring: CallPeer[]\n invites: CallInviteContact[]\n }\n): Promise<boolean> {\n return startCall(arbi, { context: {}, title: opts.title, ring: opts.ring, invites: opts.invites })\n}\n\n/**\n * Open a call by id (link, upcoming list, notification) into the pre-join.\n * `key` comes from the link fragment; without it we use our sealed copy.\n * `inviteToken` (a personal invite link's `?i=`) is redeemed on join: straight in, no lobby.\n */\nexport async function openCall(\n arbi: Arbi,\n opts: {\n callExtId: string\n key?: Uint8Array | null\n linkVersion?: number | null\n inviteToken?: string | null\n }\n): Promise<boolean> {\n if (alreadyInCall(opts.callExtId)) return false\n try {\n const { call, key, title } = await arbi.calls.open(opts.callExtId, opts.key)\n callSession.setActiveCall({\n callExtId: call.external_id,\n key,\n linkVersion: opts.linkVersion ?? call.link_version,\n title,\n isCreator: call.is_creator,\n ...callContext(call),\n phase: 'prejoin',\n tokenResponse: null,\n choices: null,\n knock: null,\n ringOnJoin: null,\n inviteToken: opts.inviteToken ?? null,\n })\n return true\n } catch (err) {\n fail(err, 'open the call')\n return false\n }\n}\n\n/** Answer a ring: open K from the ring and join straight away (no pre-join). */\nexport async function acceptRing(arbi: Arbi, ring: IncomingCall): Promise<boolean> {\n // Accepting while in another call switches to the new one.\n const current = callSession.getState().active\n if (current && current.callExtId !== ring.call_ext_id) callSession.endActiveCall()\n try {\n const { key, token, title } = await arbi.calls.answer(ring)\n callSession.setActiveCall({\n callExtId: ring.call_ext_id,\n key,\n linkVersion: ring.link_version,\n title: title || ring.caller_name,\n isCreator: false,\n chatExtId: ring.chat_ext_id ?? null,\n logConversationExtId: ring.log_conversation_ext_id ?? null,\n meetingConversationExtId: ring.meeting_conversation_ext_id ?? null,\n lockedWorkspaceExtId: ring.context === 'thread' ? (ring.workspace_ext_id ?? null) : null,\n phase: 'connected',\n tokenResponse: token,\n choices: DEFAULT_JOIN_CHOICES,\n knock: null,\n ringOnJoin: null,\n })\n return true\n } catch (err) {\n fail(err, 'join the call')\n callSession.removeIncomingCall(ring.call_ext_id)\n return false\n }\n}\n\nexport function declineRing(arbi: Arbi, ring: IncomingCall): void {\n callSession.removeIncomingCall(ring.call_ext_id)\n arbi.calls\n .decline(ring.call_ext_id)\n .catch((err: unknown) => console.warn('[calls] decline failed', err))\n}\n\nconst KNOCK_POLL_MS = 2_000\n\n/**\n * Wait in the lobby: poll a knock until it is admitted (\u2192 token), denied or\n * expired (\u2192 throws). `signal` aborts the wait (the user gave up).\n */\nasync function waitForAdmission(\n arbi: Arbi,\n callExtId: string,\n knock: Pick<calls.CallKnockResponse, 'knock_id'>,\n signal: AbortSignal\n): Promise<calls.CallTokenResponse> {\n for (;;) {\n if (signal.aborted) throw new DOMException('Stopped waiting', 'AbortError')\n await new Promise((resolve) => setTimeout(resolve, KNOCK_POLL_MS))\n if (signal.aborted) throw new DOMException('Stopped waiting', 'AbortError')\n const state = await arbi.calls.pollKnock(callExtId, knock.knock_id)\n if (state.status === 'admitted' && state.token) return state.token\n if (state.status === 'denied') throw new CallApiError('The host declined your request.', 403)\n if (state.status === 'expired') throw new CallApiError('Nobody let you in. Try again.', 410)\n }\n}\n\n/**\n * Pre-join done: get a token (or knock when the policy says so), connect, and\n * ring whoever this call was started for.\n */\nexport async function joinFromPreJoin(arbi: Arbi, choices: JoinChoices): Promise<void> {\n const active = callSession.getState().active\n if (!active) return\n const { callExtId, linkVersion, inviteToken } = active\n const update = (patch: Partial<ActiveCall>) => callSession.updateActiveCall(callExtId, patch)\n try {\n let tokenResponse: calls.CallTokenResponse\n try {\n // A personal invite link admits its account straight in (no lobby).\n tokenResponse = await arbi.calls.token(callExtId, linkVersion, inviteToken)\n } catch (err) {\n if (!(err instanceof CallApiError && err.code === 'knock_required')) throw err\n // Knock as the signed-in user (the server names me to the hosts from my account); the\n // token comes at once when the policy lets us straight in.\n const knock = await arbi.calls.knock(callExtId, linkVersion)\n if (knock.status === 'admitted' && knock.token) tokenResponse = knock.token\n else {\n const controller = new AbortController()\n update({ phase: 'knocking', choices, knock: { abort: () => controller.abort() } })\n tokenResponse = await waitForAdmission(arbi, callExtId, knock, controller.signal)\n }\n }\n if (callSession.getState().active?.callExtId !== callExtId) return // left meanwhile\n update({ phase: 'connected', tokenResponse, choices, knock: null })\n const ring = active.ringOnJoin\n if (ring && Object.keys(ring).length) {\n update({ ringOnJoin: null })\n await arbi.calls\n .ring(callExtId, ring, linkVersion)\n .catch((err: unknown) => console.warn('[calls] ring failed', err))\n }\n } catch (err) {\n if (err instanceof DOMException && err.name === 'AbortError') return\n // A webinar's audience before go-live: \"Starting soon\", joining by itself once it is live.\n if (err instanceof CallApiError && err.code === 'webinar_not_live') {\n update({ phase: 'webinar-waiting', choices, knock: null })\n return\n }\n fail(err, 'join the call')\n if (callSession.getState().active?.callExtId === callExtId) {\n callSession.endActiveCall()\n }\n }\n}\n"],
5
+ "mappings": "AAmBA,SAAS,qBAAoC;AAC7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A,IAC5B;AAAA,EACF;AACF;",
6
6
  "names": []
7
7
  }
@@ -2,9 +2,11 @@ import { base64ToBytes } from "@arbidocs/client";
2
2
  function checkedCallMedia(value, participant) {
3
3
  if (!value || typeof value !== "object") throw new Error("Invalid call media");
4
4
  const v = value;
5
- if (v.protocol !== "arbi.call.media.v1" || v.participant !== participant || typeof v.utterance_id !== "string" || v.utterance_id.length > 64 || !Number.isSafeInteger(v.sequence) || Number(v.sequence) < 0 || !["start", "media", "end", "stop", "fallback"].includes(String(v.type)))
5
+ if (v.protocol !== "arbi.call.media.v1" || v.participant !== participant || typeof v.utterance_id !== "string" || v.utterance_id.length > 64 || !Number.isSafeInteger(v.sequence) || Number(v.sequence) < 0 || !["start", "media", "audio", "animation", "video-stop", "end", "stop", "fallback"].includes(
6
+ String(v.type)
7
+ ))
6
8
  throw new Error("Invalid call media identity or sequence");
7
- if (v.type === "start" && (v.sample_rate !== 24e3 || v.fps !== 60 || typeof v.avatar !== "string" || !Array.isArray(v.names) || v.names.length !== 52 || new Set(v.names).size !== 52 || !v.names.every((name) => typeof name === "string" && name.length < 80)))
9
+ if (v.type === "start" && (v.sample_rate !== 24e3 || v.fps !== 60 || typeof v.avatar !== "string" || !Array.isArray(v.names) || v.names.length !== 52 && !(v.independent === true && v.names.length === 0) || new Set(v.names).size !== v.names.length || !v.names.every((name) => typeof name === "string" && name.length < 80)))
8
10
  throw new Error("Invalid call media configuration");
9
11
  if (v.type === "media" && (!Number.isSafeInteger(v.start_sample) || Number(v.start_sample) < 0 || typeof v.pcm !== "string" || v.pcm.length > 6400 || !Array.isArray(v.frames) || !v.frames.length || v.frames.length > 6 || !v.frames.every(
10
12
  (frame) => Array.isArray(frame) && frame.length === 52 && frame.every(
@@ -12,6 +14,16 @@ function checkedCallMedia(value, participant) {
12
14
  )
13
15
  )))
14
16
  throw new Error("Invalid call media samples");
17
+ if ((v.type === "audio" || v.type === "animation") && (!Number.isSafeInteger(v.start_sample) || Number(v.start_sample) < 0))
18
+ throw new Error("Invalid independent media clock");
19
+ if (v.type === "audio" && (typeof v.pcm !== "string" || !v.pcm.length || v.pcm.length > 14e3))
20
+ throw new Error("Invalid independent PCM");
21
+ if (v.type === "animation" && (!Array.isArray(v.names) || v.names.length !== 52 || new Set(v.names).size !== 52 || !v.names.every((name) => typeof name === "string" && name.length < 80) || !Array.isArray(v.frames) || !v.frames.length || v.frames.length > 6 || !v.frames.every(
22
+ (frame) => Array.isArray(frame) && frame.length === 52 && frame.every(
23
+ (x) => typeof x === "number" && Number.isFinite(x) && x >= -2 && x <= 2
24
+ )
25
+ )))
26
+ throw new Error("Invalid independent animation");
15
27
  return v;
16
28
  }
17
29
  class CallMediaPlayer {
@@ -25,11 +37,16 @@ class CallMediaPlayer {
25
37
  changed;
26
38
  measured;
27
39
  streaming = false;
40
+ independent = false;
41
+ motionRequested = true;
42
+ motionCurrent = true;
43
+ motionLag = 0;
44
+ motion = [];
28
45
  audible = false;
29
46
  get active() {
30
47
  return this.audible;
31
48
  }
32
- /** Retain transport ownership between utterances; reattaching RTC can replay its buffered tail. */
49
+ /** Retain ownership between utterances; only explicit fallback may unmute RTC. */
33
50
  suppressesTrack = false;
34
51
  avatar = "";
35
52
  names = [];
@@ -59,15 +76,24 @@ class CallMediaPlayer {
59
76
  }
60
77
  if (message.type === "start") {
61
78
  if (message.sequence !== 0 || this.seen.has(message.utterance_id)) return;
62
- this.reset();
79
+ const preserveAudio = this.independent && message.independent === true;
80
+ const previousEnd = preserveAudio ? this.nextTime : 0;
81
+ this.reset(false, preserveAudio);
63
82
  this.seen.add(message.utterance_id);
64
83
  if (this.seen.size > 64) this.seen.delete(this.seen.values().next().value);
65
84
  this.utterance = message.utterance_id;
85
+ this.independent = message.independent === true;
86
+ this.motionCurrent = this.motionRequested;
87
+ this.motionLag = 0;
88
+ this.motion = [];
66
89
  this.avatar = message.avatar;
67
90
  this.names = message.names;
68
91
  this.sequence = 0;
69
92
  this.nextSample = 0;
70
- this.nextTime = this.context.currentTime + 0.15;
93
+ this.nextTime = Math.max(
94
+ previousEnd,
95
+ this.context.currentTime + (this.independent ? 0.04 : 0.15)
96
+ );
71
97
  this.streaming = true;
72
98
  this.renderedMouth = false;
73
99
  this.mouthRest = void 0;
@@ -81,11 +107,32 @@ class CallMediaPlayer {
81
107
  if (message.utterance_id !== this.utterance || message.sequence <= this.sequence) return;
82
108
  if (message.sequence !== this.sequence + 1) throw new Error("Call media sequence gap");
83
109
  this.sequence = message.sequence;
84
- if (message.type === "media") {
110
+ if (["audio", "animation", "video-stop"].includes(message.type) && !this.independent)
111
+ throw new Error("Independent media was not negotiated");
112
+ if (message.type === "video-stop") {
113
+ this.motionCurrent = false;
114
+ this.motion = [];
115
+ return;
116
+ }
117
+ if (message.type === "animation") {
118
+ if (!this.independent || !this.motionCurrent) return;
119
+ if (!this.motion.length) {
120
+ const current = this.segments.find(
121
+ (s) => this.context.currentTime >= s.at && this.context.currentTime < s.at + s.duration
122
+ );
123
+ const sample = current ? current.startSample + (this.context.currentTime - current.at) * 24e3 : 0;
124
+ this.motionLag = Math.min(2, Math.max(0, (sample - message.start_sample) / 24e3) + 0.1);
125
+ }
126
+ this.names = message.names;
127
+ this.motion.push({ startSample: message.start_sample, frames: message.frames });
128
+ if (this.motion.length > 128) this.motion.shift();
129
+ return;
130
+ }
131
+ if (message.type === "media" || message.type === "audio") {
85
132
  if (!this.streaming || message.start_sample !== this.nextSample)
86
133
  throw new Error("Call media sample gap");
87
134
  const pcm = base64ToBytes(message.pcm);
88
- if (pcm.length % 2 || pcm.length > message.frames.length * 800)
135
+ if (pcm.length % 2 || message.type === "media" && pcm.length > message.frames.length * 800)
89
136
  throw new Error("Invalid PCM length");
90
137
  if (this.nextTime - this.context.currentTime > 2) throw new Error("Call media queue exceeded");
91
138
  const buffer = this.context.createBuffer(1, pcm.length / 2, 24e3);
@@ -141,10 +188,10 @@ class CallMediaPlayer {
141
188
  at,
142
189
  startSample: message.start_sample,
143
190
  duration: buffer.duration,
144
- frames: message.frames
191
+ frames: message.frames ?? []
145
192
  });
146
193
  this.segments = this.segments.filter(
147
- (s) => s.at + s.duration > this.context.currentTime - 0.1
194
+ (s) => s.at + s.duration > this.context.currentTime - (this.independent ? 2.1 : 0.1)
148
195
  );
149
196
  this.nextTime = at + buffer.duration;
150
197
  this.nextSample += values.length;
@@ -157,25 +204,38 @@ class CallMediaPlayer {
157
204
  this.streaming = false;
158
205
  this.finishTimer = setTimeout(
159
206
  () => this.reset(),
160
- Math.max(0, this.nextTime - this.context.currentTime) * 1e3 + 30
207
+ Math.max(
208
+ 0,
209
+ this.nextTime - this.context.currentTime + (this.independent && this.motionCurrent ? this.motionLag + 0.1 : 0)
210
+ ) * 1e3 + 30
161
211
  );
162
212
  } else if (message.type === "fallback" || message.type === "stop") {
163
213
  this.reset(message.type === "fallback");
164
214
  }
165
215
  }
166
216
  sample() {
167
- const now = this.context.currentTime;
217
+ const now = this.context.currentTime - (this.independent ? this.motionLag : 0);
168
218
  const segment = this.segments.find((s) => now >= s.at && now < s.at + s.duration);
169
- if (!segment) return null;
170
- const frame = (now - segment.at) * 60;
171
- const i = Math.min(Math.floor(frame), segment.frames.length - 1);
172
- const a = segment.frames[i], b = segment.frames[Math.min(i + 1, segment.frames.length - 1)];
219
+ if (!segment || this.independent && !this.motionCurrent) return null;
220
+ let frames = segment.frames;
221
+ let frame = (now - segment.at) * 60;
222
+ if (this.independent) {
223
+ const sourceSample = segment.startSample + (now - segment.at) * 24e3;
224
+ const packet = this.motion.find(
225
+ (p) => sourceSample >= p.startSample && sourceSample < p.startSample + p.frames.length * 400
226
+ );
227
+ if (!packet) return null;
228
+ frames = packet.frames;
229
+ frame = (sourceSample - packet.startSample) / 400;
230
+ }
231
+ const i = Math.min(Math.floor(frame), frames.length - 1);
232
+ const a = frames[i], b = frames[Math.min(i + 1, frames.length - 1)];
173
233
  return a.map((value, j) => value + (b[j] - value) * (frame - i));
174
234
  }
175
235
  /** Call after the real mesh render, only with mouth/jaw controls actually applied to it. */
176
236
  reportMouthRenderSubmitted(controls) {
177
237
  if (this.renderedMouth) return;
178
- const now = this.context.currentTime;
238
+ const now = this.context.currentTime - (this.independent ? this.motionLag : 0);
179
239
  const segment = this.segments.find((s) => now >= s.at && now < s.at + s.duration);
180
240
  if (!segment) return;
181
241
  const mouth = Object.fromEntries(
@@ -227,16 +287,24 @@ class CallMediaPlayer {
227
287
  this.audible = value;
228
288
  this.changed();
229
289
  }
230
- reset(releaseTrack = false) {
290
+ setMotionEnabled(enabled) {
291
+ this.motionRequested = enabled;
292
+ if (!enabled) {
293
+ this.motionCurrent = false;
294
+ this.motion = [];
295
+ }
296
+ }
297
+ reset(releaseTrack = false, preserveAudio = false) {
231
298
  clearTimeout(this.finishTimer);
232
- for (const source of this.sources) {
299
+ for (const source of preserveAudio ? [] : this.sources) {
233
300
  source.stop();
234
301
  source.disconnect();
235
302
  }
236
- this.sources.clear();
303
+ if (!preserveAudio) this.sources.clear();
237
304
  this.segments = [];
305
+ this.motion = [];
238
306
  this.streaming = false;
239
- this.setAudible(false);
307
+ if (!preserveAudio) this.setAudible(false);
240
308
  if (releaseTrack) this.suppressesTrack = false;
241
309
  this.changed();
242
310
  }
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/calls/livekit/call-media-player.ts"],
4
- "sourcesContent": ["/** A single PCM clock drives both audible speech and timestamped animation controls. */\nimport { base64ToBytes } from '@arbidocs/client'\nimport type { CallTimingEnvelope, CallTimingMeasurement } from './call-timing'\n\nexport interface CallMediaEnvelope {\n protocol: 'arbi.call.media.v1'\n participant: string\n utterance_id: string\n sequence: number\n type: 'start' | 'media' | 'end' | 'stop' | 'fallback'\n avatar?: string\n sample_rate?: number\n fps?: number\n names?: string[]\n start_sample?: number\n pcm?: string\n frames?: number[][]\n}\n\nexport function checkedCallMedia(value: unknown, participant: string): CallMediaEnvelope {\n if (!value || typeof value !== 'object') throw new Error('Invalid call media')\n const v = value as Record<string, unknown>\n if (\n v.protocol !== 'arbi.call.media.v1' ||\n v.participant !== participant ||\n typeof v.utterance_id !== 'string' ||\n v.utterance_id.length > 64 ||\n !Number.isSafeInteger(v.sequence) ||\n Number(v.sequence) < 0 ||\n !['start', 'media', 'end', 'stop', 'fallback'].includes(String(v.type))\n )\n throw new Error('Invalid call media identity or sequence')\n if (\n v.type === 'start' &&\n (v.sample_rate !== 24000 ||\n v.fps !== 60 ||\n typeof v.avatar !== 'string' ||\n !Array.isArray(v.names) ||\n v.names.length !== 52 ||\n new Set(v.names).size !== 52 ||\n !v.names.every((name) => typeof name === 'string' && name.length < 80))\n )\n throw new Error('Invalid call media configuration')\n if (\n v.type === 'media' &&\n (!Number.isSafeInteger(v.start_sample) ||\n Number(v.start_sample) < 0 ||\n typeof v.pcm !== 'string' ||\n v.pcm.length > 6400 ||\n !Array.isArray(v.frames) ||\n !v.frames.length ||\n v.frames.length > 6 ||\n !v.frames.every(\n (frame: unknown) =>\n Array.isArray(frame) &&\n frame.length === 52 &&\n frame.every(\n (x: unknown) => typeof x === 'number' && Number.isFinite(x) && x >= -2 && x <= 2\n )\n ))\n )\n throw new Error('Invalid call media samples')\n return v as unknown as CallMediaEnvelope\n}\n\ninterface Segment {\n at: number\n startSample: number\n duration: number\n frames: number[][]\n}\n\nexport class CallMediaPlayer {\n private streaming = false\n private audible = false\n get active(): boolean {\n return this.audible\n }\n /** Retain transport ownership between utterances; reattaching RTC can replay its buffered tail. */\n suppressesTrack = false\n avatar = ''\n names: string[] = []\n private utterance = ''\n private sequence = -1\n private nextSample = 0\n private nextTime = 0\n private segments: Segment[] = []\n private sources = new Set<AudioBufferSourceNode>()\n private seen = new Set<string>()\n private finishTimer: ReturnType<typeof setTimeout> | undefined\n readonly measurements: CallTimingMeasurement[] = []\n private renderedMouth = false\n private mouthRest: Record<string, number> | undefined\n private scheduledNonzeroPcm = false\n private scheduledPcm = false\n readonly recording: MediaStreamAudioDestinationNode\n\n constructor(\n readonly context: AudioContext,\n private changed: () => void,\n private measured: (measurement: CallTimingMeasurement) => void = () => undefined\n ) {\n this.recording = context.createMediaStreamDestination()\n }\n\n push(message: CallMediaEnvelope, receivedAt = performance.now()): void {\n if (\n message.type === 'fallback' &&\n message.sequence === 0 &&\n message.utterance_id !== this.utterance\n ) {\n if (this.seen.has(message.utterance_id)) return\n this.utterance = message.utterance_id\n this.sequence = 0\n this.seen.add(message.utterance_id)\n if (this.seen.size > 64) this.seen.delete(this.seen.values().next().value!)\n this.reset(true)\n return\n }\n if (message.type === 'start') {\n if (message.sequence !== 0 || this.seen.has(message.utterance_id)) return\n this.reset()\n this.seen.add(message.utterance_id)\n if (this.seen.size > 64) this.seen.delete(this.seen.values().next().value!)\n this.utterance = message.utterance_id\n this.avatar = message.avatar!\n this.names = message.names!\n this.sequence = 0\n this.nextSample = 0\n this.nextTime = this.context.currentTime + 0.15\n this.streaming = true\n this.renderedMouth = false\n this.mouthRest = undefined\n this.scheduledNonzeroPcm = false\n this.scheduledPcm = false\n this.suppressesTrack = true\n this.measure({ event: 'utterance_start_received', client_performance_ms: receivedAt })\n this.changed()\n return\n }\n if (message.utterance_id !== this.utterance || message.sequence <= this.sequence) return\n if (message.sequence !== this.sequence + 1) throw new Error('Call media sequence gap')\n this.sequence = message.sequence\n if (message.type === 'media') {\n if (!this.streaming || message.start_sample !== this.nextSample)\n throw new Error('Call media sample gap')\n const pcm = base64ToBytes(message.pcm!)\n if (pcm.length % 2 || pcm.length > message.frames!.length * 800)\n throw new Error('Invalid PCM length')\n if (this.nextTime - this.context.currentTime > 2) throw new Error('Call media queue exceeded')\n const buffer = this.context.createBuffer(1, pcm.length / 2, 24000)\n const values = buffer.getChannelData(0)\n const view = new DataView(pcm.buffer, pcm.byteOffset, pcm.byteLength)\n for (let i = 0; i < values.length; i++) values[i] = view.getInt16(i * 2, true) / 32768\n const at = Math.max(this.nextTime, this.context.currentTime + 0.02)\n if (this.scheduledPcm && at > this.nextTime + 1 / 24000)\n this.measure({\n event: 'playback_underrun',\n audio_context_seconds: at,\n source_sample: message.start_sample,\n playback_gap_ms: (at - this.nextTime) * 1000,\n })\n const source = this.context.createBufferSource()\n source.buffer = buffer\n source.connect(this.context.destination)\n source.connect(this.recording)\n this.sources.add(source)\n source.onended = () => {\n source.disconnect()\n this.sources.delete(source)\n if (!this.sources.size) this.setAudible(false)\n }\n source.start(at)\n this.setAudible(true)\n if (!this.scheduledPcm) {\n this.scheduledPcm = true\n this.measure({\n event: 'first_media_received',\n client_performance_ms: receivedAt,\n source_sample: message.start_sample,\n })\n this.measure({\n event: 'first_pcm_scheduled',\n audio_context_seconds: at,\n source_sample: message.start_sample,\n })\n }\n if (!this.scheduledNonzeroPcm) {\n const first = values.findIndex((value) => Math.abs(value) > 1 / 32768)\n if (first >= 0) {\n this.scheduledNonzeroPcm = true\n this.measure({\n event: 'first_nonzero_pcm_scheduled',\n audio_context_seconds: at + first / 24000,\n estimated_output_performance_ms: this.outputTime(at + first / 24000),\n source_sample: message.start_sample! + first,\n })\n }\n }\n this.segments.push({\n at,\n startSample: message.start_sample!,\n duration: buffer.duration,\n frames: message.frames!,\n })\n this.segments = this.segments.filter(\n (s) => s.at + s.duration > this.context.currentTime - 0.1\n )\n this.nextTime = at + buffer.duration\n this.nextSample += values.length\n } else if (message.type === 'end') {\n this.measure({\n event: 'utterance_end_received',\n client_performance_ms: receivedAt,\n source_sample: this.nextSample,\n })\n this.streaming = false\n this.finishTimer = setTimeout(\n () => this.reset(),\n Math.max(0, this.nextTime - this.context.currentTime) * 1000 + 30\n )\n } else if (message.type === 'fallback' || message.type === 'stop') {\n this.reset(message.type === 'fallback')\n }\n }\n\n sample(): number[] | null {\n const now = this.context.currentTime\n const segment = this.segments.find((s) => now >= s.at && now < s.at + s.duration)\n if (!segment) return null\n const frame = (now - segment.at) * 60\n const i = Math.min(Math.floor(frame), segment.frames.length - 1)\n const a = segment.frames[i],\n b = segment.frames[Math.min(i + 1, segment.frames.length - 1)]\n return a.map((value, j) => value + (b[j] - value) * (frame - i))\n }\n\n /** Call after the real mesh render, only with mouth/jaw controls actually applied to it. */\n reportMouthRenderSubmitted(controls: Readonly<Record<string, number>>): void {\n if (this.renderedMouth) return\n const now = this.context.currentTime\n const segment = this.segments.find((s) => now >= s.at && now < s.at + s.duration)\n if (!segment) return\n const mouth = Object.fromEntries(\n Object.entries(controls).filter(\n ([name, value]) => /^(mouth|jaw)/i.test(name) && Number.isFinite(value)\n )\n )\n // The first displayed source pose is a baseline, never an onset. Constant NN idle\n // offsets and blink/gaze cannot satisfy this documented 0.02 control-change proxy.\n if (!this.mouthRest) {\n this.mouthRest = mouth\n return\n }\n const delta = Math.max(\n 0,\n ...Object.entries(mouth).map(([name, value]) =>\n Math.abs(value - (this.mouthRest![name] ?? value))\n )\n )\n if (delta < 0.02) return\n this.renderedMouth = true\n this.measure({\n event: 'first_mouth_render_submitted',\n audio_context_seconds: now,\n source_sample: segment.startSample + Math.floor((now - segment.at) * 24000),\n mouth_delta: delta,\n mouth_delta_threshold: 0.02,\n })\n }\n\n timing(event: CallTimingEnvelope, receivedAt = performance.now(), batchSize = 1): void {\n this.measure({ ...event, client_performance_ms: receivedAt, timing_batch_size: batchSize })\n }\n\n private measure(value: Partial<CallTimingMeasurement> & { event: string }): void {\n const entry: CallTimingMeasurement = {\n utterance_id: this.utterance,\n client_performance_ms: performance.now(),\n ...value,\n }\n this.measurements.push(entry)\n if (this.measurements.length > 256) this.measurements.shift()\n this.measured(entry)\n }\n\n private outputTime(at: number): number {\n const stamp = this.context.getOutputTimestamp?.()\n if (\n stamp?.contextTime !== undefined &&\n stamp.performanceTime !== undefined &&\n stamp.performanceTime > 0\n )\n return stamp.performanceTime + (at - stamp.contextTime) * 1000\n return (\n performance.now() + (at - this.context.currentTime + (this.context.baseLatency || 0)) * 1000\n )\n }\n\n private setAudible(value: boolean): void {\n if (this.audible === value) return\n this.audible = value\n this.changed()\n }\n\n reset(releaseTrack = false): void {\n clearTimeout(this.finishTimer)\n for (const source of this.sources) {\n source.stop()\n source.disconnect()\n }\n this.sources.clear()\n this.segments = []\n this.streaming = false\n this.setAudible(false)\n if (releaseTrack) this.suppressesTrack = false\n this.changed()\n }\n}\n"],
5
- "mappings": "AACA,SAAS,qBAAqB;AAkBvB,SAAS,iBAAiB,OAAgB,aAAwC;AACvF,MAAI,CAAC,SAAS,OAAO,UAAU,SAAU,OAAM,IAAI,MAAM,oBAAoB;AAC7E,QAAM,IAAI;AACV,MACE,EAAE,aAAa,wBACf,EAAE,gBAAgB,eAClB,OAAO,EAAE,iBAAiB,YAC1B,EAAE,aAAa,SAAS,MACxB,CAAC,OAAO,cAAc,EAAE,QAAQ,KAChC,OAAO,EAAE,QAAQ,IAAI,KACrB,CAAC,CAAC,SAAS,SAAS,OAAO,QAAQ,UAAU,EAAE,SAAS,OAAO,EAAE,IAAI,CAAC;AAEtE,UAAM,IAAI,MAAM,yCAAyC;AAC3D,MACE,EAAE,SAAS,YACV,EAAE,gBAAgB,QACjB,EAAE,QAAQ,MACV,OAAO,EAAE,WAAW,YACpB,CAAC,MAAM,QAAQ,EAAE,KAAK,KACtB,EAAE,MAAM,WAAW,MACnB,IAAI,IAAI,EAAE,KAAK,EAAE,SAAS,MAC1B,CAAC,EAAE,MAAM,MAAM,CAAC,SAAS,OAAO,SAAS,YAAY,KAAK,SAAS,EAAE;AAEvE,UAAM,IAAI,MAAM,kCAAkC;AACpD,MACE,EAAE,SAAS,YACV,CAAC,OAAO,cAAc,EAAE,YAAY,KACnC,OAAO,EAAE,YAAY,IAAI,KACzB,OAAO,EAAE,QAAQ,YACjB,EAAE,IAAI,SAAS,QACf,CAAC,MAAM,QAAQ,EAAE,MAAM,KACvB,CAAC,EAAE,OAAO,UACV,EAAE,OAAO,SAAS,KAClB,CAAC,EAAE,OAAO;AAAA,IACR,CAAC,UACC,MAAM,QAAQ,KAAK,KACnB,MAAM,WAAW,MACjB,MAAM;AAAA,MACJ,CAAC,MAAe,OAAO,MAAM,YAAY,OAAO,SAAS,CAAC,KAAK,KAAK,MAAM,KAAK;AAAA,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AM,QAAQ,KAAK,QAAQ,qBAAqB;AAChD,QACE,OAAO,gBAAgB,UACvB,MAAM,oBAAoB,UAC1B,MAAM,kBAAkB;AAExB,aAAO,MAAM,mBAAmB,KAAK,MAAM,eAAe;AAC5D,WACE,YAAY,IAAI,KAAK,KAAK,KAAK,QAAQ,eAAe,KAAK,QAAQ,eAAe,MAAM;AAAA,EAE5F;AAAA,EAEQ,WAAW,OAAsB;AACvC,QAAI,KAAK,YAAY,MAAO;AAC5B,SAAK,UAAU;AACf,SAAK,QAAQ;AAAA,EACf;AAAA,EAEA,MAAM,eAAe,OAAa;AAChC,iBAAa,KAAK,WAAW;AAC7B,eAAW,UAAU,KAAK,SAAS;AACjC,aAAO,KAAK;AACZ,aAAO,WAAW;AAAA,IACpB;AACA,SAAK,QAAQ,MAAM;AACnB,SAAK,WAAW,CAAC;AACjB,SAAK,YAAY;AACjB,SAAK,WAAW,KAAK;AACrB,QAAI,aAAc,MAAK,kBAAkB;AACzC,SAAK,QAAQ;AAAA,EACf;AACF;",
4
+ "sourcesContent": ["/** A single PCM clock drives both audible speech and timestamped animation controls. */\nimport { base64ToBytes } from '@arbidocs/client'\nimport type { CallTimingEnvelope, CallTimingMeasurement } from './call-timing'\n\nexport interface CallMediaEnvelope {\n protocol: 'arbi.call.media.v1'\n participant: string\n utterance_id: string\n sequence: number\n type: 'start' | 'media' | 'audio' | 'animation' | 'video-stop' | 'end' | 'stop' | 'fallback'\n independent?: boolean\n avatar?: string\n sample_rate?: number\n fps?: number\n names?: string[]\n start_sample?: number\n pcm?: string\n frames?: number[][]\n}\n\nexport function checkedCallMedia(value: unknown, participant: string): CallMediaEnvelope {\n if (!value || typeof value !== 'object') throw new Error('Invalid call media')\n const v = value as Record<string, unknown>\n if (\n v.protocol !== 'arbi.call.media.v1' ||\n v.participant !== participant ||\n typeof v.utterance_id !== 'string' ||\n v.utterance_id.length > 64 ||\n !Number.isSafeInteger(v.sequence) ||\n Number(v.sequence) < 0 ||\n !['start', 'media', 'audio', 'animation', 'video-stop', 'end', 'stop', 'fallback'].includes(\n String(v.type)\n )\n )\n throw new Error('Invalid call media identity or sequence')\n if (\n v.type === 'start' &&\n (v.sample_rate !== 24000 ||\n v.fps !== 60 ||\n typeof v.avatar !== 'string' ||\n !Array.isArray(v.names) ||\n (v.names.length !== 52 && !(v.independent === true && v.names.length === 0)) ||\n new Set(v.names).size !== v.names.length ||\n !v.names.every((name) => typeof name === 'string' && name.length < 80))\n )\n throw new Error('Invalid call media configuration')\n if (\n v.type === 'media' &&\n (!Number.isSafeInteger(v.start_sample) ||\n Number(v.start_sample) < 0 ||\n typeof v.pcm !== 'string' ||\n v.pcm.length > 6400 ||\n !Array.isArray(v.frames) ||\n !v.frames.length ||\n v.frames.length > 6 ||\n !v.frames.every(\n (frame: unknown) =>\n Array.isArray(frame) &&\n frame.length === 52 &&\n frame.every(\n (x: unknown) => typeof x === 'number' && Number.isFinite(x) && x >= -2 && x <= 2\n )\n ))\n )\n throw new Error('Invalid call media samples')\n if (\n (v.type === 'audio' || v.type === 'animation') &&\n (!Number.isSafeInteger(v.start_sample) || Number(v.start_sample) < 0)\n )\n throw new Error('Invalid independent media clock')\n if (v.type === 'audio' && (typeof v.pcm !== 'string' || !v.pcm.length || v.pcm.length > 14000))\n throw new Error('Invalid independent PCM')\n if (\n v.type === 'animation' &&\n (!Array.isArray(v.names) ||\n v.names.length !== 52 ||\n new Set(v.names).size !== 52 ||\n !v.names.every((name) => typeof name === 'string' && name.length < 80) ||\n !Array.isArray(v.frames) ||\n !v.frames.length ||\n v.frames.length > 6 ||\n !v.frames.every(\n (frame: unknown) =>\n Array.isArray(frame) &&\n frame.length === 52 &&\n frame.every(\n (x: unknown) => typeof x === 'number' && Number.isFinite(x) && x >= -2 && x <= 2\n )\n ))\n )\n throw new Error('Invalid independent animation')\n return v as unknown as CallMediaEnvelope\n}\n\ninterface Segment {\n at: number\n startSample: number\n duration: number\n frames: number[][]\n}\n\nexport class CallMediaPlayer {\n private streaming = false\n private independent = false\n private motionRequested = true\n private motionCurrent = true\n private motionLag = 0\n private motion: Array<{ startSample: number; frames: number[][] }> = []\n private audible = false\n get active(): boolean {\n return this.audible\n }\n /** Retain ownership between utterances; only explicit fallback may unmute RTC. */\n suppressesTrack = false\n avatar = ''\n names: string[] = []\n private utterance = ''\n private sequence = -1\n private nextSample = 0\n private nextTime = 0\n private segments: Segment[] = []\n private sources = new Set<AudioBufferSourceNode>()\n private seen = new Set<string>()\n private finishTimer: ReturnType<typeof setTimeout> | undefined\n readonly measurements: CallTimingMeasurement[] = []\n private renderedMouth = false\n private mouthRest: Record<string, number> | undefined\n private scheduledNonzeroPcm = false\n private scheduledPcm = false\n readonly recording: MediaStreamAudioDestinationNode\n\n constructor(\n readonly context: AudioContext,\n private changed: () => void,\n private measured: (measurement: CallTimingMeasurement) => void = () => undefined\n ) {\n this.recording = context.createMediaStreamDestination()\n }\n\n push(message: CallMediaEnvelope, receivedAt = performance.now()): void {\n if (\n message.type === 'fallback' &&\n message.sequence === 0 &&\n message.utterance_id !== this.utterance\n ) {\n if (this.seen.has(message.utterance_id)) return\n this.utterance = message.utterance_id\n this.sequence = 0\n this.seen.add(message.utterance_id)\n if (this.seen.size > 64) this.seen.delete(this.seen.values().next().value!)\n this.reset(true)\n return\n }\n if (message.type === 'start') {\n if (message.sequence !== 0 || this.seen.has(message.utterance_id)) return\n // Native acknowledgements and answers can use different utterance IDs.\n // Keep their already-scheduled tail so the next start cannot cut a word.\n const preserveAudio = this.independent && message.independent === true\n const previousEnd = preserveAudio ? this.nextTime : 0\n this.reset(false, preserveAudio)\n this.seen.add(message.utterance_id)\n if (this.seen.size > 64) this.seen.delete(this.seen.values().next().value!)\n this.utterance = message.utterance_id\n this.independent = message.independent === true\n this.motionCurrent = this.motionRequested\n this.motionLag = 0\n this.motion = []\n this.avatar = message.avatar!\n this.names = message.names!\n this.sequence = 0\n this.nextSample = 0\n this.nextTime = Math.max(\n previousEnd,\n this.context.currentTime + (this.independent ? 0.04 : 0.15)\n )\n this.streaming = true\n this.renderedMouth = false\n this.mouthRest = undefined\n this.scheduledNonzeroPcm = false\n this.scheduledPcm = false\n this.suppressesTrack = true\n this.measure({ event: 'utterance_start_received', client_performance_ms: receivedAt })\n this.changed()\n return\n }\n if (message.utterance_id !== this.utterance || message.sequence <= this.sequence) return\n if (message.sequence !== this.sequence + 1) throw new Error('Call media sequence gap')\n this.sequence = message.sequence\n if (['audio', 'animation', 'video-stop'].includes(message.type) && !this.independent)\n throw new Error('Independent media was not negotiated')\n if (message.type === 'video-stop') {\n this.motionCurrent = false\n this.motion = []\n return\n }\n if (message.type === 'animation') {\n if (!this.independent || !this.motionCurrent) return\n if (!this.motion.length) {\n const current = this.segments.find(\n (s) => this.context.currentTime >= s.at && this.context.currentTime < s.at + s.duration\n )\n const sample = current\n ? current.startSample + (this.context.currentTime - current.at) * 24000\n : 0\n // The preview gets its own observed delay. Speech's clock is never moved.\n this.motionLag = Math.min(2, Math.max(0, (sample - message.start_sample!) / 24000) + 0.1)\n }\n this.names = message.names!\n this.motion.push({ startSample: message.start_sample!, frames: message.frames! })\n if (this.motion.length > 128) this.motion.shift()\n return\n }\n if (message.type === 'media' || message.type === 'audio') {\n if (!this.streaming || message.start_sample !== this.nextSample)\n throw new Error('Call media sample gap')\n const pcm = base64ToBytes(message.pcm!)\n if (pcm.length % 2 || (message.type === 'media' && pcm.length > message.frames!.length * 800))\n throw new Error('Invalid PCM length')\n if (this.nextTime - this.context.currentTime > 2) throw new Error('Call media queue exceeded')\n const buffer = this.context.createBuffer(1, pcm.length / 2, 24000)\n const values = buffer.getChannelData(0)\n const view = new DataView(pcm.buffer, pcm.byteOffset, pcm.byteLength)\n for (let i = 0; i < values.length; i++) values[i] = view.getInt16(i * 2, true) / 32768\n const at = Math.max(this.nextTime, this.context.currentTime + 0.02)\n if (this.scheduledPcm && at > this.nextTime + 1 / 24000)\n this.measure({\n event: 'playback_underrun',\n audio_context_seconds: at,\n source_sample: message.start_sample,\n playback_gap_ms: (at - this.nextTime) * 1000,\n })\n const source = this.context.createBufferSource()\n source.buffer = buffer\n source.connect(this.context.destination)\n source.connect(this.recording)\n this.sources.add(source)\n source.onended = () => {\n source.disconnect()\n this.sources.delete(source)\n if (!this.sources.size) this.setAudible(false)\n }\n source.start(at)\n this.setAudible(true)\n if (!this.scheduledPcm) {\n this.scheduledPcm = true\n this.measure({\n event: 'first_media_received',\n client_performance_ms: receivedAt,\n source_sample: message.start_sample,\n })\n this.measure({\n event: 'first_pcm_scheduled',\n audio_context_seconds: at,\n source_sample: message.start_sample,\n })\n }\n if (!this.scheduledNonzeroPcm) {\n const first = values.findIndex((value) => Math.abs(value) > 1 / 32768)\n if (first >= 0) {\n this.scheduledNonzeroPcm = true\n this.measure({\n event: 'first_nonzero_pcm_scheduled',\n audio_context_seconds: at + first / 24000,\n estimated_output_performance_ms: this.outputTime(at + first / 24000),\n source_sample: message.start_sample! + first,\n })\n }\n }\n this.segments.push({\n at,\n startSample: message.start_sample!,\n duration: buffer.duration,\n frames: message.frames ?? [],\n })\n this.segments = this.segments.filter(\n (s) => s.at + s.duration > this.context.currentTime - (this.independent ? 2.1 : 0.1)\n )\n this.nextTime = at + buffer.duration\n this.nextSample += values.length\n } else if (message.type === 'end') {\n this.measure({\n event: 'utterance_end_received',\n client_performance_ms: receivedAt,\n source_sample: this.nextSample,\n })\n this.streaming = false\n this.finishTimer = setTimeout(\n () => this.reset(),\n Math.max(\n 0,\n this.nextTime -\n this.context.currentTime +\n (this.independent && this.motionCurrent ? this.motionLag + 0.1 : 0)\n ) *\n 1000 +\n 30\n )\n } else if (message.type === 'fallback' || message.type === 'stop') {\n this.reset(message.type === 'fallback')\n }\n }\n\n sample(): number[] | null {\n const now = this.context.currentTime - (this.independent ? this.motionLag : 0)\n const segment = this.segments.find((s) => now >= s.at && now < s.at + s.duration)\n if (!segment || (this.independent && !this.motionCurrent)) return null\n let frames = segment.frames\n let frame = (now - segment.at) * 60\n if (this.independent) {\n const sourceSample = segment.startSample + (now - segment.at) * 24000\n const packet = this.motion.find(\n (p) => sourceSample >= p.startSample && sourceSample < p.startSample + p.frames.length * 400\n )\n if (!packet) return null\n frames = packet.frames\n frame = (sourceSample - packet.startSample) / 400\n }\n const i = Math.min(Math.floor(frame), frames.length - 1)\n const a = frames[i],\n b = frames[Math.min(i + 1, frames.length - 1)]\n return a.map((value, j) => value + (b[j] - value) * (frame - i))\n }\n\n /** Call after the real mesh render, only with mouth/jaw controls actually applied to it. */\n reportMouthRenderSubmitted(controls: Readonly<Record<string, number>>): void {\n if (this.renderedMouth) return\n const now = this.context.currentTime - (this.independent ? this.motionLag : 0)\n const segment = this.segments.find((s) => now >= s.at && now < s.at + s.duration)\n if (!segment) return\n const mouth = Object.fromEntries(\n Object.entries(controls).filter(\n ([name, value]) => /^(mouth|jaw)/i.test(name) && Number.isFinite(value)\n )\n )\n // The first displayed source pose is a baseline, never an onset. Constant NN idle\n // offsets and blink/gaze cannot satisfy this documented 0.02 control-change proxy.\n if (!this.mouthRest) {\n this.mouthRest = mouth\n return\n }\n const delta = Math.max(\n 0,\n ...Object.entries(mouth).map(([name, value]) =>\n Math.abs(value - (this.mouthRest![name] ?? value))\n )\n )\n if (delta < 0.02) return\n this.renderedMouth = true\n this.measure({\n event: 'first_mouth_render_submitted',\n audio_context_seconds: now,\n source_sample: segment.startSample + Math.floor((now - segment.at) * 24000),\n mouth_delta: delta,\n mouth_delta_threshold: 0.02,\n })\n }\n\n timing(event: CallTimingEnvelope, receivedAt = performance.now(), batchSize = 1): void {\n this.measure({ ...event, client_performance_ms: receivedAt, timing_batch_size: batchSize })\n }\n\n private measure(value: Partial<CallTimingMeasurement> & { event: string }): void {\n const entry: CallTimingMeasurement = {\n utterance_id: this.utterance,\n client_performance_ms: performance.now(),\n ...value,\n }\n this.measurements.push(entry)\n if (this.measurements.length > 256) this.measurements.shift()\n this.measured(entry)\n }\n\n private outputTime(at: number): number {\n const stamp = this.context.getOutputTimestamp?.()\n if (\n stamp?.contextTime !== undefined &&\n stamp.performanceTime !== undefined &&\n stamp.performanceTime > 0\n )\n return stamp.performanceTime + (at - stamp.contextTime) * 1000\n return (\n performance.now() + (at - this.context.currentTime + (this.context.baseLatency || 0)) * 1000\n )\n }\n\n private setAudible(value: boolean): void {\n if (this.audible === value) return\n this.audible = value\n this.changed()\n }\n\n setMotionEnabled(enabled: boolean): void {\n this.motionRequested = enabled\n if (!enabled) {\n this.motionCurrent = false\n this.motion = []\n }\n }\n\n reset(releaseTrack = false, preserveAudio = false): void {\n clearTimeout(this.finishTimer)\n for (const source of preserveAudio ? [] : this.sources) {\n source.stop()\n source.disconnect()\n }\n if (!preserveAudio) this.sources.clear()\n this.segments = []\n this.motion = []\n this.streaming = false\n if (!preserveAudio) this.setAudible(false)\n if (releaseTrack) this.suppressesTrack = false\n this.changed()\n }\n}\n"],
5
+ "mappings": "AACA,SAAS,qBAAqB;AAmBvB,SAAS,iBAAiB,OAAgB,aAAwC;AACvF,MAAI,CAAC,SAAS,OAAO,UAAU,SAAU,OAAM,IAAI,MAAM,oBAAoB;AAC7E,QAAM,IAAI;AACV,MACE,EAAE,aAAa,wBACf,EAAE,gBAAgB,eAClB,OAAO,EAAE,iBAAiB,YAC1B,EAAE,aAAa,SAAS,MACxB,CAAC,OAAO,cAAc,EAAE,QAAQ,KAChC,OAAO,EAAE,QAAQ,IAAI,KACrB,CAAC,CAAC,SAAS,SAAS,SAAS,aAAa,cAAc,OAAO,QAAQ,UAAU,EAAE;AAAA,IACjF,OAAO,EAAE,IAAI;AAAA,EACf;AAEA,UAAM,IAAI,MAAM,yCAAyC;AAC3D,MACE,EAAE,SAAS,YACV,EAAE,gBAAgB,QACjB,EAAE,QAAQ,MACV,OAAO,EAAE,WAAW,YACpB,CAAC,MAAM,QAAQ,EAAE,KAAK,KACrB,EAAE,MAAM,WAAW,MAAM,EAAE,EAAE,gBAAgB,QAAQ,EAAE,MAAM,WAAW,MACzE,IAAI,IAAI,EAAE,KAAK,EAAE,SAAS,EAAE,MAA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vC,SAAK,WAAW,CAAC;AACjB,SAAK,SAAS,CAAC;AACf,SAAK,YAAY;AACjB,QAAI,CAAC,cAAe,MAAK,WAAW,KAAK;AACzC,QAAI,aAAc,MAAK,kBAAkB;AACzC,SAAK,QAAQ;AAAA,EACf;AACF;",
6
6
  "names": []
7
7
  }
@@ -7,7 +7,20 @@ const EVENTS = /* @__PURE__ */ new Set([
7
7
  "first_answer_text",
8
8
  "first_tts_request",
9
9
  "first_pcm",
10
+ "native_speech_started",
11
+ "mic_last_voiced_frame_forwarded",
12
+ "native_speech_stopped",
13
+ "native_response_created",
14
+ "native_function_arguments_ready",
15
+ "native_first_pcm_received",
16
+ "native_first_voiced_pcm_received",
10
17
  "first_pose",
18
+ "tool_result_sent",
19
+ "first_pcm_after_tool",
20
+ "first_voiced_pcm_after_tool",
21
+ "first_voiced_answer_pcm",
22
+ "post_tool_audio_ambiguous",
23
+ "first_pcm_after_answer_text",
11
24
  "animation_connect_started",
12
25
  "animation_ready"
13
26
  ]);
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/calls/livekit/call-timing.ts"],
4
- "sourcesContent": ["/** Content-free call measurements. Server and browser clocks remain explicitly separate. */\nexport const CALL_TIMING_PROTOCOL = 'arbi.call.timing.v1'\nconst EVENTS = new Set([\n 'speech_end',\n 'transcription_started',\n 'transcription_completed',\n 'agent_started',\n 'first_answer_text',\n 'first_tts_request',\n 'first_pcm',\n 'first_pose',\n 'animation_connect_started',\n 'animation_ready',\n])\nexport interface CallTimingEnvelope {\n protocol: typeof CALL_TIMING_PROTOCOL\n participant: string\n utterance_id: string\n generation: number\n event: string\n server_epoch_ms: number\n server_monotonic_ms: number\n}\nexport interface CallTimingMeasurement {\n utterance_id: string\n event: string\n client_performance_ms: number\n audio_context_seconds?: number\n estimated_output_performance_ms?: number\n source_sample?: number\n server_epoch_ms?: number\n server_monotonic_ms?: number\n generation?: number\n timing_batch_size?: number\n mouth_delta?: number\n mouth_delta_threshold?: number\n playback_gap_ms?: number\n}\nexport function checkedCallTiming(value: unknown, participant: string): CallTimingEnvelope {\n if (!value || typeof value !== 'object') throw new Error('Invalid call timing')\n const v = value as Record<string, unknown>\n if (\n v.protocol !== CALL_TIMING_PROTOCOL ||\n v.participant !== participant ||\n typeof v.utterance_id !== 'string' ||\n !v.utterance_id.length ||\n v.utterance_id.length > 64 ||\n !Number.isSafeInteger(v.generation) ||\n Number(v.generation) < 0 ||\n typeof v.event !== 'string' ||\n !EVENTS.has(v.event) ||\n typeof v.server_epoch_ms !== 'number' ||\n !Number.isFinite(v.server_epoch_ms) ||\n typeof v.server_monotonic_ms !== 'number' ||\n !Number.isFinite(v.server_monotonic_ms)\n )\n throw new Error('Invalid call timing')\n return v as unknown as CallTimingEnvelope\n}\n\n/** Publication can be deferred/coalesced; server timestamps must survive that transport delay. */\nexport function checkedCallTimings(value: unknown, participant: string): CallTimingEnvelope[] {\n if (!value || typeof value !== 'object') throw new Error('Invalid call timing')\n const v = value as Record<string, unknown>\n if (!('events' in v)) return [checkedCallTiming(v, participant)]\n if (!Array.isArray(v.events) || !v.events.length || v.events.length > 16)\n throw new Error('Invalid call timing batch')\n return v.events.map((event: unknown) => {\n if (!event || typeof event !== 'object') throw new Error('Invalid call timing event')\n const e = event as Record<string, unknown>\n return checkedCallTiming(\n {\n protocol: v.protocol,\n participant: v.participant,\n utterance_id: v.utterance_id,\n generation: v.generation,\n event: e.event,\n server_epoch_ms: e.server_epoch_ms,\n server_monotonic_ms: e.server_monotonic_ms,\n },\n participant\n )\n })\n}\n"],
5
- "mappings": "AACO,MAAM,uBAAuB;AACpC,MAAM,SAAS,oBAAI,IAAI;AAAA,EACrB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAyBM,SAAS,kBAAkB,OAAgB,aAAyC;AACzF,MAAI,CAAC,SAAS,OAAO,UAAU,SAAU,OAAM,IAAI,MAAM,qBAAqB;AAC9E,QAAM,IAAI;AACV,MACE,EAAE,aAAa,wBACf,EAAE,gBAAgB,eAClB,OAAO,EAAE,iBAAiB,YAC1B,CAAC,EAAE,aAAa,UAChB,EAAE,aAAa,SAAS,MACxB,CAAC,OAAO,cAAc,EAAE,UAAU,KAClC,OAAO,EAAE,UAAU,IAAI,KACvB,OAAO,EAAE,UAAU,YACnB,CAAC,OAAO,IAAI,EAAE,KAAK,KACnB,OAAO,EAAE,oBAAoB,YAC7B,CAAC,OAAO,SAAS,EAAE,eAAe,KAClC,OAAO,EAAE,wBAAwB,YACjC,CAAC,OAAO,SAAS,EAAE,mBAAmB;AAEtC,UAAM,IAAI,MAAM,qBAAqB;AACvC,SAAO;AACT;AAGO,SAAS,mBAAmB,OAAgB,aAA2C;AAC5F,MAAI,CAAC,SAAS,OAAO,UAAU,SAAU,OAAM,IAAI,MAAM,qBAAqB;AAC9E,QAAM,IAAI;AACV,MAAI,EAAE,YAAY,GAAI,QAAO,CAAC,kBAAkB,GAAG,WAAW,CAAC;AAC/D,MAAI,CAAC,MAAM,QAAQ,EAAE,MAAM,KAAK,CAAC,EAAE,OAAO,UAAU,EAAE,OAAO,SAAS;AACpE,UAAM,IAAI,MAAM,2BAA2B;AAC7C,SAAO,EAAE,OAAO,IAAI,CAAC,UAAmB;AACtC,QAAI,CAAC,SAAS,OAAO,UAAU,SAAU,OAAM,IAAI,MAAM,2BAA2B;AACpF,UAAM,IAAI;AACV,WAAO;AAAA,MACL;AAAA,QACE,UAAU,EAAE;AAAA,QACZ,aAAa,EAAE;AAAA,QACf,cAAc,EAAE;AAAA,QAChB,YAAY,EAAE;AAAA,QACd,OAAO,EAAE;AAAA,QACT,iBAAiB,EAAE;AAAA,QACnB,qBAAqB,EAAE;AAAA,MACzB;AAAA,MACA;AAAA,IACF;AAAA,EACF,CAAC;AACH;",
4
+ "sourcesContent": ["/** Content-free call measurements. Server and browser clocks remain explicitly separate. */\nexport const CALL_TIMING_PROTOCOL = 'arbi.call.timing.v1'\nconst EVENTS = new Set([\n 'speech_end',\n 'transcription_started',\n 'transcription_completed',\n 'agent_started',\n 'first_answer_text',\n 'first_tts_request',\n 'first_pcm',\n 'native_speech_started',\n 'mic_last_voiced_frame_forwarded',\n 'native_speech_stopped',\n 'native_response_created',\n 'native_function_arguments_ready',\n 'native_first_pcm_received',\n 'native_first_voiced_pcm_received',\n 'first_pose',\n 'tool_result_sent',\n 'first_pcm_after_tool',\n 'first_voiced_pcm_after_tool',\n 'first_voiced_answer_pcm',\n 'post_tool_audio_ambiguous',\n 'first_pcm_after_answer_text',\n 'animation_connect_started',\n 'animation_ready',\n])\nexport interface CallTimingEnvelope {\n protocol: typeof CALL_TIMING_PROTOCOL\n participant: string\n utterance_id: string\n generation: number\n event: string\n server_epoch_ms: number\n server_monotonic_ms: number\n}\nexport interface CallTimingMeasurement {\n utterance_id: string\n event: string\n client_performance_ms: number\n audio_context_seconds?: number\n estimated_output_performance_ms?: number\n source_sample?: number\n server_epoch_ms?: number\n server_monotonic_ms?: number\n generation?: number\n timing_batch_size?: number\n mouth_delta?: number\n mouth_delta_threshold?: number\n playback_gap_ms?: number\n}\nexport function checkedCallTiming(value: unknown, participant: string): CallTimingEnvelope {\n if (!value || typeof value !== 'object') throw new Error('Invalid call timing')\n const v = value as Record<string, unknown>\n if (\n v.protocol !== CALL_TIMING_PROTOCOL ||\n v.participant !== participant ||\n typeof v.utterance_id !== 'string' ||\n !v.utterance_id.length ||\n v.utterance_id.length > 64 ||\n !Number.isSafeInteger(v.generation) ||\n Number(v.generation) < 0 ||\n typeof v.event !== 'string' ||\n !EVENTS.has(v.event) ||\n typeof v.server_epoch_ms !== 'number' ||\n !Number.isFinite(v.server_epoch_ms) ||\n typeof v.server_monotonic_ms !== 'number' ||\n !Number.isFinite(v.server_monotonic_ms)\n )\n throw new Error('Invalid call timing')\n return v as unknown as CallTimingEnvelope\n}\n\n/** Publication can be deferred/coalesced; server timestamps must survive that transport delay. */\nexport function checkedCallTimings(value: unknown, participant: string): CallTimingEnvelope[] {\n if (!value || typeof value !== 'object') throw new Error('Invalid call timing')\n const v = value as Record<string, unknown>\n if (!('events' in v)) return [checkedCallTiming(v, participant)]\n if (!Array.isArray(v.events) || !v.events.length || v.events.length > 16)\n throw new Error('Invalid call timing batch')\n return v.events.map((event: unknown) => {\n if (!event || typeof event !== 'object') throw new Error('Invalid call timing event')\n const e = event as Record<string, unknown>\n return checkedCallTiming(\n {\n protocol: v.protocol,\n participant: v.participant,\n utterance_id: v.utterance_id,\n generation: v.generation,\n event: e.event,\n server_epoch_ms: e.server_epoch_ms,\n server_monotonic_ms: e.server_monotonic_ms,\n },\n participant\n )\n })\n}\n"],
5
+ "mappings": "AACO,MAAM,uBAAuB;AACpC,MAAM,SAAS,oBAAI,IAAI;AAAA,EACrB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAyBM,SAAS,kBAAkB,OAAgB,aAAyC;AACzF,MAAI,CAAC,SAAS,OAAO,UAAU,SAAU,OAAM,IAAI,MAAM,qBAAqB;AAC9E,QAAM,IAAI;AACV,MACE,EAAE,aAAa,wBACf,EAAE,gBAAgB,eAClB,OAAO,EAAE,iBAAiB,YAC1B,CAAC,EAAE,aAAa,UAChB,EAAE,aAAa,SAAS,MACxB,CAAC,OAAO,cAAc,EAAE,UAAU,KAClC,OAAO,EAAE,UAAU,IAAI,KACvB,OAAO,EAAE,UAAU,YACnB,CAAC,OAAO,IAAI,EAAE,KAAK,KACnB,OAAO,EAAE,oBAAoB,YAC7B,CAAC,OAAO,SAAS,EAAE,eAAe,KAClC,OAAO,EAAE,wBAAwB,YACjC,CAA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