@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
@@ -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.14.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": {
@@ -1,7 +1,7 @@
1
1
  // Generated by scripts/generate-omni-starter.mjs; edit examples/omni-starter instead.
2
2
  export const omniTemplate = Object.freeze({
3
- "README.md": "# Runnable Omni starter\n\nRequires Node 20.19+ and ESM. Node 20 uses the included `ws` transport;\nNode 22 also works. The separate MCP server requires Node 22+.\nThis server-side example uses a synthetic read-only office-hours tool. Read\n`PYAI.md` when generating the project through the CLI.\n\n<!-- omni-install:start -->\n```sh\nnpm install @pyai/sdk@0.13.0\nnpx pyai init voice-demo --template omni\ncd voice-demo\nnpm install\n```\n\nInitialization is offline; installing dependencies and running `main.mjs` are\nseparate steps. For an existing checkout of this example, run `npm install`\nin its directory instead.\n<!-- omni-install:end -->\n\nInject `PYAI_API_KEY` through your secret manager or shell environment. Do not\npaste a real key into source, a prompt, or shell history. `.env.example` documents\nthe variable; this program does not load `.env` or saved CLI profiles.\n\nPrepare a 24 kHz PCM16 mono WAV, at most 20 seconds, saying “Please look up the\noffice opening time.” Then run:\n\n```sh\nnode main.mjs caller.wav\n```\n\nRunning the program explicitly opens one bounded Omni session and uploads its\ncaptured reply to Hear. Both consume your key's allowed usage. Automatic retries\nare disabled. No managed number is bought and no phone call is placed.\n\n`session.mjs` waits for configuration and the greeting to drain, sends exactly\none paced input stream (caller PCM or silence), returns the read tool's result,\nand captures output using the rate from `hello.audio_out`. Never run a separate\nsilence timer alongside caller audio. `timing.mjs` is generated from the existing\nOmni evaluation harness's timing utilities.\n\nThe new private `omni-run-*` folder contains `session.wav`, `reply.wav`, and\n`report.json`. The report separates received audio, an office-hours answer\nrecovered by Hear from captured audio, and physical playback (not tested).\nThe office-hours check accepts formatting such as `opens@9a.m`, `9 a.m.` and\n`nine in the morning` in a complete affirmative opening-time sentence. Wrong\ntimes, negation, conflicting or truncated text remain unverified. This is a\nconservative check for the example fact, not a general answer-quality score.\nA synthesis transcript is advisory; it is not evidence that speech arrived.\nThis starter does not negotiate playback receipts. Capture ends after the\nsimulated queue drains and two seconds of quiet, a bounded capture heuristic.\nListen to the saved file when qualifying actual sound quality or completeness.\n\nTo exercise interruption, supply a second WAV saying “Stop speaking now”:\n\n```sh\nnode main.mjs caller.wav interruption.wav\n```\n\nThe second clip starts while reply audio is queued. `onBargeIn` clears that\nsimulated queue, and capture observes at least five seconds after that clip ends.\nAn interrupted answer can correctly fail the full-answer check;\ninspect the separate interruption evidence. This is not a physical speaker test.\nFor a real playback adapter, cancel both queued and currently playing audio.\nReplace the example lookup with authorized application data before product use.\n\nOn a session error, the program exits with JSON containing a recognized machine\n`code` (for example `media_dead` or `invalid_configure`). Unknown server codes\nbecome `unrecognized_server_error`; transport or decoding errors without a\nrecognized transport code become `transport_or_protocol_error`. Raw error text,\ncall IDs and unknown code values are omitted. No automatic retry is attempted;\ninspect the code and your authorized diagnostics before deciding to retry.\n",
4
- "package.json": "{\n \"name\": \"pyai-omni-starter\",\n \"version\": \"0.0.0\",\n \"private\": true,\n \"type\": \"module\",\n \"engines\": {\n \"node\": \">=20.19.0\"\n },\n \"scripts\": {\n \"start\": \"node main.mjs\"\n },\n \"dependencies\": {\n \"@pyai/sdk\": \"0.13.0\",\n \"ws\": \"^8.18.3\"\n }\n}\n",
3
+ "README.md": "# Runnable Omni starter\n\nRequires Node 20.19+ and ESM. Node 20 uses the included `ws` transport;\nNode 22 also works. The separate MCP server requires Node 22+.\nThis server-side example uses a synthetic read-only office-hours tool. Read\n`PYAI.md` when generating the project through the CLI.\n\n<!-- omni-install:start -->\n```sh\nnpm install @pyai/sdk@0.14.0\nnpx pyai init voice-demo --template omni\ncd voice-demo\nnpm install\n```\n\nInitialization is offline; installing dependencies and running `main.mjs` are\nseparate steps. For an existing checkout of this example, run `npm install`\nin its directory instead.\n<!-- omni-install:end -->\n\nInject `PYAI_API_KEY` through your secret manager or shell environment. Do not\npaste a real key into source, a prompt, or shell history. `.env.example` documents\nthe variable; this program does not load `.env` or saved CLI profiles.\n\nPrepare a 24 kHz PCM16 mono WAV, at most 20 seconds, saying “Please look up the\noffice opening time.” Then run:\n\n```sh\nnode main.mjs caller.wav\n```\n\nRunning the program explicitly opens one bounded Omni session and uploads its\ncaptured reply to Hear. Both consume your key's allowed usage. Automatic retries\nare disabled. No managed number is bought and no phone call is placed.\n\n`session.mjs` waits for configuration and the greeting to drain, sends exactly\none paced input stream (caller PCM or silence), returns the read tool's result,\nand captures output using the rate from `hello.audio_out`. Never run a separate\nsilence timer alongside caller audio. `timing.mjs` is generated from the existing\nOmni evaluation harness's timing utilities.\n\nThe new private `omni-run-*` folder contains `session.wav`, `reply.wav`, and\n`report.json`. The report separates received audio, an office-hours answer\nrecovered by Hear from captured audio, and physical playback (not tested).\nThe office-hours check accepts formatting such as `opens@9a.m`, `9 a.m.` and\n`nine in the morning` in a complete affirmative opening-time sentence. Wrong\ntimes, negation, conflicting or truncated text remain unverified. This is a\nconservative check for the example fact, not a general answer-quality score.\nA synthesis transcript is advisory; it is not evidence that speech arrived.\nThis starter does not negotiate playback receipts. Capture ends after the\nsimulated queue drains and two seconds of quiet, a bounded capture heuristic.\nListen to the saved file when qualifying actual sound quality or completeness.\n\nTo exercise interruption, supply a second WAV saying “Stop speaking now”:\n\n```sh\nnode main.mjs caller.wav interruption.wav\n```\n\nThe second clip starts while reply audio is queued. `onBargeIn` clears that\nsimulated queue, and capture observes at least five seconds after that clip ends.\nAn interrupted answer can correctly fail the full-answer check;\ninspect the separate interruption evidence. This is not a physical speaker test.\nFor a real playback adapter, cancel both queued and currently playing audio.\nReplace the example lookup with authorized application data before product use.\n\nOn a session error, the program exits with JSON containing a recognized machine\n`code` (for example `media_dead` or `invalid_configure`). Unknown server codes\nbecome `unrecognized_server_error`; transport or decoding errors without a\nrecognized transport code become `transport_or_protocol_error`. Raw error text,\ncall IDs and unknown code values are omitted. No automatic retry is attempted;\ninspect the code and your authorized diagnostics before deciding to retry.\n",
4
+ "package.json": "{\n \"name\": \"pyai-omni-starter\",\n \"version\": \"0.0.0\",\n \"private\": true,\n \"type\": \"module\",\n \"engines\": {\n \"node\": \">=20.19.0\"\n },\n \"scripts\": {\n \"start\": \"node main.mjs\"\n },\n \"dependencies\": {\n \"@pyai/sdk\": \"0.14.0\",\n \"ws\": \"^8.18.3\"\n }\n}\n",
5
5
  "timing.mjs": "// Monotonic capture timing. Arrival time is distinct from queued playback:\n// a single packet may contain seconds of audio and must finish before settling.\nexport const FRAME_MS = 20;\nexport const REALTIME_GAP_LIMIT_MS = 100;\n// Interruption tests need an observation window after caller transmission,\n// even when an earlier cue/response already finished. These are test bounds,\n// not an inferred engine reply-end or a naturalness threshold.\nexport const INTERRUPTION_OBSERVATION = Object.freeze({\n minimumAfterCallerStreamMs: 5000, quietMs: 2000, maximumAfterCallerStreamMs: 25000,\n});\n\n/** Approximate audible bounds; this is energy detection, not a speech/VAD claim. */\nexport function audibleBounds(pcm, rate, rmsFloor = 160) {\n const window = Math.max(1, Math.round(rate / 100)); // 10 ms windows\n let first = null;\n let last = null;\n for (let off = 0; off < pcm.length; off += window) {\n const end = Math.min(pcm.length, off + window);\n let energy = 0;\n for (let i = off; i < end; i++) energy += pcm[i] * pcm[i];\n if (Math.sqrt(energy / (end - off)) >= rmsFloor) {\n first ??= off;\n last = end;\n }\n }\n return { first, last };\n}\n\nexport function newAudioCapture(started) {\n return {\n started, firstPacketAt: null, lastPacketAt: null,\n firstAudioAt: null, lastAudioAt: null, playbackEndAt: null,\n samples: 0, pcm: [], turnBeginAt: null, eouMs: null,\n latestTurnBeginAt: null, postTurnBeginFirstPacketAt: null,\n postTurnBeginFirstAudioAt: null, lastAssistantTranscriptAt: null, lastCallerTranscriptAt: null,\n callerTranscriptEvents: [], assistantTranscriptEvents: [],\n turnBegins: [], unheardCancellations: [], unheardSupersededTurns: [], tools: [], toolResults: [], kb: null, events: [],\n };\n}\n\nexport function recordTurnBegin(ctx, at, turn, origin = 0) {\n const prior = ctx.turnBegins.at(-1);\n const cancellation = ctx.unheardCancellations.at(-1);\n if (prior && cancellation && !cancellation.admitted\n && cancellation.turn === prior.turn && cancellation.turnBeginIndex === ctx.turnBegins.length - 1\n && Number.isSafeInteger(turn) && turn > prior.turn && at > cancellation.at\n && ctx.samples === 0 && ctx.assistantTranscriptEvents.length === 0\n && ctx.tools.length === 0 && ctx.toolResults.length === 0) {\n cancellation.admitted = true;\n ctx.unheardSupersededTurns.push({ turn: prior.turn, beginAtMs: prior.atMs,\n cancelledAtMs: cancellation.atMs, cancellationEventIndex: cancellation.eventIndex,\n replacementTurn: turn, outputPacketsBeforeReplacement: 0 });\n }\n ctx.turnBeginAt ??= at;\n ctx.latestTurnBeginAt = at;\n // Earlier PCM can be a listening cue. A new reply is still pending even\n // when that cue has already finished playing; retain all of its PCM.\n ctx.postTurnBeginFirstPacketAt = null;\n ctx.postTurnBeginFirstAudioAt = null;\n ctx.turnBegins.push({ atMs: Math.round(at - origin), turn: turn ?? null });\n}\n\nexport function recordUnheardCancellation(ctx, event, at, origin, eventIndex) {\n const prior = ctx.turnBegins.at(-1);\n if (event.event !== \"flush\" || event.reason !== \"turn_merge\"\n || !Number.isSafeInteger(event.cancelled_turn) || event.cancelled_turn <= 0\n || prior?.turn !== event.cancelled_turn || at < ctx.latestTurnBeginAt\n || ctx.samples !== 0 || ctx.assistantTranscriptEvents.length\n || ctx.tools.length || ctx.toolResults.length\n || ctx.unheardCancellations.some(c => c.turnBeginIndex === ctx.turnBegins.length - 1)) return;\n ctx.unheardCancellations.push({ turn: event.cancelled_turn, at,\n atMs: Math.round(at - origin), eventIndex, turnBeginIndex: ctx.turnBegins.length - 1,\n admitted: false });\n}\n\nexport function recordAudio(ctx, pcm, at, rate) {\n if (!(pcm instanceof Int16Array) || !pcm.length) return null;\n const copy = pcm.slice(); // Some transports reuse callback buffers.\n const playbackAt = Math.max(at, ctx.playbackEndAt ?? at);\n const endAt = playbackAt + (copy.length / rate) * 1000;\n const bounds = audibleBounds(copy, rate);\n ctx.firstPacketAt ??= at;\n ctx.lastPacketAt = at;\n ctx.playbackEndAt = endAt;\n const afterTurnBegin = ctx.latestTurnBeginAt != null && at >= ctx.latestTurnBeginAt;\n if (afterTurnBegin) ctx.postTurnBeginFirstPacketAt ??= at;\n if (bounds.first != null) {\n ctx.firstAudioAt ??= playbackAt + (bounds.first / rate) * 1000;\n ctx.lastAudioAt = playbackAt + (bounds.last / rate) * 1000;\n if (afterTurnBegin) ctx.postTurnBeginFirstAudioAt ??= playbackAt + (bounds.first / rate) * 1000;\n }\n ctx.samples += copy.length;\n ctx.pcm.push(copy);\n return { playbackAt, endAt, pcm: copy };\n}\n\n/** Preserve negative gaps: they are overlaps, never missing measurements. */\nexport function captureTiming(ctx, caller, origin = 0) {\n const relative = (at) => at == null ? null : Math.round(at - origin);\n const gap = (at) => at == null || caller.speechOffsetAt == null\n ? null : Math.round(at - caller.speechOffsetAt);\n return {\n ttfbMs: gap(ctx.firstAudioAt),\n anyAudioTtfbMs: gap(ctx.firstAudioAt),\n postTurnBeginTtfbMs: gap(ctx.postTurnBeginFirstAudioAt),\n turnMs: gap(ctx.lastAudioAt),\n packetTtfbMs: gap(ctx.firstPacketAt),\n callerStartMs: relative(caller.startedAt),\n callerSpeechOnsetMs: relative(caller.speechOnsetAt),\n callerSpeechOffsetMs: relative(caller.speechOffsetAt),\n callerStreamEndMs: relative(caller.streamEndAt),\n agentFirstPacketMs: relative(ctx.firstPacketAt),\n agentLastPacketMs: relative(ctx.lastPacketAt),\n agentSpeechOnsetMs: relative(ctx.firstAudioAt),\n agentSpeechOffsetMs: relative(ctx.lastAudioAt),\n agentPlaybackEndMs: relative(ctx.playbackEndAt),\n latestTurnBeginMs: relative(ctx.latestTurnBeginAt),\n postTurnBeginFirstPacketMs: relative(ctx.postTurnBeginFirstPacketAt),\n postTurnBeginSpeechOnsetMs: relative(ctx.postTurnBeginFirstAudioAt),\n lastAssistantTranscriptMs: relative(ctx.lastAssistantTranscriptAt),\n callerMaxFrameGapMs: Math.round(caller.maxFrameGapMs ?? 0),\n method: \"client-monotonic-queued-playback-energy-bounds\",\n };\n}\n\nexport async function streamPcmRealtime(omni, pcm, rate, clock, onFrame = () => {}) {\n const frameSize = Math.max(1, Math.round((rate * FRAME_MS) / 1000));\n const bounds = audibleBounds(pcm, rate);\n const startedAt = clock.now();\n let speechOnsetAt = null;\n let speechOffsetAt = null;\n let previousFrameEnd = startedAt;\n let maxFrameGapMs = 0;\n for (let off = 0; off < pcm.length; off += frameSize) {\n const frame = pcm.subarray(off, Math.min(off + frameSize, pcm.length));\n const at = clock.now();\n maxFrameGapMs = Math.max(maxFrameGapMs, at - previousFrameEnd);\n const durationMs = (frame.length / rate) * 1000;\n omni.sendAudio(frame);\n onFrame(frame, at);\n if (bounds.first != null && bounds.first >= off && bounds.first < off + frame.length) {\n speechOnsetAt = at + ((bounds.first - off) / rate) * 1000;\n }\n if (bounds.last != null && bounds.last > off && bounds.last <= off + frame.length) {\n speechOffsetAt = at + ((bounds.last - off) / rate) * 1000;\n }\n previousFrameEnd = at + durationMs;\n // Pace from the actual send. Never burst late frames to \"catch up\".\n await clock.sleep(Math.max(0, previousFrameEnd - clock.now()));\n }\n return { startedAt, speechOnsetAt, speechOffsetAt,\n streamEndAt: clock.now(), maxFrameGapMs };\n}\n\nexport async function streamSilenceWhile(omni, rate, shouldContinue, clock, onFrame = () => {}) {\n const silence = new Int16Array(Math.max(1, Math.round((rate * FRAME_MS) / 1000)));\n while (shouldContinue()) {\n const at = clock.now();\n omni.sendAudio(silence);\n onFrame(silence, at);\n await clock.sleep(FRAME_MS);\n }\n}\n\nexport async function waitForAgentSettle(getCtx, clock, opts = {}) {\n const started = clock.now();\n const observation = opts.callerStreamEndAt != null;\n if (observation && (!Number.isFinite(opts.callerStreamEndAt)\n || opts.callerStreamEndAt < 0 || opts.callerStreamEndAt > started)) {\n throw new Error(\"Invalid caller observation boundary\");\n }\n const timeoutMs = observation ? INTERRUPTION_OBSERVATION.maximumAfterCallerStreamMs : opts.timeoutMs ?? 25000;\n const settleMs = observation ? INTERRUPTION_OBSERVATION.quietMs : opts.settleMs ?? 2000;\n const deadlineAt = (observation ? opts.callerStreamEndAt : started) + timeoutMs;\n const minimumAt = observation ? opts.callerStreamEndAt + INTERRUPTION_OBSERVATION.minimumAfterCallerStreamMs : -Infinity;\n while (true) {\n const ctx = getCtx();\n const at = clock.now();\n if (opts.isClosed?.()) return { reason: \"closed\", at };\n if (observation && at >= deadlineAt) return { reason: \"timeout\", at };\n const hasResponseAudio = !opts.requireTurnBegin || (ctx.latestTurnBeginAt != null\n && ctx.postTurnBeginFirstAudioAt != null);\n // Synthesis text is progress, not a completion event. It can arrive after\n // early/final audio, so extend the quiet floor without demanding another\n // packet after every advisory. The protocol still has no reply-end marker.\n const activityEnd = Math.max(ctx.playbackEndAt ?? -Infinity,\n ctx.latestTurnBeginAt ?? -Infinity, ctx.lastAssistantTranscriptAt ?? -Infinity,\n observation ? ctx.lastCallerTranscriptAt ?? -Infinity : -Infinity);\n // Do not demand a new post-caller turn_begin: an earlier turn can be\n // coalesced and speak later. This records a bounded quiet observation;\n // downstream response-timing checks can impose a stricter begin boundary.\n if (ctx.firstPacketAt != null && hasResponseAudio && at >= minimumAt && at >= activityEnd + settleMs) {\n return { reason: \"settled\", at };\n }\n if (opts.allowEmpty && ctx.firstPacketAt == null && at >= minimumAt && at - started >= (opts.emptyWaitMs ?? 800)) {\n return { reason: \"empty\", at };\n }\n if (at - started >= timeoutMs) return { reason: \"timeout\", at };\n await clock.sleep(observation ? Math.min(20, deadlineAt - at) : 20);\n }\n}\n\nexport async function withTimeout(promise, ms, message, clock) {\n let timer;\n try {\n return await Promise.race([\n promise,\n new Promise((_, reject) => {\n timer = clock.setTimeout(() => reject(new Error(message)), ms);\n }),\n ]);\n } finally {\n clock.clearTimeout(timer);\n }\n}\n",
6
6
  "main.mjs": "import PyAI from \"@pyai/sdk\";\nimport WebSocket from \"ws\"; // Explicit transport makes this work on Node 20 too.\nimport { readFile, writeFile, mkdtemp } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { runSession } from \"./session.mjs\";\nimport { readWav, writeWav, assessAnswer } from \"./audio.mjs\";\n\nasync function main() {\n const [callerPath, interruptionPath, extra] = process.argv.slice(2);\n if (!callerPath || extra) throw new Error(\"Usage: node main.mjs caller.wav [interruption.wav]\");\n if (!process.env.PYAI_API_KEY) throw new Error(\"Inject PYAI_API_KEY through your environment first\");\n const caller = readWav(await readFile(callerPath));\n const interruption = interruptionPath ? readWav(await readFile(interruptionPath)) : undefined;\n const pyai = new PyAI({ apiKey: process.env.PYAI_API_KEY, maxRetries: 0,\n fetch: (url, options) => fetch(url, { ...options, signal: AbortSignal.timeout(30000) }),\n });\n const { report, audio, replyAudio } = await runSession({ pyai, webSocket: WebSocket, caller, interruption });\n const directory = await mkdtemp(join(process.cwd(), \"omni-run-\"));\n const save = (name, data) => writeFile(join(directory, name), data, { mode: 0o600, flag: \"wx\" });\n await save(\"session.wav\", writeWav(audio, report.output_rate ?? 24000));\n const reply = writeWav(replyAudio, report.output_rate ?? 24000);\n await save(\"reply.wav\", reply);\n // Hear the captured bytes, rather than trusting synthesis-advisory text.\n let capturedTranscript = \"\";\n if (report.reply_audio_bytes) {\n try {\n const heard = await pyai.audio.transcriptions.create({ file: new File([reply], \"reply.wav\", { type: \"audio/wav\" }), model: \"pyai-hear\" });\n capturedTranscript = heard.text;\n } catch { report.hear_error = \"Captured audio saved; Hear verification failed\"; }\n }\n const result = { ...report, captured_transcript: capturedTranscript, evidence: assessAnswer(report, capturedTranscript) };\n await save(\"report.json\", JSON.stringify(result, null, 2) + \"\\n\");\n console.log(JSON.stringify({ directory, ...result }, null, 2));\n if (result.evidence.captured_answer !== \"verified_by_hear\" || (interruption && result.evidence.interruption !== \"simulated_queue_cleared\")) process.exitCode = 1;\n}\n\nmain().catch(error => {\n const message = String(error.message).replaceAll(process.env.PYAI_API_KEY || \"\\0\", \"[REDACTED]\");\n console.error(JSON.stringify({ error: message, ...(error.omni_code ? { code: error.omni_code } : {}) })); process.exitCode = 1;\n});\n",
7
7
  "session.mjs": "import { newAudioCapture, recordAudio, recordTurnBegin, streamPcmRealtime, INTERRUPTION_OBSERVATION } from \"./timing.mjs\";\n\nexport const realClock = {\n now: () => performance.now(),\n sleep: ms => new Promise(resolve => setTimeout(resolve, ms)),\n};\n\n// Only recognized machine codes may leave the example. Error messages, call\n// IDs and arbitrary code values can contain credentials or customer content.\nconst publicErrorCodes = new Set([\n \"invalid_configure\", \"unsupported_tool_transport\", \"tool_configuration_locked\",\n \"media_dead\", \"unauthorized\", \"insufficient_scope\", \"rate_limit_exceeded\",\n \"concurrency_limit_exceeded\", \"daily_cap_exceeded\", \"credit_exhausted\",\n]);\nconst transportErrorCodes = new Set([\"ECONNRESET\", \"ECONNREFUSED\", \"ETIMEDOUT\", \"ENOTFOUND\", \"EAI_AGAIN\"]);\nexport function omniFailure(error) {\n const code = error instanceof Error\n ? (transportErrorCodes.has(error.code) ? error.code : \"transport_or_protocol_error\")\n : (publicErrorCodes.has(error?.code) ? error.code : \"unrecognized_server_error\");\n return Object.assign(new Error(`Omni failed (${code}); no automatic retry was attempted`), { omni_code: code });\n}\n\n/** One bounded, server-side example. Its playback queue is simulated. */\nexport async function runSession({ pyai, webSocket, caller, interruption, clock = realClock, timeoutMs = 60000 }) {\n const rate = 24000, frameSize = 480, silence = new Int16Array(frameSize);\n if (!(caller instanceof Int16Array) || !caller.length || caller.length > rate * 20) throw new Error(\"Provide 1–20 seconds of caller PCM16 at 24 kHz\");\n if (interruption && (!(interruption instanceof Int16Array) || !interruption.length || interruption.length > rate * 20)) throw new Error(\"Invalid interruption PCM\");\n const started = clock.now(), all = newAudioCapture(started), reply = newAudioCapture(started);\n const report = { input_rate: rate, output_rate: null, playback_sink: \"simulated\", tool_calls: 0, tool_executions: 0, duplicate_tool_calls: 0, flushes_after_interruption: 0, cleared_queue_ms: 0, interruption_requested: !!interruption, caller_started_ms: null, interruption_started_ms: null, advisory_transcripts: [], end_reason: \"timeout\" };\n let session, configuredAt = null, closed = false, failure = null, phase = \"greeting\", offset = 0, queueEnd = started, interruptionSent = false, inputEndAt = started;\n const handled = new Set();\n const fail = message => { failure ??= new Error(message); };\n try {\n session = pyai.omni.connect({\n webSocket, rate,\n configure: {\n voice_id: \"stock_amos_en_us\", language: \"en\", greeting: \"Hello. How can I help?\",\n persona: \"When asked about office hours, call lookup_office_hours. Never guess. After the result, say one short sentence giving its opening_time.\",\n tools: [{ name: \"lookup_office_hours\", description: \"Read the synthetic example office opening time.\", side_effect: \"read\", parameters: { type: \"object\", properties: {}, required: [], additionalProperties: false } }],\n },\n onHello: frame => {\n const match = /^pcm16@(8000|24000)$/.exec(frame.audio_out ?? \"\");\n if (!match) return fail(\"Unsupported Omni output format\");\n report.output_rate = Number(match[1]);\n },\n onConfigured: () => { configuredAt ??= clock.now(); },\n onAudio: chunk => {\n if (!report.output_rate) return fail(\"Audio arrived before its output format\");\n const bytes = chunk instanceof ArrayBuffer ? new Uint8Array(chunk) : new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength);\n if (bytes.byteLength % 2) return fail(\"Invalid PCM16 output\");\n const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n const pcm = Int16Array.from({ length: bytes.length / 2 }, (_, i) => view.getInt16(i * 2, true));\n const now = clock.now();\n recordAudio(all, pcm, now, report.output_rate);\n queueEnd = Math.max(now, queueEnd) + pcm.length / report.output_rate * 1000;\n if (report.tool_executions) recordAudio(reply, pcm, now, report.output_rate);\n },\n onEvent: frame => {\n if (frame.event === \"turn_begin\") recordTurnBegin(all, clock.now(), frame.turn);\n },\n onTranscript: frame => {\n // An assistant advisory is progress; never treat it as received speech.\n if (report.advisory_transcripts.length < 100) report.advisory_transcripts.push({ role: frame.role, text: frame.text });\n if (frame.role === \"assistant\") all.lastAssistantTranscriptAt = clock.now();\n },\n onToolCall: frame => {\n report.tool_calls++;\n if (handled.has(frame.call_id)) { report.duplicate_tool_calls++; return; }\n handled.add(frame.call_id);\n if (frame.name !== \"lookup_office_hours\") { session.toolResult(frame.call_id, { error: \"Unknown example tool\" }); return; }\n // Replace this read-only fixture with your authorized data lookup.\n report.tool_executions++;\n session.toolResult(frame.call_id, { result: { opening_time: \"9 a.m.\", source: \"synthetic example office\" } });\n },\n onBargeIn: () => {\n const now = clock.now(), queued = Math.max(0, queueEnd - now);\n if (report.interruption_started_ms != null) { report.flushes_after_interruption++; report.cleared_queue_ms += queued; }\n // A real speaker adapter must cancel scheduled and currently playing audio.\n queueEnd = now; all.playbackEndAt = now; reply.playbackEndAt = now;\n },\n onError: error => { failure ??= omniFailure(error); },\n onClose: () => { closed = true; },\n });\n while (clock.now() - started < timeoutMs) {\n if (failure) throw failure;\n if (closed) { report.end_reason = \"closed\"; break; }\n const now = clock.now();\n if (configuredAt == null || !report.output_rate) {\n if (now - started >= 10000) throw new Error(\"Omni connection/configuration timed out\");\n await clock.sleep(20); continue;\n }\n const quietAt = Math.max(queueEnd, all.lastPacketAt ?? now, all.lastAssistantTranscriptAt ?? 0, inputEndAt);\n if (phase === \"greeting\") {\n if (all.firstPacketAt != null && now - configuredAt >= 2000 && now >= quietAt + 800) {\n phase = \"caller\"; report.caller_started_ms = now - started;\n } else if (now - configuredAt > 15000) throw new Error(\"Greeting did not drain within 15 seconds\");\n }\n if (phase === \"reply\" && interruption && !interruptionSent && reply.samples && queueEnd - now >= 200) {\n phase = \"interruption\"; offset = 0; interruptionSent = true; report.interruption_started_ms = now - started;\n }\n const observationEnd = inputEndAt + (interruptionSent ? INTERRUPTION_OBSERVATION.minimumAfterCallerStreamMs : 0);\n if (phase === \"reply\" && reply.samples && now >= quietAt + 2000 && now >= observationEnd && (!interruption || interruptionSent)) {\n report.end_reason = \"quiet_window\"; break;\n }\n // Exactly one producer: each 20 ms slot contains caller PCM OR silence.\n let pcm = silence;\n if (phase === \"caller\" || phase === \"interruption\") {\n const source = phase === \"caller\" ? caller : interruption;\n pcm = source.subarray(offset, offset + frameSize); offset += pcm.length;\n if (offset >= source.length) {\n inputEndAt = now + pcm.length / rate * 1000;\n report[phase === \"caller\" ? \"caller_completed_ms\" : \"interruption_completed_ms\"] = inputEndAt - started;\n phase = \"reply\"; offset = 0;\n }\n }\n await streamPcmRealtime(session, pcm, rate, clock);\n }\n report.audio_bytes = all.samples * 2;\n report.reply_audio_bytes = reply.samples * 2;\n report.elapsed_ms = Math.round(clock.now() - started);\n return { report, audio: all.pcm, replyAudio: reply.pcm };\n } finally { session?.close(); }\n}\n",
@@ -17,6 +17,8 @@ export interface BrowserCredential {
17
17
  key_id: string;
18
18
  org_id: string;
19
19
  project_id: string;
20
+ /** Verified approving human, when returned by the current device flow. */
21
+ user_id?: string;
20
22
  environment: "live" | "test";
21
23
  scopes: string[];
22
24
  expires_at: number;
@@ -132,6 +134,7 @@ export async function browserLogin(options: BrowserLoginOptions): Promise<Browse
132
134
  if (!["key_id", "org_id", "project_id"].every(key => typeof result[key] === "string" && result[key].length > 0)
133
135
  || !["test", "live"].includes(result.environment) || !Array.isArray(result.scopes) || !result.scopes.every((s: unknown) => typeof s === "string")
134
136
  || typeof result.expires_at !== "number" || !Number.isFinite(result.expires_at) || result.expires_at <= now()) invalidResponse();
137
+ if (result.user_id !== undefined && (typeof result.user_id !== "string" || !result.user_id.trim() || result.user_id.length > 200 || /[\x00-\x1f\x7f]/.test(result.user_id))) throw new CliError("invalid_response", "The login response contained an invalid user identity.", 5);
135
138
  return result as BrowserCredential;
136
139
  } catch (error) {
137
140
  if (!(error instanceof CliError)) throw error;