@pyai/sdk 0.12.0 → 0.14.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 +58 -6
- package/dist/cli-omni-template.d.ts +2 -2
- package/dist/cli-omni-template.js +2 -2
- package/dist/cli-web-auth.d.ts +2 -0
- package/dist/cli-web-auth.js +2 -0
- package/dist/cli.js +2 -2
- package/dist/dialer/appServer.d.ts +4 -0
- package/dist/dialer/appServer.js +84 -4
- package/dist/dialer/dialerElement.js +28 -6
- package/dist/dialer/dialingQueue.d.ts +33 -10
- package/dist/dialer/dialingQueue.js +124 -41
- package/dist/dialer/fileMeetingIntelligenceJournal.d.ts +14 -0
- package/dist/dialer/fileMeetingIntelligenceJournal.js +147 -0
- package/dist/dialer/index.d.ts +1 -0
- package/dist/dialer/index.js +1 -0
- package/dist/dialer/indexedDbJournal.d.ts +9 -0
- package/dist/dialer/indexedDbJournal.js +62 -1
- package/dist/dialer/managedDialer.d.ts +40 -2
- package/dist/dialer/managedDialer.js +137 -10
- package/dist/dialer/meetingIntelligence.d.ts +28 -0
- package/dist/dialer/meetingIntelligence.js +3 -0
- package/dist/dialer/meetingIntelligenceElement.d.ts +21 -0
- package/dist/dialer/meetingIntelligenceElement.js +112 -0
- package/dist/dialer/serverBroker.js +19 -2
- package/dist/dialer/serverMeetingIntelligence.d.ts +60 -0
- package/dist/dialer/serverMeetingIntelligence.js +207 -0
- package/dist/index.d.ts +40 -0
- package/dist/index.js +24 -0
- package/package.json +9 -1
- package/src/cli-omni-template.ts +2 -2
- package/src/cli-web-auth.ts +3 -0
- package/src/cli.ts +2 -2
- package/src/dialer/MEETING_INTELLIGENCE.md +76 -0
- package/src/dialer/app/app.html +3 -3
- package/src/dialer/app/app.js +45 -16
- package/src/dialer/appServer.ts +63 -5
- package/src/dialer/dialerElement.ts +24 -5
- package/src/dialer/dialingQueue.ts +108 -45
- package/src/dialer/fileMeetingIntelligenceJournal.ts +77 -0
- package/src/dialer/index.ts +2 -0
- package/src/dialer/indexedDbJournal.ts +58 -1
- package/src/dialer/managedDialer.ts +115 -9
- package/src/dialer/meetingIntelligence.ts +21 -0
- package/src/dialer/meetingIntelligenceElement.ts +65 -0
- package/src/dialer/serverBroker.ts +17 -2
- package/src/dialer/serverMeetingIntelligence.ts +148 -0
- package/src/index.ts +37 -1
package/src/dialer/app/app.js
CHANGED
|
@@ -1,19 +1,23 @@
|
|
|
1
|
-
import { ManagedDialer } from '/modules/managedDialer.js';
|
|
2
|
-
import { IndexedDbDialerJournal } from '/modules/indexedDbJournal.js';
|
|
1
|
+
import { ManagedDialer, dialerCallHandedOff } from '/modules/managedDialer.js';
|
|
2
|
+
import { IndexedDbDialerJournal, IndexedDbDialingQueueJournal } from '/modules/indexedDbJournal.js';
|
|
3
3
|
import { VoiceSdkAudio } from '/modules/voiceSdkAudio.js';
|
|
4
4
|
import { DialingQueue } from '/modules/dialingQueue.js';
|
|
5
5
|
import { MeetingRecorder } from '/modules/meetingRecorder.js';
|
|
6
6
|
import { IndexedDbMeetingRecordingStore } from '/modules/meetingRecordingStore.js';
|
|
7
7
|
import '/modules/dialerElement.js';
|
|
8
8
|
import '/modules/meetingRecorderElement.js';
|
|
9
|
+
import '/modules/meetingIntelligenceElement.js';
|
|
9
10
|
|
|
10
11
|
const $=selector=>document.querySelector(selector),error=$('#error');
|
|
11
12
|
const showError=value=>{error.textContent=value instanceof Error?value.message:String(value);};
|
|
12
13
|
let config,dialer,queue,audio,closed=false,poll,audioGeneration=0;
|
|
13
|
-
let localSession=null;
|
|
14
|
+
let localSession=null,preparingClose=false;const meetingOperations=new Set();
|
|
14
15
|
async function request(path,options={}){
|
|
15
|
-
|
|
16
|
-
const
|
|
16
|
+
if(preparingClose&&options.method==='POST'&&(path==='/api/sessions'||path.startsWith('/api/meetings/')))throw Error('The app is preparing to close. Reopen the workspace to continue.');
|
|
17
|
+
const operation=(async()=>{const response=await fetch(path,{...options,headers:{...(options.body?{'content-type':options.body instanceof Blob?options.body.type:'application/json'}:{}),...(localSession?{authorization:`Bearer ${localSession}`} :{}),...(config?{'x-pyai-local-session':config.nonce}:{}),...options.headers},cache:'no-store',signal:AbortSignal.timeout(20000)});
|
|
18
|
+
const body=await response.json();if(!response.ok)throw Error(body?.error?.message??'This operation could not be confirmed.');return body;})();
|
|
19
|
+
const tracked=path.startsWith('/api/meetings/')&&options.method==='POST';if(tracked)meetingOperations.add(operation);
|
|
20
|
+
try{return await operation;}finally{if(tracked)meetingOperations.delete(operation);}
|
|
17
21
|
}
|
|
18
22
|
let media;
|
|
19
23
|
async function loadMedia(){
|
|
@@ -23,11 +27,14 @@ async function loadMedia(){
|
|
|
23
27
|
if(!window.Twilio?.Device)throw Error('Calling audio is unavailable.');
|
|
24
28
|
}
|
|
25
29
|
function renderQueue(){
|
|
26
|
-
if(!queue)return;const state=queue.current,active=dialer.current.state!=='idle';
|
|
27
|
-
$('#queue-start').disabled=active||state.running||!config.numbers.length;
|
|
30
|
+
if(!queue)return;const state=queue.current,active=dialer.current.state!=='idle',saved=Boolean(state.remaining);
|
|
31
|
+
$('#queue-start').disabled=active||state.running||Boolean(state.remaining)||!config.numbers.length;
|
|
32
|
+
$('#queue-clear').disabled=active||state.running||!state.remaining;
|
|
33
|
+
$('#parallel-choice').hidden=$('#mode').value!=='parallel';$('#parallel-lines').disabled=active||state.running||Boolean(state.remaining);
|
|
28
34
|
$('#queue-pause').disabled=!state.running;$('#queue-resume').disabled=state.running||!state.remaining;
|
|
29
|
-
$('#
|
|
30
|
-
$('#
|
|
35
|
+
$('#allow-transfers').disabled=active||state.running||saved||$('#mode').value==='parallel';if($('#mode').value==='parallel')$('#allow-transfers').checked=false;
|
|
36
|
+
$('#source').disabled=active||state.running||saved||!config.numbers.length;$('#mode').disabled=active||state.running||saved;$('#record-calls').disabled=active||state.running||saved;$('#contacts').disabled=state.running||active||Boolean(state.remaining);
|
|
37
|
+
$('#queue-status').textContent=state.activeId?`${state.running?'Queue running':'Queue paused'} · ${state.activeIds.length} in this attempt · ${state.remaining} remaining. Finish this call and choose Done to continue.`:state.remaining?`${state.remaining} contacts saved in this browser. Choose Resume queue when ready.`:'You choose when to start. Your workspace calling rules apply to every call.';
|
|
31
38
|
}
|
|
32
39
|
async function refresh(){
|
|
33
40
|
clearTimeout(poll);if(closed)return;
|
|
@@ -38,19 +45,21 @@ async function init(){
|
|
|
38
45
|
try{localSession=localStorage.getItem('pyai-local-app-session');}catch{throw Error('Private app storage is unavailable. Enable storage for this local app before calling.');}
|
|
39
46
|
const code=location.hash.slice(1);history.replaceState(null,'',location.pathname);
|
|
40
47
|
if(code){const unlocked=await request('/api/unlock',{method:'POST',body:JSON.stringify({code})});localSession=unlocked.session_token;localStorage.setItem('pyai-local-app-session',localSession);}
|
|
41
|
-
config=await request('/api/config');document.title=config.name;$('[data-brand]').textContent=config.name;
|
|
48
|
+
config=await request('/api/config');$('#transfer-choice').hidden=!config.transfers_enabled;document.title=config.name;$('[data-brand]').textContent=config.name;
|
|
42
49
|
if(config.white_label){$('.logo').textContent=(config.name.match(/[A-Za-z]/)?.[0]??'P').toUpperCase();$('.aside-foot small').hidden=true;$('footer').textContent='Calls and call recordings stay in your workspace. Meeting audio stays in this browser until you save or submit it.';}
|
|
43
50
|
const source=$('#source');source.replaceChildren();
|
|
44
51
|
for(const number of config.numbers){const option=document.createElement('option');option.value=number.id;option.textContent=number.phone_number;source.append(option);}
|
|
45
52
|
if(!config.numbers.length){const option=document.createElement('option');option.textContent='No active voice numbers in this workspace';source.append(option);}
|
|
46
53
|
source.disabled=!config.numbers.length;
|
|
47
|
-
const broker={create:(input,key)=>request('/api/sessions',{method:'POST',headers:{'idempotency-key':key},body:JSON.stringify(input)}),get:id=>request(`/api/calls/${encodeURIComponent(id)}`),hangup:id=>request(`/api/calls/${encodeURIComponent(id)}/hangup`,{method:'POST',body:'{}'})};
|
|
54
|
+
const broker={create:(input,key)=>request('/api/sessions',{method:'POST',headers:{'idempotency-key':key},body:JSON.stringify(input)}),get:id=>request(`/api/calls/${encodeURIComponent(id)}`),hangup:id=>request(`/api/calls/${encodeURIComponent(id)}/hangup`,{method:'POST',body:'{}'}),transfers:{create:(id,input,key)=>request(`/api/calls/${encodeURIComponent(id)}/transfers`,{method:'POST',headers:{'idempotency-key':key},body:JSON.stringify(input)}),complete:(id,transferId)=>request(`/api/calls/${encodeURIComponent(id)}/transfers/${encodeURIComponent(transferId)}/complete`,{method:'POST',body:'{}'}),cancel:(id,transferId)=>request(`/api/calls/${encodeURIComponent(id)}/transfers/${encodeURIComponent(transferId)}/cancel`,{method:'POST',body:'{}'})}};
|
|
48
55
|
const transport=new VoiceSdkAudio(token=>new window.Twilio.Device(token,{logLevel:'silent'}));
|
|
49
|
-
audio={connect:async(...args)=>{const generation=++audioGeneration;await loadMedia();if(generation!==audioGeneration)throw Error('Calling audio was cancelled.');return transport.connect(...args);},disconnect:()=>{++audioGeneration;transport.disconnect();},mute:value=>transport.mute(value),sendDigits:digits=>transport.sendDigits(digits)};
|
|
56
|
+
audio={connect:async(...args)=>{if(closed)throw Error('Calling audio was cancelled.');const generation=++audioGeneration;await loadMedia();if(closed||generation!==audioGeneration)throw Error('Calling audio was cancelled.');return transport.connect(...args);},disconnect:()=>{++audioGeneration;transport.disconnect();},mute:value=>transport.mute(value),sendDigits:digits=>transport.sendDigits(digits)};
|
|
50
57
|
dialer=new ManagedDialer(config.scope,broker,new IndexedDbDialerJournal(),audio);
|
|
51
58
|
await dialer.restore();
|
|
52
|
-
const inputFor=to=>({from_number_id:source.value,to,user_id:config.user_id,client_reference:crypto.randomUUID(),recording:$('#record-calls').checked,max_duration_seconds:3600,use_case:'support'});
|
|
53
|
-
queue=new DialingQueue(dialer,async contact=>{const latest=await request('/api/config');return latest.scope===config.scope&&latest.numbers.some(n=>n.id===contact.input.from_number_id);});
|
|
59
|
+
const inputFor=to=>({from_number_id:source.value,to,user_id:config.user_id,client_reference:crypto.randomUUID(),recording:$('#record-calls').checked,max_duration_seconds:3600,use_case:'support',...(config.transfers_enabled&&$('#allow-transfers').checked?{transfer_enabled:true}:{})});
|
|
60
|
+
queue=new DialingQueue(dialer,async contact=>{const latest=await request('/api/config');return latest.scope===config.scope&&latest.numbers.some(n=>n.id===contact.input.from_number_id);},{scope:config.scope,journal:new IndexedDbDialingQueueJournal()});
|
|
61
|
+
await queue.restore();
|
|
62
|
+
if(queue.current.remaining||queue.current.activeIds.length){$('#mode').value=queue.current.mode;$('#parallel-lines').value=String(queue.current.parallelLines);}
|
|
54
63
|
$('pyai-dialer').bind(dialer,to=>{
|
|
55
64
|
if(!config.numbers.length)throw Error('Add a voice number in your PyAI workspace before calling.');
|
|
56
65
|
const sourceNumber=config.numbers.find(n=>n.id===source.value);if(sourceNumber?.phone_number===to)throw Error('Choose a destination different from your calling number.');
|
|
@@ -58,17 +67,37 @@ async function init(){
|
|
|
58
67
|
},{name:config.name,showBranding:!config.white_label},async()=>{await queue.finishWrapup();renderQueue();});
|
|
59
68
|
dialer.subscribe(()=>renderQueue());renderQueue();
|
|
60
69
|
const store=new IndexedDbMeetingRecordingStore(),recorder=new MeetingRecorder(config.scope,store);$('pyai-meeting-recorder').bind(recorder,store);
|
|
70
|
+
$('pyai-meeting-intelligence').bind(config.scope,store,{availability:()=>request('/api/meetings/availability'),submit:(id,audio,notice)=>request(`/api/meetings/${encodeURIComponent(id)}`,{method:'POST',headers:{'x-pyai-meeting-notice':notice?'accepted':''},body:audio}),get:id=>request(`/api/meetings/${encodeURIComponent(id)}`),remove:id=>request(`/api/meetings/${encodeURIComponent(id)}/remove`,{method:'POST',body:'{}'})});
|
|
61
71
|
$('#queue-start').addEventListener('click',()=>void act(async()=>{
|
|
62
72
|
const contacts=$('#contacts').value.split(/\r?\n/).map(line=>line.trim()).filter(Boolean).map((line,index)=>{
|
|
63
73
|
const [number,priority='0']=line.split(',').map(value=>value.trim());const to=number.replace(/[\s()-]/g,'');
|
|
64
74
|
if(config.numbers.find(n=>n.id===source.value)?.phone_number===to)throw Error(`Line ${index+1} matches your calling number.`);
|
|
65
75
|
return {id:crypto.randomUUID(),input:inputFor(to),priority:Number(priority)};
|
|
66
|
-
});await queue.start(contacts,$('#mode').value);renderQueue();
|
|
76
|
+
});await queue.start(contacts,$('#mode').value,{parallelLines:Number($('#parallel-lines').value)});renderQueue();
|
|
67
77
|
}));
|
|
78
|
+
$('#mode').addEventListener('change',renderQueue);
|
|
79
|
+
$('#queue-clear').addEventListener('click',()=>void act(async()=>{await queue.clear();renderQueue();}));
|
|
68
80
|
$('#queue-pause').addEventListener('click',()=>{queue.pause();renderQueue();});$('#queue-resume').addEventListener('click',()=>void act(async()=>{await queue.resume();renderQueue();}));
|
|
81
|
+
let closePreparation=null;
|
|
82
|
+
window.addEventListener('pyai-desktop-prepare-close',event=>{
|
|
83
|
+
const requestId=event.detail?.requestId;if(typeof requestId!=='string'||!/^[A-Za-z0-9_-]{1,128}$/.test(requestId))return;
|
|
84
|
+
closePreparation??=(async()=>{
|
|
85
|
+
preparingClose=true;queue.pause();audio.disconnect();clearTimeout(poll);
|
|
86
|
+
await recorder.stop();await Promise.allSettled([...meetingOperations]);
|
|
87
|
+
// Never replay admission during close. An intent without a known call ID
|
|
88
|
+
// remains recoverable under the same credential after the app reopens.
|
|
89
|
+
let state=dialer.current;
|
|
90
|
+
if(state.callId&&!['idle','wrapup','transferred','handing_off'].includes(state.state)&&!dialerCallHandedOff(state.call??{})){
|
|
91
|
+
await dialer.stop();try{await dialer.refresh();}catch{}state=dialer.current;
|
|
92
|
+
}
|
|
93
|
+
const ready=['idle','wrapup'].includes(state.state)||dialerCallHandedOff(state.call??{});
|
|
94
|
+
return {ready,reason:ready?'Calling and recording state saved.':'A calling attempt is still unconfirmed. Keep the same signed-in profile and recover it after reopening.'};
|
|
95
|
+
})().catch(()=>({ready:false,reason:'Private activity could not be finalized. Keep this profile and recover the saved state after reopening.'}));
|
|
96
|
+
void closePreparation.then(result=>window.dispatchEvent(new CustomEvent('pyai-desktop-close-result',{detail:{requestId,...result}})));
|
|
97
|
+
});
|
|
69
98
|
window.addEventListener('pagehide',()=>{
|
|
70
99
|
closed=true;clearTimeout(poll);queue.pause();audio.disconnect();void recorder.stop();
|
|
71
|
-
const id=dialer.current.callId;if(id&&!['idle','wrapup'].includes(dialer.current.state))void fetch(`/api/calls/${encodeURIComponent(id)}/hangup`,{method:'POST',headers:{'content-type':'application/json','x-pyai-local-session':config.nonce,authorization:`Bearer ${localSession}`},body:'{}',keepalive:true}).catch(()=>{});
|
|
100
|
+
const id=dialer.current.callId;if(id&&!['idle','wrapup','transferred','handing_off'].includes(dialer.current.state)&&!dialerCallHandedOff(dialer.current.call??{}))void fetch(`/api/calls/${encodeURIComponent(id)}/hangup`,{method:'POST',headers:{'content-type':'application/json','x-pyai-local-session':config.nonce,authorization:`Bearer ${localSession}`},body:'{}',keepalive:true}).catch(()=>{});
|
|
72
101
|
});
|
|
73
102
|
void refresh();
|
|
74
103
|
}
|
package/src/dialer/appServer.ts
CHANGED
|
@@ -4,10 +4,15 @@ import { createServer, type IncomingMessage, type ServerResponse } from "node:ht
|
|
|
4
4
|
import { randomBytes, timingSafeEqual } from "node:crypto";
|
|
5
5
|
import { readFile } from "node:fs/promises";
|
|
6
6
|
import { createRequire } from "node:module";
|
|
7
|
+
import { homedir } from "node:os";
|
|
8
|
+
import { FileMeetingIntelligenceJournal } from "./fileMeetingIntelligenceJournal.ts";
|
|
9
|
+
import { createSdkMeetingApi, createServerMeetingIntelligence } from "./serverMeetingIntelligence.ts";
|
|
10
|
+
import type { MeetingIntelligenceBroker } from "./meetingIntelligence.ts";
|
|
7
11
|
import { dirname, join } from "node:path";
|
|
8
12
|
import { Readable } from "node:stream";
|
|
9
13
|
import type { PyAI, TelephonyBrowserSessionCreate, TelephonyCall } from "../index.ts";
|
|
10
14
|
import { createServerDialerBroker } from "./serverBroker.ts";
|
|
15
|
+
import { dialerCallHandedOff } from "./managedDialer.ts";
|
|
11
16
|
|
|
12
17
|
export interface DialerAppOptions {
|
|
13
18
|
sdk: PyAI;
|
|
@@ -16,13 +21,17 @@ export interface DialerAppOptions {
|
|
|
16
21
|
scope: string;
|
|
17
22
|
name?: string;
|
|
18
23
|
whiteLabel?: boolean;
|
|
24
|
+
/** Operator opt-in; the API independently enforces transfer activation. */
|
|
25
|
+
allowTransfers?: boolean;
|
|
19
26
|
port?: number;
|
|
27
|
+
/** Trusted host path; never accepted through HTTP. Metadata only, no audio. */
|
|
28
|
+
meetingJournalDirectory?: string;
|
|
20
29
|
/** Explicit asset injection for packaging/tests, never selected by HTTP. */
|
|
21
30
|
assets?: { read(path: string): Promise<Uint8Array> };
|
|
22
31
|
}
|
|
23
32
|
const terminal = (call: TelephonyCall) => ["completed", "failed", "canceled"].includes(call.status);
|
|
24
33
|
const secretMatches = (input: unknown, expected: string) => typeof input === "string" && /^[A-Za-z0-9_-]+$/.test(input) && input.length === expected.length && timingSafeEqual(Buffer.from(input), Buffer.from(expected));
|
|
25
|
-
const browserModules = new Set(["managedDialer", "dialingQueue", "indexedDbJournal", "voiceSdkAudio", "dialerElement", "meetingRecorder", "meetingRecordingStore", "meetingRecorderElement"]);
|
|
34
|
+
const browserModules = new Set(["managedDialer", "dialingQueue", "indexedDbJournal", "voiceSdkAudio", "dialerElement", "meetingRecorder", "meetingRecordingStore", "meetingRecorderElement", "meetingIntelligence", "meetingIntelligenceElement"]);
|
|
26
35
|
const publicAssets = new Set(["/", "/app.js", "/app.css", "/manifest.webmanifest", "/icon.svg"]);
|
|
27
36
|
const publicModule = (path: string) => { const match = /^\/modules\/([A-Za-z]+)\.js$/.exec(path); return match && browserModules.has(match[1]!) ? match[1] : null; };
|
|
28
37
|
async function packagedAsset(path: string): Promise<Uint8Array> {
|
|
@@ -60,9 +69,21 @@ export async function startDialerApp(options: DialerAppOptions) {
|
|
|
60
69
|
const bootstrap = randomBytes(32).toString("base64url"), rendererToken = randomBytes(32).toString("base64url"), bootstrapExpires = Date.now() + 60000;
|
|
61
70
|
let bootstrapUsed = false;
|
|
62
71
|
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; };
|
|
72
|
+
const remember = (call: TelephonyCall) => { if (terminal(call) || dialerCallHandedOff(call)) calls.delete(call.id); else calls.add(call.id); return call; };
|
|
64
73
|
const numbers = async () => (await options.sdk.telephony.numbers.list()).data.filter(number => number.status !== "released" && number.capabilities?.voice === true);
|
|
65
74
|
const own = async (id: string) => remember(await broker.get(id));
|
|
75
|
+
const meetingJournal = new FileMeetingIntelligenceJournal(options.meetingJournalDirectory ?? join(homedir(), ".config", "pyai", "meetings"), options.scope);
|
|
76
|
+
let meetings: Promise<MeetingIntelligenceBroker> | null = null;
|
|
77
|
+
const meetingActions = new Set<Promise<unknown>>();
|
|
78
|
+
const getMeetings = () => meetings ??= (async () => {
|
|
79
|
+
const me = await options.sdk.me();
|
|
80
|
+
await meetingJournal.sweep();
|
|
81
|
+
if (!me.org_id || !me.project_id || !me.key_id) throw new AppError(403, "Select a signed-in PyAI project before sending a meeting.");
|
|
82
|
+
return createServerMeetingIntelligence({ api: createSdkMeetingApi(options.sdk), orgId: me.org_id, projectId: me.project_id, keyId: me.key_id, userId: options.userId, journal: meetingJournal });
|
|
83
|
+
})().catch(error => { meetings = null; throw error; });
|
|
84
|
+
const trackMeeting = async <T>(action: () => Promise<T>) => { const pending = action(); meetingActions.add(pending); try { return await pending; } finally { meetingActions.delete(pending); } };
|
|
85
|
+
const sweep = setInterval(() => { void meetingJournal.sweep().catch(() => {}); }, 3600000); sweep.unref();
|
|
86
|
+
|
|
66
87
|
const server = createServer(async (request, response) => {
|
|
67
88
|
response.setHeader("cache-control", "no-store"); response.setHeader("x-content-type-options", "nosniff"); response.setHeader("x-frame-options", "DENY");
|
|
68
89
|
response.setHeader("referrer-policy", "no-referrer");
|
|
@@ -87,16 +108,52 @@ export async function startDialerApp(options: DialerAppOptions) {
|
|
|
87
108
|
}
|
|
88
109
|
if (url.pathname === "/api/config" && method === "GET") {
|
|
89
110
|
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,
|
|
111
|
+
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
112
|
numbers: owned.map(number => ({ id: number.id, phone_number: number.phone_number, country: number.country })) });
|
|
92
113
|
}
|
|
114
|
+
if (url.pathname === "/api/meetings/availability" && method === "GET") return json(response, 200, await (await getMeetings()).availability());
|
|
115
|
+
const meetingPath = /^\/api\/meetings\/([A-Za-z0-9_-]{1,200})(?:\/(remove))?$/.exec(url.pathname);
|
|
116
|
+
if (meetingPath) {
|
|
117
|
+
if (closing) throw new AppError(503, "The app is closing. Recover this meeting after reopening the same workspace.");
|
|
118
|
+
const id = meetingPath[1]!, operation = meetingPath[2];
|
|
119
|
+
if (method === "GET" && !operation) return json(response, 200, await trackMeeting(async () => (await getMeetings()).get(id)));
|
|
120
|
+
if (method === "POST" && operation === "remove") { await body(request); return json(response, 200, await trackMeeting(async () => (await getMeetings()).remove(id))); }
|
|
121
|
+
if (method === "POST" && !operation) {
|
|
122
|
+
if (request.headers["x-pyai-meeting-notice"] !== "accepted") throw new AppError(400, "Accept the meeting upload and retention notice first.");
|
|
123
|
+
const mimeType = request.headers["content-type"] ?? "";
|
|
124
|
+
if (!/^audio\/(webm|mp4|wav|x-wav|mpeg|ogg)(?:;|$)/i.test(mimeType)) throw new AppError(415, "Send a saved audio recording.");
|
|
125
|
+
// Verify capabilities before accepting a large audio body. Browser
|
|
126
|
+
// bytes never cause a fallback to an operator or parent credential.
|
|
127
|
+
const meetingBroker = await getMeetings(), allowed = await meetingBroker.availability();
|
|
128
|
+
if (!allowed.available) throw new AppError(403, allowed.reason!);
|
|
129
|
+
const maximum = 128 * 1024 * 1024, declared = Number(request.headers["content-length"] ?? 0);
|
|
130
|
+
if (!Number.isSafeInteger(declared) || declared < 0 || declared > maximum) throw new AppError(413, "Meeting audio exceeds the 128 MiB upload limit.");
|
|
131
|
+
const chunks: Buffer[] = []; let bytes = 0;
|
|
132
|
+
for await (const chunk of request) { bytes += chunk.length; if (bytes > maximum) throw new AppError(413, "Meeting audio exceeds the 128 MiB upload limit."); chunks.push(Buffer.from(chunk)); }
|
|
133
|
+
if (!bytes) throw new AppError(400, "Choose a saved recording with audio.");
|
|
134
|
+
return json(response, 202, await trackMeeting(() => meetingBroker.submit(id, new Blob([new Uint8Array(Buffer.concat(chunks))], { type: mimeType }), true)));
|
|
135
|
+
}
|
|
136
|
+
}
|
|
93
137
|
if (url.pathname === "/api/sessions" && method === "POST") {
|
|
94
138
|
if (closing) throw new AppError(503, "Dialer is closing. No new calls are admitted.");
|
|
95
139
|
const input = await body(request), key = request.headers["idempotency-key"];
|
|
140
|
+
if (input.transfer_enabled === true && options.allowTransfers !== true) throw new AppError(400, "Open this dialer with transfers enabled before starting a transferable call.");
|
|
96
141
|
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
142
|
const session = await broker.create(input as unknown as TelephonyBrowserSessionCreate, key); remember(session.call);
|
|
98
143
|
return json(response, 200, session);
|
|
99
144
|
}
|
|
145
|
+
const transferPath = /^\/api\/calls\/([A-Za-z0-9_-]{1,200})\/transfers(?:\/([A-Za-z0-9_-]{1,200})\/(complete|cancel))?$/.exec(url.pathname);
|
|
146
|
+
if (transferPath && method === "POST") {
|
|
147
|
+
if (closing || options.allowTransfers !== true) throw new AppError(503, "Transfers are not enabled in this dialer.");
|
|
148
|
+
const id = transferPath[1]!, transferId = transferPath[2], operation = transferPath[3];
|
|
149
|
+
await own(id); const input = await body(request);
|
|
150
|
+
if (transferId && (operation === "complete" || operation === "cancel"))
|
|
151
|
+
return json(response, 202, remember(await broker.transfers));
|
|
152
|
+
const key = request.headers["idempotency-key"];
|
|
153
|
+
if (typeof key !== "string" || typeof input.to !== "string" || !/^\+[1-9]\d{6,14}$/.test(input.to) || !["warm", "cold"].includes(String(input.mode)))
|
|
154
|
+
throw new AppError(400, "Choose a transfer destination, mode and retry key.");
|
|
155
|
+
return json(response, 202, remember(await broker.transfers!.create(id, { to: input.to, mode: input.mode as "warm" | "cold" }, key)));
|
|
156
|
+
}
|
|
100
157
|
const callPath = /^\/api\/calls\/([A-Za-z0-9_-]{1,200})(?:\/(hangup|recording))?$/.exec(url.pathname);
|
|
101
158
|
if (callPath) {
|
|
102
159
|
const id = callPath[1]!, operation = callPath[2]; await own(id);
|
|
@@ -137,12 +194,13 @@ export async function startDialerApp(options: DialerAppOptions) {
|
|
|
137
194
|
}
|
|
138
195
|
});
|
|
139
196
|
server.requestTimeout = 20000; server.headersTimeout = 10000; server.maxRequestsPerSocket = 100;
|
|
140
|
-
await new Promise<void>((resolve, reject) => { server.once("error", reject); server.listen(options.port ?? 43117, "127.0.0.1", () => { server.off("error", reject); resolve(); }); });
|
|
197
|
+
await new Promise<void>((resolve, reject) => { server.once("error", error => { clearInterval(sweep); reject(error); }); server.listen(options.port ?? 43117, "127.0.0.1", () => { server.off("error", reject); resolve(); }); });
|
|
141
198
|
const address = server.address(); if (!address || typeof address === "string") throw new Error("No local dialer address.");
|
|
142
199
|
origin = `http://127.0.0.1:${address.port}`;
|
|
143
200
|
let closePromise: Promise<{ unsettled: string[] }> | null = null;
|
|
144
201
|
return { url: origin, launchUrl: `${origin}#${bootstrap}`, close: () => closePromise ??= (async () => {
|
|
145
|
-
closing = true; const deadline = Date.now() + 20000;
|
|
202
|
+
closing = true; clearInterval(sweep); const deadline = Date.now() + 20000;
|
|
203
|
+
await Promise.allSettled([...meetingActions]);
|
|
146
204
|
await Promise.allSettled([...calls].map(async id => { remember(await broker.hangup(id)); }));
|
|
147
205
|
while (calls.size && Date.now() < deadline) { await new Promise(resolve => setTimeout(resolve, 500)); await Promise.allSettled([...calls].map(own)); }
|
|
148
206
|
await new Promise<void>(resolve => { server.close(() => resolve()); server.closeIdleConnections?.(); });
|
|
@@ -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
|
});
|
|
@@ -6,24 +6,65 @@ export interface DialingContact {
|
|
|
6
6
|
input: TelephonyBrowserSessionCreate;
|
|
7
7
|
priority?: number;
|
|
8
8
|
}
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
9
|
+
export interface DialingQueueState {
|
|
10
|
+
scope: string;
|
|
11
|
+
key: string;
|
|
12
|
+
revision: number;
|
|
13
|
+
contacts: DialingContact[];
|
|
14
|
+
active: DialingContact[];
|
|
15
|
+
wrapped: boolean;
|
|
16
|
+
mode: "auto" | "dynamic" | "parallel";
|
|
17
|
+
parallelLines: number;
|
|
18
|
+
}
|
|
19
|
+
export interface DialingQueueJournal {
|
|
20
|
+
read(scope: string): Promise<DialingQueueState | null>;
|
|
21
|
+
/** Compare-and-swap; null means no queue may already exist. */
|
|
22
|
+
write(state: DialingQueueState, expectedRevision: number | null): Promise<void>;
|
|
23
|
+
}
|
|
24
|
+
export interface DialingQueuePersistence { scope: string; journal: DialingQueueJournal; }
|
|
25
|
+
/** Auto, priority-based dynamic, and server-owned parallel dialing. Durable
|
|
26
|
+
* queues restore paused; no calls resume automatically after reload. */
|
|
12
27
|
export class DialingQueue {
|
|
13
|
-
private
|
|
28
|
+
private state: DialingQueueState | null = null;
|
|
14
29
|
private running = false;
|
|
15
30
|
private advancing = false;
|
|
16
|
-
private
|
|
17
|
-
private
|
|
18
|
-
private parallelLines = 1;
|
|
31
|
+
private wrapping = false;
|
|
32
|
+
private initialized: boolean;
|
|
19
33
|
private readonly dialer: ManagedDialer;
|
|
20
34
|
private readonly eligible: (contact: DialingContact) => Promise<boolean>;
|
|
21
|
-
|
|
22
|
-
|
|
35
|
+
private readonly persistence?: DialingQueuePersistence;
|
|
36
|
+
constructor(dialer: ManagedDialer, eligible: (contact: DialingContact) => Promise<boolean>, persistence?: DialingQueuePersistence) {
|
|
37
|
+
this.dialer = dialer; this.eligible = eligible; this.persistence = persistence;
|
|
38
|
+
if (persistence && (!persistence.scope.trim() || persistence.scope !== dialer.recoveryScope))
|
|
39
|
+
throw new Error("The saved queue must use the calling controller’s authenticated workspace/user scope.");
|
|
40
|
+
this.initialized = !persistence;
|
|
41
|
+
}
|
|
42
|
+
get current() { return { running: this.running, remaining: this.state?.contacts.length ?? 0,
|
|
43
|
+
activeId: this.state?.active[0]?.id ?? null, activeIds: this.state?.active.map(contact => contact.id) ?? [],
|
|
44
|
+
mode: this.state?.mode ?? "auto", parallelLines: this.state?.parallelLines ?? 1 }; }
|
|
45
|
+
private commit(state: DialingQueueState): Promise<void> | void {
|
|
46
|
+
const next = structuredClone(state); next.revision = (this.state?.revision ?? 0) + 1;
|
|
47
|
+
if (this.persistence) return this.persistence.journal.write(next, this.state?.revision ?? null).then(() => { this.state = next; });
|
|
48
|
+
this.state = next;
|
|
49
|
+
}
|
|
50
|
+
async restore() {
|
|
51
|
+
if (this.initialized) return;
|
|
52
|
+
if (!this.dialer.restored) throw new Error("Restore the calling journal before restoring the queue.");
|
|
53
|
+
const saved = await this.persistence!.journal.read(this.persistence!.scope);
|
|
54
|
+
if (saved && saved.scope !== this.persistence!.scope) throw new Error("Saved queue belongs to another workspace.");
|
|
55
|
+
this.state = saved ? structuredClone(saved) : null;
|
|
56
|
+
// A crash before call-intent persistence is safe to retry. A crash after
|
|
57
|
+
// wrap-up persistence must never put the completed contacts back in line.
|
|
58
|
+
if (this.state?.active.length) {
|
|
59
|
+
const context = this.dialer.queueContext;
|
|
60
|
+
const same = context?.key === this.state.key && JSON.stringify(context.contactIds) === JSON.stringify(this.state.active.map(c => c.id));
|
|
61
|
+
if (!same) await this.commit({ ...this.state, contacts: this.state.wrapped ? this.state.contacts : [...this.state.active, ...this.state.contacts], active: [], wrapped: false });
|
|
62
|
+
}
|
|
63
|
+
this.initialized = true;
|
|
23
64
|
}
|
|
24
|
-
get current() { return { running: this.running, remaining: this.contacts.length, activeId: this.activeId, activeIds: [...this.activeIds] }; }
|
|
25
65
|
async start(contacts: DialingContact[], mode: "auto" | "dynamic" | "parallel" = "auto", options: { parallelLines?: number } = {}) {
|
|
26
|
-
if (this.
|
|
66
|
+
if (!this.initialized) throw new Error("Restore the calling queue before dialing.");
|
|
67
|
+
if (this.running || this.advancing || this.wrapping || this.dialer.current.state !== "idle") throw new Error("Finish the current call before starting a queue.");
|
|
27
68
|
if (!contacts.length || contacts.length > 500 || new Set(contacts.map(c => c.id)).size !== contacts.length ||
|
|
28
69
|
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
70
|
if (!["auto", "dynamic", "parallel"].includes(mode)) throw new Error("Choose a supported calling order.");
|
|
@@ -31,63 +72,85 @@ export class DialingQueue {
|
|
|
31
72
|
if (!Number.isInteger(parallelLines) || parallelLines < 1 || parallelLines > 4 || mode === "parallel" && parallelLines < 2)
|
|
32
73
|
throw new Error("Parallel dialing requires two to four lines.");
|
|
33
74
|
if (mode === "parallel") {
|
|
75
|
+
if (contacts.some(contact => contact.input.transfer_enabled === true)) throw new Error("Transfer-enabled calls use single-line dialing.");
|
|
34
76
|
const fingerprint = (contact: DialingContact) => JSON.stringify([contact.input.from_number_id, contact.input.user_id,
|
|
35
77
|
contact.input.recording, contact.input.use_case ?? "support", contact.input.max_duration_seconds ?? 3600]);
|
|
36
78
|
if (new Set(contacts.map(c => c.input.to)).size !== contacts.length || contacts.some(c => fingerprint(c) !== fingerprint(contacts[0]!)))
|
|
37
79
|
throw new Error("Parallel contacts must have distinct numbers and share the same user, source and calling settings.");
|
|
38
80
|
}
|
|
39
|
-
this.
|
|
40
|
-
|
|
41
|
-
if (mode === "dynamic" || mode === "parallel")
|
|
42
|
-
this.
|
|
81
|
+
if (this.state?.contacts.length || this.state?.active.length) throw new Error("Resume or clear the saved queue before starting another.");
|
|
82
|
+
const ordered = structuredClone(contacts);
|
|
83
|
+
if (mode === "dynamic" || mode === "parallel") ordered.sort((a, b) => (b.priority ?? 0) - (a.priority ?? 0));
|
|
84
|
+
this.advancing = true; this.running = true;
|
|
85
|
+
try {
|
|
86
|
+
const saved = this.commit({ scope: this.persistence?.scope ?? "", key: crypto.randomUUID(), revision: 0, contacts: ordered, active: [], wrapped: false, mode, parallelLines });
|
|
87
|
+
if (saved) await saved;
|
|
88
|
+
}
|
|
89
|
+
catch (error) { this.running = false; throw error; }
|
|
90
|
+
finally { this.advancing = false; }
|
|
91
|
+
await this.advance();
|
|
43
92
|
}
|
|
44
93
|
pause() { this.running = false; }
|
|
45
94
|
async resume() {
|
|
46
|
-
if (this.
|
|
47
|
-
if (
|
|
95
|
+
if (!this.initialized) throw new Error("Restore the calling queue before dialing.");
|
|
96
|
+
if (this.advancing || this.wrapping) throw new Error("Queue admission is still pending.");
|
|
97
|
+
if (!this.state?.contacts.length) return;
|
|
98
|
+
// A failed final queue write after successful call-journal cleanup is safe
|
|
99
|
+
// to reconcile, because wrap-up was already persisted before that cleanup.
|
|
100
|
+
if (this.state.wrapped && this.dialer.current.state === "idle") await this.commit({ ...this.state, active: [], wrapped: false });
|
|
48
101
|
this.running = true;
|
|
49
102
|
if (this.dialer.current.state === "idle") await this.advance();
|
|
50
103
|
}
|
|
51
|
-
|
|
52
|
-
|
|
104
|
+
async clear() {
|
|
105
|
+
if (!this.initialized || this.advancing || this.wrapping || this.dialer.current.state !== "idle") throw new Error("Finish the current call before clearing the queue.");
|
|
106
|
+
this.running = false;
|
|
107
|
+
if (this.state) await this.commit({ ...this.state, contacts: [], active: [], wrapped: false });
|
|
108
|
+
}
|
|
109
|
+
/** Persist completed group progress before clearing the call journal. A local
|
|
110
|
+
* audio disconnect or stop acknowledgment never advances the queue. */
|
|
53
111
|
async finishWrapup() {
|
|
54
|
-
|
|
112
|
+
if (this.wrapping || this.advancing) throw new Error("Queue admission is still pending.");
|
|
113
|
+
const snapshot = this.dialer.current;
|
|
114
|
+
if (!["wrapup", "transferred"].includes(snapshot.state)) throw new Error("Confirmed call completion or successful transfer is required.");
|
|
115
|
+
this.wrapping = true;
|
|
116
|
+
try {
|
|
117
|
+
if (this.state?.active.length && !this.state.wrapped) await this.commit({ ...this.state, wrapped: true });
|
|
118
|
+
await this.dialer.finishWrapup();
|
|
119
|
+
if (this.state?.active.length) await this.commit({ ...this.state, active: [], wrapped: false });
|
|
120
|
+
} catch (error) { this.running = false; throw error; }
|
|
121
|
+
finally { this.wrapping = false; }
|
|
55
122
|
if (this.running) await this.advance();
|
|
56
123
|
}
|
|
57
124
|
private async advance() {
|
|
58
|
-
if (this.advancing || !this.running || this.dialer.current.state !== "idle") return;
|
|
125
|
+
if (this.advancing || !this.running || this.dialer.current.state !== "idle" || !this.state) return;
|
|
59
126
|
this.advancing = true;
|
|
60
127
|
try {
|
|
61
|
-
const batch: DialingContact[] = [];
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
const skipped = new Set<string>();
|
|
65
|
-
for (const contact of this.contacts) {
|
|
66
|
-
if (!this.running || batch.length >= this.parallelLines) break;
|
|
128
|
+
const batch: DialingContact[] = [], skipped = new Set<string>();
|
|
129
|
+
for (const contact of this.state.contacts) {
|
|
130
|
+
if (!this.running || batch.length >= this.state.parallelLines) break;
|
|
67
131
|
const permitted = await this.eligible(structuredClone(contact));
|
|
68
132
|
if (!this.running) return;
|
|
69
133
|
if (permitted) batch.push(contact); else skipped.add(contact.id);
|
|
70
134
|
}
|
|
71
135
|
if (!this.running) return;
|
|
72
|
-
|
|
136
|
+
const selected = new Set(batch.map(contact => contact.id));
|
|
137
|
+
await this.commit({ ...this.state, contacts: this.state.contacts.filter(contact => !skipped.has(contact.id) && !selected.has(contact.id)), active: batch, wrapped: false });
|
|
138
|
+
if (!this.running) {
|
|
139
|
+
await this.commit({ ...this.state!, contacts: [...batch, ...this.state!.contacts], active: [] }); return;
|
|
140
|
+
}
|
|
73
141
|
if (batch.length) {
|
|
74
142
|
const first = batch[0]!;
|
|
75
|
-
|
|
76
|
-
const
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
} catch (error) {
|
|
88
|
-
this.running = false;
|
|
89
|
-
// An unconfirmed call remains fenced inside ManagedDialer.
|
|
90
|
-
throw error;
|
|
91
|
-
} finally { this.advancing = false; }
|
|
143
|
+
const { to: _to, destinations: _destinations, transfer_enabled: _transferEnabled, ...common } = first.input;
|
|
144
|
+
const intent: TelephonyBrowserSessionCreate = batch.length === 1 ? first.input : { ...common, destinations: batch.map(contact => contact.input.to!) };
|
|
145
|
+
try { await this.dialer.start(intent, { key: this.state!.key, contactIds: batch.map(contact => contact.id) }); }
|
|
146
|
+
catch (error) {
|
|
147
|
+
// No persisted call means admission did not happen. Retain the group
|
|
148
|
+
// for an explicit retry, including storage denial before network I/O.
|
|
149
|
+
if (this.dialer.queueContext?.key !== this.state!.key) await this.commit({ ...this.state!, contacts: [...batch, ...this.state!.contacts], active: [] });
|
|
150
|
+
throw error;
|
|
151
|
+
}
|
|
152
|
+
} else if (!this.state!.contacts.length) this.running = false;
|
|
153
|
+
} catch (error) { this.running = false; throw error; }
|
|
154
|
+
finally { this.advancing = false; }
|
|
92
155
|
}
|
|
93
156
|
}
|