@pyai/sdk 0.16.0 → 0.18.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.
@@ -2,7 +2,6 @@
2
2
  import { createHash } from "node:crypto";
3
3
  import type { PyAI, TelephonyBrowserSessionCreate } from "../index.ts";
4
4
  import type { DialerBroker } from "./managedDialer.ts";
5
- import { dialerCallHandedOff } from "./managedDialer.ts";
6
5
 
7
6
  export function createServerDialerBroker(sdk: PyAI, authenticatedUserId: string): DialerBroker {
8
7
  if (!authenticatedUserId.trim()) throw new Error("An authenticated user is required.");
@@ -20,9 +19,9 @@ export function createServerDialerBroker(sdk: PyAI, authenticatedUserId: string)
20
19
  },
21
20
  get: ownedCall,
22
21
  async hangup(id: string) {
23
- const call = await ownedCall(id);
24
- if (dialerCallHandedOff(call)) return call;
25
- return sdk.telephony.calls.hangup(id);
22
+ await ownedCall(id);
23
+ // The provider rechecks handoff ownership in the stop CAS, after this read.
24
+ return sdk.telephony.calls.hangup(id,{user_id:authenticatedUserId});
26
25
  },
27
26
  async setHold(id, held, key) {
28
27
  await ownedCall(id);
@@ -30,6 +29,12 @@ export function createServerDialerBroker(sdk: PyAI, authenticatedUserId: string)
30
29
  const scopedKey = "dialer-hold:" + createHash("sha256").update(authenticatedUserId).update("\0").update(id).update("\0").update(key).digest("hex");
31
30
  return sdk.telephony.calls.setHold(id, { held, user_id: authenticatedUserId }, { idempotencyKey: scopedKey });
32
31
  },
32
+ async sendDtmf(id, digits, key) {
33
+ await ownedCall(id);
34
+ if (!key || key.length > 255 || /[\r\n]/.test(key)) throw new Error("A valid keypad retry key is required.");
35
+ const scopedKey = "dialer-keypad:" + createHash("sha256").update(authenticatedUserId).update("\0").update(id).update("\0").update(key).digest("hex");
36
+ return sdk.telephony.calls.sendDtmf(id, { digits, user_id: authenticatedUserId }, { idempotencyKey: scopedKey });
37
+ },
33
38
  transfers: {
34
39
  async create(id, input, key) {
35
40
  await ownedCall(id);
package/src/index.ts CHANGED
@@ -129,7 +129,8 @@ export interface SpeechParams {
129
129
  voice?: string;
130
130
  model?: SpeakModel;
131
131
  /**
132
- * Delivery mode. The API defaults to true and every catalog voice accepts
132
+ * Delivery mode. `speech` defaults to false; `speechStream` always uses true.
133
+ * The API itself defaults to true and every catalog voice accepts
133
134
  * both values. Set false when you want one complete buffered body with a
134
135
  * `Content-Length`. A voice whose serving fleet has no streaming lane is
135
136
  * rendered buffered either way and says so with `x-pyai-stream: buffered`.
@@ -183,6 +184,10 @@ export type CreateJobParams = CreateJobOptions & (
183
184
  );
184
185
 
185
186
  export interface CreateJobOptions {
187
+ /** Spoken-language hint for every audio chunk; omit for automatic detection. */
188
+ transcription_language?: string;
189
+ /** Original script (default), or Roman letters preserving the spoken language; no translation. */
190
+ output_script?: "original" | "latin";
186
191
  /** Requires Trace entitlement; incompatible with channel/diarize. */
187
192
  trace?: boolean;
188
193
  rule_pack?: Record<string, unknown>;
@@ -500,7 +505,7 @@ export interface HearStreamOptions {
500
505
  /** Streaming STT model. Server default `pyai-hear`. */
501
506
  model?: string;
502
507
  /** Omit or use auto for automatic detection; an explicit code pins recognition. */
503
- language?: "auto" | "en" | "es" | "fr" | "de" | "hi" | "it" | "pt" | "nl" | "zh" | "yue" | "ar" | "id" | "ko" | "th" | "vi" | "ja" | "tr" | "ms" | "sv" | "da" | "fi" | "pl" | "cs" | "fil" | "fa" | "el" | "hu" | "mk" | "ro";
508
+ language?: "auto" | "en" | "es" | "fr" | "de" | "hi" | "it" | "pt" | "nl" | "zh" | "yue" | "ar" | "id" | "ko" | "th" | "vi" | "ja" | "tr" | "ms" | "sv" | "da" | "fi" | "pl" | "cs" | "fil" | "fa" | "el" | "hu" | "mk" | "ro" | "ru";
504
509
  /** Input PCM sample rate in Hz. Default 16000 server-side. */
505
510
  sampleRate?: number;
506
511
  /** Audio frame encoding. Default "pcm16". */
@@ -1504,6 +1509,7 @@ export interface TelephonyCall {
1504
1509
  held?: boolean;
1505
1510
  hold_pending?: boolean;
1506
1511
  transfers?: TelephonyTransfer[];
1512
+ forwarding?: { to: string | null; status: "waiting" | "claimed" | "unknown" | "acknowledged" | "canceled"; menu?: { kind: "keypad"; status: "pending" | "selected" | "rejected"; choice_id: string | null } };
1507
1513
  user_id?: string;
1508
1514
  client_reference: string | null;
1509
1515
  stop_requested: boolean;
@@ -1546,6 +1552,14 @@ export interface TelephonyCallCapabilities {
1546
1552
  revalidation_required: true;
1547
1553
  }
1548
1554
 
1555
+ export interface TelephonyCallControl {
1556
+ object: "telephony.call_control";
1557
+ id: string;
1558
+ call_id: string;
1559
+ action: "send_dtmf";
1560
+ status: "acknowledged" | "unknown" | "rejected";
1561
+ }
1562
+
1549
1563
  export interface TelephonyCallCreate {
1550
1564
  from_number_id: string;
1551
1565
  to: string;
@@ -1593,6 +1607,12 @@ export interface TelephonyAvailableNumber {
1593
1607
  region?: string | null;
1594
1608
  capabilities?: TelephonyCapabilities;
1595
1609
  monthly_cost_cents?: number;
1610
+ /** Bind purchase to the exact account/market inventory result. */
1611
+ inventory_reference?: string;
1612
+ }
1613
+
1614
+ export interface TelephonyNumberInventory extends ListResponse<TelephonyAvailableNumber> {
1615
+ provisioning?: { mode: "automated" | "assisted"; capability: string; message: string };
1596
1616
  }
1597
1617
 
1598
1618
  export interface TelephonyNumber {
@@ -1617,7 +1637,7 @@ export interface TelephonyNumberOrder {
1617
1637
  id: string;
1618
1638
  status: "pending" | "unknown" | "completed" | "failed" | "released";
1619
1639
  phone_number: string;
1620
- country: "AU";
1640
+ country: "AU" | "US" | "CA";
1621
1641
  project_id: string;
1622
1642
  retry_after_seconds: number;
1623
1643
  message: string;
@@ -1626,6 +1646,8 @@ export interface TelephonyNumberOrder {
1626
1646
  }
1627
1647
  export interface TelephonyNumberPurchase {
1628
1648
  phone_number: string;
1649
+ country?: "US" | "CA" | "IN" | "AU";
1650
+ inventory_reference?: string;
1629
1651
  agent_id?: string | null;
1630
1652
  provisioning_mode?: "automated" | "adopt_preowned";
1631
1653
  project_id?: string;
@@ -1633,6 +1655,68 @@ export interface TelephonyNumberPurchase {
1633
1655
  max_monthly_cost_cents?: number;
1634
1656
  }
1635
1657
 
1658
+ export interface TelephonyDesktopEndpoint {
1659
+ object:'telephony.desktop_endpoint';id:string;project_id:string;user_id:string;actor_type:'application';label:string;
1660
+ registered:boolean;available:boolean;number_id:string;status:'active'|'revoked';
1661
+ }
1662
+ export interface TelephonyDesktopEnrollment {object:'telephony.desktop_enrollment';version:1;endpoint_id:string;enrollment_token:string;expires_at:number;redeem_path:string;}
1663
+ export interface TelephonyDesktopCredentials {endpoint_id:string;org_id:string;project_id:string;user_id:string;label:string;refresh_token:string;refresh_expires_at:number;access_token:string;expires_at:number;presence_token:string;heartbeat_interval_seconds:15;}
1664
+ export interface TelephonyInboundRingGroup {
1665
+ mode:'simultaneous'|'desktop_first';desktop_endpoint_ids:[string];external_to:string;desktop_timeout_seconds:number;
1666
+ ring_timeout_seconds:number;on_no_answer:'hangup';max_duration_seconds:number;recording:boolean;
1667
+ }
1668
+ export interface TelephonyInboundCapabilities {
1669
+ object:'telephony.inbound_capabilities';number_id:string;binding_version:number;
1670
+ ring_group:{supported:boolean;modes:Array<'simultaneous'|'desktop_first'>;max_desktop_endpoints:1;on_no_answer:['hangup'];desktop_registration_required:true};
1671
+ }
1672
+
1673
+ export interface TelephonyInboundBinding {
1674
+ object: "telephony.inbound_binding";
1675
+ number_id: string;
1676
+ version: number;
1677
+ enabled: boolean;
1678
+ project_id?: string;
1679
+ agent_id?: string;
1680
+ agent_release_id?: string;
1681
+ agent_profile_sha256?: string;
1682
+ admission_mode?: "client" | "platform";
1683
+ forward?: TelephonyInboundForward | null;
1684
+ ring_group?:TelephonyInboundRingGroup|null;
1685
+ carrier_operation?: { id: string; phase: "pending" | "unknown" | "active" | "rollback_pending" | "rolled_back"; action: "activate" | "rollback" };
1686
+ }
1687
+
1688
+ export interface TelephonyInboundMenu {
1689
+ /** Saved single-digit spoken menu before forwarding. */
1690
+ kind: "keypad";
1691
+ prompt: string;
1692
+ choices: Array<{ id: string; key: string; to: string }>;
1693
+ timeout_seconds: number;
1694
+ /** null hangs up; otherwise the ID of one saved choice. */
1695
+ timeout_choice_id: string | null;
1696
+ }
1697
+ export type TelephonyInboundForward = {
1698
+ max_duration_seconds: number;
1699
+ recording: boolean;
1700
+ } & ({ to: string; menu?: never } | { to?: never; menu: TelephonyInboundMenu });
1701
+
1702
+ export type TelephonyInboundBindingUpdate = {
1703
+ expected_version: number;
1704
+ activate_carrier_route?: boolean;
1705
+ rollback_carrier_route?: boolean;
1706
+ /** Persist the original operation ID; recover it instead of inventing a new one. */
1707
+ carrier_operation_id?: string;
1708
+ } & ({ enabled: false } | {
1709
+ enabled: true;
1710
+ project_id: string;
1711
+ agent_id: string;
1712
+ agent_release_id: string;
1713
+ agent_profile_sha256: string;
1714
+ admission_mode?: "client" | "platform";
1715
+ agent_knowledge_receipt?: Record<string, unknown>;
1716
+ forward?: TelephonyInboundForward | null;
1717
+ ring_group?:TelephonyInboundRingGroup|null;
1718
+ });
1719
+
1636
1720
  /* ------------------------------------------------------------------------- *
1637
1721
  * Trace (compliance)
1638
1722
  * ------------------------------------------------------------------------- */
@@ -2258,13 +2342,13 @@ export class PyAI {
2258
2342
  // --- audio --------------------------------------------------------------
2259
2343
 
2260
2344
  audio = {
2261
- /** Text-to-speech. Returns the raw audio bytes (default WAV). */
2345
+ /** Text-to-speech. Returns complete audio bytes (default WAV, stream:false). */
2262
2346
  speech: async (params: SpeechParams): Promise<ArrayBuffer> => {
2263
2347
  assertActiveSpeechParams(params);
2264
2348
  const res = await this.request("/v1/audio/speech", {
2265
2349
  method: "POST",
2266
2350
  headers: this.authHeaders({ "Content-Type": "application/json" }),
2267
- body: JSON.stringify({ model: "pyai-speak", ...params }),
2351
+ body: JSON.stringify({ model: "pyai-speak", ...params, stream: params.stream ?? false }),
2268
2352
  });
2269
2353
  await validateSpeechResponse(res, params);
2270
2354
  return res.arrayBuffer();
@@ -2355,11 +2439,15 @@ export class PyAI {
2355
2439
  },
2356
2440
  /** Upload a recording with a durable retry key. Requires the current
2357
2441
  * keyed multipart job contract; never change the key after an unknown ACK. */
2358
- upload: async (params: { file: Blob; filename: string; call_id?: string; diarize?: boolean; output_formats?: Array<"json" | "srt" | "vtt"> }, opts: { idempotencyKey: string }): Promise<TranscriptionJob> => {
2442
+ upload: async (params: { file: Blob; filename: string; call_id?: string; diarize?: boolean; channel?: boolean; transcription_language?: string; output_script?: "original" | "latin"; webhook_url?: string; output_formats?: Array<"json" | "srt" | "vtt"> }, opts: { idempotencyKey: string }): Promise<TranscriptionJob> => {
2359
2443
  if (!opts.idempotencyKey || opts.idempotencyKey.length > 255 || /[\r\n]/.test(opts.idempotencyKey)) throw new Error("A valid recording retry key is required.");
2360
2444
  const form = new FormData();
2361
2445
  if (params.call_id) form.set("call_id", params.call_id);
2362
2446
  if (params.diarize !== undefined) form.set("diarize", String(params.diarize));
2447
+ if (params.channel !== undefined) form.set("channel", String(params.channel));
2448
+ if (params.transcription_language) form.set("transcription_language", params.transcription_language);
2449
+ if (params.output_script) form.set("output_script", params.output_script);
2450
+ if (params.webhook_url) form.set("webhook_url", params.webhook_url);
2363
2451
  if (params.output_formats) form.set("output_formats", params.output_formats.join(","));
2364
2452
  form.set("audio", params.file, params.filename);
2365
2453
  const response = await this.request("/v1/transcription/jobs", { method: "POST", headers: this.authHeaders({ "Idempotency-Key": opts.idempotencyKey }), body: form });
@@ -2420,6 +2508,11 @@ export class PyAI {
2420
2508
 
2421
2509
  telephony = {
2422
2510
  /** Server-side methods. Keep the PyAI key in your backend. */
2511
+ desktopEndpoints: {
2512
+ list:(input:{number_id?:string}={}):Promise<ListResponse<TelephonyDesktopEndpoint>>=>this.getJson('/v1/telephony/desktop-endpoints'+(input.number_id?'?'+new URLSearchParams({number_id:input.number_id}):'')),
2513
+ create:(input:{number_id:string;user_id:string;client_reference:string;label:string}):Promise<TelephonyDesktopEndpoint>=>this.postJson('/v1/telephony/desktop-endpoints',input),
2514
+ enroll:(id:string,input:{user_id:string},options:{idempotencyKey:string}):Promise<TelephonyDesktopEnrollment>=>this.postJson(`/v1/telephony/desktop-endpoints/${encodeURIComponent(id)}/enrollment`,input,telephonyIdempotencyHeader(options.idempotencyKey)),
2515
+ },
2423
2516
  calls: {
2424
2517
  create: (input: TelephonyCallCreate, options: { idempotencyKey: string }): Promise<TelephonyCall> =>
2425
2518
  this.postJson("/v1/telephony/calls", input, telephonyIdempotencyHeader(options.idempotencyKey)),
@@ -2432,7 +2525,7 @@ export class PyAI {
2432
2525
  return this.getJson(`/v1/telephony/calls${query.size ? `?${query}` : ""}`);
2433
2526
  },
2434
2527
  /** Durable stop intent; use get() until a terminal status is confirmed. */
2435
- hangup: (id: string): Promise<TelephonyCall> => this.postJson(`/v1/telephony/calls/${encodeURIComponent(id)}/hangup`, {}),
2528
+ hangup: (id: string, input?: {user_id:string}): Promise<TelephonyCall> => this.postJson(`/v1/telephony/calls/${encodeURIComponent(id)}/hangup`, input ?? {}),
2436
2529
  decideAdmission: (id: string, input: { decision: "accept" | "reject"; client_reference: string; max_duration_seconds: number }): Promise<TelephonyCall> =>
2437
2530
  this.postJson(`/v1/telephony/calls/${encodeURIComponent(id)}/admission`, input),
2438
2531
  recording: (id: string, options: { range?: string } = {}): Promise<Response> =>
@@ -2441,6 +2534,12 @@ export class PyAI {
2441
2534
  /** The same durable key recovers an uncertain hold command without repeating it. */
2442
2535
  setHold: (id: string, input: { user_id: string; held: boolean }, options: { idempotencyKey: string }): Promise<TelephonyCall> =>
2443
2536
  this.postJson(`/v1/telephony/calls/${encodeURIComponent(id)}/hold`, input, telephonyIdempotencyHeader(options.idempotencyKey)),
2537
+ /** Server-side keypad command for an owned switch call. Reuse the same key
2538
+ * after an unknown result; never store keypad digits in a browser journal. */
2539
+ sendDtmf: (id: string, input: { digits: string; user_id: string }, options: { idempotencyKey: string }): Promise<TelephonyCallControl> => {
2540
+ if (!/^[0-9A-D*#]{1,32}$/.test(input.digits)) throw new Error("Use 1–32 keypad digits (0–9, *, #, A–D).");
2541
+ return this.postJson(`/v1/telephony/calls/${encodeURIComponent(id)}/dtmf`, input, telephonyIdempotencyHeader(options.idempotencyKey));
2542
+ },
2444
2543
  transfers: {
2445
2544
  /** Persist the key and target before requesting a consultation. */
2446
2545
  create: (id: string, input: { to: string; mode: "warm" | "cold"; user_id: string }, options: { idempotencyKey: string }): Promise<TelephonyCall> =>
@@ -2460,7 +2559,7 @@ export class PyAI {
2460
2559
  /** Search managed inventory; country availability and ordering may be gated. */
2461
2560
  available: (
2462
2561
  params: { country?: "US" | "CA" | "IN" | "AU"; areaCode?: string; contains?: string; limit?: number } = {},
2463
- ): Promise<ListResponse<TelephonyAvailableNumber>> => {
2562
+ ): Promise<TelephonyNumberInventory> => {
2464
2563
  const q = new URLSearchParams();
2465
2564
  if (params.country) q.set("country", params.country);
2466
2565
  if (params.areaCode) q.set("area_code", params.areaCode);
@@ -2480,6 +2579,13 @@ export class PyAI {
2480
2579
  /** Route a number to an agent (`agentId: null` to unassign). */
2481
2580
  assign: (id: string, agentId: string | null): Promise<TelephonyNumber> =>
2482
2581
  this.postJson(`/v1/telephony/numbers/${encodeURIComponent(id)}/assign`, { agent_id: agentId }),
2582
+ getInboundCapabilities:(id:string):Promise<TelephonyInboundCapabilities>=>this.getJson(`/v1/telephony/numbers/${encodeURIComponent(id)}/inbound-capabilities`),
2583
+ getInboundBinding: (id: string): Promise<TelephonyInboundBinding> =>
2584
+ this.getJson(`/v1/telephony/numbers/${encodeURIComponent(id)}/inbound-binding`),
2585
+ /** Save the profile and stable operation first; after uncertainty read the
2586
+ * binding before explicitly recovering that same operation. */
2587
+ setInboundBinding: (id: string, input: TelephonyInboundBindingUpdate): Promise<TelephonyInboundBinding> =>
2588
+ this.putJson(`/v1/telephony/numbers/${encodeURIComponent(id)}/inbound-binding`, input),
2483
2589
  /** Release a number back to the carrier (idempotent). */
2484
2590
  release: async (id: string): Promise<TelephonyNumber> => {
2485
2591
  const res = await this.deleteReq(`/v1/telephony/numbers/${encodeURIComponent(id)}`);