@pyai/sdk 0.13.0 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/README.md +57 -4
  2. package/dist/cli-omni-template.d.ts +2 -2
  3. package/dist/cli-omni-template.js +2 -2
  4. package/dist/cli-web-auth.d.ts +2 -0
  5. package/dist/cli-web-auth.js +2 -0
  6. package/dist/dialer/appServer.d.ts +2 -0
  7. package/dist/dialer/appServer.js +65 -2
  8. package/dist/dialer/dialingQueue.d.ts +33 -10
  9. package/dist/dialer/dialingQueue.js +121 -40
  10. package/dist/dialer/fileMeetingIntelligenceJournal.d.ts +14 -0
  11. package/dist/dialer/fileMeetingIntelligenceJournal.js +147 -0
  12. package/dist/dialer/index.d.ts +2 -0
  13. package/dist/dialer/index.js +2 -0
  14. package/dist/dialer/indexedDbJournal.d.ts +9 -0
  15. package/dist/dialer/indexedDbJournal.js +44 -2
  16. package/dist/dialer/managedBrowserAudio.d.ts +21 -0
  17. package/dist/dialer/managedBrowserAudio.js +69 -0
  18. package/dist/dialer/managedDialer.d.ts +14 -1
  19. package/dist/dialer/managedDialer.js +25 -7
  20. package/dist/dialer/meetingIntelligence.d.ts +28 -0
  21. package/dist/dialer/meetingIntelligence.js +3 -0
  22. package/dist/dialer/meetingIntelligenceElement.d.ts +21 -0
  23. package/dist/dialer/meetingIntelligenceElement.js +112 -0
  24. package/dist/dialer/serverMeetingIntelligence.d.ts +60 -0
  25. package/dist/dialer/serverMeetingIntelligence.js +207 -0
  26. package/dist/index.d.ts +14 -0
  27. package/dist/index.js +18 -0
  28. package/package.json +9 -1
  29. package/src/cli-omni-template.ts +2 -2
  30. package/src/cli-web-auth.ts +3 -0
  31. package/src/dialer/MEETING_INTELLIGENCE.md +76 -0
  32. package/src/dialer/app/app.html +2 -2
  33. package/src/dialer/app/app.js +39 -12
  34. package/src/dialer/appServer.ts +45 -3
  35. package/src/dialer/dialingQueue.ts +107 -46
  36. package/src/dialer/fileMeetingIntelligenceJournal.ts +77 -0
  37. package/src/dialer/index.ts +3 -0
  38. package/src/dialer/indexedDbJournal.ts +44 -2
  39. package/src/dialer/managedBrowserAudio.ts +75 -0
  40. package/src/dialer/managedDialer.ts +21 -7
  41. package/src/dialer/meetingIntelligence.ts +21 -0
  42. package/src/dialer/meetingIntelligenceElement.ts +65 -0
  43. package/src/dialer/serverMeetingIntelligence.ts +148 -0
  44. package/src/index.ts +15 -0
@@ -1,22 +1,57 @@
1
- /** Auto, priority-based dynamic, and server-owned parallel dialing. A session must
2
- * be explicitly started in the foreground; no calls resume automatically after
3
- * reload. The backend rechecks policy and capacity for every admission. */
1
+ /** Auto, priority-based dynamic, and server-owned parallel dialing. Durable
2
+ * queues restore paused; no calls resume automatically after reload. */
4
3
  export class DialingQueue {
5
- contacts = [];
4
+ state = null;
6
5
  running = false;
7
6
  advancing = false;
8
- activeId = null;
9
- activeIds = [];
10
- parallelLines = 1;
7
+ wrapping = false;
8
+ initialized;
11
9
  dialer;
12
10
  eligible;
13
- constructor(dialer, eligible) {
11
+ persistence;
12
+ constructor(dialer, eligible, persistence) {
14
13
  this.dialer = dialer;
15
14
  this.eligible = eligible;
15
+ this.persistence = persistence;
16
+ if (persistence && (!persistence.scope.trim() || persistence.scope !== dialer.recoveryScope))
17
+ throw new Error("The saved queue must use the calling controller’s authenticated workspace/user scope.");
18
+ this.initialized = !persistence;
19
+ }
20
+ get current() {
21
+ return { running: this.running, remaining: this.state?.contacts.length ?? 0,
22
+ activeId: this.state?.active[0]?.id ?? null, activeIds: this.state?.active.map(contact => contact.id) ?? [],
23
+ mode: this.state?.mode ?? "auto", parallelLines: this.state?.parallelLines ?? 1 };
24
+ }
25
+ commit(state) {
26
+ const next = structuredClone(state);
27
+ next.revision = (this.state?.revision ?? 0) + 1;
28
+ if (this.persistence)
29
+ return this.persistence.journal.write(next, this.state?.revision ?? null).then(() => { this.state = next; });
30
+ this.state = next;
31
+ }
32
+ async restore() {
33
+ if (this.initialized)
34
+ return;
35
+ if (!this.dialer.restored)
36
+ throw new Error("Restore the calling journal before restoring the queue.");
37
+ const saved = await this.persistence.journal.read(this.persistence.scope);
38
+ if (saved && saved.scope !== this.persistence.scope)
39
+ throw new Error("Saved queue belongs to another workspace.");
40
+ this.state = saved ? structuredClone(saved) : null;
41
+ // A crash before call-intent persistence is safe to retry. A crash after
42
+ // wrap-up persistence must never put the completed contacts back in line.
43
+ if (this.state?.active.length) {
44
+ const context = this.dialer.queueContext;
45
+ const same = context?.key === this.state.key && JSON.stringify(context.contactIds) === JSON.stringify(this.state.active.map(c => c.id));
46
+ if (!same)
47
+ await this.commit({ ...this.state, contacts: this.state.wrapped ? this.state.contacts : [...this.state.active, ...this.state.contacts], active: [], wrapped: false });
48
+ }
49
+ this.initialized = true;
16
50
  }
17
- get current() { return { running: this.running, remaining: this.contacts.length, activeId: this.activeId, activeIds: [...this.activeIds] }; }
18
51
  async start(contacts, mode = "auto", options = {}) {
19
- if (this.running || this.advancing || this.dialer.current.state !== "idle")
52
+ if (!this.initialized)
53
+ throw new Error("Restore the calling queue before dialing.");
54
+ if (this.running || this.advancing || this.wrapping || this.dialer.current.state !== "idle")
20
55
  throw new Error("Finish the current call before starting a queue.");
21
56
  if (!contacts.length || contacts.length > 500 || new Set(contacts.map(c => c.id)).size !== contacts.length ||
22
57
  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)))
@@ -34,43 +69,84 @@ export class DialingQueue {
34
69
  if (new Set(contacts.map(c => c.input.to)).size !== contacts.length || contacts.some(c => fingerprint(c) !== fingerprint(contacts[0])))
35
70
  throw new Error("Parallel contacts must have distinct numbers and share the same user, source and calling settings.");
36
71
  }
37
- this.parallelLines = parallelLines;
38
- this.contacts = structuredClone(contacts);
72
+ if (this.state?.contacts.length || this.state?.active.length)
73
+ throw new Error("Resume or clear the saved queue before starting another.");
74
+ const ordered = structuredClone(contacts);
39
75
  if (mode === "dynamic" || mode === "parallel")
40
- this.contacts.sort((a, b) => (b.priority ?? 0) - (a.priority ?? 0));
76
+ ordered.sort((a, b) => (b.priority ?? 0) - (a.priority ?? 0));
77
+ this.advancing = true;
41
78
  this.running = true;
79
+ try {
80
+ const saved = this.commit({ scope: this.persistence?.scope ?? "", key: crypto.randomUUID(), revision: 0, contacts: ordered, active: [], wrapped: false, mode, parallelLines });
81
+ if (saved)
82
+ await saved;
83
+ }
84
+ catch (error) {
85
+ this.running = false;
86
+ throw error;
87
+ }
88
+ finally {
89
+ this.advancing = false;
90
+ }
42
91
  await this.advance();
43
92
  }
44
93
  pause() { this.running = false; }
45
94
  async resume() {
46
- if (this.advancing)
95
+ if (!this.initialized)
96
+ throw new Error("Restore the calling queue before dialing.");
97
+ if (this.advancing || this.wrapping)
47
98
  throw new Error("Queue admission is still pending.");
48
- if (!this.contacts.length)
99
+ if (!this.state?.contacts.length)
49
100
  return;
101
+ // A failed final queue write after successful call-journal cleanup is safe
102
+ // to reconcile, because wrap-up was already persisted before that cleanup.
103
+ if (this.state.wrapped && this.dialer.current.state === "idle")
104
+ await this.commit({ ...this.state, active: [], wrapped: false });
50
105
  this.running = true;
51
106
  if (this.dialer.current.state === "idle")
52
107
  await this.advance();
53
108
  }
54
- /** Explicit wrap-up acknowledgment gates the next admission. A local audio
55
- * disconnect or a durable stop acknowledgment never advances the queue. */
109
+ async clear() {
110
+ if (!this.initialized || this.advancing || this.wrapping || this.dialer.current.state !== "idle")
111
+ throw new Error("Finish the current call before clearing the queue.");
112
+ this.running = false;
113
+ if (this.state)
114
+ await this.commit({ ...this.state, contacts: [], active: [], wrapped: false });
115
+ }
116
+ /** Persist completed group progress before clearing the call journal. A local
117
+ * audio disconnect or stop acknowledgment never advances the queue. */
56
118
  async finishWrapup() {
57
- await this.dialer.finishWrapup();
58
- this.activeId = null;
59
- this.activeIds = [];
119
+ if (this.wrapping || this.advancing)
120
+ throw new Error("Queue admission is still pending.");
121
+ const snapshot = this.dialer.current;
122
+ if (!["wrapup", "transferred"].includes(snapshot.state))
123
+ throw new Error("Confirmed call completion or successful transfer is required.");
124
+ this.wrapping = true;
125
+ try {
126
+ if (this.state?.active.length && !this.state.wrapped)
127
+ await this.commit({ ...this.state, wrapped: true });
128
+ await this.dialer.finishWrapup();
129
+ if (this.state?.active.length)
130
+ await this.commit({ ...this.state, active: [], wrapped: false });
131
+ }
132
+ catch (error) {
133
+ this.running = false;
134
+ throw error;
135
+ }
136
+ finally {
137
+ this.wrapping = false;
138
+ }
60
139
  if (this.running)
61
140
  await this.advance();
62
141
  }
63
142
  async advance() {
64
- if (this.advancing || !this.running || this.dialer.current.state !== "idle")
143
+ if (this.advancing || !this.running || this.dialer.current.state !== "idle" || !this.state)
65
144
  return;
66
145
  this.advancing = true;
67
146
  try {
68
- const batch = [];
69
- // Select the entire batch before admitting one immutable group. Pausing
70
- // during eligibility cannot launch a partial group or consume contacts.
71
- const skipped = new Set();
72
- for (const contact of this.contacts) {
73
- if (!this.running || batch.length >= this.parallelLines)
147
+ const batch = [], skipped = new Set();
148
+ for (const contact of this.state.contacts) {
149
+ if (!this.running || batch.length >= this.state.parallelLines)
74
150
  break;
75
151
  const permitted = await this.eligible(structuredClone(contact));
76
152
  if (!this.running)
@@ -82,27 +158,32 @@ export class DialingQueue {
82
158
  }
83
159
  if (!this.running)
84
160
  return;
85
- this.contacts = this.contacts.filter(contact => !skipped.has(contact.id));
161
+ const selected = new Set(batch.map(contact => contact.id));
162
+ await this.commit({ ...this.state, contacts: this.state.contacts.filter(contact => !skipped.has(contact.id) && !selected.has(contact.id)), active: batch, wrapped: false });
163
+ if (!this.running) {
164
+ await this.commit({ ...this.state, contacts: [...batch, ...this.state.contacts], active: [] });
165
+ return;
166
+ }
86
167
  if (batch.length) {
87
168
  const first = batch[0];
88
- this.activeId = first.id;
89
- this.activeIds = batch.map(contact => contact.id);
90
169
  const { to: _to, destinations: _destinations, transfer_enabled: _transferEnabled, ...common } = first.input;
91
- const intent = batch.length === 1 ? first.input
92
- : { ...common, destinations: batch.map(contact => contact.input.to) };
93
- // ManagedDialer persists the group and one key before any request.
94
- // Unconfirmed admission remains fenced; no individual line is retried.
95
- await this.dialer.start(intent);
96
- const admitted = new Set(this.activeIds);
97
- this.contacts = this.contacts.filter(contact => !admitted.has(contact.id));
98
- return;
170
+ const intent = batch.length === 1 ? first.input : { ...common, destinations: batch.map(contact => contact.input.to) };
171
+ try {
172
+ await this.dialer.start(intent, { key: this.state.key, contactIds: batch.map(contact => contact.id) });
173
+ }
174
+ catch (error) {
175
+ // No persisted call means admission did not happen. Retain the group
176
+ // for an explicit retry, including storage denial before network I/O.
177
+ if (this.dialer.queueContext?.key !== this.state.key)
178
+ await this.commit({ ...this.state, contacts: [...batch, ...this.state.contacts], active: [] });
179
+ throw error;
180
+ }
99
181
  }
100
- if (!this.contacts.length)
182
+ else if (!this.state.contacts.length)
101
183
  this.running = false;
102
184
  }
103
185
  catch (error) {
104
186
  this.running = false;
105
- // An unconfirmed call remains fenced inside ManagedDialer.
106
187
  throw error;
107
188
  }
108
189
  finally {
@@ -0,0 +1,14 @@
1
+ import type { MeetingIntelligenceEntry, MeetingIntelligenceJournal } from "./serverMeetingIntelligence.ts";
2
+ export declare class FileMeetingIntelligenceJournal implements MeetingIntelligenceJournal {
3
+ private readonly directory;
4
+ private initialized;
5
+ constructor(root: string, scope: string);
6
+ private initialize;
7
+ sweep(): Promise<void>;
8
+ private path;
9
+ private alive;
10
+ run<T>(key: string, action: () => Promise<T>): Promise<T>;
11
+ get(key: string): Promise<MeetingIntelligenceEntry | null>;
12
+ private write;
13
+ save(entry: MeetingIntelligenceEntry): Promise<void>;
14
+ }
@@ -0,0 +1,147 @@
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
+ export class FileMeetingIntelligenceJournal {
7
+ directory;
8
+ initialized = null;
9
+ constructor(root, scope) {
10
+ if (!scope.trim())
11
+ throw new Error("A private meeting scope is required.");
12
+ this.directory = join(root, createHash("sha256").update(scope).digest("hex"));
13
+ }
14
+ initialize() {
15
+ 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())
19
+ throw new Error("Meeting journal must be a private directory owned by this user.");
20
+ })();
21
+ }
22
+ async sweep() {
23
+ await this.initialize();
24
+ const files = await readdir(this.directory);
25
+ if (files.length > 20000)
26
+ throw new Error("Meeting metadata limit reached. Clean up old local meeting entries.");
27
+ for (const file of files.filter(file => /^meeting_[a-f0-9]{64}\.json$/.test(file))) {
28
+ const entry = await this.get(file.slice(0, -5));
29
+ if (entry && entry.expiresAt <= Date.now() && (entry.transcript || entry.notes || entry.actionItems.length))
30
+ await this.run(entry.key, async () => {
31
+ const current = await this.get(entry.key);
32
+ if (current && current.expiresAt <= Date.now())
33
+ await this.save({ ...current, transcript: null, notes: null, actionItems: [] });
34
+ });
35
+ }
36
+ }
37
+ path(key) { if (!/^meeting_[a-f0-9]{64}$/.test(key))
38
+ throw new Error("Invalid private meeting key."); return join(this.directory, key + ".json"); }
39
+ alive(pid) { try {
40
+ process.kill(pid, 0);
41
+ return true;
42
+ }
43
+ catch (error) {
44
+ return error.code !== "ESRCH";
45
+ } }
46
+ async run(key, action) {
47
+ await this.initialize();
48
+ this.path(key);
49
+ const lock = join(this.directory, key + ".lock"), token = randomUUID();
50
+ const deadline = Date.now() + 3000, staged = lock + "." + token + ".staged";
51
+ let acquired = false;
52
+ // Publish a fully written owner atomically. A crash between mkdir and an
53
+ // owner write must never leave an ownerless visible lease.
54
+ await mkdir(staged, { mode: 0o700 });
55
+ await this.write(join(staged, "owner.json"), { pid: process.pid, token });
56
+ try {
57
+ while (!acquired) {
58
+ try {
59
+ await rename(staged, lock);
60
+ acquired = true;
61
+ }
62
+ catch (error) {
63
+ if (!["EEXIST", "ENOTEMPTY", ...(process.platform === "win32" ? ["EPERM"] : [])].includes(error.code ?? ""))
64
+ throw error;
65
+ // Recover a crashed writer under a separate exclusive recovery gate.
66
+ // A competing live writer is never removed. An interrupted recovery
67
+ // fails closed rather than guessing about ownership.
68
+ try {
69
+ const prior = JSON.parse(await readFile(join(lock, "owner.json"), "utf8"));
70
+ if (Number.isInteger(prior.pid) && prior.pid > 0 && !this.alive(prior.pid)) {
71
+ const recovery = await open(lock + ".recover", "wx", 0o600);
72
+ try {
73
+ const current = JSON.parse(await readFile(join(lock, "owner.json"), "utf8"));
74
+ if (current.token === prior.token && !this.alive(current.pid))
75
+ await rm(lock, { recursive: true, force: true });
76
+ }
77
+ finally {
78
+ await recovery.close();
79
+ await rm(lock + ".recover", { force: true });
80
+ }
81
+ }
82
+ }
83
+ catch (error) {
84
+ if (!(error instanceof SyntaxError) && !["ENOENT", "EEXIST"].includes(error.code ?? ""))
85
+ throw error;
86
+ }
87
+ if (Date.now() >= deadline)
88
+ throw new Error("This meeting is being updated in another app. Wait for it to finish and recover the same recording.");
89
+ await new Promise(resolve => setTimeout(resolve, 25));
90
+ }
91
+ }
92
+ return await action();
93
+ }
94
+ finally {
95
+ await rm(staged, { recursive: true, force: true });
96
+ if (acquired) {
97
+ const owner = JSON.parse(await readFile(join(lock, "owner.json"), "utf8"));
98
+ if (owner.token === token)
99
+ await rm(lock, { recursive: true, force: true });
100
+ }
101
+ }
102
+ }
103
+ async get(key) {
104
+ try {
105
+ const file = this.path(key), info = await lstat(file);
106
+ if (!info.isFile() || info.isSymbolicLink() || info.size > 4 * 1024 * 1024 || (process.platform !== "win32" && (info.mode & 0o077)))
107
+ throw new Error("Private meeting metadata is invalid.");
108
+ return JSON.parse(await readFile(file, "utf8"));
109
+ }
110
+ catch (error) {
111
+ if (error.code === "ENOENT")
112
+ return null;
113
+ throw error;
114
+ }
115
+ }
116
+ async write(file, value) { const handle = await open(file, "wx", 0o600); try {
117
+ await handle.writeFile(JSON.stringify(value));
118
+ await handle.sync();
119
+ }
120
+ finally {
121
+ await handle.close();
122
+ } }
123
+ async save(entry) {
124
+ const file = this.path(entry.key), current = await this.get(entry.key);
125
+ if (current?.state === "removed" && entry.state !== "removed")
126
+ throw new Error("This meeting was removed. Recover the current state.");
127
+ const temporary = file + "." + randomUUID() + ".tmp";
128
+ try {
129
+ if (Buffer.byteLength(JSON.stringify(entry)) > 4 * 1024 * 1024)
130
+ throw new Error("Meeting metadata exceeds the private cache limit.");
131
+ await this.write(temporary, entry);
132
+ await rename(temporary, file);
133
+ if (process.platform !== "win32") {
134
+ const directory = await open(this.directory, "r");
135
+ try {
136
+ await directory.sync();
137
+ }
138
+ finally {
139
+ await directory.close();
140
+ }
141
+ }
142
+ }
143
+ finally {
144
+ await rm(temporary, { force: true });
145
+ }
146
+ }
147
+ }
@@ -2,5 +2,7 @@ export * from "./managedDialer.ts";
2
2
  export * from "./dialingQueue.ts";
3
3
  export * from "./indexedDbJournal.ts";
4
4
  export * from "./voiceSdkAudio.ts";
5
+ export * from "./managedBrowserAudio.ts";
5
6
  export * from "./meetingRecorder.ts";
6
7
  export * from "./meetingRecordingStore.ts";
8
+ export * from "./meetingIntelligence.ts";
@@ -2,5 +2,7 @@ export * from "./managedDialer.js";
2
2
  export * from "./dialingQueue.js";
3
3
  export * from "./indexedDbJournal.js";
4
4
  export * from "./voiceSdkAudio.js";
5
+ export * from "./managedBrowserAudio.js";
5
6
  export * from "./meetingRecorder.js";
6
7
  export * from "./meetingRecordingStore.js";
8
+ export * from "./meetingIntelligence.js";
@@ -1,4 +1,5 @@
1
1
  import type { DialerIntent, DialerJournal } from "./managedDialer.ts";
2
+ import type { DialingQueueJournal, DialingQueueState } from "./dialingQueue.ts";
2
3
  /** Origin-local recovery journal. Browser capabilities never enter this store.
3
4
  * Conflicting tabs cannot overwrite a different intent for the same scope. */
4
5
  export declare class IndexedDbDialerJournal implements DialerJournal {
@@ -9,3 +10,11 @@ export declare class IndexedDbDialerJournal implements DialerJournal {
9
10
  write(intent: DialerIntent): Promise<void>;
10
11
  clear(scope: string, key: string): Promise<void>;
11
12
  }
13
+ /** Queue progress lives separately from call capabilities. Revision checks stop
14
+ * stale tabs from replacing or advancing another tab's saved contact list. */
15
+ export declare class IndexedDbDialingQueueJournal implements DialingQueueJournal {
16
+ private readonly database;
17
+ constructor(name?: string);
18
+ read(scope: string): Promise<DialingQueueState | null>;
19
+ write(state: DialingQueueState, expectedRevision: number | null): Promise<void>;
20
+ }
@@ -34,7 +34,7 @@ export class IndexedDbDialerJournal {
34
34
  request.onsuccess = () => {
35
35
  const prior = request.result;
36
36
  if (prior && (prior.key !== next.key || JSON.stringify(prior.input) !== JSON.stringify(next.input) ||
37
- (prior.callId && prior.callId !== next.callId))) {
37
+ (prior.callId && prior.callId !== next.callId) || JSON.stringify(prior.queue) !== JSON.stringify(next.queue))) {
38
38
  fail("Another call is already saved in this workspace. Recover it before dialing.");
39
39
  return;
40
40
  }
@@ -50,11 +50,13 @@ export class IndexedDbDialerJournal {
50
50
  next.transfer = structuredClone(prior.transfer);
51
51
  else if (prior.transfer.key !== next.transfer.key || prior.transfer.to !== next.transfer.to || prior.transfer.mode !== next.transfer.mode ||
52
52
  prior.transfer.id && next.transfer.id && prior.transfer.id !== next.transfer.id ||
53
- prior.transfer.command && next.transfer.command && prior.transfer.command !== next.transfer.command) {
53
+ prior.transfer.command && next.transfer.command && prior.transfer.command !== next.transfer.command ||
54
+ prior.transfer.priorIds && next.transfer.priorIds && JSON.stringify(prior.transfer.priorIds) !== JSON.stringify(next.transfer.priorIds)) {
54
55
  fail("Another transfer is saved for this call. Recover the original transfer.");
55
56
  return;
56
57
  }
57
58
  else {
59
+ next.transfer.priorIds ??= prior.transfer.priorIds;
58
60
  next.transfer.id ??= prior.transfer.id;
59
61
  next.transfer.command ??= prior.transfer.command;
60
62
  }
@@ -79,3 +81,43 @@ export class IndexedDbDialerJournal {
79
81
  });
80
82
  }
81
83
  }
84
+ /** Queue progress lives separately from call capabilities. Revision checks stop
85
+ * stale tabs from replacing or advancing another tab's saved contact list. */
86
+ export class IndexedDbDialingQueueJournal {
87
+ database;
88
+ constructor(name = "pyai-dialing-queue") {
89
+ this.database = new Promise((resolve, reject) => {
90
+ const request = indexedDB.open(name, 1);
91
+ request.onupgradeneeded = () => { request.result.createObjectStore("queues", { keyPath: "scope" }); };
92
+ request.onsuccess = () => { request.result.onversionchange = () => request.result.close(); resolve(request.result); };
93
+ request.onerror = () => reject(new Error("Calling queue storage is unavailable."));
94
+ request.onblocked = () => reject(new Error("Close the older dialer tab to open queue storage."));
95
+ });
96
+ }
97
+ async read(scope) {
98
+ const db = await this.database;
99
+ return new Promise((resolve, reject) => {
100
+ const tx = db.transaction("queues", "readonly"), request = tx.objectStore("queues").get(scope);
101
+ tx.oncomplete = () => resolve(request.result ? structuredClone(request.result) : null);
102
+ tx.onerror = tx.onabort = () => reject(new Error("Calling queue storage is unavailable."));
103
+ });
104
+ }
105
+ async write(state, expectedRevision) {
106
+ const db = await this.database, next = structuredClone(state);
107
+ return new Promise((resolve, reject) => {
108
+ const tx = db.transaction("queues", "readwrite"), store = tx.objectStore("queues"), request = store.get(next.scope);
109
+ let conflict = false;
110
+ request.onsuccess = () => {
111
+ const prior = request.result;
112
+ if ((prior?.revision ?? null) !== expectedRevision || next.revision !== (expectedRevision ?? 0) + 1) {
113
+ conflict = true;
114
+ tx.abort();
115
+ return;
116
+ }
117
+ store.put(next);
118
+ };
119
+ tx.oncomplete = () => resolve();
120
+ tx.onerror = tx.onabort = () => reject(new Error(conflict ? "The saved queue changed in another tab. Reload before continuing." : "Calling queue progress could not be saved."));
121
+ });
122
+ }
123
+ }
@@ -0,0 +1,21 @@
1
+ import type { DialerAudio } from "./managedDialer.ts";
2
+ import type { TelephonyBrowserSession } from "../index.ts";
3
+ /** Issued by the application's server after PyAI has authorized one call.
4
+ * This contains no workspace key or reusable carrier credential. */
5
+ export type BrowserAudioCapability = Pick<TelephonyBrowserSession, "access_token" | "connect_params"> & {
6
+ transport?: "voice-sdk";
7
+ };
8
+ type AudioEvent = Parameters<DialerAudio["connect"]>[1];
9
+ export interface ManagedBrowserAudio {
10
+ connect(capability: BrowserAudioCapability, event: AudioEvent): Promise<void>;
11
+ disconnect(): void;
12
+ mute(value: boolean): void;
13
+ sendDigits(digits: string): void;
14
+ }
15
+ export interface ManagedBrowserAudioOptions {
16
+ /** Optional media adapter for embedded hosts. Ordinary applications omit it. */
17
+ loadTransport?: (transport: "voice-sdk") => Promise<DialerAudio>;
18
+ }
19
+ /** Provider-owned, lazy media setup. A cancelled import cannot place a late call. */
20
+ export declare function createManagedBrowserAudio(options?: ManagedBrowserAudioOptions): ManagedBrowserAudio;
21
+ export {};
@@ -0,0 +1,69 @@
1
+ import { VoiceSdkAudio } from "./voiceSdkAudio.js";
2
+ async function loadTransport() {
3
+ // The upstream transport is an implementation detail of this PyAI adapter.
4
+ // Applications must not import or construct the carrier's Device themselves.
5
+ const { Device } = await import("@twilio/voice-sdk");
6
+ return new VoiceSdkAudio(token => new Device(token));
7
+ }
8
+ /** Provider-owned, lazy media setup. A cancelled import cannot place a late call. */
9
+ export function createManagedBrowserAudio(options = {}) {
10
+ let generation = 0;
11
+ let audio = null;
12
+ const disconnect = () => {
13
+ generation++;
14
+ const prior = audio;
15
+ audio = null;
16
+ try {
17
+ prior?.disconnect();
18
+ }
19
+ catch { /* Remote call cleanup belongs to the server broker. */ }
20
+ };
21
+ return {
22
+ async connect(capability, event) {
23
+ const params = capability.connect_params;
24
+ if (!capability.access_token || capability.transport !== undefined && capability.transport !== "voice-sdk" ||
25
+ !params || Object.keys(params).length !== 1 || typeof params.session_id !== "string" ||
26
+ params.session_id.length < 1 || params.session_id.length > 200) {
27
+ throw new Error("A supported, single-call PyAI audio capability is required.");
28
+ }
29
+ // Capture before awaiting a lazy import; never retain a mutable caller object.
30
+ const session = { access_token: capability.access_token, connect_params: { session_id: params.session_id } };
31
+ disconnect();
32
+ const current = generation;
33
+ const candidate = await (options.loadTransport ?? loadTransport)("voice-sdk");
34
+ if (current !== generation) {
35
+ try {
36
+ candidate.disconnect();
37
+ }
38
+ catch { /* Not connected. */ }
39
+ return;
40
+ }
41
+ audio = candidate;
42
+ try {
43
+ // DialerAudio implementations consume this same opaque media capability.
44
+ await candidate.connect(session, state => {
45
+ if (current === generation)
46
+ event(state);
47
+ });
48
+ }
49
+ catch (error) {
50
+ if (current === generation)
51
+ disconnect();
52
+ throw error;
53
+ }
54
+ },
55
+ disconnect,
56
+ mute(value) {
57
+ if (!audio)
58
+ throw new Error("No active audio.");
59
+ audio.mute(value);
60
+ },
61
+ sendDigits(digits) {
62
+ if (!audio)
63
+ throw new Error("No active audio.");
64
+ if (!/^[0-9*#]{1,32}$/.test(digits))
65
+ throw new Error("Use one to 32 keypad digits.");
66
+ audio.sendDigits(digits);
67
+ },
68
+ };
69
+ }
@@ -20,10 +20,15 @@ export interface DialerIntent {
20
20
  input: TelephonyBrowserSessionCreate;
21
21
  callId?: string;
22
22
  stopping: boolean;
23
+ queue?: {
24
+ key: string;
25
+ contactIds: string[];
26
+ };
23
27
  transfer?: {
24
28
  key: string;
25
29
  to: string;
26
30
  mode: "warm" | "cold";
31
+ priorIds?: string[];
27
32
  id?: string;
28
33
  command?: "complete" | "cancel";
29
34
  };
@@ -58,6 +63,7 @@ export declare class ManagedDialer {
58
63
  private readonly listeners;
59
64
  private operation;
60
65
  private initialized;
66
+ private stopBeforeIntent;
61
67
  private readonly scope;
62
68
  private readonly broker;
63
69
  private readonly journal;
@@ -66,11 +72,18 @@ export declare class ManagedDialer {
66
72
  private readonly now;
67
73
  constructor(scope: string, broker: DialerBroker, journal: DialerJournal, audio: DialerAudio, newKey?: () => string, now?: () => number);
68
74
  get current(): DialerSnapshot;
75
+ get restored(): boolean;
76
+ get recoveryScope(): string;
77
+ /** Durable queue ownership only; never contains a browser capability. */
78
+ get queueContext(): {
79
+ key: string;
80
+ contactIds: string[];
81
+ } | null;
69
82
  subscribe(listener: (snapshot: DialerSnapshot) => void): () => void;
70
83
  private update;
71
84
  private exclusive;
72
85
  restore(): Promise<void>;
73
- start(input: TelephonyBrowserSessionCreate): Promise<void>;
86
+ start(input: TelephonyBrowserSessionCreate, queue?: DialerIntent["queue"]): Promise<void>;
74
87
  retrySetup(): Promise<void>;
75
88
  private setup;
76
89
  refresh(): Promise<void>;