@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
@@ -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.";
@@ -0,0 +1,21 @@
1
+ import { type MeetingIntelligenceBroker } from "./meetingIntelligence.ts";
2
+ import type { MeetingRecordingStore } from "./meetingRecorder.ts";
3
+ /** Optional companion to pyai-meeting-recorder. Bind the trusted current
4
+ * org/user scope and authenticated host broker; never pass a project API key. */
5
+ export declare class PyaiMeetingIntelligenceElement extends HTMLElement {
6
+ private root;
7
+ private scope;
8
+ private store;
9
+ private broker;
10
+ private generation;
11
+ private busy;
12
+ constructor();
13
+ bind(scope: string, store: MeetingRecordingStore, broker: MeetingIntelligenceBroker): void;
14
+ disconnectedCallback(): void;
15
+ private selected;
16
+ private clear;
17
+ private buttons;
18
+ private refreshRecordings;
19
+ private render;
20
+ private run;
21
+ }
@@ -0,0 +1,112 @@
1
+ import { MEETING_UPLOAD_NOTICE } from "./meetingIntelligence.js";
2
+ /** Optional companion to pyai-meeting-recorder. Bind the trusted current
3
+ * org/user scope and authenticated host broker; never pass a project API key. */
4
+ export class PyaiMeetingIntelligenceElement extends HTMLElement {
5
+ root;
6
+ scope = "";
7
+ store = null;
8
+ broker = null;
9
+ generation = 0;
10
+ busy = false;
11
+ constructor() {
12
+ super();
13
+ this.root = this.attachShadow({ mode: "open" });
14
+ this.root.innerHTML = `<style>:host{display:block;font:14px/1.5 system-ui;color:#202332;max-width:600px}section{border:1px solid #e7e8ef;border-radius:20px;padding:24px;background:white}label{display:block;margin:12px 0}select,button{font:inherit;padding:10px;border:1px solid #ddd;border-radius:10px;margin:4px}button:disabled{opacity:.5}pre{white-space:pre-wrap;font:inherit;overflow-wrap:anywhere}.notice{font-size:12px;color:#667085}h3{margin-top:0}[role=alert]{color:#b42338}</style><section><h3>Meeting transcript & notes</h3><p data-availability role="status"></p><select aria-label="Saved meeting" data-recording></select><button data-list>Refresh recordings</button><label class="notice"><input type="checkbox" data-notice> <span data-notice-text></span></label><button data-send disabled>Send for transcription</button><button data-refresh disabled>Refresh transcript & notes</button><button data-remove disabled>Remove meeting from app</button><p data-status role="status" aria-live="polite"></p><p role="alert" data-error></p><h4>Transcript</h4><pre data-transcript></pre><h4>Notes</h4><pre data-notes></pre><h4>Action items</h4><ul data-actions></ul></section>`;
15
+ this.root.querySelector("[data-notice-text]").textContent = MEETING_UPLOAD_NOTICE;
16
+ this.root.querySelector("[data-list]").addEventListener("click", () => void this.run(() => this.refreshRecordings()));
17
+ this.root.querySelector("[data-notice]").addEventListener("change", () => this.buttons());
18
+ this.root.querySelector("[data-recording]").addEventListener("change", () => { this.clear(); this.buttons(); });
19
+ this.root.querySelector("[data-send]").addEventListener("click", () => void this.run(async () => {
20
+ const id = this.selected(), scope = this.scope, store = this.store, broker = this.broker, generation = this.generation;
21
+ if (!this.root.querySelector("[data-notice]").checked)
22
+ throw new Error("Accept the upload and retention notice first.");
23
+ const recording = await store.get(scope, id);
24
+ if (!recording || recording.scope !== scope || recording.state !== "ready")
25
+ throw new Error("Stop the recording and review any interrupted capture before submitting it through your app.");
26
+ const audio = await store.audio(scope, id);
27
+ // A workspace change cannot submit the former workspace's audio.
28
+ if (generation !== this.generation)
29
+ return;
30
+ const result = await broker.submit(id, audio, true);
31
+ if (generation === this.generation)
32
+ this.render(result);
33
+ }));
34
+ for (const [selector, operation] of [["[data-refresh]", "get"], ["[data-remove]", "remove"]])
35
+ this.root.querySelector(selector).addEventListener("click", () => void this.run(async () => {
36
+ const generation = this.generation, result = await this.broker[operation](this.selected());
37
+ if (generation === this.generation)
38
+ this.render(result);
39
+ }));
40
+ }
41
+ bind(scope, store, broker) {
42
+ if (this.busy)
43
+ throw new Error("Wait for the current meeting action before switching workspaces.");
44
+ if (!scope.trim())
45
+ throw new Error("An authenticated workspace/user scope is required.");
46
+ ++this.generation;
47
+ this.scope = scope;
48
+ this.store = store;
49
+ this.broker = broker;
50
+ this.clear();
51
+ this.root.querySelector("[data-notice]").checked = false;
52
+ void this.run(() => this.refreshRecordings());
53
+ }
54
+ disconnectedCallback() { ++this.generation; }
55
+ selected() { const id = this.root.querySelector("[data-recording]").value; if (!id)
56
+ throw new Error("Choose a saved meeting."); return id; }
57
+ clear() { for (const selector of ["[data-status]", "[data-error]", "[data-transcript]", "[data-notes]", "[data-actions]"])
58
+ this.root.querySelector(selector).textContent = ""; }
59
+ buttons() {
60
+ const selected = !!this.root.querySelector("[data-recording]").value;
61
+ for (const selector of ["[data-send]", "[data-refresh]", "[data-remove]"])
62
+ this.root.querySelector(selector).disabled = this.busy || !this.broker || !selected || selector === "[data-send]" && !this.root.querySelector("[data-notice]").checked || selector === "[data-send]" && this.root.querySelector("[data-availability]").getAttribute("data-available") !== "true";
63
+ this.root.querySelector("[data-recording]").disabled = this.busy;
64
+ }
65
+ async refreshRecordings() {
66
+ if (!this.store || !this.broker)
67
+ return;
68
+ const generation = this.generation, [records, availability] = await Promise.all([this.store.list(this.scope), this.broker.availability()]);
69
+ if (generation !== this.generation)
70
+ return;
71
+ const status = this.root.querySelector("[data-availability]");
72
+ status.textContent = availability.reason ?? "Choose a saved recording, then explicitly send it for transcription.";
73
+ status.setAttribute("data-available", String(availability.available));
74
+ const select = this.root.querySelector("[data-recording]"), previous = select.value;
75
+ select.replaceChildren();
76
+ for (const recording of records.filter(recording => recording.state === "ready").slice(0, 40)) {
77
+ const option = document.createElement("option");
78
+ option.value = recording.id;
79
+ option.textContent = new Date(recording.createdAt).toLocaleString();
80
+ select.append(option);
81
+ }
82
+ if (Array.from(select.options).some(option => option.value === previous))
83
+ select.value = previous;
84
+ this.buttons();
85
+ }
86
+ render(view) {
87
+ this.root.querySelector("[data-status]").textContent = ({ submitting: "Sending recording…", transcribing: "Transcribing… Refresh to check progress.", summarizing: "Transcript ready. Preparing notes… Refresh to check progress.", complete: "Transcript and notes ready.", failed: "Meeting needs attention.", removed: "Cached notes removed. The browser recording remains saved; cloud retention still applies." })[view.state];
88
+ this.root.querySelector("[data-error]").textContent = view.error ?? "";
89
+ this.root.querySelector("[data-transcript]").textContent = view.transcript ?? "";
90
+ this.root.querySelector("[data-notes]").textContent = view.notes ?? "";
91
+ const list = this.root.querySelector("[data-actions]");
92
+ list.replaceChildren();
93
+ for (const action of view.actionItems) {
94
+ const item = document.createElement("li");
95
+ item.textContent = [action.task, action.owner, action.due].filter(Boolean).join(" · ");
96
+ list.append(item);
97
+ }
98
+ }
99
+ async run(action) { if (this.busy)
100
+ return; this.busy = true; this.buttons(); try {
101
+ await action();
102
+ }
103
+ catch (error) {
104
+ this.root.querySelector("[data-error]").textContent = error instanceof Error ? error.message : "Meeting action failed. Recover the same recording before sending another.";
105
+ }
106
+ finally {
107
+ this.busy = false;
108
+ this.buttons();
109
+ } }
110
+ }
111
+ if (!customElements.get("pyai-meeting-intelligence"))
112
+ customElements.define("pyai-meeting-intelligence", PyaiMeetingIntelligenceElement);
@@ -0,0 +1,60 @@
1
+ import type { MeResponse, PyAI, RecapCall, TranscriptionJob } from "../index.ts";
2
+ import type { MeetingIntelligenceBroker, MeetingIntelligenceView } from "./meetingIntelligence.ts";
3
+ export interface MeetingIntelligenceApi {
4
+ me(): Promise<MeResponse>;
5
+ recapEnabled(): Promise<boolean>;
6
+ upload(audio: Blob, filename: string, callId: string, key: string): Promise<TranscriptionJob>;
7
+ job(id: string): Promise<TranscriptionJob>;
8
+ recap(id: string): Promise<RecapCall | null>;
9
+ cancel(id: string): Promise<TranscriptionJob>;
10
+ }
11
+ export declare class MeetingApiError extends Error {
12
+ readonly status: number;
13
+ constructor(status: number);
14
+ }
15
+ /** Uses only public routes. Keyed multipart requires the durable job retry contract; no public bucket,
16
+ * arbitrary result_url fetch, or browser-held key is involved. */
17
+ export declare function createPyaiMeetingApi(options: {
18
+ apiKey: string;
19
+ baseURL?: string;
20
+ fetch?: typeof fetch;
21
+ timeoutMs?: number;
22
+ }): MeetingIntelligenceApi;
23
+ export interface MeetingIntelligenceEntry {
24
+ key: string;
25
+ recordingId: string;
26
+ owner: string;
27
+ digest: string;
28
+ mimeType: string;
29
+ bytes: number;
30
+ createdAt: number;
31
+ expiresAt: number;
32
+ jobId: string | null;
33
+ state: MeetingIntelligenceView["state"];
34
+ transcript: string | null;
35
+ notes: string | null;
36
+ actionItems: MeetingIntelligenceView["actionItems"];
37
+ error: string | null;
38
+ }
39
+ /** Host-owned persistent store. run must serialize across ALL host instances,
40
+ * including erase vs submit/get. Save must durably commit before resolving.
41
+ * Reuse the host's existing ownership journal/transaction facility. */
42
+ export interface MeetingIntelligenceJournal {
43
+ run<T>(key: string, action: () => Promise<T>): Promise<T>;
44
+ get(key: string): Promise<MeetingIntelligenceEntry | null>;
45
+ save(entry: MeetingIntelligenceEntry): Promise<void>;
46
+ }
47
+ export declare function createServerMeetingIntelligence(options: {
48
+ api: MeetingIntelligenceApi;
49
+ orgId: string;
50
+ projectId: string;
51
+ userId: string;
52
+ keyId: string;
53
+ journal: MeetingIntelligenceJournal;
54
+ now?: () => number;
55
+ maxBytes?: number;
56
+ retentionMs?: number;
57
+ }): MeetingIntelligenceBroker;
58
+ /** Reuses the host's already selected SDK instance and its normal transport.
59
+ * The SDK never exposes the key to the renderer. */
60
+ export declare function createSdkMeetingApi(sdk: PyAI): MeetingIntelligenceApi;
@@ -0,0 +1,207 @@
1
+ /** Server-only. Bind one broker to a trusted org/user and an existing project
2
+ * key. Never fall back to an operator/parent key or change that key's grants. */
3
+ import { createHash } from "node:crypto";
4
+ export class MeetingApiError extends Error {
5
+ status;
6
+ constructor(status) { super(`PyAI meeting request failed (${status}).`); this.status = status; }
7
+ }
8
+ /** Uses only public routes. Keyed multipart requires the durable job retry contract; no public bucket,
9
+ * arbitrary result_url fetch, or browser-held key is involved. */
10
+ export function createPyaiMeetingApi(options) {
11
+ const base = new URL(options.baseURL ?? "https://api.pyai.com");
12
+ if ((base.protocol !== "https:" && !(base.protocol === "http:" && ["127.0.0.1", "[::1]"].includes(base.hostname))) || base.username || base.password || base.search || base.hash || base.pathname !== "/")
13
+ throw new Error("Use a trusted HTTPS API origin.");
14
+ if (!options.apiKey || /[\r\n]/.test(options.apiKey))
15
+ throw new Error("An existing project key is required.");
16
+ const timeout = options.timeoutMs ?? 20000;
17
+ if (!Number.isInteger(timeout) || timeout < 1 || timeout > 60000)
18
+ throw new Error("Meeting requests require a deadline of 1–60000 ms.");
19
+ const request = async (path, method = "GET", input, key) => {
20
+ const response = await (options.fetch ?? fetch)(new URL(path, base), { method, redirect: "error", signal: AbortSignal.timeout(timeout),
21
+ headers: { Authorization: `Bearer ${options.apiKey}`, ...(input !== undefined && !(input instanceof FormData) ? { "content-type": "application/json" } : {}), ...(key ? { "Idempotency-Key": key } : {}) },
22
+ ...(input !== undefined ? { body: input instanceof FormData ? input : JSON.stringify(input) } : {}) });
23
+ if (!response.ok) {
24
+ await response.body?.cancel();
25
+ throw new MeetingApiError(response.status);
26
+ }
27
+ // Avoid unbounded or attacker-selected artifact downloads. Recap supplies
28
+ // retained transcript text even when Hear returns only a signed result URL.
29
+ const reader = response.body?.getReader();
30
+ if (!reader)
31
+ throw new Error("PyAI returned an empty response.");
32
+ const chunks = [];
33
+ let bytes = 0;
34
+ try {
35
+ while (true) {
36
+ const chunk = await reader.read();
37
+ if (chunk.done)
38
+ break;
39
+ bytes += chunk.value.length;
40
+ if (bytes > 4 * 1024 * 1024)
41
+ throw new Error("Meeting response exceeds 4 MiB.");
42
+ chunks.push(chunk.value);
43
+ }
44
+ }
45
+ finally {
46
+ await reader.cancel();
47
+ }
48
+ return JSON.parse(Buffer.concat(chunks).toString("utf8"));
49
+ };
50
+ return { me: () => request("/v1/me"), recapEnabled: async () => (await request("/v1/recap/config")).enabled === true,
51
+ upload: (audio, filename, callId, key) => { const form = new FormData(); form.set("call_id", callId); form.set("diarize", "true"); form.set("output_formats", "json"); form.set("audio", audio, filename); return request("/v1/transcription/jobs", "POST", form, key); },
52
+ job: id => request(`/v1/transcription/jobs/${encodeURIComponent(id)}`), cancel: id => request(`/v1/transcription/jobs/${encodeURIComponent(id)}`, "DELETE"),
53
+ recap: async (id) => { try {
54
+ return await request(`/v1/recap/calls/${encodeURIComponent(id)}`);
55
+ }
56
+ catch (error) {
57
+ if (error instanceof MeetingApiError && error.status === 404)
58
+ return null;
59
+ throw error;
60
+ } } };
61
+ }
62
+ const hash = (...values) => createHash("sha256").update(JSON.stringify(values)).digest("hex");
63
+ const view = (entry) => ({ recordingId: entry.recordingId, state: entry.state, transcript: entry.transcript, notes: entry.notes, actionItems: structuredClone(entry.actionItems), error: entry.error });
64
+ export function createServerMeetingIntelligence(options) {
65
+ const { api, journal } = options, now = options.now ?? Date.now;
66
+ const maxBytes = options.maxBytes ?? 128 * 1024 * 1024, retention = options.retentionMs ?? 24 * 3600000;
67
+ if (![options.orgId, options.projectId, options.userId, options.keyId].every(value => value.trim()) || !Number.isSafeInteger(maxBytes) || maxBytes < 1 || maxBytes > 256 * 1024 * 1024 || !Number.isSafeInteger(retention) || retention < 60000 || retention > 7 * 24 * 3600000)
68
+ throw new Error("Trusted identity and bounded private recording retention are required.");
69
+ const owner = hash(options.orgId, options.projectId, options.userId);
70
+ const identity = (id) => { if (!/^[A-Za-z0-9_-]{1,200}$/.test(id))
71
+ throw new Error("Invalid recording ID."); return "meeting_" + hash(owner, id); };
72
+ const owned = async (key) => { const entry = await journal.get(key); if (!entry || entry.owner !== owner || entry.key !== key)
73
+ throw new Error("No meeting in this workspace."); return entry; };
74
+ const availability = async () => {
75
+ const me = await api.me();
76
+ if (me.org_id !== options.orgId || me.project_id !== options.projectId || me.key_id !== options.keyId)
77
+ throw new Error("The selected PyAI project identity changed. Select the original project.");
78
+ const required = ["hear:transcribe", "transcribe:jobs", "recap:read", "recap:configure"];
79
+ const missing = required.filter(scope => !me.scopes?.includes(scope));
80
+ if (missing.length)
81
+ return { available: false, reason: `Select a project permitted to transcribe and summarize meetings. Missing scopes: ${missing.join(", ")}. Managed calling access alone does not include this feature.` };
82
+ if (!await api.recapEnabled())
83
+ return { available: false, reason: "Enable Recap through your workspace's normal settings before sending meeting audio." };
84
+ return { available: true, reason: null };
85
+ };
86
+ const requireAvailable = async () => { const result = await availability(); if (!result.available)
87
+ throw new Error(result.reason); };
88
+ const refresh = async (entry) => {
89
+ if (entry.state === "removed")
90
+ return view(entry);
91
+ if (now() >= entry.expiresAt) {
92
+ entry.state = "removed";
93
+ entry.transcript = null;
94
+ entry.notes = null;
95
+ entry.actionItems = [];
96
+ entry.error = "Private meeting retention expired. PyAI results and Recap follow workspace retention.";
97
+ await journal.save(entry);
98
+ if (entry.jobId)
99
+ await api.cancel(entry.jobId);
100
+ return view(entry);
101
+ }
102
+ if (!entry.jobId)
103
+ return view(entry);
104
+ const job = await api.job(entry.jobId);
105
+ if (job.job_id !== entry.jobId)
106
+ throw new Error("PyAI returned a different meeting job.");
107
+ if (["failed", "cancelled"].includes(job.status)) {
108
+ entry.state = "failed";
109
+ entry.error = "Transcription did not complete. Saved audio remains available locally; review the job before starting another submission.";
110
+ await journal.save(entry);
111
+ return view(entry);
112
+ }
113
+ if (job.status !== "completed") {
114
+ entry.state = "transcribing";
115
+ await journal.save(entry);
116
+ return view(entry);
117
+ }
118
+ const result = job.result;
119
+ if (typeof result?.text === "string")
120
+ entry.transcript = result.text;
121
+ entry.state = "summarizing";
122
+ await journal.save(entry);
123
+ const recap = await api.recap(entry.key);
124
+ if (recap && recap.call_id !== entry.key)
125
+ throw new Error("PyAI returned a different meeting summary.");
126
+ if (recap?.status === "failed") {
127
+ entry.state = "failed";
128
+ entry.error = "The transcript is ready but Recap failed. Review the existing summary job; audio is not submitted again.";
129
+ }
130
+ if (recap?.status === "complete") {
131
+ entry.transcript ??= recap.transcript?.utterances.map(item => item.text).join("\n") ?? null;
132
+ entry.notes = recap.record?.summary ?? recap.record?.tldr ?? null;
133
+ entry.actionItems = structuredClone(recap.record?.action_items ?? []);
134
+ entry.state = "complete";
135
+ entry.error = null;
136
+ }
137
+ await journal.save(entry);
138
+ return view(entry);
139
+ };
140
+ return { availability,
141
+ async submit(id, audio, noticeAccepted) {
142
+ if (noticeAccepted !== true)
143
+ throw new Error("Accept the upload and retention notice before sending audio.");
144
+ if (!audio.size || audio.size > maxBytes || !/^audio\/(webm|mp4|wav|x-wav|mpeg|ogg)(?:;|$)/i.test(audio.type))
145
+ throw new Error("Choose a supported saved audio recording within the workspace size limit.");
146
+ const key = identity(id);
147
+ await requireAvailable();
148
+ const digest = createHash("sha256").update(new Uint8Array(await audio.arrayBuffer())).digest("hex");
149
+ return journal.run(key, async () => {
150
+ let entry = await journal.get(key);
151
+ if (entry && (entry.owner !== owner || entry.digest !== digest || entry.mimeType !== audio.type || entry.bytes !== audio.size))
152
+ throw new Error("This recording ID already belongs to different audio. Recover the original submission.");
153
+ if (entry?.state === "removed")
154
+ throw new Error("This meeting was removed. It cannot be resubmitted with the same ID.");
155
+ if (!entry) {
156
+ entry = { key, recordingId: id, owner, digest, mimeType: audio.type, bytes: audio.size, createdAt: now(), expiresAt: now() + retention, jobId: null, state: "submitting", transcript: null, notes: null, actionItems: [], error: null };
157
+ await journal.save(entry);
158
+ }
159
+ if (now() >= entry.expiresAt || entry.jobId)
160
+ return refresh(entry);
161
+ // Persist the same content identity before POST. A lost response is
162
+ // recovered with the SAME durable JSON/multipart job retry key.
163
+ const extension = { "audio/webm": "webm", "audio/mp4": "m4a", "audio/wav": "wav", "audio/x-wav": "wav", "audio/mpeg": "mp3", "audio/ogg": "ogg" }[audio.type.split(";")[0].toLowerCase()];
164
+ const job = await api.upload(audio, `meeting.${extension}`, key, key);
165
+ entry.jobId = job.job_id;
166
+ entry.state = "transcribing";
167
+ await journal.save(entry);
168
+ return refresh(entry);
169
+ });
170
+ },
171
+ async get(id) { const key = identity(id); await requireAvailable(); return journal.run(key, async () => refresh(await owned(key))); },
172
+ async remove(id) {
173
+ const key = identity(id);
174
+ return journal.run(key, async () => {
175
+ const entry = await owned(key);
176
+ entry.state = "removed";
177
+ entry.transcript = null;
178
+ entry.notes = null;
179
+ entry.actionItems = [];
180
+ entry.error = "Cached notes removed. PyAI uploaded audio may remain for up to 7 days and results up to 30 days; Recap follows workspace retention. Cancellation is not erasure.";
181
+ await journal.save(entry);
182
+ // Erase never submits or replays audio. If the initial POST outcome was
183
+ // unknown we cannot invent its job ID or claim it was cancelled.
184
+ if (!entry.jobId)
185
+ entry.error = "Cached notes removed. The earlier submission outcome is unknown; a PyAI job may remain under workspace retention. Uploaded audio may remain for up to 7 days and results up to 30 days.";
186
+ await journal.save(entry);
187
+ if (entry.jobId)
188
+ await api.cancel(entry.jobId);
189
+ return view(entry);
190
+ });
191
+ }, };
192
+ }
193
+ /** Reuses the host's already selected SDK instance and its normal transport.
194
+ * The SDK never exposes the key to the renderer. */
195
+ export function createSdkMeetingApi(sdk) {
196
+ return { me: () => sdk.me(), recapEnabled: async () => (await sdk.recap.config.get()).enabled === true,
197
+ upload: (audio, filename, callId, key) => sdk.transcriptionJobs.upload({ file: audio, filename, call_id: callId, diarize: true, output_formats: ["json"] }, { idempotencyKey: key }),
198
+ job: id => sdk.transcriptionJobs.get(id), cancel: id => sdk.transcriptionJobs.cancel(id),
199
+ recap: async (id) => { try {
200
+ return await sdk.recap.calls.get(id);
201
+ }
202
+ catch (error) {
203
+ if (error.status === 404)
204
+ return null;
205
+ throw error;
206
+ } } };
207
+ }
package/dist/index.d.ts CHANGED
@@ -819,6 +819,7 @@ export declare class OmniConnection {
819
819
  }
820
820
  /** Shape of `GET /v1/me`. Fields are best-effort / forward-compatible. */
821
821
  export interface MeResponse {
822
+ project_id?: string;
822
823
  object?: string;
823
824
  key_id?: string;
824
825
  org_id?: string;
@@ -1457,6 +1458,19 @@ export declare class PyAI {
1457
1458
  create: (params: CreateJobParams, opts?: {
1458
1459
  idempotencyKey?: string;
1459
1460
  }) => Promise<TranscriptionJob>;
1461
+ /** Upload a recording with a durable retry key. Requires the current
1462
+ * keyed multipart job contract; never change the key after an unknown ACK. */
1463
+ upload: (params: {
1464
+ file: Blob;
1465
+ filename: string;
1466
+ call_id?: string;
1467
+ diarize?: boolean;
1468
+ output_formats?: Array<"json" | "srt" | "vtt">;
1469
+ }, opts: {
1470
+ idempotencyKey: string;
1471
+ }) => Promise<TranscriptionJob>;
1472
+ /** Cancels queued/running work; existing cloud retention still applies. */
1473
+ cancel: (jobId: string) => Promise<TranscriptionJob>;
1460
1474
  get: (jobId: string) => Promise<TranscriptionJob>;
1461
1475
  list: (params?: {
1462
1476
  limit?: number;
package/dist/index.js CHANGED
@@ -1113,6 +1113,24 @@ export class PyAI {
1113
1113
  });
1114
1114
  return (await res.json());
1115
1115
  },
1116
+ /** Upload a recording with a durable retry key. Requires the current
1117
+ * keyed multipart job contract; never change the key after an unknown ACK. */
1118
+ upload: async (params, opts) => {
1119
+ if (!opts.idempotencyKey || opts.idempotencyKey.length > 255 || /[\r\n]/.test(opts.idempotencyKey))
1120
+ throw new Error("A valid recording retry key is required.");
1121
+ const form = new FormData();
1122
+ if (params.call_id)
1123
+ form.set("call_id", params.call_id);
1124
+ if (params.diarize !== undefined)
1125
+ form.set("diarize", String(params.diarize));
1126
+ if (params.output_formats)
1127
+ form.set("output_formats", params.output_formats.join(","));
1128
+ form.set("audio", params.file, params.filename);
1129
+ const response = await this.request("/v1/transcription/jobs", { method: "POST", headers: this.authHeaders({ "Idempotency-Key": opts.idempotencyKey }), body: form });
1130
+ return await response.json();
1131
+ },
1132
+ /** Cancels queued/running work; existing cloud retention still applies. */
1133
+ cancel: async (jobId) => { const response = await this.request(`/v1/transcription/jobs/${encodeURIComponent(jobId)}`, { method: "DELETE", headers: this.authHeaders() }); return await response.json(); },
1116
1134
  get: (jobId) => this.getJson(`/v1/transcription/jobs/${encodeURIComponent(jobId)}`),
1117
1135
  list: (params = {}) => {
1118
1136
  const q = new URLSearchParams();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pyai/sdk",
3
- "version": "0.13.0",
3
+ "version": "0.15.0",
4
4
  "description": "Official TypeScript/JavaScript SDK for PyAI, speech-to-text (Hear), text-to-speech (Speak), realtime voice agents (Omni), and call compliance (Trace).",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -29,6 +29,14 @@
29
29
  "./dialer/app": {
30
30
  "types": "./dist/dialer/appServer.d.ts",
31
31
  "import": "./dist/dialer/appServer.js"
32
+ },
33
+ "./dialer/meeting-intelligence": {
34
+ "types": "./dist/dialer/meetingIntelligenceElement.d.ts",
35
+ "import": "./dist/dialer/meetingIntelligenceElement.js"
36
+ },
37
+ "./dialer/meeting-server": {
38
+ "types": "./dist/dialer/serverMeetingIntelligence.d.ts",
39
+ "import": "./dist/dialer/serverMeetingIntelligence.js"
32
40
  }
33
41
  },
34
42
  "bin": {