@pyai/sdk 0.9.3 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/CLI.schema.json +11 -0
  2. package/README.md +106 -3
  3. package/dist/cli-omni-template.d.ts +2 -2
  4. package/dist/cli-omni-template.js +2 -2
  5. package/dist/cli.js +39 -4
  6. package/dist/dialer/appServer.d.ts +21 -0
  7. package/dist/dialer/appServer.js +195 -0
  8. package/dist/dialer/dialerElement.d.ts +23 -0
  9. package/dist/dialer/dialerElement.js +108 -0
  10. package/dist/dialer/dialingQueue.d.ts +31 -0
  11. package/dist/dialer/dialingQueue.js +78 -0
  12. package/dist/dialer/index.d.ts +6 -0
  13. package/dist/dialer/index.js +6 -0
  14. package/dist/dialer/indexedDbJournal.d.ts +11 -0
  15. package/dist/dialer/indexedDbJournal.js +62 -0
  16. package/dist/dialer/managedDialer.d.ts +65 -0
  17. package/dist/dialer/managedDialer.js +217 -0
  18. package/dist/dialer/meetingRecorder.d.ts +83 -0
  19. package/dist/dialer/meetingRecorder.js +261 -0
  20. package/dist/dialer/meetingRecorderElement.d.ts +20 -0
  21. package/dist/dialer/meetingRecorderElement.js +138 -0
  22. package/dist/dialer/meetingRecordingStore.d.ts +17 -0
  23. package/dist/dialer/meetingRecordingStore.js +129 -0
  24. package/dist/dialer/serverBroker.d.ts +3 -0
  25. package/dist/dialer/serverBroker.js +23 -0
  26. package/dist/dialer/voiceSdkAudio.d.ts +33 -0
  27. package/dist/dialer/voiceSdkAudio.js +66 -0
  28. package/dist/index.d.ts +122 -6
  29. package/dist/index.js +36 -3
  30. package/package.json +24 -1
  31. package/src/cli-omni-template.ts +2 -2
  32. package/src/cli.ts +25 -4
  33. package/src/dialer/app/app.css +1 -0
  34. package/src/dialer/app/app.html +7 -0
  35. package/src/dialer/app/app.js +88 -0
  36. package/src/dialer/app/icon.svg +1 -0
  37. package/src/dialer/app/manifest.webmanifest +1 -0
  38. package/src/dialer/appServer.ts +151 -0
  39. package/src/dialer/dialerElement.ts +80 -0
  40. package/src/dialer/dialingQueue.ts +65 -0
  41. package/src/dialer/index.ts +6 -0
  42. package/src/dialer/indexedDbJournal.ts +56 -0
  43. package/src/dialer/managedDialer.ts +187 -0
  44. package/src/dialer/meetingRecorder.ts +220 -0
  45. package/src/dialer/meetingRecorderElement.ts +99 -0
  46. package/src/dialer/meetingRecordingStore.ts +99 -0
  47. package/src/dialer/serverBroker.ts +23 -0
  48. package/src/dialer/voiceSdkAudio.ts +61 -0
  49. package/src/index.ts +118 -5
@@ -0,0 +1,88 @@
1
+ import { ManagedDialer } from '/modules/managedDialer.js';
2
+ import { IndexedDbDialerJournal } from '/modules/indexedDbJournal.js';
3
+ import { VoiceSdkAudio } from '/modules/voiceSdkAudio.js';
4
+ import { DialingQueue } from '/modules/dialingQueue.js';
5
+ import { MeetingRecorder } from '/modules/meetingRecorder.js';
6
+ import { IndexedDbMeetingRecordingStore } from '/modules/meetingRecordingStore.js';
7
+ import '/modules/dialerElement.js';
8
+ import '/modules/meetingRecorderElement.js';
9
+
10
+ const $=selector=>document.querySelector(selector),error=$('#error');
11
+ const showError=value=>{error.textContent=value instanceof Error?value.message:String(value);};
12
+ let config,dialer,queue,audio,closed=false,poll,audioGeneration=0;
13
+ let localSession=null;
14
+ async function request(path,options={}){
15
+ const response=await fetch(path,{...options,headers:{...(options.body?{'content-type':'application/json'}:{}),...(localSession?{authorization:`Bearer ${localSession}`} :{}),...(config?{'x-pyai-local-session':config.nonce}:{}),...options.headers},cache:'no-store',signal:AbortSignal.timeout(20000)});
16
+ const body=await response.json();if(!response.ok)throw Error(body?.error?.message??'This operation could not be confirmed.');return body;
17
+ }
18
+ let media;
19
+ async function loadMedia(){
20
+ if(window.Twilio?.Device)return;
21
+ media??=new Promise((resolve,reject)=>{const script=document.createElement('script');script.src='/voice-sdk.js';script.onload=resolve;script.onerror=()=>reject(Error('Calling audio could not load. End or recover this attempt.'));document.head.append(script);});
22
+ try{await media;}catch(e){media=null;throw e;}
23
+ if(!window.Twilio?.Device)throw Error('Calling audio is unavailable.');
24
+ }
25
+ function renderQueue(){
26
+ if(!queue)return;const state=queue.current,active=dialer.current.state!=='idle';
27
+ $('#queue-start').disabled=active||state.running||!config.numbers.length;
28
+ $('#queue-pause').disabled=!state.running;$('#queue-resume').disabled=state.running||!state.remaining;
29
+ $('#source').disabled=active||state.running;$('#mode').disabled=active||state.running;$('#record-calls').disabled=active||state.running;$('#contacts').disabled=state.running||active;
30
+ $('#queue-status').textContent=state.activeId?`${state.running?'Queue running':'Queue paused'} · ${state.remaining} remaining. Finish this call and choose Done to continue.`:state.remaining?`${state.remaining} contacts waiting. Choose Resume queue when ready.`:'You choose when to start. Your workspace calling rules apply to every call.';
31
+ }
32
+ async function refresh(){
33
+ clearTimeout(poll);if(closed)return;
34
+ try{if(dialer&&dialer.current.callId&&!['idle','wrapup'].includes(dialer.current.state))await dialer.refresh();}catch(e){showError(e);}
35
+ if(!closed)poll=setTimeout(refresh,dialer?.current.state==='idle'?8000:1500);
36
+ }
37
+ async function init(){
38
+ try{localSession=localStorage.getItem('pyai-local-app-session');}catch{throw Error('Private app storage is unavailable. Enable storage for this local app before calling.');}
39
+ const code=location.hash.slice(1);history.replaceState(null,'',location.pathname);
40
+ if(code){const unlocked=await request('/api/unlock',{method:'POST',body:JSON.stringify({code})});localSession=unlocked.session_token;localStorage.setItem('pyai-local-app-session',localSession);}
41
+ config=await request('/api/config');document.title=config.name;$('[data-brand]').textContent=config.name;
42
+ if(config.white_label){$('.logo').textContent=(config.name.match(/[A-Za-z]/)?.[0]??'P').toUpperCase();$('.aside-foot small').hidden=true;$('footer').textContent='Calls and call recordings stay in your workspace. Meeting audio stays in this browser until you save or submit it.';}
43
+ const source=$('#source');source.replaceChildren();
44
+ for(const number of config.numbers){const option=document.createElement('option');option.value=number.id;option.textContent=number.phone_number;source.append(option);}
45
+ if(!config.numbers.length){const option=document.createElement('option');option.textContent='No active voice numbers in this workspace';source.append(option);}
46
+ source.disabled=!config.numbers.length;
47
+ const broker={create:(input,key)=>request('/api/sessions',{method:'POST',headers:{'idempotency-key':key},body:JSON.stringify(input)}),get:id=>request(`/api/calls/${encodeURIComponent(id)}`),hangup:id=>request(`/api/calls/${encodeURIComponent(id)}/hangup`,{method:'POST',body:'{}'})};
48
+ const transport=new VoiceSdkAudio(token=>new window.Twilio.Device(token,{logLevel:'silent'}));
49
+ audio={connect:async(...args)=>{const generation=++audioGeneration;await loadMedia();if(generation!==audioGeneration)throw Error('Calling audio was cancelled.');return transport.connect(...args);},disconnect:()=>{++audioGeneration;transport.disconnect();},mute:value=>transport.mute(value),sendDigits:digits=>transport.sendDigits(digits)};
50
+ dialer=new ManagedDialer(config.scope,broker,new IndexedDbDialerJournal(),audio);
51
+ await dialer.restore();
52
+ const inputFor=to=>({from_number_id:source.value,to,user_id:config.user_id,client_reference:crypto.randomUUID(),recording:$('#record-calls').checked,max_duration_seconds:3600,use_case:'support'});
53
+ queue=new DialingQueue(dialer,async contact=>{const latest=await request('/api/config');return latest.scope===config.scope&&latest.numbers.some(n=>n.id===contact.input.from_number_id);});
54
+ $('pyai-dialer').bind(dialer,to=>{
55
+ if(!config.numbers.length)throw Error('Add a voice number in your PyAI workspace before calling.');
56
+ const sourceNumber=config.numbers.find(n=>n.id===source.value);if(sourceNumber?.phone_number===to)throw Error('Choose a destination different from your calling number.');
57
+ return inputFor(to);
58
+ },{name:config.name,showBranding:!config.white_label},async()=>{await queue.finishWrapup();renderQueue();});
59
+ dialer.subscribe(()=>renderQueue());renderQueue();
60
+ const store=new IndexedDbMeetingRecordingStore(),recorder=new MeetingRecorder(config.scope,store);$('pyai-meeting-recorder').bind(recorder,store);
61
+ $('#queue-start').addEventListener('click',()=>void act(async()=>{
62
+ const contacts=$('#contacts').value.split(/\r?\n/).map(line=>line.trim()).filter(Boolean).map((line,index)=>{
63
+ const [number,priority='0']=line.split(',').map(value=>value.trim());const to=number.replace(/[\s()-]/g,'');
64
+ if(config.numbers.find(n=>n.id===source.value)?.phone_number===to)throw Error(`Line ${index+1} matches your calling number.`);
65
+ return {id:crypto.randomUUID(),input:inputFor(to),priority:Number(priority)};
66
+ });await queue.start(contacts,$('#mode').value);renderQueue();
67
+ }));
68
+ $('#queue-pause').addEventListener('click',()=>{queue.pause();renderQueue();});$('#queue-resume').addEventListener('click',()=>void act(async()=>{await queue.resume();renderQueue();}));
69
+ window.addEventListener('pagehide',()=>{
70
+ closed=true;clearTimeout(poll);queue.pause();audio.disconnect();void recorder.stop();
71
+ const id=dialer.current.callId;if(id&&!['idle','wrapup'].includes(dialer.current.state))void fetch(`/api/calls/${encodeURIComponent(id)}/hangup`,{method:'POST',headers:{'content-type':'application/json','x-pyai-local-session':config.nonce,authorization:`Bearer ${localSession}`},body:'{}',keepalive:true}).catch(()=>{});
72
+ });
73
+ void refresh();
74
+ }
75
+ async function act(action){error.textContent='';try{await action();}catch(e){showError(e);renderQueue();}}
76
+ for(const tab of document.querySelectorAll('[data-tab]'))tab.addEventListener('click',()=>{
77
+ for(const button of document.querySelectorAll('[data-tab]'))button.classList.toggle('selected',button===tab);
78
+ for(const panel of document.querySelectorAll('[data-panel]'))panel.hidden=panel.dataset.panel!==tab.dataset.tab;
79
+ $('[data-heading]').textContent=tab.dataset.tab==='calls'?'Make the next connection.':'Be present. Keep the conversation.';
80
+ $('[data-subtitle]').textContent=tab.dataset.tab==='calls'?'A clear line. A little less busywork.':'A private recording, on your terms.';
81
+ });
82
+ async function connectWorkspace(){
83
+ $('#retry').disabled=true;error.textContent='';
84
+ try{await init();$('#retry').hidden=true;}
85
+ catch(e){showError(e);$('#retry').hidden=false;$('#retry').disabled=false;}
86
+ }
87
+ $('#retry').addEventListener('click',()=>void connectWorkspace());
88
+ void connectWorkspace();
@@ -0,0 +1 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" width="512" height="512" viewBox="0 0 512 512"><rect width="512" height="512" rx="116" fill="#5b55e7"/><path d="M164 384V202c0-58 37-91 93-91 62 0 99 43 99 105s-37 104-99 104c-17 0-32-3-46-10v74h-47zm92-108c35 0 54-24 54-60s-19-60-54-60-53 24-53 60 18 60 53 60z" fill="white"/></svg>
@@ -0,0 +1 @@
1
+ {"id":"/","name":"PyAI Phone","short_name":"PyAI Phone","description":"Workspace calling and private meeting recording","start_url":"/","scope":"/","display":"standalone","background_color":"#f6f6fa","theme_color":"#5b55e7","icons":[{"src":"/icon.svg","sizes":"any","type":"image/svg+xml","purpose":"any maskable"}]}
@@ -0,0 +1,151 @@
1
+ /** Personal loopback companion. Project credentials stay in the local Node
2
+ * process; the renderer receives only the managed one-call capability. */
3
+ import { createServer, type IncomingMessage, type ServerResponse } from "node:http";
4
+ import { randomBytes, timingSafeEqual } from "node:crypto";
5
+ import { readFile } from "node:fs/promises";
6
+ import { createRequire } from "node:module";
7
+ import { dirname, join } from "node:path";
8
+ import { Readable } from "node:stream";
9
+ import type { PyAI, TelephonyBrowserSessionCreate, TelephonyCall } from "../index.ts";
10
+ import { createServerDialerBroker } from "./serverBroker.ts";
11
+
12
+ export interface DialerAppOptions {
13
+ sdk: PyAI;
14
+ /** Derived by the trusted local host, never accepted from renderer input. */
15
+ userId: string;
16
+ scope: string;
17
+ name?: string;
18
+ whiteLabel?: boolean;
19
+ port?: number;
20
+ /** Explicit asset injection for packaging/tests, never selected by HTTP. */
21
+ assets?: { read(path: string): Promise<Uint8Array> };
22
+ }
23
+ const terminal = (call: TelephonyCall) => ["completed", "failed", "canceled"].includes(call.status);
24
+ const secretMatches = (input: unknown, expected: string) => typeof input === "string" && /^[A-Za-z0-9_-]+$/.test(input) && input.length === expected.length && timingSafeEqual(Buffer.from(input), Buffer.from(expected));
25
+ const browserModules = new Set(["managedDialer", "dialingQueue", "indexedDbJournal", "voiceSdkAudio", "dialerElement", "meetingRecorder", "meetingRecordingStore", "meetingRecorderElement"]);
26
+ const publicAssets = new Set(["/", "/app.js", "/app.css", "/manifest.webmanifest", "/icon.svg"]);
27
+ const publicModule = (path: string) => { const match = /^\/modules\/([A-Za-z]+)\.js$/.exec(path); return match && browserModules.has(match[1]!) ? match[1] : null; };
28
+ async function packagedAsset(path: string): Promise<Uint8Array> {
29
+ if (path === "/" || path === "/app.js" || path === "/app.css" || path === "/manifest.webmanifest" || path === "/icon.svg") {
30
+ const file = path === "/" ? "app.html" : path.slice(1);
31
+ return readFile(new URL(`../../src/dialer/app/${file}`, import.meta.url));
32
+ }
33
+ if (path === "/voice-sdk.js") {
34
+ const require = createRequire(import.meta.url);
35
+ const root = dirname(dirname(require.resolve("@twilio/voice-sdk")));
36
+ return readFile(join(root, "dist/twilio.min.js"));
37
+ }
38
+ const module = publicModule(path);
39
+ if (module) return readFile(new URL(`./${module}.js`, import.meta.url));
40
+ throw new Error("No such asset.");
41
+ }
42
+ class AppError extends Error {
43
+ readonly status: number;
44
+ constructor(status: number, message: string) { super(message); this.status = status; }
45
+ }
46
+ async function body(request: IncomingMessage): Promise<Record<string, unknown>> {
47
+ if (!/^application\/json(?:\s*;|$)/i.test(request.headers["content-type"] ?? "")) throw new AppError(415, "Send a JSON request.");
48
+ const chunks: Buffer[] = []; let size = 0;
49
+ for await (const chunk of request) {
50
+ size += chunk.length; if (size > 16384) throw new AppError(413, "Calling request is too large.");
51
+ chunks.push(Buffer.from(chunk));
52
+ }
53
+ try { const value = JSON.parse(Buffer.concat(chunks).toString("utf8")); if (!value || Array.isArray(value) || typeof value !== "object") throw Error(); return value; }
54
+ catch { throw new AppError(400, "Invalid calling request."); }
55
+ }
56
+ function json(response: ServerResponse, status: number, value: unknown) { response.writeHead(status, { "content-type": "application/json; charset=utf-8" }); response.end(JSON.stringify(value)); }
57
+ export async function startDialerApp(options: DialerAppOptions) {
58
+ if (!options.scope.trim() || !options.userId.trim() || !Number.isInteger(options.port ?? 43117) || (options.port ?? 43117) < 0 || (options.port ?? 43117) > 65535) throw new Error("A local user, scope and valid port are required.");
59
+ const broker = createServerDialerBroker(options.sdk, options.userId), nonce = randomBytes(32).toString("base64url");
60
+ const bootstrap = randomBytes(32).toString("base64url"), rendererToken = randomBytes(32).toString("base64url"), bootstrapExpires = Date.now() + 60000;
61
+ let bootstrapUsed = false;
62
+ let origin = "", closing = false; const calls = new Set<string>();
63
+ const remember = (call: TelephonyCall) => { if (terminal(call)) calls.delete(call.id); else calls.add(call.id); return call; };
64
+ const numbers = async () => (await options.sdk.telephony.numbers.list()).data.filter(number => number.status !== "released" && number.capabilities?.voice === true);
65
+ const own = async (id: string) => remember(await broker.get(id));
66
+ const server = createServer(async (request, response) => {
67
+ response.setHeader("cache-control", "no-store"); response.setHeader("x-content-type-options", "nosniff"); response.setHeader("x-frame-options", "DENY");
68
+ response.setHeader("referrer-policy", "no-referrer");
69
+ response.setHeader("content-security-policy", "default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self'; manifest-src 'self'; connect-src 'self' https://*.twilio.com wss://*.twilio.com; media-src 'self' blob: https://sdk.twilio.com; worker-src 'self' blob:; frame-ancestors 'none'; base-uri 'none'; form-action 'none'");
70
+ try {
71
+ // Prevent DNS rebinding, cross-site loopback probes and requests to a
72
+ // publicly bound address. No CORS or wildcard-host mode exists.
73
+ if (!origin || request.headers.host !== new URL(origin).host || request.headers["sec-fetch-site"] === "cross-site" || (request.headers.origin && request.headers.origin !== origin)) throw new AppError(403, "Open the local PyAI dialer directly.");
74
+ const url = new URL(request.url ?? "/", origin), method = request.method ?? "GET";
75
+ if (url.search || url.hash) throw new AppError(400, "Unexpected request parameters.");
76
+ if (url.pathname === "/api/unlock" && method === "POST") {
77
+ if (request.headers.origin !== origin) throw new AppError(403, "Open the private local link from your terminal.");
78
+ const input = await body(request);
79
+ if (bootstrapUsed || Date.now() > bootstrapExpires || !secretMatches(input.code, bootstrap)) throw new AppError(403, "The private launch link has expired or was already used. Reopen the dialer from your terminal.");
80
+ bootstrapUsed = true;
81
+ return json(response, 200, { session_token: rendererToken });
82
+ }
83
+ if (url.pathname.startsWith("/api/") && !secretMatches(request.headers.authorization?.replace(/^Bearer /, ""), rendererToken)) throw new AppError(401, "Open the private local link from your terminal to unlock this app.");
84
+ if (method !== "GET") {
85
+ const supplied = request.headers["x-pyai-local-session"];
86
+ if (request.headers.origin !== origin || !secretMatches(supplied, nonce)) throw new AppError(403, "Local calling session changed. Reload the app.");
87
+ }
88
+ if (url.pathname === "/api/config" && method === "GET") {
89
+ const owned = await numbers();
90
+ return json(response, 200, { name: options.name ?? (options.whiteLabel ? "Phone" : "PyAI Phone"), white_label: options.whiteLabel === true, scope: options.scope, user_id: options.userId, nonce,
91
+ numbers: owned.map(number => ({ id: number.id, phone_number: number.phone_number, country: number.country })) });
92
+ }
93
+ if (url.pathname === "/api/sessions" && method === "POST") {
94
+ if (closing) throw new AppError(503, "Dialer is closing. No new calls are admitted.");
95
+ const input = await body(request), key = request.headers["idempotency-key"];
96
+ if (typeof key !== "string" || typeof input.from_number_id !== "string" || !(await numbers()).some(number => number.id === input.from_number_id)) throw new AppError(400, "Choose an owned voice number and a calling retry key.");
97
+ const session = await broker.create(input as unknown as TelephonyBrowserSessionCreate, key); remember(session.call);
98
+ return json(response, 200, session);
99
+ }
100
+ const callPath = /^\/api\/calls\/([A-Za-z0-9_-]{1,200})(?:\/(hangup|recording))?$/.exec(url.pathname);
101
+ if (callPath) {
102
+ const id = callPath[1]!, operation = callPath[2]; await own(id);
103
+ if (method === "GET" && !operation) return json(response, 200, await own(id));
104
+ if (method === "POST" && operation === "hangup") { await body(request); return json(response, 202, remember(await broker.hangup(id))); }
105
+ if (method === "GET" && operation === "recording") {
106
+ const range = request.headers.range;
107
+ if (range && !/^bytes=\d+-\d*$/.test(range)) throw new AppError(400, "Invalid recording range.");
108
+ const recording = await options.sdk.telephony.calls.recording(id, range ? { range } : {});
109
+ response.statusCode = recording.status;
110
+ for (const header of ["content-type", "content-length", "content-range", "accept-ranges"]) { const value = recording.headers.get(header); if (value) response.setHeader(header, value); }
111
+ response.setHeader("content-disposition", `attachment; filename="Call-${id}.wav"`);
112
+ if (!recording.body) return response.end();
113
+ const stream = Readable.fromWeb(recording.body as import("node:stream/web").ReadableStream);
114
+ response.on("close", () => stream.destroy()); stream.on("error", () => response.destroy()); stream.pipe(response); return;
115
+ }
116
+ }
117
+ if (method !== "GET" || url.pathname.startsWith("/api/")) throw new AppError(404, "No such dialer operation.");
118
+ if (url.pathname === "/manifest.webmanifest") {
119
+ response.writeHead(200, { "content-type": "application/manifest+json" });
120
+ return response.end(JSON.stringify({ id: "/", name: options.name ?? (options.whiteLabel ? "Phone" : "PyAI Phone"), short_name: options.name ?? "Phone", start_url: "/", scope: "/", display: "standalone", background_color: "#f6f6fa", theme_color: "#5b55e7", icons: [{ src: "/icon.svg", sizes: "any", type: "image/svg+xml", purpose: "any maskable" }] }));
121
+ }
122
+ if (url.pathname === "/icon.svg" && options.whiteLabel) {
123
+ const monogram = (options.name ?? "Phone").match(/[A-Za-z]/)?.[0]?.toUpperCase() ?? "P";
124
+ response.writeHead(200, { "content-type": "image/svg+xml" });
125
+ return response.end(`<svg xmlns="http://www.w3.org/2000/svg" width="512" height="512" viewBox="0 0 512 512"><rect width="512" height="512" rx="116" fill="#5b55e7"/><text x="256" y="360" text-anchor="middle" font-family="system-ui,sans-serif" font-size="320" fill="white">${monogram}</text></svg>`);
126
+ }
127
+ if (!publicAssets.has(url.pathname) && url.pathname !== "/voice-sdk.js" && !publicModule(url.pathname)) throw new AppError(404, "No such dialer asset.");
128
+ const bytes = await (options.assets?.read ?? packagedAsset)(url.pathname).catch(() => { throw new AppError(404, "No such dialer asset."); });
129
+ const type = url.pathname === "/" ? "text/html; charset=utf-8" : url.pathname.endsWith(".js") ? "text/javascript" : url.pathname.endsWith(".css") ? "text/css" : url.pathname.endsWith(".svg") ? "image/svg+xml" : "application/manifest+json";
130
+ response.writeHead(200, { "content-type": type }); response.end(bytes);
131
+ } catch (error) {
132
+ if (response.headersSent) { response.destroy(); return; }
133
+ // Never reflect upstream responses, credentials, URLs, or stack traces.
134
+ const status = error instanceof AppError ? error.status : typeof (error as { status?: number })?.status === "number" ? (error as { status: number }).status : 502;
135
+ const message = error instanceof AppError ? error.message : status === 401 || status === 403 ? "Your PyAI project does not permit this operation. Check your signed-in profile and calling policy." : "PyAI could not confirm this operation. Recover the same call before trying another.";
136
+ json(response, status, { error: { message } });
137
+ }
138
+ });
139
+ server.requestTimeout = 20000; server.headersTimeout = 10000; server.maxRequestsPerSocket = 100;
140
+ await new Promise<void>((resolve, reject) => { server.once("error", reject); server.listen(options.port ?? 43117, "127.0.0.1", () => { server.off("error", reject); resolve(); }); });
141
+ const address = server.address(); if (!address || typeof address === "string") throw new Error("No local dialer address.");
142
+ origin = `http://127.0.0.1:${address.port}`;
143
+ let closePromise: Promise<{ unsettled: string[] }> | null = null;
144
+ return { url: origin, launchUrl: `${origin}#${bootstrap}`, close: () => closePromise ??= (async () => {
145
+ closing = true; const deadline = Date.now() + 20000;
146
+ await Promise.allSettled([...calls].map(async id => { remember(await broker.hangup(id)); }));
147
+ while (calls.size && Date.now() < deadline) { await new Promise(resolve => setTimeout(resolve, 500)); await Promise.allSettled([...calls].map(own)); }
148
+ await new Promise<void>(resolve => { server.close(() => resolve()); server.closeIdleConnections?.(); });
149
+ return { unsettled: [...calls] };
150
+ })() };
151
+ }
@@ -0,0 +1,80 @@
1
+ import type { ManagedDialer, DialerSnapshot } from "./managedDialer.ts";
2
+ import type { TelephonyBrowserSessionCreate } from "../index.ts";
3
+
4
+ export interface DialerAppearance { name?: string; accent?: string; showBranding?: boolean; }
5
+ /** Framework-free, shadow-DOM widget. Import this module in a browser only.
6
+ * The host supplies an authenticated broker and durable journal to the controller. */
7
+ export class PyaiDialerElement extends HTMLElement {
8
+ private readonly root: ShadowRoot;
9
+ private dialer: ManagedDialer | null = null;
10
+ private inputFor: ((to: string) => TelephonyBrowserSessionCreate) | null = null;
11
+ private unsubscribe: (() => void) | null = null;
12
+ private wrapup: (() => Promise<void>) | null = null;
13
+ constructor() {
14
+ super(); this.root = this.attachShadow({ mode: "open" });
15
+ this.root.innerHTML = `<style>
16
+ :host{--dialer-accent:#5b55e7;display:block;max-width:380px;color:#202332;font:14px/1.5 system-ui,sans-serif}
17
+ *{box-sizing:border-box}section{background:#fff;border:1px solid #e7e8ef;border-radius:24px;padding:24px;box-shadow:0 16px 56px #25284c12}
18
+ header{display:flex;align-items:center;justify-content:space-between;gap:12px}h2{margin:0;font-size:16px;font-weight:650}.badge{font-size:11px;color:#667085;background:#f3f4f8;padding:4px 9px;border-radius:20px}
19
+ .status{display:flex;align-items:center;gap:7px;color:#667085;margin:20px 0 5px}.dot{width:7px;height:7px;border-radius:50%;background:#9a9dad}.dot.active{background:#12a777}
20
+ input{width:100%;border:0;border-bottom:1px solid #ececf2;padding:12px 0;font:500 26px/1.3 system-ui;letter-spacing:.5px;color:inherit;background:transparent}input:focus{outline:0;border-color:var(--dialer-accent)}
21
+ .hint{font-size:12px;color:#8c91a2;margin-top:8px}.keys{display:grid;grid-template-columns:repeat(3,1fr);gap:8px;margin:22px 0}.key{background:#f8f8fb;border:0;border-radius:14px;padding:9px;cursor:pointer;font:500 23px system-ui;color:inherit;min-height:57px}.key small{display:block;font-size:9px;letter-spacing:2px;color:#9296a5;margin-top:1px}.key:hover{background:#eeedf9}
22
+ .actions{display:flex;gap:8px}button{font:600 13px system-ui;cursor:pointer}button:focus-visible{outline:3px solid #bdb8ff;outline-offset:2px}.primary,.secondary{border:0;border-radius:13px;padding:14px 18px;min-height:46px}.primary{flex:1;color:white;background:var(--dialer-accent)}.primary.end{background:#da4055}.secondary{background:#f1f2f7;color:#535b70}button:disabled{opacity:.45;cursor:default}.error{color:#b42338;font-size:12px;min-height:18px;margin:12px 0 0}.privacy{font-size:11px;color:#8b91a1;margin:16px 0 0;text-align:center}
23
+ @media(prefers-color-scheme:dark){:host{color:#eaebf3}section{background:#191b26;border-color:#303341}.key{background:#252836}.key:hover,.secondary{background:#34364a}.badge{background:#282b39;color:#a7aec0}input{border-color:#36394a}.error{color:#ff9eaa}}
24
+ </style><section aria-label="Phone"><header><h2>Phone</h2><span class="badge">PyAI</span></header>
25
+ <div class="status" role="status" aria-live="polite"><span class="dot"></span><span data-status>Connect your workspace</span></div>
26
+ <input type="tel" inputmode="tel" autocomplete="tel" aria-label="Phone number" placeholder="+1 415 555 0100" maxlength="32"><div class="hint">Include the country code</div>
27
+ <div class="keys"></div><div class="actions"><button class="secondary" data-action="mute" disabled>Mute</button><button class="primary" data-action="call" disabled>Call</button><button class="secondary" data-action="recover" hidden>Recover</button></div>
28
+ <p class="error" role="alert"></p><p class="privacy">Calls and recordings stay in your workspace</p></section>`;
29
+ const letters = ["", "ABC", "DEF", "GHI", "JKL", "MNO", "PQRS", "TUV", "WXYZ", "", "+", ""];
30
+ "123456789*0#".split("").forEach((digit, i) => {
31
+ const button = document.createElement("button"); button.className = "key"; button.type = "button";
32
+ button.setAttribute("aria-label", digit); button.textContent = digit;
33
+ const small = document.createElement("small"); small.textContent = letters[i]!; button.append(small);
34
+ button.addEventListener("click", () => {
35
+ if (this.dialer?.current.state === "active") { this.dialer.sendDigits(digit); return; }
36
+ const input = this.root.querySelector("input")!; if (!input.disabled) input.value += digit;
37
+ }); this.root.querySelector(".keys")!.append(button);
38
+ });
39
+ this.root.querySelector("[data-action=call]")!.addEventListener("click", () => void this.act());
40
+ this.root.querySelector("[data-action=mute]")!.addEventListener("click", () => { if (this.dialer) this.dialer.mute(!this.dialer.current.muted); });
41
+ this.root.querySelector("[data-action=recover]")!.addEventListener("click", () => void this.run(() => this.dialer!.retrySetup()));
42
+ this.root.querySelector("input")!.addEventListener("keydown", event => { if (event.key === "Enter") void this.act(); });
43
+ }
44
+ bind(dialer: ManagedDialer, inputFor: (to: string) => TelephonyBrowserSessionCreate, appearance: DialerAppearance = {}, finishWrapup?: () => Promise<void>) {
45
+ if (this.dialer && this.dialer !== dialer && this.dialer.current.state !== "idle") throw new Error("Finish the current call before switching workspaces.");
46
+ this.unsubscribe?.(); this.dialer = dialer; this.inputFor = inputFor; this.wrapup = finishWrapup ?? (() => dialer.finishWrapup());
47
+ this.root.querySelector("h2")!.textContent = appearance.name ?? "Phone";
48
+ this.root.querySelector<HTMLElement>(".badge")!.hidden = appearance.showBranding === false;
49
+ if (appearance.accent && /^#[0-9a-f]{6}$/i.test(appearance.accent)) this.style.setProperty("--dialer-accent", appearance.accent);
50
+ this.unsubscribe = dialer.subscribe(snapshot => this.render(snapshot));
51
+ }
52
+ connectedCallback() { if (this.dialer && !this.unsubscribe) this.unsubscribe = this.dialer.subscribe(s => this.render(s)); }
53
+ disconnectedCallback() { this.unsubscribe?.(); this.unsubscribe = null; }
54
+ private render(snapshot: DialerSnapshot) {
55
+ const labels: Record<DialerSnapshot["state"], string> = { idle: "Ready to call", preparing: "Connecting…", ringing: "Ringing…", active: "Connected", stopping: "Confirming call ended…", unconfirmed: "Call needs recovery", wrapup: "Call finished" };
56
+ this.root.querySelector("[data-status]")!.textContent = labels[snapshot.state];
57
+ this.root.querySelector(".dot")!.classList.toggle("active", snapshot.state === "active");
58
+ this.root.querySelector("input")!.disabled = snapshot.state !== "idle";
59
+ const call = this.root.querySelector<HTMLButtonElement>("[data-action=call]")!;
60
+ call.disabled = snapshot.state === "stopping"; call.classList.toggle("end", !["idle", "wrapup"].includes(snapshot.state));
61
+ call.textContent = snapshot.state === "idle" ? "Call" : snapshot.state === "wrapup" ? "Done" : "End call";
62
+ const mute = this.root.querySelector<HTMLButtonElement>("[data-action=mute]")!;
63
+ mute.disabled = snapshot.state !== "active"; mute.textContent = snapshot.muted ? "Unmute" : "Mute";
64
+ mute.setAttribute("aria-pressed", String(snapshot.muted));
65
+ this.root.querySelector<HTMLButtonElement>("[data-action=recover]")!.hidden = !["unconfirmed", "stopping"].includes(snapshot.state);
66
+ this.root.querySelector(".error")!.textContent = snapshot.error ?? "";
67
+ }
68
+ private async run(action: () => Promise<void>) {
69
+ try { await action(); } catch (error) { this.root.querySelector(".error")!.textContent = error instanceof Error ? error.message : "Calling request failed."; }
70
+ }
71
+ private async act() {
72
+ if (!this.dialer || !this.inputFor) return;
73
+ await this.run(async () => {
74
+ if (this.dialer!.current.state === "wrapup") await this.wrapup!();
75
+ else if (this.dialer!.current.state !== "idle") await this.dialer!.stop();
76
+ else await this.dialer!.start(this.inputFor!(this.root.querySelector("input")!.value.replace(/[\s()-]/g, "")));
77
+ });
78
+ }
79
+ }
80
+ if (!customElements.get("pyai-dialer")) customElements.define("pyai-dialer", PyaiDialerElement);
@@ -0,0 +1,65 @@
1
+ import type { TelephonyBrowserSessionCreate } from "../index.ts";
2
+ import type { ManagedDialer } from "./managedDialer.ts";
3
+
4
+ export interface DialingContact {
5
+ id: string;
6
+ input: TelephonyBrowserSessionCreate;
7
+ priority?: number;
8
+ }
9
+ /** Sequential auto dialing and priority-based dynamic dialing. A session must
10
+ * be explicitly started in the foreground; no calls resume automatically after
11
+ * reload. The backend rechecks policy and capacity for every admission. */
12
+ export class DialingQueue {
13
+ private contacts: DialingContact[] = [];
14
+ private running = false;
15
+ private advancing = false;
16
+ private activeId: string | null = null;
17
+ private readonly dialer: ManagedDialer;
18
+ private readonly eligible: (contact: DialingContact) => Promise<boolean>;
19
+ constructor(dialer: ManagedDialer, eligible: (contact: DialingContact) => Promise<boolean>) {
20
+ this.dialer = dialer; this.eligible = eligible;
21
+ }
22
+ get current() { return { running: this.running, remaining: this.contacts.length, activeId: this.activeId }; }
23
+ async start(contacts: DialingContact[], mode: "auto" | "dynamic" = "auto") {
24
+ if (this.running || this.advancing || this.dialer.current.state !== "idle") throw new Error("Finish the current call before starting a queue.");
25
+ if (!contacts.length || contacts.length > 500 || new Set(contacts.map(c => c.id)).size !== contacts.length ||
26
+ contacts.some(c => !c.id || !/^\+[1-9]\d{6,14}$/.test(c.input.to) || !Number.isFinite(c.priority ?? 0))) throw new Error("Choose 1–500 unique contacts with valid destinations and priorities.");
27
+ this.contacts = structuredClone(contacts);
28
+ if (mode === "dynamic") this.contacts.sort((a, b) => (b.priority ?? 0) - (a.priority ?? 0));
29
+ this.running = true; await this.advance();
30
+ }
31
+ pause() { this.running = false; }
32
+ async resume() {
33
+ if (this.advancing) throw new Error("Queue admission is still pending.");
34
+ if (!this.contacts.length) return;
35
+ this.running = true;
36
+ if (this.dialer.current.state === "idle") await this.advance();
37
+ }
38
+ /** Explicit wrap-up acknowledgment gates the next admission. A local audio
39
+ * disconnect or a durable stop acknowledgment never advances the queue. */
40
+ async finishWrapup() {
41
+ await this.dialer.finishWrapup(); this.activeId = null;
42
+ if (this.running) await this.advance();
43
+ }
44
+ private async advance() {
45
+ if (this.advancing || !this.running || this.dialer.current.state !== "idle") return;
46
+ this.advancing = true;
47
+ try {
48
+ while (this.running && this.contacts.length) {
49
+ const contact = this.contacts[0]!;
50
+ const permitted = await this.eligible(structuredClone(contact));
51
+ if (!this.running) return;
52
+ if (!permitted) { this.contacts.shift(); continue; }
53
+ this.activeId = contact.id;
54
+ // Remove only once this intent has been durably admitted locally.
55
+ await this.dialer.start(contact.input);
56
+ this.contacts.shift(); return;
57
+ }
58
+ if (!this.contacts.length) this.running = false;
59
+ } catch (error) {
60
+ this.running = false;
61
+ // An unconfirmed call remains fenced inside ManagedDialer.
62
+ throw error;
63
+ } finally { this.advancing = false; }
64
+ }
65
+ }
@@ -0,0 +1,6 @@
1
+ export * from "./managedDialer.ts";
2
+ export * from "./dialingQueue.ts";
3
+ export * from "./indexedDbJournal.ts";
4
+ export * from "./voiceSdkAudio.ts";
5
+ export * from "./meetingRecorder.ts";
6
+ export * from "./meetingRecordingStore.ts";
@@ -0,0 +1,56 @@
1
+ import type { DialerIntent, DialerJournal } from "./managedDialer.ts";
2
+
3
+ /** Origin-local recovery journal. Browser capabilities never enter this store.
4
+ * Conflicting tabs cannot overwrite a different intent for the same scope. */
5
+ export class IndexedDbDialerJournal implements DialerJournal {
6
+ private readonly database: Promise<IDBDatabase>;
7
+ constructor(name = "pyai-dialer") {
8
+ this.database = new Promise((resolve, reject) => {
9
+ const request = indexedDB.open(name, 1);
10
+ request.onupgradeneeded = () => { request.result.createObjectStore("intents", { keyPath: "scope" }); };
11
+ request.onsuccess = () => { request.result.onversionchange = () => request.result.close(); resolve(request.result); };
12
+ request.onerror = () => reject(new Error("Calling recovery storage is unavailable."));
13
+ request.onblocked = () => reject(new Error("Close the older dialer tab to upgrade recovery storage."));
14
+ });
15
+ }
16
+ private async transaction<T>(mode: IDBTransactionMode, operation: (store: IDBObjectStore, result: (value: T) => void, fail: (message: string) => void) => void): Promise<T> {
17
+ const db = await this.database;
18
+ return new Promise((resolve, reject) => {
19
+ const tx = db.transaction("intents", mode); let value: T, failure: string | null = null;
20
+ tx.oncomplete = () => resolve(value);
21
+ tx.onerror = tx.onabort = () => reject(new Error(failure ?? "Calling recovery storage could not be updated."));
22
+ operation(tx.objectStore("intents"), next => { value = next; }, message => { failure = message; tx.abort(); });
23
+ });
24
+ }
25
+ read(scope: string): Promise<DialerIntent | null> {
26
+ return this.transaction("readonly", (store, result) => {
27
+ const request = store.get(scope);
28
+ request.onsuccess = () => result(request.result ? structuredClone(request.result) as DialerIntent : null);
29
+ });
30
+ }
31
+ write(intent: DialerIntent): Promise<void> {
32
+ const next = structuredClone(intent);
33
+ return this.transaction("readwrite", (store, result, fail) => {
34
+ const request = store.get(next.scope);
35
+ request.onsuccess = () => {
36
+ const prior = request.result as DialerIntent | undefined;
37
+ if (prior && (prior.key !== next.key || JSON.stringify(prior.input) !== JSON.stringify(next.input) ||
38
+ (prior.callId && prior.callId !== next.callId))) {
39
+ fail("Another call is already saved in this workspace. Recover it before dialing."); return;
40
+ }
41
+ if (prior?.stopping) next.stopping = true;
42
+ store.put(next); result(undefined);
43
+ };
44
+ });
45
+ }
46
+ clear(scope: string, key: string): Promise<void> {
47
+ return this.transaction("readwrite", (store, result, fail) => {
48
+ const request = store.get(scope);
49
+ request.onsuccess = () => {
50
+ const prior = request.result as DialerIntent | undefined;
51
+ if (prior && prior.key !== key) { fail("The saved call changed; recover it before clearing."); return; }
52
+ store.delete(scope); result(undefined);
53
+ };
54
+ });
55
+ }
56
+ }