@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/src/cli.ts CHANGED
@@ -46,7 +46,7 @@ const commands: Command[] = [
46
46
  { command: "init", description: "Create a new project with API context and request examples offline", args: ["directory"], flags: { template: "string" }, example: "pyai init voice-demo --template typescript" },
47
47
  { command: "smoke", description: "Check models, voices, and speech synthesis", flags: { "tolerate-upstream": "boolean" } },
48
48
  { command: "doctor", description: "Diagnose key, catalogs, and a Speak to Hear round-trip" },
49
- { command: "dialer", description: "Open the private desktop calling and meeting-recording app", flags: { port: "string", "no-browser": "boolean", name: "string", "white-label": "boolean", transfers: "boolean" }, example: "pyai dialer --profile production" },
49
+ { command: "dialer", description: "Open the private desktop calling and meeting-recording app", flags: { port: "string", "no-browser": "boolean", name: "string", "white-label": "boolean", transfers: "boolean", receive: "boolean" }, example: "pyai dialer --profile production" },
50
50
  ...routes.map((r): Command => ({ command: r.command, description: r.description, args: r.id ? ["id"] : [], flags: {
51
51
  ...(r.body ? bodyFlags : {}), ...(r.binary ? outputFlags : {}), ...(r.wait ? waitFlags : {}),
52
52
  ...(r.query ?? {}), ...(r.confirm ? { confirm: "boolean" as const } : {}),
@@ -331,18 +331,19 @@ async function main(): Promise<void> {
331
331
  }
332
332
  const sandbox = cmd === "auth sandbox";
333
333
  const sandboxProfile = sandbox ? validateProfileName(value(flags, "profile") ?? process.env.PYAI_PROFILE ?? "sandbox") : undefined;
334
- const config = await resolveConfig({ apiKey: value(flags, "api-key"), baseURL: value(flags, "base-url"), profile: sandboxProfile ?? value(flags, "profile"), allowMissingProfile: sandbox });
334
+ const config = cmd === "dialer" && flags.receive === true ? { baseURL: value(flags,"base-url") ?? "https://api.pyai.com", apiKey: undefined, profile: "receive" } : await resolveConfig({ apiKey: value(flags, "api-key"), baseURL: value(flags, "base-url"), profile: sandboxProfile ?? value(flags, "profile"), allowMissingProfile: sandbox });
335
335
  if (config.apiKey) secrets.add(config.apiKey);
336
336
  const retries = number(flags, "retries", 2, 0, 5); if (!Number.isInteger(retries)) usage("--retries must be an integer");
337
337
  const http = new CliHttp({ baseURL: config.baseURL, apiKey: config.apiKey, timeoutMs: number(flags, "timeout", 30, 0.001) * 1000, maxRetries: retries });
338
338
  if (cmd === "dialer") {
339
339
  const port = number(flags, "port", 43117, 0, 65535); if (!Number.isInteger(port)) usage("--port must be an integer");
340
340
  if (flags["dry-run"]) { output({ dry_run: true, command: cmd, bind: "127.0.0.1", port, browser: !flags["no-browser"], calls: "Only after a foreground Call or Start calling action; no number is dialed at startup" }, flags); return; }
341
- if (!config.apiKey) throw new CliError("authentication_required", "Run pyai login or set PYAI_API_KEY to a live project key with telephony:manage.", 3);
341
+ const receiveOnly=flags.receive===true;
342
+ if (!receiveOnly&&!config.apiKey) throw new CliError("authentication_required", "Run pyai login or use pyai dialer --receive for incoming calls.", 3);
342
343
  const { startDialerApp } = await import("./dialer/appServer.ts");
343
- const fingerprint = createHash("sha256").update(config.baseURL).update("\0").update(config.apiKey).digest("hex");
344
- const sdk = new PyAI({ apiKey: config.apiKey, baseURL: config.baseURL, fetch: (url, init) => fetch(url, { ...init, redirect: "error", signal: init?.signal ?? AbortSignal.timeout(15000) }) });
345
- const app = await startDialerApp({ sdk, userId: `desktop_${fingerprint.slice(0,40)}`, scope: `desktop:${fingerprint}`, port, name: value(flags, "name"), whiteLabel: flags["white-label"] === true, allowTransfers: flags.transfers === true });
344
+ const fingerprint = createHash("sha256").update(config.baseURL).update("\0").update(config.apiKey ?? "receive-only").digest("hex");
345
+ const sdk = receiveOnly ? undefined : new PyAI({ apiKey: config.apiKey!, baseURL: config.baseURL, fetch: (url, init) => fetch(url, { ...init, redirect: "error", signal: init?.signal ?? AbortSignal.timeout(15000) }) });
346
+ const app = await startDialerApp({ sdk, receiveOnly, incomingApiOrigin: config.baseURL, userId: `desktop_${fingerprint.slice(0,40)}`, scope: `desktop:${fingerprint}`, port, name: value(flags, "name"), whiteLabel: flags["white-label"] === true, allowTransfers: flags.transfers === true });
346
347
  output({ url: app.url, local_only: true }, flags, `PyAI Phone is ready at ${app.url}\nKeep this window open. Press Ctrl+C to stop the app and end its owned calls.`);
347
348
  if (flags["no-browser"] || !(await openBrowser(app.launchUrl))) process.stderr.write(`Private one-use launch link (valid for 60 seconds): ${app.launchUrl}\n`);
348
349
  await new Promise<void>(resolve => {
@@ -380,8 +381,9 @@ async function main(): Promise<void> {
380
381
  const sampleRate = value(flags, "sample-rate") === undefined ? undefined : number(flags, "sample-rate", 24000, 8000, 48000);
381
382
  if (sampleRate !== undefined && !(SPEECH_SAMPLE_RATES as readonly number[]).includes(sampleRate)) usage(`--sample-rate must be one of ${SPEECH_SAMPLE_RATES.join(", ")}`);
382
383
  if (format.startsWith("g711_") && sampleRate !== undefined && sampleRate !== 8000) usage("G.711 audio requires --sample-rate 8000");
383
- const payload = { input: text, model: value(flags, "model") ?? "pyai-speak", voice: value(flags, "voice"), response_format: format, sample_rate: sampleRate };
384
384
  const path = value(flags, "out") ?? `pyai-speak.${format.startsWith("g711_") ? "raw" : format}`;
385
+ // Files need finalized container headers; stdout remains an incremental stream.
386
+ const payload = { input: text, model: value(flags, "model") ?? "pyai-speak", voice: value(flags, "voice"), response_format: format, sample_rate: sampleRate, stream: path === "-" };
385
387
  await checkOutput(path, flags);
386
388
  if (preview(flags, config.baseURL, "POST", "/v1/audio/speech", payload)) return;
387
389
  await writeAudio(await http.request("POST", "/v1/audio/speech", { json: payload }), path, flags); return;
@@ -1 +1,6 @@
1
- :root{font:14px/1.5 system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;color:#252638;background:#f6f6fa;--accent:#5b55e7}*{box-sizing:border-box}body{margin:0;display:grid;grid-template-columns:240px 1fr;min-height:100vh}aside{padding:34px 24px;border-right:1px solid #e6e7ee;background:#fff;display:flex;flex-direction:column;position:sticky;top:0;height:100vh}.brand{font-size:18px;font-weight:700;display:flex;align-items:center;gap:10px;color:inherit;text-decoration:none;letter-spacing:-.5px}.logo{display:grid;place-items:center;border-radius:13px;width:36px;height:36px;color:white;background:var(--accent);font-size:30px;line-height:1}nav{display:grid;gap:6px;margin-top:48px}button,select,textarea{font:inherit}button{cursor:pointer;border:0}nav button{padding:14px 13px;text-align:left;border-radius:12px;background:transparent;font-weight:550;color:#7e8193;display:flex;justify-content:space-between}nav button.selected{background:#eeedfd;color:var(--accent)}.aside-foot{margin-top:auto;font-size:12px;color:#73778c}.aside-foot small{font-size:11px;color:#a0a3b3;padding-left:16px}.online{display:inline-block;width:6px;height:6px;border-radius:50%;background:#24b18b;margin-right:6px}main{padding:44px clamp(22px,4.5vw,78px) 24px;max-width:1440px;width:100%;margin:auto}header{display:flex;justify-content:space-between;align-items:center;margin-bottom:38px}.eyebrow{font-size:10px;letter-spacing:1.7px;font-weight:650;color:#9294ab;margin:0 0 9px}h1{font-weight:600;letter-spacing:-1.3px;font-size:32px;line-height:1.2;margin:0 0 12px}.subtitle{margin:0;color:#83879c}.local-badge{border:1px solid #e3e5ee;border-radius:20px;padding:7px 12px;color:#888da2;font-size:11px;background:white}.calling-grid{display:grid;grid-template-columns:minmax(280px,380px) minmax(300px,1fr);gap:clamp(24px,4vw,72px);align-items:start}.source-label,.queue-card label{display:block;font-size:11px;font-weight:600;color:#7b8196;margin-bottom:8px}select{width:100%;padding:11px 14px;border:1px solid #e2e4ee;border-radius:11px;background:white;color:#464d65;min-height:43px}.recording-choice{display:flex;align-items:center;gap:7px;font-size:10px;color:#8b90a3;margin:12px 0 20px}.recording-choice input{accent-color:var(--accent)}.queue-card{background:white;padding:30px;border:1px solid #e7e8f0;border-radius:22px;margin-top:86px}.card-top{display:flex;justify-content:space-between}.quiet-icon{font-size:23px;color:#a5a1f0}.queue-card h2{font-size:24px;letter-spacing:-.8px;font-weight:550;line-height:1.3;margin:10px 0 15px}.queue-card>p{font-size:12px;color:#8c91a5;margin:0 0 26px;max-width:300px}.queue-card textarea{border:1px solid #e4e6f0;border-radius:12px;background:#fafaff;width:100%;height:114px;resize:vertical;padding:12px;font-size:13px;margin-bottom:15px}.queue-actions{display:flex;gap:7px;flex-wrap:wrap;margin-top:18px}.queue-actions button{border-radius:10px;background:#f1f2f8;color:#697087;padding:11px 13px;font-size:11px;font-weight:600}.queue-actions button.primary{background:var(--accent);color:white}.queue-actions button:disabled{opacity:.45;cursor:default}#queue-status{font-size:11px;color:#9398ab;margin:15px 0 0}.meeting-grid{display:grid;grid-template-columns:1fr minmax(300px,440px);gap:60px;align-items:center}.meeting-copy h2{font-size:48px;letter-spacing:-2px;font-weight:550;line-height:1.05;margin:18px 0 25px}.meeting-copy>p{font-size:14px;line-height:1.8;color:#81879b;max-width:320px}.feature{display:flex;gap:14px;max-width:330px;margin-top:23px;color:#8b91a5;font-size:12px}.feature b{background:#edebff;color:#837bdb;border-radius:10px;width:36px;min-width:36px;height:36px;display:grid;place-items:center}.feature strong{display:block;color:#5a617a;font-size:12px;font-weight:600;margin-bottom:3px}footer{font-size:10px;color:#a0a6b8;margin-top:38px;max-width:660px}#error{color:#b42338;font-size:12px;min-height:18px;margin-bottom:12px}button:focus-visible,select:focus-visible,textarea:focus-visible{outline:3px solid #bdb8ff;outline-offset:3px}[hidden]{display:none!important}@media(max-width:1000px){body{grid-template-columns:190px 1fr}aside{padding:28px 18px}.calling-grid{gap:25px;grid-template-columns:1fr}.queue-card{margin-top:0;max-width:380px}.meeting-grid{grid-template-columns:1fr;gap:24px}.meeting-copy h2{font-size:38px}.meeting-copy .feature{display:none}}@media(max-width:650px){body{display:block}aside{height:auto;padding:18px 22px;position:static;border:0;border-bottom:1px solid #e8e9f0}.brand{font-size:16px}nav{margin-top:20px;display:flex}nav button{flex:1;font-size:12px}.aside-foot{display:none}main{padding:28px 22px}header{margin-bottom:22px}h1{font-size:27px}.local-badge{display:none}.calling-grid{justify-items:center}.calling-grid>div,.queue-card{width:100%;max-width:380px}.meeting-copy h2{font-size:36px}.meeting-copy>p{font-size:12px}.meeting-grid{display:block}pyai-meeting-recorder{margin-top:25px}}
1
+
2
+ :root{font:13px/1.45 -apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;color:#282936;background:#f3f4f8;--accent:#5c4de4;--line:#e9eaf0}*{box-sizing:border-box}html{min-height:100%;background:radial-gradient(ellipse at 50% 0,#eae7fa,transparent 55%),#f3f4f8}body{margin:28px auto;display:flex;flex-direction:column;width:min(460px,calc(100% - 32px));max-height:calc(100dvh - 56px);min-height:0;background:#fff;border:1px solid #e3e4ec;border-radius:23px;box-shadow:0 18px 60px #25234412,0 2px 8px #25234406;overflow:hidden}aside{padding:17px 18px 12px;display:flex;flex-wrap:wrap;align-items:center;gap:14px;flex-shrink:0;border-bottom:1px solid var(--line);background:#fff}.brand{font-size:15px;font-weight:700;display:flex;align-items:center;gap:9px;color:inherit;text-decoration:none;letter-spacing:-.45px}.logo{display:grid;place-items:center;border-radius:10px;width:29px;height:29px;color:#fff;background:var(--accent);font-size:25px;line-height:1;box-shadow:0 3px 8px #5c4de422}.aside-foot{margin-left:auto;display:flex;align-items:center;gap:5px;font-size:0;color:#9295a5}.aside-foot:after{content:"On this device";font-size:10px}.aside-foot small,.aside-foot br{display:none}.online{width:5px;height:5px;border-radius:50%;background:#b7b8c5}nav{display:flex;gap:3px;width:100%;padding:3px;background:#f4f4f8;border-radius:11px}button,input,select,textarea{font:inherit}button{cursor:pointer}nav button{flex:1;min-height:34px;padding:7px 9px;border:0;border-radius:8px;background:transparent;font-size:11px;font-weight:600;color:#777b8c;white-space:nowrap}nav button span{display:none}nav button.selected{background:#fff;color:#5044ce;box-shadow:0 1px 4px #24273513}nav[data-single="true"]{display:none}main{padding:17px 18px 15px;width:100%;margin:0;overflow-y:auto;overscroll-behavior:contain}main>header{display:flex;justify-content:space-between;align-items:center;gap:12px;margin-bottom:15px}h1{font-size:17px;font-weight:650;letter-spacing:-.55px;line-height:1.2;margin:0}.subtitle,header .eyebrow{display:none}.local-badge{font-size:9px;font-weight:550;background:#f5f4fc;color:#817b9d;padding:4px 7px;border-radius:6px;white-space:nowrap}.eyebrow{font-size:9px;letter-spacing:1.2px;font-weight:650;color:#8b8b9e;margin:0 0 6px}.calling-grid{display:grid;grid-template-columns:minmax(0,1fr);gap:13px;align-items:start}.calling-grid>div{min-width:0}.source-label,.queue-card label{display:block;font-size:11px;font-weight:600;color:#686f82;margin-bottom:6px}select,input:not([type="checkbox"]):not([type="file"]){width:100%;padding:8px 10px;border:1px solid #e2e4ed;border-radius:9px;background:#fafafd;color:#343a4d;min-height:36px}.recording-choice{display:flex;align-items:center;gap:6px;font-size:10px;color:#7c8293;margin:9px 0 12px}.recording-choice input{accent-color:var(--accent);margin:0}.queue-card{background:#fff;padding:16px;border:1px solid var(--line);border-radius:15px;margin:0}.queue-card h2{font-size:18px;letter-spacing:-.55px;font-weight:650;line-height:1.25;margin:0 0 8px}.queue-card>p{font-size:12px;color:#7b7f91;margin:0 0 15px}.card-top,.quiet-icon{display:none}.queue-card textarea{border:1px solid #e2e4ed;border-radius:10px;background:#fafafd;width:100%;height:86px;resize:vertical;padding:10px;font-size:12px;line-height:1.5;margin-bottom:12px;color:#3a4052}.queue-card textarea::placeholder{color:#a1a5b4}.queue-actions{display:flex;gap:7px;flex-wrap:wrap;margin-top:12px}.queue-actions button,#incoming-send{border:1px solid #e7e8ef;border-radius:9px;background:#f7f7fa;color:#626b7e;padding:8px 11px;min-height:35px;font-size:11px;font-weight:600}.queue-actions button:hover:enabled,#incoming-send:hover:enabled{background:#efedf9}.queue-actions button.primary{background:var(--accent);border-color:var(--accent);color:#fff;box-shadow:0 2px 5px #5c4de41c}.queue-actions button:disabled{opacity:.4;cursor:default;box-shadow:none}#queue-status{font-size:10px;color:#83899b;margin:12px 0 0}.power-queue{padding:0;background:#fafafd}.power-queue>summary{display:flex;align-items:center;gap:10px;cursor:pointer;list-style:none;padding:13px 14px}.power-queue>summary::-webkit-details-marker{display:none}.queue-mark{width:29px;height:29px;border:1px solid #e5e1fa;border-radius:9px;background:#eeebfc;color:#7463d9;display:grid;place-items:center;font-size:17px}.power-queue summary strong{display:block;font-size:12px;font-weight:650;color:#49445f}.power-queue summary small{display:block;font-size:10px;color:#9090a1;margin-top:1px}.queue-chevron{margin-left:auto;color:#9997ab}.power-queue[open] .queue-chevron{transform:rotate(180deg)}.queue-content{border-top:1px solid var(--line);padding:14px;background:#fff;border-radius:0 0 15px 15px}.queue-content>p{font-size:11px;color:#7b7f91;margin:0 0 14px}.incoming-card{padding:17px;border-color:#e9e6f2;background:linear-gradient(180deg,#fcfbff,#fff)}.receiver-hero{text-align:center;padding:3px 0 17px}.receiver-icon{width:45px;height:45px;border:1px solid #e5dff9;background:#eee9fc;color:#7761db;display:grid;place-items:center;border-radius:15px;margin:0 auto 12px}.receiver-hero h2{font-size:20px;letter-spacing:-.65px;margin-bottom:7px}.receiver-hero p{font-size:12px;line-height:1.5;color:#838397;max-width:270px;margin:0 auto}.incoming-card #incoming-handoff{height:76px;min-height:60px;font-size:11px}.incoming-card input[type="file"]{font-size:10px;color:#9394a4;width:100%;margin:0 0 4px}.incoming-card input[type="file"]::file-selector-button{font:600 10px system-ui;border:1px solid #e3e2eb;border-radius:7px;color:#6b657f;background:#fff;padding:7px 9px;margin-right:8px;cursor:pointer}.pairing-fields .queue-actions button{width:100%}#incoming-enroll{background:var(--accent);color:#fff;border-color:var(--accent)}#incoming-binding{font-size:11px;font-weight:600;color:#57516f;text-align:center;overflow-wrap:anywhere;margin:13px 0 7px}#incoming-binding:empty{display:none}#incoming-status{display:flex;align-items:center;justify-content:center;gap:6px;background:#f3f3f8;border:1px solid #e9e8ef;border-radius:8px;padding:9px 10px;font-size:11px;color:#818193;margin:12px 0}#incoming-status:before{content:"";width:6px;height:6px;flex-shrink:0;background:#b8b7c7;border-radius:50%}#incoming-status[data-phase="ready"]{background:#eff8f3;border-color:#dceddf;color:#3e7b5b}#incoming-status[data-phase="ready"]:before{background:#60a57e}.receiver-controls{justify-content:center}.receiver-controls button{flex:1}.receiver-note{font-size:10px!important;line-height:1.55!important;color:#9593a5!important;text-align:center;margin:13px 0 0!important}.incoming-card:has(#incoming-status[data-phase]:not([data-phase="offline"])) .pairing-fields{display:none}.incoming-card:has(#incoming-status[data-phase="offline"]) .receiver-controls{display:none}#incoming-call{padding:14px;margin-top:12px;background:#fff;border:1px solid #e6e2f4;border-radius:11px;text-align:center}#incoming-caller{font-size:18px;font-weight:600;letter-spacing:-.4px}#incoming-call .queue-actions{justify-content:center}#incoming-call button:disabled{display:none}#incoming-answer{background:#248865;border-color:#248865;color:white}#incoming-end{background:#fceef0;color:#b74458;border-color:#f5dce1}#incoming-call label{margin-top:15px;text-align:left}#incoming-digits{margin-bottom:8px}#incoming-call:has(#incoming-answer:enabled) label,#incoming-call:has(#incoming-answer:enabled) #incoming-digits,#incoming-call:has(#incoming-answer:enabled) #incoming-send{display:none}.meeting-grid{display:grid;grid-template-columns:minmax(0,1fr);gap:13px}.meeting-copy{display:none}pyai-dialer,pyai-meeting-recorder,pyai-meeting-intelligence{display:block;width:100%;max-width:none}footer{font-size:9px;line-height:1.55;color:#a0a3b0;margin-top:15px;padding-top:12px;border-top:1px solid #f0f0f5}#error{color:#b54b5c;font-size:11px;min-height:0;margin:0}#error:not(:empty){padding:9px 11px;background:#fdf1f3;border:1px solid #f7dfe4;border-radius:8px;margin:0 0 12px}#retry{font-size:11px;padding:7px 10px;margin:0 0 12px;border:1px solid #e3e1ee;border-radius:8px;color:#625c79;background:#f6f5fa}button:focus-visible,select:focus-visible,textarea:focus-visible,input:focus-visible,summary:focus-visible{outline:3px solid #bcb4fa;outline-offset:2px}[hidden]{display:none!important}@media(max-width:520px){html{background:#fff}body{width:100%;margin:0;border:0;border-radius:0;box-shadow:none;max-height:100dvh;min-height:100dvh}aside{padding:16px 17px 11px}main{padding:15px 17px;flex:1}}
3
+
4
+ .local-badge{display:none}body[data-receive-only="true"] footer{display:none}
5
+
6
+ body[data-layout="comfortable"]{width:min(680px,calc(100% - 32px))}nav button.selected{color:var(--accent)}.logo{color:var(--accent-ink,#fff);overflow:hidden}.logo img{display:block;width:100%;height:100%;object-fit:contain;background:#fff}.queue-actions button.primary,#incoming-enroll{color:var(--accent-ink,#fff)}.appearance-toggle{margin-left:auto;width:29px;height:29px;border:1px solid var(--line);border-radius:9px;background:#fafafd;color:#7a778c;font-size:16px;display:grid;place-items:center}.appearance-settings{border:1px solid var(--line);border-radius:13px;padding:14px;margin-bottom:15px;background:#fafafd}.settings-heading{display:flex;align-items:center;justify-content:space-between}.settings-heading h2{font-size:15px;margin:0}.settings-heading button{border:0;background:transparent;color:#858392;font-size:21px}.appearance-settings p,.connection-help{font-size:11px;line-height:1.6;color:#7d8091}.appearance-settings label{display:block;font-size:11px;font-weight:550;margin:11px 0 5px}.settings-row{display:grid;grid-template-columns:1fr 2fr;gap:12px}.appearance-settings input[type="color"]{padding:3px;width:100%;height:36px}.appearance-settings input[type="file"]{font-size:11px;width:100%}.appearance-settings small{display:block;font-size:10px;color:#8b8d9d;margin:6px 0;line-height:1.55}.appearance-settings .settings-check,.appearance-settings fieldset label{display:flex;align-items:center;gap:7px;font-weight:400}.appearance-settings fieldset{border:1px solid var(--line);border-radius:9px;margin:14px 0 9px;padding:6px 10px 10px;display:grid;grid-template-columns:1fr 1fr}.appearance-settings legend{font-size:11px;font-weight:600;color:#696e80}.appearance-settings fieldset label{margin:5px 0;font-size:11px}.appearance-settings input[type="checkbox"]{accent-color:var(--accent)}#appearance-clear-logo{margin-top:5px;border:0;background:transparent;color:#777287;font-size:10px;padding:2px 0}.connection-help{padding:10px 12px;background:#f7f7fb;border:1px solid var(--line);border-radius:9px}#appearance-result:empty{display:none}@media(max-width:520px){body[data-layout="comfortable"]{width:100%}}
@@ -1,7 +1,7 @@
1
1
  <!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="theme-color" content="#5b55e7"><title>PyAI Phone</title><link rel="icon" href="/icon.svg"><link rel="manifest" href="/manifest.webmanifest"><link rel="stylesheet" href="/app.css"><script type="module" src="/app.js"></script></head><body>
2
- <aside><a class="brand" href="/" aria-label="PyAI Phone"><span class="logo">p</span> <span data-brand>PyAI Phone</span></a><nav aria-label="Workspace"><button class="selected" data-tab="calls">Phone <span>↗</span></button><button data-tab="meetings">Meeting recorder <span>◉</span></button></nav><div class="aside-foot"><span class="online"></span> Private workspace<br><small>Powered by PyAI</small></div></aside>
2
+ <aside><a class="brand" href="/" aria-label="PyAI Phone"><span class="logo">p</span> <span data-brand>PyAI Phone</span></a><button id="appearance-toggle" class="appearance-toggle" aria-label="Customize app" aria-expanded="false" title="Customize app">⚙</button><nav aria-label="Workspace"><button class="selected" data-tab="calls">Phone <span>↗</span></button><button data-tab="incoming">Receive calls <span>↓</span></button><button data-tab="meetings">Meeting recorder <span>◉</span></button></nav><div class="aside-foot"><span class="online"></span> Private workspace<br><small>Powered by PyAI</small></div></aside>
3
3
  <main><header><div><p class="eyebrow">YOUR CONVERSATIONS, TOGETHER</p><h1 data-heading>Make the next connection.</h1><p class="subtitle" data-subtitle>A clear line. A little less busywork.</p></div><span class="local-badge">On this device</span></header>
4
- <div id="error" role="alert"></div><button id="retry" hidden>Retry connection</button><section data-panel="calls"><div class="calling-grid"><div><label class="source-label" for="source">Calling from</label><select id="source" disabled><option>Loading workspace numbers…</option></select><label class="recording-choice"><input id="record-calls" type="checkbox">Record calls · tell the other person before recording</label><label class="recording-choice" id="transfer-choice" hidden><input id="allow-transfers" type="checkbox">Allow transfers · single-line calls</label><pyai-dialer></pyai-dialer></div>
5
- <section class="queue-card"><div class="card-top"><span class="eyebrow">STAY IN YOUR FLOW</span><span class="quiet-icon">≋</span></div><h2>One good conversation<br>after another.</h2><p>Paste your contacts and move through them at your own pace. Each call waits for your wrap-up.</p><label for="contacts">Phone numbers, one per line</label><textarea id="contacts" placeholder="+61 2 5550 0100&#10;+1 415 555 0100" spellcheck="false"></textarea><label for="mode">Calling order</label><select id="mode"><option value="auto">In list order</option><option value="dynamic">Highest priority first · number, priority</option><option value="parallel">Parallel lines · first answer connects</option></select><div id="parallel-choice" hidden><label for="parallel-lines">Parallel lines</label><select id="parallel-lines"><option value="2">2 lines</option><option value="3">3 lines</option><option value="4">4 lines</option></select></div><div class="queue-actions"><button id="queue-start" class="primary" disabled>Start calling</button><button id="queue-pause" disabled>Pause queue</button><button id="queue-resume" disabled>Resume queue</button><button id="queue-clear" disabled>Clear queue</button></div><p id="queue-status" role="status" aria-live="polite">You choose when to start. Your workspace calling rules apply to every call.</p></section></div></section>
6
- <section data-panel="meetings" hidden><div class="meeting-grid"><div class="meeting-copy"><span class="eyebrow">LESS DISTRACTION, MORE PRESENCE</span><h2>Stay in the<br>conversation.</h2><p>Choose the audio you want to keep. Record your meeting and microphone together, pause when you need to, and save a private audio file. When you choose, send it for a transcript, notes and action items.</p><div class="feature"><b>◉</b><span><strong>Your choice of audio</strong>Choose a supported meeting tab or system source in the browser picker.</span></div><div class="feature"><b>▦</b><span><strong>Saved as you go</strong>Committed audio can be recovered after an interrupted tab.</span></div><div class="feature"><b>↧</b><span><strong>Yours to keep</strong>Download your recording. No automatic uploads or hidden capture.</span></div></div><pyai-meeting-recorder></pyai-meeting-recorder><pyai-meeting-intelligence></pyai-meeting-intelligence></div></section>
4
+ <section id="appearance-settings" class="appearance-settings" hidden aria-label="App appearance"><div class="settings-heading"><h2>Make it yours</h2><button id="appearance-close" aria-label="Close appearance">×</button></div><p id="appearance-context">Changes preview on this device. Connect a workspace to save them.</p><form id="appearance-form"><label for="appearance-name">App name</label><input id="appearance-name" maxlength="60" required><div class="settings-row"><div><label for="appearance-color">Main color</label><input id="appearance-color" type="color"></div><div><label for="appearance-layout">Layout</label><select id="appearance-layout"><option value="compact">Compact</option><option value="comfortable">Roomier</option></select></div></div><label for="appearance-logo">Your logo</label><input id="appearance-logo" type="file" accept="image/png,.png"><small>PNG, up to 8 KB and 512 × 512 pixels.</small><button type="button" id="appearance-clear-logo">Use initials instead</button><label class="settings-check"><input id="appearance-white-label" type="checkbox">Use my brand only</label><fieldset><legend>App sections</legend><label><input type="checkbox" data-appearance-feature="calls">Phone</label><label><input type="checkbox" data-appearance-feature="incoming">Incoming calls</label><label><input type="checkbox" data-appearance-feature="meetings">Meetings</label><label><input type="checkbox" data-appearance-feature="power_queue">Power queue</label></fieldset><small>These choices change visibility. Workspace permissions still apply, and active work stays accessible.</small><div class="queue-actions"><button id="appearance-save" class="primary" type="submit">Apply preview</button></div><p id="appearance-result" role="status" aria-live="polite"></p></form></section><div id="error" role="alert"></div><p id="connection-help" class="connection-help" hidden></p><p id="sections-hidden" class="connection-help" hidden>All app sections are hidden. Bring them back in Customize.</p><button id="retry" hidden>Retry connection</button><section data-panel="calls"><div class="calling-grid"><div><label class="source-label" for="source">Calling from</label><select id="source" disabled><option>Loading workspace numbers…</option></select><label class="recording-choice"><input id="record-calls" type="checkbox">Record calls · tell the other person before recording</label><label class="recording-choice" id="transfer-choice" hidden><input id="allow-transfers" type="checkbox">Allow transfers · single-line calls</label><pyai-dialer compact></pyai-dialer></div>
5
+ <details class="queue-card power-queue"><summary><span class="queue-mark" aria-hidden="true">≋</span><span><strong>Power queue</strong><small>Contacts, priority &amp; parallel lines</small></span><span class="queue-chevron" aria-hidden="true">⌄</span></summary><div class="queue-content"><div class="card-top"><span class="eyebrow">STAY IN YOUR FLOW</span><span class="quiet-icon">≋</span></div><p>Add a list and work through it at your own pace. Each call waits for your wrap-up.</p><label for="contacts">Phone numbers, one per line</label><textarea id="contacts" placeholder="+61 2 5550 0100&#10;+1 415 555 0100" spellcheck="false"></textarea><label for="mode">Calling order</label><select id="mode"><option value="auto">In list order</option><option value="dynamic">Highest priority first · number, priority</option><option value="parallel">Parallel lines · first answer connects</option></select><div id="parallel-choice" hidden><label for="parallel-lines">Parallel lines</label><select id="parallel-lines"><option value="2">2 lines</option><option value="3">3 lines</option><option value="4">4 lines</option></select></div><div class="queue-actions"><button id="queue-start" class="primary" disabled>Start calling</button><button id="queue-pause" disabled>Pause queue</button><button id="queue-resume" disabled>Resume queue</button><button id="queue-clear" disabled>Clear queue</button></div><p id="queue-status" role="status" aria-live="polite">You choose when to start. Your workspace calling rules apply to every call.</p></div></details></div></section>
6
+ <section data-panel="incoming" hidden><div class="queue-card incoming-card"><div class="receiver-hero"><span class="receiver-icon" aria-hidden="true"><svg width="23" height="23" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.65" stroke-linecap="round" stroke-linejoin="round"><path d="M8 3H5a2 2 0 0 0-2 2c0 8.8 7.2 16 16 16a2 2 0 0 0 2-2v-3l-5-2-2 2a13 13 0 0 1-6-6l2-2-2-5Z"/><path d="M15 3v5m0 0 3-3m-3 3-3-3"/></svg></span><h2>Your desk. Your calls.</h2><p>Connect your workspace and answer calls right here.</p></div><div class="pairing-fields"><label for="incoming-handoff">Workspace connection</label><textarea id="incoming-handoff" autocomplete="off" spellcheck="false" placeholder="Paste your workspace connection"></textarea><input id="incoming-file" type="file" accept="application/json,.json"><div class="queue-actions"><button id="incoming-enroll">Connect workspace</button></div></div><div class="queue-actions receiver-controls"><button id="incoming-enable" class="primary" disabled>Enable incoming calls</button><button id="incoming-logout" disabled>Disconnect receiver</button></div><p id="incoming-binding"></p><p id="incoming-status" data-phase="offline" role="status" aria-live="polite">Incoming calls are off.</p><div id="incoming-call" hidden><strong id="incoming-caller"></strong><div class="queue-actions"><button id="incoming-answer" class="primary">Answer</button><button id="incoming-reject">Decline</button><button id="incoming-end">End call</button><button id="incoming-mute">Mute</button></div><label for="incoming-digits">Keypad</label><input id="incoming-digits" inputmode="tel" maxlength="32"><button id="incoming-send">Send digits</button></div><p class="receiver-note">Keep this window open to receive calls.<br>Your microphone starts only when you answer.</p></div></section><section data-panel="meetings" hidden><div class="meeting-grid"><div class="meeting-copy"><span class="eyebrow">LESS DISTRACTION, MORE PRESENCE</span><h2>Stay in the<br>conversation.</h2><p>Choose the audio you want to keep. Record your meeting and microphone together, pause when you need to, and save a private audio file. When you choose, send it for a transcript, notes and action items.</p><div class="feature"><b>◉</b><span><strong>Your choice of audio</strong>Choose a supported meeting tab or system source in the browser picker.</span></div><div class="feature"><b>▦</b><span><strong>Saved as you go</strong>Committed audio can be recovered after an interrupted tab.</span></div><div class="feature"><b>↧</b><span><strong>Yours to keep</strong>Download your recording. No automatic uploads or hidden capture.</span></div></div><pyai-meeting-recorder></pyai-meeting-recorder><pyai-meeting-intelligence></pyai-meeting-intelligence></div></section>
7
7
  <footer>Call history and call recordings are stored in your PyAI workspace. Meeting audio stays in this browser until you save or submit it.</footer></main></body></html>
@@ -1,3 +1,4 @@
1
+ import { IncomingReceiver } from '/incoming.js';
1
2
  import { ManagedDialer, dialerCallHandedOff } from '/modules/managedDialer.js';
2
3
  import { IndexedDbDialerJournal, IndexedDbDialingQueueJournal } from '/modules/indexedDbJournal.js';
3
4
  import { VoiceSdkAudio } from '/modules/voiceSdkAudio.js';
@@ -10,15 +11,68 @@ import '/modules/meetingIntelligenceElement.js';
10
11
 
11
12
  const $=selector=>document.querySelector(selector),error=$('#error');
12
13
  const showError=value=>{error.textContent=value instanceof Error?value.message:String(value);};
13
- let config,dialer,queue,audio,closed=false,poll,audioGeneration=0;
14
+ let incoming,config,dialer,queue,audio,meetingRecorder,closed=false,poll,audioGeneration=0;
15
+ let presentation,appearanceInfo,appearanceLogo=null,appearanceSequence=0,lastAppearanceBinding,manifestUrl;
14
16
  let localSession=null,preparingClose=false;const meetingOperations=new Set();
15
17
  async function request(path,options={}){
16
18
  if(preparingClose&&options.method==='POST'&&(path==='/api/sessions'||path.startsWith('/api/meetings/')))throw Error('The app is preparing to close. Reopen the workspace to continue.');
17
19
  const operation=(async()=>{const response=await fetch(path,{...options,headers:{...(options.body?{'content-type':options.body instanceof Blob?options.body.type:'application/json'}:{}),...(localSession?{authorization:`Bearer ${localSession}`} :{}),...(config?{'x-pyai-local-session':config.nonce}:{}),...options.headers},cache:'no-store',signal:AbortSignal.timeout(20000)});
18
- const body=await response.json();if(!response.ok)throw Error(body?.error?.message??'This operation could not be confirmed.');return body;})();
20
+ const body=await response.json();if(!response.ok){const error=Error(body?.error?.message??'This operation could not be confirmed.');error.status=response.status;throw error;}return body;})();
19
21
  const tracked=path.startsWith('/api/meetings/')&&options.method==='POST';if(tracked)meetingOperations.add(operation);
20
22
  try{return await operation;}finally{if(tracked)meetingOperations.delete(operation);}
21
23
  }
24
+ function inkFor(color){const c=[1,3,5].map(i=>parseInt(color.slice(i,i+2),16)/255).map(v=>v<=.04045?v/12.92:((v+.055)/1.055)**2.4);return .2126*c[0]+.7152*c[1]+.0722*c[2]>.179?'#111827':'#FFFFFF';}
25
+ function applyFeatureVisibility(){
26
+ if(!config||!presentation)return;
27
+ const supported=appearanceInfo?.features_supported??{calls:!config.receive_only,incoming:true,meetings:!config.receive_only,power_queue:!config.receive_only};
28
+ const pending=Boolean(queue&&(queue.current.remaining||queue.current.activeIds.length)),callActive=Boolean(dialer&&dialer.current.state!=='idle');
29
+ const captureActive=Boolean(meetingRecorder&&['starting','recording','paused','stopping'].includes(meetingRecorder.current.state))||meetingOperations.size>0;
30
+ const visible={calls:supported.calls&&(presentation.features.calls||callActive||pending),incoming:supported.incoming&&(presentation.features.incoming||!!incoming?.credential),meetings:supported.meetings&&(presentation.features.meetings||captureActive)};
31
+ for(const [key,value] of Object.entries(visible))document.querySelector(`[data-tab="${key}"]`).hidden=!value;
32
+ $('nav').dataset.single=String(Object.values(visible).filter(Boolean).length<=1);
33
+ $('details.power-queue').hidden=!(supported.power_queue&&(presentation.features.power_queue||pending));
34
+ const selected=document.querySelector('nav button.selected');if(selected?.hidden){const next=[...document.querySelectorAll('nav [data-tab]')].find(x=>!x.hidden);if(next)next.click();}
35
+ const activeTab=document.querySelector('nav button.selected:not([hidden])')?.dataset.tab;for(const panel of document.querySelectorAll('[data-panel]'))panel.hidden=!visible[panel.dataset.panel]||panel.dataset.panel!==activeTab;
36
+ $('#sections-hidden').hidden=Object.values(visible).some(Boolean);
37
+ }
38
+ function applyAppearance(){
39
+ if(!presentation)return;const p=presentation,ink=inkFor(p.primary_color);
40
+ document.title=p.name;document.body.dataset.layout=p.layout;document.body.dataset.receiveOnly=String(config?.receive_only===true);
41
+ document.documentElement.style.setProperty('--accent',p.primary_color);document.documentElement.style.setProperty('--accent-ink',ink);
42
+ $('[data-brand]').textContent=p.name;$('.brand').setAttribute('aria-label',p.name);
43
+ const logo=$('.logo');logo.replaceChildren();if(p.logo_png){const image=document.createElement('img');image.src=p.logo_png;image.alt='';logo.append(image);}else logo.textContent=[...p.name][0]?.toUpperCase()??'P';
44
+ $('.aside-foot small').hidden=p.white_label;
45
+ $('footer').textContent=p.white_label?'Call history and recordings stay in your workspace. Meeting audio stays on this device until you save or send it.':'Call history and call recordings are stored in your PyAI workspace. Meeting audio stays on this device until you save or send it.';
46
+ $('pyai-dialer').setAppearance?.({name:p.name,accent:p.primary_color,showBranding:!p.white_label});
47
+ let icon=p.logo_png;
48
+ try{if(!icon){const canvas=document.createElement('canvas');canvas.width=canvas.height=512;const paint=canvas.getContext('2d');if(paint){paint.fillStyle=p.primary_color;paint.fillRect(0,0,512,512);paint.fillStyle=ink;paint.font='600 336px system-ui';paint.textAlign='center';paint.textBaseline='middle';paint.fillText([...p.name][0]?.toUpperCase()??'P',256,272);icon=canvas.toDataURL('image/png');}}}catch{/* Optional icon rendering never blocks calling. */}
49
+ icon??=new URL('/icon.svg',location.origin).href;document.querySelector('link[rel="icon"]').href=icon;document.querySelector('meta[name="theme-color"]').content=p.primary_color;
50
+ try{if(manifestUrl)URL.revokeObjectURL(manifestUrl);manifestUrl=URL.createObjectURL(new Blob([JSON.stringify({id:location.origin+'/',name:p.name,short_name:p.name.slice(0,24),start_url:location.origin+'/',scope:location.origin+'/',display:'standalone',theme_color:p.primary_color,background_color:'#FFFFFF',icons:[{src:icon,sizes:'any',type:icon.startsWith('data:image/png')?'image/png':'image/svg+xml'}]})],{type:'application/manifest+json'}));document.querySelector('link[rel="manifest"]').href=manifestUrl;}catch{/* Keep the ordinary app usable if this browser cannot install it. */}
51
+ $('#connection-help').textContent=`Open ${p.name} from the installed app or your terminal, then use its private launch link in this browser. A workspace connection cannot unlock another browser profile.`;
52
+ applyFeatureVisibility();
53
+ }
54
+ function fillAppearance(){
55
+ if(!presentation)return;$('#appearance-name').value=presentation.name;$('#appearance-color').value=presentation.primary_color;$('#appearance-layout').value=presentation.layout;$('#appearance-white-label').checked=presentation.white_label;appearanceLogo=presentation.logo_png;
56
+ for(const field of document.querySelectorAll('[data-appearance-feature]')){field.disabled=appearanceInfo?.features_supported?.[field.dataset.appearanceFeature]===false;field.checked=!field.disabled&&presentation.features[field.dataset.appearanceFeature];}
57
+ $('#appearance-context').textContent=appearanceInfo?.save_enabled?'Connected to your calling workspace. Appearance saves for this workspace only.':'Preview on this device. Connect a workspace to save its appearance.';
58
+ $('#appearance-save').textContent=appearanceInfo?.save_enabled?'Save for workspace':'Apply preview';
59
+ }
60
+ async function refreshAppearance(){
61
+ const sequence=++appearanceSequence;
62
+ try{const result=await request('/api/presentation');if(sequence!==appearanceSequence||closed)return;appearanceInfo=result;presentation=result.presentation;applyAppearance();fillAppearance();}catch{if(!presentation&&config?.presentation){presentation=config.presentation;applyAppearance();fillAppearance();}}
63
+ }
64
+ $('#appearance-toggle').addEventListener('click',()=>{$('#appearance-settings').hidden=!$('#appearance-settings').hidden;$('#appearance-toggle').setAttribute('aria-expanded',String(!$('#appearance-settings').hidden));if(!$('#appearance-settings').hidden){fillAppearance();$('#appearance-name').focus();}});
65
+ $('#appearance-close').addEventListener('click',()=>{$('#appearance-settings').hidden=true;$('#appearance-toggle').setAttribute('aria-expanded','false');$('#appearance-toggle').focus();});
66
+ $('#appearance-logo').addEventListener('change',()=>void act(async()=>{const file=$('#appearance-logo').files?.[0];if(!file)return;if(file.size>8192||file.type!=='image/png')throw Error('Choose a PNG logo up to 8 KB.');appearanceLogo=await new Promise((resolve,reject)=>{const reader=new FileReader();reader.onload=()=>resolve(reader.result);reader.onerror=()=>reject(Error('The logo could not be read.'));reader.readAsDataURL(file);});$('#appearance-logo').value='';}));
67
+ $('#appearance-clear-logo').addEventListener('click',()=>{appearanceLogo=null;$('#appearance-logo').value='';$('#appearance-result').textContent='Initials will be used when you apply these changes.';});
68
+ $('#appearance-form').addEventListener('submit',event=>{event.preventDefault();void act(async()=>{
69
+ const features={};for(const field of document.querySelectorAll('[data-appearance-feature]'))features[field.dataset.appearanceFeature]=field.checked;
70
+ const draft={name:$('#appearance-name').value,primary_color:$('#appearance-color').value,layout:$('#appearance-layout').value,white_label:$('#appearance-white-label').checked,logo_png:appearanceLogo,features};
71
+ const save=appearanceInfo?.save_enabled===true;const result=await request(save?'/api/presentation':'/api/presentation/preview',{method:save?'PUT':'POST',body:JSON.stringify(save?{workspace_scope:appearanceInfo.workspace_scope,presentation:draft}:draft)});
72
+ appearanceInfo=result;presentation=result.presentation;applyAppearance();fillAppearance();$('#appearance-result').textContent=save?'Saved for this workspace.':'Preview applied. It will reset when the app closes or you connect a workspace.';
73
+ });});
74
+ window.addEventListener('pagehide',()=>{if(manifestUrl)URL.revokeObjectURL(manifestUrl);});
75
+
22
76
  let media;
23
77
  async function loadMedia(){
24
78
  if(window.Twilio?.Device)return;
@@ -26,8 +80,27 @@ async function loadMedia(){
26
80
  try{await media;}catch(e){media=null;throw e;}
27
81
  if(!window.Twilio?.Device)throw Error('Calling audio is unavailable.');
28
82
  }
83
+ function setupIncoming(){
84
+ const status=$('#incoming-status'),labels={offline:'Incoming calls are off.',enrolled:'Workspace connected. Enable incoming calls to register this device.',registering:'Registering incoming audio…',registered:'Registered. Confirming availability…',ringing:'Incoming call',answering:'Answering…',on_call:'On a call'};
85
+ incoming=new IncomingReceiver({request,createDevice:token=>new window.Twilio.Device(token,{logLevel:'silent'}),isBusy:()=>Boolean(dialer&&!['idle','wrapup','transferred','handing_off'].includes(dialer.current.state)),onChange:state=>{
86
+ status.dataset.phase=state.phase==='registered'&&state.available?'ready':state.phase;
87
+ status.textContent=state.error??(state.phase==='registered'&&state.available?'Ready for incoming calls.':labels[state.phase]);
88
+ $('#incoming-binding').textContent=state.binding?state.binding.label:'';
89
+ $('#incoming-enable').disabled=state.phase!=='enrolled'||!window.Twilio?.Device;$('#incoming-logout').disabled=state.phase==='offline';
90
+ const active=['ringing','answering','on_call'].includes(state.phase);$('#incoming-call').hidden=!active;$('#incoming-caller').textContent=state.caller??'';
91
+ $('#incoming-answer').disabled=state.phase!=='ringing';$('#incoming-reject').disabled=state.phase!=='ringing';$('#incoming-end').disabled=!['answering','on_call'].includes(state.phase);$('#incoming-mute').disabled=state.phase!=='on_call';$('#incoming-send').disabled=state.phase!=='on_call';renderQueue();
92
+ const binding=state.binding?`${state.binding.org_id}:${state.binding.project_id}`:null;if(config&&binding!==lastAppearanceBinding){lastAppearanceBinding=binding;void refreshAppearance();}
93
+ }});
94
+ $('#incoming-file').addEventListener('change',()=>void act(async()=>{const file=$('#incoming-file').files?.[0];if(file){if(file.size>16384)throw Error('Choose a desktop enrollment JSON file.');$('#incoming-handoff').value=await file.text();}$('#incoming-file').value='';}));
95
+ $('#incoming-enroll').addEventListener('click',()=>void act(async()=>{const raw=$('#incoming-handoff').value;$('#incoming-handoff').value='';let handoff;try{handoff=JSON.parse(raw);}catch{throw Error('Paste the desktop enrollment JSON from your workspace.');}await loadMedia();await incoming.enroll(handoff);}));
96
+ $('#incoming-enable').addEventListener('click',()=>void act(()=>incoming.register()));
97
+ $('#incoming-logout').addEventListener('click',()=>void act(()=>incoming.stop()));
98
+ $('#incoming-answer').addEventListener('click',()=>void act(()=>incoming.answer()));$('#incoming-reject').addEventListener('click',()=>void act(()=>incoming.reject()));$('#incoming-end').addEventListener('click',()=>void act(()=>incoming.hangup()));
99
+ let muted=false;$('#incoming-mute').addEventListener('click',()=>void act(()=>{muted=!muted;incoming.mute(muted);$('#incoming-mute').textContent=muted?'Unmute':'Mute';}));$('#incoming-send').addEventListener('click',()=>void act(()=>incoming.digits($('#incoming-digits').value)));
100
+ window.addEventListener('pagehide',()=>{void incoming.stop(false);void fetch('/api/incoming/presence',{method:'POST',headers:{'content-type':'application/json','x-pyai-local-session':config.nonce,authorization:`Bearer ${localSession}`},body:JSON.stringify({ready:false}),keepalive:true}).catch(()=>{});});
101
+ }
29
102
  function renderQueue(){
30
- if(!queue)return;const state=queue.current,active=dialer.current.state!=='idle',saved=Boolean(state.remaining);
103
+ applyFeatureVisibility();if(!queue)return;const state=queue.current;if(state.remaining||state.activeIds.length)document.querySelector('details.power-queue').open=true;const active=dialer.current.state!=='idle'||Boolean(incoming?.call),saved=Boolean(state.remaining);
31
104
  $('#queue-start').disabled=active||state.running||Boolean(state.remaining)||!config.numbers.length;
32
105
  $('#queue-clear').disabled=active||state.running||!state.remaining;
33
106
  $('#parallel-choice').hidden=$('#mode').value!=='parallel';$('#parallel-lines').disabled=active||state.running||Boolean(state.remaining);
@@ -45,8 +118,13 @@ async function init(){
45
118
  try{localSession=localStorage.getItem('pyai-local-app-session');}catch{throw Error('Private app storage is unavailable. Enable storage for this local app before calling.');}
46
119
  const code=location.hash.slice(1);history.replaceState(null,'',location.pathname);
47
120
  if(code){const unlocked=await request('/api/unlock',{method:'POST',body:JSON.stringify({code})});localSession=unlocked.session_token;localStorage.setItem('pyai-local-app-session',localSession);}
48
- config=await request('/api/config');$('#transfer-choice').hidden=!config.transfers_enabled;document.title=config.name;$('[data-brand]').textContent=config.name;
49
- if(config.white_label){$('.logo').textContent=(config.name.match(/[A-Za-z]/)?.[0]??'P').toUpperCase();$('.aside-foot small').hidden=true;$('footer').textContent='Calls and call recordings stay in your workspace. Meeting audio stays in this browser until you save or submit it.';}
121
+ config=await request('/api/config');$('#connection-help').hidden=true;presentation=config.presentation;setupIncoming();await incoming.restore();if(incoming.credential){await loadMedia();incoming.publish({});}$('#transfer-choice').hidden=!config.transfers_enabled;await refreshAppearance();
122
+ if(config.receive_only){
123
+ for(const tab of document.querySelectorAll('[data-tab="calls"],[data-tab="meetings"]'))tab.hidden=true;
124
+ document.querySelector('[data-tab="incoming"]').click();
125
+ window.addEventListener('pyai-desktop-prepare-close',event=>{const requestId=event.detail?.requestId;if(typeof requestId==='string')void incoming.stop().then(()=>window.dispatchEvent(new CustomEvent('pyai-desktop-close-result',{detail:{requestId,ready:true,reason:'Incoming receiver disconnected.'}})));});
126
+ return;
127
+ }
50
128
  const source=$('#source');source.replaceChildren();
51
129
  for(const number of config.numbers){const option=document.createElement('option');option.value=number.id;option.textContent=number.phone_number;source.append(option);}
52
130
  if(!config.numbers.length){const option=document.createElement('option');option.textContent='No active voice numbers in this workspace';source.append(option);}
@@ -61,12 +139,13 @@ async function init(){
61
139
  await queue.restore();
62
140
  if(queue.current.remaining||queue.current.activeIds.length){$('#mode').value=queue.current.mode;$('#parallel-lines').value=String(queue.current.parallelLines);}
63
141
  $('pyai-dialer').bind(dialer,to=>{
142
+ if(incoming?.call)throw Error('Finish the incoming call before dialing.');
64
143
  if(!config.numbers.length)throw Error('Add a voice number in your PyAI workspace before calling.');
65
144
  const sourceNumber=config.numbers.find(n=>n.id===source.value);if(sourceNumber?.phone_number===to)throw Error('Choose a destination different from your calling number.');
66
145
  return inputFor(to);
67
146
  },{name:config.name,showBranding:!config.white_label},async()=>{await queue.finishWrapup();renderQueue();});
68
- dialer.subscribe(()=>renderQueue());renderQueue();
69
- const store=new IndexedDbMeetingRecordingStore(),recorder=new MeetingRecorder(config.scope,store);$('pyai-meeting-recorder').bind(recorder,store);
147
+ dialer.subscribe(()=>{incoming?.busyChanged();renderQueue();});renderQueue();
148
+ const store=new IndexedDbMeetingRecordingStore(),recorder=new MeetingRecorder(config.scope,store);meetingRecorder=recorder;recorder.subscribe(()=>applyFeatureVisibility());$('pyai-meeting-recorder').bind(recorder,store);
70
149
  $('pyai-meeting-intelligence').bind(config.scope,store,{availability:()=>request('/api/meetings/availability'),submit:(id,audio,notice)=>request(`/api/meetings/${encodeURIComponent(id)}`,{method:'POST',headers:{'x-pyai-meeting-notice':notice?'accepted':''},body:audio}),get:id=>request(`/api/meetings/${encodeURIComponent(id)}`),remove:id=>request(`/api/meetings/${encodeURIComponent(id)}/remove`,{method:'POST',body:'{}'})});
71
150
  $('#queue-start').addEventListener('click',()=>void act(async()=>{
72
151
  const contacts=$('#contacts').value.split(/\r?\n/).map(line=>line.trim()).filter(Boolean).map((line,index)=>{
@@ -82,7 +161,7 @@ async function init(){
82
161
  window.addEventListener('pyai-desktop-prepare-close',event=>{
83
162
  const requestId=event.detail?.requestId;if(typeof requestId!=='string'||!/^[A-Za-z0-9_-]{1,128}$/.test(requestId))return;
84
163
  closePreparation??=(async()=>{
85
- preparingClose=true;queue.pause();audio.disconnect();clearTimeout(poll);
164
+ preparingClose=true;await incoming?.stop();queue.pause();audio.disconnect();clearTimeout(poll);
86
165
  await recorder.stop();await Promise.allSettled([...meetingOperations]);
87
166
  // Never replay admission during close. An intent without a known call ID
88
167
  // remains recoverable under the same credential after the app reopens.
@@ -99,19 +178,20 @@ async function init(){
99
178
  closed=true;clearTimeout(poll);queue.pause();audio.disconnect();void recorder.stop();
100
179
  const id=dialer.current.callId;if(id&&!['idle','wrapup','transferred','handing_off'].includes(dialer.current.state)&&!dialerCallHandedOff(dialer.current.call??{}))void fetch(`/api/calls/${encodeURIComponent(id)}/hangup`,{method:'POST',headers:{'content-type':'application/json','x-pyai-local-session':config.nonce,authorization:`Bearer ${localSession}`},body:'{}',keepalive:true}).catch(()=>{});
101
180
  });
102
- void refresh();
181
+ applyAppearance();void refresh();
103
182
  }
104
183
  async function act(action){error.textContent='';try{await action();}catch(e){showError(e);renderQueue();}}
105
184
  for(const tab of document.querySelectorAll('[data-tab]'))tab.addEventListener('click',()=>{
106
185
  for(const button of document.querySelectorAll('[data-tab]'))button.classList.toggle('selected',button===tab);
107
186
  for(const panel of document.querySelectorAll('[data-panel]'))panel.hidden=panel.dataset.panel!==tab.dataset.tab;
108
- $('[data-heading]').textContent=tab.dataset.tab==='calls'?'Make the next connection.':'Be present. Keep the conversation.';
109
- $('[data-subtitle]').textContent=tab.dataset.tab==='calls'?'A clear line. A little less busywork.':'A private recording, on your terms.';
187
+ $('[data-heading]').textContent=tab.dataset.tab==='calls'?'Phone':tab.dataset.tab==='incoming'?'Incoming calls':'Meetings';
188
+ $('[data-subtitle]').textContent=tab.dataset.tab==='calls'?'A clear line. A little less busywork.':tab.dataset.tab==='incoming'?'Connect from your workspace. Answer when ready.':'A private recording, on your terms.';
110
189
  });
111
190
  async function connectWorkspace(){
112
191
  $('#retry').disabled=true;error.textContent='';
113
192
  try{await init();$('#retry').hidden=true;}
114
- catch(e){showError(e);$('#retry').hidden=false;$('#retry').disabled=false;}
193
+ catch(e){showError(e);if(e?.status===401&&!config){$('#connection-help').hidden=false;$('#connection-help').textContent=`Open ${presentation?.name??'PyAI Phone'} from the installed app or your terminal, then use its private launch link in this browser. A workspace connection cannot unlock another browser profile.`;}$('#retry').hidden=false;$('#retry').disabled=false;}
115
194
  }
116
195
  $('#retry').addEventListener('click',()=>void connectWorkspace());
196
+ try{presentation=JSON.parse(document.body.dataset.presentationDefaults);applyAppearance();fillAppearance();}catch{/* A private app launch still confirms actual backend configuration. */}
117
197
  void connectWorkspace();
@@ -0,0 +1,107 @@
1
+ /** Incoming-only SDK lifecycle. No project key, enrollment, presence or refresh
2
+ * capability is retained in this renderer. Registration is a user action. */
3
+ export class IncomingReceiver {
4
+ constructor({request,createDevice,onChange=()=>{},isBusy=()=>false,clock=()=>Date.now(),later=(fn,ms)=>globalThis.setTimeout(fn,ms),cancel=handle=>globalThis.clearTimeout(handle)}){
5
+ Object.assign(this,{request,createDevice,onChange,isBusy,clock,later,cancel});this.generation=0;this.state={phase:'offline',available:false};
6
+ }
7
+ publish(fields){this.state={...this.state,...fields};this.onChange({...this.state});}
8
+ async restore(){
9
+ const generation=this.generation;try{const credential=await this.request('/api/incoming/status',{method:'POST',body:'{}'});if(generation===this.generation){this.credential=credential;this.publish({phase:'enrolled',binding:credential.binding,available:false,error:null});if(credential.expires_at<=this.clock())await this.renew();}}catch(error){if(![401,403,410].includes(error.status))throw error;await this.stop();}
10
+ }
11
+ async enroll(handoff){
12
+ if(this.call)throw Error('Finish the incoming call before changing workspace.');
13
+ await this.stop();const generation=++this.generation;
14
+ const credential=await this.request('/api/incoming/enroll',{method:'POST',body:JSON.stringify(handoff)});
15
+ if(generation!==this.generation)return;
16
+ this.credential=credential;this.publish({phase:'enrolled',binding:credential.binding,available:false,error:null});
17
+ }
18
+ // Called directly from the Enable button: no network await before register().
19
+ async register(){
20
+ if(!this.credential)throw Error('Reconnect your workspace before enabling incoming calls.');
21
+ if(this.credential.session_expires_at<=this.clock()){await this.stop();throw Error('Reconnect your workspace before enabling incoming calls.');}
22
+ this.deviceFault=false;
23
+ if(this.credential.expires_at<=this.clock()){try{await this.renew();}catch(error){if([401,403,410].includes(error.status))await this.stop();throw Error('Incoming renewal could not be confirmed.');}return;}
24
+ if(this.device){if(this.device.state==='registered'){this.registered=true;this.publish({phase:'registered',error:null,error_code:null,error_phase:null});await this.beat();return;}this.publish({phase:'registering',available:false,error:null});if(this.device.state!=='registering')await this.device.register();return;}
25
+ const generation=this.generation,device=this.device=this.createDevice(this.credential.access_token),current=()=>generation===this.generation&&this.device===device;
26
+ device.on('registered',()=>{if(current()){this.registered=true;this.publish({phase:this.call?'on_call':this.deviceFault?'enrolled':'registered',...(!this.deviceFault?{error:null,error_code:null,error_phase:null}:{})});void this.beat();}});
27
+ device.on('unregistered',()=>{if(current()){this.registered=false;this.publish({phase:this.call?'on_call':'enrolled',available:false});void this.beat();}});
28
+ device.on('tokenWillExpire',()=>{if(current()&&!this.deviceFault)void this.renew().catch(error=>{if(!current())return;if([401,403,410].includes(error.status))void this.stop();else this.publish({error:'Incoming renewal could not be confirmed.',available:false});});});
29
+ device.on('incoming',call=>{if(current())this.incoming(call);else call.reject();});
30
+ device.on('error',error=>{if(current())this.deviceError(error);});
31
+ this.publish({phase:'registering',available:false});
32
+ try{await device.register();}catch(error){if(current())this.deviceError(error);throw Error(this.state.error??'Incoming registration could not be confirmed.');}
33
+ if(current())this.armExpiry();
34
+ }
35
+ deviceError(error){
36
+ // Retain only the SDK's numeric classification, never its message/URL/token.
37
+ const code=Number.isSafeInteger(error?.code)&&error.code>0&&error.code<=99999?error.code:null;
38
+ const generation=this.generation,expired=code===31205||code===20104; // SDK maps signaling 31205 to AccessTokenExpired (20104).
39
+ this.registered=false;this.deviceFault=!expired;
40
+ this.publish({phase:this.call?this.state.phase:'enrolled',available:false,error_code:code,error_phase:this.state.phase,
41
+ error:expired?'Incoming token expired; confirming renewal.':`Incoming calling is unavailable${code===null?'':` (code ${code})`}. Check the connection or reconnect your workspace.`});
42
+ if(!this.credential)return;
43
+ if(this.credential.session_expires_at<=this.clock()){void this.stop();return;}
44
+ if(expired){void this.renew().catch(error=>{if(generation!==this.generation)return;if([401,403,410].includes(error.status))void this.stop();else{this.publish({available:false,error:'Incoming renewal could not be confirmed.'});void this.beat();}});}
45
+ else{this.armExpiry();void this.beat();}
46
+ }
47
+ armExpiry(){
48
+ this.cancel(this.expiry);const generation=this.generation;
49
+ const until=this.deviceFault?this.credential.session_expires_at:Math.min(this.credential.expires_at,this.credential.session_expires_at);
50
+ this.expiry=this.later(()=>{if(generation!==this.generation)return;
51
+ if(this.credential.session_expires_at<=this.clock()){void this.stop();return;}
52
+ this.publish({available:false});
53
+ if(this.call){this.renewPending=true;void this.beat();this.expiry=this.later(()=>{if(generation===this.generation)void this.stop();},Math.max(0,this.credential.session_expires_at-this.clock()));}else void this.beat();
54
+ },Math.max(0,until-this.clock()));
55
+ }
56
+ async beat(){
57
+ if(this.beating)return;this.cancel(this.heartbeat);if(!this.credential)return;
58
+ // The existing call is owned by the SDK; an expired incoming grant cannot
59
+ // be refreshed mid-call or used as authority to tear that call down.
60
+ if(this.credential.session_expires_at<=this.clock()){await this.stop();return;}
61
+ if(this.deviceFault&&this.credential.expires_at<=this.clock()){this.publish({available:false});return;}
62
+ if(this.credential.expires_at<=this.clock()){
63
+ this.publish({available:false});if(this.call){this.renewPending=true;return;}
64
+ try{await this.renew();}catch(error){if([401,403,410].includes(error.status))await this.stop();else{this.publish({error:'Incoming renewal could not be confirmed.',available:false});const generation=this.generation;this.heartbeat=this.later(()=>{if(generation===this.generation)void this.beat();},15000);}}return;
65
+ }
66
+ this.beating=true;const generation=this.generation;
67
+ try{const ready=Boolean(this.registered&&!this.deviceFault&&!this.call&&!this.isBusy()&&this.credential.expires_at>this.clock()&&this.credential.session_expires_at>this.clock());const result=await this.request('/api/incoming/presence',{method:'POST',body:JSON.stringify({ready})});
68
+ if(generation===this.generation)this.publish({available:ready&&result.available===true});
69
+ }catch(error){if(generation===this.generation){this.publish({available:false,error:'Incoming availability could not be confirmed.'});if([401,403,410].includes(error.status)&&!(this.call&&this.credential?.expires_at<=this.clock()))void this.stop();}}
70
+ finally{this.beating=false;if(generation===this.generation&&this.credential)this.heartbeat=this.later(()=>void this.beat(),15000);}
71
+ }
72
+ async renew(){
73
+ if(this.deviceFault)return;
74
+ if(this.call){this.renewPending=true;return;}// Do not disrupt an active SDK call to update a token.
75
+ if(this.renewing)return this.renewing;
76
+ const generation=this.generation;
77
+ this.renewing=(async()=>{const credential=await this.request('/api/incoming/renew',{method:'POST',body:'{}'});
78
+ if(generation!==this.generation)return;
79
+ this.credential=credential;
80
+ if(this.deviceFault){this.armExpiry();return;}
81
+ if(this.device){this.device.updateToken(credential.access_token);if(this.device.state==='registered'){this.registered=true;this.publish({phase:'registered',error:null,error_code:null,error_phase:null});}else if(!this.registered&&this.device.state!=='registering')await this.device.register();}else this.publish({phase:'enrolled',available:false,error:null});
82
+ this.armExpiry();await this.beat();
83
+ })();try{await this.renewing;}finally{this.renewing=null;}
84
+ }
85
+ incoming(call){
86
+ if(this.call||this.isBusy()||this.deviceFault||!this.registered||this.credential?.expires_at<=this.clock()||this.credential?.session_expires_at<=this.clock()){call.reject();return;}
87
+ const generation=this.generation;this.call=call;this.publish({phase:'ringing',caller:String(call.parameters?.From??'Incoming call'),available:false});void this.beat();
88
+ const done=()=>{if(generation!==this.generation||this.call!==call)return;this.call=null;call.removeAllListeners?.();this.publish({phase:this.registered?'registered':'enrolled',caller:null});
89
+ if(this.renewPending||this.credential?.expires_at<=this.clock()){this.renewPending=false;void this.renew().catch(error=>{if([401,403,410].includes(error.status))void this.stop();else{this.publish({available:false,error:'Incoming renewal could not be confirmed.'});void this.beat();}});}else void this.beat();};
90
+ call.on('accept',()=>{if(generation===this.generation&&this.call===call)this.publish({phase:'on_call'});});
91
+ for(const event of ['cancel','reject','disconnect','error'])call.on(event,done);
92
+ }
93
+ answer(){if(!this.call||this.state.phase!=='ringing')throw Error('No incoming call is waiting.');this.publish({phase:'answering'});this.call.accept();}
94
+ reject(){if(this.call&&['ringing','answering'].includes(this.state.phase))this.call.reject();}
95
+ hangup(){if(this.call)this.call.disconnect();}
96
+ mute(value){if(this.call&&this.state.phase==='on_call')this.call.mute(value);}
97
+ digits(value){if(!/^[0-9*#]{1,32}$/.test(value))throw Error('Use keypad digits only.');if(this.call&&this.state.phase==='on_call')this.call.sendDigits(value);}
98
+ busyChanged(){void this.beat();}
99
+ async stop(server=true){
100
+ ++this.generation;this.cancel(this.heartbeat);this.cancel(this.expiry);
101
+ const device=this.device,call=this.call;this.device=null;this.call=null;this.credential=null;this.registered=false;this.renewPending=false;this.deviceFault=false;
102
+ call?.removeAllListeners?.();try{call?.disconnect();}catch{}
103
+ let unregister;try{unregister=device?.unregister();}catch{}finally{try{device?.destroy();}catch{}device?.removeAllListeners?.();}
104
+ this.publish({phase:'offline',available:false,caller:null,binding:null});
105
+ await Promise.allSettled([unregister,...(server?[this.request('/api/incoming/logout',{method:'POST',body:'{}'})]:[])]);
106
+ }
107
+ }