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