@pyai/sdk 0.13.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/README.md +34 -4
- 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/dialer/appServer.d.ts +2 -0
- package/dist/dialer/appServer.js +65 -2
- package/dist/dialer/dialingQueue.d.ts +33 -10
- package/dist/dialer/dialingQueue.js +121 -40
- 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 +44 -2
- package/dist/dialer/managedDialer.d.ts +14 -1
- package/dist/dialer/managedDialer.js +25 -7
- 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/serverMeetingIntelligence.d.ts +60 -0
- package/dist/dialer/serverMeetingIntelligence.js +207 -0
- package/dist/index.d.ts +14 -0
- package/dist/index.js +18 -0
- package/package.json +9 -1
- package/src/cli-omni-template.ts +2 -2
- package/src/cli-web-auth.ts +3 -0
- package/src/dialer/MEETING_INTELLIGENCE.md +76 -0
- package/src/dialer/app/app.html +2 -2
- package/src/dialer/app/app.js +39 -12
- package/src/dialer/appServer.ts +45 -3
- package/src/dialer/dialingQueue.ts +107 -46
- package/src/dialer/fileMeetingIntelligenceJournal.ts +77 -0
- package/src/dialer/index.ts +2 -0
- package/src/dialer/indexedDbJournal.ts +44 -2
- package/src/dialer/managedDialer.ts +21 -7
- package/src/dialer/meetingIntelligence.ts +21 -0
- package/src/dialer/meetingIntelligenceElement.ts +65 -0
- package/src/dialer/serverMeetingIntelligence.ts +148 -0
- package/src/index.ts +15 -0
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
# Meeting transcripts, notes and action items
|
|
2
|
+
|
|
3
|
+
The CLI and desktop meeting app now include **Send for transcription** beside
|
|
4
|
+
saved recordings. Capture stays in the browser until the user accepts the
|
|
5
|
+
upload/retention notice and chooses Send. The app uses its selected existing
|
|
6
|
+
project key, the normal private Hear multipart job upload, and existing
|
|
7
|
+
Hear-to-Recap delivery. It does not enable Recap, grant scopes, select a parent
|
|
8
|
+
credential, or upload automatically when recording stops.
|
|
9
|
+
|
|
10
|
+
The host verifies organization/key identity and requires `hear:transcribe`,
|
|
11
|
+
`transcribe:jobs`, `recap:read`, `recap:configure` and enabled Recap. Managed calling
|
|
12
|
+
credentials with only Omni/telephony scopes display an unavailable state with
|
|
13
|
+
the missing access. Choose an already permitted project, or complete the normal
|
|
14
|
+
explicitly authorized feature grant. No operator credential fallback exists.
|
|
15
|
+
|
|
16
|
+
`startDialerApp` includes authenticated same-origin meeting routes, the visible
|
|
17
|
+
browser controls, and a private metadata journal by default. No external asset
|
|
18
|
+
adapter or cloud bucket setup is needed. Project credentials remain in the host.
|
|
19
|
+
The renderer receives only its existing private local session. Uploads require
|
|
20
|
+
that session, the current local nonce, an exact trusted Origin, the accepted
|
|
21
|
+
notice, a supported audio type, and a maximum of 128 MiB. No public route accepts
|
|
22
|
+
an organization, user, job ID, Recap call ID, or audio source URL from the browser.
|
|
23
|
+
|
|
24
|
+
The journal contains an opaque owner/recording key, content digest, job ID and
|
|
25
|
+
cached output. It never stores audio or API keys. It uses a private per-scope
|
|
26
|
+
directory, private files, atomic replacement and durable saves, plus a filesystem
|
|
27
|
+
lease across host instances. A removed entry cannot be resurrected. A crashed
|
|
28
|
+
writer with a recorded dead process can be recovered; an interrupted lease
|
|
29
|
+
recovery fails closed rather than guessing at ownership. The default metadata
|
|
30
|
+
root is the user's `.config/pyai/meetings`; a trusted host can select
|
|
31
|
+
`meetingJournalDirectory`. The normal startup and hourly sweep clear expired
|
|
32
|
+
cached text; the default cache lifetime is 24 hours. Opaque submission tombstones
|
|
33
|
+
remain to prevent unintended re-upload. Windows inherits the private profile's
|
|
34
|
+
access controls; Unix additionally enforces owner-only directory/file modes.
|
|
35
|
+
|
|
36
|
+
The public job API now supports optional Idempotency-Key on both JSON and
|
|
37
|
+
multipart submissions. Its deterministic job identity is scoped to the
|
|
38
|
+
organization and authenticated project. The stored fingerprint binds normalized
|
|
39
|
+
caller options, uploaded bytes and original upload filename. The database
|
|
40
|
+
primary key selects the durable winner even across processes or a lost create
|
|
41
|
+
acknowledgement. Each candidate upload has a content-addressed name, and the
|
|
42
|
+
worker reads the winner's exact file. A losing candidate cannot overwrite its
|
|
43
|
+
audio. Original billing/key/environment and resolved vocabulary snapshots stay
|
|
44
|
+
unchanged. Known jobs recover before new funding/add-on gates; new work still
|
|
45
|
+
passes them. Changed explicit input returns 409. Unkeyed uploads and existing
|
|
46
|
+
GPT-Live deduplication remain compatible.
|
|
47
|
+
|
|
48
|
+
A lost submission response is recovered by sending the **same saved recording**
|
|
49
|
+
with the same owner/recording identity. Do not create a new recording ID after an
|
|
50
|
+
uncertain response. Refresh checks the existing job once, then displays the
|
|
51
|
+
Hear transcript and Recap notes/actions. It does not fetch arbitrary result URLs
|
|
52
|
+
or automatically resubmit failed work. Recap can provide the retained transcript
|
|
53
|
+
when Hear offloads its result. The UI renders output as text nodes.
|
|
54
|
+
|
|
55
|
+
**Retention is explicit.** Uploaded audio may remain in PyAI for up to seven days
|
|
56
|
+
and job result artifacts up to 30 days. Recap records follow workspace retention.
|
|
57
|
+
Removing the meeting from the app clears cached notes, preserves a tombstone and
|
|
58
|
+
requests cancellation of a known unfinished job. Existing DELETE is not a cloud
|
|
59
|
+
erasure API. An uncertain first submission can leave an unknown existing job;
|
|
60
|
+
removal says so and never replays a POST. The browser's saved recording remains
|
|
61
|
+
available. Do not enable submission for a policy requiring immediate cloud
|
|
62
|
+
input/result/Recap erasure until the normal erasure mechanism supports it.
|
|
63
|
+
|
|
64
|
+
The desktop close lifecycle uses `pyai-desktop-prepare-close` and a matching
|
|
65
|
+
`pyai-desktop-close-result` ticket. The app pauses the queue, finalizes capture
|
|
66
|
+
and in-flight journal writes, and stops/reconciles known owned calls. An unknown
|
|
67
|
+
admission returns `ready: false` without replaying a create. Transferred calls
|
|
68
|
+
continue independently. The native host retains credentials when recovery is
|
|
69
|
+
still needed.
|
|
70
|
+
|
|
71
|
+
`softphone-desktop/test-browser/run-meetings.mjs` proves the assembled app UI,
|
|
72
|
+
file journal, SDK upload, actual API and worker, Recap ingest/callback/read,
|
|
73
|
+
lost-response recovery, reload, readable transcript/notes/actions, removal and
|
|
74
|
+
close lifecycle. It uses a tiny synthetic WAV and controlled transcription and
|
|
75
|
+
summary outputs. This proves integration, not ASR or summary quality. It uses
|
|
76
|
+
no customer audio, public model, carrier call or real account credential.
|
package/src/dialer/app/app.html
CHANGED
|
@@ -2,6 +2,6 @@
|
|
|
2
2
|
<aside><a class="brand" href="/" aria-label="PyAI Phone"><span class="logo">p</span> <span data-brand>PyAI Phone</span></a><nav aria-label="Workspace"><button class="selected" data-tab="calls">Phone <span>↗</span></button><button data-tab="meetings">Meeting recorder <span>◉</span></button></nav><div class="aside-foot"><span class="online"></span> Private workspace<br><small>Powered by PyAI</small></div></aside>
|
|
3
3
|
<main><header><div><p class="eyebrow">YOUR CONVERSATIONS, TOGETHER</p><h1 data-heading>Make the next connection.</h1><p class="subtitle" data-subtitle>A clear line. A little less busywork.</p></div><span class="local-badge">On this device</span></header>
|
|
4
4
|
<div id="error" role="alert"></div><button id="retry" hidden>Retry connection</button><section data-panel="calls"><div class="calling-grid"><div><label class="source-label" for="source">Calling from</label><select id="source" disabled><option>Loading workspace numbers…</option></select><label class="recording-choice"><input id="record-calls" type="checkbox">Record calls · tell the other person before recording</label><label class="recording-choice" id="transfer-choice" hidden><input id="allow-transfers" type="checkbox">Allow transfers · single-line calls</label><pyai-dialer></pyai-dialer></div>
|
|
5
|
-
<section class="queue-card"><div class="card-top"><span class="eyebrow">STAY IN YOUR FLOW</span><span class="quiet-icon">≋</span></div><h2>One good conversation<br>after another.</h2><p>Paste your contacts and move through them at your own pace. Each call waits for your wrap-up.</p><label for="contacts">Phone numbers, one per line</label><textarea id="contacts" placeholder="+61 2 5550 0100 +1 415 555 0100" spellcheck="false"></textarea><label for="mode">Calling order</label><select id="mode"><option value="auto">In list order</option><option value="dynamic">Highest priority first · number, priority</option><option value="parallel">
|
|
6
|
-
<section data-panel="meetings" hidden><div class="meeting-grid"><div class="meeting-copy"><span class="eyebrow">LESS DISTRACTION, MORE PRESENCE</span><h2>Stay in the<br>conversation.</h2><p>Choose the audio you want to keep. Record your meeting and microphone together, pause when you need to, and save a private audio file.</p><div class="feature"><b>◉</b><span><strong>Your choice of audio</strong>Choose a supported meeting tab or system source in the browser picker.</span></div><div class="feature"><b>▦</b><span><strong>Saved as you go</strong>Committed audio can be recovered after an interrupted tab.</span></div><div class="feature"><b>↧</b><span><strong>Yours to keep</strong>Download your recording. No automatic uploads or hidden capture.</span></div></div><pyai-meeting-recorder></pyai-meeting-recorder></div></section>
|
|
5
|
+
<section class="queue-card"><div class="card-top"><span class="eyebrow">STAY IN YOUR FLOW</span><span class="quiet-icon">≋</span></div><h2>One good conversation<br>after another.</h2><p>Paste your contacts and move through them at your own pace. Each call waits for your wrap-up.</p><label for="contacts">Phone numbers, one per line</label><textarea id="contacts" placeholder="+61 2 5550 0100 +1 415 555 0100" spellcheck="false"></textarea><label for="mode">Calling order</label><select id="mode"><option value="auto">In list order</option><option value="dynamic">Highest priority first · number, priority</option><option value="parallel">Parallel lines · first answer connects</option></select><div id="parallel-choice" hidden><label for="parallel-lines">Parallel lines</label><select id="parallel-lines"><option value="2">2 lines</option><option value="3">3 lines</option><option value="4">4 lines</option></select></div><div class="queue-actions"><button id="queue-start" class="primary" disabled>Start calling</button><button id="queue-pause" disabled>Pause queue</button><button id="queue-resume" disabled>Resume queue</button><button id="queue-clear" disabled>Clear queue</button></div><p id="queue-status" role="status" aria-live="polite">You choose when to start. Your workspace calling rules apply to every call.</p></section></div></section>
|
|
6
|
+
<section data-panel="meetings" hidden><div class="meeting-grid"><div class="meeting-copy"><span class="eyebrow">LESS DISTRACTION, MORE PRESENCE</span><h2>Stay in the<br>conversation.</h2><p>Choose the audio you want to keep. Record your meeting and microphone together, pause when you need to, and save a private audio file. When you choose, send it for a transcript, notes and action items.</p><div class="feature"><b>◉</b><span><strong>Your choice of audio</strong>Choose a supported meeting tab or system source in the browser picker.</span></div><div class="feature"><b>▦</b><span><strong>Saved as you go</strong>Committed audio can be recovered after an interrupted tab.</span></div><div class="feature"><b>↧</b><span><strong>Yours to keep</strong>Download your recording. No automatic uploads or hidden capture.</span></div></div><pyai-meeting-recorder></pyai-meeting-recorder><pyai-meeting-intelligence></pyai-meeting-intelligence></div></section>
|
|
7
7
|
<footer>Call history and call recordings are stored in your PyAI workspace. Meeting audio stays in this browser until you save or submit it.</footer></main></body></html>
|
package/src/dialer/app/app.js
CHANGED
|
@@ -1,19 +1,23 @@
|
|
|
1
1
|
import { ManagedDialer, dialerCallHandedOff } from '/modules/managedDialer.js';
|
|
2
|
-
import { IndexedDbDialerJournal } from '/modules/indexedDbJournal.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,12 +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
|
-
$('#allow-transfers').disabled=active||state.running||$('#mode').value==='parallel';if($('#mode').value==='parallel')$('#allow-transfers').checked=false;
|
|
30
|
-
$('#source').disabled=active||state.running;$('#mode').disabled=active||state.running;$('#record-calls').disabled=active||state.running;$('#contacts').disabled=state.running||active;
|
|
31
|
-
$('#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
|
|
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.';
|
|
32
38
|
}
|
|
33
39
|
async function refresh(){
|
|
34
40
|
clearTimeout(poll);if(closed)return;
|
|
@@ -47,11 +53,13 @@ async function init(){
|
|
|
47
53
|
source.disabled=!config.numbers.length;
|
|
48
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:'{}'})}};
|
|
49
55
|
const transport=new VoiceSdkAudio(token=>new window.Twilio.Device(token,{logLevel:'silent'}));
|
|
50
|
-
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)};
|
|
51
57
|
dialer=new ManagedDialer(config.scope,broker,new IndexedDbDialerJournal(),audio);
|
|
52
58
|
await dialer.restore();
|
|
53
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}:{})});
|
|
54
|
-
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);});
|
|
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);}
|
|
55
63
|
$('pyai-dialer').bind(dialer,to=>{
|
|
56
64
|
if(!config.numbers.length)throw Error('Add a voice number in your PyAI workspace before calling.');
|
|
57
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.');
|
|
@@ -59,15 +67,34 @@ async function init(){
|
|
|
59
67
|
},{name:config.name,showBranding:!config.white_label},async()=>{await queue.finishWrapup();renderQueue();});
|
|
60
68
|
dialer.subscribe(()=>renderQueue());renderQueue();
|
|
61
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:'{}'})});
|
|
62
71
|
$('#queue-start').addEventListener('click',()=>void act(async()=>{
|
|
63
72
|
const contacts=$('#contacts').value.split(/\r?\n/).map(line=>line.trim()).filter(Boolean).map((line,index)=>{
|
|
64
73
|
const [number,priority='0']=line.split(',').map(value=>value.trim());const to=number.replace(/[\s()-]/g,'');
|
|
65
74
|
if(config.numbers.find(n=>n.id===source.value)?.phone_number===to)throw Error(`Line ${index+1} matches your calling number.`);
|
|
66
75
|
return {id:crypto.randomUUID(),input:inputFor(to),priority:Number(priority)};
|
|
67
|
-
});await queue.start(contacts,$('#mode').value);renderQueue();
|
|
76
|
+
});await queue.start(contacts,$('#mode').value,{parallelLines:Number($('#parallel-lines').value)});renderQueue();
|
|
68
77
|
}));
|
|
69
78
|
$('#mode').addEventListener('change',renderQueue);
|
|
79
|
+
$('#queue-clear').addEventListener('click',()=>void act(async()=>{await queue.clear();renderQueue();}));
|
|
70
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
|
+
});
|
|
71
98
|
window.addEventListener('pagehide',()=>{
|
|
72
99
|
closed=true;clearTimeout(poll);queue.pause();audio.disconnect();void recorder.stop();
|
|
73
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(()=>{});
|
package/src/dialer/appServer.ts
CHANGED
|
@@ -4,6 +4,10 @@ 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";
|
|
@@ -20,12 +24,14 @@ export interface DialerAppOptions {
|
|
|
20
24
|
/** Operator opt-in; the API independently enforces transfer activation. */
|
|
21
25
|
allowTransfers?: boolean;
|
|
22
26
|
port?: number;
|
|
27
|
+
/** Trusted host path; never accepted through HTTP. Metadata only, no audio. */
|
|
28
|
+
meetingJournalDirectory?: string;
|
|
23
29
|
/** Explicit asset injection for packaging/tests, never selected by HTTP. */
|
|
24
30
|
assets?: { read(path: string): Promise<Uint8Array> };
|
|
25
31
|
}
|
|
26
32
|
const terminal = (call: TelephonyCall) => ["completed", "failed", "canceled"].includes(call.status);
|
|
27
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));
|
|
28
|
-
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"]);
|
|
29
35
|
const publicAssets = new Set(["/", "/app.js", "/app.css", "/manifest.webmanifest", "/icon.svg"]);
|
|
30
36
|
const publicModule = (path: string) => { const match = /^\/modules\/([A-Za-z]+)\.js$/.exec(path); return match && browserModules.has(match[1]!) ? match[1] : null; };
|
|
31
37
|
async function packagedAsset(path: string): Promise<Uint8Array> {
|
|
@@ -66,6 +72,18 @@ export async function startDialerApp(options: DialerAppOptions) {
|
|
|
66
72
|
const remember = (call: TelephonyCall) => { if (terminal(call) || dialerCallHandedOff(call)) calls.delete(call.id); else calls.add(call.id); return call; };
|
|
67
73
|
const numbers = async () => (await options.sdk.telephony.numbers.list()).data.filter(number => number.status !== "released" && number.capabilities?.voice === true);
|
|
68
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
|
+
|
|
69
87
|
const server = createServer(async (request, response) => {
|
|
70
88
|
response.setHeader("cache-control", "no-store"); response.setHeader("x-content-type-options", "nosniff"); response.setHeader("x-frame-options", "DENY");
|
|
71
89
|
response.setHeader("referrer-policy", "no-referrer");
|
|
@@ -93,6 +111,29 @@ export async function startDialerApp(options: DialerAppOptions) {
|
|
|
93
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,
|
|
94
112
|
numbers: owned.map(number => ({ id: number.id, phone_number: number.phone_number, country: number.country })) });
|
|
95
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
|
+
}
|
|
96
137
|
if (url.pathname === "/api/sessions" && method === "POST") {
|
|
97
138
|
if (closing) throw new AppError(503, "Dialer is closing. No new calls are admitted.");
|
|
98
139
|
const input = await body(request), key = request.headers["idempotency-key"];
|
|
@@ -153,12 +194,13 @@ export async function startDialerApp(options: DialerAppOptions) {
|
|
|
153
194
|
}
|
|
154
195
|
});
|
|
155
196
|
server.requestTimeout = 20000; server.headersTimeout = 10000; server.maxRequestsPerSocket = 100;
|
|
156
|
-
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(); }); });
|
|
157
198
|
const address = server.address(); if (!address || typeof address === "string") throw new Error("No local dialer address.");
|
|
158
199
|
origin = `http://127.0.0.1:${address.port}`;
|
|
159
200
|
let closePromise: Promise<{ unsettled: string[] }> | null = null;
|
|
160
201
|
return { url: origin, launchUrl: `${origin}#${bootstrap}`, close: () => closePromise ??= (async () => {
|
|
161
|
-
closing = true; const deadline = Date.now() + 20000;
|
|
202
|
+
closing = true; clearInterval(sweep); const deadline = Date.now() + 20000;
|
|
203
|
+
await Promise.allSettled([...meetingActions]);
|
|
162
204
|
await Promise.allSettled([...calls].map(async id => { remember(await broker.hangup(id)); }));
|
|
163
205
|
while (calls.size && Date.now() < deadline) { await new Promise(resolve => setTimeout(resolve, 500)); await Promise.allSettled([...calls].map(own)); }
|
|
164
206
|
await new Promise<void>(resolve => { server.close(() => resolve()); server.closeIdleConnections?.(); });
|
|
@@ -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,65 +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") {
|
|
34
|
-
if (contacts.some(contact => contact.input.transfer_enabled === true))
|
|
35
|
-
throw new Error("Transfer-enabled calls use single-line dialing.");
|
|
75
|
+
if (contacts.some(contact => contact.input.transfer_enabled === true)) throw new Error("Transfer-enabled calls use single-line dialing.");
|
|
36
76
|
const fingerprint = (contact: DialingContact) => JSON.stringify([contact.input.from_number_id, contact.input.user_id,
|
|
37
77
|
contact.input.recording, contact.input.use_case ?? "support", contact.input.max_duration_seconds ?? 3600]);
|
|
38
78
|
if (new Set(contacts.map(c => c.input.to)).size !== contacts.length || contacts.some(c => fingerprint(c) !== fingerprint(contacts[0]!)))
|
|
39
79
|
throw new Error("Parallel contacts must have distinct numbers and share the same user, source and calling settings.");
|
|
40
80
|
}
|
|
41
|
-
this.
|
|
42
|
-
|
|
43
|
-
if (mode === "dynamic" || mode === "parallel")
|
|
44
|
-
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();
|
|
45
92
|
}
|
|
46
93
|
pause() { this.running = false; }
|
|
47
94
|
async resume() {
|
|
48
|
-
if (this.
|
|
49
|
-
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 });
|
|
50
101
|
this.running = true;
|
|
51
102
|
if (this.dialer.current.state === "idle") await this.advance();
|
|
52
103
|
}
|
|
53
|
-
|
|
54
|
-
|
|
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. */
|
|
55
111
|
async finishWrapup() {
|
|
56
|
-
|
|
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; }
|
|
57
122
|
if (this.running) await this.advance();
|
|
58
123
|
}
|
|
59
124
|
private async advance() {
|
|
60
|
-
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;
|
|
61
126
|
this.advancing = true;
|
|
62
127
|
try {
|
|
63
|
-
const batch: DialingContact[] = [];
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
const skipped = new Set<string>();
|
|
67
|
-
for (const contact of this.contacts) {
|
|
68
|
-
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;
|
|
69
131
|
const permitted = await this.eligible(structuredClone(contact));
|
|
70
132
|
if (!this.running) return;
|
|
71
133
|
if (permitted) batch.push(contact); else skipped.add(contact.id);
|
|
72
134
|
}
|
|
73
135
|
if (!this.running) return;
|
|
74
|
-
|
|
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
|
+
}
|
|
75
141
|
if (batch.length) {
|
|
76
142
|
const first = batch[0]!;
|
|
77
|
-
this.activeId = first.id; this.activeIds = batch.map(contact => contact.id);
|
|
78
143
|
const { to: _to, destinations: _destinations, transfer_enabled: _transferEnabled, ...common } = first.input;
|
|
79
|
-
const intent: TelephonyBrowserSessionCreate = batch.length === 1 ? first.input
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
}
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
this.running = false;
|
|
91
|
-
// An unconfirmed call remains fenced inside ManagedDialer.
|
|
92
|
-
throw error;
|
|
93
|
-
} finally { this.advancing = false; }
|
|
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; }
|
|
94
155
|
}
|
|
95
156
|
}
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
/** Private local metadata journal used by the CLI and desktop companion.
|
|
2
|
+
* Audio remains in the browser store until an explicit send. */
|
|
3
|
+
import { mkdir, open, readFile, rename, rm, lstat, readdir } from "node:fs/promises";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
6
|
+
import type { MeetingIntelligenceEntry, MeetingIntelligenceJournal } from "./serverMeetingIntelligence.ts";
|
|
7
|
+
|
|
8
|
+
export class FileMeetingIntelligenceJournal implements MeetingIntelligenceJournal {
|
|
9
|
+
private readonly directory: string;
|
|
10
|
+
private initialized: Promise<void> | null = null;
|
|
11
|
+
constructor(root: string, scope: string) {
|
|
12
|
+
if (!scope.trim()) throw new Error("A private meeting scope is required.");
|
|
13
|
+
this.directory = join(root, createHash("sha256").update(scope).digest("hex"));
|
|
14
|
+
}
|
|
15
|
+
private initialize() { return this.initialized ??= (async () => {
|
|
16
|
+
await mkdir(this.directory, { recursive: true, mode: 0o700 });
|
|
17
|
+
const info = await lstat(this.directory);
|
|
18
|
+
if (!info.isDirectory() || info.isSymbolicLink() || (process.platform !== "win32" && (info.mode & 0o077)) || process.getuid && info.uid !== process.getuid()) throw new Error("Meeting journal must be a private directory owned by this user.");
|
|
19
|
+
})(); }
|
|
20
|
+
async sweep(): Promise<void> {
|
|
21
|
+
await this.initialize();
|
|
22
|
+
const files = await readdir(this.directory);
|
|
23
|
+
if (files.length > 20000) throw new Error("Meeting metadata limit reached. Clean up old local meeting entries.");
|
|
24
|
+
for (const file of files.filter(file => /^meeting_[a-f0-9]{64}\.json$/.test(file))) {
|
|
25
|
+
const entry = await this.get(file.slice(0, -5));
|
|
26
|
+
if (entry && entry.expiresAt <= Date.now() && (entry.transcript || entry.notes || entry.actionItems.length)) await this.run(entry.key, async () => {
|
|
27
|
+
const current = await this.get(entry.key); if (current && current.expiresAt <= Date.now()) await this.save({ ...current, transcript: null, notes: null, actionItems: [] });
|
|
28
|
+
});
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
private path(key: string) { if (!/^meeting_[a-f0-9]{64}$/.test(key)) throw new Error("Invalid private meeting key."); return join(this.directory, key + ".json"); }
|
|
32
|
+
private alive(pid: number) { try { process.kill(pid, 0); return true; } catch (error) { return (error as NodeJS.ErrnoException).code !== "ESRCH"; } }
|
|
33
|
+
async run<T>(key: string, action: () => Promise<T>): Promise<T> {
|
|
34
|
+
await this.initialize();
|
|
35
|
+
this.path(key); const lock = join(this.directory, key + ".lock"), token = randomUUID();
|
|
36
|
+
const deadline = Date.now() + 3000, staged = lock + "." + token + ".staged"; let acquired = false;
|
|
37
|
+
// Publish a fully written owner atomically. A crash between mkdir and an
|
|
38
|
+
// owner write must never leave an ownerless visible lease.
|
|
39
|
+
await mkdir(staged, { mode: 0o700 }); await this.write(join(staged, "owner.json"), { pid: process.pid, token });
|
|
40
|
+
try { while (!acquired) {
|
|
41
|
+
try { await rename(staged, lock); acquired = true; }
|
|
42
|
+
catch (error) {
|
|
43
|
+
if (!["EEXIST", "ENOTEMPTY", ...(process.platform === "win32" ? ["EPERM"] : [])].includes((error as NodeJS.ErrnoException).code ?? "")) throw error;
|
|
44
|
+
// Recover a crashed writer under a separate exclusive recovery gate.
|
|
45
|
+
// A competing live writer is never removed. An interrupted recovery
|
|
46
|
+
// fails closed rather than guessing about ownership.
|
|
47
|
+
try {
|
|
48
|
+
const prior = JSON.parse(await readFile(join(lock, "owner.json"), "utf8")) as { pid: number; token: string };
|
|
49
|
+
if (Number.isInteger(prior.pid) && prior.pid > 0 && !this.alive(prior.pid)) {
|
|
50
|
+
const recovery = await open(lock + ".recover", "wx", 0o600);
|
|
51
|
+
try { const current = JSON.parse(await readFile(join(lock, "owner.json"), "utf8")) as { pid: number; token: string }; if (current.token === prior.token && !this.alive(current.pid)) await rm(lock, { recursive: true, force: true }); }
|
|
52
|
+
finally { await recovery.close(); await rm(lock + ".recover", { force: true }); }
|
|
53
|
+
}
|
|
54
|
+
} catch (error) { if (!(error instanceof SyntaxError) && !["ENOENT", "EEXIST"].includes((error as NodeJS.ErrnoException).code ?? "")) throw error; }
|
|
55
|
+
if (Date.now() >= deadline) throw new Error("This meeting is being updated in another app. Wait for it to finish and recover the same recording.");
|
|
56
|
+
await new Promise(resolve => setTimeout(resolve, 25));
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
return await action();
|
|
60
|
+
} finally {
|
|
61
|
+
await rm(staged, { recursive: true, force: true });
|
|
62
|
+
if (acquired) { const owner = JSON.parse(await readFile(join(lock, "owner.json"), "utf8")) as { token: string }; if (owner.token === token) await rm(lock, { recursive: true, force: true }); }
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
async get(key: string): Promise<MeetingIntelligenceEntry | null> {
|
|
66
|
+
try { const file = this.path(key), info = await lstat(file); if (!info.isFile() || info.isSymbolicLink() || info.size > 4 * 1024 * 1024 || (process.platform !== "win32" && (info.mode & 0o077))) throw new Error("Private meeting metadata is invalid."); return JSON.parse(await readFile(file, "utf8")) as MeetingIntelligenceEntry; }
|
|
67
|
+
catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") return null; throw error; }
|
|
68
|
+
}
|
|
69
|
+
private async write(file: string, value: unknown) { const handle = await open(file, "wx", 0o600); try { await handle.writeFile(JSON.stringify(value)); await handle.sync(); } finally { await handle.close(); } }
|
|
70
|
+
async save(entry: MeetingIntelligenceEntry): Promise<void> {
|
|
71
|
+
const file = this.path(entry.key), current = await this.get(entry.key);
|
|
72
|
+
if (current?.state === "removed" && entry.state !== "removed") throw new Error("This meeting was removed. Recover the current state.");
|
|
73
|
+
const temporary = file + "." + randomUUID() + ".tmp";
|
|
74
|
+
try { if (Buffer.byteLength(JSON.stringify(entry)) > 4 * 1024 * 1024) throw new Error("Meeting metadata exceeds the private cache limit."); await this.write(temporary, entry); await rename(temporary, file); if (process.platform !== "win32") { const directory = await open(this.directory, "r"); try { await directory.sync(); } finally { await directory.close(); } } }
|
|
75
|
+
finally { await rm(temporary, { force: true }); }
|
|
76
|
+
}
|
|
77
|
+
}
|