@pyai/sdk 0.17.0 → 0.18.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,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 } 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.js";
@@ -11,13 +11,14 @@ import { dirname, join } from "node:path";
11
11
  import { Readable } from "node:stream";
12
12
  import { createServerDialerBroker } from "./serverBroker.js";
13
13
  import { dialerCallHandedOff } from "./managedDialer.js";
14
+ import { validatePresentation } from "./presentation.js";
14
15
  const terminal = (call) => ["completed", "failed", "canceled"].includes(call.status);
15
16
  const secretMatches = (input, expected) => typeof input === "string" && /^[A-Za-z0-9_-]+$/.test(input) && input.length === expected.length && timingSafeEqual(Buffer.from(input), Buffer.from(expected));
16
17
  const browserModules = new Set(["managedDialer", "dialingQueue", "indexedDbJournal", "voiceSdkAudio", "dialerElement", "meetingRecorder", "meetingRecordingStore", "meetingRecorderElement", "meetingIntelligence", "meetingIntelligenceElement"]);
17
- const publicAssets = new Set(["/", "/app.js", "/app.css", "/manifest.webmanifest", "/icon.svg"]);
18
+ const publicAssets = new Set(["/", "/app.js", "/incoming.js", "/app.css", "/manifest.webmanifest", "/icon.svg"]);
18
19
  const publicModule = (path) => { const match = /^\/modules\/([A-Za-z]+)\.js$/.exec(path); return match && browserModules.has(match[1]) ? match[1] : null; };
19
20
  async function packagedAsset(path) {
20
- if (path === "/" || path === "/app.js" || path === "/app.css" || path === "/manifest.webmanifest" || path === "/icon.svg") {
21
+ if (path === "/" || path === "/app.js" || path === "/incoming.js" || path === "/app.css" || path === "/manifest.webmanifest" || path === "/icon.svg") {
21
22
  const file = path === "/" ? "app.html" : path.slice(1);
22
23
  return readFile(new URL(`../../src/dialer/app/${file}`, import.meta.url));
23
24
  }
@@ -60,7 +61,13 @@ function json(response, status, value) { response.writeHead(status, { "content-t
60
61
  export async function startDialerApp(options) {
61
62
  if (!options.scope.trim() || !options.userId.trim() || !Number.isInteger(options.port ?? 43117) || (options.port ?? 43117) < 0 || (options.port ?? 43117) > 65535)
62
63
  throw new Error("A local user, scope and valid port are required.");
63
- const broker = createServerDialerBroker(options.sdk, options.userId), nonce = randomBytes(32).toString("base64url");
64
+ const presentationDefaults = validatePresentation({ name: options.name ?? (options.whiteLabel ? "Phone" : "PyAI Phone"), white_label: options.whiteLabel === true, ...options.presentation });
65
+ const sdk = options.sdk;
66
+ if (!sdk && !options.receiveOnly)
67
+ throw Error("A signed-in workspace or receive-only mode is required.");
68
+ const broker = sdk ? createServerDialerBroker(sdk, options.userId) : null, nonce = randomBytes(32).toString("base64url");
69
+ const requireBroker = () => { if (!broker || options.receiveOnly)
70
+ throw new AppError(403, "Sign in to a workspace before making calls."); return broker; };
64
71
  const bootstrap = randomBytes(32).toString("base64url"), rendererToken = randomBytes(32).toString("base64url"), bootstrapExpires = Date.now() + 60000;
65
72
  let bootstrapUsed = false;
66
73
  let origin = "", closing = false;
@@ -69,17 +76,19 @@ export async function startDialerApp(options) {
69
76
  calls.delete(call.id);
70
77
  else
71
78
  calls.add(call.id); return call; };
72
- const numbers = async () => (await options.sdk.telephony.numbers.list()).data.filter(number => number.status !== "released" && number.capabilities?.voice === true);
73
- const own = async (id) => remember(await broker.get(id));
79
+ const numbers = async () => !sdk || options.receiveOnly ? [] : (await sdk.telephony.numbers.list()).data.filter(number => number.status !== "released" && number.capabilities?.voice === true);
80
+ const own = async (id) => remember(await requireBroker().get(id));
74
81
  const meetingJournal = new FileMeetingIntelligenceJournal(options.meetingJournalDirectory ?? join(homedir(), ".config", "pyai", "meetings"), options.scope);
75
82
  let meetings = null;
76
83
  const meetingActions = new Set();
77
84
  const getMeetings = () => meetings ??= (async () => {
78
- const me = await options.sdk.me();
85
+ if (!sdk || options.receiveOnly)
86
+ throw new AppError(403, "Sign in to a workspace before sending a meeting.");
87
+ const me = await sdk.me();
79
88
  await meetingJournal.sweep();
80
89
  if (!me.org_id || !me.project_id || !me.key_id)
81
90
  throw new AppError(403, "Select a signed-in PyAI project before sending a meeting.");
82
- return createServerMeetingIntelligence({ api: createSdkMeetingApi(options.sdk), orgId: me.org_id, projectId: me.project_id, keyId: me.key_id, userId: options.userId, journal: meetingJournal });
91
+ return createServerMeetingIntelligence({ api: createSdkMeetingApi(sdk), orgId: me.org_id, projectId: me.project_id, keyId: me.key_id, userId: options.userId, journal: meetingJournal });
83
92
  })().catch(error => { meetings = null; throw error; });
84
93
  const trackMeeting = async (action) => { const pending = action(); meetingActions.add(pending); try {
85
94
  return await pending;
@@ -87,20 +96,174 @@ export async function startDialerApp(options) {
87
96
  finally {
88
97
  meetingActions.delete(pending);
89
98
  } };
90
- const sweep = setInterval(() => { void meetingJournal.sweep().catch(() => { }); }, 3600000);
91
- sweep.unref();
99
+ const sweep = options.receiveOnly ? undefined : setInterval(() => { void meetingJournal.sweep().catch(() => { }); }, 3600000);
100
+ sweep?.unref();
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))
103
+ throw Error("A trusted HTTPS PyAI API origin is required.");
104
+ 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$/;
105
+ let registration = null, incomingGeneration = 0, incomingBusy = false;
106
+ const capability = (value) => typeof value === "string" && value.length > 0 && value.length <= 8192 && /^[\x21-\x7e]+$/.test(value);
107
+ const incomingPost = async (path, token, payload, key) => {
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)
110
+ throw new AppError([401, 403, 410].includes(reply.status) ? 401 : 502, "Incoming enrollment could not be confirmed. Reconnect from your workspace.");
111
+ return await reply.json();
112
+ };
113
+ const credentials = (value, path, until) => {
114
+ const match = incomingPath.exec(path);
115
+ const now = Date.now();
116
+ 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 ||
117
+ !capability(value.access_token) || !capability(value.presence_token) || !capability(value.refresh_token) || value.heartbeat_interval_seconds !== 15 ||
118
+ typeof value.expires_at !== "number" || !Number.isFinite(value.expires_at) || value.expires_at <= now || value.expires_at > now + 310000 ||
119
+ 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)
120
+ throw new AppError(502, "Incoming enrollment authority could not be confirmed.");
121
+ return value;
122
+ };
123
+ const publicCredentials = (c) => ({ 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 } });
124
+ const logoutIncoming = async () => { const current = registration; ++incomingGeneration; registration = null; if (current)
125
+ await incomingPost(current.path.replace(/redeem$/, "logout"), current.credentials.refresh_token, {}); };
126
+ const incomingRoute = async (path, input) => {
127
+ if (path === "/api/incoming/logout") {
128
+ await logoutIncoming();
129
+ return { registered: false, available: false };
130
+ }
131
+ if (incomingBusy)
132
+ throw new AppError(409, "Incoming enrollment is already being confirmed.");
133
+ incomingBusy = true;
134
+ const generation = incomingGeneration;
135
+ try {
136
+ if (path === "/api/incoming/enroll") {
137
+ const redeemPath = input.redeem_path;
138
+ 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)
139
+ throw new AppError(400, "Paste a current desktop enrollment from your workspace.");
140
+ const fingerprint = createHash("sha256").update(redeemPath).update("\0").update(input.enrollment_token).digest("hex");
141
+ if (registration) {
142
+ if (registration.fingerprint === fingerprint)
143
+ return publicCredentials(registration.credentials);
144
+ throw new AppError(409, "Disconnect the current incoming workspace before connecting another.");
145
+ }
146
+ const c = credentials(await incomingPost(redeemPath, input.enrollment_token, {}), redeemPath);
147
+ if (generation !== incomingGeneration) {
148
+ await incomingPost(redeemPath.replace(/redeem$/, "logout"), c.refresh_token, {}).catch(() => { });
149
+ throw new AppError(409, "Incoming enrollment was canceled.");
150
+ }
151
+ registration = { path: redeemPath, credentials: c, fingerprint };
152
+ return publicCredentials(c);
153
+ }
154
+ const current = registration;
155
+ if (!current || current.credentials.refresh_expires_at <= Date.now())
156
+ throw new AppError(401, "Reconnect your workspace to receive calls.");
157
+ if (path === "/api/incoming/status") {
158
+ if (Object.keys(input).length)
159
+ throw new AppError(400, "Unexpected status fields.");
160
+ return publicCredentials(current.credentials);
161
+ }
162
+ if (path === "/api/incoming/presence") {
163
+ if (typeof input.ready !== "boolean" || Object.keys(input).length !== 1)
164
+ throw new AppError(400, "Incoming readiness must be confirmed.");
165
+ return await incomingPost(current.path.replace(/redeem$/, "heartbeat"), current.credentials.presence_token, { ready: input.ready });
166
+ }
167
+ if (path === "/api/incoming/renew") {
168
+ if (Object.keys(input).length)
169
+ throw new AppError(400, "Unexpected renewal fields.");
170
+ current.renew ??= { token: current.credentials.refresh_token, key: randomUUID(), started: Date.now() };
171
+ if (Date.now() - current.renew.started > 60000)
172
+ throw new AppError(401, "Reconnect your workspace after the unconfirmed renewal.");
173
+ const c = credentials(await incomingPost(current.path.replace(/redeem$/, "refresh"), current.renew.token, {}, current.renew.key), current.path, current.credentials.refresh_expires_at);
174
+ if (generation !== incomingGeneration) {
175
+ await incomingPost(current.path.replace(/redeem$/, "logout"), c.refresh_token, {}).catch(() => { });
176
+ throw new AppError(409, "Incoming enrollment was canceled.");
177
+ }
178
+ registration = { ...current, credentials: c, renew: undefined };
179
+ return publicCredentials(c);
180
+ }
181
+ throw new AppError(404, "No such incoming action.");
182
+ }
183
+ finally {
184
+ incomingBusy = false;
185
+ }
186
+ };
187
+ // Resolve presentation ownership from authenticated backend identity, not
188
+ // renderer input, key fingerprints or decoded media-token claims.
189
+ let projectIdentity;
190
+ const identity = async () => {
191
+ const incoming = registration?.credentials;
192
+ if (sdk) {
193
+ 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; });
194
+ const project = await projectIdentity;
195
+ if (!project || incoming && (incoming.org_id !== project.org_id || incoming.project_id !== project.project_id))
196
+ return null;
197
+ return project;
198
+ }
199
+ return incoming ? { org_id: incoming.org_id, project_id: incoming.project_id } : null;
200
+ };
201
+ const presentationScope = (workspace) => createHash("sha256").update(providerOrigin.origin).update("\0").update(workspace.org_id).update("\0").update(workspace.project_id).digest("hex");
202
+ const presentationDirectory = options.presentationDirectory ?? join(homedir(), ".config", "pyai", "phone-presentation");
203
+ const presentationView = async () => {
204
+ const workspace = await identity();
205
+ let appearance = presentationDefaults;
206
+ if (workspace) {
207
+ const path = join(presentationDirectory, presentationScope(workspace) + ".json");
208
+ try {
209
+ const st = await lstat(path);
210
+ if (st.isFile() && !st.isSymbolicLink() && st.size <= 16384)
211
+ appearance = validatePresentation(JSON.parse(await readFile(path, "utf8")), presentationDefaults);
212
+ }
213
+ catch { /* Missing/invalid presentation never changes calling authority. */ }
214
+ }
215
+ const stillCurrent = await identity();
216
+ const unchanged = !!workspace && !!stillCurrent && presentationScope(workspace) === presentationScope(stillCurrent);
217
+ 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 } };
218
+ };
219
+ const savePresentation = async (input) => {
220
+ if (Object.keys(input).length !== 2 || !("presentation" in input) || typeof input.workspace_scope !== "string")
221
+ throw new AppError(400, "Save appearance for the currently connected workspace.");
222
+ let appearance;
223
+ try {
224
+ appearance = validatePresentation(input.presentation, presentationDefaults);
225
+ }
226
+ catch (error) {
227
+ throw new AppError(400, error.message);
228
+ }
229
+ const workspace = await identity();
230
+ if (!workspace)
231
+ throw new AppError(409, "Connect one verified workspace before saving its appearance.");
232
+ const scope = presentationScope(workspace);
233
+ if (input.workspace_scope !== scope)
234
+ throw new AppError(409, "The connected workspace changed. Reload its appearance before saving.");
235
+ await mkdir(presentationDirectory, { recursive: true, mode: 0o700 });
236
+ const directory = await lstat(presentationDirectory);
237
+ if (!directory.isDirectory() || directory.isSymbolicLink())
238
+ throw new AppError(409, "The app appearance folder is unavailable.");
239
+ const target = join(presentationDirectory, scope + ".json"), temp = join(presentationDirectory, "." + scope + "-" + randomUUID() + ".tmp");
240
+ try {
241
+ await writeFile(temp, JSON.stringify(appearance) + "\n", { flag: "wx", mode: 0o600 });
242
+ const current = await identity();
243
+ if (!current || presentationScope(current) !== scope)
244
+ throw new AppError(409, "The connected workspace changed. Save again in the current workspace.");
245
+ await rename(temp, target);
246
+ }
247
+ finally {
248
+ await unlink(temp).catch(() => { });
249
+ }
250
+ return await presentationView();
251
+ };
92
252
  const server = createServer(async (request, response) => {
93
253
  response.setHeader("cache-control", "no-store");
94
254
  response.setHeader("x-content-type-options", "nosniff");
95
255
  response.setHeader("x-frame-options", "DENY");
96
256
  response.setHeader("referrer-policy", "no-referrer");
97
- 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'");
257
+ 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'");
98
258
  try {
99
259
  // Prevent DNS rebinding, cross-site loopback probes and requests to a
100
260
  // publicly bound address. No CORS or wildcard-host mode exists.
101
- if (!origin || request.headers.host !== new URL(origin).host || request.headers["sec-fetch-site"] === "cross-site" || (request.headers.origin && request.headers.origin !== origin))
102
- throw new AppError(403, "Open the local PyAI dialer directly.");
103
- const url = new URL(request.url ?? "/", origin), method = request.method ?? "GET";
261
+ const url = new URL(request.url ?? "/", origin || "http://127.0.0.1"), method = request.method ?? "GET";
262
+ // A top-level app link can open the public, secret-free shell. It cannot
263
+ // unlock a new browser profile or access any authenticated API route.
264
+ const publicShell = method === "GET" && !url.search && !url.hash && (publicAssets.has(url.pathname) || !!publicModule(url.pathname));
265
+ if (!origin || request.headers.host !== new URL(origin).host || (!publicShell && (request.headers["sec-fetch-site"] === "cross-site" || (request.headers.origin && request.headers.origin !== origin))))
266
+ throw new AppError(403, "Open your local phone app directly.");
104
267
  if (url.search || url.hash)
105
268
  throw new AppError(400, "Unexpected request parameters.");
106
269
  if (url.pathname === "/api/unlock" && method === "POST") {
@@ -119,9 +282,29 @@ export async function startDialerApp(options) {
119
282
  if (request.headers.origin !== origin || !secretMatches(supplied, nonce))
120
283
  throw new AppError(403, "Local calling session changed. Reload the app.");
121
284
  }
285
+ if (url.pathname === "/api/presentation" && method === "GET")
286
+ return json(response, 200, await presentationView());
287
+ if (url.pathname === "/api/presentation" && method === "PUT")
288
+ return json(response, 200, await savePresentation(await body(request)));
289
+ if (url.pathname === "/api/presentation/preview" && method === "POST") {
290
+ try {
291
+ const appearance = validatePresentation(await body(request), presentationDefaults);
292
+ return json(response, 200, { ...(await presentationView()), presentation: appearance });
293
+ }
294
+ catch (error) {
295
+ if (error instanceof AppError)
296
+ throw error;
297
+ throw new AppError(400, error.message);
298
+ }
299
+ }
300
+ if (url.pathname.startsWith("/api/incoming/") && method === "POST") {
301
+ if (closing)
302
+ throw new AppError(503, "The app is closing.");
303
+ return json(response, 200, await incomingRoute(url.pathname, await body(request)));
304
+ }
122
305
  if (url.pathname === "/api/config" && method === "GET") {
123
306
  const owned = await numbers();
124
- return json(response, 200, { name: options.name ?? (options.whiteLabel ? "Phone" : "PyAI Phone"), white_label: options.whiteLabel === true, transfers_enabled: options.allowTransfers === true, scope: options.scope, user_id: options.userId, nonce,
307
+ 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,
125
308
  numbers: owned.map(number => ({ id: number.id, phone_number: number.phone_number, country: number.country })) });
126
309
  }
127
310
  if (url.pathname === "/api/meetings/availability" && method === "GET")
@@ -172,7 +355,7 @@ export async function startDialerApp(options) {
172
355
  throw new AppError(400, "Open this dialer with transfers enabled before starting a transferable call.");
173
356
  if (typeof key !== "string" || typeof input.from_number_id !== "string" || !(await numbers()).some(number => number.id === input.from_number_id))
174
357
  throw new AppError(400, "Choose an owned voice number and a calling retry key.");
175
- const session = await broker.create(input, key);
358
+ const session = await requireBroker().create(input, key);
176
359
  remember(session.call);
177
360
  return json(response, 200, session);
178
361
  }
@@ -184,11 +367,11 @@ export async function startDialerApp(options) {
184
367
  await own(id);
185
368
  const input = await body(request);
186
369
  if (transferId && (operation === "complete" || operation === "cancel"))
187
- return json(response, 202, remember(await broker.transfers[operation](id, transferId)));
370
+ return json(response, 202, remember(await requireBroker().transfers[operation](id, transferId)));
188
371
  const key = request.headers["idempotency-key"];
189
372
  if (typeof key !== "string" || typeof input.to !== "string" || !/^\+[1-9]\d{6,14}$/.test(input.to) || !["warm", "cold"].includes(String(input.mode)))
190
373
  throw new AppError(400, "Choose a transfer destination, mode and retry key.");
191
- return json(response, 202, remember(await broker.transfers.create(id, { to: input.to, mode: input.mode }, key)));
374
+ return json(response, 202, remember(await requireBroker().transfers.create(id, { to: input.to, mode: input.mode }, key)));
192
375
  }
193
376
  const callPath = /^\/api\/calls\/([A-Za-z0-9_-]{1,200})(?:\/(hangup|recording))?$/.exec(url.pathname);
194
377
  if (callPath) {
@@ -198,13 +381,15 @@ export async function startDialerApp(options) {
198
381
  return json(response, 200, await own(id));
199
382
  if (method === "POST" && operation === "hangup") {
200
383
  await body(request);
201
- return json(response, 202, remember(await broker.hangup(id)));
384
+ return json(response, 202, remember(await requireBroker().hangup(id)));
202
385
  }
203
386
  if (method === "GET" && operation === "recording") {
204
387
  const range = request.headers.range;
205
388
  if (range && !/^bytes=\d+-\d*$/.test(range))
206
389
  throw new AppError(400, "Invalid recording range.");
207
- const recording = await options.sdk.telephony.calls.recording(id, range ? { range } : {});
390
+ if (!sdk)
391
+ throw new AppError(403, "Sign in to a workspace before reading recordings.");
392
+ const recording = await sdk.telephony.calls.recording(id, range ? { range } : {});
208
393
  response.statusCode = recording.status;
209
394
  for (const header of ["content-type", "content-length", "content-range", "accept-ranges"]) {
210
395
  const value = recording.headers.get(header);
@@ -225,16 +410,26 @@ export async function startDialerApp(options) {
225
410
  throw new AppError(404, "No such dialer operation.");
226
411
  if (url.pathname === "/manifest.webmanifest") {
227
412
  response.writeHead(200, { "content-type": "application/manifest+json" });
228
- 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" }] }));
413
+ 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" }] }));
229
414
  }
230
- if (url.pathname === "/icon.svg" && options.whiteLabel) {
231
- const monogram = (options.name ?? "Phone").match(/[A-Za-z]/)?.[0]?.toUpperCase() ?? "P";
415
+ if (url.pathname === "/icon.svg" && presentationDefaults.white_label) {
416
+ const monogram = presentationDefaults.name.match(/[A-Za-z]/)?.[0]?.toUpperCase() ?? "P";
232
417
  response.writeHead(200, { "content-type": "image/svg+xml" });
233
- 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>`);
418
+ 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>`);
234
419
  }
235
420
  if (!publicAssets.has(url.pathname) && url.pathname !== "/voice-sdk.js" && !publicModule(url.pathname))
236
421
  throw new AppError(404, "No such dialer asset.");
237
- const bytes = await (options.assets?.read ?? packagedAsset)(url.pathname).catch(() => { throw new AppError(404, "No such dialer asset."); });
422
+ let bytes = await (options.assets?.read ?? packagedAsset)(url.pathname).catch(() => { throw new AppError(404, "No such dialer asset."); });
423
+ if (url.pathname === "/") {
424
+ const htmlEscape = (text) => text.replace(/[&<>"']/g, char => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" }[char]));
425
+ // Only validated public presentation defaults enter the shell. No
426
+ // backend identity, session capability, nonce or credential is embedded.
427
+ const name = htmlEscape(presentationDefaults.name);
428
+ 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>");
429
+ if (presentationDefaults.white_label)
430
+ html = html.replace("Powered by PyAI", "Private workspace").replace("stored in your PyAI workspace", "stored in your workspace");
431
+ bytes = Buffer.from(html);
432
+ }
238
433
  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";
239
434
  response.writeHead(200, { "content-type": type });
240
435
  response.end(bytes);
@@ -246,7 +441,7 @@ export async function startDialerApp(options) {
246
441
  }
247
442
  // Never reflect upstream responses, credentials, URLs, or stack traces.
248
443
  const status = error instanceof AppError ? error.status : typeof error?.status === "number" ? error.status : 502;
249
- 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.";
444
+ 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.";
250
445
  json(response, status, { error: { message } });
251
446
  }
252
447
  });
@@ -263,8 +458,9 @@ export async function startDialerApp(options) {
263
458
  closing = true;
264
459
  clearInterval(sweep);
265
460
  const deadline = Date.now() + 20000;
461
+ await logoutIncoming().catch(() => { });
266
462
  await Promise.allSettled([...meetingActions]);
267
- await Promise.allSettled([...calls].map(async (id) => { remember(await broker.hangup(id)); }));
463
+ await Promise.allSettled([...calls].map(async (id) => { remember(await requireBroker().hangup(id)); }));
268
464
  while (calls.size && Date.now() < deadline) {
269
465
  await new Promise(resolve => setTimeout(resolve, 500));
270
466
  await Promise.allSettled([...calls].map(own));
@@ -15,6 +15,8 @@ export declare class PyaiDialerElement extends HTMLElement {
15
15
  private wrapup;
16
16
  constructor();
17
17
  bind(dialer: ManagedDialer, inputFor: (to: string) => TelephonyBrowserSessionCreate, appearance?: DialerAppearance, finishWrapup?: () => Promise<void>): void;
18
+ /** Presentation can change without replacing the active call controller. */
19
+ setAppearance(appearance?: DialerAppearance): void;
18
20
  connectedCallback(): void;
19
21
  disconnectedCallback(): void;
20
22
  private render;
@@ -16,7 +16,8 @@ export class PyaiDialerElement extends HTMLElement {
16
16
  .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}
17
17
  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)}
18
18
  .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}
19
- .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}
19
+ .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}
20
+ :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}
20
21
  @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}}
21
22
  </style><section aria-label="Phone"><header><h2>Phone</h2><span class="badge">PyAI</span></header>
22
23
  <div class="status" role="status" aria-live="polite"><span class="dot"></span><span data-status>Connect your workspace</span></div>
@@ -67,11 +68,19 @@ export class PyaiDialerElement extends HTMLElement {
67
68
  this.dialer = dialer;
68
69
  this.inputFor = inputFor;
69
70
  this.wrapup = finishWrapup ?? (() => dialer.finishWrapup());
71
+ this.setAppearance(appearance);
72
+ this.unsubscribe = dialer.subscribe(snapshot => this.render(snapshot));
73
+ }
74
+ /** Presentation can change without replacing the active call controller. */
75
+ setAppearance(appearance = {}) {
70
76
  this.root.querySelector("h2").textContent = appearance.name ?? "Phone";
71
77
  this.root.querySelector(".badge").hidden = appearance.showBranding === false;
72
- if (appearance.accent && /^#[0-9a-f]{6}$/i.test(appearance.accent))
78
+ if (appearance.accent && /^#[0-9a-f]{6}$/i.test(appearance.accent)) {
73
79
  this.style.setProperty("--dialer-accent", appearance.accent);
74
- this.unsubscribe = dialer.subscribe(snapshot => this.render(snapshot));
80
+ 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);
81
+ const luminance = .2126 * channels[0] + .7152 * channels[1] + .0722 * channels[2];
82
+ this.style.setProperty("--dialer-accent-ink", luminance > .179 ? "#111827" : "#FFFFFF");
83
+ }
75
84
  }
76
85
  connectedCallback() { if (this.dialer && !this.unsubscribe)
77
86
  this.unsubscribe = this.dialer.subscribe(s => this.render(s)); }
@@ -16,6 +16,8 @@ export interface DialingQueueState {
16
16
  parallelLines: number;
17
17
  }
18
18
  export interface DialingQueueJournal {
19
+ /** Serialize recovery and admission across clients sharing both journals. */
20
+ runExclusive?<T>(scope: string, action: () => Promise<T>): Promise<T>;
19
21
  read(scope: string): Promise<DialingQueueState | null>;
20
22
  /** Compare-and-swap; null means no queue may already exist. */
21
23
  write(state: DialingQueueState, expectedRevision: number | null): Promise<void>;
@@ -45,6 +47,7 @@ export declare class DialingQueue {
45
47
  parallelLines: number;
46
48
  };
47
49
  private commit;
50
+ private withAdmissionLock;
48
51
  restore(): Promise<void>;
49
52
  start(contacts: DialingContact[], mode?: "auto" | "dynamic" | "parallel", options?: {
50
53
  parallelLines?: number;
@@ -29,24 +29,36 @@ export class DialingQueue {
29
29
  return this.persistence.journal.write(next, this.state?.revision ?? null).then(() => { this.state = next; });
30
30
  this.state = next;
31
31
  }
32
+ withAdmissionLock(action) {
33
+ const persistence = this.persistence;
34
+ return persistence?.journal.runExclusive
35
+ ? persistence.journal.runExclusive(persistence.scope, action) : action();
36
+ }
32
37
  async restore() {
33
38
  if (this.initialized)
34
39
  return;
35
40
  if (!this.dialer.restored)
36
41
  throw new Error("Restore the calling journal before restoring the queue.");
37
- const saved = await this.persistence.journal.read(this.persistence.scope);
38
- if (saved && saved.scope !== this.persistence.scope)
39
- throw new Error("Saved queue belongs to another workspace.");
40
- this.state = saved ? structuredClone(saved) : null;
41
- // A crash before call-intent persistence is safe to retry. A crash after
42
- // wrap-up persistence must never put the completed contacts back in line.
43
- if (this.state?.active.length) {
44
- const context = this.dialer.queueContext;
45
- const same = context?.key === this.state.key && JSON.stringify(context.contactIds) === JSON.stringify(this.state.active.map(c => c.id));
46
- if (!same)
47
- await this.commit({ ...this.state, contacts: this.state.wrapped ? this.state.contacts : [...this.state.active, ...this.state.contacts], active: [], wrapped: false });
48
- }
49
- this.initialized = true;
42
+ const persistence = this.persistence;
43
+ await this.withAdmissionLock(async () => {
44
+ if (this.initialized)
45
+ return;
46
+ const saved = await persistence.journal.read(persistence.scope);
47
+ if (saved && saved.scope !== persistence.scope)
48
+ throw new Error("Saved queue belongs to another workspace.");
49
+ this.state = saved ? structuredClone(saved) : null;
50
+ if (this.state?.active.length) {
51
+ // Read the call journal after taking the same lock used to save the
52
+ // active batch and its call intent. A cached idle tab cannot decide
53
+ // that an admission in progress was abandoned.
54
+ await this.dialer.restore();
55
+ const context = this.dialer.queueContext;
56
+ const same = context?.key === this.state.key && JSON.stringify(context.contactIds) === JSON.stringify(this.state.active.map(c => c.id));
57
+ if (!same)
58
+ await this.commit({ ...this.state, contacts: this.state.wrapped ? this.state.contacts : [...this.state.active, ...this.state.contacts], active: [], wrapped: false });
59
+ }
60
+ this.initialized = true;
61
+ });
50
62
  }
51
63
  async start(contacts, mode = "auto", options = {}) {
52
64
  if (!this.initialized)
@@ -140,47 +152,51 @@ export class DialingQueue {
140
152
  await this.advance();
141
153
  }
142
154
  async advance() {
143
- if (this.advancing || !this.running || this.dialer.current.state !== "idle" || !this.state)
155
+ if (this.advancing || !this.running || this.dialer.current.state !== "idle" || !this.state || this.state.active.length)
144
156
  return;
145
157
  this.advancing = true;
146
158
  try {
147
- const batch = [], skipped = new Set();
148
- for (const contact of this.state.contacts) {
149
- if (!this.running || batch.length >= this.state.parallelLines)
150
- break;
151
- const permitted = await this.eligible(structuredClone(contact));
159
+ await this.withAdmissionLock(async () => {
160
+ if (!this.running || this.dialer.current.state !== "idle" || this.state.active.length)
161
+ return;
162
+ const batch = [], skipped = new Set();
163
+ for (const contact of this.state.contacts) {
164
+ if (!this.running || batch.length >= this.state.parallelLines)
165
+ break;
166
+ const permitted = await this.eligible(structuredClone(contact));
167
+ if (!this.running)
168
+ return;
169
+ if (permitted)
170
+ batch.push(contact);
171
+ else
172
+ skipped.add(contact.id);
173
+ }
152
174
  if (!this.running)
153
175
  return;
154
- if (permitted)
155
- batch.push(contact);
156
- else
157
- skipped.add(contact.id);
158
- }
159
- if (!this.running)
160
- return;
161
- const selected = new Set(batch.map(contact => contact.id));
162
- await this.commit({ ...this.state, contacts: this.state.contacts.filter(contact => !skipped.has(contact.id) && !selected.has(contact.id)), active: batch, wrapped: false });
163
- if (!this.running) {
164
- await this.commit({ ...this.state, contacts: [...batch, ...this.state.contacts], active: [] });
165
- return;
166
- }
167
- if (batch.length) {
168
- const first = batch[0];
169
- const { to: _to, destinations: _destinations, transfer_enabled: _transferEnabled, ...common } = first.input;
170
- const intent = batch.length === 1 ? first.input : { ...common, destinations: batch.map(contact => contact.input.to) };
171
- try {
172
- await this.dialer.start(intent, { key: this.state.key, contactIds: batch.map(contact => contact.id) });
176
+ const selected = new Set(batch.map(contact => contact.id));
177
+ await this.commit({ ...this.state, contacts: this.state.contacts.filter(contact => !skipped.has(contact.id) && !selected.has(contact.id)), active: batch, wrapped: false });
178
+ if (!this.running) {
179
+ await this.commit({ ...this.state, contacts: [...batch, ...this.state.contacts], active: [] });
180
+ return;
173
181
  }
174
- catch (error) {
175
- // No persisted call means admission did not happen. Retain the group
176
- // for an explicit retry, including storage denial before network I/O.
177
- if (this.dialer.queueContext?.key !== this.state.key)
178
- await this.commit({ ...this.state, contacts: [...batch, ...this.state.contacts], active: [] });
179
- throw error;
182
+ if (batch.length) {
183
+ const first = batch[0];
184
+ const { to: _to, destinations: _destinations, transfer_enabled: _transferEnabled, ...common } = first.input;
185
+ const intent = batch.length === 1 ? first.input : { ...common, destinations: batch.map(contact => contact.input.to) };
186
+ try {
187
+ await this.dialer.start(intent, { key: this.state.key, contactIds: batch.map(contact => contact.id) });
188
+ }
189
+ catch (error) {
190
+ // No persisted call means admission did not happen. Retain the group
191
+ // for an explicit retry, including storage denial before network I/O.
192
+ if (this.dialer.queueContext?.key !== this.state.key)
193
+ await this.commit({ ...this.state, contacts: [...batch, ...this.state.contacts], active: [] });
194
+ throw error;
195
+ }
180
196
  }
181
- }
182
- else if (!this.state.contacts.length)
183
- this.running = false;
197
+ else if (!this.state.contacts.length)
198
+ this.running = false;
199
+ });
184
200
  }
185
201
  catch (error) {
186
202
  this.running = false;
@@ -13,8 +13,10 @@ export declare class IndexedDbDialerJournal implements DialerJournal {
13
13
  /** Queue progress lives separately from call capabilities. Revision checks stop
14
14
  * stale tabs from replacing or advancing another tab's saved contact list. */
15
15
  export declare class IndexedDbDialingQueueJournal implements DialingQueueJournal {
16
+ private readonly name;
16
17
  private readonly database;
17
18
  constructor(name?: string);
19
+ runExclusive<T>(scope: string, action: () => Promise<T>): Promise<T>;
18
20
  read(scope: string): Promise<DialingQueueState | null>;
19
21
  write(state: DialingQueueState, expectedRevision: number | null): Promise<void>;
20
22
  }
@@ -84,8 +84,10 @@ export class IndexedDbDialerJournal {
84
84
  /** Queue progress lives separately from call capabilities. Revision checks stop
85
85
  * stale tabs from replacing or advancing another tab's saved contact list. */
86
86
  export class IndexedDbDialingQueueJournal {
87
+ name;
87
88
  database;
88
89
  constructor(name = "pyai-dialing-queue") {
90
+ this.name = name;
89
91
  this.database = new Promise((resolve, reject) => {
90
92
  const request = indexedDB.open(name, 1);
91
93
  request.onupgradeneeded = () => { request.result.createObjectStore("queues", { keyPath: "scope" }); };
@@ -94,6 +96,12 @@ export class IndexedDbDialingQueueJournal {
94
96
  request.onblocked = () => reject(new Error("Close the older dialer tab to open queue storage."));
95
97
  });
96
98
  }
99
+ async runExclusive(scope, action) {
100
+ const locks = globalThis.navigator?.locks;
101
+ if (!locks)
102
+ throw new Error("This browser cannot safely recover a saved calling queue.");
103
+ return await locks.request(JSON.stringify(["pyai-dialing-queue", this.name, scope]), action);
104
+ }
97
105
  async read(scope) {
98
106
  const db = await this.database;
99
107
  return new Promise((resolve, reject) => {