@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.
@@ -153,6 +153,7 @@ var Realtime = class {
153
153
  bufferSize;
154
154
  subscriptions = /* @__PURE__ */ new Set();
155
155
  waiters = [];
156
+ listeners = /* @__PURE__ */ new Set();
156
157
  /** Opens the socket and resolves once the server has answered a ping (the connect path has finished). */
157
158
  async connect() {
158
159
  this.closedByCaller = false;
@@ -192,6 +193,12 @@ var Realtime = class {
192
193
  }
193
194
  }
194
195
  this.options.onEvent?.(event);
196
+ for (const listener of this.listeners) listener(event);
197
+ }
198
+ /** Receive every event as it arrives, beside `onEvent` (0.2.5); returns the detach function. */
199
+ on(listener) {
200
+ this.listeners.add(listener);
201
+ return () => this.listeners.delete(listener);
195
202
  }
196
203
  async onClose(code) {
197
204
  this.ws = null;
@@ -5147,6 +5154,7 @@ var NativeSession = class {
5147
5154
  joinToken = "";
5148
5155
  keepalive = null;
5149
5156
  homeChannelId = null;
5157
+ resolvedProfile = null;
5150
5158
  producing = null;
5151
5159
  timestamp = 0;
5152
5160
  owners = /* @__PURE__ */ new Map();
@@ -5232,10 +5240,16 @@ var NativeSession = class {
5232
5240
  * before, and on a talk frequency that channel is `broadcast_open`, so every first `speak()`
5233
5241
  * was refused "no transmit permission". The personal channel is matched by the agent's own
5234
5242
  * callsign in its name; a frequency with no personal channel for this agent (an old one, a
5235
- * station) falls back to the default group channel as before.
5243
+ * station) falls back to the default group channel as before. A station's broadcaster homes on
5244
+ * the program channel (Public) instead (0.2.5).
5236
5245
  */
5237
5246
  async defaultChannelId() {
5238
5247
  const channels = await this.frequencies.channels(this.frequencyId);
5248
+ const detail = await this.frequencies.get(this.frequencyId).catch(() => null);
5249
+ if (detail?.mode === "broadcast" && detail.mayBroadcast === true) {
5250
+ const program = channels.find((c) => c.isDefault)?.id;
5251
+ if (program) return program;
5252
+ }
5239
5253
  const personal = channels.filter((c) => c.kind === "personal");
5240
5254
  let own = personal.length === 1 ? personal[0] : void 0;
5241
5255
  if (personal.length > 1) {
@@ -5388,10 +5402,35 @@ var NativeSession = class {
5388
5402
  listen(channelId) {
5389
5403
  this.send({ type: "subscribeChannel", channelId });
5390
5404
  }
5391
- /** Announce a voice stream on the home channel (plus relays), and return its stream id. */
5405
+ /**
5406
+ * The capture profile a stream on the home channel should carry when the caller did not say
5407
+ * (0.2.5): `broadcast` when this agent is the station's broadcaster speaking on its program
5408
+ * channel, `voice` everywhere else (contract §6, "Who sends the program"). That is: a broadcast
5409
+ * frequency, `mayBroadcast` true, and the home is the frequency's default channel (Public). A
5410
+ * voice from a broadcaster on Public is mixed UNDER the program rather than being it, and the
5411
+ * Service Manager gates it like any talker, which is how an agent DJ's show went unheard there
5412
+ * on 2026-11-27. Read once per session: the answer rides the join token, so it cannot change
5413
+ * until a re-tune anyway.
5414
+ */
5415
+ async programProfile() {
5416
+ if (this.resolvedProfile) return this.resolvedProfile;
5417
+ let profile = "voice";
5418
+ try {
5419
+ const detail = await this.frequencies.get(this.frequencyId);
5420
+ if (detail.mode === "broadcast" && detail.mayBroadcast === true) {
5421
+ const channels = await this.frequencies.channels(this.frequencyId);
5422
+ if (channels.find((c) => c.isDefault)?.id === this.homeChannelId) profile = "broadcast";
5423
+ }
5424
+ } catch {
5425
+ }
5426
+ this.resolvedProfile = profile;
5427
+ return profile;
5428
+ }
5429
+ /** Announce a stream on the home channel (plus relays), and return its stream id. `profile` defaults to `programProfile()`'s answer. */
5392
5430
  async startTalking(options = {}) {
5393
5431
  if (!this.homeChannelId) throw new Error("native: not open");
5394
- this.send({ type: "nativeProduce", channelId: this.homeChannelId, relayChannelIds: options.relayChannelIds ?? [], sourceKey: options.sourceKey ?? "agent", profile: "voice" });
5432
+ const profile = options.profile ?? await this.programProfile();
5433
+ this.send({ type: "nativeProduce", channelId: this.homeChannelId, relayChannelIds: options.relayChannelIds ?? [], sourceKey: options.sourceKey ?? "agent", profile });
5395
5434
  const produced = await this.waitFor("nativeProduced", 1e4);
5396
5435
  this.producing = { streamId: Number(produced.streamId), channelId: this.homeChannelId };
5397
5436
  this.events.splice(this.events.indexOf(produced), 1);
@@ -5728,7 +5767,7 @@ var Speaker = class {
5728
5767
  async speakPcm(samples, sampleRate, options = {}) {
5729
5768
  const codec = await this.opus();
5730
5769
  const pcm = resample(samples, sampleRate, SAMPLE_RATE);
5731
- await this.session.startTalking({ relayChannelIds: options.relayChannelIds });
5770
+ await this.session.startTalking({ relayChannelIds: options.relayChannelIds, ...options.profile ? { profile: options.profile } : {} });
5732
5771
  try {
5733
5772
  const started = Date.now();
5734
5773
  let i = 0;
@@ -5824,6 +5863,231 @@ var Listener = class {
5824
5863
  }
5825
5864
  };
5826
5865
 
5866
+ // src/stream.ts
5867
+ function installationOf(token) {
5868
+ try {
5869
+ const claims = JSON.parse(Buffer.from(token.split(".")[1] ?? "", "base64url").toString());
5870
+ return typeof claims.installation_id === "string" ? claims.installation_id : null;
5871
+ } catch {
5872
+ return null;
5873
+ }
5874
+ }
5875
+ function parseMediaPlaylist(text2, base) {
5876
+ const lines = text2.split(/\r?\n/);
5877
+ let sequence = 0;
5878
+ let targetDuration = 2;
5879
+ let pending = 0;
5880
+ let variant = null;
5881
+ const segments = [];
5882
+ for (const raw of lines) {
5883
+ const line = raw.trim();
5884
+ if (!line) continue;
5885
+ if (line.startsWith("#EXT-X-MEDIA-SEQUENCE:")) sequence = Number(line.slice(22)) || 0;
5886
+ else if (line.startsWith("#EXT-X-TARGETDURATION:")) targetDuration = Number(line.slice(22)) || targetDuration;
5887
+ else if (line.startsWith("#EXTINF:")) pending = Number.parseFloat(line.slice(8)) || 0;
5888
+ else if (!line.startsWith("#")) {
5889
+ const url = new URL(line, base).toString();
5890
+ if (new URL(url).pathname.endsWith(".m3u8")) {
5891
+ variant ??= url;
5892
+ continue;
5893
+ }
5894
+ segments.push({ sequence: sequence++, durationSeconds: pending, url });
5895
+ pending = 0;
5896
+ }
5897
+ }
5898
+ return { targetDuration, segments, variant };
5899
+ }
5900
+ var StationStream = class {
5901
+ constructor(client, realtime, frequencyId, options = {}) {
5902
+ this.client = client;
5903
+ this.realtime = realtime;
5904
+ this.frequencyId = frequencyId;
5905
+ this.options = options;
5906
+ }
5907
+ client;
5908
+ realtime;
5909
+ frequencyId;
5910
+ options;
5911
+ mediaUrl = null;
5912
+ installationId = null;
5913
+ lastSequence = -1;
5914
+ running = false;
5915
+ loop = null;
5916
+ offAir = false;
5917
+ detachRealtime = null;
5918
+ ended = null;
5919
+ collectors = /* @__PURE__ */ new Set();
5920
+ /** Wakes the poll loop's wait early, so `stop()` does not sit out a five-second Retry-After. */
5921
+ wake = null;
5922
+ stats = { segments: 0, bytes: 0, remints: 0, playlistErrors: 0, segmentErrors: 0 };
5923
+ /** The last ticket minted (quality, live state). */
5924
+ ticket = null;
5925
+ /** Why the stream ended, or null while it runs (and before `start()`). */
5926
+ get endedWith() {
5927
+ return this.ended;
5928
+ }
5929
+ /**
5930
+ * Mint a ticket and start following the stream. `takeover: true` is for a deliberate start
5931
+ * only (contract §6): it takes the account's stream from wherever else it is playing. Throws
5932
+ * the mint's refusal as a `FrequencyError` (`OFF_AIR` with `retryAfterSeconds`,
5933
+ * `STREAM_CONFLICT`, `STATION_FULL`, `NOT_MEMBER`).
5934
+ */
5935
+ async start(options = {}) {
5936
+ if (this.running) throw new Error("stream: already started");
5937
+ const ticket = await this.mint(options.takeover === true);
5938
+ this.ended = null;
5939
+ this.running = true;
5940
+ this.detachRealtime = this.realtime?.on((event) => this.onRealtime(event)) ?? null;
5941
+ this.loop = this.follow();
5942
+ return ticket;
5943
+ }
5944
+ async mint(takeover) {
5945
+ const body = { ...takeover ? { takeover: true } : {}, ...this.options.monitor ? { monitor: true } : {} };
5946
+ const ticket = await this.client.request(`/v1/listen/${encodeURIComponent(this.frequencyId)}/ticket`, { method: "POST", ...Object.keys(body).length ? { body } : {} });
5947
+ this.installationId = installationOf(await this.client.accessToken());
5948
+ this.ticket = ticket;
5949
+ this.mediaUrl = new URL(ticket.playlistUrl, this.client.baseUrl).toString();
5950
+ return ticket;
5951
+ }
5952
+ onRealtime(event) {
5953
+ const e = event;
5954
+ if (e.type !== "stream.displaced" || e.frequencyId !== this.frequencyId) return;
5955
+ if (e.installationId && this.installationId && e.installationId !== this.installationId) return;
5956
+ this.end("displaced");
5957
+ }
5958
+ end(reason) {
5959
+ if (!this.running) return;
5960
+ this.running = false;
5961
+ this.ended = reason;
5962
+ this.detachRealtime?.();
5963
+ this.detachRealtime = null;
5964
+ this.wake?.();
5965
+ this.options.onEnd?.(reason);
5966
+ }
5967
+ async follow() {
5968
+ while (this.running) {
5969
+ let wait = 2e3;
5970
+ try {
5971
+ wait = await this.poll();
5972
+ } catch {
5973
+ this.stats.playlistErrors += 1;
5974
+ }
5975
+ if (this.running) await new Promise((resolve) => {
5976
+ const timer = setTimeout(resolve, wait);
5977
+ this.wake = () => {
5978
+ clearTimeout(timer);
5979
+ resolve();
5980
+ };
5981
+ });
5982
+ this.wake = null;
5983
+ }
5984
+ }
5985
+ /** One playlist poll; answers how long to wait before the next. */
5986
+ async poll() {
5987
+ const res = await fetch(this.mediaUrl);
5988
+ if (res.status === 401) {
5989
+ const code = await res.json().then((j) => j.error?.code).catch(() => void 0);
5990
+ if (code !== "TICKET_EXPIRED") {
5991
+ this.end("signed_out");
5992
+ return 0;
5993
+ }
5994
+ try {
5995
+ await this.mint(false);
5996
+ this.stats.remints += 1;
5997
+ } catch (err) {
5998
+ if (err instanceof FrequencyError && err.code === "STREAM_CONFLICT") this.end("conflict");
5999
+ else if (err instanceof FrequencyError && err.status === 401) this.end("signed_out");
6000
+ else if (err instanceof FrequencyError && err.code === "OFF_AIR") return this.setOffAir(err.retryAfterSeconds);
6001
+ return 2e3;
6002
+ }
6003
+ return 0;
6004
+ }
6005
+ if (res.status === 503) return this.setOffAir(Number(res.headers.get("retry-after")) || 5);
6006
+ if (!res.ok) {
6007
+ this.stats.playlistErrors += 1;
6008
+ return 2e3;
6009
+ }
6010
+ if (this.offAir) {
6011
+ this.offAir = false;
6012
+ this.options.onOffAir?.(false);
6013
+ }
6014
+ const playlist = parseMediaPlaylist(await res.text(), this.mediaUrl);
6015
+ if (playlist.variant) {
6016
+ this.mediaUrl = playlist.variant;
6017
+ return 0;
6018
+ }
6019
+ const fresh = this.lastSequence < 0 ? playlist.segments.slice(-1) : playlist.segments.filter((s) => s.sequence > this.lastSequence);
6020
+ for (const segment of fresh) {
6021
+ if (!this.running) break;
6022
+ this.lastSequence = segment.sequence;
6023
+ try {
6024
+ const got = await fetch(segment.url);
6025
+ if (!got.ok) {
6026
+ this.stats.segmentErrors += 1;
6027
+ continue;
6028
+ }
6029
+ const data = Buffer.from(await got.arrayBuffer());
6030
+ this.stats.segments += 1;
6031
+ this.stats.bytes += data.length;
6032
+ const out = { sequence: segment.sequence, durationSeconds: segment.durationSeconds, data };
6033
+ this.options.onSegment?.(out);
6034
+ for (const collect of this.collectors) collect(out);
6035
+ } catch {
6036
+ this.stats.segmentErrors += 1;
6037
+ }
6038
+ }
6039
+ return Math.max(500, playlist.targetDuration * 1e3 / 2);
6040
+ }
6041
+ setOffAir(retryAfterSeconds2) {
6042
+ if (!this.offAir) {
6043
+ this.offAir = true;
6044
+ this.options.onOffAir?.(true);
6045
+ }
6046
+ return Math.max(1, retryAfterSeconds2 ?? 5) * 1e3;
6047
+ }
6048
+ /** Receive every segment as it arrives, beside `onSegment`; returns the detach function. */
6049
+ attach(listener) {
6050
+ this.collectors.add(listener);
6051
+ return () => this.collectors.delete(listener);
6052
+ }
6053
+ /** Collect `seconds` of the stream (by segment duration) and return it as one MPEG-TS buffer; ends early if the stream does. */
6054
+ async record(seconds) {
6055
+ if (!this.running) throw new Error("stream: not started");
6056
+ const parts = [];
6057
+ let total = 0;
6058
+ await new Promise((resolve) => {
6059
+ const detach = this.attach((segment) => {
6060
+ parts.push(segment.data);
6061
+ total += segment.durationSeconds;
6062
+ if (total >= seconds) finish();
6063
+ });
6064
+ const watch = setInterval(() => {
6065
+ if (!this.running) finish();
6066
+ }, 250);
6067
+ const deadline = setTimeout(finish, (seconds + 30) * 1e3);
6068
+ function finish() {
6069
+ detach();
6070
+ clearInterval(watch);
6071
+ clearTimeout(deadline);
6072
+ resolve();
6073
+ }
6074
+ });
6075
+ return { data: Buffer.concat(parts), seconds: Math.round(total * 100) / 100, segments: parts.length };
6076
+ }
6077
+ /** Stop following and release the account's stream at once (`DELETE` the ticket). */
6078
+ async stop() {
6079
+ const wasRunning = this.running;
6080
+ this.running = false;
6081
+ this.detachRealtime?.();
6082
+ this.detachRealtime = null;
6083
+ if (wasRunning) this.ended = "stopped";
6084
+ this.wake?.();
6085
+ await this.loop?.catch(() => void 0);
6086
+ this.loop = null;
6087
+ await this.client.request(`/v1/listen/${encodeURIComponent(this.frequencyId)}/ticket`, { method: "DELETE" }).catch(() => void 0);
6088
+ }
6089
+ };
6090
+
5827
6091
  // src/agent.ts
5828
6092
  var Agent = class _Agent {
5829
6093
  client;
@@ -5877,6 +6141,15 @@ var Agent = class _Agent {
5877
6141
  listener(session, options) {
5878
6142
  return new Listener(session, options);
5879
6143
  }
6144
+ /**
6145
+ * A station's listen stream, as its audience hears it (0.2.5): the program mixed with every voice
6146
+ * on Public. Call `start()` to mint and follow it, `stop()` to release it. Membership is
6147
+ * required, as for any listener; `monitor: true` is for the station's own staff.
6148
+ */
6149
+ stream(frequencyId, options) {
6150
+ this.realtime.subscribe(frequencyId);
6151
+ return new StationStream(this.client, this.realtime, frequencyId, options);
6152
+ }
5880
6153
  async close() {
5881
6154
  for (const id of [...this.sessions.keys()]) await this.closeSession(id);
5882
6155
  this.realtime.close();
@@ -5959,6 +6232,22 @@ function registerTools(server, agent) {
5959
6232
  async (body) => run(() => agent.frequencies.create({ ...body, ageConfirmed: true, termsAccepted: true }))
5960
6233
  );
5961
6234
  server.tool("frequency_leave", "Leave a frequency (membership).", { frequencyId: z19.string() }, async ({ frequencyId }) => run(() => agent.frequencies.leave(frequencyId).then(() => "left")));
6235
+ server.tool("frequency_members", "A frequency's members and their roles (owner, admin, user; staffRole for a company's station staff).", { frequencyId: z19.string() }, async ({ frequencyId }) => run(() => agent.frequencies.members(frequencyId)));
6236
+ server.tool(
6237
+ "frequency_invite",
6238
+ "Invite somebody to a frequency by callsign, Station ID (FT-XXXX) or email. They accept or decline it themselves.",
6239
+ { frequencyId: z19.string(), handleOrEmail: z19.string().min(1) },
6240
+ async ({ frequencyId, handleOrEmail }) => run(() => agent.frequencies.invite(frequencyId, handleOrEmail))
6241
+ );
6242
+ server.tool(
6243
+ "frequency_set_role",
6244
+ "Make a member an admin, or an admin an ordinary member (owner or admin only). Admins manage channels, members and invitations; on a station, an admin also sends the program.",
6245
+ { frequencyId: z19.string(), userId: z19.string(), role: z19.enum(["admin", "user"]) },
6246
+ async ({ frequencyId, userId, role }) => run(() => agent.frequencies.changeRole(frequencyId, userId, role))
6247
+ );
6248
+ server.tool("invitation_list", "Invitations waiting on this agent, with the frequency and who sent each.", {}, async () => run(() => agent.frequencies.myInvitations()));
6249
+ server.tool("invitation_accept", "Accept an invitation: the agent becomes a member of its frequency.", { invitationId: z19.string() }, async ({ invitationId }) => run(() => agent.frequencies.acceptInvitation(invitationId)));
6250
+ server.tool("invitation_decline", "Decline an invitation.", { invitationId: z19.string() }, async ({ invitationId }) => run(() => agent.frequencies.declineInvitation(invitationId)));
5962
6251
  server.tool("contacts_list", "The agent's contacts.", {}, async () => run(() => agent.contacts.list()));
5963
6252
  server.tool("contacts_search", "Find people and agents by callsign or Station ID.", { query: z19.string().min(1) }, async ({ query }) => run(() => agent.contacts.search(query)));
5964
6253
  server.tool("contacts_request", "Ask somebody to be a contact, by Station ID (FT-XXXX).", { stationId: z19.string() }, async ({ stationId }) => run(() => agent.contacts.request(stationId)));
@@ -5996,7 +6285,7 @@ function registerTools(server, agent) {
5996
6285
  server.tool("phone_live", "The calls ringing or live on a frequency's phone channels, from the server.", { frequencyId: z19.string() }, async ({ frequencyId }) => run(() => agent.phone.live(frequencyId)));
5997
6286
  server.tool(
5998
6287
  "audio_speak",
5999
- "Speak a WAV file (16-bit PCM) on a frequency's default channel over the native voice transport. Opens the session if needed.",
6288
+ "Speak a WAV file (16-bit PCM) on a frequency over the native voice transport. Opens the session if needed. On a station where this agent may broadcast (frequency_list's mayBroadcast), it goes out as the station's program; otherwise as a voice.",
6000
6289
  { frequencyId: z19.string(), wavPath: z19.string() },
6001
6290
  async ({ frequencyId, wavPath }) => run(async () => {
6002
6291
  const session = await agent.session(frequencyId);
@@ -6029,6 +6318,22 @@ function registerTools(server, agent) {
6029
6318
  })
6030
6319
  );
6031
6320
  server.tool("audio_close", "Close the native session on a frequency.", { frequencyId: z19.string() }, async ({ frequencyId }) => run(() => agent.closeSession(frequencyId).then(() => "closed")));
6321
+ server.tool(
6322
+ "stream_record",
6323
+ "Record a station's listen stream, as its audience hears it (the program mixed with every voice on Public), for `seconds`, to an MPEG-TS file (AAC audio) at `path`. Set `monitor` when this agent is the station's staff checking its own air. Takes the account's stream from wherever else it plays only when `takeover` is set.",
6324
+ { frequencyId: z19.string(), seconds: z19.number().int().min(2).max(600).default(30), path: z19.string(), monitor: z19.boolean().default(false), takeover: z19.boolean().default(false) },
6325
+ async ({ frequencyId, seconds, path, monitor, takeover }) => run(async () => {
6326
+ const stream = agent.stream(frequencyId, { monitor });
6327
+ const ticket = await stream.start({ takeover });
6328
+ try {
6329
+ const recorded = await stream.record(seconds);
6330
+ await writeFile(path, recorded.data);
6331
+ return { path, seconds: recorded.seconds, segments: recorded.segments, quality: ticket.quality ?? "standard", liveState: ticket.liveState, ended: stream.endedWith };
6332
+ } finally {
6333
+ await stream.stop();
6334
+ }
6335
+ })
6336
+ );
6032
6337
  server.tool("credit_balance", "The prepaid credit that pays for what this agent does, with today's daily prices and the rails a top-up can use.", {}, async () => run(() => agent.client.credit()));
6033
6338
  server.tool(
6034
6339
  "credit_topup_challenge",