@pyai/sdk 0.16.0 → 0.18.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.
- package/CLI.md +20 -0
- package/CLI.schema.json +2 -1
- package/README.md +3 -3
- package/dist/cli-omni-template.d.ts +2 -2
- package/dist/cli-omni-template.js +2 -2
- package/dist/cli.js +10 -8
- package/dist/dialer/appServer.d.ts +11 -1
- package/dist/dialer/appServer.js +224 -28
- package/dist/dialer/dialerElement.d.ts +2 -0
- package/dist/dialer/dialerElement.js +13 -4
- package/dist/dialer/dialingQueue.d.ts +3 -0
- package/dist/dialer/dialingQueue.js +63 -47
- package/dist/dialer/indexedDbJournal.d.ts +2 -0
- package/dist/dialer/indexedDbJournal.js +8 -0
- package/dist/dialer/managedDialer.d.ts +2 -1
- package/dist/dialer/managedDialer.js +7 -3
- package/dist/dialer/presentation.d.ts +19 -0
- package/dist/dialer/presentation.js +37 -0
- package/dist/dialer/serverBroker.js +10 -5
- package/dist/index.d.ts +188 -6
- package/dist/index.js +28 -3
- package/package.json +1 -1
- package/src/cli-omni-template.ts +2 -2
- package/src/cli.ts +9 -7
- package/src/dialer/app/app.css +6 -1
- package/src/dialer/app/app.html +4 -4
- package/src/dialer/app/app.js +92 -12
- package/src/dialer/app/incoming.js +107 -0
- package/src/dialer/appServer.ts +159 -27
- package/src/dialer/dialerElement.ts +14 -4
- package/src/dialer/dialingQueue.ts +51 -35
- package/src/dialer/indexedDbJournal.ts +6 -1
- package/src/dialer/managedDialer.ts +8 -4
- package/src/dialer/presentation.ts +38 -0
- package/src/dialer/serverBroker.ts +9 -4
- package/src/index.ts +114 -8
package/src/dialer/appServer.ts
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
/** Personal loopback companion. Project credentials stay in the local Node
|
|
2
2
|
* process; the renderer receives only the managed one-call capability. */
|
|
3
3
|
import { createServer, type IncomingMessage, type ServerResponse } from "node:http";
|
|
4
|
-
import { randomBytes, timingSafeEqual } from "node:crypto";
|
|
5
|
-
import { readFile } from "node:fs/promises";
|
|
4
|
+
import { randomBytes, timingSafeEqual, createHash, randomUUID } from "node:crypto";
|
|
5
|
+
import { readFile, mkdir, lstat, writeFile, rename, unlink } from "node:fs/promises";
|
|
6
6
|
import { createRequire } from "node:module";
|
|
7
7
|
import { homedir } from "node:os";
|
|
8
8
|
import { FileMeetingIntelligenceJournal } from "./fileMeetingIntelligenceJournal.ts";
|
|
@@ -13,14 +13,24 @@ import { Readable } from "node:stream";
|
|
|
13
13
|
import type { PyAI, TelephonyBrowserSessionCreate, TelephonyCall } from "../index.ts";
|
|
14
14
|
import { createServerDialerBroker } from "./serverBroker.ts";
|
|
15
15
|
import { dialerCallHandedOff } from "./managedDialer.ts";
|
|
16
|
+
import { defaultPresentation, validatePresentation, type DialerPresentation, type DialerPresentationInput } from "./presentation.ts";
|
|
17
|
+
export type { DialerPresentation, DialerPresentationInput } from "./presentation.ts";
|
|
16
18
|
|
|
17
19
|
export interface DialerAppOptions {
|
|
18
|
-
sdk
|
|
20
|
+
sdk?: PyAI;
|
|
21
|
+
receiveOnly?: boolean;
|
|
22
|
+
/** Trusted host configuration, never selected by an enrollment handoff. */
|
|
23
|
+
incomingApiOrigin?: string;
|
|
24
|
+
incomingFetch?: typeof fetch;
|
|
19
25
|
/** Derived by the trusted local host, never accepted from renderer input. */
|
|
20
26
|
userId: string;
|
|
21
27
|
scope: string;
|
|
22
28
|
name?: string;
|
|
23
29
|
whiteLabel?: boolean;
|
|
30
|
+
/** Validated defaults for this host; never changes calling permissions. */
|
|
31
|
+
presentation?: DialerPresentationInput;
|
|
32
|
+
/** Trusted host metadata path, never accepted through HTTP. */
|
|
33
|
+
presentationDirectory?: string;
|
|
24
34
|
/** Operator opt-in; the API independently enforces transfer activation. */
|
|
25
35
|
allowTransfers?: boolean;
|
|
26
36
|
port?: number;
|
|
@@ -32,10 +42,10 @@ export interface DialerAppOptions {
|
|
|
32
42
|
const terminal = (call: TelephonyCall) => ["completed", "failed", "canceled"].includes(call.status);
|
|
33
43
|
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));
|
|
34
44
|
const browserModules = new Set(["managedDialer", "dialingQueue", "indexedDbJournal", "voiceSdkAudio", "dialerElement", "meetingRecorder", "meetingRecordingStore", "meetingRecorderElement", "meetingIntelligence", "meetingIntelligenceElement"]);
|
|
35
|
-
const publicAssets = new Set(["/", "/app.js", "/app.css", "/manifest.webmanifest", "/icon.svg"]);
|
|
45
|
+
const publicAssets = new Set(["/", "/app.js", "/incoming.js", "/app.css", "/manifest.webmanifest", "/icon.svg"]);
|
|
36
46
|
const publicModule = (path: string) => { const match = /^\/modules\/([A-Za-z]+)\.js$/.exec(path); return match && browserModules.has(match[1]!) ? match[1] : null; };
|
|
37
47
|
async function packagedAsset(path: string): Promise<Uint8Array> {
|
|
38
|
-
if (path === "/" || path === "/app.js" || path === "/app.css" || path === "/manifest.webmanifest" || path === "/icon.svg") {
|
|
48
|
+
if (path === "/" || path === "/app.js" || path === "/incoming.js" || path === "/app.css" || path === "/manifest.webmanifest" || path === "/icon.svg") {
|
|
39
49
|
const file = path === "/" ? "app.html" : path.slice(1);
|
|
40
50
|
return readFile(new URL(`../../src/dialer/app/${file}`, import.meta.url));
|
|
41
51
|
}
|
|
@@ -65,34 +75,135 @@ async function body(request: IncomingMessage): Promise<Record<string, unknown>>
|
|
|
65
75
|
function json(response: ServerResponse, status: number, value: unknown) { response.writeHead(status, { "content-type": "application/json; charset=utf-8" }); response.end(JSON.stringify(value)); }
|
|
66
76
|
export async function startDialerApp(options: DialerAppOptions) {
|
|
67
77
|
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.");
|
|
68
|
-
const
|
|
78
|
+
const presentationDefaults = validatePresentation({ name: options.name ?? (options.whiteLabel ? "Phone" : "PyAI Phone"), white_label: options.whiteLabel === true, ...options.presentation });
|
|
79
|
+
const sdk=options.sdk; if(!sdk&&!options.receiveOnly)throw Error("A signed-in workspace or receive-only mode is required.");
|
|
80
|
+
const broker = sdk ? createServerDialerBroker(sdk, options.userId) : null, nonce = randomBytes(32).toString("base64url");
|
|
81
|
+
const requireBroker=()=>{if(!broker||options.receiveOnly)throw new AppError(403,"Sign in to a workspace before making calls.");return broker;};
|
|
69
82
|
const bootstrap = randomBytes(32).toString("base64url"), rendererToken = randomBytes(32).toString("base64url"), bootstrapExpires = Date.now() + 60000;
|
|
70
83
|
let bootstrapUsed = false;
|
|
71
84
|
let origin = "", closing = false; const calls = new Set<string>();
|
|
72
85
|
const remember = (call: TelephonyCall) => { if (terminal(call) || dialerCallHandedOff(call)) calls.delete(call.id); else calls.add(call.id); return call; };
|
|
73
|
-
const numbers = async () => (await
|
|
74
|
-
const own = async (id: string) => remember(await
|
|
86
|
+
const numbers = async () => !sdk||options.receiveOnly ? [] : (await sdk.telephony.numbers.list()).data.filter(number => number.status !== "released" && number.capabilities?.voice === true);
|
|
87
|
+
const own = async (id: string) => remember(await requireBroker().get(id));
|
|
75
88
|
const meetingJournal = new FileMeetingIntelligenceJournal(options.meetingJournalDirectory ?? join(homedir(), ".config", "pyai", "meetings"), options.scope);
|
|
76
89
|
let meetings: Promise<MeetingIntelligenceBroker> | null = null;
|
|
77
90
|
const meetingActions = new Set<Promise<unknown>>();
|
|
78
91
|
const getMeetings = () => meetings ??= (async () => {
|
|
79
|
-
|
|
92
|
+
if(!sdk||options.receiveOnly)throw new AppError(403,"Sign in to a workspace before sending a meeting.");
|
|
93
|
+
const me = await sdk.me();
|
|
80
94
|
await meetingJournal.sweep();
|
|
81
95
|
if (!me.org_id || !me.project_id || !me.key_id) throw new AppError(403, "Select a signed-in PyAI project before sending a meeting.");
|
|
82
|
-
return createServerMeetingIntelligence({ api: createSdkMeetingApi(
|
|
96
|
+
return createServerMeetingIntelligence({ api: createSdkMeetingApi(sdk), orgId: me.org_id, projectId: me.project_id, keyId: me.key_id, userId: options.userId, journal: meetingJournal });
|
|
83
97
|
})().catch(error => { meetings = null; throw error; });
|
|
84
98
|
const trackMeeting = async <T>(action: () => Promise<T>) => { const pending = action(); meetingActions.add(pending); try { return await pending; } finally { meetingActions.delete(pending); } };
|
|
85
|
-
const sweep = setInterval(() => { void meetingJournal.sweep().catch(() => {}); }, 3600000); sweep
|
|
99
|
+
const sweep = options.receiveOnly ? undefined : setInterval(() => { void meetingJournal.sweep().catch(() => {}); }, 3600000); sweep?.unref();
|
|
100
|
+
|
|
101
|
+
const providerOrigin=new URL(options.incomingApiOrigin??"https://api.pyai.com");
|
|
102
|
+
if(providerOrigin.protocol!=="https:"||providerOrigin.username||providerOrigin.password||providerOrigin.search||providerOrigin.hash||!["/","/v1","/v1/"].includes(providerOrigin.pathname))throw Error("A trusted HTTPS PyAI API origin is required.");
|
|
103
|
+
const incomingPath=/^\/public\/telephony\/desktop-endpoints\/([A-Za-z0-9_-]{1,128})\/([A-Za-z0-9_-]{1,128})\/([A-Za-z0-9_-]{1,128})\/redeem$/;
|
|
104
|
+
type Credentials={endpoint_id:string;org_id:string;project_id:string;user_id:string;label:string;access_token:string;expires_at:number;presence_token:string;heartbeat_interval_seconds:number;refresh_token:string;refresh_expires_at:number};
|
|
105
|
+
let registration:{path:string;credentials:Credentials;fingerprint:string;renew?:{token:string;key:string;started:number}}|null=null,incomingGeneration=0,incomingBusy=false;
|
|
106
|
+
const capability=(value:unknown)=>typeof value==="string"&&value.length>0&&value.length<=8192&&/^[\x21-\x7e]+$/.test(value);
|
|
107
|
+
const incomingPost=async(path:string,token:string,payload:unknown,key?:string)=>{
|
|
108
|
+
const reply=await(options.incomingFetch??fetch)(new URL(path,providerOrigin.origin),{method:"POST",headers:{authorization:`Bearer ${token}`,"content-type":"application/json",accept:"application/json",...(key?{"idempotency-key":key}:{})},body:JSON.stringify(payload),redirect:"error",cache:"no-store",signal:AbortSignal.timeout(10000)});
|
|
109
|
+
if(!reply.ok)throw new AppError([401,403,410].includes(reply.status)?401:502,"Incoming enrollment could not be confirmed. Reconnect from your workspace.");
|
|
110
|
+
return await reply.json() as Record<string,unknown>;
|
|
111
|
+
};
|
|
112
|
+
const credentials=(value:Record<string,unknown>,path:string,until?:number):Credentials=>{
|
|
113
|
+
const match=incomingPath.exec(path)!;const now=Date.now();
|
|
114
|
+
if(value.org_id!==match[1]||value.project_id!==match[2]||value.endpoint_id!==match[3]||typeof value.user_id!=="string"||!value.user_id||typeof value.label!=="string"||value.label.length>200||
|
|
115
|
+
!capability(value.access_token)||!capability(value.presence_token)||!capability(value.refresh_token)||value.heartbeat_interval_seconds!==15||
|
|
116
|
+
typeof value.expires_at!=="number"||!Number.isFinite(value.expires_at)||value.expires_at<=now||value.expires_at>now+310000||
|
|
117
|
+
typeof value.refresh_expires_at!=="number"||!Number.isFinite(value.refresh_expires_at)||value.refresh_expires_at<=now||value.refresh_expires_at>now+43205000||until!==undefined&&value.refresh_expires_at!==until)
|
|
118
|
+
throw new AppError(502,"Incoming enrollment authority could not be confirmed.");
|
|
119
|
+
return value as unknown as Credentials;
|
|
120
|
+
};
|
|
121
|
+
const publicCredentials=(c:Credentials)=>({access_token:c.access_token,expires_at:c.expires_at,session_expires_at:c.refresh_expires_at,heartbeat_interval_seconds:15,binding:{endpoint_id:c.endpoint_id,org_id:c.org_id,project_id:c.project_id,user_id:c.user_id,label:c.label}});
|
|
122
|
+
const logoutIncoming=async()=>{const current=registration;++incomingGeneration;registration=null;if(current)await incomingPost(current.path.replace(/redeem$/,"logout"),current.credentials.refresh_token,{});};
|
|
123
|
+
const incomingRoute=async(path:string,input:Record<string,unknown>)=>{
|
|
124
|
+
if(path==="/api/incoming/logout"){await logoutIncoming();return {registered:false,available:false};}
|
|
125
|
+
if(incomingBusy)throw new AppError(409,"Incoming enrollment is already being confirmed.");
|
|
126
|
+
incomingBusy=true;const generation=incomingGeneration;
|
|
127
|
+
try{
|
|
128
|
+
if(path==="/api/incoming/enroll"){
|
|
129
|
+
const redeemPath=input.redeem_path;
|
|
130
|
+
if(input.object!=="telephony.desktop_enrollment"||input.version!==1||typeof redeemPath!=="string"||!incomingPath.test(redeemPath)||incomingPath.exec(redeemPath)![3]!==input.endpoint_id||!capability(input.enrollment_token)||typeof input.expires_at!=="number"||!Number.isFinite(input.expires_at)||input.expires_at<=Date.now()||input.expires_at>Date.now()+125000)throw new AppError(400,"Paste a current desktop enrollment from your workspace.");
|
|
131
|
+
const fingerprint=createHash("sha256").update(redeemPath).update("\0").update(input.enrollment_token as string).digest("hex");
|
|
132
|
+
if(registration){if(registration.fingerprint===fingerprint)return publicCredentials(registration.credentials);throw new AppError(409,"Disconnect the current incoming workspace before connecting another.");}
|
|
133
|
+
const c=credentials(await incomingPost(redeemPath,input.enrollment_token as string,{}),redeemPath);
|
|
134
|
+
if(generation!==incomingGeneration){await incomingPost(redeemPath.replace(/redeem$/,"logout"),c.refresh_token,{}).catch(()=>{});throw new AppError(409,"Incoming enrollment was canceled.");}
|
|
135
|
+
registration={path:redeemPath,credentials:c,fingerprint};return publicCredentials(c);
|
|
136
|
+
}
|
|
137
|
+
const current=registration;if(!current||current.credentials.refresh_expires_at<=Date.now())throw new AppError(401,"Reconnect your workspace to receive calls.");
|
|
138
|
+
if(path==="/api/incoming/status"){if(Object.keys(input).length)throw new AppError(400,"Unexpected status fields.");return publicCredentials(current.credentials);}
|
|
139
|
+
if(path==="/api/incoming/presence"){
|
|
140
|
+
if(typeof input.ready!=="boolean"||Object.keys(input).length!==1)throw new AppError(400,"Incoming readiness must be confirmed.");
|
|
141
|
+
return await incomingPost(current.path.replace(/redeem$/,"heartbeat"),current.credentials.presence_token,{ready:input.ready});
|
|
142
|
+
}
|
|
143
|
+
if(path==="/api/incoming/renew"){
|
|
144
|
+
if(Object.keys(input).length)throw new AppError(400,"Unexpected renewal fields.");
|
|
145
|
+
current.renew??={token:current.credentials.refresh_token,key:randomUUID(),started:Date.now()};
|
|
146
|
+
if(Date.now()-current.renew.started>60000)throw new AppError(401,"Reconnect your workspace after the unconfirmed renewal.");
|
|
147
|
+
const c=credentials(await incomingPost(current.path.replace(/redeem$/,"refresh"),current.renew.token,{},current.renew.key),current.path,current.credentials.refresh_expires_at);
|
|
148
|
+
if(generation!==incomingGeneration){await incomingPost(current.path.replace(/redeem$/,"logout"),c.refresh_token,{}).catch(()=>{});throw new AppError(409,"Incoming enrollment was canceled.");}
|
|
149
|
+
registration={...current,credentials:c,renew:undefined};return publicCredentials(c);
|
|
150
|
+
}
|
|
151
|
+
throw new AppError(404,"No such incoming action.");
|
|
152
|
+
}finally{incomingBusy=false;}
|
|
153
|
+
};
|
|
154
|
+
|
|
155
|
+
// Resolve presentation ownership from authenticated backend identity, not
|
|
156
|
+
// renderer input, key fingerprints or decoded media-token claims.
|
|
157
|
+
let projectIdentity: Promise<{org_id:string;project_id:string}|null>|undefined;
|
|
158
|
+
const identity = async () => {
|
|
159
|
+
const incoming = registration?.credentials;
|
|
160
|
+
if (sdk) {
|
|
161
|
+
projectIdentity ??= sdk.me().then(me => typeof me.org_id === "string" && typeof me.project_id === "string" && me.org_id && me.project_id ? {org_id:me.org_id,project_id:me.project_id} : null).catch(() => { projectIdentity=undefined; return null; });
|
|
162
|
+
const project = await projectIdentity;
|
|
163
|
+
if (!project || incoming && (incoming.org_id!==project.org_id || incoming.project_id!==project.project_id)) return null;
|
|
164
|
+
return project;
|
|
165
|
+
}
|
|
166
|
+
return incoming ? {org_id:incoming.org_id,project_id:incoming.project_id} : null;
|
|
167
|
+
};
|
|
168
|
+
const presentationScope = (workspace:{org_id:string;project_id:string}) => createHash("sha256").update(providerOrigin.origin).update("\0").update(workspace.org_id).update("\0").update(workspace.project_id).digest("hex");
|
|
169
|
+
const presentationDirectory = options.presentationDirectory ?? join(homedir(), ".config", "pyai", "phone-presentation");
|
|
170
|
+
const presentationView = async () => {
|
|
171
|
+
const workspace=await identity(); let appearance=presentationDefaults;
|
|
172
|
+
if(workspace) {
|
|
173
|
+
const path=join(presentationDirectory,presentationScope(workspace)+".json");
|
|
174
|
+
try { const st=await lstat(path); if(st.isFile()&&!st.isSymbolicLink()&&st.size<=16384) appearance=validatePresentation(JSON.parse(await readFile(path,"utf8")),presentationDefaults); } catch { /* Missing/invalid presentation never changes calling authority. */ }
|
|
175
|
+
}
|
|
176
|
+
const stillCurrent=await identity();const unchanged=!!workspace&&!!stillCurrent&&presentationScope(workspace)===presentationScope(stillCurrent);
|
|
177
|
+
return {presentation:unchanged?appearance:presentationDefaults,save_enabled:unchanged,workspace:unchanged?workspace:null,workspace_scope:unchanged?presentationScope(workspace!):null,features_supported:{calls:!!sdk&&!options.receiveOnly,incoming:true,meetings:!!sdk&&!options.receiveOnly,power_queue:!!sdk&&!options.receiveOnly}};
|
|
178
|
+
};
|
|
179
|
+
const savePresentation = async (input:Record<string,unknown>) => {
|
|
180
|
+
if(Object.keys(input).length!==2||!("presentation" in input)||typeof input.workspace_scope!=="string")throw new AppError(400,"Save appearance for the currently connected workspace.");
|
|
181
|
+
let appearance:DialerPresentation; try { appearance=validatePresentation(input.presentation,presentationDefaults); } catch(error) { throw new AppError(400,(error as Error).message); }
|
|
182
|
+
const workspace=await identity(); if(!workspace) throw new AppError(409,"Connect one verified workspace before saving its appearance.");
|
|
183
|
+
const scope=presentationScope(workspace);if(input.workspace_scope!==scope)throw new AppError(409,"The connected workspace changed. Reload its appearance before saving.");
|
|
184
|
+
await mkdir(presentationDirectory,{recursive:true,mode:0o700});
|
|
185
|
+
const directory=await lstat(presentationDirectory);if(!directory.isDirectory()||directory.isSymbolicLink())throw new AppError(409,"The app appearance folder is unavailable.");
|
|
186
|
+
const target=join(presentationDirectory,scope+".json"),temp=join(presentationDirectory,"."+scope+"-"+randomUUID()+".tmp");
|
|
187
|
+
try {
|
|
188
|
+
await writeFile(temp,JSON.stringify(appearance)+"\n",{flag:"wx",mode:0o600});
|
|
189
|
+
const current=await identity();if(!current||presentationScope(current)!==scope)throw new AppError(409,"The connected workspace changed. Save again in the current workspace.");
|
|
190
|
+
await rename(temp,target);
|
|
191
|
+
}finally{await unlink(temp).catch(()=>{});}
|
|
192
|
+
return await presentationView();
|
|
193
|
+
};
|
|
86
194
|
|
|
87
195
|
const server = createServer(async (request, response) => {
|
|
88
196
|
response.setHeader("cache-control", "no-store"); response.setHeader("x-content-type-options", "nosniff"); response.setHeader("x-frame-options", "DENY");
|
|
89
197
|
response.setHeader("referrer-policy", "no-referrer");
|
|
90
|
-
response.setHeader("content-security-policy", "default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self'
|
|
198
|
+
response.setHeader("content-security-policy", "default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; manifest-src 'self' blob:; 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'");
|
|
91
199
|
try {
|
|
92
200
|
// Prevent DNS rebinding, cross-site loopback probes and requests to a
|
|
93
201
|
// publicly bound address. No CORS or wildcard-host mode exists.
|
|
94
|
-
|
|
95
|
-
|
|
202
|
+
const url = new URL(request.url ?? "/", origin || "http://127.0.0.1"), method = request.method ?? "GET";
|
|
203
|
+
// A top-level app link can open the public, secret-free shell. It cannot
|
|
204
|
+
// unlock a new browser profile or access any authenticated API route.
|
|
205
|
+
const publicShell = method === "GET" && !url.search && !url.hash && (publicAssets.has(url.pathname) || !!publicModule(url.pathname));
|
|
206
|
+
if (!origin || request.headers.host !== new URL(origin).host || (!publicShell && (request.headers["sec-fetch-site"] === "cross-site" || (request.headers.origin && request.headers.origin !== origin)))) throw new AppError(403, "Open your local phone app directly.");
|
|
96
207
|
if (url.search || url.hash) throw new AppError(400, "Unexpected request parameters.");
|
|
97
208
|
if (url.pathname === "/api/unlock" && method === "POST") {
|
|
98
209
|
if (request.headers.origin !== origin) throw new AppError(403, "Open the private local link from your terminal.");
|
|
@@ -106,9 +217,19 @@ export async function startDialerApp(options: DialerAppOptions) {
|
|
|
106
217
|
const supplied = request.headers["x-pyai-local-session"];
|
|
107
218
|
if (request.headers.origin !== origin || !secretMatches(supplied, nonce)) throw new AppError(403, "Local calling session changed. Reload the app.");
|
|
108
219
|
}
|
|
220
|
+
if(url.pathname==="/api/presentation"&&method==="GET")return json(response,200,await presentationView());
|
|
221
|
+
if(url.pathname==="/api/presentation"&&method==="PUT")return json(response,200,await savePresentation(await body(request)));
|
|
222
|
+
if(url.pathname==="/api/presentation/preview"&&method==="POST"){
|
|
223
|
+
try { const appearance=validatePresentation(await body(request),presentationDefaults);return json(response,200,{...(await presentationView()),presentation:appearance}); }
|
|
224
|
+
catch(error){if(error instanceof AppError)throw error;throw new AppError(400,(error as Error).message);}
|
|
225
|
+
}
|
|
226
|
+
if(url.pathname.startsWith("/api/incoming/")&&method==="POST"){
|
|
227
|
+
if(closing)throw new AppError(503,"The app is closing.");
|
|
228
|
+
return json(response,200,await incomingRoute(url.pathname,await body(request)));
|
|
229
|
+
}
|
|
109
230
|
if (url.pathname === "/api/config" && method === "GET") {
|
|
110
231
|
const owned = await numbers();
|
|
111
|
-
return json(response, 200, { name:
|
|
232
|
+
return json(response, 200, { name: presentationDefaults.name, white_label: presentationDefaults.white_label, presentation: presentationDefaults, transfers_enabled: !options.receiveOnly&&options.allowTransfers === true, receive_only: options.receiveOnly===true, scope: options.scope, user_id: options.userId, nonce,
|
|
112
233
|
numbers: owned.map(number => ({ id: number.id, phone_number: number.phone_number, country: number.country })) });
|
|
113
234
|
}
|
|
114
235
|
if (url.pathname === "/api/meetings/availability" && method === "GET") return json(response, 200, await (await getMeetings()).availability());
|
|
@@ -139,7 +260,7 @@ export async function startDialerApp(options: DialerAppOptions) {
|
|
|
139
260
|
const input = await body(request), key = request.headers["idempotency-key"];
|
|
140
261
|
if (input.transfer_enabled === true && options.allowTransfers !== true) throw new AppError(400, "Open this dialer with transfers enabled before starting a transferable call.");
|
|
141
262
|
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.");
|
|
142
|
-
const session = await
|
|
263
|
+
const session = await requireBroker().create(input as unknown as TelephonyBrowserSessionCreate, key); remember(session.call);
|
|
143
264
|
return json(response, 200, session);
|
|
144
265
|
}
|
|
145
266
|
const transferPath = /^\/api\/calls\/([A-Za-z0-9_-]{1,200})\/transfers(?:\/([A-Za-z0-9_-]{1,200})\/(complete|cancel))?$/.exec(url.pathname);
|
|
@@ -148,21 +269,22 @@ export async function startDialerApp(options: DialerAppOptions) {
|
|
|
148
269
|
const id = transferPath[1]!, transferId = transferPath[2], operation = transferPath[3];
|
|
149
270
|
await own(id); const input = await body(request);
|
|
150
271
|
if (transferId && (operation === "complete" || operation === "cancel"))
|
|
151
|
-
return json(response, 202, remember(await
|
|
272
|
+
return json(response, 202, remember(await requireBroker().transfers));
|
|
152
273
|
const key = request.headers["idempotency-key"];
|
|
153
274
|
if (typeof key !== "string" || typeof input.to !== "string" || !/^\+[1-9]\d{6,14}$/.test(input.to) || !["warm", "cold"].includes(String(input.mode)))
|
|
154
275
|
throw new AppError(400, "Choose a transfer destination, mode and retry key.");
|
|
155
|
-
return json(response, 202, remember(await
|
|
276
|
+
return json(response, 202, remember(await requireBroker().transfers!.create(id, { to: input.to, mode: input.mode as "warm" | "cold" }, key)));
|
|
156
277
|
}
|
|
157
278
|
const callPath = /^\/api\/calls\/([A-Za-z0-9_-]{1,200})(?:\/(hangup|recording))?$/.exec(url.pathname);
|
|
158
279
|
if (callPath) {
|
|
159
280
|
const id = callPath[1]!, operation = callPath[2]; await own(id);
|
|
160
281
|
if (method === "GET" && !operation) return json(response, 200, await own(id));
|
|
161
|
-
if (method === "POST" && operation === "hangup") { await body(request); return json(response, 202, remember(await
|
|
282
|
+
if (method === "POST" && operation === "hangup") { await body(request); return json(response, 202, remember(await requireBroker().hangup(id))); }
|
|
162
283
|
if (method === "GET" && operation === "recording") {
|
|
163
284
|
const range = request.headers.range;
|
|
164
285
|
if (range && !/^bytes=\d+-\d*$/.test(range)) throw new AppError(400, "Invalid recording range.");
|
|
165
|
-
|
|
286
|
+
if (!sdk) throw new AppError(403, "Sign in to a workspace before reading recordings.");
|
|
287
|
+
const recording = await sdk.telephony.calls.recording(id, range ? { range } : {});
|
|
166
288
|
response.statusCode = recording.status;
|
|
167
289
|
for (const header of ["content-type", "content-length", "content-range", "accept-ranges"]) { const value = recording.headers.get(header); if (value) response.setHeader(header, value); }
|
|
168
290
|
response.setHeader("content-disposition", `attachment; filename="Call-${id}.wav"`);
|
|
@@ -174,22 +296,31 @@ export async function startDialerApp(options: DialerAppOptions) {
|
|
|
174
296
|
if (method !== "GET" || url.pathname.startsWith("/api/")) throw new AppError(404, "No such dialer operation.");
|
|
175
297
|
if (url.pathname === "/manifest.webmanifest") {
|
|
176
298
|
response.writeHead(200, { "content-type": "application/manifest+json" });
|
|
177
|
-
return response.end(JSON.stringify({ id: "/", name:
|
|
299
|
+
return response.end(JSON.stringify({ id: "/", name: presentationDefaults.name, short_name: presentationDefaults.name.slice(0,24), start_url: "/", scope: "/", display: "standalone", background_color: "#f6f6fa", theme_color: presentationDefaults.primary_color, icons: [{ src: "/icon.svg", sizes: "any", type: "image/svg+xml", purpose: "any maskable" }] }));
|
|
178
300
|
}
|
|
179
|
-
if (url.pathname === "/icon.svg" &&
|
|
180
|
-
const monogram =
|
|
301
|
+
if (url.pathname === "/icon.svg" && presentationDefaults.white_label) {
|
|
302
|
+
const monogram = presentationDefaults.name.match(/[A-Za-z]/)?.[0]?.toUpperCase() ?? "P";
|
|
181
303
|
response.writeHead(200, { "content-type": "image/svg+xml" });
|
|
182
|
-
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="
|
|
304
|
+
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="${presentationDefaults.primary_color}"/><text x="256" y="360" text-anchor="middle" font-family="system-ui,sans-serif" font-size="320" fill="white">${monogram}</text></svg>`);
|
|
183
305
|
}
|
|
184
306
|
if (!publicAssets.has(url.pathname) && url.pathname !== "/voice-sdk.js" && !publicModule(url.pathname)) throw new AppError(404, "No such dialer asset.");
|
|
185
|
-
|
|
307
|
+
let bytes = await (options.assets?.read ?? packagedAsset)(url.pathname).catch(() => { throw new AppError(404, "No such dialer asset."); });
|
|
308
|
+
if(url.pathname==="/") {
|
|
309
|
+
const htmlEscape=(text:string)=>text.replace(/[&<>"']/g,char=>({"&":"&","<":"<",">":">",'"':""","'":"'"}[char]!));
|
|
310
|
+
// Only validated public presentation defaults enter the shell. No
|
|
311
|
+
// backend identity, session capability, nonce or credential is embedded.
|
|
312
|
+
const name=htmlEscape(presentationDefaults.name);
|
|
313
|
+
let html=Buffer.from(bytes).toString("utf8").replace("<body>",'<body data-presentation-defaults="'+htmlEscape(JSON.stringify(presentationDefaults))+'">').replace("<title>PyAI Phone</title>","<title>"+name+"</title>").replace('aria-label="PyAI Phone"','aria-label="'+name+'"').replace("<span data-brand>PyAI Phone</span>","<span data-brand>"+name+"</span>");
|
|
314
|
+
if(presentationDefaults.white_label)html=html.replace("Powered by PyAI","Private workspace").replace("stored in your PyAI workspace","stored in your workspace");
|
|
315
|
+
bytes=Buffer.from(html);
|
|
316
|
+
}
|
|
186
317
|
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";
|
|
187
318
|
response.writeHead(200, { "content-type": type }); response.end(bytes);
|
|
188
319
|
} catch (error) {
|
|
189
320
|
if (response.headersSent) { response.destroy(); return; }
|
|
190
321
|
// Never reflect upstream responses, credentials, URLs, or stack traces.
|
|
191
322
|
const status = error instanceof AppError ? error.status : typeof (error as { status?: number })?.status === "number" ? (error as { status: number }).status : 502;
|
|
192
|
-
const message = error instanceof AppError ? error.message : status === 401 || status === 403 ? "Your
|
|
323
|
+
const message = error instanceof AppError ? error.message : status === 401 || status === 403 ? "Your calling workspace does not permit this operation. Check your signed-in profile and calling policy." : "The calling workspace could not confirm this operation. Recover the same call before trying another.";
|
|
193
324
|
json(response, status, { error: { message } });
|
|
194
325
|
}
|
|
195
326
|
});
|
|
@@ -200,8 +331,9 @@ export async function startDialerApp(options: DialerAppOptions) {
|
|
|
200
331
|
let closePromise: Promise<{ unsettled: string[] }> | null = null;
|
|
201
332
|
return { url: origin, launchUrl: `${origin}#${bootstrap}`, close: () => closePromise ??= (async () => {
|
|
202
333
|
closing = true; clearInterval(sweep); const deadline = Date.now() + 20000;
|
|
334
|
+
await logoutIncoming().catch(()=>{});
|
|
203
335
|
await Promise.allSettled([...meetingActions]);
|
|
204
|
-
await Promise.allSettled([...calls].map(async id => { remember(await
|
|
336
|
+
await Promise.allSettled([...calls].map(async id => { remember(await requireBroker().hangup(id)); }));
|
|
205
337
|
while (calls.size && Date.now() < deadline) { await new Promise(resolve => setTimeout(resolve, 500)); await Promise.allSettled([...calls].map(own)); }
|
|
206
338
|
await new Promise<void>(resolve => { server.close(() => resolve()); server.closeIdleConnections?.(); });
|
|
207
339
|
return { unsettled: [...calls] };
|
|
@@ -19,7 +19,8 @@ export class PyaiDialerElement extends HTMLElement {
|
|
|
19
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
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
21
|
.hint,.transfer-help{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}
|
|
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);color:var(--dialer-accent-ink,#fff)}.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
|
+
:host([compact]){max-width:none;font-size:13px}:host([compact]) section{padding:16px;border-radius:15px;box-shadow:none}:host([compact]) .status{margin-top:12px}:host([compact]) input{font-size:24px;padding:10px 0}:host([compact]) .keys{gap:6px;margin:15px 0}:host([compact]) .key{min-height:45px;padding:5px;font-size:21px;border-radius:10px}:host([compact]) .primary,:host([compact]) .secondary{min-height:40px;padding:10px 12px;border-radius:10px}:host([compact]) .privacy{display:none}:host([compact]) .error:empty{display:none}
|
|
23
24
|
@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
25
|
</style><section aria-label="Phone"><header><h2>Phone</h2><span class="badge">PyAI</span></header>
|
|
25
26
|
<div class="status" role="status" aria-live="polite"><span class="dot"></span><span data-status>Connect your workspace</span></div>
|
|
@@ -53,10 +54,19 @@ export class PyaiDialerElement extends HTMLElement {
|
|
|
53
54
|
bind(dialer: ManagedDialer, inputFor: (to: string) => TelephonyBrowserSessionCreate, appearance: DialerAppearance = {}, finishWrapup?: () => Promise<void>) {
|
|
54
55
|
if (this.dialer && this.dialer !== dialer && this.dialer.current.state !== "idle") throw new Error("Finish the current call before switching workspaces.");
|
|
55
56
|
this.unsubscribe?.(); this.dialer = dialer; this.inputFor = inputFor; this.wrapup = finishWrapup ?? (() => dialer.finishWrapup());
|
|
57
|
+
this.setAppearance(appearance);
|
|
58
|
+
this.unsubscribe = dialer.subscribe(snapshot => this.render(snapshot));
|
|
59
|
+
}
|
|
60
|
+
/** Presentation can change without replacing the active call controller. */
|
|
61
|
+
setAppearance(appearance: DialerAppearance = {}) {
|
|
56
62
|
this.root.querySelector("h2")!.textContent = appearance.name ?? "Phone";
|
|
57
63
|
this.root.querySelector<HTMLElement>(".badge")!.hidden = appearance.showBranding === false;
|
|
58
|
-
if (appearance.accent && /^#[0-9a-f]{6}$/i.test(appearance.accent))
|
|
59
|
-
|
|
64
|
+
if (appearance.accent && /^#[0-9a-f]{6}$/i.test(appearance.accent)) {
|
|
65
|
+
this.style.setProperty("--dialer-accent", appearance.accent);
|
|
66
|
+
const channels=[1,3,5].map(offset=>parseInt(appearance.accent!.slice(offset,offset+2),16)/255).map(v=>v<=.04045?v/12.92:((v+.055)/1.055)**2.4);
|
|
67
|
+
const luminance=.2126*channels[0]!+.7152*channels[1]!+.0722*channels[2]!;
|
|
68
|
+
this.style.setProperty("--dialer-accent-ink",luminance>.179?"#111827":"#FFFFFF");
|
|
69
|
+
}
|
|
60
70
|
}
|
|
61
71
|
connectedCallback() { if (this.dialer && !this.unsubscribe) this.unsubscribe = this.dialer.subscribe(s => this.render(s)); }
|
|
62
72
|
disconnectedCallback() { this.unsubscribe?.(); this.unsubscribe = null; }
|
|
@@ -88,7 +98,7 @@ export class PyaiDialerElement extends HTMLElement {
|
|
|
88
98
|
const complete = this.root.querySelector<HTMLButtonElement>("[data-action=complete-transfer]")!;
|
|
89
99
|
complete.hidden = transfer?.mode !== "warm" || transfer.status !== "ready"; complete.disabled = Boolean(snapshot.transferPending);
|
|
90
100
|
const cancel = this.root.querySelector<HTMLButtonElement>("[data-action=cancel-transfer]")!;
|
|
91
|
-
cancel.hidden = transfer
|
|
101
|
+
cancel.hidden = !transfer || !pending; cancel.disabled = Boolean(snapshot.transferPending || ["completing", "canceling"].includes(transfer?.status ?? ""));
|
|
92
102
|
this.root.querySelector<HTMLButtonElement>("[data-action=recover-transfer]")!.hidden = !snapshot.transferPending;
|
|
93
103
|
}
|
|
94
104
|
private async run(action: () => Promise<void>) {
|
|
@@ -17,6 +17,8 @@ export interface DialingQueueState {
|
|
|
17
17
|
parallelLines: number;
|
|
18
18
|
}
|
|
19
19
|
export interface DialingQueueJournal {
|
|
20
|
+
/** Serialize recovery and admission across clients sharing both journals. */
|
|
21
|
+
runExclusive?<T>(scope: string, action: () => Promise<T>): Promise<T>;
|
|
20
22
|
read(scope: string): Promise<DialingQueueState | null>;
|
|
21
23
|
/** Compare-and-swap; null means no queue may already exist. */
|
|
22
24
|
write(state: DialingQueueState, expectedRevision: number | null): Promise<void>;
|
|
@@ -47,20 +49,31 @@ export class DialingQueue {
|
|
|
47
49
|
if (this.persistence) return this.persistence.journal.write(next, this.state?.revision ?? null).then(() => { this.state = next; });
|
|
48
50
|
this.state = next;
|
|
49
51
|
}
|
|
52
|
+
private withAdmissionLock<T>(action: () => Promise<T>): Promise<T> {
|
|
53
|
+
const persistence = this.persistence;
|
|
54
|
+
return persistence?.journal.runExclusive
|
|
55
|
+
? persistence.journal.runExclusive(persistence.scope, action) : action();
|
|
56
|
+
}
|
|
50
57
|
async restore() {
|
|
51
58
|
if (this.initialized) return;
|
|
52
59
|
if (!this.dialer.restored) throw new Error("Restore the calling journal before restoring the queue.");
|
|
53
|
-
const
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
60
|
+
const persistence = this.persistence!;
|
|
61
|
+
await this.withAdmissionLock(async () => {
|
|
62
|
+
if (this.initialized) return;
|
|
63
|
+
const saved = await persistence.journal.read(persistence.scope);
|
|
64
|
+
if (saved && saved.scope !== persistence.scope) throw new Error("Saved queue belongs to another workspace.");
|
|
65
|
+
this.state = saved ? structuredClone(saved) : null;
|
|
66
|
+
if (this.state?.active.length) {
|
|
67
|
+
// Read the call journal after taking the same lock used to save the
|
|
68
|
+
// active batch and its call intent. A cached idle tab cannot decide
|
|
69
|
+
// that an admission in progress was abandoned.
|
|
70
|
+
await this.dialer.restore();
|
|
71
|
+
const context = this.dialer.queueContext;
|
|
72
|
+
const same = context?.key === this.state.key && JSON.stringify(context.contactIds) === JSON.stringify(this.state.active.map(c => c.id));
|
|
73
|
+
if (!same) await this.commit({ ...this.state, contacts: this.state.wrapped ? this.state.contacts : [...this.state.active, ...this.state.contacts], active: [], wrapped: false });
|
|
74
|
+
}
|
|
75
|
+
this.initialized = true;
|
|
76
|
+
});
|
|
64
77
|
}
|
|
65
78
|
async start(contacts: DialingContact[], mode: "auto" | "dynamic" | "parallel" = "auto", options: { parallelLines?: number } = {}) {
|
|
66
79
|
if (!this.initialized) throw new Error("Restore the calling queue before dialing.");
|
|
@@ -122,34 +135,37 @@ export class DialingQueue {
|
|
|
122
135
|
if (this.running) await this.advance();
|
|
123
136
|
}
|
|
124
137
|
private async advance() {
|
|
125
|
-
if (this.advancing || !this.running || this.dialer.current.state !== "idle" || !this.state) return;
|
|
138
|
+
if (this.advancing || !this.running || this.dialer.current.state !== "idle" || !this.state || this.state.active.length) return;
|
|
126
139
|
this.advancing = true;
|
|
127
140
|
try {
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
const
|
|
141
|
+
await this.withAdmissionLock(async () => {
|
|
142
|
+
if (!this.running || this.dialer.current.state !== "idle" || this.state!.active.length) return;
|
|
143
|
+
const batch: DialingContact[] = [], skipped = new Set<string>();
|
|
144
|
+
for (const contact of this.state!.contacts) {
|
|
145
|
+
if (!this.running || batch.length >= this.state!.parallelLines) break;
|
|
146
|
+
const permitted = await this.eligible(structuredClone(contact));
|
|
147
|
+
if (!this.running) return;
|
|
148
|
+
if (permitted) batch.push(contact); else skipped.add(contact.id);
|
|
149
|
+
}
|
|
132
150
|
if (!this.running) return;
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
await this.commit({ ...this.state, contacts: this.state.contacts.filter(contact => !skipped.has(contact.id) && !selected.has(contact.id)), active: batch, wrapped: false });
|
|
138
|
-
if (!this.running) {
|
|
139
|
-
await this.commit({ ...this.state!, contacts: [...batch, ...this.state!.contacts], active: [] }); return;
|
|
140
|
-
}
|
|
141
|
-
if (batch.length) {
|
|
142
|
-
const first = batch[0]!;
|
|
143
|
-
const { to: _to, destinations: _destinations, transfer_enabled: _transferEnabled, ...common } = first.input;
|
|
144
|
-
const intent: TelephonyBrowserSessionCreate = batch.length === 1 ? first.input : { ...common, destinations: batch.map(contact => contact.input.to!) };
|
|
145
|
-
try { await this.dialer.start(intent, { key: this.state!.key, contactIds: batch.map(contact => contact.id) }); }
|
|
146
|
-
catch (error) {
|
|
147
|
-
// No persisted call means admission did not happen. Retain the group
|
|
148
|
-
// for an explicit retry, including storage denial before network I/O.
|
|
149
|
-
if (this.dialer.queueContext?.key !== this.state!.key) await this.commit({ ...this.state!, contacts: [...batch, ...this.state!.contacts], active: [] });
|
|
150
|
-
throw error;
|
|
151
|
+
const selected = new Set(batch.map(contact => contact.id));
|
|
152
|
+
await this.commit({ ...this.state!, contacts: this.state!.contacts.filter(contact => !skipped.has(contact.id) && !selected.has(contact.id)), active: batch, wrapped: false });
|
|
153
|
+
if (!this.running) {
|
|
154
|
+
await this.commit({ ...this.state!, contacts: [...batch, ...this.state!.contacts], active: [] }); return;
|
|
151
155
|
}
|
|
152
|
-
|
|
156
|
+
if (batch.length) {
|
|
157
|
+
const first = batch[0]!;
|
|
158
|
+
const { to: _to, destinations: _destinations, transfer_enabled: _transferEnabled, ...common } = first.input;
|
|
159
|
+
const intent: TelephonyBrowserSessionCreate = batch.length === 1 ? first.input : { ...common, destinations: batch.map(contact => contact.input.to!) };
|
|
160
|
+
try { await this.dialer.start(intent, { key: this.state!.key, contactIds: batch.map(contact => contact.id) }); }
|
|
161
|
+
catch (error) {
|
|
162
|
+
// No persisted call means admission did not happen. Retain the group
|
|
163
|
+
// for an explicit retry, including storage denial before network I/O.
|
|
164
|
+
if (this.dialer.queueContext?.key !== this.state!.key) await this.commit({ ...this.state!, contacts: [...batch, ...this.state!.contacts], active: [] });
|
|
165
|
+
throw error;
|
|
166
|
+
}
|
|
167
|
+
} else if (!this.state!.contacts.length) this.running = false;
|
|
168
|
+
});
|
|
153
169
|
} catch (error) { this.running = false; throw error; }
|
|
154
170
|
finally { this.advancing = false; }
|
|
155
171
|
}
|
|
@@ -77,7 +77,7 @@ export class IndexedDbDialerJournal implements DialerJournal {
|
|
|
77
77
|
* stale tabs from replacing or advancing another tab's saved contact list. */
|
|
78
78
|
export class IndexedDbDialingQueueJournal implements DialingQueueJournal {
|
|
79
79
|
private readonly database: Promise<IDBDatabase>;
|
|
80
|
-
constructor(name = "pyai-dialing-queue") {
|
|
80
|
+
constructor(private readonly name = "pyai-dialing-queue") {
|
|
81
81
|
this.database = new Promise((resolve, reject) => {
|
|
82
82
|
const request = indexedDB.open(name, 1);
|
|
83
83
|
request.onupgradeneeded = () => { request.result.createObjectStore("queues", { keyPath: "scope" }); };
|
|
@@ -86,6 +86,11 @@ export class IndexedDbDialingQueueJournal implements DialingQueueJournal {
|
|
|
86
86
|
request.onblocked = () => reject(new Error("Close the older dialer tab to open queue storage."));
|
|
87
87
|
});
|
|
88
88
|
}
|
|
89
|
+
async runExclusive<T>(scope: string, action: () => Promise<T>): Promise<T> {
|
|
90
|
+
const locks = globalThis.navigator?.locks;
|
|
91
|
+
if (!locks) throw new Error("This browser cannot safely recover a saved calling queue.");
|
|
92
|
+
return await locks.request(JSON.stringify(["pyai-dialing-queue", this.name, scope]), action);
|
|
93
|
+
}
|
|
89
94
|
async read(scope: string): Promise<DialingQueueState | null> {
|
|
90
95
|
const db = await this.database;
|
|
91
96
|
return new Promise((resolve, reject) => {
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { TelephonyBrowserSession, TelephonyBrowserSessionCreate, TelephonyCall } from "../index.ts";
|
|
1
|
+
import type { TelephonyBrowserSession, TelephonyBrowserSessionCreate, TelephonyCall, TelephonyCallControl } from "../index.ts";
|
|
2
2
|
|
|
3
3
|
/** Implement on your server using PyAI's telephony client. The browser receives
|
|
4
4
|
* a single-call capability, never an organization key or carrier credential. */
|
|
@@ -7,6 +7,7 @@ export interface DialerBroker {
|
|
|
7
7
|
get(callId: string): Promise<TelephonyCall>;
|
|
8
8
|
hangup(callId: string): Promise<TelephonyCall>;
|
|
9
9
|
setHold?(callId: string, held: boolean, key: string): Promise<TelephonyCall>;
|
|
10
|
+
sendDtmf?(callId: string, digits: string, key: string): Promise<TelephonyCallControl>;
|
|
10
11
|
transfers?: {
|
|
11
12
|
create(callId: string, input: { to: string; mode: "warm" | "cold" }, key: string): Promise<TelephonyCall>;
|
|
12
13
|
complete(callId: string, transferId: string): Promise<TelephonyCall>;
|
|
@@ -45,7 +46,7 @@ export interface DialerSnapshot {
|
|
|
45
46
|
const terminal = (call: TelephonyCall) => ["completed", "failed", "canceled"].includes(call.status);
|
|
46
47
|
/** A durable handoff keeps its original room after the browser goes away. */
|
|
47
48
|
export const dialerCallHandedOff = (call: TelephonyCall) => call.transfer_enabled === true && Boolean(call.transfers?.some(transfer =>
|
|
48
|
-
transfer.status === "completed" || transfer.mode === "cold" &&
|
|
49
|
+
transfer.status === "completed" || transfer.mode === "cold" && transfer.status === "completing"));
|
|
49
50
|
|
|
50
51
|
/** One immutable workspace/user scope per instance. Setup and stop retain the
|
|
51
52
|
* original intent through lost acknowledgments, reloads and audio failures. */
|
|
@@ -90,7 +91,9 @@ export class ManagedDialer {
|
|
|
90
91
|
}
|
|
91
92
|
async restore(): Promise<void> {
|
|
92
93
|
return this.exclusive(async () => {
|
|
93
|
-
|
|
94
|
+
// Queue recovery may have waited for another tab to save an admission
|
|
95
|
+
// after this instance first loaded an empty journal.
|
|
96
|
+
if (this.initialized && this.intent) return;
|
|
94
97
|
const saved = await this.journal.read(this.scope);
|
|
95
98
|
if (saved && saved.scope !== this.scope) throw new Error("Saved call belongs to another workspace.");
|
|
96
99
|
this.intent = saved ? structuredClone(saved) : null;
|
|
@@ -258,7 +261,8 @@ export class ManagedDialer {
|
|
|
258
261
|
if (!this.intent?.transfer?.id || !this.broker.transfers) throw new Error("Recover the transfer identity first.");
|
|
259
262
|
const transfer = this.snapshot.call?.transfers?.find(item => item.id === this.intent!.transfer!.id);
|
|
260
263
|
if (command === "complete" && transfer?.status !== "ready") throw new Error("Wait until the transfer target has joined.");
|
|
261
|
-
if (this.intent.transfer.mode !== "warm") throw new Error("Cold transfers complete automatically.");
|
|
264
|
+
if (this.intent.transfer.mode !== "warm" && command === "complete") throw new Error("Cold transfers complete automatically.");
|
|
265
|
+
if (command === "cancel" && ["completing", "completed"].includes(transfer?.status ?? "")) throw new Error("The handoff has started. Check its status instead of canceling it.");
|
|
262
266
|
if (this.intent.transfer.command && this.intent.transfer.command !== command) throw new Error("Recover the saved transfer command first.");
|
|
263
267
|
const next = structuredClone(this.intent); next.transfer!.command = command;
|
|
264
268
|
await this.journal.write(next); this.intent = next;
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/** Presentation metadata only. No credentials, network origins or calling policy. */
|
|
2
|
+
export interface DialerPresentation {
|
|
3
|
+
name: string;
|
|
4
|
+
white_label: boolean;
|
|
5
|
+
primary_color: string;
|
|
6
|
+
logo_png: string | null;
|
|
7
|
+
layout: "compact" | "comfortable";
|
|
8
|
+
features: { calls: boolean; incoming: boolean; meetings: boolean; power_queue: boolean };
|
|
9
|
+
}
|
|
10
|
+
export type DialerPresentationInput = Partial<Omit<DialerPresentation, "features">> & { features?: Partial<DialerPresentation["features"]> };
|
|
11
|
+
const featureNames = ["calls", "incoming", "meetings", "power_queue"] as const;
|
|
12
|
+
export const defaultPresentation: DialerPresentation = {
|
|
13
|
+
name: "PyAI Phone", white_label: false, primary_color: "#5C4DE4", logo_png: null,
|
|
14
|
+
layout: "compact", features: { calls: true, incoming: true, meetings: true, power_queue: true },
|
|
15
|
+
};
|
|
16
|
+
const record = (value: unknown): value is Record<string, unknown> => !!value && typeof value === "object" && !Array.isArray(value);
|
|
17
|
+
export function validatePresentation(value: unknown, defaults: DialerPresentation = defaultPresentation): DialerPresentation {
|
|
18
|
+
if (!record(value) || Object.keys(value).some(key => !["name", "white_label", "primary_color", "logo_png", "layout", "features"].includes(key))) throw Error("Use only the app appearance settings.");
|
|
19
|
+
const result = { ...defaults, ...value, features: { ...defaults.features } } as DialerPresentation;
|
|
20
|
+
if (typeof result.name !== "string" || !result.name.trim() || result.name.trim().length > 60 || /[\x00-\x1f\x7f]/.test(result.name)) throw Error("Use an app name of 1–60 characters.");
|
|
21
|
+
result.name = result.name.trim();
|
|
22
|
+
if (result.white_label && result.name === "PyAI Phone") result.name = "Phone";
|
|
23
|
+
if (typeof result.white_label !== "boolean" || typeof result.primary_color !== "string" || !/^#[0-9a-f]{6}$/i.test(result.primary_color) || !["compact", "comfortable"].includes(result.layout)) throw Error("Choose a valid app color, layout and branding setting.");
|
|
24
|
+
result.primary_color = result.primary_color.toUpperCase();
|
|
25
|
+
if (result.logo_png !== null) {
|
|
26
|
+
if (typeof result.logo_png !== "string" || !/^data:image\/png;base64,[A-Za-z0-9+/]+={0,2}$/.test(result.logo_png)) throw Error("Choose a PNG logo, not a URL or an SVG.");
|
|
27
|
+
const encoded = result.logo_png.slice(22), bytes = Buffer.from(encoded, "base64");
|
|
28
|
+
if (bytes.length > 8192 || bytes.length < 33 || bytes.toString("base64") !== encoded || !bytes.subarray(0, 8).equals(Buffer.from([137,80,78,71,13,10,26,10])) || bytes.toString("ascii",12,16)!=="IHDR" || bytes.readUInt32BE(8)!==13 || bytes.readUInt32BE(16)<1 || bytes.readUInt32BE(20)<1 || bytes.readUInt32BE(16)>512 || bytes.readUInt32BE(20)>512) throw Error("Choose a PNG logo up to 8 KB and 512×512 pixels.");
|
|
29
|
+
}
|
|
30
|
+
if (value.features !== undefined) {
|
|
31
|
+
if (!record(value.features) || Object.keys(value.features).some(key => !(featureNames as readonly string[]).includes(key))) throw Error("Choose only the supported app sections.");
|
|
32
|
+
for (const key of featureNames) if (key in value.features) {
|
|
33
|
+
if (typeof value.features[key] !== "boolean") throw Error("App section visibility must be on or off.");
|
|
34
|
+
result.features[key] = value.features[key] as boolean;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
return result;
|
|
38
|
+
}
|