@pyai/sdk 0.11.0 → 0.13.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.
@@ -8,6 +8,7 @@ import { dirname, join } from "node:path";
8
8
  import { Readable } from "node:stream";
9
9
  import type { PyAI, TelephonyBrowserSessionCreate, TelephonyCall } from "../index.ts";
10
10
  import { createServerDialerBroker } from "./serverBroker.ts";
11
+ import { dialerCallHandedOff } from "./managedDialer.ts";
11
12
 
12
13
  export interface DialerAppOptions {
13
14
  sdk: PyAI;
@@ -16,6 +17,8 @@ export interface DialerAppOptions {
16
17
  scope: string;
17
18
  name?: string;
18
19
  whiteLabel?: boolean;
20
+ /** Operator opt-in; the API independently enforces transfer activation. */
21
+ allowTransfers?: boolean;
19
22
  port?: number;
20
23
  /** Explicit asset injection for packaging/tests, never selected by HTTP. */
21
24
  assets?: { read(path: string): Promise<Uint8Array> };
@@ -60,7 +63,7 @@ export async function startDialerApp(options: DialerAppOptions) {
60
63
  const bootstrap = randomBytes(32).toString("base64url"), rendererToken = randomBytes(32).toString("base64url"), bootstrapExpires = Date.now() + 60000;
61
64
  let bootstrapUsed = false;
62
65
  let origin = "", closing = false; const calls = new Set<string>();
63
- const remember = (call: TelephonyCall) => { if (terminal(call)) calls.delete(call.id); else calls.add(call.id); return call; };
66
+ const remember = (call: TelephonyCall) => { if (terminal(call) || dialerCallHandedOff(call)) calls.delete(call.id); else calls.add(call.id); return call; };
64
67
  const numbers = async () => (await options.sdk.telephony.numbers.list()).data.filter(number => number.status !== "released" && number.capabilities?.voice === true);
65
68
  const own = async (id: string) => remember(await broker.get(id));
66
69
  const server = createServer(async (request, response) => {
@@ -87,16 +90,29 @@ export async function startDialerApp(options: DialerAppOptions) {
87
90
  }
88
91
  if (url.pathname === "/api/config" && method === "GET") {
89
92
  const owned = await numbers();
90
- 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,
93
+ return json(response, 200, { name: options.name ?? (options.whiteLabel ? "Phone" : "PyAI Phone"), white_label: options.whiteLabel === true, transfers_enabled: options.allowTransfers === true, scope: options.scope, user_id: options.userId, nonce,
91
94
  numbers: owned.map(number => ({ id: number.id, phone_number: number.phone_number, country: number.country })) });
92
95
  }
93
96
  if (url.pathname === "/api/sessions" && method === "POST") {
94
97
  if (closing) throw new AppError(503, "Dialer is closing. No new calls are admitted.");
95
98
  const input = await body(request), key = request.headers["idempotency-key"];
99
+ if (input.transfer_enabled === true && options.allowTransfers !== true) throw new AppError(400, "Open this dialer with transfers enabled before starting a transferable call.");
96
100
  if (typeof key !== "string" || typeof input.from_number_id !== "string" || !(await numbers()).some(number => number.id === input.from_number_id)) throw new AppError(400, "Choose an owned voice number and a calling retry key.");
97
101
  const session = await broker.create(input as unknown as TelephonyBrowserSessionCreate, key); remember(session.call);
98
102
  return json(response, 200, session);
99
103
  }
104
+ const transferPath = /^\/api\/calls\/([A-Za-z0-9_-]{1,200})\/transfers(?:\/([A-Za-z0-9_-]{1,200})\/(complete|cancel))?$/.exec(url.pathname);
105
+ if (transferPath && method === "POST") {
106
+ if (closing || options.allowTransfers !== true) throw new AppError(503, "Transfers are not enabled in this dialer.");
107
+ const id = transferPath[1]!, transferId = transferPath[2], operation = transferPath[3];
108
+ await own(id); const input = await body(request);
109
+ if (transferId && (operation === "complete" || operation === "cancel"))
110
+ return json(response, 202, remember(await broker.transfers![operation](id, transferId)));
111
+ const key = request.headers["idempotency-key"];
112
+ if (typeof key !== "string" || typeof input.to !== "string" || !/^\+[1-9]\d{6,14}$/.test(input.to) || !["warm", "cold"].includes(String(input.mode)))
113
+ throw new AppError(400, "Choose a transfer destination, mode and retry key.");
114
+ return json(response, 202, remember(await broker.transfers!.create(id, { to: input.to, mode: input.mode as "warm" | "cold" }, key)));
115
+ }
100
116
  const callPath = /^\/api\/calls\/([A-Za-z0-9_-]{1,200})(?:\/(hangup|recording))?$/.exec(url.pathname);
101
117
  if (callPath) {
102
118
  const id = callPath[1]!, operation = callPath[2]; await own(id);
@@ -18,13 +18,17 @@ export class PyaiDialerElement extends HTMLElement {
18
18
  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}
19
19
  .status{display:flex;align-items:center;gap:7px;color:#667085;margin:20px 0 5px}.dot{width:7px;height:7px;border-radius:50%;background:#9a9dad}.dot.active{background:#12a777}
20
20
  input{width:100%;border:0;border-bottom:1px solid #ececf2;padding:12px 0;font:500 26px/1.3 system-ui;letter-spacing:.5px;color:inherit;background:transparent}input:focus{outline:0;border-color:var(--dialer-accent)}
21
- .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}
21
+ .hint,.transfer-help{font-size:12px;color:#8c91a2;margin-top:8px}.keys{display:grid;grid-template-columns:repeat(3,1fr);gap:8px;margin:22px 0}.key{background:#f8f8fb;border:0;border-radius:14px;padding:9px;cursor:pointer;font:500 23px system-ui;color:inherit;min-height:57px}.key small{display:block;font-size:9px;letter-spacing:2px;color:#9296a5;margin-top:1px}.key:hover{background:#eeedf9}
22
22
  .actions{display:flex;gap:8px}button{font:600 13px system-ui;cursor:pointer}button:focus-visible{outline:3px solid #bdb8ff;outline-offset:2px}.primary,.secondary{border:0;border-radius:13px;padding:14px 18px;min-height:46px}.primary{flex:1;color:white;background:var(--dialer-accent)}.primary.end{background:#da4055}.secondary{background:#f1f2f7;color:#535b70}button:disabled{opacity:.45;cursor:default}.error{color:#b42338;font-size:12px;min-height:18px;margin:12px 0 0}.privacy{font-size:11px;color:#8b91a1;margin:16px 0 0;text-align:center}
23
23
  @media(prefers-color-scheme:dark){:host{color:#eaebf3}section{background:#191b26;border-color:#303341}.key{background:#252836}.key:hover,.secondary{background:#34364a}.badge{background:#282b39;color:#a7aec0}input{border-color:#36394a}.error{color:#ff9eaa}}
24
24
  </style><section aria-label="Phone"><header><h2>Phone</h2><span class="badge">PyAI</span></header>
25
25
  <div class="status" role="status" aria-live="polite"><span class="dot"></span><span data-status>Connect your workspace</span></div>
26
26
  <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>
27
27
  <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>
28
+ <div data-transfer hidden><p data-transfer-status role="status" aria-live="polite"></p><input class="transfer-number" type="tel" aria-label="Transfer phone number" placeholder="+61 2 5550 1000" maxlength="32">
29
+ <div class="actions"><button class="secondary" data-action="warm">Consult first</button><button class="secondary" data-action="cold">Transfer now</button></div>
30
+ <p class="transfer-help">Consult first keeps your caller on hold while you talk to the target. Transfer now leaves the call before the target answers.</p>
31
+ <div class="actions"><button class="primary" data-action="complete-transfer" hidden>Complete transfer</button><button class="secondary" data-action="cancel-transfer" hidden>Return to caller</button><button class="secondary" data-action="recover-transfer" hidden>Recover transfer</button></div></div>
28
32
  <p class="error" role="alert"></p><p class="privacy">Calls and recordings stay in your workspace</p></section>`;
29
33
  const letters = ["", "ABC", "DEF", "GHI", "JKL", "MNO", "PQRS", "TUV", "WXYZ", "", "+", ""];
30
34
  "123456789*0#".split("").forEach((digit, i) => {
@@ -40,6 +44,11 @@ export class PyaiDialerElement extends HTMLElement {
40
44
  this.root.querySelector("[data-action=mute]")!.addEventListener("click", () => { if (this.dialer) this.dialer.mute(!this.dialer.current.muted); });
41
45
  this.root.querySelector("[data-action=recover]")!.addEventListener("click", () => void this.run(() => this.dialer!.retrySetup()));
42
46
  this.root.querySelector("input")!.addEventListener("keydown", event => { if (event.key === "Enter") void this.act(); });
47
+ for (const [action, mode] of [["warm", "warm"], ["cold", "cold"]] as const)
48
+ this.root.querySelector(`[data-action=${action}]`)!.addEventListener("click", () => void this.run(() => this.dialer!.transfer(this.root.querySelector<HTMLInputElement>(".transfer-number")!.value.replace(/[\s()-]/g, ""), mode)));
49
+ this.root.querySelector("[data-action=complete-transfer]")!.addEventListener("click", () => void this.run(() => this.dialer!.completeTransfer()));
50
+ this.root.querySelector("[data-action=cancel-transfer]")!.addEventListener("click", () => void this.run(() => this.dialer!.cancelTransfer()));
51
+ this.root.querySelector("[data-action=recover-transfer]")!.addEventListener("click", () => void this.run(() => this.dialer!.retryTransfer()));
43
52
  }
44
53
  bind(dialer: ManagedDialer, inputFor: (to: string) => TelephonyBrowserSessionCreate, appearance: DialerAppearance = {}, finishWrapup?: () => Promise<void>) {
45
54
  if (this.dialer && this.dialer !== dialer && this.dialer.current.state !== "idle") throw new Error("Finish the current call before switching workspaces.");
@@ -52,18 +61,35 @@ export class PyaiDialerElement extends HTMLElement {
52
61
  connectedCallback() { if (this.dialer && !this.unsubscribe) this.unsubscribe = this.dialer.subscribe(s => this.render(s)); }
53
62
  disconnectedCallback() { this.unsubscribe?.(); this.unsubscribe = null; }
54
63
  private render(snapshot: DialerSnapshot) {
55
- const labels: Record<DialerSnapshot["state"], string> = { idle: "Ready to call", preparing: "Connecting…", ringing: "Ringing…", active: "Connected", stopping: "Confirming call ended…", unconfirmed: "Call needs recovery", wrapup: "Call finished" };
64
+ const labels: Record<DialerSnapshot["state"], string> = { idle: "Ready to call", preparing: "Connecting…", ringing: "Ringing…", active: "Connected", stopping: "Confirming call ended…", unconfirmed: "Call needs recovery", handing_off: "Transfer in progress · caller stays connected", transferred: "Transfer complete · caller stays connected", wrapup: "Call finished" };
56
65
  this.root.querySelector("[data-status]")!.textContent = labels[snapshot.state];
57
66
  this.root.querySelector(".dot")!.classList.toggle("active", snapshot.state === "active");
58
- this.root.querySelector("input")!.disabled = snapshot.state !== "idle";
67
+ const destinationInput = this.root.querySelector("input")!;
68
+ destinationInput.disabled = snapshot.state !== "idle";
69
+ const group = snapshot.call?.dialing_mode === "parallel" ? snapshot.call : null;
70
+ if (snapshot.state !== "idle" && snapshot.call) destinationInput.value = group
71
+ ? group.connected_to ?? `${group.destinations?.length ?? 0} parallel lines` : snapshot.call.to;
72
+ this.root.querySelector(".hint")!.textContent = group
73
+ ? group.lines?.map(line => `${line.to} · ${line.status}`).join(" / ") ?? "The first answered line connects. Other lines are canceled."
74
+ : "Include the country code";
59
75
  const call = this.root.querySelector<HTMLButtonElement>("[data-action=call]")!;
60
- call.disabled = snapshot.state === "stopping"; call.classList.toggle("end", !["idle", "wrapup"].includes(snapshot.state));
61
- call.textContent = snapshot.state === "idle" ? "Call" : snapshot.state === "wrapup" ? "Done" : "End call";
76
+ call.disabled = ["stopping", "handing_off"].includes(snapshot.state); call.classList.toggle("end", !["idle", "wrapup", "transferred"].includes(snapshot.state));
77
+ call.textContent = snapshot.state === "idle" ? "Call" : ["wrapup", "transferred"].includes(snapshot.state) ? "Done" : snapshot.state === "handing_off" ? "Transferring…" : "End call";
62
78
  const mute = this.root.querySelector<HTMLButtonElement>("[data-action=mute]")!;
63
79
  mute.disabled = snapshot.state !== "active"; mute.textContent = snapshot.muted ? "Unmute" : "Mute";
64
80
  mute.setAttribute("aria-pressed", String(snapshot.muted));
65
81
  this.root.querySelector<HTMLButtonElement>("[data-action=recover]")!.hidden = !["unconfirmed", "stopping"].includes(snapshot.state);
66
82
  this.root.querySelector(".error")!.textContent = snapshot.error ?? "";
83
+ const transfer = snapshot.call?.transfers?.at(-1), pending = transfer && !["completed", "canceled", "failed"].includes(transfer.status);
84
+ this.root.querySelector<HTMLElement>("[data-transfer]")!.hidden = snapshot.call?.transfer_enabled !== true || ["idle", "preparing", "ringing", "wrapup"].includes(snapshot.state);
85
+ this.root.querySelector("[data-transfer-status]")!.textContent = transfer ? `${transfer.to ?? "Transfer target"} · ${transfer.status}` : "Transfer this caller";
86
+ this.root.querySelector<HTMLInputElement>(".transfer-number")!.disabled = Boolean(pending || snapshot.transferPending || snapshot.state !== "active");
87
+ for (const action of ["warm", "cold"]) this.root.querySelector<HTMLButtonElement>(`[data-action=${action}]`)!.disabled = Boolean(pending || snapshot.transferPending || snapshot.state !== "active");
88
+ const complete = this.root.querySelector<HTMLButtonElement>("[data-action=complete-transfer]")!;
89
+ complete.hidden = transfer?.mode !== "warm" || transfer.status !== "ready"; complete.disabled = Boolean(snapshot.transferPending);
90
+ const cancel = this.root.querySelector<HTMLButtonElement>("[data-action=cancel-transfer]")!;
91
+ cancel.hidden = transfer?.mode !== "warm" || !pending; cancel.disabled = Boolean(snapshot.transferPending || ["completing", "canceling"].includes(transfer?.status ?? ""));
92
+ this.root.querySelector<HTMLButtonElement>("[data-action=recover-transfer]")!.hidden = !snapshot.transferPending;
67
93
  }
68
94
  private async run(action: () => Promise<void>) {
69
95
  try { await action(); } catch (error) { this.root.querySelector(".error")!.textContent = error instanceof Error ? error.message : "Calling request failed."; }
@@ -71,7 +97,7 @@ export class PyaiDialerElement extends HTMLElement {
71
97
  private async act() {
72
98
  if (!this.dialer || !this.inputFor) return;
73
99
  await this.run(async () => {
74
- if (this.dialer!.current.state === "wrapup") await this.wrapup!();
100
+ if (["wrapup", "transferred"].includes(this.dialer!.current.state)) await this.wrapup!();
75
101
  else if (this.dialer!.current.state !== "idle") await this.dialer!.stop();
76
102
  else await this.dialer!.start(this.inputFor!(this.root.querySelector("input")!.value.replace(/[\s()-]/g, "")));
77
103
  });
@@ -6,7 +6,7 @@ export interface DialingContact {
6
6
  input: TelephonyBrowserSessionCreate;
7
7
  priority?: number;
8
8
  }
9
- /** Sequential auto dialing and priority-based dynamic dialing. A session must
9
+ /** Auto, priority-based dynamic, and server-owned parallel dialing. A session must
10
10
  * be explicitly started in the foreground; no calls resume automatically after
11
11
  * reload. The backend rechecks policy and capacity for every admission. */
12
12
  export class DialingQueue {
@@ -14,18 +14,33 @@ export class DialingQueue {
14
14
  private running = false;
15
15
  private advancing = false;
16
16
  private activeId: string | null = null;
17
+ private activeIds: string[] = [];
18
+ private parallelLines = 1;
17
19
  private readonly dialer: ManagedDialer;
18
20
  private readonly eligible: (contact: DialingContact) => Promise<boolean>;
19
21
  constructor(dialer: ManagedDialer, eligible: (contact: DialingContact) => Promise<boolean>) {
20
22
  this.dialer = dialer; this.eligible = eligible;
21
23
  }
22
- get current() { return { running: this.running, remaining: this.contacts.length, activeId: this.activeId }; }
23
- async start(contacts: DialingContact[], mode: "auto" | "dynamic" = "auto") {
24
+ get current() { return { running: this.running, remaining: this.contacts.length, activeId: this.activeId, activeIds: [...this.activeIds] }; }
25
+ async start(contacts: DialingContact[], mode: "auto" | "dynamic" | "parallel" = "auto", options: { parallelLines?: number } = {}) {
24
26
  if (this.running || this.advancing || this.dialer.current.state !== "idle") throw new Error("Finish the current call before starting a queue.");
25
27
  if (!contacts.length || contacts.length > 500 || new Set(contacts.map(c => c.id)).size !== contacts.length ||
26
- contacts.some(c => !c.id || !/^\+[1-9]\d{6,14}$/.test(c.input.to) || !Number.isFinite(c.priority ?? 0))) throw new Error("Choose 1–500 unique contacts with valid destinations and priorities.");
28
+ 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))) throw new Error("Choose 1–500 unique contacts with valid destinations and priorities.");
29
+ if (!["auto", "dynamic", "parallel"].includes(mode)) throw new Error("Choose a supported calling order.");
30
+ const parallelLines = mode === "parallel" ? options.parallelLines ?? 2 : 1;
31
+ if (!Number.isInteger(parallelLines) || parallelLines < 1 || parallelLines > 4 || mode === "parallel" && parallelLines < 2)
32
+ throw new Error("Parallel dialing requires two to four lines.");
33
+ if (mode === "parallel") {
34
+ if (contacts.some(contact => contact.input.transfer_enabled === true))
35
+ throw new Error("Transfer-enabled calls use single-line dialing.");
36
+ const fingerprint = (contact: DialingContact) => JSON.stringify([contact.input.from_number_id, contact.input.user_id,
37
+ contact.input.recording, contact.input.use_case ?? "support", contact.input.max_duration_seconds ?? 3600]);
38
+ if (new Set(contacts.map(c => c.input.to)).size !== contacts.length || contacts.some(c => fingerprint(c) !== fingerprint(contacts[0]!)))
39
+ throw new Error("Parallel contacts must have distinct numbers and share the same user, source and calling settings.");
40
+ }
41
+ this.parallelLines = parallelLines;
27
42
  this.contacts = structuredClone(contacts);
28
- if (mode === "dynamic") this.contacts.sort((a, b) => (b.priority ?? 0) - (a.priority ?? 0));
43
+ if (mode === "dynamic" || mode === "parallel") this.contacts.sort((a, b) => (b.priority ?? 0) - (a.priority ?? 0));
29
44
  this.running = true; await this.advance();
30
45
  }
31
46
  pause() { this.running = false; }
@@ -38,22 +53,37 @@ export class DialingQueue {
38
53
  /** Explicit wrap-up acknowledgment gates the next admission. A local audio
39
54
  * disconnect or a durable stop acknowledgment never advances the queue. */
40
55
  async finishWrapup() {
41
- await this.dialer.finishWrapup(); this.activeId = null;
56
+ await this.dialer.finishWrapup(); this.activeId = null; this.activeIds = [];
42
57
  if (this.running) await this.advance();
43
58
  }
44
59
  private async advance() {
45
60
  if (this.advancing || !this.running || this.dialer.current.state !== "idle") return;
46
61
  this.advancing = true;
47
62
  try {
48
- while (this.running && this.contacts.length) {
49
- const contact = this.contacts[0]!;
63
+ const batch: DialingContact[] = [];
64
+ // Select the entire batch before admitting one immutable group. Pausing
65
+ // during eligibility cannot launch a partial group or consume contacts.
66
+ const skipped = new Set<string>();
67
+ for (const contact of this.contacts) {
68
+ if (!this.running || batch.length >= this.parallelLines) break;
50
69
  const permitted = await this.eligible(structuredClone(contact));
51
70
  if (!this.running) return;
52
- if (!permitted) { this.contacts.shift(); continue; }
53
- this.activeId = contact.id;
54
- // Remove only once this intent has been durably admitted locally.
55
- await this.dialer.start(contact.input);
56
- this.contacts.shift(); return;
71
+ if (permitted) batch.push(contact); else skipped.add(contact.id);
72
+ }
73
+ if (!this.running) return;
74
+ this.contacts = this.contacts.filter(contact => !skipped.has(contact.id));
75
+ if (batch.length) {
76
+ const first = batch[0]!;
77
+ this.activeId = first.id; this.activeIds = batch.map(contact => contact.id);
78
+ const { to: _to, destinations: _destinations, transfer_enabled: _transferEnabled, ...common } = first.input;
79
+ const intent: TelephonyBrowserSessionCreate = batch.length === 1 ? first.input
80
+ : { ...common, destinations: batch.map(contact => contact.input.to!) };
81
+ // ManagedDialer persists the group and one key before any request.
82
+ // Unconfirmed admission remains fenced; no individual line is retried.
83
+ await this.dialer.start(intent);
84
+ const admitted = new Set(this.activeIds);
85
+ this.contacts = this.contacts.filter(contact => !admitted.has(contact.id));
86
+ return;
57
87
  }
58
88
  if (!this.contacts.length) this.running = false;
59
89
  } catch (error) {
@@ -39,6 +39,21 @@ export class IndexedDbDialerJournal implements DialerJournal {
39
39
  fail("Another call is already saved in this workspace. Recover it before dialing."); return;
40
40
  }
41
41
  if (prior?.stopping) next.stopping = true;
42
+ next.retiredTransferKeys = [...new Set([...(prior?.retiredTransferKeys ?? []), ...(next.retiredTransferKeys ?? [])])];
43
+ if (next.transfer && next.retiredTransferKeys.includes(next.transfer.key)) {
44
+ fail("This transfer has already finished. Refresh the original call."); return;
45
+ }
46
+ if (prior?.transfer && !next.retiredTransferKeys.includes(prior.transfer.key)) {
47
+ if (!next.transfer) next.transfer = structuredClone(prior.transfer);
48
+ else if (prior.transfer.key !== next.transfer.key || prior.transfer.to !== next.transfer.to || prior.transfer.mode !== next.transfer.mode ||
49
+ prior.transfer.id && next.transfer.id && prior.transfer.id !== next.transfer.id ||
50
+ prior.transfer.command && next.transfer.command && prior.transfer.command !== next.transfer.command) {
51
+ fail("Another transfer is saved for this call. Recover the original transfer."); return;
52
+ } else {
53
+ next.transfer.id ??= prior.transfer.id;
54
+ next.transfer.command ??= prior.transfer.command;
55
+ }
56
+ }
42
57
  store.put(next); result(undefined);
43
58
  };
44
59
  });
@@ -6,6 +6,11 @@ export interface DialerBroker {
6
6
  create(input: TelephonyBrowserSessionCreate, idempotencyKey: string): Promise<TelephonyBrowserSession>;
7
7
  get(callId: string): Promise<TelephonyCall>;
8
8
  hangup(callId: string): Promise<TelephonyCall>;
9
+ transfers?: {
10
+ create(callId: string, input: { to: string; mode: "warm" | "cold" }, key: string): Promise<TelephonyCall>;
11
+ complete(callId: string, transferId: string): Promise<TelephonyCall>;
12
+ cancel(callId: string, transferId: string): Promise<TelephonyCall>;
13
+ };
9
14
  }
10
15
  export interface DialerIntent {
11
16
  scope: string;
@@ -13,6 +18,8 @@ export interface DialerIntent {
13
18
  input: TelephonyBrowserSessionCreate;
14
19
  callId?: string;
15
20
  stopping: boolean;
21
+ transfer?: { key: string; to: string; mode: "warm" | "cold"; id?: string; command?: "complete" | "cancel" };
22
+ retiredTransferKeys?: string[];
16
23
  }
17
24
  export interface DialerJournal {
18
25
  read(scope: string): Promise<DialerIntent | null>;
@@ -26,13 +33,17 @@ export interface DialerAudio {
26
33
  sendDigits(digits: string): void;
27
34
  }
28
35
  export interface DialerSnapshot {
29
- state: "idle" | "preparing" | "ringing" | "active" | "stopping" | "unconfirmed" | "wrapup";
36
+ state: "idle" | "preparing" | "ringing" | "active" | "stopping" | "unconfirmed" | "handing_off" | "transferred" | "wrapup";
30
37
  callId: string | null;
31
38
  call: TelephonyCall | null;
32
39
  muted: boolean;
33
40
  error: string | null;
41
+ transferPending?: boolean;
34
42
  }
35
43
  const terminal = (call: TelephonyCall) => ["completed", "failed", "canceled"].includes(call.status);
44
+ /** A durable handoff keeps its original room after the browser goes away. */
45
+ export const dialerCallHandedOff = (call: TelephonyCall) => call.transfer_enabled === true && Boolean(call.transfers?.some(transfer =>
46
+ transfer.status === "completed" || transfer.mode === "cold" && ["dialing", "ready", "completing"].includes(transfer.status)));
36
47
 
37
48
  /** One immutable workspace/user scope per instance. Setup and stop retain the
38
49
  * original intent through lost acknowledgments, reloads and audio failures. */
@@ -78,7 +89,7 @@ export class ManagedDialer {
78
89
  this.intent = saved ? structuredClone(saved) : null;
79
90
  this.initialized = true;
80
91
  if (saved) {
81
- this.update({ state: "unconfirmed", callId: saved.callId ?? null, error: "Recover the previous call before starting another." });
92
+ this.update({ state: "unconfirmed", callId: saved.callId ?? null, transferPending: Boolean(saved.transfer), error: "Recover the previous call before starting another." });
82
93
  // Reload never consumes a new browser capability automatically.
83
94
  if (saved.callId) await this.readStatus();
84
95
  }
@@ -87,7 +98,10 @@ export class ManagedDialer {
87
98
  async start(input: TelephonyBrowserSessionCreate): Promise<void> {
88
99
  if (!this.initialized) throw new Error("Restore the calling journal before dialing.");
89
100
  if (this.intent) throw new Error("The previous call must finish and be wrapped up first.");
90
- if (!/^\+[1-9]\d{6,14}$/.test(input.to)) throw new Error("Enter the full destination with its country code.");
101
+ const destinations = input.destinations ?? [input.to];
102
+ if ((input.destinations !== undefined && (input.to !== undefined || !Array.isArray(input.destinations) || destinations.length < 2 || destinations.length > 4)) ||
103
+ new Set(destinations).size !== destinations.length || destinations.some(to => typeof to !== "string" || !/^\+[1-9]\d{6,14}$/.test(to)))
104
+ throw new Error("Choose one destination or two to four distinct parallel destinations with country codes.");
91
105
  return this.exclusive(async () => {
92
106
  const intent: DialerIntent = { scope: this.scope, key: this.newKey(), input: structuredClone(input), stopping: false };
93
107
  // Persist before the first network request. A storage failure cannot dial.
@@ -115,13 +129,13 @@ export class ManagedDialer {
115
129
  if (!saved || saved.key !== intent.key || saved.callId !== intent.callId) throw new Error("Calling recovery intent changed.");
116
130
  if (saved.stopping) intent.stopping = true;
117
131
  this.update({ callId: session.call_id, call: session.call });
118
- if (terminal(session.call)) { await this.acceptStatus(session.call); return; }
132
+ if (terminal(session.call) || dialerCallHandedOff(session.call)) { await this.acceptStatus(session.call); return; }
119
133
  if (intent.stopping) { await this.stopKnown(); return; }
120
134
  if (!session.access_token || session.expires_at <= this.now() || session.call.stop_requested) {
121
135
  this.update({ state: "unconfirmed", error: "This session was consumed, stopped or expired. End or recover the original call." }); return;
122
136
  }
123
137
  await this.audio.connect(session, state => {
124
- if (this.intent !== intent || intent.stopping || this.snapshot.state === "wrapup") return;
138
+ if (this.intent?.key !== intent.key || this.intent.stopping || ["wrapup", "handing_off", "transferred"].includes(this.snapshot.state)) return;
125
139
  if (state === "disconnected") {
126
140
  this.audio.disconnect();
127
141
  this.update({ state: "unconfirmed", error: "Audio disconnected. Check the original call before dialing again." });
@@ -144,19 +158,40 @@ export class ManagedDialer {
144
158
  private async acceptStatus(call: TelephonyCall) {
145
159
  if (!this.intent || call.id !== this.intent.callId) throw new Error("Calling status identity changed.");
146
160
  if (this.snapshot.call && call.version < this.snapshot.call.version) return;
161
+ const transfer = this.intent.transfer;
162
+ if (transfer) {
163
+ const observed = call.transfers?.find(item => transfer.id ? item.id === transfer.id : item.to === transfer.to && item.mode === transfer.mode);
164
+ if (observed && observed.to === transfer.to && observed.mode === transfer.mode) {
165
+ const next = structuredClone(this.intent);
166
+ if (["canceled", "failed"].includes(observed.status)) {
167
+ next.retiredTransferKeys = [...new Set([...(next.retiredTransferKeys ?? []), transfer.key])];
168
+ delete next.transfer;
169
+ }
170
+ else next.transfer!.id = observed.id;
171
+ await this.journal.write(next); this.intent = next;
172
+ this.update({ transferPending: Boolean(transfer.command && !["completed", "canceled", "failed"].includes(observed.status)) });
173
+ }
174
+ }
147
175
  if (terminal(call)) {
148
176
  this.audio.disconnect();
149
177
  this.update({ call, state: "wrapup", muted: false, error: null });
178
+ } else if (dialerCallHandedOff(call)) {
179
+ this.audio.disconnect();
180
+ this.update({ call, state: call.transfers?.some(item => item.status === "completed") ? "transferred" : "handing_off", muted: false, error: null });
150
181
  } else this.update({ call });
151
182
  }
152
183
  async stop(): Promise<void> {
153
184
  if (!this.intent) return;
185
+ if (this.snapshot.call && dialerCallHandedOff(this.snapshot.call)) throw new Error("The transferred conversation continues independently. Check its status instead of ending the caller's conversation.");
154
186
  // Mark immediately so a late create acknowledgment cannot connect audio.
155
187
  this.intent.stopping = true; this.audio.disconnect();
156
188
  this.update({ state: "stopping", muted: false });
157
189
  // Await in-flight setup; never issue an independent replacement create.
158
190
  if (this.operation) await this.operation;
159
191
  return this.exclusive(async () => {
192
+ if (this.snapshot.call && dialerCallHandedOff(this.snapshot.call)) {
193
+ this.intent!.stopping = false; await this.journal.write(structuredClone(this.intent!)); return;
194
+ }
160
195
  await this.journal.write(structuredClone(this.intent!));
161
196
  if (!this.intent!.callId) await this.setup();
162
197
  else await this.stopKnown();
@@ -164,6 +199,11 @@ export class ManagedDialer {
164
199
  }
165
200
  private async stopKnown() {
166
201
  try {
202
+ const current = await this.broker.get(this.intent!.callId!);
203
+ if (dialerCallHandedOff(current)) {
204
+ this.intent!.stopping = false; await this.journal.write(structuredClone(this.intent!));
205
+ await this.acceptStatus(current); return;
206
+ }
167
207
  const call = await this.broker.hangup(this.intent!.callId!);
168
208
  await this.acceptStatus(call);
169
209
  if (!terminal(call)) this.update({ state: "stopping", error: null });
@@ -171,11 +211,66 @@ export class ManagedDialer {
171
211
  }
172
212
  async finishWrapup(): Promise<void> {
173
213
  return this.exclusive(async () => {
174
- if (!this.intent || this.snapshot.state !== "wrapup" || !this.snapshot.call || !terminal(this.snapshot.call)) throw new Error("Confirmed call completion is required.");
214
+ if (!this.intent || !this.snapshot.call || !(this.snapshot.state === "wrapup" && terminal(this.snapshot.call) ||
215
+ this.snapshot.state === "transferred" && this.snapshot.call.transfers?.some(item => item.status === "completed"))) throw new Error("Confirmed call completion or successful transfer is required.");
175
216
  await this.journal.clear(this.scope, this.intent.key); this.intent = null;
176
- this.update({ state: "idle", callId: null, call: null, muted: false, error: null });
217
+ this.update({ state: "idle", callId: null, call: null, muted: false, error: null, transferPending: false });
177
218
  });
178
219
  }
220
+ async transfer(to: string, mode: "warm" | "cold") {
221
+ if (!/^\+[1-9]\d{6,14}$/.test(to) || !["warm", "cold"].includes(mode)) throw new Error("Choose a transfer destination with its country code and a transfer mode.");
222
+ return this.exclusive(async () => {
223
+ if (!this.intent?.callId || this.snapshot.state !== "active" || !this.snapshot.call?.transfer_enabled || !this.broker.transfers)
224
+ throw new Error("Transfers require a connected call started with transfers enabled.");
225
+ if (this.intent.transfer || this.snapshot.call.transfers?.some(item => !["completed", "canceled", "failed"].includes(item.status)))
226
+ throw new Error("Recover or finish the current transfer before starting another.");
227
+ const next = structuredClone(this.intent);
228
+ next.transfer = { key: this.newKey(), to, mode };
229
+ await this.journal.write(next); this.intent = next;
230
+ await this.transferKnown();
231
+ });
232
+ }
233
+ async retryTransfer() {
234
+ return this.exclusive(async () => {
235
+ if (!this.intent?.transfer) throw new Error("No transfer to recover.");
236
+ await this.transferKnown();
237
+ });
238
+ }
239
+ async completeTransfer() { return this.transferCommand("complete"); }
240
+ async cancelTransfer() { return this.transferCommand("cancel"); }
241
+ private async transferCommand(command: "complete" | "cancel") {
242
+ return this.exclusive(async () => {
243
+ if (!this.intent?.transfer?.id || !this.broker.transfers) throw new Error("Recover the transfer identity first.");
244
+ const transfer = this.snapshot.call?.transfers?.find(item => item.id === this.intent!.transfer!.id);
245
+ if (command === "complete" && transfer?.status !== "ready") throw new Error("Wait until the transfer target has joined.");
246
+ if (this.intent.transfer.mode !== "warm") throw new Error("Cold transfers complete automatically.");
247
+ if (this.intent.transfer.command && this.intent.transfer.command !== command) throw new Error("Recover the saved transfer command first.");
248
+ const next = structuredClone(this.intent); next.transfer!.command = command;
249
+ await this.journal.write(next); this.intent = next;
250
+ await this.transferKnown();
251
+ });
252
+ }
253
+ private async transferKnown() {
254
+ this.update({ transferPending: true, error: null });
255
+ try {
256
+ const original = this.intent!, saved = await this.journal.read(this.scope);
257
+ if (!saved || saved.scope !== this.scope || saved.key !== original.key || saved.callId !== original.callId ||
258
+ saved.transfer?.key !== original.transfer?.key || saved.transfer?.to !== original.transfer?.to || saved.transfer?.mode !== original.transfer?.mode)
259
+ throw new Error("Saved transfer intent changed.");
260
+ this.intent = saved;
261
+ if (saved.stopping) { await this.stopKnown(); return; }
262
+ const intent = saved, transfer = saved.transfer!, broker = this.broker.transfers!;
263
+ const call = transfer.command && transfer.id ? await broker[transfer.command](intent.callId!, transfer.id)
264
+ : await broker.create(intent.callId!, { to: transfer.to, mode: transfer.mode }, transfer.key);
265
+ if (call.id !== intent.callId) throw new Error("Transfer call identity changed.");
266
+ const observed = transfer.id ? call.transfers?.find(item => item.id === transfer.id)
267
+ : call.transfers?.slice().reverse().find(item => item.to === transfer.to && item.mode === transfer.mode);
268
+ if (!observed || observed.to !== transfer.to || observed.mode !== transfer.mode) throw new Error("Transfer identity is unavailable.");
269
+ transfer.id = observed.id;
270
+ await this.journal.write(structuredClone(intent));
271
+ await this.acceptStatus(call); this.update({ transferPending: false });
272
+ } catch { this.update({ transferPending: true, error: "Transfer is unconfirmed. Recover this same transfer before trying another." }); }
273
+ }
179
274
  mute(value: boolean) {
180
275
  if (this.snapshot.state !== "active") throw new Error("No active audio call.");
181
276
  this.audio.mute(value); this.update({ muted: value });
@@ -2,12 +2,13 @@
2
2
  import { createHash } from "node:crypto";
3
3
  import type { PyAI, TelephonyBrowserSessionCreate } from "../index.ts";
4
4
  import type { DialerBroker } from "./managedDialer.ts";
5
+ import { dialerCallHandedOff } from "./managedDialer.ts";
5
6
 
6
7
  export function createServerDialerBroker(sdk: PyAI, authenticatedUserId: string): DialerBroker {
7
8
  if (!authenticatedUserId.trim()) throw new Error("An authenticated user is required.");
8
9
  const ownedCall = async (id: string) => {
9
10
  const call = await sdk.telephony.calls.get(id);
10
- if (call.call_type !== "human" || call.user_id !== authenticatedUserId) throw new Error("No such call.");
11
+ if (call.id !== id || call.call_type !== "human" || call.user_id !== authenticatedUserId) throw new Error("No such call.");
11
12
  return call;
12
13
  };
13
14
  return {
@@ -18,6 +19,20 @@ export function createServerDialerBroker(sdk: PyAI, authenticatedUserId: string)
18
19
  return sdk.telephony.browserSessions.create({ ...input, user_id: authenticatedUserId }, { idempotencyKey: scopedKey });
19
20
  },
20
21
  get: ownedCall,
21
- async hangup(id: string) { await ownedCall(id); return sdk.telephony.calls.hangup(id); },
22
+ async hangup(id: string) {
23
+ const call = await ownedCall(id);
24
+ if (dialerCallHandedOff(call)) return call;
25
+ return sdk.telephony.calls.hangup(id);
26
+ },
27
+ transfers: {
28
+ async create(id, input, key) {
29
+ await ownedCall(id);
30
+ if (!key || key.length > 255 || /[\r\n]/.test(key)) throw new Error("A valid transfer retry key is required.");
31
+ const scopedKey = "dialer-transfer:" + createHash("sha256").update(authenticatedUserId).update("\0").update(id).update("\0").update(key).digest("hex");
32
+ return sdk.telephony.calls.transfers.create(id, { ...input, user_id: authenticatedUserId }, { idempotencyKey: scopedKey });
33
+ },
34
+ async complete(id, transferId) { await ownedCall(id); return sdk.telephony.calls.transfers.complete(id, transferId, authenticatedUserId); },
35
+ async cancel(id, transferId) { await ownedCall(id); return sdk.telephony.calls.transfers.cancel(id, transferId, authenticatedUserId); },
36
+ },
22
37
  };
23
38
  }
package/src/index.ts CHANGED
@@ -235,6 +235,8 @@ export interface AgentConfig {
235
235
  name?: string;
236
236
  /** Saved instructions: 8,000 Unicode characters by default; 32,000 on commitment plans. */
237
237
  persona_system_prompt?: string | null;
238
+ /** Separate setup rules, writable only by explicitly enrolled server credentials. */
239
+ platform_guidance?: string | null;
238
240
  /** False restricts retrieval to explicit agent bindings, including none. Default true. */
239
241
  inherit_org_knowledgebases?: boolean;
240
242
  greeting?: string | null;
@@ -951,6 +953,8 @@ export interface OmniConfigure {
951
953
  voice_id?: string;
952
954
  /** System prompt / role + instructions for the agent. */
953
955
  persona?: string;
956
+ /** Separate bounded platform guidance, applied before customer instructions. */
957
+ role_scaffold?: string;
954
958
  /** Customer-hosted URL the engine calls per turn for grounding. */
955
959
  kb_endpoint?: string;
956
960
  /** Bearer the engine presents to `kb_endpoint`. */
@@ -1488,9 +1492,15 @@ export interface TelephonyCall {
1488
1492
  version: number;
1489
1493
  from: string;
1490
1494
  to: string;
1495
+ dialing_mode?: "parallel";
1496
+ destinations?: string[];
1497
+ connected_to?: string | null;
1498
+ lines?: Array<{ id: string; to: string; status: "pending" | "queued" | "ringing" | "answered" | "completed" | "failed" | "canceled"; duration_seconds: number | null }>;
1491
1499
  from_number_id: string | null;
1492
1500
  agent_id: string | null;
1493
1501
  call_type?: "human";
1502
+ transfer_enabled?: boolean;
1503
+ transfers?: TelephonyTransfer[];
1494
1504
  user_id?: string;
1495
1505
  client_reference: string | null;
1496
1506
  stop_requested: boolean;
@@ -1501,6 +1511,12 @@ export interface TelephonyCall {
1501
1511
  [key: string]: unknown;
1502
1512
  }
1503
1513
  export type TelephonyUseCase = "transactional" | "support" | "sales" | "collections" | "survey";
1514
+ export interface TelephonyTransfer {
1515
+ id: string;
1516
+ mode: "warm" | "cold";
1517
+ status: "holding" | "dialing" | "ready" | "completing" | "canceling" | "completed" | "canceled" | "failed";
1518
+ to: string | null;
1519
+ }
1504
1520
  export interface TelephonyCallCreate {
1505
1521
  from_number_id: string;
1506
1522
  to: string;
@@ -1512,16 +1528,15 @@ export interface TelephonyCallCreate {
1512
1528
  max_duration_seconds?: number;
1513
1529
  stop_requested?: boolean;
1514
1530
  }
1515
- export interface TelephonyBrowserSessionCreate {
1531
+ export type TelephonyBrowserSessionCreate = {
1516
1532
  from_number_id: string;
1517
- to: string;
1518
1533
  /** Resolve from your authenticated server session, never from untrusted form data. */
1519
1534
  user_id: string;
1520
1535
  client_reference: string;
1521
1536
  recording: boolean;
1522
1537
  use_case?: TelephonyUseCase;
1523
1538
  max_duration_seconds?: number;
1524
- }
1539
+ } & ({ to: string; destinations?: never; transfer_enabled?: boolean } | { to?: never; destinations: string[]; transfer_enabled?: false });
1525
1540
  export interface TelephonyBrowserSession {
1526
1541
  object: "telephony.browser_session";
1527
1542
  id: string;
@@ -2378,6 +2393,15 @@ export class PyAI {
2378
2393
  recording: (id: string, options: { range?: string } = {}): Promise<Response> =>
2379
2394
  this.request(`/v1/telephony/calls/${encodeURIComponent(id)}/recording`, { headers: this.authHeaders(options.range ? { Range: options.range } : {}) }),
2380
2395
  deleteRecording: async (id: string): Promise<void> => { await this.deleteReq(`/v1/telephony/calls/${encodeURIComponent(id)}/recording`); },
2396
+ transfers: {
2397
+ /** Persist the key and target before requesting a consultation. */
2398
+ create: (id: string, input: { to: string; mode: "warm" | "cold"; user_id: string }, options: { idempotencyKey: string }): Promise<TelephonyCall> =>
2399
+ this.postJson(`/v1/telephony/calls/${encodeURIComponent(id)}/transfers`, input, telephonyIdempotencyHeader(options.idempotencyKey)),
2400
+ complete: (id: string, transferId: string, userId: string): Promise<TelephonyCall> =>
2401
+ this.postJson(`/v1/telephony/calls/${encodeURIComponent(id)}/transfers/${encodeURIComponent(transferId)}/complete`, { user_id: userId }),
2402
+ cancel: (id: string, transferId: string, userId: string): Promise<TelephonyCall> =>
2403
+ this.postJson(`/v1/telephony/calls/${encodeURIComponent(id)}/transfers/${encodeURIComponent(transferId)}/cancel`, { user_id: userId }),
2404
+ },
2381
2405
  },
2382
2406
  browserSessions: {
2383
2407
  /** Persist input and key on your server; retries recover the original session. */