@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/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;
|
|
@@ -4649,6 +4656,9 @@ var BlockedWordsSchema = z14.object({ words: z14.array(BlockedWordSchema).max(2e
|
|
|
4649
4656
|
|
|
4650
4657
|
// ../shared/dist/nativeTransport.js
|
|
4651
4658
|
var NATIVE_TRANSPORT_VERSION = 1;
|
|
4659
|
+
var NATIVE_TRANSPORT_WIRE_V2 = 2;
|
|
4660
|
+
var FLAG_CONTROL = 16;
|
|
4661
|
+
var FLAG_CONTENT_KEY = 32;
|
|
4652
4662
|
var NODE_SEQUENCE_BASE = 1n << 63n;
|
|
4653
4663
|
var HEADER = {
|
|
4654
4664
|
/** version (low nibble) + flags (high nibble). */
|
|
@@ -4707,6 +4717,19 @@ var PAYLOAD = {
|
|
|
4707
4717
|
OPUS_OFFSET: 9
|
|
4708
4718
|
};
|
|
4709
4719
|
var PAYLOAD_TYPE = { audio: 0, keepalive: 1, contentKey: 2, videoShard: 3, shareAudio: 4 };
|
|
4720
|
+
var CONTENT_KEY_PAYLOAD = {
|
|
4721
|
+
TYPE_OFFSET: 0,
|
|
4722
|
+
/** uint32. The stream whose audio `K_s` seals. */
|
|
4723
|
+
STREAM_ID_OFFSET: 1,
|
|
4724
|
+
/** uint32, 48 kHz. The talkspurt's timestamp when this key packet was sent; informational. */
|
|
4725
|
+
TIMESTAMP_OFFSET: 5,
|
|
4726
|
+
/** uint32. Monotonic per stream; its LOW BYTE is the generation an audio header carries. */
|
|
4727
|
+
CONTENT_KEY_ID_OFFSET: 9,
|
|
4728
|
+
/** 32 bytes: `K_s`, an AES-256-GCM key. */
|
|
4729
|
+
KEY_OFFSET: 13,
|
|
4730
|
+
LENGTH: 45
|
|
4731
|
+
};
|
|
4732
|
+
var SHARE_CHANNEL_ID = 4294967295;
|
|
4710
4733
|
var VIDEO_SHARD = {
|
|
4711
4734
|
TYPE_OFFSET: 0,
|
|
4712
4735
|
STREAM_ID_OFFSET: 1,
|
|
@@ -4745,8 +4768,13 @@ var PROJECTS_BY_PLATFORM = {
|
|
|
4745
4768
|
// than a rider on `broadcast` (a Windows lane) or `tuner_apple`, for the reason `broadcast` got
|
|
4746
4769
|
// one: the board enforces one in-flight task per PROJECT, so a shared lane makes one app's claim
|
|
4747
4770
|
// answer 409 AGENT_BUSY while the other holds the slot.
|
|
4771
|
+
// `switchboard_apple` is the macOS Switchboard (owner, 2026-11-27: "build switchboard for mac"):
|
|
4772
|
+
// a native build of the same product the Windows `switchboard` lane builds, developed here on the
|
|
4773
|
+
// Mac like `tuner_apple` and `broadcast_apple`. Its own lane rather than a rider on `switchboard`
|
|
4774
|
+
// (a Windows lane) or `switchboard_steamos` (the SteamOS group), for the one-in-flight reason
|
|
4775
|
+
// `broadcast_apple` records above. A Mac lane only: not in the Windows set, not in the SteamOS group.
|
|
4748
4776
|
// The SteamOS group (`STEAMOS_PROJECTS`, above) is on both platforms since 2026-11-03.
|
|
4749
|
-
mac: ["frequency", "tuner_apple", "site", "platform", "broadcast_apple", ...STEAMOS_PROJECTS],
|
|
4777
|
+
mac: ["frequency", "tuner_apple", "site", "platform", "broadcast_apple", "switchboard_apple", ...STEAMOS_PROJECTS],
|
|
4750
4778
|
// `broadcast` is its own lane rather than a rider on `windows` (2026-08-31): the board
|
|
4751
4779
|
// enforces one in-flight task per PROJECT, and `windows` already carries the Jacked
|
|
4752
4780
|
// audio-driver work, so sharing it meant a Broadcast claim answered 409 AGENT_BUSY for
|
|
@@ -5122,9 +5150,12 @@ var NativeSession = class {
|
|
|
5122
5150
|
joinToken = "";
|
|
5123
5151
|
keepalive = null;
|
|
5124
5152
|
homeChannelId = null;
|
|
5153
|
+
resolvedProfile = null;
|
|
5125
5154
|
producing = null;
|
|
5126
5155
|
timestamp = 0;
|
|
5127
5156
|
owners = /* @__PURE__ */ new Map();
|
|
5157
|
+
/** `${connectionId}:${streamId}` -> that stream's content keys (wire v2). */
|
|
5158
|
+
contentKeys = /* @__PURE__ */ new Map();
|
|
5128
5159
|
pending = [];
|
|
5129
5160
|
/** The last 500 signalling events, oldest first. A probe reads them; `waitFor` searches them. */
|
|
5130
5161
|
events = [];
|
|
@@ -5136,7 +5167,7 @@ var NativeSession = class {
|
|
|
5136
5167
|
/** The stale-key watch: consecutive packets that would not open since the last one that did, and when a refresh was last asked for. */
|
|
5137
5168
|
staleRun = 0;
|
|
5138
5169
|
lastStaleRefresh = 0;
|
|
5139
|
-
receiveStats = { frames: 0, unsupportedVersion: 0, unknownChannel: 0, undecryptable: 0, notAudio: 0, misattributed: 0 };
|
|
5170
|
+
receiveStats = { frames: 0, unsupportedVersion: 0, contentKeys: 0, awaitingContentKey: 0, unknownChannel: 0, undecryptable: 0, notAudio: 0, misattributed: 0 };
|
|
5140
5171
|
/** The node-issued datapath identity, 0 until `open()` has authenticated. */
|
|
5141
5172
|
get connectionId() {
|
|
5142
5173
|
return this.connection;
|
|
@@ -5205,10 +5236,16 @@ var NativeSession = class {
|
|
|
5205
5236
|
* before, and on a talk frequency that channel is `broadcast_open`, so every first `speak()`
|
|
5206
5237
|
* was refused "no transmit permission". The personal channel is matched by the agent's own
|
|
5207
5238
|
* callsign in its name; a frequency with no personal channel for this agent (an old one, a
|
|
5208
|
-
* 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).
|
|
5209
5241
|
*/
|
|
5210
5242
|
async defaultChannelId() {
|
|
5211
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
|
+
}
|
|
5212
5249
|
const personal = channels.filter((c) => c.kind === "personal");
|
|
5213
5250
|
let own = personal.length === 1 ? personal[0] : void 0;
|
|
5214
5251
|
if (personal.length > 1) {
|
|
@@ -5238,7 +5275,7 @@ var NativeSession = class {
|
|
|
5238
5275
|
this.owners.set(streamId, connectionId);
|
|
5239
5276
|
this.options.onStream?.({ streamId, connectionId, producerUserId: event.producerUserId, producerCallsign: event.producerCallsign, channelId: event.channelId });
|
|
5240
5277
|
}
|
|
5241
|
-
if (event.type === "nativeStreamClosed") this.
|
|
5278
|
+
if (event.type === "nativeStreamClosed") this.forgetStream(Number(event.streamId));
|
|
5242
5279
|
if (event.type === "nativeKeysRotated") this.onKeysRotated(String(event.keysetId));
|
|
5243
5280
|
for (const p of [...this.pending]) {
|
|
5244
5281
|
if (p.type === event.type) {
|
|
@@ -5361,10 +5398,35 @@ var NativeSession = class {
|
|
|
5361
5398
|
listen(channelId) {
|
|
5362
5399
|
this.send({ type: "subscribeChannel", channelId });
|
|
5363
5400
|
}
|
|
5364
|
-
/**
|
|
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. */
|
|
5365
5426
|
async startTalking(options = {}) {
|
|
5366
5427
|
if (!this.homeChannelId) throw new Error("native: not open");
|
|
5367
|
-
|
|
5428
|
+
const profile = options.profile ?? await this.programProfile();
|
|
5429
|
+
this.send({ type: "nativeProduce", channelId: this.homeChannelId, relayChannelIds: options.relayChannelIds ?? [], sourceKey: options.sourceKey ?? "agent", profile });
|
|
5368
5430
|
const produced = await this.waitFor("nativeProduced", 1e4);
|
|
5369
5431
|
this.producing = { streamId: Number(produced.streamId), channelId: this.homeChannelId };
|
|
5370
5432
|
this.events.splice(this.events.indexOf(produced), 1);
|
|
@@ -5389,12 +5451,24 @@ var NativeSession = class {
|
|
|
5389
5451
|
}
|
|
5390
5452
|
onPacket(packet) {
|
|
5391
5453
|
if (!this.native || packet.length < HEADER.LENGTH + AEAD.TAG_BYTES) return;
|
|
5392
|
-
|
|
5454
|
+
const byte0 = packet[HEADER.VERSION_FLAGS_OFFSET];
|
|
5455
|
+
const version = byte0 & 15;
|
|
5456
|
+
const flags = byte0 & 240;
|
|
5457
|
+
const connectionId = packet.readUInt32BE(HEADER.CONNECTION_ID_OFFSET);
|
|
5458
|
+
const channelNativeId = packet.readUInt32BE(HEADER.CHANNEL_ID_OFFSET);
|
|
5459
|
+
if (version === NATIVE_TRANSPORT_VERSION && flags === FLAG_CONTROL) {
|
|
5460
|
+
this.receiveStats.notAudio += 1;
|
|
5461
|
+
return;
|
|
5462
|
+
}
|
|
5463
|
+
if (version === NATIVE_TRANSPORT_WIRE_V2 && flags === 0 && channelNativeId !== SHARE_CHANNEL_ID) {
|
|
5464
|
+
this.onV2Audio(packet, connectionId, channelNativeId);
|
|
5465
|
+
return;
|
|
5466
|
+
}
|
|
5467
|
+
const keyPacket = version === NATIVE_TRANSPORT_WIRE_V2 && flags === FLAG_CONTENT_KEY;
|
|
5468
|
+
if (!keyPacket && !(version === NATIVE_TRANSPORT_VERSION && flags === 0)) {
|
|
5393
5469
|
this.receiveStats.unsupportedVersion += 1;
|
|
5394
5470
|
return;
|
|
5395
5471
|
}
|
|
5396
|
-
const connectionId = packet.readUInt32BE(HEADER.CONNECTION_ID_OFFSET);
|
|
5397
|
-
const channelNativeId = packet.readUInt32BE(HEADER.CHANNEL_ID_OFFSET);
|
|
5398
5472
|
const entry = Object.values(this.native.channelKeys.keys).find((k) => k.id === channelNativeId);
|
|
5399
5473
|
if (!entry) {
|
|
5400
5474
|
this.receiveStats.unknownChannel += 1;
|
|
@@ -5409,10 +5483,89 @@ var NativeSession = class {
|
|
|
5409
5483
|
return;
|
|
5410
5484
|
}
|
|
5411
5485
|
this.staleRun = 0;
|
|
5486
|
+
if (keyPacket) {
|
|
5487
|
+
this.onContentKey(connectionId, body);
|
|
5488
|
+
return;
|
|
5489
|
+
}
|
|
5412
5490
|
if (body.type !== PAYLOAD_TYPE.audio) {
|
|
5413
5491
|
this.receiveStats.notAudio += 1;
|
|
5414
5492
|
return;
|
|
5415
5493
|
}
|
|
5494
|
+
this.deliver(connectionId, body);
|
|
5495
|
+
}
|
|
5496
|
+
/** A v2 key packet that opened under a channel key: attribute it, then file `K_s` under the stream's home. */
|
|
5497
|
+
onContentKey(connectionId, body) {
|
|
5498
|
+
const rest = body.opus;
|
|
5499
|
+
const restLength = CONTENT_KEY_PAYLOAD.LENGTH - CONTENT_KEY_PAYLOAD.CONTENT_KEY_ID_OFFSET;
|
|
5500
|
+
if (body.type !== PAYLOAD_TYPE.contentKey || rest.length !== restLength) {
|
|
5501
|
+
this.receiveStats.notAudio += 1;
|
|
5502
|
+
return;
|
|
5503
|
+
}
|
|
5504
|
+
const owner = this.owners.get(body.streamId);
|
|
5505
|
+
if (owner === void 0 || owner !== connectionId) {
|
|
5506
|
+
this.receiveStats.misattributed += 1;
|
|
5507
|
+
return;
|
|
5508
|
+
}
|
|
5509
|
+
const contentKeyId = rest.readUInt32BE(0);
|
|
5510
|
+
const key = Buffer.from(rest.subarray(CONTENT_KEY_PAYLOAD.KEY_OFFSET - CONTENT_KEY_PAYLOAD.CONTENT_KEY_ID_OFFSET));
|
|
5511
|
+
const slot = `${connectionId}:${body.streamId}`;
|
|
5512
|
+
let stream = this.contentKeys.get(slot);
|
|
5513
|
+
if (!stream) {
|
|
5514
|
+
stream = { connectionId, streamId: body.streamId, generations: /* @__PURE__ */ new Map() };
|
|
5515
|
+
this.contentKeys.set(slot, stream);
|
|
5516
|
+
}
|
|
5517
|
+
const generation = contentKeyId & 255;
|
|
5518
|
+
const held = stream.generations.get(generation);
|
|
5519
|
+
if (held && held.contentKeyId === contentKeyId) return;
|
|
5520
|
+
stream.generations.delete(generation);
|
|
5521
|
+
stream.generations.set(generation, { contentKeyId, key });
|
|
5522
|
+
while (stream.generations.size > 2) stream.generations.delete(stream.generations.keys().next().value);
|
|
5523
|
+
this.receiveStats.contentKeys += 1;
|
|
5524
|
+
}
|
|
5525
|
+
/**
|
|
5526
|
+
* v2 audio: sealed under `K_s`, found by (connection, home wire id, generation). The stream bound
|
|
5527
|
+
* to that home is tried first; a connection's streams whose home is not yet learned are tried
|
|
5528
|
+
* after (one connection rarely carries more than one), and the first that opens with its own
|
|
5529
|
+
* streamId inside binds the home.
|
|
5530
|
+
*/
|
|
5531
|
+
onV2Audio(packet, connectionId, homeWireId) {
|
|
5532
|
+
const generation = packet[HEADER.KEY_EPOCH_OFFSET];
|
|
5533
|
+
const candidates = [];
|
|
5534
|
+
for (const entry of this.contentKeys.values()) {
|
|
5535
|
+
if (entry.connectionId !== connectionId || !entry.generations.has(generation)) continue;
|
|
5536
|
+
if (entry.homeWireId === homeWireId) candidates.unshift(entry);
|
|
5537
|
+
else if (entry.homeWireId === void 0) candidates.push(entry);
|
|
5538
|
+
}
|
|
5539
|
+
if (candidates.length === 0) {
|
|
5540
|
+
this.receiveStats.awaitingContentKey += 1;
|
|
5541
|
+
return;
|
|
5542
|
+
}
|
|
5543
|
+
for (const stream of candidates) {
|
|
5544
|
+
let body;
|
|
5545
|
+
try {
|
|
5546
|
+
body = open(packet, stream.generations.get(generation).key);
|
|
5547
|
+
} catch {
|
|
5548
|
+
continue;
|
|
5549
|
+
}
|
|
5550
|
+
if (body.type !== PAYLOAD_TYPE.audio) {
|
|
5551
|
+
this.receiveStats.notAudio += 1;
|
|
5552
|
+
return;
|
|
5553
|
+
}
|
|
5554
|
+
if (body.streamId !== stream.streamId) {
|
|
5555
|
+
this.receiveStats.misattributed += 1;
|
|
5556
|
+
return;
|
|
5557
|
+
}
|
|
5558
|
+
if (stream.homeWireId === void 0) {
|
|
5559
|
+
for (const [slot, other] of this.contentKeys) if (other !== stream && other.connectionId === connectionId && other.homeWireId === homeWireId) this.contentKeys.delete(slot);
|
|
5560
|
+
stream.homeWireId = homeWireId;
|
|
5561
|
+
}
|
|
5562
|
+
this.deliver(connectionId, body);
|
|
5563
|
+
return;
|
|
5564
|
+
}
|
|
5565
|
+
this.receiveStats.undecryptable += 1;
|
|
5566
|
+
}
|
|
5567
|
+
/** The owner check and hand-off every opened audio frame goes through, whichever wire version carried it. */
|
|
5568
|
+
deliver(connectionId, body) {
|
|
5416
5569
|
const owner = this.owners.get(body.streamId);
|
|
5417
5570
|
if (owner === void 0 || owner !== connectionId) {
|
|
5418
5571
|
this.receiveStats.misattributed += 1;
|
|
@@ -5423,6 +5576,10 @@ var NativeSession = class {
|
|
|
5423
5576
|
this.options.onAudio?.(frame);
|
|
5424
5577
|
for (const listener of this.audioListeners) listener(frame);
|
|
5425
5578
|
}
|
|
5579
|
+
forgetStream(streamId) {
|
|
5580
|
+
this.owners.delete(streamId);
|
|
5581
|
+
for (const [slot, entry] of this.contentKeys) if (entry.streamId === streamId) this.contentKeys.delete(slot);
|
|
5582
|
+
}
|
|
5426
5583
|
/**
|
|
5427
5584
|
* The backstop for a missed `nativeKeysRotated` (the node announces a rotation only once it
|
|
5428
5585
|
* has a baseline to compare against, so a rotation inside its first poll window is never
|
|
@@ -5489,7 +5646,7 @@ async function createOpus() {
|
|
|
5489
5646
|
return {
|
|
5490
5647
|
encode: (pcm) => enc.encode(Buffer.from(pcm.buffer, pcm.byteOffset, pcm.byteLength)),
|
|
5491
5648
|
decode: (packet) => toInt16(enc.decode(packet)),
|
|
5492
|
-
conceal: () => new Int16Array(
|
|
5649
|
+
conceal: (samples = FRAME_SAMPLES) => new Int16Array(samples),
|
|
5493
5650
|
close: () => enc.delete?.()
|
|
5494
5651
|
};
|
|
5495
5652
|
} catch {
|
|
@@ -5502,7 +5659,7 @@ async function createOpus() {
|
|
|
5502
5659
|
return {
|
|
5503
5660
|
encode: (pcm) => codec.encode(Buffer.from(pcm.buffer, pcm.byteOffset, pcm.byteLength), FRAME_SAMPLES),
|
|
5504
5661
|
decode: (packet) => toInt16(codec.decode(packet)),
|
|
5505
|
-
conceal: () => new Int16Array(
|
|
5662
|
+
conceal: (samples = FRAME_SAMPLES) => new Int16Array(samples),
|
|
5506
5663
|
close: () => codec.delete()
|
|
5507
5664
|
};
|
|
5508
5665
|
}
|
|
@@ -5606,7 +5763,7 @@ var Speaker = class {
|
|
|
5606
5763
|
async speakPcm(samples, sampleRate, options = {}) {
|
|
5607
5764
|
const codec = await this.opus();
|
|
5608
5765
|
const pcm = resample(samples, sampleRate, SAMPLE_RATE);
|
|
5609
|
-
await this.session.startTalking({ relayChannelIds: options.relayChannelIds });
|
|
5766
|
+
await this.session.startTalking({ relayChannelIds: options.relayChannelIds, ...options.profile ? { profile: options.profile } : {} });
|
|
5610
5767
|
try {
|
|
5611
5768
|
const started = Date.now();
|
|
5612
5769
|
let i = 0;
|
|
@@ -5651,15 +5808,17 @@ var Listener = class {
|
|
|
5651
5808
|
if (!this.options.includeOwn && frame.connectionId === this.session.connectionId) return;
|
|
5652
5809
|
let s = this.streams.get(frame.streamId);
|
|
5653
5810
|
if (!s) {
|
|
5654
|
-
s = { connectionId: frame.connectionId, chunks: [], lastTimestamp: null, first: frame.timestamp };
|
|
5811
|
+
s = { connectionId: frame.connectionId, chunks: [], lastTimestamp: null, lastSamples: 0, first: frame.timestamp };
|
|
5655
5812
|
this.streams.set(frame.streamId, s);
|
|
5656
5813
|
}
|
|
5657
5814
|
if (s.lastTimestamp !== null) {
|
|
5658
|
-
const
|
|
5659
|
-
|
|
5815
|
+
const gap = (frame.timestamp - s.lastTimestamp >>> 0) - s.lastSamples;
|
|
5816
|
+
if (gap > 0 && gap <= 48e3) s.chunks.push(codec.conceal(gap));
|
|
5660
5817
|
}
|
|
5661
|
-
|
|
5818
|
+
const pcm = codec.decode(frame.opus);
|
|
5819
|
+
s.chunks.push(pcm);
|
|
5662
5820
|
s.lastTimestamp = frame.timestamp;
|
|
5821
|
+
s.lastSamples = pcm.length;
|
|
5663
5822
|
};
|
|
5664
5823
|
this.detach = this.session.attachAudio(handler);
|
|
5665
5824
|
}
|
|
@@ -5700,6 +5859,231 @@ var Listener = class {
|
|
|
5700
5859
|
}
|
|
5701
5860
|
};
|
|
5702
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
|
+
|
|
5703
6087
|
// src/config.ts
|
|
5704
6088
|
import { readFile as readFile2 } from "fs/promises";
|
|
5705
6089
|
import { homedir } from "os";
|
|
@@ -5779,6 +6163,15 @@ var Agent = class _Agent {
|
|
|
5779
6163
|
listener(session, options) {
|
|
5780
6164
|
return new Listener(session, options);
|
|
5781
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
|
+
}
|
|
5782
6175
|
async close() {
|
|
5783
6176
|
for (const id of [...this.sessions.keys()]) await this.closeSession(id);
|
|
5784
6177
|
this.realtime.close();
|
|
@@ -5800,12 +6193,14 @@ export {
|
|
|
5800
6193
|
Realtime,
|
|
5801
6194
|
SAMPLE_RATE,
|
|
5802
6195
|
Speaker,
|
|
6196
|
+
StationStream,
|
|
5803
6197
|
WS_CLOSE_SESSION_REVOKED,
|
|
5804
6198
|
WS_CLOSE_UNAUTHORIZED,
|
|
5805
6199
|
createOpus,
|
|
5806
6200
|
downmix,
|
|
5807
6201
|
frames,
|
|
5808
6202
|
loadKey,
|
|
6203
|
+
parseMediaPlaylist,
|
|
5809
6204
|
readWav,
|
|
5810
6205
|
resample,
|
|
5811
6206
|
writeWav
|