@pyai/sdk 0.9.3 → 0.12.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 +114 -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 +116 -0
  10. package/dist/dialer/dialingQueue.d.ts +36 -0
  11. package/dist/dialer/dialingQueue.js +110 -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 +219 -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 +136 -6
  29. package/dist/index.js +36 -3
  30. package/package.json +24 -1
  31. package/src/cli-omni-template.ts +2 -2
  32. package/src/cli.ts +25 -4
  33. package/src/dialer/app/app.css +1 -0
  34. package/src/dialer/app/app.html +7 -0
  35. package/src/dialer/app/app.js +88 -0
  36. package/src/dialer/app/icon.svg +1 -0
  37. package/src/dialer/app/manifest.webmanifest +1 -0
  38. package/src/dialer/appServer.ts +151 -0
  39. package/src/dialer/dialerElement.ts +87 -0
  40. package/src/dialer/dialingQueue.ts +93 -0
  41. package/src/dialer/index.ts +6 -0
  42. package/src/dialer/indexedDbJournal.ts +56 -0
  43. package/src/dialer/managedDialer.ts +190 -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 +121 -5
@@ -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,116 @@
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
+ const destinationInput = this.root.querySelector("input");
75
+ destinationInput.disabled = snapshot.state !== "idle";
76
+ const group = snapshot.call?.dialing_mode === "parallel" ? snapshot.call : null;
77
+ if (snapshot.state !== "idle" && snapshot.call)
78
+ destinationInput.value = group
79
+ ? group.connected_to ?? `${group.destinations?.length ?? 0} parallel lines` : snapshot.call.to;
80
+ this.root.querySelector(".hint").textContent = group
81
+ ? group.lines?.map(line => `${line.to} · ${line.status}`).join(" / ") ?? "The first answered line connects. Other lines are canceled."
82
+ : "Include the country code";
83
+ const call = this.root.querySelector("[data-action=call]");
84
+ call.disabled = snapshot.state === "stopping";
85
+ call.classList.toggle("end", !["idle", "wrapup"].includes(snapshot.state));
86
+ call.textContent = snapshot.state === "idle" ? "Call" : snapshot.state === "wrapup" ? "Done" : "End call";
87
+ const mute = this.root.querySelector("[data-action=mute]");
88
+ mute.disabled = snapshot.state !== "active";
89
+ mute.textContent = snapshot.muted ? "Unmute" : "Mute";
90
+ mute.setAttribute("aria-pressed", String(snapshot.muted));
91
+ this.root.querySelector("[data-action=recover]").hidden = !["unconfirmed", "stopping"].includes(snapshot.state);
92
+ this.root.querySelector(".error").textContent = snapshot.error ?? "";
93
+ }
94
+ async run(action) {
95
+ try {
96
+ await action();
97
+ }
98
+ catch (error) {
99
+ this.root.querySelector(".error").textContent = error instanceof Error ? error.message : "Calling request failed.";
100
+ }
101
+ }
102
+ async act() {
103
+ if (!this.dialer || !this.inputFor)
104
+ return;
105
+ await this.run(async () => {
106
+ if (this.dialer.current.state === "wrapup")
107
+ await this.wrapup();
108
+ else if (this.dialer.current.state !== "idle")
109
+ await this.dialer.stop();
110
+ else
111
+ await this.dialer.start(this.inputFor(this.root.querySelector("input").value.replace(/[\s()-]/g, "")));
112
+ });
113
+ }
114
+ }
115
+ if (!customElements.get("pyai-dialer"))
116
+ customElements.define("pyai-dialer", PyaiDialerElement);
@@ -0,0 +1,36 @@
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
+ /** Auto, priority-based dynamic, and server-owned parallel 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 activeIds;
17
+ private parallelLines;
18
+ private readonly dialer;
19
+ private readonly eligible;
20
+ constructor(dialer: ManagedDialer, eligible: (contact: DialingContact) => Promise<boolean>);
21
+ get current(): {
22
+ running: boolean;
23
+ remaining: number;
24
+ activeId: string | null;
25
+ activeIds: string[];
26
+ };
27
+ start(contacts: DialingContact[], mode?: "auto" | "dynamic" | "parallel", options?: {
28
+ parallelLines?: number;
29
+ }): Promise<void>;
30
+ pause(): void;
31
+ resume(): Promise<void>;
32
+ /** Explicit wrap-up acknowledgment gates the next admission. A local audio
33
+ * disconnect or a durable stop acknowledgment never advances the queue. */
34
+ finishWrapup(): Promise<void>;
35
+ private advance;
36
+ }
@@ -0,0 +1,110 @@
1
+ /** Auto, priority-based dynamic, and server-owned parallel 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
+ activeIds = [];
10
+ parallelLines = 1;
11
+ dialer;
12
+ eligible;
13
+ constructor(dialer, eligible) {
14
+ this.dialer = dialer;
15
+ this.eligible = eligible;
16
+ }
17
+ get current() { return { running: this.running, remaining: this.contacts.length, activeId: this.activeId, activeIds: [...this.activeIds] }; }
18
+ async start(contacts, mode = "auto", options = {}) {
19
+ if (this.running || this.advancing || this.dialer.current.state !== "idle")
20
+ throw new Error("Finish the current call before starting a queue.");
21
+ if (!contacts.length || contacts.length > 500 || new Set(contacts.map(c => c.id)).size !== contacts.length ||
22
+ contacts.some(c => !c.id || typeof c.input.to !== "string" || c.input.destinations !== undefined || !/^\+[1-9]\d{6,14}$/.test(c.input.to) || !Number.isFinite(c.priority ?? 0)))
23
+ throw new Error("Choose 1–500 unique contacts with valid destinations and priorities.");
24
+ if (!["auto", "dynamic", "parallel"].includes(mode))
25
+ throw new Error("Choose a supported calling order.");
26
+ const parallelLines = mode === "parallel" ? options.parallelLines ?? 2 : 1;
27
+ if (!Number.isInteger(parallelLines) || parallelLines < 1 || parallelLines > 4 || mode === "parallel" && parallelLines < 2)
28
+ throw new Error("Parallel dialing requires two to four lines.");
29
+ if (mode === "parallel") {
30
+ const fingerprint = (contact) => JSON.stringify([contact.input.from_number_id, contact.input.user_id,
31
+ contact.input.recording, contact.input.use_case ?? "support", contact.input.max_duration_seconds ?? 3600]);
32
+ if (new Set(contacts.map(c => c.input.to)).size !== contacts.length || contacts.some(c => fingerprint(c) !== fingerprint(contacts[0])))
33
+ throw new Error("Parallel contacts must have distinct numbers and share the same user, source and calling settings.");
34
+ }
35
+ this.parallelLines = parallelLines;
36
+ this.contacts = structuredClone(contacts);
37
+ if (mode === "dynamic" || mode === "parallel")
38
+ this.contacts.sort((a, b) => (b.priority ?? 0) - (a.priority ?? 0));
39
+ this.running = true;
40
+ await this.advance();
41
+ }
42
+ pause() { this.running = false; }
43
+ async resume() {
44
+ if (this.advancing)
45
+ throw new Error("Queue admission is still pending.");
46
+ if (!this.contacts.length)
47
+ return;
48
+ this.running = true;
49
+ if (this.dialer.current.state === "idle")
50
+ await this.advance();
51
+ }
52
+ /** Explicit wrap-up acknowledgment gates the next admission. A local audio
53
+ * disconnect or a durable stop acknowledgment never advances the queue. */
54
+ async finishWrapup() {
55
+ await this.dialer.finishWrapup();
56
+ this.activeId = null;
57
+ this.activeIds = [];
58
+ if (this.running)
59
+ await this.advance();
60
+ }
61
+ async advance() {
62
+ if (this.advancing || !this.running || this.dialer.current.state !== "idle")
63
+ return;
64
+ this.advancing = true;
65
+ try {
66
+ const batch = [];
67
+ // Select the entire batch before admitting one immutable group. Pausing
68
+ // during eligibility cannot launch a partial group or consume contacts.
69
+ const skipped = new Set();
70
+ for (const contact of this.contacts) {
71
+ if (!this.running || batch.length >= this.parallelLines)
72
+ break;
73
+ const permitted = await this.eligible(structuredClone(contact));
74
+ if (!this.running)
75
+ return;
76
+ if (permitted)
77
+ batch.push(contact);
78
+ else
79
+ skipped.add(contact.id);
80
+ }
81
+ if (!this.running)
82
+ return;
83
+ this.contacts = this.contacts.filter(contact => !skipped.has(contact.id));
84
+ if (batch.length) {
85
+ const first = batch[0];
86
+ this.activeId = first.id;
87
+ this.activeIds = batch.map(contact => contact.id);
88
+ const { to: _to, destinations: _destinations, ...common } = first.input;
89
+ const intent = batch.length === 1 ? first.input
90
+ : { ...common, destinations: batch.map(contact => contact.input.to) };
91
+ // ManagedDialer persists the group and one key before any request.
92
+ // Unconfirmed admission remains fenced; no individual line is retried.
93
+ await this.dialer.start(intent);
94
+ const admitted = new Set(this.activeIds);
95
+ this.contacts = this.contacts.filter(contact => !admitted.has(contact.id));
96
+ return;
97
+ }
98
+ if (!this.contacts.length)
99
+ this.running = false;
100
+ }
101
+ catch (error) {
102
+ this.running = false;
103
+ // An unconfirmed call remains fenced inside ManagedDialer.
104
+ throw error;
105
+ }
106
+ finally {
107
+ this.advancing = false;
108
+ }
109
+ }
110
+ }
@@ -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
+ }
@@ -0,0 +1,219 @@
1
+ const terminal = (call) => ["completed", "failed", "canceled"].includes(call.status);
2
+ /** One immutable workspace/user scope per instance. Setup and stop retain the
3
+ * original intent through lost acknowledgments, reloads and audio failures. */
4
+ export class ManagedDialer {
5
+ intent = null;
6
+ snapshot = { state: "idle", callId: null, call: null, muted: false, error: null };
7
+ listeners = new Set();
8
+ operation = null;
9
+ initialized = false;
10
+ scope;
11
+ broker;
12
+ journal;
13
+ audio;
14
+ newKey;
15
+ now;
16
+ constructor(scope, broker, journal, audio, newKey = () => crypto.randomUUID(), now = Date.now) {
17
+ if (!scope.trim())
18
+ throw new Error("An authenticated workspace/user scope is required.");
19
+ this.scope = scope;
20
+ this.broker = broker;
21
+ this.journal = journal;
22
+ this.audio = audio;
23
+ this.newKey = newKey;
24
+ this.now = now;
25
+ }
26
+ get current() { return structuredClone(this.snapshot); }
27
+ subscribe(listener) {
28
+ this.listeners.add(listener);
29
+ listener(this.current);
30
+ return () => { this.listeners.delete(listener); };
31
+ }
32
+ update(patch) {
33
+ this.snapshot = { ...this.snapshot, ...patch };
34
+ for (const listener of this.listeners) {
35
+ try {
36
+ listener(this.current);
37
+ }
38
+ catch { /* UI observers cannot interrupt cleanup. */ }
39
+ }
40
+ }
41
+ async exclusive(action) {
42
+ if (this.operation)
43
+ throw new Error("Calling operation is already in progress.");
44
+ const operation = action();
45
+ this.operation = operation;
46
+ try {
47
+ await operation;
48
+ }
49
+ finally {
50
+ if (this.operation === operation)
51
+ this.operation = null;
52
+ }
53
+ }
54
+ async restore() {
55
+ return this.exclusive(async () => {
56
+ if (this.initialized)
57
+ return;
58
+ const saved = await this.journal.read(this.scope);
59
+ if (saved && saved.scope !== this.scope)
60
+ throw new Error("Saved call belongs to another workspace.");
61
+ this.intent = saved ? structuredClone(saved) : null;
62
+ this.initialized = true;
63
+ if (saved) {
64
+ this.update({ state: "unconfirmed", callId: saved.callId ?? null, error: "Recover the previous call before starting another." });
65
+ // Reload never consumes a new browser capability automatically.
66
+ if (saved.callId)
67
+ await this.readStatus();
68
+ }
69
+ });
70
+ }
71
+ async start(input) {
72
+ if (!this.initialized)
73
+ throw new Error("Restore the calling journal before dialing.");
74
+ if (this.intent)
75
+ throw new Error("The previous call must finish and be wrapped up first.");
76
+ const destinations = input.destinations ?? [input.to];
77
+ if ((input.destinations !== undefined && (input.to !== undefined || !Array.isArray(input.destinations) || destinations.length < 2 || destinations.length > 4)) ||
78
+ new Set(destinations).size !== destinations.length || destinations.some(to => typeof to !== "string" || !/^\+[1-9]\d{6,14}$/.test(to)))
79
+ throw new Error("Choose one destination or two to four distinct parallel destinations with country codes.");
80
+ return this.exclusive(async () => {
81
+ const intent = { scope: this.scope, key: this.newKey(), input: structuredClone(input), stopping: false };
82
+ // Persist before the first network request. A storage failure cannot dial.
83
+ await this.journal.write(structuredClone(intent));
84
+ this.intent = intent;
85
+ await this.setup();
86
+ });
87
+ }
88
+ async retrySetup() {
89
+ if (!this.intent)
90
+ throw new Error("No call to recover.");
91
+ return this.exclusive(async () => {
92
+ if (this.intent.callId) {
93
+ await this.readStatus();
94
+ return;
95
+ }
96
+ await this.setup();
97
+ });
98
+ }
99
+ async setup() {
100
+ const intent = this.intent;
101
+ this.update({ state: intent.stopping ? "stopping" : "preparing", error: null });
102
+ try {
103
+ const session = await this.broker.create(structuredClone(intent.input), intent.key);
104
+ if (session.id !== session.call_id || session.call.id !== session.call_id || session.connect_params.session_id !== session.call_id ||
105
+ session.transport !== "voice-sdk" || (intent.callId && intent.callId !== session.call_id))
106
+ throw new Error("Calling session identity changed.");
107
+ intent.callId = session.call_id;
108
+ await this.journal.write(structuredClone(intent));
109
+ const saved = await this.journal.read(this.scope);
110
+ if (!saved || saved.key !== intent.key || saved.callId !== intent.callId)
111
+ throw new Error("Calling recovery intent changed.");
112
+ if (saved.stopping)
113
+ intent.stopping = true;
114
+ this.update({ callId: session.call_id, call: session.call });
115
+ if (terminal(session.call)) {
116
+ await this.acceptStatus(session.call);
117
+ return;
118
+ }
119
+ if (intent.stopping) {
120
+ await this.stopKnown();
121
+ return;
122
+ }
123
+ if (!session.access_token || session.expires_at <= this.now() || session.call.stop_requested) {
124
+ this.update({ state: "unconfirmed", error: "This session was consumed, stopped or expired. End or recover the original call." });
125
+ return;
126
+ }
127
+ await this.audio.connect(session, state => {
128
+ if (this.intent !== intent || intent.stopping || this.snapshot.state === "wrapup")
129
+ return;
130
+ if (state === "disconnected") {
131
+ this.audio.disconnect();
132
+ this.update({ state: "unconfirmed", error: "Audio disconnected. Check the original call before dialing again." });
133
+ }
134
+ else
135
+ this.update({ state, error: null });
136
+ });
137
+ }
138
+ catch {
139
+ this.audio.disconnect();
140
+ this.update({ state: "unconfirmed", error: "Call setup is unconfirmed. Recover or end this same attempt." });
141
+ }
142
+ }
143
+ async refresh() {
144
+ if (this.operation)
145
+ await this.operation;
146
+ return this.exclusive(() => this.readStatus());
147
+ }
148
+ async readStatus() {
149
+ if (!this.intent?.callId)
150
+ return;
151
+ try {
152
+ await this.acceptStatus(await this.broker.get(this.intent.callId));
153
+ }
154
+ catch {
155
+ this.update({ error: "Call status is unavailable. The original call is still retained." });
156
+ }
157
+ }
158
+ async acceptStatus(call) {
159
+ if (!this.intent || call.id !== this.intent.callId)
160
+ throw new Error("Calling status identity changed.");
161
+ if (this.snapshot.call && call.version < this.snapshot.call.version)
162
+ return;
163
+ if (terminal(call)) {
164
+ this.audio.disconnect();
165
+ this.update({ call, state: "wrapup", muted: false, error: null });
166
+ }
167
+ else
168
+ this.update({ call });
169
+ }
170
+ async stop() {
171
+ if (!this.intent)
172
+ return;
173
+ // Mark immediately so a late create acknowledgment cannot connect audio.
174
+ this.intent.stopping = true;
175
+ this.audio.disconnect();
176
+ this.update({ state: "stopping", muted: false });
177
+ // Await in-flight setup; never issue an independent replacement create.
178
+ if (this.operation)
179
+ await this.operation;
180
+ return this.exclusive(async () => {
181
+ await this.journal.write(structuredClone(this.intent));
182
+ if (!this.intent.callId)
183
+ await this.setup();
184
+ else
185
+ await this.stopKnown();
186
+ });
187
+ }
188
+ async stopKnown() {
189
+ try {
190
+ const call = await this.broker.hangup(this.intent.callId);
191
+ await this.acceptStatus(call);
192
+ if (!terminal(call))
193
+ this.update({ state: "stopping", error: null });
194
+ }
195
+ catch {
196
+ this.update({ state: "unconfirmed", error: "Stop is unconfirmed. Retry ending the same call." });
197
+ }
198
+ }
199
+ async finishWrapup() {
200
+ return this.exclusive(async () => {
201
+ if (!this.intent || this.snapshot.state !== "wrapup" || !this.snapshot.call || !terminal(this.snapshot.call))
202
+ throw new Error("Confirmed call completion is required.");
203
+ await this.journal.clear(this.scope, this.intent.key);
204
+ this.intent = null;
205
+ this.update({ state: "idle", callId: null, call: null, muted: false, error: null });
206
+ });
207
+ }
208
+ mute(value) {
209
+ if (this.snapshot.state !== "active")
210
+ throw new Error("No active audio call.");
211
+ this.audio.mute(value);
212
+ this.update({ muted: value });
213
+ }
214
+ sendDigits(digits) {
215
+ if (this.snapshot.state !== "active" || !/^[0-9*#w]{1,32}$/.test(digits))
216
+ throw new Error("Enter up to 32 keypad digits on an active call.");
217
+ this.audio.sendDigits(digits);
218
+ }
219
+ }