@pyai/sdk 0.9.2 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/CLI.schema.json +11 -0
  2. package/README.md +131 -3
  3. package/dist/cli-omni-template.d.ts +2 -2
  4. package/dist/cli-omni-template.js +2 -2
  5. package/dist/cli.js +39 -4
  6. package/dist/dialer/appServer.d.ts +21 -0
  7. package/dist/dialer/appServer.js +195 -0
  8. package/dist/dialer/dialerElement.d.ts +23 -0
  9. package/dist/dialer/dialerElement.js +108 -0
  10. package/dist/dialer/dialingQueue.d.ts +31 -0
  11. package/dist/dialer/dialingQueue.js +78 -0
  12. package/dist/dialer/index.d.ts +6 -0
  13. package/dist/dialer/index.js +6 -0
  14. package/dist/dialer/indexedDbJournal.d.ts +11 -0
  15. package/dist/dialer/indexedDbJournal.js +62 -0
  16. package/dist/dialer/managedDialer.d.ts +65 -0
  17. package/dist/dialer/managedDialer.js +217 -0
  18. package/dist/dialer/meetingRecorder.d.ts +83 -0
  19. package/dist/dialer/meetingRecorder.js +261 -0
  20. package/dist/dialer/meetingRecorderElement.d.ts +20 -0
  21. package/dist/dialer/meetingRecorderElement.js +138 -0
  22. package/dist/dialer/meetingRecordingStore.d.ts +17 -0
  23. package/dist/dialer/meetingRecordingStore.js +129 -0
  24. package/dist/dialer/serverBroker.d.ts +3 -0
  25. package/dist/dialer/serverBroker.js +23 -0
  26. package/dist/dialer/voiceSdkAudio.d.ts +33 -0
  27. package/dist/dialer/voiceSdkAudio.js +66 -0
  28. package/dist/index.d.ts +238 -6
  29. package/dist/index.js +67 -3
  30. package/package.json +24 -1
  31. package/src/cli-omni-template.ts +2 -2
  32. package/src/cli.ts +25 -4
  33. package/src/dialer/app/app.css +1 -0
  34. package/src/dialer/app/app.html +7 -0
  35. package/src/dialer/app/app.js +88 -0
  36. package/src/dialer/app/icon.svg +1 -0
  37. package/src/dialer/app/manifest.webmanifest +1 -0
  38. package/src/dialer/appServer.ts +151 -0
  39. package/src/dialer/dialerElement.ts +80 -0
  40. package/src/dialer/dialingQueue.ts +65 -0
  41. package/src/dialer/index.ts +6 -0
  42. package/src/dialer/indexedDbJournal.ts +56 -0
  43. package/src/dialer/managedDialer.ts +187 -0
  44. package/src/dialer/meetingRecorder.ts +220 -0
  45. package/src/dialer/meetingRecorderElement.ts +99 -0
  46. package/src/dialer/meetingRecordingStore.ts +99 -0
  47. package/src/dialer/serverBroker.ts +23 -0
  48. package/src/dialer/voiceSdkAudio.ts +61 -0
  49. package/src/index.ts +174 -5
@@ -0,0 +1,195 @@
1
+ /** Personal loopback companion. Project credentials stay in the local Node
2
+ * process; the renderer receives only the managed one-call capability. */
3
+ import { createServer } from "node:http";
4
+ import { randomBytes, timingSafeEqual } from "node:crypto";
5
+ import { readFile } from "node:fs/promises";
6
+ import { createRequire } from "node:module";
7
+ import { dirname, join } from "node:path";
8
+ import { Readable } from "node:stream";
9
+ import { createServerDialerBroker } from "./serverBroker.js";
10
+ const terminal = (call) => ["completed", "failed", "canceled"].includes(call.status);
11
+ const secretMatches = (input, expected) => typeof input === "string" && /^[A-Za-z0-9_-]+$/.test(input) && input.length === expected.length && timingSafeEqual(Buffer.from(input), Buffer.from(expected));
12
+ const browserModules = new Set(["managedDialer", "dialingQueue", "indexedDbJournal", "voiceSdkAudio", "dialerElement", "meetingRecorder", "meetingRecordingStore", "meetingRecorderElement"]);
13
+ const publicAssets = new Set(["/", "/app.js", "/app.css", "/manifest.webmanifest", "/icon.svg"]);
14
+ const publicModule = (path) => { const match = /^\/modules\/([A-Za-z]+)\.js$/.exec(path); return match && browserModules.has(match[1]) ? match[1] : null; };
15
+ async function packagedAsset(path) {
16
+ if (path === "/" || path === "/app.js" || path === "/app.css" || path === "/manifest.webmanifest" || path === "/icon.svg") {
17
+ const file = path === "/" ? "app.html" : path.slice(1);
18
+ return readFile(new URL(`../../src/dialer/app/${file}`, import.meta.url));
19
+ }
20
+ if (path === "/voice-sdk.js") {
21
+ const require = createRequire(import.meta.url);
22
+ const root = dirname(dirname(require.resolve("@twilio/voice-sdk")));
23
+ return readFile(join(root, "dist/twilio.min.js"));
24
+ }
25
+ const module = publicModule(path);
26
+ if (module)
27
+ return readFile(new URL(`./${module}.js`, import.meta.url));
28
+ throw new Error("No such asset.");
29
+ }
30
+ class AppError extends Error {
31
+ status;
32
+ constructor(status, message) { super(message); this.status = status; }
33
+ }
34
+ async function body(request) {
35
+ if (!/^application\/json(?:\s*;|$)/i.test(request.headers["content-type"] ?? ""))
36
+ throw new AppError(415, "Send a JSON request.");
37
+ const chunks = [];
38
+ let size = 0;
39
+ for await (const chunk of request) {
40
+ size += chunk.length;
41
+ if (size > 16384)
42
+ throw new AppError(413, "Calling request is too large.");
43
+ chunks.push(Buffer.from(chunk));
44
+ }
45
+ try {
46
+ const value = JSON.parse(Buffer.concat(chunks).toString("utf8"));
47
+ if (!value || Array.isArray(value) || typeof value !== "object")
48
+ throw Error();
49
+ return value;
50
+ }
51
+ catch {
52
+ throw new AppError(400, "Invalid calling request.");
53
+ }
54
+ }
55
+ function json(response, status, value) { response.writeHead(status, { "content-type": "application/json; charset=utf-8" }); response.end(JSON.stringify(value)); }
56
+ export async function startDialerApp(options) {
57
+ if (!options.scope.trim() || !options.userId.trim() || !Number.isInteger(options.port ?? 43117) || (options.port ?? 43117) < 0 || (options.port ?? 43117) > 65535)
58
+ throw new Error("A local user, scope and valid port are required.");
59
+ const broker = createServerDialerBroker(options.sdk, options.userId), nonce = randomBytes(32).toString("base64url");
60
+ const bootstrap = randomBytes(32).toString("base64url"), rendererToken = randomBytes(32).toString("base64url"), bootstrapExpires = Date.now() + 60000;
61
+ let bootstrapUsed = false;
62
+ let origin = "", closing = false;
63
+ const calls = new Set();
64
+ const remember = (call) => { if (terminal(call))
65
+ calls.delete(call.id);
66
+ else
67
+ calls.add(call.id); return call; };
68
+ const numbers = async () => (await options.sdk.telephony.numbers.list()).data.filter(number => number.status !== "released" && number.capabilities?.voice === true);
69
+ const own = async (id) => remember(await broker.get(id));
70
+ const server = createServer(async (request, response) => {
71
+ response.setHeader("cache-control", "no-store");
72
+ response.setHeader("x-content-type-options", "nosniff");
73
+ response.setHeader("x-frame-options", "DENY");
74
+ response.setHeader("referrer-policy", "no-referrer");
75
+ 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'");
76
+ try {
77
+ // Prevent DNS rebinding, cross-site loopback probes and requests to a
78
+ // publicly bound address. No CORS or wildcard-host mode exists.
79
+ if (!origin || request.headers.host !== new URL(origin).host || request.headers["sec-fetch-site"] === "cross-site" || (request.headers.origin && request.headers.origin !== origin))
80
+ throw new AppError(403, "Open the local PyAI dialer directly.");
81
+ const url = new URL(request.url ?? "/", origin), method = request.method ?? "GET";
82
+ if (url.search || url.hash)
83
+ throw new AppError(400, "Unexpected request parameters.");
84
+ if (url.pathname === "/api/unlock" && method === "POST") {
85
+ if (request.headers.origin !== origin)
86
+ throw new AppError(403, "Open the private local link from your terminal.");
87
+ const input = await body(request);
88
+ if (bootstrapUsed || Date.now() > bootstrapExpires || !secretMatches(input.code, bootstrap))
89
+ throw new AppError(403, "The private launch link has expired or was already used. Reopen the dialer from your terminal.");
90
+ bootstrapUsed = true;
91
+ return json(response, 200, { session_token: rendererToken });
92
+ }
93
+ if (url.pathname.startsWith("/api/") && !secretMatches(request.headers.authorization?.replace(/^Bearer /, ""), rendererToken))
94
+ throw new AppError(401, "Open the private local link from your terminal to unlock this app.");
95
+ if (method !== "GET") {
96
+ const supplied = request.headers["x-pyai-local-session"];
97
+ if (request.headers.origin !== origin || !secretMatches(supplied, nonce))
98
+ throw new AppError(403, "Local calling session changed. Reload the app.");
99
+ }
100
+ if (url.pathname === "/api/config" && method === "GET") {
101
+ const owned = await numbers();
102
+ return json(response, 200, { name: options.name ?? (options.whiteLabel ? "Phone" : "PyAI Phone"), white_label: options.whiteLabel === true, scope: options.scope, user_id: options.userId, nonce,
103
+ numbers: owned.map(number => ({ id: number.id, phone_number: number.phone_number, country: number.country })) });
104
+ }
105
+ if (url.pathname === "/api/sessions" && method === "POST") {
106
+ if (closing)
107
+ throw new AppError(503, "Dialer is closing. No new calls are admitted.");
108
+ const input = await body(request), key = request.headers["idempotency-key"];
109
+ if (typeof key !== "string" || typeof input.from_number_id !== "string" || !(await numbers()).some(number => number.id === input.from_number_id))
110
+ throw new AppError(400, "Choose an owned voice number and a calling retry key.");
111
+ const session = await broker.create(input, key);
112
+ remember(session.call);
113
+ return json(response, 200, session);
114
+ }
115
+ const callPath = /^\/api\/calls\/([A-Za-z0-9_-]{1,200})(?:\/(hangup|recording))?$/.exec(url.pathname);
116
+ if (callPath) {
117
+ const id = callPath[1], operation = callPath[2];
118
+ await own(id);
119
+ if (method === "GET" && !operation)
120
+ return json(response, 200, await own(id));
121
+ if (method === "POST" && operation === "hangup") {
122
+ await body(request);
123
+ return json(response, 202, remember(await broker.hangup(id)));
124
+ }
125
+ if (method === "GET" && operation === "recording") {
126
+ const range = request.headers.range;
127
+ if (range && !/^bytes=\d+-\d*$/.test(range))
128
+ throw new AppError(400, "Invalid recording range.");
129
+ const recording = await options.sdk.telephony.calls.recording(id, range ? { range } : {});
130
+ response.statusCode = recording.status;
131
+ for (const header of ["content-type", "content-length", "content-range", "accept-ranges"]) {
132
+ const value = recording.headers.get(header);
133
+ if (value)
134
+ response.setHeader(header, value);
135
+ }
136
+ response.setHeader("content-disposition", `attachment; filename="Call-${id}.wav"`);
137
+ if (!recording.body)
138
+ return response.end();
139
+ const stream = Readable.fromWeb(recording.body);
140
+ response.on("close", () => stream.destroy());
141
+ stream.on("error", () => response.destroy());
142
+ stream.pipe(response);
143
+ return;
144
+ }
145
+ }
146
+ if (method !== "GET" || url.pathname.startsWith("/api/"))
147
+ throw new AppError(404, "No such dialer operation.");
148
+ if (url.pathname === "/manifest.webmanifest") {
149
+ response.writeHead(200, { "content-type": "application/manifest+json" });
150
+ 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" }] }));
151
+ }
152
+ if (url.pathname === "/icon.svg" && options.whiteLabel) {
153
+ const monogram = (options.name ?? "Phone").match(/[A-Za-z]/)?.[0]?.toUpperCase() ?? "P";
154
+ response.writeHead(200, { "content-type": "image/svg+xml" });
155
+ 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>`);
156
+ }
157
+ if (!publicAssets.has(url.pathname) && url.pathname !== "/voice-sdk.js" && !publicModule(url.pathname))
158
+ throw new AppError(404, "No such dialer asset.");
159
+ const bytes = await (options.assets?.read ?? packagedAsset)(url.pathname).catch(() => { throw new AppError(404, "No such dialer asset."); });
160
+ 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";
161
+ response.writeHead(200, { "content-type": type });
162
+ response.end(bytes);
163
+ }
164
+ catch (error) {
165
+ if (response.headersSent) {
166
+ response.destroy();
167
+ return;
168
+ }
169
+ // Never reflect upstream responses, credentials, URLs, or stack traces.
170
+ const status = error instanceof AppError ? error.status : typeof error?.status === "number" ? error.status : 502;
171
+ 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.";
172
+ json(response, status, { error: { message } });
173
+ }
174
+ });
175
+ server.requestTimeout = 20000;
176
+ server.headersTimeout = 10000;
177
+ server.maxRequestsPerSocket = 100;
178
+ await new Promise((resolve, reject) => { server.once("error", reject); server.listen(options.port ?? 43117, "127.0.0.1", () => { server.off("error", reject); resolve(); }); });
179
+ const address = server.address();
180
+ if (!address || typeof address === "string")
181
+ throw new Error("No local dialer address.");
182
+ origin = `http://127.0.0.1:${address.port}`;
183
+ let closePromise = null;
184
+ return { url: origin, launchUrl: `${origin}#${bootstrap}`, close: () => closePromise ??= (async () => {
185
+ closing = true;
186
+ const deadline = Date.now() + 20000;
187
+ await Promise.allSettled([...calls].map(async (id) => { remember(await broker.hangup(id)); }));
188
+ while (calls.size && Date.now() < deadline) {
189
+ await new Promise(resolve => setTimeout(resolve, 500));
190
+ await Promise.allSettled([...calls].map(own));
191
+ }
192
+ await new Promise(resolve => { server.close(() => resolve()); server.closeIdleConnections?.(); });
193
+ return { unsettled: [...calls] };
194
+ })() };
195
+ }
@@ -0,0 +1,23 @@
1
+ import type { ManagedDialer } from "./managedDialer.ts";
2
+ import type { TelephonyBrowserSessionCreate } from "../index.ts";
3
+ export interface DialerAppearance {
4
+ name?: string;
5
+ accent?: string;
6
+ showBranding?: boolean;
7
+ }
8
+ /** Framework-free, shadow-DOM widget. Import this module in a browser only.
9
+ * The host supplies an authenticated broker and durable journal to the controller. */
10
+ export declare class PyaiDialerElement extends HTMLElement {
11
+ private readonly root;
12
+ private dialer;
13
+ private inputFor;
14
+ private unsubscribe;
15
+ private wrapup;
16
+ constructor();
17
+ bind(dialer: ManagedDialer, inputFor: (to: string) => TelephonyBrowserSessionCreate, appearance?: DialerAppearance, finishWrapup?: () => Promise<void>): void;
18
+ connectedCallback(): void;
19
+ disconnectedCallback(): void;
20
+ private render;
21
+ private run;
22
+ private act;
23
+ }
@@ -0,0 +1,108 @@
1
+ /** Framework-free, shadow-DOM widget. Import this module in a browser only.
2
+ * The host supplies an authenticated broker and durable journal to the controller. */
3
+ export class PyaiDialerElement extends HTMLElement {
4
+ root;
5
+ dialer = null;
6
+ inputFor = null;
7
+ unsubscribe = null;
8
+ wrapup = null;
9
+ constructor() {
10
+ super();
11
+ this.root = this.attachShadow({ mode: "open" });
12
+ this.root.innerHTML = `<style>
13
+ :host{--dialer-accent:#5b55e7;display:block;max-width:380px;color:#202332;font:14px/1.5 system-ui,sans-serif}
14
+ *{box-sizing:border-box}section{background:#fff;border:1px solid #e7e8ef;border-radius:24px;padding:24px;box-shadow:0 16px 56px #25284c12}
15
+ header{display:flex;align-items:center;justify-content:space-between;gap:12px}h2{margin:0;font-size:16px;font-weight:650}.badge{font-size:11px;color:#667085;background:#f3f4f8;padding:4px 9px;border-radius:20px}
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
+ 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
+ .hint{font-size:12px;color:#8c91a2;margin-top:8px}.keys{display:grid;grid-template-columns:repeat(3,1fr);gap:8px;margin:22px 0}.key{background:#f8f8fb;border:0;border-radius:14px;padding:9px;cursor:pointer;font:500 23px system-ui;color:inherit;min-height:57px}.key small{display:block;font-size:9px;letter-spacing:2px;color:#9296a5;margin-top:1px}.key:hover{background:#eeedf9}
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}
20
+ @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
+ </style><section aria-label="Phone"><header><h2>Phone</h2><span class="badge">PyAI</span></header>
22
+ <div class="status" role="status" aria-live="polite"><span class="dot"></span><span data-status>Connect your workspace</span></div>
23
+ <input type="tel" inputmode="tel" autocomplete="tel" aria-label="Phone number" placeholder="+1 415 555 0100" maxlength="32"><div class="hint">Include the country code</div>
24
+ <div class="keys"></div><div class="actions"><button class="secondary" data-action="mute" disabled>Mute</button><button class="primary" data-action="call" disabled>Call</button><button class="secondary" data-action="recover" hidden>Recover</button></div>
25
+ <p class="error" role="alert"></p><p class="privacy">Calls and recordings stay in your workspace</p></section>`;
26
+ const letters = ["", "ABC", "DEF", "GHI", "JKL", "MNO", "PQRS", "TUV", "WXYZ", "", "+", ""];
27
+ "123456789*0#".split("").forEach((digit, i) => {
28
+ const button = document.createElement("button");
29
+ button.className = "key";
30
+ button.type = "button";
31
+ button.setAttribute("aria-label", digit);
32
+ button.textContent = digit;
33
+ const small = document.createElement("small");
34
+ small.textContent = letters[i];
35
+ button.append(small);
36
+ button.addEventListener("click", () => {
37
+ if (this.dialer?.current.state === "active") {
38
+ this.dialer.sendDigits(digit);
39
+ return;
40
+ }
41
+ const input = this.root.querySelector("input");
42
+ if (!input.disabled)
43
+ input.value += digit;
44
+ });
45
+ this.root.querySelector(".keys").append(button);
46
+ });
47
+ this.root.querySelector("[data-action=call]").addEventListener("click", () => void this.act());
48
+ this.root.querySelector("[data-action=mute]").addEventListener("click", () => { if (this.dialer)
49
+ this.dialer.mute(!this.dialer.current.muted); });
50
+ this.root.querySelector("[data-action=recover]").addEventListener("click", () => void this.run(() => this.dialer.retrySetup()));
51
+ this.root.querySelector("input").addEventListener("keydown", event => { if (event.key === "Enter")
52
+ void this.act(); });
53
+ }
54
+ bind(dialer, inputFor, appearance = {}, finishWrapup) {
55
+ if (this.dialer && this.dialer !== dialer && this.dialer.current.state !== "idle")
56
+ throw new Error("Finish the current call before switching workspaces.");
57
+ this.unsubscribe?.();
58
+ this.dialer = dialer;
59
+ this.inputFor = inputFor;
60
+ this.wrapup = finishWrapup ?? (() => dialer.finishWrapup());
61
+ this.root.querySelector("h2").textContent = appearance.name ?? "Phone";
62
+ this.root.querySelector(".badge").hidden = appearance.showBranding === false;
63
+ if (appearance.accent && /^#[0-9a-f]{6}$/i.test(appearance.accent))
64
+ this.style.setProperty("--dialer-accent", appearance.accent);
65
+ this.unsubscribe = dialer.subscribe(snapshot => this.render(snapshot));
66
+ }
67
+ connectedCallback() { if (this.dialer && !this.unsubscribe)
68
+ this.unsubscribe = this.dialer.subscribe(s => this.render(s)); }
69
+ disconnectedCallback() { this.unsubscribe?.(); this.unsubscribe = null; }
70
+ render(snapshot) {
71
+ const labels = { idle: "Ready to call", preparing: "Connecting…", ringing: "Ringing…", active: "Connected", stopping: "Confirming call ended…", unconfirmed: "Call needs recovery", wrapup: "Call finished" };
72
+ this.root.querySelector("[data-status]").textContent = labels[snapshot.state];
73
+ this.root.querySelector(".dot").classList.toggle("active", snapshot.state === "active");
74
+ this.root.querySelector("input").disabled = snapshot.state !== "idle";
75
+ const call = this.root.querySelector("[data-action=call]");
76
+ call.disabled = snapshot.state === "stopping";
77
+ call.classList.toggle("end", !["idle", "wrapup"].includes(snapshot.state));
78
+ call.textContent = snapshot.state === "idle" ? "Call" : snapshot.state === "wrapup" ? "Done" : "End call";
79
+ const mute = this.root.querySelector("[data-action=mute]");
80
+ mute.disabled = snapshot.state !== "active";
81
+ mute.textContent = snapshot.muted ? "Unmute" : "Mute";
82
+ mute.setAttribute("aria-pressed", String(snapshot.muted));
83
+ this.root.querySelector("[data-action=recover]").hidden = !["unconfirmed", "stopping"].includes(snapshot.state);
84
+ this.root.querySelector(".error").textContent = snapshot.error ?? "";
85
+ }
86
+ async run(action) {
87
+ try {
88
+ await action();
89
+ }
90
+ catch (error) {
91
+ this.root.querySelector(".error").textContent = error instanceof Error ? error.message : "Calling request failed.";
92
+ }
93
+ }
94
+ async act() {
95
+ if (!this.dialer || !this.inputFor)
96
+ return;
97
+ await this.run(async () => {
98
+ if (this.dialer.current.state === "wrapup")
99
+ await this.wrapup();
100
+ else if (this.dialer.current.state !== "idle")
101
+ await this.dialer.stop();
102
+ else
103
+ await this.dialer.start(this.inputFor(this.root.querySelector("input").value.replace(/[\s()-]/g, "")));
104
+ });
105
+ }
106
+ }
107
+ if (!customElements.get("pyai-dialer"))
108
+ customElements.define("pyai-dialer", PyaiDialerElement);
@@ -0,0 +1,31 @@
1
+ import type { TelephonyBrowserSessionCreate } from "../index.ts";
2
+ import type { ManagedDialer } from "./managedDialer.ts";
3
+ export interface DialingContact {
4
+ id: string;
5
+ input: TelephonyBrowserSessionCreate;
6
+ priority?: number;
7
+ }
8
+ /** Sequential auto dialing and priority-based dynamic dialing. A session must
9
+ * be explicitly started in the foreground; no calls resume automatically after
10
+ * reload. The backend rechecks policy and capacity for every admission. */
11
+ export declare class DialingQueue {
12
+ private contacts;
13
+ private running;
14
+ private advancing;
15
+ private activeId;
16
+ private readonly dialer;
17
+ private readonly eligible;
18
+ constructor(dialer: ManagedDialer, eligible: (contact: DialingContact) => Promise<boolean>);
19
+ get current(): {
20
+ running: boolean;
21
+ remaining: number;
22
+ activeId: string | null;
23
+ };
24
+ start(contacts: DialingContact[], mode?: "auto" | "dynamic"): Promise<void>;
25
+ pause(): void;
26
+ resume(): Promise<void>;
27
+ /** Explicit wrap-up acknowledgment gates the next admission. A local audio
28
+ * disconnect or a durable stop acknowledgment never advances the queue. */
29
+ finishWrapup(): Promise<void>;
30
+ private advance;
31
+ }
@@ -0,0 +1,78 @@
1
+ /** Sequential auto dialing and priority-based dynamic dialing. A session must
2
+ * be explicitly started in the foreground; no calls resume automatically after
3
+ * reload. The backend rechecks policy and capacity for every admission. */
4
+ export class DialingQueue {
5
+ contacts = [];
6
+ running = false;
7
+ advancing = false;
8
+ activeId = null;
9
+ dialer;
10
+ eligible;
11
+ constructor(dialer, eligible) {
12
+ this.dialer = dialer;
13
+ this.eligible = eligible;
14
+ }
15
+ get current() { return { running: this.running, remaining: this.contacts.length, activeId: this.activeId }; }
16
+ async start(contacts, mode = "auto") {
17
+ if (this.running || this.advancing || this.dialer.current.state !== "idle")
18
+ throw new Error("Finish the current call before starting a queue.");
19
+ if (!contacts.length || contacts.length > 500 || new Set(contacts.map(c => c.id)).size !== contacts.length ||
20
+ contacts.some(c => !c.id || !/^\+[1-9]\d{6,14}$/.test(c.input.to) || !Number.isFinite(c.priority ?? 0)))
21
+ throw new Error("Choose 1–500 unique contacts with valid destinations and priorities.");
22
+ this.contacts = structuredClone(contacts);
23
+ if (mode === "dynamic")
24
+ this.contacts.sort((a, b) => (b.priority ?? 0) - (a.priority ?? 0));
25
+ this.running = true;
26
+ await this.advance();
27
+ }
28
+ pause() { this.running = false; }
29
+ async resume() {
30
+ if (this.advancing)
31
+ throw new Error("Queue admission is still pending.");
32
+ if (!this.contacts.length)
33
+ return;
34
+ this.running = true;
35
+ if (this.dialer.current.state === "idle")
36
+ await this.advance();
37
+ }
38
+ /** Explicit wrap-up acknowledgment gates the next admission. A local audio
39
+ * disconnect or a durable stop acknowledgment never advances the queue. */
40
+ async finishWrapup() {
41
+ await this.dialer.finishWrapup();
42
+ this.activeId = null;
43
+ if (this.running)
44
+ await this.advance();
45
+ }
46
+ async advance() {
47
+ if (this.advancing || !this.running || this.dialer.current.state !== "idle")
48
+ return;
49
+ this.advancing = true;
50
+ try {
51
+ while (this.running && this.contacts.length) {
52
+ const contact = this.contacts[0];
53
+ const permitted = await this.eligible(structuredClone(contact));
54
+ if (!this.running)
55
+ return;
56
+ if (!permitted) {
57
+ this.contacts.shift();
58
+ continue;
59
+ }
60
+ this.activeId = contact.id;
61
+ // Remove only once this intent has been durably admitted locally.
62
+ await this.dialer.start(contact.input);
63
+ this.contacts.shift();
64
+ return;
65
+ }
66
+ if (!this.contacts.length)
67
+ this.running = false;
68
+ }
69
+ catch (error) {
70
+ this.running = false;
71
+ // An unconfirmed call remains fenced inside ManagedDialer.
72
+ throw error;
73
+ }
74
+ finally {
75
+ this.advancing = false;
76
+ }
77
+ }
78
+ }
@@ -0,0 +1,6 @@
1
+ export * from "./managedDialer.ts";
2
+ export * from "./dialingQueue.ts";
3
+ export * from "./indexedDbJournal.ts";
4
+ export * from "./voiceSdkAudio.ts";
5
+ export * from "./meetingRecorder.ts";
6
+ export * from "./meetingRecordingStore.ts";
@@ -0,0 +1,6 @@
1
+ export * from "./managedDialer.js";
2
+ export * from "./dialingQueue.js";
3
+ export * from "./indexedDbJournal.js";
4
+ export * from "./voiceSdkAudio.js";
5
+ export * from "./meetingRecorder.js";
6
+ export * from "./meetingRecordingStore.js";
@@ -0,0 +1,11 @@
1
+ import type { DialerIntent, DialerJournal } from "./managedDialer.ts";
2
+ /** Origin-local recovery journal. Browser capabilities never enter this store.
3
+ * Conflicting tabs cannot overwrite a different intent for the same scope. */
4
+ export declare class IndexedDbDialerJournal implements DialerJournal {
5
+ private readonly database;
6
+ constructor(name?: string);
7
+ private transaction;
8
+ read(scope: string): Promise<DialerIntent | null>;
9
+ write(intent: DialerIntent): Promise<void>;
10
+ clear(scope: string, key: string): Promise<void>;
11
+ }
@@ -0,0 +1,62 @@
1
+ /** Origin-local recovery journal. Browser capabilities never enter this store.
2
+ * Conflicting tabs cannot overwrite a different intent for the same scope. */
3
+ export class IndexedDbDialerJournal {
4
+ database;
5
+ constructor(name = "pyai-dialer") {
6
+ this.database = new Promise((resolve, reject) => {
7
+ const request = indexedDB.open(name, 1);
8
+ request.onupgradeneeded = () => { request.result.createObjectStore("intents", { keyPath: "scope" }); };
9
+ request.onsuccess = () => { request.result.onversionchange = () => request.result.close(); resolve(request.result); };
10
+ request.onerror = () => reject(new Error("Calling recovery storage is unavailable."));
11
+ request.onblocked = () => reject(new Error("Close the older dialer tab to upgrade recovery storage."));
12
+ });
13
+ }
14
+ async transaction(mode, operation) {
15
+ const db = await this.database;
16
+ return new Promise((resolve, reject) => {
17
+ const tx = db.transaction("intents", mode);
18
+ let value, failure = null;
19
+ tx.oncomplete = () => resolve(value);
20
+ tx.onerror = tx.onabort = () => reject(new Error(failure ?? "Calling recovery storage could not be updated."));
21
+ operation(tx.objectStore("intents"), next => { value = next; }, message => { failure = message; tx.abort(); });
22
+ });
23
+ }
24
+ read(scope) {
25
+ return this.transaction("readonly", (store, result) => {
26
+ const request = store.get(scope);
27
+ request.onsuccess = () => result(request.result ? structuredClone(request.result) : null);
28
+ });
29
+ }
30
+ write(intent) {
31
+ const next = structuredClone(intent);
32
+ return this.transaction("readwrite", (store, result, fail) => {
33
+ const request = store.get(next.scope);
34
+ request.onsuccess = () => {
35
+ const prior = request.result;
36
+ if (prior && (prior.key !== next.key || JSON.stringify(prior.input) !== JSON.stringify(next.input) ||
37
+ (prior.callId && prior.callId !== next.callId))) {
38
+ fail("Another call is already saved in this workspace. Recover it before dialing.");
39
+ return;
40
+ }
41
+ if (prior?.stopping)
42
+ next.stopping = true;
43
+ store.put(next);
44
+ result(undefined);
45
+ };
46
+ });
47
+ }
48
+ clear(scope, key) {
49
+ return this.transaction("readwrite", (store, result, fail) => {
50
+ const request = store.get(scope);
51
+ request.onsuccess = () => {
52
+ const prior = request.result;
53
+ if (prior && prior.key !== key) {
54
+ fail("The saved call changed; recover it before clearing.");
55
+ return;
56
+ }
57
+ store.delete(scope);
58
+ result(undefined);
59
+ };
60
+ });
61
+ }
62
+ }
@@ -0,0 +1,65 @@
1
+ import type { TelephonyBrowserSession, TelephonyBrowserSessionCreate, TelephonyCall } from "../index.ts";
2
+ /** Implement on your server using PyAI's telephony client. The browser receives
3
+ * a single-call capability, never an organization key or carrier credential. */
4
+ export interface DialerBroker {
5
+ create(input: TelephonyBrowserSessionCreate, idempotencyKey: string): Promise<TelephonyBrowserSession>;
6
+ get(callId: string): Promise<TelephonyCall>;
7
+ hangup(callId: string): Promise<TelephonyCall>;
8
+ }
9
+ export interface DialerIntent {
10
+ scope: string;
11
+ key: string;
12
+ input: TelephonyBrowserSessionCreate;
13
+ callId?: string;
14
+ stopping: boolean;
15
+ }
16
+ export interface DialerJournal {
17
+ read(scope: string): Promise<DialerIntent | null>;
18
+ write(intent: DialerIntent): Promise<void>;
19
+ clear(scope: string, key: string): Promise<void>;
20
+ }
21
+ export interface DialerAudio {
22
+ connect(session: TelephonyBrowserSession, event: (state: "ringing" | "active" | "disconnected") => void): Promise<void>;
23
+ disconnect(): void;
24
+ mute(value: boolean): void;
25
+ sendDigits(digits: string): void;
26
+ }
27
+ export interface DialerSnapshot {
28
+ state: "idle" | "preparing" | "ringing" | "active" | "stopping" | "unconfirmed" | "wrapup";
29
+ callId: string | null;
30
+ call: TelephonyCall | null;
31
+ muted: boolean;
32
+ error: string | null;
33
+ }
34
+ /** One immutable workspace/user scope per instance. Setup and stop retain the
35
+ * original intent through lost acknowledgments, reloads and audio failures. */
36
+ export declare class ManagedDialer {
37
+ private intent;
38
+ private snapshot;
39
+ private readonly listeners;
40
+ private operation;
41
+ private initialized;
42
+ private readonly scope;
43
+ private readonly broker;
44
+ private readonly journal;
45
+ private readonly audio;
46
+ private readonly newKey;
47
+ private readonly now;
48
+ constructor(scope: string, broker: DialerBroker, journal: DialerJournal, audio: DialerAudio, newKey?: () => string, now?: () => number);
49
+ get current(): DialerSnapshot;
50
+ subscribe(listener: (snapshot: DialerSnapshot) => void): () => void;
51
+ private update;
52
+ private exclusive;
53
+ restore(): Promise<void>;
54
+ start(input: TelephonyBrowserSessionCreate): Promise<void>;
55
+ retrySetup(): Promise<void>;
56
+ private setup;
57
+ refresh(): Promise<void>;
58
+ private readStatus;
59
+ private acceptStatus;
60
+ stop(): Promise<void>;
61
+ private stopKnown;
62
+ finishWrapup(): Promise<void>;
63
+ mute(value: boolean): void;
64
+ sendDigits(digits: string): void;
65
+ }