@frequencytalk/agent 0.2.3 → 0.2.5

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
@@ -130,11 +130,14 @@ declare class Realtime {
130
130
  private readonly bufferSize;
131
131
  private readonly subscriptions;
132
132
  private readonly waiters;
133
+ private readonly listeners;
133
134
  constructor(client: FrequencyClient, options?: RealtimeOptions);
134
135
  /** Opens the socket and resolves once the server has answered a ping (the connect path has finished). */
135
136
  connect(): Promise<void>;
136
137
  private open;
137
138
  private onMessage;
139
+ /** Receive every event as it arrives, beside `onEvent` (0.2.5); returns the detach function. */
140
+ on(listener: (event: RealtimeEvent) => void): () => void;
138
141
  private onClose;
139
142
  send(frame: ClientToServerEvent): void;
140
143
  subscribe(frequencyId: string): void;
@@ -159,6 +162,8 @@ interface FrequencySummary {
159
162
  mode: "push_to_talk" | "broadcast" | "direct";
160
163
  publiclyListable?: boolean;
161
164
  description?: string | null;
165
+ /** Whether this agent may send the station's PROGRAM (the broadcast profile) here: owner, admin, or on-air company staff (contract §6). On the list and the detail; absent elsewhere. */
166
+ mayBroadcast?: boolean;
162
167
  }
163
168
  interface ChannelSummary {
164
169
  id: string;
@@ -494,9 +499,20 @@ declare class Phone {
494
499
  * application's problem; `misattributed` or `undecryptable` climbing is a key or announcement
495
500
  * problem; `installs` is the number that proves a rotation was survived.
496
501
  *
497
- * Wire version 1 is sent and received. Version 2 audio (one seal, the content key wrapped per
498
- * channel) is announced by capability `native-transport-v2` and is counted here as
499
- * `unsupportedVersion`; peers on v2 are the next step for this package (handoff).
502
+ * Wire version 1 is sent; versions 1 AND 2 are received (0.2.4). Contract §7c has a sender
503
+ * choose v2 from the container's accept list alone, never from who is listening, so every
504
+ * receiver on a v2 container must read it: a v1-only receiver hears nothing from a v2 talker
505
+ * (measured 2026-11-27, Switchboard for Apple to an SDK agent: 319 of 319 datagrams dropped).
506
+ * v2 is two packet kinds, told apart by the CLEARTEXT flag because the payload type is sealed:
507
+ * - a KEY PACKET (0x22, FLAG_CONTENT_KEY): the talkspurt's content key `K_s`, sealed under a
508
+ * carrying channel's key exactly as v1 audio is. Filed per (connection, stream) after the
509
+ * owner check, by generation (contentKeyId's low byte); current and previous are kept, so
510
+ * audio in flight across a mid-talkspurt rotation still opens;
511
+ * - AUDIO (0x02): sealed once under `K_s`; the header names the stream's HOME wire id and the
512
+ * generation. The home is learned from the first audio that opens under a stream's key, NOT
513
+ * from the announcement: `nativeStream.channelId` is the channel THIS listener matched on,
514
+ * which for a relay listener is the relay, not the sender's home. The opened streamId must
515
+ * be the stream whose key opened it, and the owner check applies to both kinds.
500
516
  */
501
517
  type MediaEvent = {
502
518
  type: string;
@@ -532,8 +548,12 @@ interface NativeResyncStats {
532
548
  interface NativeReceiveStats {
533
549
  /** Audio frames opened and attributed, handed to the listeners. */
534
550
  frames: number;
535
- /** Packets whose version byte this build does not read (wire v2). */
551
+ /** Packets whose version or flag bits this build does not read (a future version, or a shape no version defines). */
536
552
  unsupportedVersion: number;
553
+ /** Wire-v2 content keys installed from key packets (one per key packet that opened and was attributed). */
554
+ contentKeys: number;
555
+ /** Wire-v2 audio for which no content key is held yet: a listener joining mid-talkspurt hears from the next key packet (at most 200 ms). */
556
+ awaitingContentKey: number;
537
557
  /** Packets on a channel this session holds no key for. */
538
558
  unknownChannel: number;
539
559
  /** Packets that did not open under the channel key: a stale ring on one side. */
@@ -574,9 +594,12 @@ declare class NativeSession {
574
594
  private joinToken;
575
595
  private keepalive;
576
596
  private homeChannelId;
597
+ private resolvedProfile;
577
598
  private producing;
578
599
  private timestamp;
579
600
  private readonly owners;
601
+ /** `${connectionId}:${streamId}` -> that stream's content keys (wire v2). */
602
+ private readonly contentKeys;
580
603
  private readonly pending;
581
604
  /** The last 500 signalling events, oldest first. A probe reads them; `waitFor` searches them. */
582
605
  readonly events: MediaEvent[];
@@ -611,7 +634,8 @@ declare class NativeSession {
611
634
  * before, and on a talk frequency that channel is `broadcast_open`, so every first `speak()`
612
635
  * was refused "no transmit permission". The personal channel is matched by the agent's own
613
636
  * callsign in its name; a frequency with no personal channel for this agent (an old one, a
614
- * station) falls back to the default group channel as before.
637
+ * station) falls back to the default group channel as before. A station's broadcaster homes on
638
+ * the program channel (Public) instead (0.2.5).
615
639
  */
616
640
  private defaultChannelId;
617
641
  private send;
@@ -634,15 +658,39 @@ declare class NativeSession {
634
658
  private sendKeepalive;
635
659
  /** Subscribe to a channel's streams (listening). */
636
660
  listen(channelId: string): void;
637
- /** Announce a voice stream on the home channel (plus relays), and return its stream id. */
661
+ /**
662
+ * The capture profile a stream on the home channel should carry when the caller did not say
663
+ * (0.2.5): `broadcast` when this agent is the station's broadcaster speaking on its program
664
+ * channel, `voice` everywhere else (contract §6, "Who sends the program"). That is: a broadcast
665
+ * frequency, `mayBroadcast` true, and the home is the frequency's default channel (Public). A
666
+ * voice from a broadcaster on Public is mixed UNDER the program rather than being it, and the
667
+ * Service Manager gates it like any talker, which is how an agent DJ's show went unheard there
668
+ * on 2026-11-27. Read once per session: the answer rides the join token, so it cannot change
669
+ * until a re-tune anyway.
670
+ */
671
+ private programProfile;
672
+ /** Announce a stream on the home channel (plus relays), and return its stream id. `profile` defaults to `programProfile()`'s answer. */
638
673
  startTalking(options?: {
639
674
  relayChannelIds?: string[];
640
675
  sourceKey?: string;
676
+ profile?: "voice" | "broadcast";
641
677
  }): Promise<number>;
642
678
  /** One 20 ms Opus frame onto the stream: sealed under the home channel, and each relay, as the contract requires. */
643
679
  sendOpusFrame(opus: Buffer, relayChannelIds?: string[]): void;
644
680
  stopTalking(): void;
645
681
  private onPacket;
682
+ /** A v2 key packet that opened under a channel key: attribute it, then file `K_s` under the stream's home. */
683
+ private onContentKey;
684
+ /**
685
+ * v2 audio: sealed under `K_s`, found by (connection, home wire id, generation). The stream bound
686
+ * to that home is tried first; a connection's streams whose home is not yet learned are tried
687
+ * after (one connection rarely carries more than one), and the first that opens with its own
688
+ * streamId inside binds the home.
689
+ */
690
+ private onV2Audio;
691
+ /** The owner check and hand-off every opened audio frame goes through, whichever wire version carried it. */
692
+ private deliver;
693
+ private forgetStream;
646
694
  /**
647
695
  * The backstop for a missed `nativeKeysRotated` (the node announces a rotation only once it
648
696
  * has a baseline to compare against, so a rotation inside its first poll window is never
@@ -672,10 +720,12 @@ declare class Speaker {
672
720
  /** Speak 16-bit mono PCM at `sampleRate`; resampled to 48 kHz. */
673
721
  speakPcm(samples: Int16Array, sampleRate: number, options?: {
674
722
  relayChannelIds?: string[];
723
+ profile?: "voice" | "broadcast";
675
724
  }): Promise<void>;
676
725
  /** Speak a WAV file (16-bit PCM, any rate, mono or stereo). */
677
726
  speakWav(path: string, options?: {
678
727
  relayChannelIds?: string[];
728
+ profile?: "voice" | "broadcast";
679
729
  }): Promise<void>;
680
730
  close(): void;
681
731
  }
@@ -717,6 +767,119 @@ declare class Listener {
717
767
  close(): void;
718
768
  }
719
769
 
770
+ /**
771
+ * A station's LISTEN STREAM (contract §6, "Listening: HLS egress"), the way Tuner hears a
772
+ * station: the program plus every voice on Public, mixed by the media node, as the HLS stream
773
+ * listeners get. The native session hears each talker separately and does not carry the program
774
+ * mix; this is what an agent wants to hear a station AS ITS AUDIENCE DOES (to monitor its own
775
+ * show, transcribe a station, or check what went out).
776
+ *
777
+ * The obligations the contract puts on a listen client, each kept here:
778
+ * - mint a connect ticket first and read every refusal off that plain request
779
+ * (`503 OFF_AIR`, `409 STREAM_CONFLICT`, `409 STATION_FULL`) before any media request;
780
+ * - send `takeover` only for a deliberate start (`start({ takeover: true })`), never from the
781
+ * automatic re-mint this class makes after `401 TICKET_EXPIRED`;
782
+ * - treat `stream.displaced` for this install as final: stop, never re-mint with takeover;
783
+ * - hand the playlist URL out verbatim (the mint picks `live` or `hifi`), and follow it;
784
+ * - DELETE the ticket on an explicit stop, so the account's next player starts at once.
785
+ *
786
+ * Segments are MPEG-TS carrying AAC, handed over as they arrive (`onSegment`) or collected by
787
+ * `record()`. Concatenated, they are one playable `.ts` file that ffmpeg and most transcription
788
+ * tools read directly; this package bundles no AAC decoder.
789
+ */
790
+ interface ListenTicket {
791
+ ticket: string;
792
+ playlistUrl: string;
793
+ expiresInSeconds: number;
794
+ quality?: "standard" | "premium";
795
+ liveState?: string;
796
+ }
797
+ interface StreamSegment {
798
+ /** The HLS media sequence number. */
799
+ sequence: number;
800
+ /** Seconds of audio, from the playlist's EXTINF. */
801
+ durationSeconds: number;
802
+ /** MPEG-TS bytes. */
803
+ data: Buffer;
804
+ }
805
+ type StreamStopReason = "stopped" | "displaced" | "conflict" | "signed_out";
806
+ interface StationStreamOptions {
807
+ /** Hear what listeners hear as station staff (contract §6 "The air monitor"): opens no listener-ledger row and never counts toward the station's limit. */
808
+ monitor?: boolean;
809
+ onSegment?: (segment: StreamSegment) => void;
810
+ /** The stream ended on its own (displaced, a conflict on re-mint, or the session signed out). Not called for `stop()`. */
811
+ onEnd?: (reason: StreamStopReason) => void;
812
+ /** The station went off air (true) or came back (false). Polling continues on the server's Retry-After. */
813
+ onOffAir?: (offAir: boolean) => void;
814
+ }
815
+ interface StationStreamStats {
816
+ segments: number;
817
+ bytes: number;
818
+ /** New tickets minted after `401 TICKET_EXPIRED`. */
819
+ remints: number;
820
+ playlistErrors: number;
821
+ segmentErrors: number;
822
+ }
823
+ /** A playlist's segments, with their sequence numbers and durations. */
824
+ declare function parseMediaPlaylist(text: string, base: string): {
825
+ targetDuration: number;
826
+ segments: Array<{
827
+ sequence: number;
828
+ durationSeconds: number;
829
+ url: string;
830
+ }>;
831
+ variant: string | null;
832
+ };
833
+ declare class StationStream {
834
+ private readonly client;
835
+ private readonly realtime;
836
+ readonly frequencyId: string;
837
+ private readonly options;
838
+ private mediaUrl;
839
+ private installationId;
840
+ private lastSequence;
841
+ private running;
842
+ private loop;
843
+ private offAir;
844
+ private detachRealtime;
845
+ private ended;
846
+ private readonly collectors;
847
+ /** Wakes the poll loop's wait early, so `stop()` does not sit out a five-second Retry-After. */
848
+ private wake;
849
+ readonly stats: StationStreamStats;
850
+ /** The last ticket minted (quality, live state). */
851
+ ticket: ListenTicket | null;
852
+ constructor(client: FrequencyClient, realtime: Realtime | null, frequencyId: string, options?: StationStreamOptions);
853
+ /** Why the stream ended, or null while it runs (and before `start()`). */
854
+ get endedWith(): StreamStopReason | null;
855
+ /**
856
+ * Mint a ticket and start following the stream. `takeover: true` is for a deliberate start
857
+ * only (contract §6): it takes the account's stream from wherever else it is playing. Throws
858
+ * the mint's refusal as a `FrequencyError` (`OFF_AIR` with `retryAfterSeconds`,
859
+ * `STREAM_CONFLICT`, `STATION_FULL`, `NOT_MEMBER`).
860
+ */
861
+ start(options?: {
862
+ takeover?: boolean;
863
+ }): Promise<ListenTicket>;
864
+ private mint;
865
+ private onRealtime;
866
+ private end;
867
+ private follow;
868
+ /** One playlist poll; answers how long to wait before the next. */
869
+ private poll;
870
+ private setOffAir;
871
+ /** Receive every segment as it arrives, beside `onSegment`; returns the detach function. */
872
+ attach(listener: (segment: StreamSegment) => void): () => void;
873
+ /** Collect `seconds` of the stream (by segment duration) and return it as one MPEG-TS buffer; ends early if the stream does. */
874
+ record(seconds: number): Promise<{
875
+ data: Buffer;
876
+ seconds: number;
877
+ segments: number;
878
+ }>;
879
+ /** Stop following and release the account's stream at once (`DELETE` the ticket). */
880
+ stop(): Promise<void>;
881
+ }
882
+
720
883
  /**
721
884
  * WAV in and out: 16-bit PCM, any rate and channel count on read (callers resample and
722
885
  * downmix); 48 kHz mono on write. Enough for an agent that plays a file it rendered and
@@ -751,8 +914,8 @@ declare const FRAME_SAMPLES: number;
751
914
  interface OpusCodec {
752
915
  encode(pcm: Int16Array): Buffer;
753
916
  decode(packet: Buffer): Int16Array;
754
- /** Packet-loss concealment for one missing frame. */
755
- conceal(): Int16Array;
917
+ /** Packet-loss concealment for a gap: `samples` at 48 kHz (default one 20 ms frame). */
918
+ conceal(samples?: number): Int16Array;
756
919
  close(): void;
757
920
  }
758
921
  declare function createOpus(): Promise<OpusCodec>;
@@ -804,8 +967,14 @@ declare class Agent {
804
967
  closeSession(frequencyId: string): Promise<void>;
805
968
  speaker(session: NativeSession): Speaker;
806
969
  listener(session: NativeSession, options?: ListenerOptions): Listener;
970
+ /**
971
+ * A station's listen stream, as its audience hears it (0.2.5): the program mixed with every voice
972
+ * on Public. Call `start()` to mint and follow it, `stop()` to release it. Membership is
973
+ * required, as for any listener; `monitor: true` is for the station's own staff.
974
+ */
975
+ stream(frequencyId: string, options?: StationStreamOptions): StationStream;
807
976
  close(): Promise<void>;
808
977
  }
809
978
 
810
- 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 };
811
- 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 };
979
+ export { Agent, Calls, Chat, Contacts, FRAME_SAMPLES, Frequencies, FrequencyClient, FrequencyError, Listener, NativeSession, PaymentRequired, Phone, Realtime, SAMPLE_RATE, Speaker, StationStream, WS_CLOSE_SESSION_REVOKED, WS_CLOSE_UNAUTHORIZED, createOpus, downmix, frames, loadKey, parseMediaPlaylist, readWav, resample, writeWav };
980
+ export type { AgentKeySource, AgentOptions, ApiClient, ChannelSummary, ChatMessage, Contact, FrequencyClientOptions, FrequencySummary, Heard, IncomingRing, ListenTicket, ListenerOptions, NativeAudioFrame, NativeReceiveStats, NativeResyncStats, NativeSessionOptions, NativeStreamAnnouncement, NativeTransportBlock, OpusCodec, PhoneCall, PhoneRing, PlacedCall, RealtimeEvent, RealtimeOptions, RequestOptions, RosterMember, StationStreamOptions, StationStreamStats, StreamSegment, StreamStopReason, TuneResult };