@pyai/sdk 0.12.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.
- package/CLI.schema.json +2 -1
- package/README.md +26 -4
- package/dist/cli-omni-template.d.ts +2 -2
- package/dist/cli-omni-template.js +2 -2
- package/dist/cli.js +2 -2
- package/dist/dialer/appServer.d.ts +2 -0
- package/dist/dialer/appServer.js +19 -2
- package/dist/dialer/dialerElement.js +28 -6
- package/dist/dialer/dialingQueue.js +3 -1
- package/dist/dialer/indexedDbJournal.js +19 -0
- package/dist/dialer/managedDialer.d.ts +26 -1
- package/dist/dialer/managedDialer.js +115 -6
- package/dist/dialer/serverBroker.js +19 -2
- package/dist/index.d.ts +26 -0
- package/dist/index.js +6 -0
- package/package.json +1 -1
- package/src/cli-omni-template.ts +2 -2
- package/src/cli.ts +2 -2
- package/src/dialer/app/app.html +1 -1
- package/src/dialer/app/app.js +7 -5
- package/src/dialer/appServer.ts +18 -2
- package/src/dialer/dialerElement.ts +24 -5
- package/src/dialer/dialingQueue.ts +3 -1
- package/src/dialer/indexedDbJournal.ts +15 -0
- package/src/dialer/managedDialer.ts +98 -6
- package/src/dialer/serverBroker.ts +17 -2
- package/src/index.ts +22 -1
|
@@ -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,7 +61,7 @@ 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
67
|
const destinationInput = this.root.querySelector("input")!;
|
|
@@ -64,13 +73,23 @@ export class PyaiDialerElement extends HTMLElement {
|
|
|
64
73
|
? group.lines?.map(line => `${line.to} · ${line.status}`).join(" / ") ?? "The first answered line connects. Other lines are canceled."
|
|
65
74
|
: "Include the country code";
|
|
66
75
|
const call = this.root.querySelector<HTMLButtonElement>("[data-action=call]")!;
|
|
67
|
-
call.disabled = snapshot.state
|
|
68
|
-
call.textContent = snapshot.state === "idle" ? "Call" : snapshot.state === "
|
|
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";
|
|
69
78
|
const mute = this.root.querySelector<HTMLButtonElement>("[data-action=mute]")!;
|
|
70
79
|
mute.disabled = snapshot.state !== "active"; mute.textContent = snapshot.muted ? "Unmute" : "Mute";
|
|
71
80
|
mute.setAttribute("aria-pressed", String(snapshot.muted));
|
|
72
81
|
this.root.querySelector<HTMLButtonElement>("[data-action=recover]")!.hidden = !["unconfirmed", "stopping"].includes(snapshot.state);
|
|
73
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;
|
|
74
93
|
}
|
|
75
94
|
private async run(action: () => Promise<void>) {
|
|
76
95
|
try { await action(); } catch (error) { this.root.querySelector(".error")!.textContent = error instanceof Error ? error.message : "Calling request failed."; }
|
|
@@ -78,7 +97,7 @@ export class PyaiDialerElement extends HTMLElement {
|
|
|
78
97
|
private async act() {
|
|
79
98
|
if (!this.dialer || !this.inputFor) return;
|
|
80
99
|
await this.run(async () => {
|
|
81
|
-
if (this.dialer!.current.state
|
|
100
|
+
if (["wrapup", "transferred"].includes(this.dialer!.current.state)) await this.wrapup!();
|
|
82
101
|
else if (this.dialer!.current.state !== "idle") await this.dialer!.stop();
|
|
83
102
|
else await this.dialer!.start(this.inputFor!(this.root.querySelector("input")!.value.replace(/[\s()-]/g, "")));
|
|
84
103
|
});
|
|
@@ -31,6 +31,8 @@ export class DialingQueue {
|
|
|
31
31
|
if (!Number.isInteger(parallelLines) || parallelLines < 1 || parallelLines > 4 || mode === "parallel" && parallelLines < 2)
|
|
32
32
|
throw new Error("Parallel dialing requires two to four lines.");
|
|
33
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.");
|
|
34
36
|
const fingerprint = (contact: DialingContact) => JSON.stringify([contact.input.from_number_id, contact.input.user_id,
|
|
35
37
|
contact.input.recording, contact.input.use_case ?? "support", contact.input.max_duration_seconds ?? 3600]);
|
|
36
38
|
if (new Set(contacts.map(c => c.input.to)).size !== contacts.length || contacts.some(c => fingerprint(c) !== fingerprint(contacts[0]!)))
|
|
@@ -73,7 +75,7 @@ export class DialingQueue {
|
|
|
73
75
|
if (batch.length) {
|
|
74
76
|
const first = batch[0]!;
|
|
75
77
|
this.activeId = first.id; this.activeIds = batch.map(contact => contact.id);
|
|
76
|
-
const { to: _to, destinations: _destinations, ...common } = first.input;
|
|
78
|
+
const { to: _to, destinations: _destinations, transfer_enabled: _transferEnabled, ...common } = first.input;
|
|
77
79
|
const intent: TelephonyBrowserSessionCreate = batch.length === 1 ? first.input
|
|
78
80
|
: { ...common, destinations: batch.map(contact => contact.input.to!) };
|
|
79
81
|
// ManagedDialer persists the group and one key before any request.
|
|
@@ -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
|
}
|
|
@@ -118,13 +129,13 @@ export class ManagedDialer {
|
|
|
118
129
|
if (!saved || saved.key !== intent.key || saved.callId !== intent.callId) throw new Error("Calling recovery intent changed.");
|
|
119
130
|
if (saved.stopping) intent.stopping = true;
|
|
120
131
|
this.update({ callId: session.call_id, call: session.call });
|
|
121
|
-
if (terminal(session.call)) { await this.acceptStatus(session.call); return; }
|
|
132
|
+
if (terminal(session.call) || dialerCallHandedOff(session.call)) { await this.acceptStatus(session.call); return; }
|
|
122
133
|
if (intent.stopping) { await this.stopKnown(); return; }
|
|
123
134
|
if (!session.access_token || session.expires_at <= this.now() || session.call.stop_requested) {
|
|
124
135
|
this.update({ state: "unconfirmed", error: "This session was consumed, stopped or expired. End or recover the original call." }); return;
|
|
125
136
|
}
|
|
126
137
|
await this.audio.connect(session, state => {
|
|
127
|
-
if (this.intent !== intent || intent.stopping || this.snapshot.state
|
|
138
|
+
if (this.intent?.key !== intent.key || this.intent.stopping || ["wrapup", "handing_off", "transferred"].includes(this.snapshot.state)) return;
|
|
128
139
|
if (state === "disconnected") {
|
|
129
140
|
this.audio.disconnect();
|
|
130
141
|
this.update({ state: "unconfirmed", error: "Audio disconnected. Check the original call before dialing again." });
|
|
@@ -147,19 +158,40 @@ export class ManagedDialer {
|
|
|
147
158
|
private async acceptStatus(call: TelephonyCall) {
|
|
148
159
|
if (!this.intent || call.id !== this.intent.callId) throw new Error("Calling status identity changed.");
|
|
149
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
|
+
}
|
|
150
175
|
if (terminal(call)) {
|
|
151
176
|
this.audio.disconnect();
|
|
152
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 });
|
|
153
181
|
} else this.update({ call });
|
|
154
182
|
}
|
|
155
183
|
async stop(): Promise<void> {
|
|
156
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.");
|
|
157
186
|
// Mark immediately so a late create acknowledgment cannot connect audio.
|
|
158
187
|
this.intent.stopping = true; this.audio.disconnect();
|
|
159
188
|
this.update({ state: "stopping", muted: false });
|
|
160
189
|
// Await in-flight setup; never issue an independent replacement create.
|
|
161
190
|
if (this.operation) await this.operation;
|
|
162
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
|
+
}
|
|
163
195
|
await this.journal.write(structuredClone(this.intent!));
|
|
164
196
|
if (!this.intent!.callId) await this.setup();
|
|
165
197
|
else await this.stopKnown();
|
|
@@ -167,6 +199,11 @@ export class ManagedDialer {
|
|
|
167
199
|
}
|
|
168
200
|
private async stopKnown() {
|
|
169
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
|
+
}
|
|
170
207
|
const call = await this.broker.hangup(this.intent!.callId!);
|
|
171
208
|
await this.acceptStatus(call);
|
|
172
209
|
if (!terminal(call)) this.update({ state: "stopping", error: null });
|
|
@@ -174,11 +211,66 @@ export class ManagedDialer {
|
|
|
174
211
|
}
|
|
175
212
|
async finishWrapup(): Promise<void> {
|
|
176
213
|
return this.exclusive(async () => {
|
|
177
|
-
if (!this.intent || this.snapshot.
|
|
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.");
|
|
178
216
|
await this.journal.clear(this.scope, this.intent.key); this.intent = null;
|
|
179
|
-
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 });
|
|
180
218
|
});
|
|
181
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
|
+
}
|
|
182
274
|
mute(value: boolean) {
|
|
183
275
|
if (this.snapshot.state !== "active") throw new Error("No active audio call.");
|
|
184
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) {
|
|
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`. */
|
|
@@ -1495,6 +1499,8 @@ export interface TelephonyCall {
|
|
|
1495
1499
|
from_number_id: string | null;
|
|
1496
1500
|
agent_id: string | null;
|
|
1497
1501
|
call_type?: "human";
|
|
1502
|
+
transfer_enabled?: boolean;
|
|
1503
|
+
transfers?: TelephonyTransfer[];
|
|
1498
1504
|
user_id?: string;
|
|
1499
1505
|
client_reference: string | null;
|
|
1500
1506
|
stop_requested: boolean;
|
|
@@ -1505,6 +1511,12 @@ export interface TelephonyCall {
|
|
|
1505
1511
|
[key: string]: unknown;
|
|
1506
1512
|
}
|
|
1507
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
|
+
}
|
|
1508
1520
|
export interface TelephonyCallCreate {
|
|
1509
1521
|
from_number_id: string;
|
|
1510
1522
|
to: string;
|
|
@@ -1524,7 +1536,7 @@ export type TelephonyBrowserSessionCreate = {
|
|
|
1524
1536
|
recording: boolean;
|
|
1525
1537
|
use_case?: TelephonyUseCase;
|
|
1526
1538
|
max_duration_seconds?: number;
|
|
1527
|
-
} & ({ to: string; destinations?: never } | { to?: never; destinations: string[] });
|
|
1539
|
+
} & ({ to: string; destinations?: never; transfer_enabled?: boolean } | { to?: never; destinations: string[]; transfer_enabled?: false });
|
|
1528
1540
|
export interface TelephonyBrowserSession {
|
|
1529
1541
|
object: "telephony.browser_session";
|
|
1530
1542
|
id: string;
|
|
@@ -2381,6 +2393,15 @@ export class PyAI {
|
|
|
2381
2393
|
recording: (id: string, options: { range?: string } = {}): Promise<Response> =>
|
|
2382
2394
|
this.request(`/v1/telephony/calls/${encodeURIComponent(id)}/recording`, { headers: this.authHeaders(options.range ? { Range: options.range } : {}) }),
|
|
2383
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
|
+
},
|
|
2384
2405
|
},
|
|
2385
2406
|
browserSessions: {
|
|
2386
2407
|
/** Persist input and key on your server; retries recover the original session. */
|