@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/README.md +28 -2
- package/dist/cli.js +442 -17
- package/dist/cli.js.map +1 -1
- package/dist/index.d.ts +179 -10
- package/dist/index.js +411 -16
- package/dist/index.js.map +1 -1
- package/dist/mcp/server.js +442 -17
- package/dist/mcp/server.js.map +1 -1
- package/package.json +25 -8
- package/server.json +2 -2
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_
|
|
80
|
-
`
|
|
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;
|
|
@@ -4655,6 +4662,9 @@ var BlockedWordsSchema = z14.object({ words: z14.array(BlockedWordSchema).max(2e
|
|
|
4655
4662
|
|
|
4656
4663
|
// ../shared/dist/nativeTransport.js
|
|
4657
4664
|
var NATIVE_TRANSPORT_VERSION = 1;
|
|
4665
|
+
var NATIVE_TRANSPORT_WIRE_V2 = 2;
|
|
4666
|
+
var FLAG_CONTROL = 16;
|
|
4667
|
+
var FLAG_CONTENT_KEY = 32;
|
|
4658
4668
|
var NODE_SEQUENCE_BASE = 1n << 63n;
|
|
4659
4669
|
var HEADER = {
|
|
4660
4670
|
/** version (low nibble) + flags (high nibble). */
|
|
@@ -4713,6 +4723,19 @@ var PAYLOAD = {
|
|
|
4713
4723
|
OPUS_OFFSET: 9
|
|
4714
4724
|
};
|
|
4715
4725
|
var PAYLOAD_TYPE = { audio: 0, keepalive: 1, contentKey: 2, videoShard: 3, shareAudio: 4 };
|
|
4726
|
+
var CONTENT_KEY_PAYLOAD = {
|
|
4727
|
+
TYPE_OFFSET: 0,
|
|
4728
|
+
/** uint32. The stream whose audio `K_s` seals. */
|
|
4729
|
+
STREAM_ID_OFFSET: 1,
|
|
4730
|
+
/** uint32, 48 kHz. The talkspurt's timestamp when this key packet was sent; informational. */
|
|
4731
|
+
TIMESTAMP_OFFSET: 5,
|
|
4732
|
+
/** uint32. Monotonic per stream; its LOW BYTE is the generation an audio header carries. */
|
|
4733
|
+
CONTENT_KEY_ID_OFFSET: 9,
|
|
4734
|
+
/** 32 bytes: `K_s`, an AES-256-GCM key. */
|
|
4735
|
+
KEY_OFFSET: 13,
|
|
4736
|
+
LENGTH: 45
|
|
4737
|
+
};
|
|
4738
|
+
var SHARE_CHANNEL_ID = 4294967295;
|
|
4716
4739
|
var VIDEO_SHARD = {
|
|
4717
4740
|
TYPE_OFFSET: 0,
|
|
4718
4741
|
STREAM_ID_OFFSET: 1,
|
|
@@ -4751,8 +4774,13 @@ var PROJECTS_BY_PLATFORM = {
|
|
|
4751
4774
|
// than a rider on `broadcast` (a Windows lane) or `tuner_apple`, for the reason `broadcast` got
|
|
4752
4775
|
// one: the board enforces one in-flight task per PROJECT, so a shared lane makes one app's claim
|
|
4753
4776
|
// answer 409 AGENT_BUSY while the other holds the slot.
|
|
4777
|
+
// `switchboard_apple` is the macOS Switchboard (owner, 2026-11-27: "build switchboard for mac"):
|
|
4778
|
+
// a native build of the same product the Windows `switchboard` lane builds, developed here on the
|
|
4779
|
+
// Mac like `tuner_apple` and `broadcast_apple`. Its own lane rather than a rider on `switchboard`
|
|
4780
|
+
// (a Windows lane) or `switchboard_steamos` (the SteamOS group), for the one-in-flight reason
|
|
4781
|
+
// `broadcast_apple` records above. A Mac lane only: not in the Windows set, not in the SteamOS group.
|
|
4754
4782
|
// The SteamOS group (`STEAMOS_PROJECTS`, above) is on both platforms since 2026-11-03.
|
|
4755
|
-
mac: ["frequency", "tuner_apple", "site", "platform", "broadcast_apple", ...STEAMOS_PROJECTS],
|
|
4783
|
+
mac: ["frequency", "tuner_apple", "site", "platform", "broadcast_apple", "switchboard_apple", ...STEAMOS_PROJECTS],
|
|
4756
4784
|
// `broadcast` is its own lane rather than a rider on `windows` (2026-08-31): the board
|
|
4757
4785
|
// enforces one in-flight task per PROJECT, and `windows` already carries the Jacked
|
|
4758
4786
|
// audio-driver work, so sharing it meant a Broadcast claim answered 409 AGENT_BUSY for
|
|
@@ -5128,9 +5156,12 @@ var NativeSession = class {
|
|
|
5128
5156
|
joinToken = "";
|
|
5129
5157
|
keepalive = null;
|
|
5130
5158
|
homeChannelId = null;
|
|
5159
|
+
resolvedProfile = null;
|
|
5131
5160
|
producing = null;
|
|
5132
5161
|
timestamp = 0;
|
|
5133
5162
|
owners = /* @__PURE__ */ new Map();
|
|
5163
|
+
/** `${connectionId}:${streamId}` -> that stream's content keys (wire v2). */
|
|
5164
|
+
contentKeys = /* @__PURE__ */ new Map();
|
|
5134
5165
|
pending = [];
|
|
5135
5166
|
/** The last 500 signalling events, oldest first. A probe reads them; `waitFor` searches them. */
|
|
5136
5167
|
events = [];
|
|
@@ -5142,7 +5173,7 @@ var NativeSession = class {
|
|
|
5142
5173
|
/** The stale-key watch: consecutive packets that would not open since the last one that did, and when a refresh was last asked for. */
|
|
5143
5174
|
staleRun = 0;
|
|
5144
5175
|
lastStaleRefresh = 0;
|
|
5145
|
-
receiveStats = { frames: 0, unsupportedVersion: 0, unknownChannel: 0, undecryptable: 0, notAudio: 0, misattributed: 0 };
|
|
5176
|
+
receiveStats = { frames: 0, unsupportedVersion: 0, contentKeys: 0, awaitingContentKey: 0, unknownChannel: 0, undecryptable: 0, notAudio: 0, misattributed: 0 };
|
|
5146
5177
|
/** The node-issued datapath identity, 0 until `open()` has authenticated. */
|
|
5147
5178
|
get connectionId() {
|
|
5148
5179
|
return this.connection;
|
|
@@ -5211,10 +5242,16 @@ var NativeSession = class {
|
|
|
5211
5242
|
* before, and on a talk frequency that channel is `broadcast_open`, so every first `speak()`
|
|
5212
5243
|
* was refused "no transmit permission". The personal channel is matched by the agent's own
|
|
5213
5244
|
* callsign in its name; a frequency with no personal channel for this agent (an old one, a
|
|
5214
|
-
* 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).
|
|
5215
5247
|
*/
|
|
5216
5248
|
async defaultChannelId() {
|
|
5217
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
|
+
}
|
|
5218
5255
|
const personal = channels.filter((c) => c.kind === "personal");
|
|
5219
5256
|
let own = personal.length === 1 ? personal[0] : void 0;
|
|
5220
5257
|
if (personal.length > 1) {
|
|
@@ -5244,7 +5281,7 @@ var NativeSession = class {
|
|
|
5244
5281
|
this.owners.set(streamId, connectionId);
|
|
5245
5282
|
this.options.onStream?.({ streamId, connectionId, producerUserId: event.producerUserId, producerCallsign: event.producerCallsign, channelId: event.channelId });
|
|
5246
5283
|
}
|
|
5247
|
-
if (event.type === "nativeStreamClosed") this.
|
|
5284
|
+
if (event.type === "nativeStreamClosed") this.forgetStream(Number(event.streamId));
|
|
5248
5285
|
if (event.type === "nativeKeysRotated") this.onKeysRotated(String(event.keysetId));
|
|
5249
5286
|
for (const p of [...this.pending]) {
|
|
5250
5287
|
if (p.type === event.type) {
|
|
@@ -5367,10 +5404,35 @@ var NativeSession = class {
|
|
|
5367
5404
|
listen(channelId) {
|
|
5368
5405
|
this.send({ type: "subscribeChannel", channelId });
|
|
5369
5406
|
}
|
|
5370
|
-
/**
|
|
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. */
|
|
5371
5432
|
async startTalking(options = {}) {
|
|
5372
5433
|
if (!this.homeChannelId) throw new Error("native: not open");
|
|
5373
|
-
|
|
5434
|
+
const profile = options.profile ?? await this.programProfile();
|
|
5435
|
+
this.send({ type: "nativeProduce", channelId: this.homeChannelId, relayChannelIds: options.relayChannelIds ?? [], sourceKey: options.sourceKey ?? "agent", profile });
|
|
5374
5436
|
const produced = await this.waitFor("nativeProduced", 1e4);
|
|
5375
5437
|
this.producing = { streamId: Number(produced.streamId), channelId: this.homeChannelId };
|
|
5376
5438
|
this.events.splice(this.events.indexOf(produced), 1);
|
|
@@ -5395,12 +5457,24 @@ var NativeSession = class {
|
|
|
5395
5457
|
}
|
|
5396
5458
|
onPacket(packet) {
|
|
5397
5459
|
if (!this.native || packet.length < HEADER.LENGTH + AEAD.TAG_BYTES) return;
|
|
5398
|
-
|
|
5460
|
+
const byte0 = packet[HEADER.VERSION_FLAGS_OFFSET];
|
|
5461
|
+
const version = byte0 & 15;
|
|
5462
|
+
const flags = byte0 & 240;
|
|
5463
|
+
const connectionId = packet.readUInt32BE(HEADER.CONNECTION_ID_OFFSET);
|
|
5464
|
+
const channelNativeId = packet.readUInt32BE(HEADER.CHANNEL_ID_OFFSET);
|
|
5465
|
+
if (version === NATIVE_TRANSPORT_VERSION && flags === FLAG_CONTROL) {
|
|
5466
|
+
this.receiveStats.notAudio += 1;
|
|
5467
|
+
return;
|
|
5468
|
+
}
|
|
5469
|
+
if (version === NATIVE_TRANSPORT_WIRE_V2 && flags === 0 && channelNativeId !== SHARE_CHANNEL_ID) {
|
|
5470
|
+
this.onV2Audio(packet, connectionId, channelNativeId);
|
|
5471
|
+
return;
|
|
5472
|
+
}
|
|
5473
|
+
const keyPacket = version === NATIVE_TRANSPORT_WIRE_V2 && flags === FLAG_CONTENT_KEY;
|
|
5474
|
+
if (!keyPacket && !(version === NATIVE_TRANSPORT_VERSION && flags === 0)) {
|
|
5399
5475
|
this.receiveStats.unsupportedVersion += 1;
|
|
5400
5476
|
return;
|
|
5401
5477
|
}
|
|
5402
|
-
const connectionId = packet.readUInt32BE(HEADER.CONNECTION_ID_OFFSET);
|
|
5403
|
-
const channelNativeId = packet.readUInt32BE(HEADER.CHANNEL_ID_OFFSET);
|
|
5404
5478
|
const entry = Object.values(this.native.channelKeys.keys).find((k) => k.id === channelNativeId);
|
|
5405
5479
|
if (!entry) {
|
|
5406
5480
|
this.receiveStats.unknownChannel += 1;
|
|
@@ -5415,10 +5489,89 @@ var NativeSession = class {
|
|
|
5415
5489
|
return;
|
|
5416
5490
|
}
|
|
5417
5491
|
this.staleRun = 0;
|
|
5492
|
+
if (keyPacket) {
|
|
5493
|
+
this.onContentKey(connectionId, body);
|
|
5494
|
+
return;
|
|
5495
|
+
}
|
|
5418
5496
|
if (body.type !== PAYLOAD_TYPE.audio) {
|
|
5419
5497
|
this.receiveStats.notAudio += 1;
|
|
5420
5498
|
return;
|
|
5421
5499
|
}
|
|
5500
|
+
this.deliver(connectionId, body);
|
|
5501
|
+
}
|
|
5502
|
+
/** A v2 key packet that opened under a channel key: attribute it, then file `K_s` under the stream's home. */
|
|
5503
|
+
onContentKey(connectionId, body) {
|
|
5504
|
+
const rest = body.opus;
|
|
5505
|
+
const restLength = CONTENT_KEY_PAYLOAD.LENGTH - CONTENT_KEY_PAYLOAD.CONTENT_KEY_ID_OFFSET;
|
|
5506
|
+
if (body.type !== PAYLOAD_TYPE.contentKey || rest.length !== restLength) {
|
|
5507
|
+
this.receiveStats.notAudio += 1;
|
|
5508
|
+
return;
|
|
5509
|
+
}
|
|
5510
|
+
const owner = this.owners.get(body.streamId);
|
|
5511
|
+
if (owner === void 0 || owner !== connectionId) {
|
|
5512
|
+
this.receiveStats.misattributed += 1;
|
|
5513
|
+
return;
|
|
5514
|
+
}
|
|
5515
|
+
const contentKeyId = rest.readUInt32BE(0);
|
|
5516
|
+
const key = Buffer.from(rest.subarray(CONTENT_KEY_PAYLOAD.KEY_OFFSET - CONTENT_KEY_PAYLOAD.CONTENT_KEY_ID_OFFSET));
|
|
5517
|
+
const slot = `${connectionId}:${body.streamId}`;
|
|
5518
|
+
let stream = this.contentKeys.get(slot);
|
|
5519
|
+
if (!stream) {
|
|
5520
|
+
stream = { connectionId, streamId: body.streamId, generations: /* @__PURE__ */ new Map() };
|
|
5521
|
+
this.contentKeys.set(slot, stream);
|
|
5522
|
+
}
|
|
5523
|
+
const generation = contentKeyId & 255;
|
|
5524
|
+
const held = stream.generations.get(generation);
|
|
5525
|
+
if (held && held.contentKeyId === contentKeyId) return;
|
|
5526
|
+
stream.generations.delete(generation);
|
|
5527
|
+
stream.generations.set(generation, { contentKeyId, key });
|
|
5528
|
+
while (stream.generations.size > 2) stream.generations.delete(stream.generations.keys().next().value);
|
|
5529
|
+
this.receiveStats.contentKeys += 1;
|
|
5530
|
+
}
|
|
5531
|
+
/**
|
|
5532
|
+
* v2 audio: sealed under `K_s`, found by (connection, home wire id, generation). The stream bound
|
|
5533
|
+
* to that home is tried first; a connection's streams whose home is not yet learned are tried
|
|
5534
|
+
* after (one connection rarely carries more than one), and the first that opens with its own
|
|
5535
|
+
* streamId inside binds the home.
|
|
5536
|
+
*/
|
|
5537
|
+
onV2Audio(packet, connectionId, homeWireId) {
|
|
5538
|
+
const generation = packet[HEADER.KEY_EPOCH_OFFSET];
|
|
5539
|
+
const candidates = [];
|
|
5540
|
+
for (const entry of this.contentKeys.values()) {
|
|
5541
|
+
if (entry.connectionId !== connectionId || !entry.generations.has(generation)) continue;
|
|
5542
|
+
if (entry.homeWireId === homeWireId) candidates.unshift(entry);
|
|
5543
|
+
else if (entry.homeWireId === void 0) candidates.push(entry);
|
|
5544
|
+
}
|
|
5545
|
+
if (candidates.length === 0) {
|
|
5546
|
+
this.receiveStats.awaitingContentKey += 1;
|
|
5547
|
+
return;
|
|
5548
|
+
}
|
|
5549
|
+
for (const stream of candidates) {
|
|
5550
|
+
let body;
|
|
5551
|
+
try {
|
|
5552
|
+
body = open(packet, stream.generations.get(generation).key);
|
|
5553
|
+
} catch {
|
|
5554
|
+
continue;
|
|
5555
|
+
}
|
|
5556
|
+
if (body.type !== PAYLOAD_TYPE.audio) {
|
|
5557
|
+
this.receiveStats.notAudio += 1;
|
|
5558
|
+
return;
|
|
5559
|
+
}
|
|
5560
|
+
if (body.streamId !== stream.streamId) {
|
|
5561
|
+
this.receiveStats.misattributed += 1;
|
|
5562
|
+
return;
|
|
5563
|
+
}
|
|
5564
|
+
if (stream.homeWireId === void 0) {
|
|
5565
|
+
for (const [slot, other] of this.contentKeys) if (other !== stream && other.connectionId === connectionId && other.homeWireId === homeWireId) this.contentKeys.delete(slot);
|
|
5566
|
+
stream.homeWireId = homeWireId;
|
|
5567
|
+
}
|
|
5568
|
+
this.deliver(connectionId, body);
|
|
5569
|
+
return;
|
|
5570
|
+
}
|
|
5571
|
+
this.receiveStats.undecryptable += 1;
|
|
5572
|
+
}
|
|
5573
|
+
/** The owner check and hand-off every opened audio frame goes through, whichever wire version carried it. */
|
|
5574
|
+
deliver(connectionId, body) {
|
|
5422
5575
|
const owner = this.owners.get(body.streamId);
|
|
5423
5576
|
if (owner === void 0 || owner !== connectionId) {
|
|
5424
5577
|
this.receiveStats.misattributed += 1;
|
|
@@ -5429,6 +5582,10 @@ var NativeSession = class {
|
|
|
5429
5582
|
this.options.onAudio?.(frame);
|
|
5430
5583
|
for (const listener of this.audioListeners) listener(frame);
|
|
5431
5584
|
}
|
|
5585
|
+
forgetStream(streamId) {
|
|
5586
|
+
this.owners.delete(streamId);
|
|
5587
|
+
for (const [slot, entry] of this.contentKeys) if (entry.streamId === streamId) this.contentKeys.delete(slot);
|
|
5588
|
+
}
|
|
5432
5589
|
/**
|
|
5433
5590
|
* The backstop for a missed `nativeKeysRotated` (the node announces a rotation only once it
|
|
5434
5591
|
* has a baseline to compare against, so a rotation inside its first poll window is never
|
|
@@ -5495,7 +5652,7 @@ async function createOpus() {
|
|
|
5495
5652
|
return {
|
|
5496
5653
|
encode: (pcm) => enc.encode(Buffer.from(pcm.buffer, pcm.byteOffset, pcm.byteLength)),
|
|
5497
5654
|
decode: (packet) => toInt16(enc.decode(packet)),
|
|
5498
|
-
conceal: () => new Int16Array(
|
|
5655
|
+
conceal: (samples = FRAME_SAMPLES) => new Int16Array(samples),
|
|
5499
5656
|
close: () => enc.delete?.()
|
|
5500
5657
|
};
|
|
5501
5658
|
} catch {
|
|
@@ -5508,7 +5665,7 @@ async function createOpus() {
|
|
|
5508
5665
|
return {
|
|
5509
5666
|
encode: (pcm) => codec.encode(Buffer.from(pcm.buffer, pcm.byteOffset, pcm.byteLength), FRAME_SAMPLES),
|
|
5510
5667
|
decode: (packet) => toInt16(codec.decode(packet)),
|
|
5511
|
-
conceal: () => new Int16Array(
|
|
5668
|
+
conceal: (samples = FRAME_SAMPLES) => new Int16Array(samples),
|
|
5512
5669
|
close: () => codec.delete()
|
|
5513
5670
|
};
|
|
5514
5671
|
}
|
|
@@ -5612,7 +5769,7 @@ var Speaker = class {
|
|
|
5612
5769
|
async speakPcm(samples, sampleRate, options = {}) {
|
|
5613
5770
|
const codec = await this.opus();
|
|
5614
5771
|
const pcm = resample(samples, sampleRate, SAMPLE_RATE);
|
|
5615
|
-
await this.session.startTalking({ relayChannelIds: options.relayChannelIds });
|
|
5772
|
+
await this.session.startTalking({ relayChannelIds: options.relayChannelIds, ...options.profile ? { profile: options.profile } : {} });
|
|
5616
5773
|
try {
|
|
5617
5774
|
const started = Date.now();
|
|
5618
5775
|
let i = 0;
|
|
@@ -5657,15 +5814,17 @@ var Listener = class {
|
|
|
5657
5814
|
if (!this.options.includeOwn && frame.connectionId === this.session.connectionId) return;
|
|
5658
5815
|
let s = this.streams.get(frame.streamId);
|
|
5659
5816
|
if (!s) {
|
|
5660
|
-
s = { connectionId: frame.connectionId, chunks: [], lastTimestamp: null, first: frame.timestamp };
|
|
5817
|
+
s = { connectionId: frame.connectionId, chunks: [], lastTimestamp: null, lastSamples: 0, first: frame.timestamp };
|
|
5661
5818
|
this.streams.set(frame.streamId, s);
|
|
5662
5819
|
}
|
|
5663
5820
|
if (s.lastTimestamp !== null) {
|
|
5664
|
-
const
|
|
5665
|
-
|
|
5821
|
+
const gap = (frame.timestamp - s.lastTimestamp >>> 0) - s.lastSamples;
|
|
5822
|
+
if (gap > 0 && gap <= 48e3) s.chunks.push(codec.conceal(gap));
|
|
5666
5823
|
}
|
|
5667
|
-
|
|
5824
|
+
const pcm = codec.decode(frame.opus);
|
|
5825
|
+
s.chunks.push(pcm);
|
|
5668
5826
|
s.lastTimestamp = frame.timestamp;
|
|
5827
|
+
s.lastSamples = pcm.length;
|
|
5669
5828
|
};
|
|
5670
5829
|
this.detach = this.session.attachAudio(handler);
|
|
5671
5830
|
}
|
|
@@ -5706,6 +5865,231 @@ var Listener = class {
|
|
|
5706
5865
|
}
|
|
5707
5866
|
};
|
|
5708
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
|
+
|
|
5709
6093
|
// src/agent.ts
|
|
5710
6094
|
var Agent = class _Agent {
|
|
5711
6095
|
client;
|
|
@@ -5759,6 +6143,15 @@ var Agent = class _Agent {
|
|
|
5759
6143
|
listener(session, options) {
|
|
5760
6144
|
return new Listener(session, options);
|
|
5761
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
|
+
}
|
|
5762
6155
|
async close() {
|
|
5763
6156
|
for (const id of [...this.sessions.keys()]) await this.closeSession(id);
|
|
5764
6157
|
this.realtime.close();
|
|
@@ -5841,6 +6234,22 @@ function registerTools(server, agent) {
|
|
|
5841
6234
|
async (body) => run(() => agent.frequencies.create({ ...body, ageConfirmed: true, termsAccepted: true }))
|
|
5842
6235
|
);
|
|
5843
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)));
|
|
5844
6253
|
server.tool("contacts_list", "The agent's contacts.", {}, async () => run(() => agent.contacts.list()));
|
|
5845
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)));
|
|
5846
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)));
|
|
@@ -5878,7 +6287,7 @@ function registerTools(server, agent) {
|
|
|
5878
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)));
|
|
5879
6288
|
server.tool(
|
|
5880
6289
|
"audio_speak",
|
|
5881
|
-
"Speak a WAV file (16-bit PCM) on a frequency
|
|
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.",
|
|
5882
6291
|
{ frequencyId: z19.string(), wavPath: z19.string() },
|
|
5883
6292
|
async ({ frequencyId, wavPath }) => run(async () => {
|
|
5884
6293
|
const session = await agent.session(frequencyId);
|
|
@@ -5911,6 +6320,22 @@ function registerTools(server, agent) {
|
|
|
5911
6320
|
})
|
|
5912
6321
|
);
|
|
5913
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
|
+
);
|
|
5914
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()));
|
|
5915
6340
|
server.tool(
|
|
5916
6341
|
"credit_topup_challenge",
|