@pyai/sdk 0.9.2 → 0.11.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 (49) hide show
  1. package/CLI.schema.json +11 -0
  2. package/README.md +131 -3
  3. package/dist/cli-omni-template.d.ts +2 -2
  4. package/dist/cli-omni-template.js +2 -2
  5. package/dist/cli.js +39 -4
  6. package/dist/dialer/appServer.d.ts +21 -0
  7. package/dist/dialer/appServer.js +195 -0
  8. package/dist/dialer/dialerElement.d.ts +23 -0
  9. package/dist/dialer/dialerElement.js +108 -0
  10. package/dist/dialer/dialingQueue.d.ts +31 -0
  11. package/dist/dialer/dialingQueue.js +78 -0
  12. package/dist/dialer/index.d.ts +6 -0
  13. package/dist/dialer/index.js +6 -0
  14. package/dist/dialer/indexedDbJournal.d.ts +11 -0
  15. package/dist/dialer/indexedDbJournal.js +62 -0
  16. package/dist/dialer/managedDialer.d.ts +65 -0
  17. package/dist/dialer/managedDialer.js +217 -0
  18. package/dist/dialer/meetingRecorder.d.ts +83 -0
  19. package/dist/dialer/meetingRecorder.js +261 -0
  20. package/dist/dialer/meetingRecorderElement.d.ts +20 -0
  21. package/dist/dialer/meetingRecorderElement.js +138 -0
  22. package/dist/dialer/meetingRecordingStore.d.ts +17 -0
  23. package/dist/dialer/meetingRecordingStore.js +129 -0
  24. package/dist/dialer/serverBroker.d.ts +3 -0
  25. package/dist/dialer/serverBroker.js +23 -0
  26. package/dist/dialer/voiceSdkAudio.d.ts +33 -0
  27. package/dist/dialer/voiceSdkAudio.js +66 -0
  28. package/dist/index.d.ts +238 -6
  29. package/dist/index.js +67 -3
  30. package/package.json +24 -1
  31. package/src/cli-omni-template.ts +2 -2
  32. package/src/cli.ts +25 -4
  33. package/src/dialer/app/app.css +1 -0
  34. package/src/dialer/app/app.html +7 -0
  35. package/src/dialer/app/app.js +88 -0
  36. package/src/dialer/app/icon.svg +1 -0
  37. package/src/dialer/app/manifest.webmanifest +1 -0
  38. package/src/dialer/appServer.ts +151 -0
  39. package/src/dialer/dialerElement.ts +80 -0
  40. package/src/dialer/dialingQueue.ts +65 -0
  41. package/src/dialer/index.ts +6 -0
  42. package/src/dialer/indexedDbJournal.ts +56 -0
  43. package/src/dialer/managedDialer.ts +187 -0
  44. package/src/dialer/meetingRecorder.ts +220 -0
  45. package/src/dialer/meetingRecorderElement.ts +99 -0
  46. package/src/dialer/meetingRecordingStore.ts +99 -0
  47. package/src/dialer/serverBroker.ts +23 -0
  48. package/src/dialer/voiceSdkAudio.ts +61 -0
  49. package/src/index.ts +174 -5
@@ -0,0 +1,61 @@
1
+ import type { TelephonyBrowserSession } from "../index.ts";
2
+ import type { DialerAudio } from "./managedDialer.ts";
3
+
4
+ interface VoiceCall {
5
+ on(event: string, callback: (...args: unknown[]) => void): void;
6
+ removeAllListeners(): void;
7
+ disconnect(): void;
8
+ mute(value: boolean): void;
9
+ sendDigits(digits: string): void;
10
+ status(): string;
11
+ }
12
+ interface VoiceDevice {
13
+ connect(options: { params: Record<string, string> }): Promise<VoiceCall>;
14
+ on(event: string, callback: (...args: unknown[]) => void): void;
15
+ removeAllListeners(): void;
16
+ destroy(): void;
17
+ }
18
+ /** Inject the supported Voice SDK's Device constructor. Lazy-load it only when
19
+ * calling starts; the dialer shell itself has no framework or media dependency. */
20
+ export class VoiceSdkAudio implements DialerAudio {
21
+ private device: VoiceDevice | null = null;
22
+ private call: VoiceCall | null = null;
23
+ private generation = 0;
24
+ private notify: ((state: "ringing" | "active" | "disconnected") => void) | null = null;
25
+ private readonly createDevice: (token: string) => VoiceDevice;
26
+ constructor(createDevice: (token: string) => VoiceDevice) { this.createDevice = createDevice; }
27
+ async connect(session: TelephonyBrowserSession, event: (state: "ringing" | "active" | "disconnected") => void) {
28
+ if (!session.access_token) throw new Error("No unconsumed calling capability.");
29
+ this.disconnect(); const generation = this.generation;
30
+ const device = this.createDevice(session.access_token); this.device = device; this.notify = event;
31
+ const emit = (state: "ringing" | "active" | "disconnected") => { if (generation === this.generation) this.notify?.(state); };
32
+ device.on("error", () => emit("disconnected"));
33
+ try {
34
+ const call = await device.connect({ params: { ...session.connect_params } });
35
+ if (generation !== this.generation) {
36
+ try { call.removeAllListeners(); } catch { /* Continue releasing stale audio. */ }
37
+ try { call.disconnect(); } catch { /* The owning device is already destroyed. */ }
38
+ return;
39
+ }
40
+ this.call = call;
41
+ call.on("ringing", () => emit("ringing"));
42
+ call.on("accept", () => emit("active"));
43
+ for (const name of ["disconnect", "cancel", "reject", "error"]) call.on(name, () => emit("disconnected"));
44
+ emit(call.status() === "open" ? "active" : "ringing");
45
+ } catch (error) {
46
+ if (generation === this.generation) this.disconnect();
47
+ throw error;
48
+ }
49
+ }
50
+ disconnect() {
51
+ this.generation++; this.notify = null;
52
+ const call = this.call, device = this.device; this.call = null; this.device = null;
53
+ // Local SDK failures must not prevent the controller's durable remote stop.
54
+ for (const close of [() => call?.removeAllListeners(), () => call?.disconnect(),
55
+ () => device?.removeAllListeners(), () => device?.destroy()]) {
56
+ try { close(); } catch { /* All owned resources still get a cleanup attempt. */ }
57
+ }
58
+ }
59
+ mute(value: boolean) { if (!this.call) throw new Error("No active audio."); this.call.mute(value); }
60
+ sendDigits(digits: string) { if (!this.call) throw new Error("No active audio."); this.call.sendDigits(digits); }
61
+ }
package/src/index.ts CHANGED
@@ -233,7 +233,10 @@ export type OmniStagedLanguage = "ht" | "zh-CN" | "ar-MSA" | "ar-Gulf";
233
233
 
234
234
  export interface AgentConfig {
235
235
  name?: string;
236
+ /** Saved instructions: 8,000 Unicode characters by default; 32,000 on commitment plans. */
236
237
  persona_system_prompt?: string | null;
238
+ /** False restricts retrieval to explicit agent bindings, including none. Default true. */
239
+ inherit_org_knowledgebases?: boolean;
237
240
  greeting?: string | null;
238
241
  voice_id?: string | null;
239
242
  language?: OmniLanguage | null;
@@ -248,8 +251,10 @@ export interface AgentConfig {
248
251
  export interface Agent {
249
252
  object: "agent";
250
253
  agent_id: string;
254
+ prompt_limit_characters?: 8000 | 32000;
251
255
  name: string;
252
256
  vocabulary: string[];
257
+ inherit_org_knowledgebases?: boolean;
253
258
  [key: string]: unknown;
254
259
  }
255
260
 
@@ -1473,6 +1478,67 @@ export interface TelephonyCapabilities {
1473
1478
  sms?: boolean;
1474
1479
  }
1475
1480
 
1481
+ export type TelephonyCallStatus = "queued" | "dispatching" | "ringing" | "in_progress" | "completed" | "failed" | "canceled" | "dispatch_unknown";
1482
+ export interface TelephonyCall {
1483
+ object: "telephony.call";
1484
+ id: string;
1485
+ project_id: string;
1486
+ direction: "inbound" | "outbound";
1487
+ status: TelephonyCallStatus;
1488
+ version: number;
1489
+ from: string;
1490
+ to: string;
1491
+ from_number_id: string | null;
1492
+ agent_id: string | null;
1493
+ call_type?: "human";
1494
+ user_id?: string;
1495
+ client_reference: string | null;
1496
+ stop_requested: boolean;
1497
+ created_at: number;
1498
+ updated_at: number;
1499
+ answered_at: number | null;
1500
+ ended_at: number | null;
1501
+ [key: string]: unknown;
1502
+ }
1503
+ export type TelephonyUseCase = "transactional" | "support" | "sales" | "collections" | "survey";
1504
+ export interface TelephonyCallCreate {
1505
+ from_number_id: string;
1506
+ to: string;
1507
+ agent_id: string;
1508
+ use_case: TelephonyUseCase;
1509
+ routing_profile?: "quality_first" | "balanced" | "cost_optimized";
1510
+ client_reference?: string;
1511
+ agent_release_id?: string;
1512
+ max_duration_seconds?: number;
1513
+ stop_requested?: boolean;
1514
+ }
1515
+ export interface TelephonyBrowserSessionCreate {
1516
+ from_number_id: string;
1517
+ to: string;
1518
+ /** Resolve from your authenticated server session, never from untrusted form data. */
1519
+ user_id: string;
1520
+ client_reference: string;
1521
+ recording: boolean;
1522
+ use_case?: TelephonyUseCase;
1523
+ max_duration_seconds?: number;
1524
+ }
1525
+ export interface TelephonyBrowserSession {
1526
+ object: "telephony.browser_session";
1527
+ id: string;
1528
+ call_id: string;
1529
+ transport: "voice-sdk";
1530
+ /** Single-call capability. Keep in memory; never log or persist this token. */
1531
+ access_token: string | null;
1532
+ expires_at: number;
1533
+ connect_params: { session_id: string };
1534
+ call: TelephonyCall;
1535
+ }
1536
+
1537
+ function telephonyIdempotencyHeader(key: string): Record<string, string> {
1538
+ if (!key || key.length > 255 || /[\r\n]/.test(key)) throw new Error("A valid Idempotency-Key is required; persist it before creating a call.");
1539
+ return { "Idempotency-Key": key };
1540
+ }
1541
+
1476
1542
  export interface TelephonyAvailableNumber {
1477
1543
  object?: "telephony.available_number";
1478
1544
  /** E.164. */
@@ -1502,6 +1568,27 @@ export interface TelephonyNumber {
1502
1568
  released_at?: number | null;
1503
1569
  }
1504
1570
 
1571
+ export interface TelephonyNumberOrder {
1572
+ object: "telephony.number_order";
1573
+ id: string;
1574
+ status: "pending" | "unknown" | "completed" | "failed" | "released";
1575
+ phone_number: string;
1576
+ country: "AU";
1577
+ project_id: string;
1578
+ retry_after_seconds: number;
1579
+ message: string;
1580
+ failure_code?: string;
1581
+ number?: TelephonyNumber;
1582
+ }
1583
+ export interface TelephonyNumberPurchase {
1584
+ phone_number: string;
1585
+ agent_id?: string | null;
1586
+ provisioning_mode?: "automated" | "adopt_preowned";
1587
+ project_id?: string;
1588
+ compliance_case_id?: string;
1589
+ max_monthly_cost_cents?: number;
1590
+ }
1591
+
1505
1592
  /* ------------------------------------------------------------------------- *
1506
1593
  * Trace (compliance)
1507
1594
  * ------------------------------------------------------------------------- */
@@ -1916,6 +2003,23 @@ function retryPause(ms: number, signal?: AbortSignal | null): Promise<void> {
1916
2003
  });
1917
2004
  }
1918
2005
 
2006
+ export type TranslationArchiveFormat = "party-v1" | "none";
2007
+ export interface TranslationRecordingTicket {
2008
+ object: "interpretation.recording";
2009
+ id:string; upload_capability:string; upload_until:number; capture_format:TranslationArchiveFormat;
2010
+ upload_url:string; complete_url:string; call_url:string;
2011
+ limits:{duration_ms:number;events:number;audio_bytes_per_perspective:number};
2012
+ }
2013
+ export interface TranslationCall {
2014
+ object:"interpretation.call"; id:string; external_call_id?:string; room_id?:string;
2015
+ provider:string; languages:string[]; created_at:number; ended_at?:number; duration_ms?:number;
2016
+ status:"recording"|"ready"|"incomplete"; capture_format?:TranslationArchiveFormat;
2017
+ audio:{bytes:number;sha256:string;content_type:string}|null;
2018
+ perspectives?:Partial<Record<"customer"|"agent",{bytes:number;sha256:string;content_type:string}>>;
2019
+ captions:Array<{event:string;leg:string;text:string;raw_text:string;sequence:number;context_id?:string;participant_id?:string}>;
2020
+ capture:string;
2021
+ }
2022
+
1919
2023
  export class PyAI {
1920
2024
  private readonly apiKey: string;
1921
2025
  private readonly baseURL: string;
@@ -2257,12 +2361,36 @@ export class PyAI {
2257
2361
  // --- telephony (managed numbers) ---------------------------------------
2258
2362
 
2259
2363
  telephony = {
2364
+ /** Server-side methods. Keep the PyAI key in your backend. */
2365
+ calls: {
2366
+ create: (input: TelephonyCallCreate, options: { idempotencyKey: string }): Promise<TelephonyCall> =>
2367
+ this.postJson("/v1/telephony/calls", input, telephonyIdempotencyHeader(options.idempotencyKey)),
2368
+ get: (id: string): Promise<TelephonyCall> => this.getJson(`/v1/telephony/calls/${encodeURIComponent(id)}`),
2369
+ list: (input: { limit?: number; cursor?: string; direction?: "inbound" | "outbound"; status?: TelephonyCallStatus } = {}): Promise<ListResponse<TelephonyCall> & { next_cursor: string | null }> => {
2370
+ const query = new URLSearchParams();
2371
+ for (const [key, value] of Object.entries(input)) if (value !== undefined) query.set(key, String(value));
2372
+ return this.getJson(`/v1/telephony/calls${query.size ? `?${query}` : ""}`);
2373
+ },
2374
+ /** Durable stop intent; use get() until a terminal status is confirmed. */
2375
+ hangup: (id: string): Promise<TelephonyCall> => this.postJson(`/v1/telephony/calls/${encodeURIComponent(id)}/hangup`, {}),
2376
+ decideAdmission: (id: string, input: { decision: "accept" | "reject"; client_reference: string; max_duration_seconds: number }): Promise<TelephonyCall> =>
2377
+ this.postJson(`/v1/telephony/calls/${encodeURIComponent(id)}/admission`, input),
2378
+ recording: (id: string, options: { range?: string } = {}): Promise<Response> =>
2379
+ this.request(`/v1/telephony/calls/${encodeURIComponent(id)}/recording`, { headers: this.authHeaders(options.range ? { Range: options.range } : {}) }),
2380
+ deleteRecording: async (id: string): Promise<void> => { await this.deleteReq(`/v1/telephony/calls/${encodeURIComponent(id)}/recording`); },
2381
+ },
2382
+ browserSessions: {
2383
+ /** Persist input and key on your server; retries recover the original session. */
2384
+ create: (input: TelephonyBrowserSessionCreate, options: { idempotencyKey: string }): Promise<TelephonyBrowserSession> =>
2385
+ this.postJson("/v1/telephony/browser-sessions", input, telephonyIdempotencyHeader(options.idempotencyKey)),
2386
+ },
2260
2387
  numbers: {
2261
- /** Search the carrier's available US local numbers. */
2388
+ /** Search managed inventory; country availability and ordering may be gated. */
2262
2389
  available: (
2263
- params: { areaCode?: string; contains?: string; limit?: number } = {},
2390
+ params: { country?: "US" | "CA" | "IN" | "AU"; areaCode?: string; contains?: string; limit?: number } = {},
2264
2391
  ): Promise<ListResponse<TelephonyAvailableNumber>> => {
2265
2392
  const q = new URLSearchParams();
2393
+ if (params.country) q.set("country", params.country);
2266
2394
  if (params.areaCode) q.set("area_code", params.areaCode);
2267
2395
  if (params.contains) q.set("contains", params.contains);
2268
2396
  if (params.limit !== undefined) q.set("limit", String(params.limit));
@@ -2274,9 +2402,9 @@ export class PyAI {
2274
2402
  const qs = params.includeReleased ? "?include_released=true" : "";
2275
2403
  return this.getJson(`/v1/telephony/numbers${qs}`);
2276
2404
  },
2277
- /** Provision (buy) a specific available number, optionally bound to an agent. */
2278
- buy: (params: { phone_number: string; agent_id?: string | null }): Promise<TelephonyNumber> =>
2279
- this.postJson("/v1/telephony/numbers", params),
2405
+ /** Persist selection and key first. Pending/unknown orders must be recovered, never repurchased. */
2406
+ buy: (params: TelephonyNumberPurchase, options: { idempotencyKey: string }): Promise<TelephonyNumber | TelephonyNumberOrder> =>
2407
+ this.postJson("/v1/telephony/numbers", params, telephonyIdempotencyHeader(options.idempotencyKey)),
2280
2408
  /** Route a number to an agent (`agentId: null` to unassign). */
2281
2409
  assign: (id: string, agentId: string | null): Promise<TelephonyNumber> =>
2282
2410
  this.postJson(`/v1/telephony/numbers/${encodeURIComponent(id)}/assign`, { agent_id: agentId }),
@@ -2286,6 +2414,47 @@ export class PyAI {
2286
2414
  return (await res.json()) as TelephonyNumber;
2287
2415
  },
2288
2416
  },
2417
+ numberOrders: {
2418
+ get: (id: string): Promise<TelephonyNumberOrder> => this.getJson(`/v1/telephony/number-orders/${encodeURIComponent(id)}`),
2419
+ /** Read/reconcile the original order; this never purchases another number. */
2420
+ reconcile: (id: string): Promise<TelephonyNumberOrder> => this.postJson(`/v1/telephony/number-orders/${encodeURIComponent(id)}/reconcile`, {}),
2421
+ },
2422
+ };
2423
+
2424
+ /** Customer-owned two-human calls. Server keys only; history is project scoped. */
2425
+ translation = {
2426
+ createSession: (input:{allowed_origins:string[];ttl_seconds?:number}):Promise<{object:"interpretation.session";token:string;url:string;expires_at:number;project_id:string;billing:"credits"}> =>
2427
+ this.postJson("/v1/audio/interpretations/sessions",input),
2428
+ recordings: {
2429
+ upload: async (ticket:Pick<TranslationRecordingTicket,"id"|"upload_capability">,audio:Uint8Array,perspective:"customer"|"agent"):Promise<{received:true}> => {
2430
+ const response=await this.request(`/auth/interpretation-recordings/${encodeURIComponent(ticket.id)}/audio?perspective=${perspective}`,
2431
+ {method:"POST",headers:{Authorization:`Bearer ${ticket.upload_capability}`,"Content-Type":"audio/wav"},body:new Blob([new Uint8Array(audio)],{type:"audio/wav"})});
2432
+ return response.json() as Promise<{received:true}>;
2433
+ },
2434
+ complete: async (ticket:Pick<TranslationRecordingTicket,"id"|"upload_capability">,input:{duration_ms:number;room_id?:string;events:Record<string,unknown>[];audio_pending?:true;audio_failed?:true}):Promise<{id:string;status:TranslationCall["status"]}> => {
2435
+ const response=await this.request(`/auth/interpretation-recordings/${encodeURIComponent(ticket.id)}/complete`,
2436
+ {method:"POST",headers:{Authorization:`Bearer ${ticket.upload_capability}`,"Content-Type":"application/json"},body:JSON.stringify(input)});
2437
+ return response.json() as Promise<{id:string;status:TranslationCall["status"]}>;
2438
+ },
2439
+ /** Explicit opt-in archive. Keep its short-lived write capability on your server. POST is not automatically retried. */
2440
+ create: (input:{languages:[string,string];external_call_id?:string;capture_format?:TranslationArchiveFormat}):Promise<TranslationRecordingTicket> =>
2441
+ this.postJson("/v1/audio/interpretations/recordings",input),
2442
+ },
2443
+ calls: {
2444
+ list: (params:{cursor?:string}={}):Promise<{object:"list";data:TranslationCall[];limit:number;next_cursor:string|null;has_more:boolean}> =>
2445
+ this.getJson("/v1/audio/interpretations/calls"+(params.cursor?"?cursor="+encodeURIComponent(params.cursor):"")),
2446
+ get: (id:string):Promise<TranslationCall> => this.getJson(`/v1/audio/interpretations/calls/${encodeURIComponent(id)}`),
2447
+ transcript: (id:string):Promise<{object:"interpretation.transcript";call_id:string;captions:TranslationCall["captions"];events:Record<string,unknown>[]}> =>
2448
+ this.getJson(`/v1/audio/interpretations/calls/${encodeURIComponent(id)}/transcript`),
2449
+ events: (id:string):Promise<{object:"list";call_id:string;data:Record<string,unknown>[]}> =>
2450
+ this.getJson(`/v1/audio/interpretations/calls/${encodeURIComponent(id)}/events`),
2451
+ /** Authenticated audio response, streamable by a server; never put an API key in an HTML audio URL. */
2452
+ recording: (id:string,params:{perspective?:"customer"|"agent";download?:boolean;range?:string}={}):Promise<Response> => {
2453
+ const q=new URLSearchParams();if(params.perspective)q.set("perspective",params.perspective);if(params.download)q.set("download","1");
2454
+ return this.request(`/v1/audio/interpretations/calls/${encodeURIComponent(id)}/recording${q.size?"?"+q:""}`,
2455
+ {headers:this.authHeaders(params.range?{Range:params.range}:{})});
2456
+ },
2457
+ },
2289
2458
  };
2290
2459
 
2291
2460
  // --- trace (compliance) -------------------------------------------------