@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/mcp/server.js
CHANGED
|
@@ -153,6 +153,7 @@ var Realtime = class {
|
|
|
153
153
|
bufferSize;
|
|
154
154
|
subscriptions = /* @__PURE__ */ new Set();
|
|
155
155
|
waiters = [];
|
|
156
|
+
listeners = /* @__PURE__ */ new Set();
|
|
156
157
|
/** Opens the socket and resolves once the server has answered a ping (the connect path has finished). */
|
|
157
158
|
async connect() {
|
|
158
159
|
this.closedByCaller = false;
|
|
@@ -192,6 +193,12 @@ var Realtime = class {
|
|
|
192
193
|
}
|
|
193
194
|
}
|
|
194
195
|
this.options.onEvent?.(event);
|
|
196
|
+
for (const listener of this.listeners) listener(event);
|
|
197
|
+
}
|
|
198
|
+
/** Receive every event as it arrives, beside `onEvent` (0.2.5); returns the detach function. */
|
|
199
|
+
on(listener) {
|
|
200
|
+
this.listeners.add(listener);
|
|
201
|
+
return () => this.listeners.delete(listener);
|
|
195
202
|
}
|
|
196
203
|
async onClose(code) {
|
|
197
204
|
this.ws = null;
|
|
@@ -4653,6 +4660,9 @@ var BlockedWordsSchema = z14.object({ words: z14.array(BlockedWordSchema).max(2e
|
|
|
4653
4660
|
|
|
4654
4661
|
// ../shared/dist/nativeTransport.js
|
|
4655
4662
|
var NATIVE_TRANSPORT_VERSION = 1;
|
|
4663
|
+
var NATIVE_TRANSPORT_WIRE_V2 = 2;
|
|
4664
|
+
var FLAG_CONTROL = 16;
|
|
4665
|
+
var FLAG_CONTENT_KEY = 32;
|
|
4656
4666
|
var NODE_SEQUENCE_BASE = 1n << 63n;
|
|
4657
4667
|
var HEADER = {
|
|
4658
4668
|
/** version (low nibble) + flags (high nibble). */
|
|
@@ -4711,6 +4721,19 @@ var PAYLOAD = {
|
|
|
4711
4721
|
OPUS_OFFSET: 9
|
|
4712
4722
|
};
|
|
4713
4723
|
var PAYLOAD_TYPE = { audio: 0, keepalive: 1, contentKey: 2, videoShard: 3, shareAudio: 4 };
|
|
4724
|
+
var CONTENT_KEY_PAYLOAD = {
|
|
4725
|
+
TYPE_OFFSET: 0,
|
|
4726
|
+
/** uint32. The stream whose audio `K_s` seals. */
|
|
4727
|
+
STREAM_ID_OFFSET: 1,
|
|
4728
|
+
/** uint32, 48 kHz. The talkspurt's timestamp when this key packet was sent; informational. */
|
|
4729
|
+
TIMESTAMP_OFFSET: 5,
|
|
4730
|
+
/** uint32. Monotonic per stream; its LOW BYTE is the generation an audio header carries. */
|
|
4731
|
+
CONTENT_KEY_ID_OFFSET: 9,
|
|
4732
|
+
/** 32 bytes: `K_s`, an AES-256-GCM key. */
|
|
4733
|
+
KEY_OFFSET: 13,
|
|
4734
|
+
LENGTH: 45
|
|
4735
|
+
};
|
|
4736
|
+
var SHARE_CHANNEL_ID = 4294967295;
|
|
4714
4737
|
var VIDEO_SHARD = {
|
|
4715
4738
|
TYPE_OFFSET: 0,
|
|
4716
4739
|
STREAM_ID_OFFSET: 1,
|
|
@@ -4749,8 +4772,13 @@ var PROJECTS_BY_PLATFORM = {
|
|
|
4749
4772
|
// than a rider on `broadcast` (a Windows lane) or `tuner_apple`, for the reason `broadcast` got
|
|
4750
4773
|
// one: the board enforces one in-flight task per PROJECT, so a shared lane makes one app's claim
|
|
4751
4774
|
// answer 409 AGENT_BUSY while the other holds the slot.
|
|
4775
|
+
// `switchboard_apple` is the macOS Switchboard (owner, 2026-11-27: "build switchboard for mac"):
|
|
4776
|
+
// a native build of the same product the Windows `switchboard` lane builds, developed here on the
|
|
4777
|
+
// Mac like `tuner_apple` and `broadcast_apple`. Its own lane rather than a rider on `switchboard`
|
|
4778
|
+
// (a Windows lane) or `switchboard_steamos` (the SteamOS group), for the one-in-flight reason
|
|
4779
|
+
// `broadcast_apple` records above. A Mac lane only: not in the Windows set, not in the SteamOS group.
|
|
4752
4780
|
// The SteamOS group (`STEAMOS_PROJECTS`, above) is on both platforms since 2026-11-03.
|
|
4753
|
-
mac: ["frequency", "tuner_apple", "site", "platform", "broadcast_apple", ...STEAMOS_PROJECTS],
|
|
4781
|
+
mac: ["frequency", "tuner_apple", "site", "platform", "broadcast_apple", "switchboard_apple", ...STEAMOS_PROJECTS],
|
|
4754
4782
|
// `broadcast` is its own lane rather than a rider on `windows` (2026-08-31): the board
|
|
4755
4783
|
// enforces one in-flight task per PROJECT, and `windows` already carries the Jacked
|
|
4756
4784
|
// audio-driver work, so sharing it meant a Broadcast claim answered 409 AGENT_BUSY for
|
|
@@ -5126,9 +5154,12 @@ var NativeSession = class {
|
|
|
5126
5154
|
joinToken = "";
|
|
5127
5155
|
keepalive = null;
|
|
5128
5156
|
homeChannelId = null;
|
|
5157
|
+
resolvedProfile = null;
|
|
5129
5158
|
producing = null;
|
|
5130
5159
|
timestamp = 0;
|
|
5131
5160
|
owners = /* @__PURE__ */ new Map();
|
|
5161
|
+
/** `${connectionId}:${streamId}` -> that stream's content keys (wire v2). */
|
|
5162
|
+
contentKeys = /* @__PURE__ */ new Map();
|
|
5132
5163
|
pending = [];
|
|
5133
5164
|
/** The last 500 signalling events, oldest first. A probe reads them; `waitFor` searches them. */
|
|
5134
5165
|
events = [];
|
|
@@ -5140,7 +5171,7 @@ var NativeSession = class {
|
|
|
5140
5171
|
/** The stale-key watch: consecutive packets that would not open since the last one that did, and when a refresh was last asked for. */
|
|
5141
5172
|
staleRun = 0;
|
|
5142
5173
|
lastStaleRefresh = 0;
|
|
5143
|
-
receiveStats = { frames: 0, unsupportedVersion: 0, unknownChannel: 0, undecryptable: 0, notAudio: 0, misattributed: 0 };
|
|
5174
|
+
receiveStats = { frames: 0, unsupportedVersion: 0, contentKeys: 0, awaitingContentKey: 0, unknownChannel: 0, undecryptable: 0, notAudio: 0, misattributed: 0 };
|
|
5144
5175
|
/** The node-issued datapath identity, 0 until `open()` has authenticated. */
|
|
5145
5176
|
get connectionId() {
|
|
5146
5177
|
return this.connection;
|
|
@@ -5209,10 +5240,16 @@ var NativeSession = class {
|
|
|
5209
5240
|
* before, and on a talk frequency that channel is `broadcast_open`, so every first `speak()`
|
|
5210
5241
|
* was refused "no transmit permission". The personal channel is matched by the agent's own
|
|
5211
5242
|
* callsign in its name; a frequency with no personal channel for this agent (an old one, a
|
|
5212
|
-
* station) falls back to the default group channel as before.
|
|
5243
|
+
* station) falls back to the default group channel as before. A station's broadcaster homes on
|
|
5244
|
+
* the program channel (Public) instead (0.2.5).
|
|
5213
5245
|
*/
|
|
5214
5246
|
async defaultChannelId() {
|
|
5215
5247
|
const channels = await this.frequencies.channels(this.frequencyId);
|
|
5248
|
+
const detail = await this.frequencies.get(this.frequencyId).catch(() => null);
|
|
5249
|
+
if (detail?.mode === "broadcast" && detail.mayBroadcast === true) {
|
|
5250
|
+
const program = channels.find((c) => c.isDefault)?.id;
|
|
5251
|
+
if (program) return program;
|
|
5252
|
+
}
|
|
5216
5253
|
const personal = channels.filter((c) => c.kind === "personal");
|
|
5217
5254
|
let own = personal.length === 1 ? personal[0] : void 0;
|
|
5218
5255
|
if (personal.length > 1) {
|
|
@@ -5242,7 +5279,7 @@ var NativeSession = class {
|
|
|
5242
5279
|
this.owners.set(streamId, connectionId);
|
|
5243
5280
|
this.options.onStream?.({ streamId, connectionId, producerUserId: event.producerUserId, producerCallsign: event.producerCallsign, channelId: event.channelId });
|
|
5244
5281
|
}
|
|
5245
|
-
if (event.type === "nativeStreamClosed") this.
|
|
5282
|
+
if (event.type === "nativeStreamClosed") this.forgetStream(Number(event.streamId));
|
|
5246
5283
|
if (event.type === "nativeKeysRotated") this.onKeysRotated(String(event.keysetId));
|
|
5247
5284
|
for (const p of [...this.pending]) {
|
|
5248
5285
|
if (p.type === event.type) {
|
|
@@ -5365,10 +5402,35 @@ var NativeSession = class {
|
|
|
5365
5402
|
listen(channelId) {
|
|
5366
5403
|
this.send({ type: "subscribeChannel", channelId });
|
|
5367
5404
|
}
|
|
5368
|
-
/**
|
|
5405
|
+
/**
|
|
5406
|
+
* The capture profile a stream on the home channel should carry when the caller did not say
|
|
5407
|
+
* (0.2.5): `broadcast` when this agent is the station's broadcaster speaking on its program
|
|
5408
|
+
* channel, `voice` everywhere else (contract §6, "Who sends the program"). That is: a broadcast
|
|
5409
|
+
* frequency, `mayBroadcast` true, and the home is the frequency's default channel (Public). A
|
|
5410
|
+
* voice from a broadcaster on Public is mixed UNDER the program rather than being it, and the
|
|
5411
|
+
* Service Manager gates it like any talker, which is how an agent DJ's show went unheard there
|
|
5412
|
+
* on 2026-11-27. Read once per session: the answer rides the join token, so it cannot change
|
|
5413
|
+
* until a re-tune anyway.
|
|
5414
|
+
*/
|
|
5415
|
+
async programProfile() {
|
|
5416
|
+
if (this.resolvedProfile) return this.resolvedProfile;
|
|
5417
|
+
let profile = "voice";
|
|
5418
|
+
try {
|
|
5419
|
+
const detail = await this.frequencies.get(this.frequencyId);
|
|
5420
|
+
if (detail.mode === "broadcast" && detail.mayBroadcast === true) {
|
|
5421
|
+
const channels = await this.frequencies.channels(this.frequencyId);
|
|
5422
|
+
if (channels.find((c) => c.isDefault)?.id === this.homeChannelId) profile = "broadcast";
|
|
5423
|
+
}
|
|
5424
|
+
} catch {
|
|
5425
|
+
}
|
|
5426
|
+
this.resolvedProfile = profile;
|
|
5427
|
+
return profile;
|
|
5428
|
+
}
|
|
5429
|
+
/** Announce a stream on the home channel (plus relays), and return its stream id. `profile` defaults to `programProfile()`'s answer. */
|
|
5369
5430
|
async startTalking(options = {}) {
|
|
5370
5431
|
if (!this.homeChannelId) throw new Error("native: not open");
|
|
5371
|
-
|
|
5432
|
+
const profile = options.profile ?? await this.programProfile();
|
|
5433
|
+
this.send({ type: "nativeProduce", channelId: this.homeChannelId, relayChannelIds: options.relayChannelIds ?? [], sourceKey: options.sourceKey ?? "agent", profile });
|
|
5372
5434
|
const produced = await this.waitFor("nativeProduced", 1e4);
|
|
5373
5435
|
this.producing = { streamId: Number(produced.streamId), channelId: this.homeChannelId };
|
|
5374
5436
|
this.events.splice(this.events.indexOf(produced), 1);
|
|
@@ -5393,12 +5455,24 @@ var NativeSession = class {
|
|
|
5393
5455
|
}
|
|
5394
5456
|
onPacket(packet) {
|
|
5395
5457
|
if (!this.native || packet.length < HEADER.LENGTH + AEAD.TAG_BYTES) return;
|
|
5396
|
-
|
|
5458
|
+
const byte0 = packet[HEADER.VERSION_FLAGS_OFFSET];
|
|
5459
|
+
const version = byte0 & 15;
|
|
5460
|
+
const flags = byte0 & 240;
|
|
5461
|
+
const connectionId = packet.readUInt32BE(HEADER.CONNECTION_ID_OFFSET);
|
|
5462
|
+
const channelNativeId = packet.readUInt32BE(HEADER.CHANNEL_ID_OFFSET);
|
|
5463
|
+
if (version === NATIVE_TRANSPORT_VERSION && flags === FLAG_CONTROL) {
|
|
5464
|
+
this.receiveStats.notAudio += 1;
|
|
5465
|
+
return;
|
|
5466
|
+
}
|
|
5467
|
+
if (version === NATIVE_TRANSPORT_WIRE_V2 && flags === 0 && channelNativeId !== SHARE_CHANNEL_ID) {
|
|
5468
|
+
this.onV2Audio(packet, connectionId, channelNativeId);
|
|
5469
|
+
return;
|
|
5470
|
+
}
|
|
5471
|
+
const keyPacket = version === NATIVE_TRANSPORT_WIRE_V2 && flags === FLAG_CONTENT_KEY;
|
|
5472
|
+
if (!keyPacket && !(version === NATIVE_TRANSPORT_VERSION && flags === 0)) {
|
|
5397
5473
|
this.receiveStats.unsupportedVersion += 1;
|
|
5398
5474
|
return;
|
|
5399
5475
|
}
|
|
5400
|
-
const connectionId = packet.readUInt32BE(HEADER.CONNECTION_ID_OFFSET);
|
|
5401
|
-
const channelNativeId = packet.readUInt32BE(HEADER.CHANNEL_ID_OFFSET);
|
|
5402
5476
|
const entry = Object.values(this.native.channelKeys.keys).find((k) => k.id === channelNativeId);
|
|
5403
5477
|
if (!entry) {
|
|
5404
5478
|
this.receiveStats.unknownChannel += 1;
|
|
@@ -5413,10 +5487,89 @@ var NativeSession = class {
|
|
|
5413
5487
|
return;
|
|
5414
5488
|
}
|
|
5415
5489
|
this.staleRun = 0;
|
|
5490
|
+
if (keyPacket) {
|
|
5491
|
+
this.onContentKey(connectionId, body);
|
|
5492
|
+
return;
|
|
5493
|
+
}
|
|
5416
5494
|
if (body.type !== PAYLOAD_TYPE.audio) {
|
|
5417
5495
|
this.receiveStats.notAudio += 1;
|
|
5418
5496
|
return;
|
|
5419
5497
|
}
|
|
5498
|
+
this.deliver(connectionId, body);
|
|
5499
|
+
}
|
|
5500
|
+
/** A v2 key packet that opened under a channel key: attribute it, then file `K_s` under the stream's home. */
|
|
5501
|
+
onContentKey(connectionId, body) {
|
|
5502
|
+
const rest = body.opus;
|
|
5503
|
+
const restLength = CONTENT_KEY_PAYLOAD.LENGTH - CONTENT_KEY_PAYLOAD.CONTENT_KEY_ID_OFFSET;
|
|
5504
|
+
if (body.type !== PAYLOAD_TYPE.contentKey || rest.length !== restLength) {
|
|
5505
|
+
this.receiveStats.notAudio += 1;
|
|
5506
|
+
return;
|
|
5507
|
+
}
|
|
5508
|
+
const owner = this.owners.get(body.streamId);
|
|
5509
|
+
if (owner === void 0 || owner !== connectionId) {
|
|
5510
|
+
this.receiveStats.misattributed += 1;
|
|
5511
|
+
return;
|
|
5512
|
+
}
|
|
5513
|
+
const contentKeyId = rest.readUInt32BE(0);
|
|
5514
|
+
const key = Buffer.from(rest.subarray(CONTENT_KEY_PAYLOAD.KEY_OFFSET - CONTENT_KEY_PAYLOAD.CONTENT_KEY_ID_OFFSET));
|
|
5515
|
+
const slot = `${connectionId}:${body.streamId}`;
|
|
5516
|
+
let stream = this.contentKeys.get(slot);
|
|
5517
|
+
if (!stream) {
|
|
5518
|
+
stream = { connectionId, streamId: body.streamId, generations: /* @__PURE__ */ new Map() };
|
|
5519
|
+
this.contentKeys.set(slot, stream);
|
|
5520
|
+
}
|
|
5521
|
+
const generation = contentKeyId & 255;
|
|
5522
|
+
const held = stream.generations.get(generation);
|
|
5523
|
+
if (held && held.contentKeyId === contentKeyId) return;
|
|
5524
|
+
stream.generations.delete(generation);
|
|
5525
|
+
stream.generations.set(generation, { contentKeyId, key });
|
|
5526
|
+
while (stream.generations.size > 2) stream.generations.delete(stream.generations.keys().next().value);
|
|
5527
|
+
this.receiveStats.contentKeys += 1;
|
|
5528
|
+
}
|
|
5529
|
+
/**
|
|
5530
|
+
* v2 audio: sealed under `K_s`, found by (connection, home wire id, generation). The stream bound
|
|
5531
|
+
* to that home is tried first; a connection's streams whose home is not yet learned are tried
|
|
5532
|
+
* after (one connection rarely carries more than one), and the first that opens with its own
|
|
5533
|
+
* streamId inside binds the home.
|
|
5534
|
+
*/
|
|
5535
|
+
onV2Audio(packet, connectionId, homeWireId) {
|
|
5536
|
+
const generation = packet[HEADER.KEY_EPOCH_OFFSET];
|
|
5537
|
+
const candidates = [];
|
|
5538
|
+
for (const entry of this.contentKeys.values()) {
|
|
5539
|
+
if (entry.connectionId !== connectionId || !entry.generations.has(generation)) continue;
|
|
5540
|
+
if (entry.homeWireId === homeWireId) candidates.unshift(entry);
|
|
5541
|
+
else if (entry.homeWireId === void 0) candidates.push(entry);
|
|
5542
|
+
}
|
|
5543
|
+
if (candidates.length === 0) {
|
|
5544
|
+
this.receiveStats.awaitingContentKey += 1;
|
|
5545
|
+
return;
|
|
5546
|
+
}
|
|
5547
|
+
for (const stream of candidates) {
|
|
5548
|
+
let body;
|
|
5549
|
+
try {
|
|
5550
|
+
body = open(packet, stream.generations.get(generation).key);
|
|
5551
|
+
} catch {
|
|
5552
|
+
continue;
|
|
5553
|
+
}
|
|
5554
|
+
if (body.type !== PAYLOAD_TYPE.audio) {
|
|
5555
|
+
this.receiveStats.notAudio += 1;
|
|
5556
|
+
return;
|
|
5557
|
+
}
|
|
5558
|
+
if (body.streamId !== stream.streamId) {
|
|
5559
|
+
this.receiveStats.misattributed += 1;
|
|
5560
|
+
return;
|
|
5561
|
+
}
|
|
5562
|
+
if (stream.homeWireId === void 0) {
|
|
5563
|
+
for (const [slot, other] of this.contentKeys) if (other !== stream && other.connectionId === connectionId && other.homeWireId === homeWireId) this.contentKeys.delete(slot);
|
|
5564
|
+
stream.homeWireId = homeWireId;
|
|
5565
|
+
}
|
|
5566
|
+
this.deliver(connectionId, body);
|
|
5567
|
+
return;
|
|
5568
|
+
}
|
|
5569
|
+
this.receiveStats.undecryptable += 1;
|
|
5570
|
+
}
|
|
5571
|
+
/** The owner check and hand-off every opened audio frame goes through, whichever wire version carried it. */
|
|
5572
|
+
deliver(connectionId, body) {
|
|
5420
5573
|
const owner = this.owners.get(body.streamId);
|
|
5421
5574
|
if (owner === void 0 || owner !== connectionId) {
|
|
5422
5575
|
this.receiveStats.misattributed += 1;
|
|
@@ -5427,6 +5580,10 @@ var NativeSession = class {
|
|
|
5427
5580
|
this.options.onAudio?.(frame);
|
|
5428
5581
|
for (const listener of this.audioListeners) listener(frame);
|
|
5429
5582
|
}
|
|
5583
|
+
forgetStream(streamId) {
|
|
5584
|
+
this.owners.delete(streamId);
|
|
5585
|
+
for (const [slot, entry] of this.contentKeys) if (entry.streamId === streamId) this.contentKeys.delete(slot);
|
|
5586
|
+
}
|
|
5430
5587
|
/**
|
|
5431
5588
|
* The backstop for a missed `nativeKeysRotated` (the node announces a rotation only once it
|
|
5432
5589
|
* has a baseline to compare against, so a rotation inside its first poll window is never
|
|
@@ -5493,7 +5650,7 @@ async function createOpus() {
|
|
|
5493
5650
|
return {
|
|
5494
5651
|
encode: (pcm) => enc.encode(Buffer.from(pcm.buffer, pcm.byteOffset, pcm.byteLength)),
|
|
5495
5652
|
decode: (packet) => toInt16(enc.decode(packet)),
|
|
5496
|
-
conceal: () => new Int16Array(
|
|
5653
|
+
conceal: (samples = FRAME_SAMPLES) => new Int16Array(samples),
|
|
5497
5654
|
close: () => enc.delete?.()
|
|
5498
5655
|
};
|
|
5499
5656
|
} catch {
|
|
@@ -5506,7 +5663,7 @@ async function createOpus() {
|
|
|
5506
5663
|
return {
|
|
5507
5664
|
encode: (pcm) => codec.encode(Buffer.from(pcm.buffer, pcm.byteOffset, pcm.byteLength), FRAME_SAMPLES),
|
|
5508
5665
|
decode: (packet) => toInt16(codec.decode(packet)),
|
|
5509
|
-
conceal: () => new Int16Array(
|
|
5666
|
+
conceal: (samples = FRAME_SAMPLES) => new Int16Array(samples),
|
|
5510
5667
|
close: () => codec.delete()
|
|
5511
5668
|
};
|
|
5512
5669
|
}
|
|
@@ -5610,7 +5767,7 @@ var Speaker = class {
|
|
|
5610
5767
|
async speakPcm(samples, sampleRate, options = {}) {
|
|
5611
5768
|
const codec = await this.opus();
|
|
5612
5769
|
const pcm = resample(samples, sampleRate, SAMPLE_RATE);
|
|
5613
|
-
await this.session.startTalking({ relayChannelIds: options.relayChannelIds });
|
|
5770
|
+
await this.session.startTalking({ relayChannelIds: options.relayChannelIds, ...options.profile ? { profile: options.profile } : {} });
|
|
5614
5771
|
try {
|
|
5615
5772
|
const started = Date.now();
|
|
5616
5773
|
let i = 0;
|
|
@@ -5655,15 +5812,17 @@ var Listener = class {
|
|
|
5655
5812
|
if (!this.options.includeOwn && frame.connectionId === this.session.connectionId) return;
|
|
5656
5813
|
let s = this.streams.get(frame.streamId);
|
|
5657
5814
|
if (!s) {
|
|
5658
|
-
s = { connectionId: frame.connectionId, chunks: [], lastTimestamp: null, first: frame.timestamp };
|
|
5815
|
+
s = { connectionId: frame.connectionId, chunks: [], lastTimestamp: null, lastSamples: 0, first: frame.timestamp };
|
|
5659
5816
|
this.streams.set(frame.streamId, s);
|
|
5660
5817
|
}
|
|
5661
5818
|
if (s.lastTimestamp !== null) {
|
|
5662
|
-
const
|
|
5663
|
-
|
|
5819
|
+
const gap = (frame.timestamp - s.lastTimestamp >>> 0) - s.lastSamples;
|
|
5820
|
+
if (gap > 0 && gap <= 48e3) s.chunks.push(codec.conceal(gap));
|
|
5664
5821
|
}
|
|
5665
|
-
|
|
5822
|
+
const pcm = codec.decode(frame.opus);
|
|
5823
|
+
s.chunks.push(pcm);
|
|
5666
5824
|
s.lastTimestamp = frame.timestamp;
|
|
5825
|
+
s.lastSamples = pcm.length;
|
|
5667
5826
|
};
|
|
5668
5827
|
this.detach = this.session.attachAudio(handler);
|
|
5669
5828
|
}
|
|
@@ -5704,6 +5863,231 @@ var Listener = class {
|
|
|
5704
5863
|
}
|
|
5705
5864
|
};
|
|
5706
5865
|
|
|
5866
|
+
// src/stream.ts
|
|
5867
|
+
function installationOf(token) {
|
|
5868
|
+
try {
|
|
5869
|
+
const claims = JSON.parse(Buffer.from(token.split(".")[1] ?? "", "base64url").toString());
|
|
5870
|
+
return typeof claims.installation_id === "string" ? claims.installation_id : null;
|
|
5871
|
+
} catch {
|
|
5872
|
+
return null;
|
|
5873
|
+
}
|
|
5874
|
+
}
|
|
5875
|
+
function parseMediaPlaylist(text2, base) {
|
|
5876
|
+
const lines = text2.split(/\r?\n/);
|
|
5877
|
+
let sequence = 0;
|
|
5878
|
+
let targetDuration = 2;
|
|
5879
|
+
let pending = 0;
|
|
5880
|
+
let variant = null;
|
|
5881
|
+
const segments = [];
|
|
5882
|
+
for (const raw of lines) {
|
|
5883
|
+
const line = raw.trim();
|
|
5884
|
+
if (!line) continue;
|
|
5885
|
+
if (line.startsWith("#EXT-X-MEDIA-SEQUENCE:")) sequence = Number(line.slice(22)) || 0;
|
|
5886
|
+
else if (line.startsWith("#EXT-X-TARGETDURATION:")) targetDuration = Number(line.slice(22)) || targetDuration;
|
|
5887
|
+
else if (line.startsWith("#EXTINF:")) pending = Number.parseFloat(line.slice(8)) || 0;
|
|
5888
|
+
else if (!line.startsWith("#")) {
|
|
5889
|
+
const url = new URL(line, base).toString();
|
|
5890
|
+
if (new URL(url).pathname.endsWith(".m3u8")) {
|
|
5891
|
+
variant ??= url;
|
|
5892
|
+
continue;
|
|
5893
|
+
}
|
|
5894
|
+
segments.push({ sequence: sequence++, durationSeconds: pending, url });
|
|
5895
|
+
pending = 0;
|
|
5896
|
+
}
|
|
5897
|
+
}
|
|
5898
|
+
return { targetDuration, segments, variant };
|
|
5899
|
+
}
|
|
5900
|
+
var StationStream = class {
|
|
5901
|
+
constructor(client, realtime, frequencyId, options = {}) {
|
|
5902
|
+
this.client = client;
|
|
5903
|
+
this.realtime = realtime;
|
|
5904
|
+
this.frequencyId = frequencyId;
|
|
5905
|
+
this.options = options;
|
|
5906
|
+
}
|
|
5907
|
+
client;
|
|
5908
|
+
realtime;
|
|
5909
|
+
frequencyId;
|
|
5910
|
+
options;
|
|
5911
|
+
mediaUrl = null;
|
|
5912
|
+
installationId = null;
|
|
5913
|
+
lastSequence = -1;
|
|
5914
|
+
running = false;
|
|
5915
|
+
loop = null;
|
|
5916
|
+
offAir = false;
|
|
5917
|
+
detachRealtime = null;
|
|
5918
|
+
ended = null;
|
|
5919
|
+
collectors = /* @__PURE__ */ new Set();
|
|
5920
|
+
/** Wakes the poll loop's wait early, so `stop()` does not sit out a five-second Retry-After. */
|
|
5921
|
+
wake = null;
|
|
5922
|
+
stats = { segments: 0, bytes: 0, remints: 0, playlistErrors: 0, segmentErrors: 0 };
|
|
5923
|
+
/** The last ticket minted (quality, live state). */
|
|
5924
|
+
ticket = null;
|
|
5925
|
+
/** Why the stream ended, or null while it runs (and before `start()`). */
|
|
5926
|
+
get endedWith() {
|
|
5927
|
+
return this.ended;
|
|
5928
|
+
}
|
|
5929
|
+
/**
|
|
5930
|
+
* Mint a ticket and start following the stream. `takeover: true` is for a deliberate start
|
|
5931
|
+
* only (contract §6): it takes the account's stream from wherever else it is playing. Throws
|
|
5932
|
+
* the mint's refusal as a `FrequencyError` (`OFF_AIR` with `retryAfterSeconds`,
|
|
5933
|
+
* `STREAM_CONFLICT`, `STATION_FULL`, `NOT_MEMBER`).
|
|
5934
|
+
*/
|
|
5935
|
+
async start(options = {}) {
|
|
5936
|
+
if (this.running) throw new Error("stream: already started");
|
|
5937
|
+
const ticket = await this.mint(options.takeover === true);
|
|
5938
|
+
this.ended = null;
|
|
5939
|
+
this.running = true;
|
|
5940
|
+
this.detachRealtime = this.realtime?.on((event) => this.onRealtime(event)) ?? null;
|
|
5941
|
+
this.loop = this.follow();
|
|
5942
|
+
return ticket;
|
|
5943
|
+
}
|
|
5944
|
+
async mint(takeover) {
|
|
5945
|
+
const body = { ...takeover ? { takeover: true } : {}, ...this.options.monitor ? { monitor: true } : {} };
|
|
5946
|
+
const ticket = await this.client.request(`/v1/listen/${encodeURIComponent(this.frequencyId)}/ticket`, { method: "POST", ...Object.keys(body).length ? { body } : {} });
|
|
5947
|
+
this.installationId = installationOf(await this.client.accessToken());
|
|
5948
|
+
this.ticket = ticket;
|
|
5949
|
+
this.mediaUrl = new URL(ticket.playlistUrl, this.client.baseUrl).toString();
|
|
5950
|
+
return ticket;
|
|
5951
|
+
}
|
|
5952
|
+
onRealtime(event) {
|
|
5953
|
+
const e = event;
|
|
5954
|
+
if (e.type !== "stream.displaced" || e.frequencyId !== this.frequencyId) return;
|
|
5955
|
+
if (e.installationId && this.installationId && e.installationId !== this.installationId) return;
|
|
5956
|
+
this.end("displaced");
|
|
5957
|
+
}
|
|
5958
|
+
end(reason) {
|
|
5959
|
+
if (!this.running) return;
|
|
5960
|
+
this.running = false;
|
|
5961
|
+
this.ended = reason;
|
|
5962
|
+
this.detachRealtime?.();
|
|
5963
|
+
this.detachRealtime = null;
|
|
5964
|
+
this.wake?.();
|
|
5965
|
+
this.options.onEnd?.(reason);
|
|
5966
|
+
}
|
|
5967
|
+
async follow() {
|
|
5968
|
+
while (this.running) {
|
|
5969
|
+
let wait = 2e3;
|
|
5970
|
+
try {
|
|
5971
|
+
wait = await this.poll();
|
|
5972
|
+
} catch {
|
|
5973
|
+
this.stats.playlistErrors += 1;
|
|
5974
|
+
}
|
|
5975
|
+
if (this.running) await new Promise((resolve) => {
|
|
5976
|
+
const timer = setTimeout(resolve, wait);
|
|
5977
|
+
this.wake = () => {
|
|
5978
|
+
clearTimeout(timer);
|
|
5979
|
+
resolve();
|
|
5980
|
+
};
|
|
5981
|
+
});
|
|
5982
|
+
this.wake = null;
|
|
5983
|
+
}
|
|
5984
|
+
}
|
|
5985
|
+
/** One playlist poll; answers how long to wait before the next. */
|
|
5986
|
+
async poll() {
|
|
5987
|
+
const res = await fetch(this.mediaUrl);
|
|
5988
|
+
if (res.status === 401) {
|
|
5989
|
+
const code = await res.json().then((j) => j.error?.code).catch(() => void 0);
|
|
5990
|
+
if (code !== "TICKET_EXPIRED") {
|
|
5991
|
+
this.end("signed_out");
|
|
5992
|
+
return 0;
|
|
5993
|
+
}
|
|
5994
|
+
try {
|
|
5995
|
+
await this.mint(false);
|
|
5996
|
+
this.stats.remints += 1;
|
|
5997
|
+
} catch (err) {
|
|
5998
|
+
if (err instanceof FrequencyError && err.code === "STREAM_CONFLICT") this.end("conflict");
|
|
5999
|
+
else if (err instanceof FrequencyError && err.status === 401) this.end("signed_out");
|
|
6000
|
+
else if (err instanceof FrequencyError && err.code === "OFF_AIR") return this.setOffAir(err.retryAfterSeconds);
|
|
6001
|
+
return 2e3;
|
|
6002
|
+
}
|
|
6003
|
+
return 0;
|
|
6004
|
+
}
|
|
6005
|
+
if (res.status === 503) return this.setOffAir(Number(res.headers.get("retry-after")) || 5);
|
|
6006
|
+
if (!res.ok) {
|
|
6007
|
+
this.stats.playlistErrors += 1;
|
|
6008
|
+
return 2e3;
|
|
6009
|
+
}
|
|
6010
|
+
if (this.offAir) {
|
|
6011
|
+
this.offAir = false;
|
|
6012
|
+
this.options.onOffAir?.(false);
|
|
6013
|
+
}
|
|
6014
|
+
const playlist = parseMediaPlaylist(await res.text(), this.mediaUrl);
|
|
6015
|
+
if (playlist.variant) {
|
|
6016
|
+
this.mediaUrl = playlist.variant;
|
|
6017
|
+
return 0;
|
|
6018
|
+
}
|
|
6019
|
+
const fresh = this.lastSequence < 0 ? playlist.segments.slice(-1) : playlist.segments.filter((s) => s.sequence > this.lastSequence);
|
|
6020
|
+
for (const segment of fresh) {
|
|
6021
|
+
if (!this.running) break;
|
|
6022
|
+
this.lastSequence = segment.sequence;
|
|
6023
|
+
try {
|
|
6024
|
+
const got = await fetch(segment.url);
|
|
6025
|
+
if (!got.ok) {
|
|
6026
|
+
this.stats.segmentErrors += 1;
|
|
6027
|
+
continue;
|
|
6028
|
+
}
|
|
6029
|
+
const data = Buffer.from(await got.arrayBuffer());
|
|
6030
|
+
this.stats.segments += 1;
|
|
6031
|
+
this.stats.bytes += data.length;
|
|
6032
|
+
const out = { sequence: segment.sequence, durationSeconds: segment.durationSeconds, data };
|
|
6033
|
+
this.options.onSegment?.(out);
|
|
6034
|
+
for (const collect of this.collectors) collect(out);
|
|
6035
|
+
} catch {
|
|
6036
|
+
this.stats.segmentErrors += 1;
|
|
6037
|
+
}
|
|
6038
|
+
}
|
|
6039
|
+
return Math.max(500, playlist.targetDuration * 1e3 / 2);
|
|
6040
|
+
}
|
|
6041
|
+
setOffAir(retryAfterSeconds2) {
|
|
6042
|
+
if (!this.offAir) {
|
|
6043
|
+
this.offAir = true;
|
|
6044
|
+
this.options.onOffAir?.(true);
|
|
6045
|
+
}
|
|
6046
|
+
return Math.max(1, retryAfterSeconds2 ?? 5) * 1e3;
|
|
6047
|
+
}
|
|
6048
|
+
/** Receive every segment as it arrives, beside `onSegment`; returns the detach function. */
|
|
6049
|
+
attach(listener) {
|
|
6050
|
+
this.collectors.add(listener);
|
|
6051
|
+
return () => this.collectors.delete(listener);
|
|
6052
|
+
}
|
|
6053
|
+
/** Collect `seconds` of the stream (by segment duration) and return it as one MPEG-TS buffer; ends early if the stream does. */
|
|
6054
|
+
async record(seconds) {
|
|
6055
|
+
if (!this.running) throw new Error("stream: not started");
|
|
6056
|
+
const parts = [];
|
|
6057
|
+
let total = 0;
|
|
6058
|
+
await new Promise((resolve) => {
|
|
6059
|
+
const detach = this.attach((segment) => {
|
|
6060
|
+
parts.push(segment.data);
|
|
6061
|
+
total += segment.durationSeconds;
|
|
6062
|
+
if (total >= seconds) finish();
|
|
6063
|
+
});
|
|
6064
|
+
const watch = setInterval(() => {
|
|
6065
|
+
if (!this.running) finish();
|
|
6066
|
+
}, 250);
|
|
6067
|
+
const deadline = setTimeout(finish, (seconds + 30) * 1e3);
|
|
6068
|
+
function finish() {
|
|
6069
|
+
detach();
|
|
6070
|
+
clearInterval(watch);
|
|
6071
|
+
clearTimeout(deadline);
|
|
6072
|
+
resolve();
|
|
6073
|
+
}
|
|
6074
|
+
});
|
|
6075
|
+
return { data: Buffer.concat(parts), seconds: Math.round(total * 100) / 100, segments: parts.length };
|
|
6076
|
+
}
|
|
6077
|
+
/** Stop following and release the account's stream at once (`DELETE` the ticket). */
|
|
6078
|
+
async stop() {
|
|
6079
|
+
const wasRunning = this.running;
|
|
6080
|
+
this.running = false;
|
|
6081
|
+
this.detachRealtime?.();
|
|
6082
|
+
this.detachRealtime = null;
|
|
6083
|
+
if (wasRunning) this.ended = "stopped";
|
|
6084
|
+
this.wake?.();
|
|
6085
|
+
await this.loop?.catch(() => void 0);
|
|
6086
|
+
this.loop = null;
|
|
6087
|
+
await this.client.request(`/v1/listen/${encodeURIComponent(this.frequencyId)}/ticket`, { method: "DELETE" }).catch(() => void 0);
|
|
6088
|
+
}
|
|
6089
|
+
};
|
|
6090
|
+
|
|
5707
6091
|
// src/agent.ts
|
|
5708
6092
|
var Agent = class _Agent {
|
|
5709
6093
|
client;
|
|
@@ -5757,6 +6141,15 @@ var Agent = class _Agent {
|
|
|
5757
6141
|
listener(session, options) {
|
|
5758
6142
|
return new Listener(session, options);
|
|
5759
6143
|
}
|
|
6144
|
+
/**
|
|
6145
|
+
* A station's listen stream, as its audience hears it (0.2.5): the program mixed with every voice
|
|
6146
|
+
* on Public. Call `start()` to mint and follow it, `stop()` to release it. Membership is
|
|
6147
|
+
* required, as for any listener; `monitor: true` is for the station's own staff.
|
|
6148
|
+
*/
|
|
6149
|
+
stream(frequencyId, options) {
|
|
6150
|
+
this.realtime.subscribe(frequencyId);
|
|
6151
|
+
return new StationStream(this.client, this.realtime, frequencyId, options);
|
|
6152
|
+
}
|
|
5760
6153
|
async close() {
|
|
5761
6154
|
for (const id of [...this.sessions.keys()]) await this.closeSession(id);
|
|
5762
6155
|
this.realtime.close();
|
|
@@ -5839,6 +6232,22 @@ function registerTools(server, agent) {
|
|
|
5839
6232
|
async (body) => run(() => agent.frequencies.create({ ...body, ageConfirmed: true, termsAccepted: true }))
|
|
5840
6233
|
);
|
|
5841
6234
|
server.tool("frequency_leave", "Leave a frequency (membership).", { frequencyId: z19.string() }, async ({ frequencyId }) => run(() => agent.frequencies.leave(frequencyId).then(() => "left")));
|
|
6235
|
+
server.tool("frequency_members", "A frequency's members and their roles (owner, admin, user; staffRole for a company's station staff).", { frequencyId: z19.string() }, async ({ frequencyId }) => run(() => agent.frequencies.members(frequencyId)));
|
|
6236
|
+
server.tool(
|
|
6237
|
+
"frequency_invite",
|
|
6238
|
+
"Invite somebody to a frequency by callsign, Station ID (FT-XXXX) or email. They accept or decline it themselves.",
|
|
6239
|
+
{ frequencyId: z19.string(), handleOrEmail: z19.string().min(1) },
|
|
6240
|
+
async ({ frequencyId, handleOrEmail }) => run(() => agent.frequencies.invite(frequencyId, handleOrEmail))
|
|
6241
|
+
);
|
|
6242
|
+
server.tool(
|
|
6243
|
+
"frequency_set_role",
|
|
6244
|
+
"Make a member an admin, or an admin an ordinary member (owner or admin only). Admins manage channels, members and invitations; on a station, an admin also sends the program.",
|
|
6245
|
+
{ frequencyId: z19.string(), userId: z19.string(), role: z19.enum(["admin", "user"]) },
|
|
6246
|
+
async ({ frequencyId, userId, role }) => run(() => agent.frequencies.changeRole(frequencyId, userId, role))
|
|
6247
|
+
);
|
|
6248
|
+
server.tool("invitation_list", "Invitations waiting on this agent, with the frequency and who sent each.", {}, async () => run(() => agent.frequencies.myInvitations()));
|
|
6249
|
+
server.tool("invitation_accept", "Accept an invitation: the agent becomes a member of its frequency.", { invitationId: z19.string() }, async ({ invitationId }) => run(() => agent.frequencies.acceptInvitation(invitationId)));
|
|
6250
|
+
server.tool("invitation_decline", "Decline an invitation.", { invitationId: z19.string() }, async ({ invitationId }) => run(() => agent.frequencies.declineInvitation(invitationId)));
|
|
5842
6251
|
server.tool("contacts_list", "The agent's contacts.", {}, async () => run(() => agent.contacts.list()));
|
|
5843
6252
|
server.tool("contacts_search", "Find people and agents by callsign or Station ID.", { query: z19.string().min(1) }, async ({ query }) => run(() => agent.contacts.search(query)));
|
|
5844
6253
|
server.tool("contacts_request", "Ask somebody to be a contact, by Station ID (FT-XXXX).", { stationId: z19.string() }, async ({ stationId }) => run(() => agent.contacts.request(stationId)));
|
|
@@ -5876,7 +6285,7 @@ function registerTools(server, agent) {
|
|
|
5876
6285
|
server.tool("phone_live", "The calls ringing or live on a frequency's phone channels, from the server.", { frequencyId: z19.string() }, async ({ frequencyId }) => run(() => agent.phone.live(frequencyId)));
|
|
5877
6286
|
server.tool(
|
|
5878
6287
|
"audio_speak",
|
|
5879
|
-
"Speak a WAV file (16-bit PCM) on a frequency
|
|
6288
|
+
"Speak a WAV file (16-bit PCM) on a frequency over the native voice transport. Opens the session if needed. On a station where this agent may broadcast (frequency_list's mayBroadcast), it goes out as the station's program; otherwise as a voice.",
|
|
5880
6289
|
{ frequencyId: z19.string(), wavPath: z19.string() },
|
|
5881
6290
|
async ({ frequencyId, wavPath }) => run(async () => {
|
|
5882
6291
|
const session = await agent.session(frequencyId);
|
|
@@ -5909,6 +6318,22 @@ function registerTools(server, agent) {
|
|
|
5909
6318
|
})
|
|
5910
6319
|
);
|
|
5911
6320
|
server.tool("audio_close", "Close the native session on a frequency.", { frequencyId: z19.string() }, async ({ frequencyId }) => run(() => agent.closeSession(frequencyId).then(() => "closed")));
|
|
6321
|
+
server.tool(
|
|
6322
|
+
"stream_record",
|
|
6323
|
+
"Record a station's listen stream, as its audience hears it (the program mixed with every voice on Public), for `seconds`, to an MPEG-TS file (AAC audio) at `path`. Set `monitor` when this agent is the station's staff checking its own air. Takes the account's stream from wherever else it plays only when `takeover` is set.",
|
|
6324
|
+
{ frequencyId: z19.string(), seconds: z19.number().int().min(2).max(600).default(30), path: z19.string(), monitor: z19.boolean().default(false), takeover: z19.boolean().default(false) },
|
|
6325
|
+
async ({ frequencyId, seconds, path, monitor, takeover }) => run(async () => {
|
|
6326
|
+
const stream = agent.stream(frequencyId, { monitor });
|
|
6327
|
+
const ticket = await stream.start({ takeover });
|
|
6328
|
+
try {
|
|
6329
|
+
const recorded = await stream.record(seconds);
|
|
6330
|
+
await writeFile(path, recorded.data);
|
|
6331
|
+
return { path, seconds: recorded.seconds, segments: recorded.segments, quality: ticket.quality ?? "standard", liveState: ticket.liveState, ended: stream.endedWith };
|
|
6332
|
+
} finally {
|
|
6333
|
+
await stream.stop();
|
|
6334
|
+
}
|
|
6335
|
+
})
|
|
6336
|
+
);
|
|
5912
6337
|
server.tool("credit_balance", "The prepaid credit that pays for what this agent does, with today's daily prices and the rails a top-up can use.", {}, async () => run(() => agent.client.credit()));
|
|
5913
6338
|
server.tool(
|
|
5914
6339
|
"credit_topup_challenge",
|