@frequencytalk/agent 0.2.4 → 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;
@@ -589,6 +594,7 @@ declare class NativeSession {
589
594
  private joinToken;
590
595
  private keepalive;
591
596
  private homeChannelId;
597
+ private resolvedProfile;
592
598
  private producing;
593
599
  private timestamp;
594
600
  private readonly owners;
@@ -628,7 +634,8 @@ declare class NativeSession {
628
634
  * before, and on a talk frequency that channel is `broadcast_open`, so every first `speak()`
629
635
  * was refused "no transmit permission". The personal channel is matched by the agent's own
630
636
  * callsign in its name; a frequency with no personal channel for this agent (an old one, a
631
- * 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).
632
639
  */
633
640
  private defaultChannelId;
634
641
  private send;
@@ -651,10 +658,22 @@ declare class NativeSession {
651
658
  private sendKeepalive;
652
659
  /** Subscribe to a channel's streams (listening). */
653
660
  listen(channelId: string): void;
654
- /** 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. */
655
673
  startTalking(options?: {
656
674
  relayChannelIds?: string[];
657
675
  sourceKey?: string;
676
+ profile?: "voice" | "broadcast";
658
677
  }): Promise<number>;
659
678
  /** One 20 ms Opus frame onto the stream: sealed under the home channel, and each relay, as the contract requires. */
660
679
  sendOpusFrame(opus: Buffer, relayChannelIds?: string[]): void;
@@ -701,10 +720,12 @@ declare class Speaker {
701
720
  /** Speak 16-bit mono PCM at `sampleRate`; resampled to 48 kHz. */
702
721
  speakPcm(samples: Int16Array, sampleRate: number, options?: {
703
722
  relayChannelIds?: string[];
723
+ profile?: "voice" | "broadcast";
704
724
  }): Promise<void>;
705
725
  /** Speak a WAV file (16-bit PCM, any rate, mono or stereo). */
706
726
  speakWav(path: string, options?: {
707
727
  relayChannelIds?: string[];
728
+ profile?: "voice" | "broadcast";
708
729
  }): Promise<void>;
709
730
  close(): void;
710
731
  }
@@ -746,6 +767,119 @@ declare class Listener {
746
767
  close(): void;
747
768
  }
748
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
+
749
883
  /**
750
884
  * WAV in and out: 16-bit PCM, any rate and channel count on read (callers resample and
751
885
  * downmix); 48 kHz mono on write. Enough for an agent that plays a file it rendered and
@@ -833,8 +967,14 @@ declare class Agent {
833
967
  closeSession(frequencyId: string): Promise<void>;
834
968
  speaker(session: NativeSession): Speaker;
835
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;
836
976
  close(): Promise<void>;
837
977
  }
838
978
 
839
- 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 };
840
- 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 };
package/dist/index.js CHANGED
@@ -149,6 +149,7 @@ var Realtime = class {
149
149
  bufferSize;
150
150
  subscriptions = /* @__PURE__ */ new Set();
151
151
  waiters = [];
152
+ listeners = /* @__PURE__ */ new Set();
152
153
  /** Opens the socket and resolves once the server has answered a ping (the connect path has finished). */
153
154
  async connect() {
154
155
  this.closedByCaller = false;
@@ -188,6 +189,12 @@ var Realtime = class {
188
189
  }
189
190
  }
190
191
  this.options.onEvent?.(event);
192
+ for (const listener of this.listeners) listener(event);
193
+ }
194
+ /** Receive every event as it arrives, beside `onEvent` (0.2.5); returns the detach function. */
195
+ on(listener) {
196
+ this.listeners.add(listener);
197
+ return () => this.listeners.delete(listener);
191
198
  }
192
199
  async onClose(code) {
193
200
  this.ws = null;
@@ -5143,6 +5150,7 @@ var NativeSession = class {
5143
5150
  joinToken = "";
5144
5151
  keepalive = null;
5145
5152
  homeChannelId = null;
5153
+ resolvedProfile = null;
5146
5154
  producing = null;
5147
5155
  timestamp = 0;
5148
5156
  owners = /* @__PURE__ */ new Map();
@@ -5228,10 +5236,16 @@ var NativeSession = class {
5228
5236
  * before, and on a talk frequency that channel is `broadcast_open`, so every first `speak()`
5229
5237
  * was refused "no transmit permission". The personal channel is matched by the agent's own
5230
5238
  * callsign in its name; a frequency with no personal channel for this agent (an old one, a
5231
- * station) falls back to the default group channel as before.
5239
+ * station) falls back to the default group channel as before. A station's broadcaster homes on
5240
+ * the program channel (Public) instead (0.2.5).
5232
5241
  */
5233
5242
  async defaultChannelId() {
5234
5243
  const channels = await this.frequencies.channels(this.frequencyId);
5244
+ const detail = await this.frequencies.get(this.frequencyId).catch(() => null);
5245
+ if (detail?.mode === "broadcast" && detail.mayBroadcast === true) {
5246
+ const program = channels.find((c) => c.isDefault)?.id;
5247
+ if (program) return program;
5248
+ }
5235
5249
  const personal = channels.filter((c) => c.kind === "personal");
5236
5250
  let own = personal.length === 1 ? personal[0] : void 0;
5237
5251
  if (personal.length > 1) {
@@ -5384,10 +5398,35 @@ var NativeSession = class {
5384
5398
  listen(channelId) {
5385
5399
  this.send({ type: "subscribeChannel", channelId });
5386
5400
  }
5387
- /** Announce a voice stream on the home channel (plus relays), and return its stream id. */
5401
+ /**
5402
+ * The capture profile a stream on the home channel should carry when the caller did not say
5403
+ * (0.2.5): `broadcast` when this agent is the station's broadcaster speaking on its program
5404
+ * channel, `voice` everywhere else (contract §6, "Who sends the program"). That is: a broadcast
5405
+ * frequency, `mayBroadcast` true, and the home is the frequency's default channel (Public). A
5406
+ * voice from a broadcaster on Public is mixed UNDER the program rather than being it, and the
5407
+ * Service Manager gates it like any talker, which is how an agent DJ's show went unheard there
5408
+ * on 2026-11-27. Read once per session: the answer rides the join token, so it cannot change
5409
+ * until a re-tune anyway.
5410
+ */
5411
+ async programProfile() {
5412
+ if (this.resolvedProfile) return this.resolvedProfile;
5413
+ let profile = "voice";
5414
+ try {
5415
+ const detail = await this.frequencies.get(this.frequencyId);
5416
+ if (detail.mode === "broadcast" && detail.mayBroadcast === true) {
5417
+ const channels = await this.frequencies.channels(this.frequencyId);
5418
+ if (channels.find((c) => c.isDefault)?.id === this.homeChannelId) profile = "broadcast";
5419
+ }
5420
+ } catch {
5421
+ }
5422
+ this.resolvedProfile = profile;
5423
+ return profile;
5424
+ }
5425
+ /** Announce a stream on the home channel (plus relays), and return its stream id. `profile` defaults to `programProfile()`'s answer. */
5388
5426
  async startTalking(options = {}) {
5389
5427
  if (!this.homeChannelId) throw new Error("native: not open");
5390
- this.send({ type: "nativeProduce", channelId: this.homeChannelId, relayChannelIds: options.relayChannelIds ?? [], sourceKey: options.sourceKey ?? "agent", profile: "voice" });
5428
+ const profile = options.profile ?? await this.programProfile();
5429
+ this.send({ type: "nativeProduce", channelId: this.homeChannelId, relayChannelIds: options.relayChannelIds ?? [], sourceKey: options.sourceKey ?? "agent", profile });
5391
5430
  const produced = await this.waitFor("nativeProduced", 1e4);
5392
5431
  this.producing = { streamId: Number(produced.streamId), channelId: this.homeChannelId };
5393
5432
  this.events.splice(this.events.indexOf(produced), 1);
@@ -5724,7 +5763,7 @@ var Speaker = class {
5724
5763
  async speakPcm(samples, sampleRate, options = {}) {
5725
5764
  const codec = await this.opus();
5726
5765
  const pcm = resample(samples, sampleRate, SAMPLE_RATE);
5727
- await this.session.startTalking({ relayChannelIds: options.relayChannelIds });
5766
+ await this.session.startTalking({ relayChannelIds: options.relayChannelIds, ...options.profile ? { profile: options.profile } : {} });
5728
5767
  try {
5729
5768
  const started = Date.now();
5730
5769
  let i = 0;
@@ -5820,6 +5859,231 @@ var Listener = class {
5820
5859
  }
5821
5860
  };
5822
5861
 
5862
+ // src/stream.ts
5863
+ function installationOf(token) {
5864
+ try {
5865
+ const claims = JSON.parse(Buffer.from(token.split(".")[1] ?? "", "base64url").toString());
5866
+ return typeof claims.installation_id === "string" ? claims.installation_id : null;
5867
+ } catch {
5868
+ return null;
5869
+ }
5870
+ }
5871
+ function parseMediaPlaylist(text, base) {
5872
+ const lines = text.split(/\r?\n/);
5873
+ let sequence = 0;
5874
+ let targetDuration = 2;
5875
+ let pending = 0;
5876
+ let variant = null;
5877
+ const segments = [];
5878
+ for (const raw of lines) {
5879
+ const line = raw.trim();
5880
+ if (!line) continue;
5881
+ if (line.startsWith("#EXT-X-MEDIA-SEQUENCE:")) sequence = Number(line.slice(22)) || 0;
5882
+ else if (line.startsWith("#EXT-X-TARGETDURATION:")) targetDuration = Number(line.slice(22)) || targetDuration;
5883
+ else if (line.startsWith("#EXTINF:")) pending = Number.parseFloat(line.slice(8)) || 0;
5884
+ else if (!line.startsWith("#")) {
5885
+ const url = new URL(line, base).toString();
5886
+ if (new URL(url).pathname.endsWith(".m3u8")) {
5887
+ variant ??= url;
5888
+ continue;
5889
+ }
5890
+ segments.push({ sequence: sequence++, durationSeconds: pending, url });
5891
+ pending = 0;
5892
+ }
5893
+ }
5894
+ return { targetDuration, segments, variant };
5895
+ }
5896
+ var StationStream = class {
5897
+ constructor(client, realtime, frequencyId, options = {}) {
5898
+ this.client = client;
5899
+ this.realtime = realtime;
5900
+ this.frequencyId = frequencyId;
5901
+ this.options = options;
5902
+ }
5903
+ client;
5904
+ realtime;
5905
+ frequencyId;
5906
+ options;
5907
+ mediaUrl = null;
5908
+ installationId = null;
5909
+ lastSequence = -1;
5910
+ running = false;
5911
+ loop = null;
5912
+ offAir = false;
5913
+ detachRealtime = null;
5914
+ ended = null;
5915
+ collectors = /* @__PURE__ */ new Set();
5916
+ /** Wakes the poll loop's wait early, so `stop()` does not sit out a five-second Retry-After. */
5917
+ wake = null;
5918
+ stats = { segments: 0, bytes: 0, remints: 0, playlistErrors: 0, segmentErrors: 0 };
5919
+ /** The last ticket minted (quality, live state). */
5920
+ ticket = null;
5921
+ /** Why the stream ended, or null while it runs (and before `start()`). */
5922
+ get endedWith() {
5923
+ return this.ended;
5924
+ }
5925
+ /**
5926
+ * Mint a ticket and start following the stream. `takeover: true` is for a deliberate start
5927
+ * only (contract §6): it takes the account's stream from wherever else it is playing. Throws
5928
+ * the mint's refusal as a `FrequencyError` (`OFF_AIR` with `retryAfterSeconds`,
5929
+ * `STREAM_CONFLICT`, `STATION_FULL`, `NOT_MEMBER`).
5930
+ */
5931
+ async start(options = {}) {
5932
+ if (this.running) throw new Error("stream: already started");
5933
+ const ticket = await this.mint(options.takeover === true);
5934
+ this.ended = null;
5935
+ this.running = true;
5936
+ this.detachRealtime = this.realtime?.on((event) => this.onRealtime(event)) ?? null;
5937
+ this.loop = this.follow();
5938
+ return ticket;
5939
+ }
5940
+ async mint(takeover) {
5941
+ const body = { ...takeover ? { takeover: true } : {}, ...this.options.monitor ? { monitor: true } : {} };
5942
+ const ticket = await this.client.request(`/v1/listen/${encodeURIComponent(this.frequencyId)}/ticket`, { method: "POST", ...Object.keys(body).length ? { body } : {} });
5943
+ this.installationId = installationOf(await this.client.accessToken());
5944
+ this.ticket = ticket;
5945
+ this.mediaUrl = new URL(ticket.playlistUrl, this.client.baseUrl).toString();
5946
+ return ticket;
5947
+ }
5948
+ onRealtime(event) {
5949
+ const e = event;
5950
+ if (e.type !== "stream.displaced" || e.frequencyId !== this.frequencyId) return;
5951
+ if (e.installationId && this.installationId && e.installationId !== this.installationId) return;
5952
+ this.end("displaced");
5953
+ }
5954
+ end(reason) {
5955
+ if (!this.running) return;
5956
+ this.running = false;
5957
+ this.ended = reason;
5958
+ this.detachRealtime?.();
5959
+ this.detachRealtime = null;
5960
+ this.wake?.();
5961
+ this.options.onEnd?.(reason);
5962
+ }
5963
+ async follow() {
5964
+ while (this.running) {
5965
+ let wait = 2e3;
5966
+ try {
5967
+ wait = await this.poll();
5968
+ } catch {
5969
+ this.stats.playlistErrors += 1;
5970
+ }
5971
+ if (this.running) await new Promise((resolve) => {
5972
+ const timer = setTimeout(resolve, wait);
5973
+ this.wake = () => {
5974
+ clearTimeout(timer);
5975
+ resolve();
5976
+ };
5977
+ });
5978
+ this.wake = null;
5979
+ }
5980
+ }
5981
+ /** One playlist poll; answers how long to wait before the next. */
5982
+ async poll() {
5983
+ const res = await fetch(this.mediaUrl);
5984
+ if (res.status === 401) {
5985
+ const code = await res.json().then((j) => j.error?.code).catch(() => void 0);
5986
+ if (code !== "TICKET_EXPIRED") {
5987
+ this.end("signed_out");
5988
+ return 0;
5989
+ }
5990
+ try {
5991
+ await this.mint(false);
5992
+ this.stats.remints += 1;
5993
+ } catch (err) {
5994
+ if (err instanceof FrequencyError && err.code === "STREAM_CONFLICT") this.end("conflict");
5995
+ else if (err instanceof FrequencyError && err.status === 401) this.end("signed_out");
5996
+ else if (err instanceof FrequencyError && err.code === "OFF_AIR") return this.setOffAir(err.retryAfterSeconds);
5997
+ return 2e3;
5998
+ }
5999
+ return 0;
6000
+ }
6001
+ if (res.status === 503) return this.setOffAir(Number(res.headers.get("retry-after")) || 5);
6002
+ if (!res.ok) {
6003
+ this.stats.playlistErrors += 1;
6004
+ return 2e3;
6005
+ }
6006
+ if (this.offAir) {
6007
+ this.offAir = false;
6008
+ this.options.onOffAir?.(false);
6009
+ }
6010
+ const playlist = parseMediaPlaylist(await res.text(), this.mediaUrl);
6011
+ if (playlist.variant) {
6012
+ this.mediaUrl = playlist.variant;
6013
+ return 0;
6014
+ }
6015
+ const fresh = this.lastSequence < 0 ? playlist.segments.slice(-1) : playlist.segments.filter((s) => s.sequence > this.lastSequence);
6016
+ for (const segment of fresh) {
6017
+ if (!this.running) break;
6018
+ this.lastSequence = segment.sequence;
6019
+ try {
6020
+ const got = await fetch(segment.url);
6021
+ if (!got.ok) {
6022
+ this.stats.segmentErrors += 1;
6023
+ continue;
6024
+ }
6025
+ const data = Buffer.from(await got.arrayBuffer());
6026
+ this.stats.segments += 1;
6027
+ this.stats.bytes += data.length;
6028
+ const out = { sequence: segment.sequence, durationSeconds: segment.durationSeconds, data };
6029
+ this.options.onSegment?.(out);
6030
+ for (const collect of this.collectors) collect(out);
6031
+ } catch {
6032
+ this.stats.segmentErrors += 1;
6033
+ }
6034
+ }
6035
+ return Math.max(500, playlist.targetDuration * 1e3 / 2);
6036
+ }
6037
+ setOffAir(retryAfterSeconds2) {
6038
+ if (!this.offAir) {
6039
+ this.offAir = true;
6040
+ this.options.onOffAir?.(true);
6041
+ }
6042
+ return Math.max(1, retryAfterSeconds2 ?? 5) * 1e3;
6043
+ }
6044
+ /** Receive every segment as it arrives, beside `onSegment`; returns the detach function. */
6045
+ attach(listener) {
6046
+ this.collectors.add(listener);
6047
+ return () => this.collectors.delete(listener);
6048
+ }
6049
+ /** Collect `seconds` of the stream (by segment duration) and return it as one MPEG-TS buffer; ends early if the stream does. */
6050
+ async record(seconds) {
6051
+ if (!this.running) throw new Error("stream: not started");
6052
+ const parts = [];
6053
+ let total = 0;
6054
+ await new Promise((resolve) => {
6055
+ const detach = this.attach((segment) => {
6056
+ parts.push(segment.data);
6057
+ total += segment.durationSeconds;
6058
+ if (total >= seconds) finish();
6059
+ });
6060
+ const watch = setInterval(() => {
6061
+ if (!this.running) finish();
6062
+ }, 250);
6063
+ const deadline = setTimeout(finish, (seconds + 30) * 1e3);
6064
+ function finish() {
6065
+ detach();
6066
+ clearInterval(watch);
6067
+ clearTimeout(deadline);
6068
+ resolve();
6069
+ }
6070
+ });
6071
+ return { data: Buffer.concat(parts), seconds: Math.round(total * 100) / 100, segments: parts.length };
6072
+ }
6073
+ /** Stop following and release the account's stream at once (`DELETE` the ticket). */
6074
+ async stop() {
6075
+ const wasRunning = this.running;
6076
+ this.running = false;
6077
+ this.detachRealtime?.();
6078
+ this.detachRealtime = null;
6079
+ if (wasRunning) this.ended = "stopped";
6080
+ this.wake?.();
6081
+ await this.loop?.catch(() => void 0);
6082
+ this.loop = null;
6083
+ await this.client.request(`/v1/listen/${encodeURIComponent(this.frequencyId)}/ticket`, { method: "DELETE" }).catch(() => void 0);
6084
+ }
6085
+ };
6086
+
5823
6087
  // src/config.ts
5824
6088
  import { readFile as readFile2 } from "fs/promises";
5825
6089
  import { homedir } from "os";
@@ -5899,6 +6163,15 @@ var Agent = class _Agent {
5899
6163
  listener(session, options) {
5900
6164
  return new Listener(session, options);
5901
6165
  }
6166
+ /**
6167
+ * A station's listen stream, as its audience hears it (0.2.5): the program mixed with every voice
6168
+ * on Public. Call `start()` to mint and follow it, `stop()` to release it. Membership is
6169
+ * required, as for any listener; `monitor: true` is for the station's own staff.
6170
+ */
6171
+ stream(frequencyId, options) {
6172
+ this.realtime.subscribe(frequencyId);
6173
+ return new StationStream(this.client, this.realtime, frequencyId, options);
6174
+ }
5902
6175
  async close() {
5903
6176
  for (const id of [...this.sessions.keys()]) await this.closeSession(id);
5904
6177
  this.realtime.close();
@@ -5920,12 +6193,14 @@ export {
5920
6193
  Realtime,
5921
6194
  SAMPLE_RATE,
5922
6195
  Speaker,
6196
+ StationStream,
5923
6197
  WS_CLOSE_SESSION_REVOKED,
5924
6198
  WS_CLOSE_UNAUTHORIZED,
5925
6199
  createOpus,
5926
6200
  downmix,
5927
6201
  frames,
5928
6202
  loadKey,
6203
+ parseMediaPlaylist,
5929
6204
  readWav,
5930
6205
  resample,
5931
6206
  writeWav