@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.
Files changed (41) hide show
  1. package/README.md +34 -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 +1 -0
  13. package/dist/dialer/index.js +1 -0
  14. package/dist/dialer/indexedDbJournal.d.ts +9 -0
  15. package/dist/dialer/indexedDbJournal.js +44 -2
  16. package/dist/dialer/managedDialer.d.ts +14 -1
  17. package/dist/dialer/managedDialer.js +25 -7
  18. package/dist/dialer/meetingIntelligence.d.ts +28 -0
  19. package/dist/dialer/meetingIntelligence.js +3 -0
  20. package/dist/dialer/meetingIntelligenceElement.d.ts +21 -0
  21. package/dist/dialer/meetingIntelligenceElement.js +112 -0
  22. package/dist/dialer/serverMeetingIntelligence.d.ts +60 -0
  23. package/dist/dialer/serverMeetingIntelligence.js +207 -0
  24. package/dist/index.d.ts +14 -0
  25. package/dist/index.js +18 -0
  26. package/package.json +9 -1
  27. package/src/cli-omni-template.ts +2 -2
  28. package/src/cli-web-auth.ts +3 -0
  29. package/src/dialer/MEETING_INTELLIGENCE.md +76 -0
  30. package/src/dialer/app/app.html +2 -2
  31. package/src/dialer/app/app.js +39 -12
  32. package/src/dialer/appServer.ts +45 -3
  33. package/src/dialer/dialingQueue.ts +107 -46
  34. package/src/dialer/fileMeetingIntelligenceJournal.ts +77 -0
  35. package/src/dialer/index.ts +2 -0
  36. package/src/dialer/indexedDbJournal.ts +44 -2
  37. package/src/dialer/managedDialer.ts +21 -7
  38. package/src/dialer/meetingIntelligence.ts +21 -0
  39. package/src/dialer/meetingIntelligenceElement.ts +65 -0
  40. package/src/dialer/serverMeetingIntelligence.ts +148 -0
  41. 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
+ }
@@ -4,3 +4,4 @@ export * from "./indexedDbJournal.ts";
4
4
  export * from "./voiceSdkAudio.ts";
5
5
  export * from "./meetingRecorder.ts";
6
6
  export * from "./meetingRecordingStore.ts";
7
+ export * from "./meetingIntelligence.ts";
@@ -4,3 +4,4 @@ export * from "./indexedDbJournal.js";
4
4
  export * from "./voiceSdkAudio.js";
5
5
  export * from "./meetingRecorder.js";
6
6
  export * from "./meetingRecordingStore.js";
7
+ 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
+ }
@@ -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>;
@@ -9,6 +9,7 @@ export class ManagedDialer {
9
9
  listeners = new Set();
10
10
  operation = null;
11
11
  initialized = false;
12
+ stopBeforeIntent = false;
12
13
  scope;
13
14
  broker;
14
15
  journal;
@@ -26,6 +27,10 @@ export class ManagedDialer {
26
27
  this.now = now;
27
28
  }
28
29
  get current() { return structuredClone(this.snapshot); }
30
+ get restored() { return this.initialized; }
31
+ get recoveryScope() { return this.scope; }
32
+ /** Durable queue ownership only; never contains a browser capability. */
33
+ get queueContext() { return this.intent?.queue ? structuredClone(this.intent.queue) : null; }
29
34
  subscribe(listener) {
30
35
  this.listeners.add(listener);
31
36
  listener(this.current);
@@ -70,7 +75,7 @@ export class ManagedDialer {
70
75
  }
71
76
  });
72
77
  }
73
- async start(input) {
78
+ async start(input, queue) {
74
79
  if (!this.initialized)
75
80
  throw new Error("Restore the calling journal before dialing.");
76
81
  if (this.intent)
@@ -80,10 +85,15 @@ export class ManagedDialer {
80
85
  new Set(destinations).size !== destinations.length || destinations.some(to => typeof to !== "string" || !/^\+[1-9]\d{6,14}$/.test(to)))
81
86
  throw new Error("Choose one destination or two to four distinct parallel destinations with country codes.");
82
87
  return this.exclusive(async () => {
83
- const intent = { scope: this.scope, key: this.newKey(), input: structuredClone(input), stopping: false };
88
+ this.stopBeforeIntent = false;
89
+ const intent = { scope: this.scope, key: this.newKey(), input: structuredClone(input), stopping: false, ...(queue ? { queue: structuredClone(queue) } : {}) };
84
90
  // Persist before the first network request. A storage failure cannot dial.
85
91
  await this.journal.write(structuredClone(intent));
86
92
  this.intent = intent;
93
+ if (this.stopBeforeIntent) {
94
+ intent.stopping = true;
95
+ await this.journal.write(structuredClone(intent));
96
+ }
87
97
  await this.setup();
88
98
  });
89
99
  }
@@ -164,7 +174,7 @@ export class ManagedDialer {
164
174
  return;
165
175
  const transfer = this.intent.transfer;
166
176
  if (transfer) {
167
- const observed = call.transfers?.find(item => transfer.id ? item.id === transfer.id : item.to === transfer.to && item.mode === transfer.mode);
177
+ const observed = call.transfers?.slice().reverse().find(item => transfer.id ? item.id === transfer.id : !transfer.priorIds?.includes(item.id) && item.to === transfer.to && item.mode === transfer.mode);
168
178
  if (observed && observed.to === transfer.to && observed.mode === transfer.mode) {
169
179
  const next = structuredClone(this.intent);
170
180
  if (["canceled", "failed"].includes(observed.status)) {
@@ -190,8 +200,16 @@ export class ManagedDialer {
190
200
  this.update({ call });
191
201
  }
192
202
  async stop() {
193
- if (!this.intent)
194
- return;
203
+ // The first durable write may still be pending, before intent is installed.
204
+ // Preserve a close/stop request so setup cannot open late browser audio.
205
+ if (!this.intent) {
206
+ if (!this.operation)
207
+ return;
208
+ this.stopBeforeIntent = true;
209
+ await this.operation;
210
+ if (!this.intent)
211
+ return;
212
+ }
195
213
  if (this.snapshot.call && dialerCallHandedOff(this.snapshot.call))
196
214
  throw new Error("The transferred conversation continues independently. Check its status instead of ending the caller's conversation.");
197
215
  // Mark immediately so a late create acknowledgment cannot connect audio.
@@ -251,7 +269,7 @@ export class ManagedDialer {
251
269
  if (this.intent.transfer || this.snapshot.call.transfers?.some(item => !["completed", "canceled", "failed"].includes(item.status)))
252
270
  throw new Error("Recover or finish the current transfer before starting another.");
253
271
  const next = structuredClone(this.intent);
254
- next.transfer = { key: this.newKey(), to, mode };
272
+ next.transfer = { key: this.newKey(), to, mode, priorIds: this.snapshot.call.transfers?.map(item => item.id) ?? [] };
255
273
  await this.journal.write(next);
256
274
  this.intent = next;
257
275
  await this.transferKnown();
@@ -302,7 +320,7 @@ export class ManagedDialer {
302
320
  if (call.id !== intent.callId)
303
321
  throw new Error("Transfer call identity changed.");
304
322
  const observed = transfer.id ? call.transfers?.find(item => item.id === transfer.id)
305
- : call.transfers?.slice().reverse().find(item => item.to === transfer.to && item.mode === transfer.mode);
323
+ : call.transfers?.slice().reverse().find(item => !transfer.priorIds?.includes(item.id) && item.to === transfer.to && item.mode === transfer.mode);
306
324
  if (!observed || observed.to !== transfer.to || observed.mode !== transfer.mode)
307
325
  throw new Error("Transfer identity is unavailable.");
308
326
  transfer.id = observed.id;
@@ -0,0 +1,28 @@
1
+ /** Browser-safe meeting intelligence contract. All methods belong to the
2
+ * authenticated host; project credentials and private audio URLs stay there. */
3
+ export declare const MEETING_UPLOAD_NOTICE = "Send this recording to PyAI Hear and Recap for a transcript, notes and action items. Uploaded audio may remain for up to 7 days and job results for up to 30 days; Recap follows your workspace retention policy. Removing the meeting from this app clears cached notes and requests cancellation, not cloud erasure. The browser recording remains saved. Continue only after informing everyone and accepting this policy.";
4
+ export interface MeetingIntelligenceView {
5
+ recordingId: string;
6
+ state: "submitting" | "transcribing" | "summarizing" | "complete" | "failed" | "removed";
7
+ transcript: string | null;
8
+ notes: string | null;
9
+ actionItems: Array<{
10
+ task: string;
11
+ owner?: string | null;
12
+ due?: string | null;
13
+ }>;
14
+ error: string | null;
15
+ }
16
+ export interface MeetingIntelligenceAvailability {
17
+ available: boolean;
18
+ reason: string | null;
19
+ }
20
+ export interface MeetingIntelligenceBroker {
21
+ availability(): Promise<MeetingIntelligenceAvailability>;
22
+ /** Must be a foreground action with the upload/retention notice accepted. */
23
+ submit(recordingId: string, audio: Blob, noticeAccepted: boolean): Promise<MeetingIntelligenceView>;
24
+ get(recordingId: string): Promise<MeetingIntelligenceView>;
25
+ /** Clears cached notes, cancels known unfinished Hear work, and keeps an
26
+ * opaque tombstone. Public job cancellation does not erase cloud artifacts. */
27
+ remove(recordingId: string): Promise<MeetingIntelligenceView>;
28
+ }
@@ -0,0 +1,3 @@
1
+ /** Browser-safe meeting intelligence contract. All methods belong to the
2
+ * authenticated host; project credentials and private audio URLs stay there. */
3
+ export const MEETING_UPLOAD_NOTICE = "Send this recording to PyAI Hear and Recap for a transcript, notes and action items. Uploaded audio may remain for up to 7 days and job results for up to 30 days; Recap follows your workspace retention policy. Removing the meeting from this app clears cached notes and requests cancellation, not cloud erasure. The browser recording remains saved. Continue only after informing everyone and accepting this policy.";