@frequencytalk/agent 0.1.1 → 0.2.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.
package/dist/index.d.ts CHANGED
@@ -344,6 +344,68 @@ declare class Calls {
344
344
  waitForRing(timeoutMs?: number): Promise<IncomingRing>;
345
345
  }
346
346
 
347
+ /**
348
+ * Calls on phone channels (capability `phone-calls`, contract section 24 "Calls"): a phone
349
+ * number bought for a frequency rings its channel; any member who may talk on that channel,
350
+ * an agent included, answers, and the caller is then heard on the channel as the line (listen
351
+ * to the phone channel with `session.listen(channelId)`) and hears whatever the agent speaks
352
+ * there (`Speaker`). Hang up from either side ends it.
353
+ *
354
+ * Rings arrive on the realtime socket as `phone.call` events on the FREQUENCY lane, so the
355
+ * socket must be subscribed to the frequency first: `waitForRing` does that for you.
356
+ */
357
+ interface PhoneRing {
358
+ type: "phone.call";
359
+ frequencyId: string;
360
+ channelId: string;
361
+ phoneNumberId: string;
362
+ callId: string;
363
+ state: "ringing" | "answering" | "active" | "ended";
364
+ from: {
365
+ e164: string;
366
+ display: string;
367
+ };
368
+ answeredByUserId?: string | null;
369
+ expiresAt?: string;
370
+ }
371
+ interface PhoneCall {
372
+ id: string;
373
+ phoneNumberId: string;
374
+ frequencyId: string;
375
+ channelId: string;
376
+ direction: "inbound" | "outbound";
377
+ state: "ringing" | "answering" | "active" | "ended";
378
+ from: {
379
+ e164: string;
380
+ display: string;
381
+ };
382
+ to: {
383
+ e164: string;
384
+ display: string;
385
+ };
386
+ answeredByUserId: string | null;
387
+ startedAt: string;
388
+ answeredAt: string | null;
389
+ endedAt: string | null;
390
+ hangupCause: string | null;
391
+ expiresAt: string | null;
392
+ }
393
+ declare class Phone {
394
+ private readonly client;
395
+ private readonly realtime?;
396
+ constructor(client: FrequencyClient, realtime?: Realtime | undefined);
397
+ /** Calls ringing on phone channels right now, from the socket's recent events (one frequency, or all). */
398
+ ringing(frequencyId?: string): PhoneRing[];
399
+ /** Subscribes to the frequency and resolves with the next ring on one of its phone channels. */
400
+ waitForRing(frequencyId: string, timeoutMs?: number): Promise<PhoneRing>;
401
+ /** Answer a ringing call: the caller joins the phone channel as the line. 409 when somebody else got there first. */
402
+ answer(callId: string): Promise<PhoneCall>;
403
+ /** Hang up a live call, or refuse one still ringing. */
404
+ hangUp(callId: string): Promise<PhoneCall>;
405
+ /** The calls ringing or live on a frequency's phone channels (the server's list; use after a reconnect). */
406
+ live(frequencyId: string): Promise<PhoneCall[]>;
407
+ }
408
+
347
409
  /**
348
410
  * A native-transport session on one frequency (audio-routing-contract.md "Transports"; the
349
411
  * wire in `@frequency/shared/native-codec`). THIS IS THE REFERENCE CLIENT: the load
@@ -560,13 +622,23 @@ interface Heard {
560
622
  samples: Int16Array;
561
623
  firstTimestamp: number;
562
624
  }
625
+ interface ListenerOptions {
626
+ /**
627
+ * Record the session's own stream too. Off by default: the node sends a connection its own
628
+ * audio back whenever it listens on the channel its stream is homed on (self-monitoring, the
629
+ * audio-routing contract), which on a one-channel room such as a call is always. An agent
630
+ * transcribing a call wants the other side, not itself (0.1.2).
631
+ */
632
+ includeOwn?: boolean;
633
+ }
563
634
  declare class Listener {
564
635
  private readonly session;
636
+ private readonly options;
565
637
  private codec;
566
638
  private readonly streams;
567
639
  private detach;
568
- constructor(session: NativeSession);
569
- /** Start recording everything the session hears. */
640
+ constructor(session: NativeSession, options?: ListenerOptions);
641
+ /** Start recording everything the session hears (its own stream excepted, see `ListenerOptions`). */
570
642
  start(): Promise<void>;
571
643
  /** Stop and return what was heard, per stream. */
572
644
  stop(): Heard[];
@@ -644,6 +716,7 @@ declare class Agent {
644
716
  readonly contacts: Contacts;
645
717
  readonly chat: Chat;
646
718
  readonly calls: Calls;
719
+ readonly phone: Phone;
647
720
  private readonly sessions;
648
721
  private constructor();
649
722
  /** Sign in with the key and open the socket. */
@@ -654,9 +727,9 @@ declare class Agent {
654
727
  }): Promise<NativeSession>;
655
728
  closeSession(frequencyId: string): Promise<void>;
656
729
  speaker(session: NativeSession): Speaker;
657
- listener(session: NativeSession): Listener;
730
+ listener(session: NativeSession, options?: ListenerOptions): Listener;
658
731
  close(): Promise<void>;
659
732
  }
660
733
 
661
- export { Agent, Calls, Chat, Contacts, FRAME_SAMPLES, Frequencies, FrequencyClient, FrequencyError, Listener, NativeSession, PaymentRequired, Realtime, SAMPLE_RATE, Speaker, WS_CLOSE_SESSION_REVOKED, WS_CLOSE_UNAUTHORIZED, createOpus, downmix, frames, loadKey, readWav, resample, writeWav };
662
- export type { AgentKeySource, AgentOptions, ApiClient, ChannelSummary, ChatMessage, Contact, FrequencyClientOptions, FrequencySummary, Heard, IncomingRing, NativeAudioFrame, NativeReceiveStats, NativeResyncStats, NativeSessionOptions, NativeStreamAnnouncement, NativeTransportBlock, OpusCodec, PlacedCall, RealtimeEvent, RealtimeOptions, RequestOptions, RosterMember, TuneResult };
734
+ export { Agent, Calls, Chat, Contacts, FRAME_SAMPLES, Frequencies, FrequencyClient, FrequencyError, Listener, NativeSession, PaymentRequired, Phone, Realtime, SAMPLE_RATE, Speaker, WS_CLOSE_SESSION_REVOKED, WS_CLOSE_UNAUTHORIZED, createOpus, downmix, frames, loadKey, readWav, resample, writeWav };
735
+ export type { AgentKeySource, AgentOptions, ApiClient, ChannelSummary, ChatMessage, Contact, FrequencyClientOptions, FrequencySummary, Heard, IncomingRing, ListenerOptions, NativeAudioFrame, NativeReceiveStats, NativeResyncStats, NativeSessionOptions, NativeStreamAnnouncement, NativeTransportBlock, OpusCodec, PhoneCall, PhoneRing, PlacedCall, RealtimeEvent, RealtimeOptions, RequestOptions, RosterMember, TuneResult };
package/dist/index.js CHANGED
@@ -426,6 +426,45 @@ var Calls = class {
426
426
  }
427
427
  };
428
428
 
429
+ // src/phone.ts
430
+ var Phone = class {
431
+ constructor(client, realtime) {
432
+ this.client = client;
433
+ this.realtime = realtime;
434
+ }
435
+ client;
436
+ realtime;
437
+ /** Calls ringing on phone channels right now, from the socket's recent events (one frequency, or all). */
438
+ ringing(frequencyId) {
439
+ if (!this.realtime) return [];
440
+ const latest = /* @__PURE__ */ new Map();
441
+ for (const e of this.realtime.recent((e2) => e2.type === "phone.call")) {
442
+ const ring = e;
443
+ if (frequencyId && ring.frequencyId !== frequencyId) continue;
444
+ latest.set(ring.callId, ring);
445
+ }
446
+ return [...latest.values()].filter((r) => r.state === "ringing");
447
+ }
448
+ /** Subscribes to the frequency and resolves with the next ring on one of its phone channels. */
449
+ waitForRing(frequencyId, timeoutMs = 12e4) {
450
+ if (!this.realtime) throw new Error("phone.waitForRing needs the realtime socket");
451
+ this.realtime.subscribe(frequencyId);
452
+ return this.realtime.waitFor((e) => e.type === "phone.call" && e.state === "ringing" && e.frequencyId === frequencyId, timeoutMs).then((e) => e);
453
+ }
454
+ /** Answer a ringing call: the caller joins the phone channel as the line. 409 when somebody else got there first. */
455
+ answer(callId) {
456
+ return this.client.request(`/v1/phone-calls/${encodeURIComponent(callId)}/answer`, { method: "POST" });
457
+ }
458
+ /** Hang up a live call, or refuse one still ringing. */
459
+ hangUp(callId) {
460
+ return this.client.request(`/v1/phone-calls/${encodeURIComponent(callId)}/hangup`, { method: "POST" });
461
+ }
462
+ /** The calls ringing or live on a frequency's phone channels (the server's list; use after a reconnect). */
463
+ live(frequencyId) {
464
+ return this.client.request(`/v1/frequencies/${encodeURIComponent(frequencyId)}/phone-calls`);
465
+ }
466
+ };
467
+
429
468
  // src/audio/native.ts
430
469
  import { createSocket } from "dgram";
431
470
  import WebSocket2 from "ws";
@@ -511,6 +550,30 @@ var PHONE_PLANS = {
511
550
  phone_pro: { key: "phone_pro", name: "Phone Line Pro", priceUsdCents: 3999, minutes: 3e3 }
512
551
  };
513
552
  var PHONE_PLAN_KEYS = Object.keys(PHONE_PLANS);
553
+ var PhoneCallStateSchema = z2.enum(["ringing", "answering", "active", "ended"]);
554
+ var PhoneCallDirectionSchema = z2.enum(["inbound", "outbound"]);
555
+ var PhoneCallPartySchema = z2.object({
556
+ e164: z2.string(),
557
+ display: z2.string()
558
+ });
559
+ var PhoneCallSchema = z2.object({
560
+ id: z2.string(),
561
+ phoneNumberId: z2.string(),
562
+ frequencyId: z2.string(),
563
+ channelId: z2.string(),
564
+ direction: PhoneCallDirectionSchema,
565
+ state: PhoneCallStateSchema,
566
+ from: PhoneCallPartySchema,
567
+ to: PhoneCallPartySchema,
568
+ answeredByUserId: z2.string().nullable(),
569
+ startedAt: z2.string(),
570
+ answeredAt: z2.string().nullable(),
571
+ endedAt: z2.string().nullable(),
572
+ /** `no_answer` when the ring ran out, else the carrier's own cause word; null while live. */
573
+ hangupCause: z2.string().nullable(),
574
+ /** When the ring ends if nobody answers (ISO 8601); null once the call is past ringing. */
575
+ expiresAt: z2.string().nullable()
576
+ });
514
577
 
515
578
  // ../shared/dist/contacts.js
516
579
  import { z as z4 } from "zod";
@@ -2689,6 +2752,23 @@ var ServerToClientEventSchema = z10.discriminatedUnion("type", [
2689
2752
  muted: z10.boolean(),
2690
2753
  byUserId: z10.string()
2691
2754
  }),
2755
+ // A call on a phone channel (capability phone-calls, contract §24). Delivered to the
2756
+ // channel's audience (its roster and the frequency's staff): `ringing` is the moment to ring
2757
+ // and offer Answer, `answering` names who took it (stop ringing everywhere else), `active`
2758
+ // means both directions carry audio, `ended` clears the row. One call per line at a time,
2759
+ // so (channelId) identifies the live call as well as callId does; callId is what the
2760
+ // answer and hangup routes take. `expiresAt` rides on `ringing` only.
2761
+ z10.object({
2762
+ type: z10.literal("phone.call"),
2763
+ frequencyId: z10.string(),
2764
+ channelId: z10.string(),
2765
+ phoneNumberId: z10.string(),
2766
+ callId: z10.string(),
2767
+ state: z10.enum(["ringing", "answering", "active", "ended"]),
2768
+ from: z10.object({ e164: z10.string(), display: z10.string() }),
2769
+ answeredByUserId: z10.string().nullable().optional(),
2770
+ expiresAt: z10.string().optional()
2771
+ }),
2692
2772
  // Covers group create/rename/delete/membership changes and channel<->group link
2693
2773
  // changes — clients just refetch groups + channels for the frequency on any of these,
2694
2774
  // same as the channel.* events above, rather than diffing individual fields over the wire.
@@ -3981,6 +4061,9 @@ var ERROR_CODES = {
3981
4061
  PHONE_NOT_CONFIGURED: { status: 503, summary: "This deployment has no carrier configured, so no phone number can be searched, bought or released." },
3982
4062
  PHONE_NUMBER_UNAVAILABLE: { status: 409, summary: "The number was taken between the search and the purchase, or is already ours. Search again." },
3983
4063
  PHONE_SUBSCRIPTION_REQUIRED: { status: 402, summary: "Buying a number needs a paid, unclaimed phone line subscription (capability phone-numbers)." },
4064
+ PHONE_CALL_NOT_RINGING: { status: 409, summary: "The phone call is not ringing any more: it was answered, hung up, or rang out (capability phone-calls)." },
4065
+ PHONE_CALL_TAKEN: { status: 409, summary: "Somebody else answered this phone call first (capability phone-calls)." },
4066
+ PHONE_CALL_ENDED: { status: 409, summary: "The phone call has already ended (capability phone-calls)." },
3984
4067
  CARRIER_ERROR: { status: 502, summary: "The carrier refused or did not answer. Nothing was changed on our side unless the message says otherwise; retry later." },
3985
4068
  PROTECTED_MEMBER: {
3986
4069
  status: 403,
@@ -5109,18 +5192,21 @@ var Speaker = class {
5109
5192
 
5110
5193
  // src/listener.ts
5111
5194
  var Listener = class {
5112
- constructor(session) {
5195
+ constructor(session, options = {}) {
5113
5196
  this.session = session;
5197
+ this.options = options;
5114
5198
  }
5115
5199
  session;
5200
+ options;
5116
5201
  codec = null;
5117
5202
  streams = /* @__PURE__ */ new Map();
5118
5203
  detach = null;
5119
- /** Start recording everything the session hears. */
5204
+ /** Start recording everything the session hears (its own stream excepted, see `ListenerOptions`). */
5120
5205
  async start() {
5121
5206
  this.codec ??= await createOpus();
5122
5207
  const codec = this.codec;
5123
5208
  const handler = (frame) => {
5209
+ if (!this.options.includeOwn && frame.connectionId === this.session.connectionId) return;
5124
5210
  let s = this.streams.get(frame.streamId);
5125
5211
  if (!s) {
5126
5212
  s = { connectionId: frame.connectionId, chunks: [], lastTimestamp: null, first: frame.timestamp };
@@ -5206,6 +5292,7 @@ var Agent = class _Agent {
5206
5292
  contacts;
5207
5293
  chat;
5208
5294
  calls;
5295
+ phone;
5209
5296
  sessions = /* @__PURE__ */ new Map();
5210
5297
  constructor(options) {
5211
5298
  this.client = new FrequencyClient(options);
@@ -5214,6 +5301,7 @@ var Agent = class _Agent {
5214
5301
  this.contacts = new Contacts(this.client);
5215
5302
  this.chat = new Chat(this.client, this.realtime);
5216
5303
  this.calls = new Calls(this.client, this.realtime);
5304
+ this.phone = new Phone(this.client, this.realtime);
5217
5305
  }
5218
5306
  /** Sign in with the key and open the socket. */
5219
5307
  static async connect(options) {
@@ -5241,8 +5329,8 @@ var Agent = class _Agent {
5241
5329
  speaker(session) {
5242
5330
  return new Speaker(session);
5243
5331
  }
5244
- listener(session) {
5245
- return new Listener(session);
5332
+ listener(session, options) {
5333
+ return new Listener(session, options);
5246
5334
  }
5247
5335
  async close() {
5248
5336
  for (const id of [...this.sessions.keys()]) await this.closeSession(id);
@@ -5261,6 +5349,7 @@ export {
5261
5349
  Listener,
5262
5350
  NativeSession,
5263
5351
  PaymentRequired,
5352
+ Phone,
5264
5353
  Realtime,
5265
5354
  SAMPLE_RATE,
5266
5355
  Speaker,