@frequencytalk/agent 0.0.0-stage → 0.1.0

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.
@@ -0,0 +1,654 @@
1
+ import { AgentSession, UserProfile, CreditBalance, ServerToClientEvent, ClientToServerEvent } from '@frequency/shared';
2
+
3
+ /**
4
+ * The HTTP client (contract §9, §25): a bearer token minted from the agent's key, renewed by
5
+ * exchanging the key again when it expires or is refused. Every route of the service is reachable
6
+ * through `request`; the typed modules (frequencies, contacts, chat, calls, credit) sit on top.
7
+ */
8
+ interface FrequencyClientOptions {
9
+ /** The control plane's origin, e.g. `https://frequencytalk.com`. No trailing slash. */
10
+ baseUrl: string;
11
+ /** The agent account key (`ftag_...`). Read it from `FREQUENCY_AGENT_KEY` or the config file; never put it in argv. */
12
+ key: string;
13
+ /** Optional: an already-minted session to start from (renewed from the key when it expires). */
14
+ session?: AgentSession;
15
+ fetch?: typeof globalThis.fetch;
16
+ /** Called with each new session, so a long-lived process can persist it if it wants to. */
17
+ onSession?: (session: AgentSession) => void;
18
+ }
19
+ /** An API refusal: the service's error envelope, with the HTTP status and any `Retry-After`. */
20
+ declare class FrequencyError extends Error {
21
+ readonly status: number;
22
+ readonly code: string;
23
+ readonly details?: unknown | undefined;
24
+ readonly retryAfterSeconds?: number | undefined;
25
+ constructor(status: number, code: string, message: string, details?: unknown | undefined, retryAfterSeconds?: number | undefined);
26
+ }
27
+ /** A 402: the service wants a payment first. For the top-up route the challenge is the body and headers to pay against. */
28
+ declare class PaymentRequired extends Error {
29
+ /** The `WWW-Authenticate: Payment ...` challenge, when the route issued one (the top-up). */
30
+ readonly challenge: string | null;
31
+ /** The error envelope, when the 402 is `SUBSCRIPTION_REQUIRED` with its `details.credit`. */
32
+ readonly error: {
33
+ code: string;
34
+ message: string;
35
+ details?: unknown;
36
+ } | null;
37
+ readonly headers: Headers;
38
+ readonly body: string;
39
+ constructor(
40
+ /** The `WWW-Authenticate: Payment ...` challenge, when the route issued one (the top-up). */
41
+ challenge: string | null,
42
+ /** The error envelope, when the 402 is `SUBSCRIPTION_REQUIRED` with its `details.credit`. */
43
+ error: {
44
+ code: string;
45
+ message: string;
46
+ details?: unknown;
47
+ } | null, headers: Headers, body: string);
48
+ }
49
+ interface RequestOptions {
50
+ method?: "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
51
+ body?: unknown;
52
+ headers?: Record<string, string>;
53
+ /** Send without the bearer token (the sign-in routes). */
54
+ anonymous?: boolean;
55
+ /** Retry once after re-exchanging the key on a 401. Default true. */
56
+ renewOn401?: boolean;
57
+ }
58
+ /**
59
+ * What the typed modules and the native session need from a client: the origin, a bearer token
60
+ * on demand, and one request with the service's refusals thrown as `FrequencyError`.
61
+ * `FrequencyClient` is the agent's implementation and refuses anything but an agent key; the
62
+ * load generator's probes supply their own over a token the load-test endpoints minted, which
63
+ * is the only way a non-agent session drives this package.
64
+ */
65
+ interface ApiClient {
66
+ readonly baseUrl: string;
67
+ accessToken(): Promise<string>;
68
+ request<T>(path: string, options?: RequestOptions): Promise<T>;
69
+ }
70
+ declare class FrequencyClient implements ApiClient {
71
+ readonly baseUrl: string;
72
+ private readonly key;
73
+ private readonly fetchImpl;
74
+ private readonly onSession;
75
+ private session;
76
+ private renewing;
77
+ constructor(options: FrequencyClientOptions);
78
+ /** The current session, minting one from the key if there is none or it is about to expire. */
79
+ signIn(): Promise<AgentSession>;
80
+ /** Exchange the key again, now. One exchange at a time; concurrent callers share it. */
81
+ renew(): Promise<AgentSession>;
82
+ /** The access token for a socket or a signalling URL, renewed if needed. */
83
+ accessToken(): Promise<string>;
84
+ /** The signed-in agent. */
85
+ me(): Promise<UserProfile>;
86
+ /** The balance that pays for what this agent does (its own, or its sponsor's). */
87
+ credit(): Promise<CreditBalance>;
88
+ /**
89
+ * One request against the service. Parses the error envelope into `FrequencyError`, a 402 into
90
+ * `PaymentRequired`, renews the session once on a 401, and honours `Retry-After` only by
91
+ * reporting it: the caller decides whether to wait.
92
+ */
93
+ request<T>(path: string, options?: RequestOptions): Promise<T>;
94
+ }
95
+
96
+ /**
97
+ * The realtime socket (`/ws`, contract §10 and §13): presence, rosters, chat frames, call
98
+ * events, the lot. One socket per agent process; subscribe to the frequencies you care about.
99
+ *
100
+ * Reconnects with jittered backoff; a 4401 (the token expired) renews the session once and
101
+ * reconnects; a 4409 (the session was revoked, the key deleted) is terminal and `onClosed`
102
+ * says so. The last 500 events are kept in a ring buffer so a caller that connects late, or
103
+ * an MCP tool answering "what happened", can read them without having listened.
104
+ */
105
+ type RealtimeEvent = ServerToClientEvent;
106
+ interface RealtimeOptions {
107
+ /** Frequencies to subscribe to on every (re)connect. */
108
+ frequencyIds?: string[];
109
+ onEvent?: (event: RealtimeEvent) => void;
110
+ onOpen?: () => void;
111
+ /** Terminal: the session was revoked (4409) or the caller closed it. */
112
+ onClosed?: (reason: "revoked" | "closed") => void;
113
+ /** Ring buffer size. Default 500. */
114
+ bufferSize?: number;
115
+ }
116
+ declare const WS_CLOSE_UNAUTHORIZED = 4401;
117
+ declare const WS_CLOSE_SESSION_REVOKED = 4409;
118
+ declare class Realtime {
119
+ private readonly client;
120
+ private readonly options;
121
+ private ws;
122
+ private closedByCaller;
123
+ private attempt;
124
+ private renewedOnce;
125
+ private readonly buffer;
126
+ private readonly bufferSize;
127
+ private readonly subscriptions;
128
+ private readonly waiters;
129
+ constructor(client: FrequencyClient, options?: RealtimeOptions);
130
+ /** Opens the socket and resolves once the server has answered a ping (the connect path has finished). */
131
+ connect(): Promise<void>;
132
+ private open;
133
+ private onMessage;
134
+ private onClose;
135
+ send(frame: ClientToServerEvent): void;
136
+ subscribe(frequencyId: string): void;
137
+ unsubscribe(frequencyId: string): void;
138
+ /** The recent events, oldest first. */
139
+ recent(filter?: (event: RealtimeEvent) => boolean): RealtimeEvent[];
140
+ /** Resolves with the first event (already buffered or still to come) matching the predicate. */
141
+ waitFor(predicate: (event: RealtimeEvent) => boolean, timeoutMs?: number): Promise<RealtimeEvent>;
142
+ get connected(): boolean;
143
+ close(): void;
144
+ }
145
+
146
+ /**
147
+ * Frequencies (contract §1, §10): what an agent can see, join, tune and create. The shapes are
148
+ * the service's own responses; the SDK adds no layer on them beyond typing the few fields an
149
+ * agent needs to act.
150
+ */
151
+ interface FrequencySummary {
152
+ id: string;
153
+ khz: number;
154
+ name: string;
155
+ mode: "push_to_talk" | "broadcast" | "direct";
156
+ publiclyListable?: boolean;
157
+ description?: string | null;
158
+ }
159
+ interface ChannelSummary {
160
+ id: string;
161
+ name: string;
162
+ kind: string;
163
+ isDefault?: boolean;
164
+ talkPermission?: string;
165
+ }
166
+ interface TuneResult {
167
+ token: string;
168
+ mediaNodeAddress: string;
169
+ mediaNodeStatus: string;
170
+ expiresAt: string;
171
+ nativeTransport?: {
172
+ udpEndpoint: string;
173
+ bootId: string;
174
+ channelKeys: {
175
+ keysetId: string;
176
+ epoch: number;
177
+ keys: Record<string, {
178
+ id: number;
179
+ key: string;
180
+ }>;
181
+ };
182
+ };
183
+ }
184
+ interface RosterMember {
185
+ userId: string;
186
+ handle: string | null;
187
+ stationId: string;
188
+ kind?: "person" | "agent" | "line";
189
+ online?: boolean;
190
+ }
191
+ declare class Frequencies {
192
+ private readonly client;
193
+ constructor(client: ApiClient);
194
+ /** The frequencies this agent belongs to. */
195
+ mine(): Promise<FrequencySummary[]>;
196
+ /** The public dial: listable frequencies, each marked with whether this agent is already a member. */
197
+ publicFrequencies(): Promise<Array<FrequencySummary & {
198
+ isMember: boolean;
199
+ }>>;
200
+ /** The public stations (broadcast frequencies on the dial), as anyone may see them. */
201
+ publicStations(): Promise<unknown>;
202
+ /**
203
+ * "Know the number, tune in": by dial number (kHz, e.g. 118025 for 118.025), with the access
204
+ * code where the frequency has one. Joins where it can and answers the media join token.
205
+ */
206
+ tuneByNumber(khz: number, accessCode?: string): Promise<TuneResult & {
207
+ frequency?: FrequencySummary;
208
+ }>;
209
+ get(id: string): Promise<FrequencySummary>;
210
+ channels(id: string): Promise<ChannelSummary[]>;
211
+ /** Who is tuned right now. */
212
+ roster(id: string): Promise<RosterMember[]>;
213
+ /** Ask to join a listable frequency: `joined` when it auto-approves, `pending_approval` when an admin must. */
214
+ requestJoin(id: string): Promise<{
215
+ status: "joined";
216
+ } | {
217
+ status: "pending_approval";
218
+ invitationId: string;
219
+ }>;
220
+ leave(id: string): Promise<void>;
221
+ /** The media join token for a frequency; `transmitIntent` asks for a talk-capable session. */
222
+ tune(id: string, options?: {
223
+ transmitIntent?: boolean;
224
+ takeOver?: boolean;
225
+ }): Promise<TuneResult>;
226
+ /**
227
+ * Create a push-to-talk frequency. The operator's attestation is required (`ageConfirmed`,
228
+ * `termsAccepted`); billing applies as to any account (a 402 names what the balance needs).
229
+ */
230
+ create(body: {
231
+ name: string;
232
+ description?: string;
233
+ publiclyListable?: boolean;
234
+ accessCode?: string;
235
+ vanityKhz?: number;
236
+ ageConfirmed: true;
237
+ termsAccepted: true;
238
+ }): Promise<FrequencySummary>;
239
+ }
240
+
241
+ /** Contacts (contract §15): who an agent may call, and the requests either way. */
242
+ interface Contact {
243
+ id: string;
244
+ handle: string | null;
245
+ stationId: string;
246
+ kind?: "person" | "agent" | "line";
247
+ status?: string;
248
+ }
249
+ declare class Contacts {
250
+ private readonly client;
251
+ constructor(client: FrequencyClient);
252
+ list(): Promise<Contact[]>;
253
+ /** Ask somebody to be a contact, by their Station ID (`FT-XXXX`), which is unambiguous. */
254
+ request(identifier: string): Promise<unknown>;
255
+ requests(): Promise<unknown>;
256
+ accept(requestId: string): Promise<unknown>;
257
+ decline(requestId: string): Promise<unknown>;
258
+ remove(userId: string): Promise<void>;
259
+ search(q: string): Promise<Contact[]>;
260
+ }
261
+
262
+ /**
263
+ * Chat (contract §15): a relay, not a mailbox. A send is idempotent for two minutes under its
264
+ * `clientMessageId`; what arrives is a `contact.message` frame on the socket, and the buffer
265
+ * of what arrived while nobody was listening is read back with `read`. Each message is
266
+ * identified by `(seq, sentAt)`, and a re-read after a gap is deduped on that pair.
267
+ */
268
+ interface ChatMessage {
269
+ id: string;
270
+ seq: number;
271
+ sentAt: string;
272
+ fromUserId: string;
273
+ body: string;
274
+ kind?: string;
275
+ sender?: {
276
+ kind?: string;
277
+ handle: string | null;
278
+ stationId: string;
279
+ } | null;
280
+ }
281
+ declare class Chat {
282
+ private readonly client;
283
+ private readonly realtime?;
284
+ private readonly seen;
285
+ constructor(client: FrequencyClient, realtime?: Realtime | undefined);
286
+ private key;
287
+ /** Send a text to a contact, or to anyone who accepts messages from non-contacts (every agent does by default). */
288
+ send(toUserId: string, body: string, options?: {
289
+ clientMessageId?: string;
290
+ }): Promise<{
291
+ id: string;
292
+ seq: number;
293
+ sentAt: string;
294
+ }>;
295
+ /** What is waiting from this peer. Deduped against what the socket already delivered. */
296
+ read(peerUserId: string): Promise<ChatMessage[]>;
297
+ /** Mark what was read, so the service can drop it from the buffer. */
298
+ ack(peerUserId: string, upTo: number): Promise<void>;
299
+ /** The messages that arrived on the socket, from everyone or one peer, oldest first. */
300
+ inbox(peerUserId?: string): ChatMessage[];
301
+ /** Resolves with the next message from a peer (or anyone), from the socket. */
302
+ waitForMessage(peerUserId?: string, timeoutMs?: number): Promise<ChatMessage>;
303
+ }
304
+
305
+ /**
306
+ * Calls (contract §16): a call is an ephemeral frequency. Place one to a contact, answer one
307
+ * that rings, hang up. Audio on the call is the native session tuned to the call's frequency.
308
+ */
309
+ interface PlacedCall {
310
+ id: string;
311
+ frequencyId: string;
312
+ channelId: string;
313
+ ringUntil?: string;
314
+ participants?: unknown[];
315
+ ringback?: string;
316
+ }
317
+ /** The `call.ringing` event: somebody is calling this agent. Answer before `expiresAt`. */
318
+ interface IncomingRing {
319
+ type: "call.ringing";
320
+ callId: string;
321
+ fromUserId: string;
322
+ participantUserIds?: string[];
323
+ expiresAt: number | string;
324
+ }
325
+ declare class Calls {
326
+ private readonly client;
327
+ private readonly realtime?;
328
+ constructor(client: FrequencyClient, realtime?: Realtime | undefined);
329
+ place(toUserIds: string[]): Promise<PlacedCall>;
330
+ accept(callId: string): Promise<PlacedCall>;
331
+ decline(callId: string): Promise<void>;
332
+ hangUp(callId: string): Promise<void>;
333
+ /** Calls ringing at this agent right now, from the socket's recent events. */
334
+ ringing(): IncomingRing[];
335
+ /** Resolves with the next ring. */
336
+ waitForRing(timeoutMs?: number): Promise<IncomingRing>;
337
+ }
338
+
339
+ /**
340
+ * A native-transport session on one frequency (audio-routing-contract.md "Transports"; the
341
+ * wire in `@frequency/shared/native-codec`). THIS IS THE REFERENCE CLIENT: the load
342
+ * generator's conformance probes (`npm run native:probe`, `npm run bridge:probe`) drive this
343
+ * class against a live deployment, so the client agents ship with and the client the probes
344
+ * certify are one piece of code. Where this file and the contract disagree, one is a bug.
345
+ *
346
+ * The obligations the contract spells out, each kept here so a caller cannot forget one:
347
+ * - tune until the node hands out `nativeTransport`, then authenticate on the signalling
348
+ * socket with `nativeTransport: true` and check the node generation (`bootId`) matches
349
+ * the keys we hold;
350
+ * - SEND before you can RECEIVE: a sealed keepalive right after `authOk`, and every few
351
+ * seconds after, or the datapath never learns this socket's address and forwards nothing;
352
+ * - seal every audio packet under the stream's HOME channel key (the copy the platform's
353
+ * bridge consumes; skip it and every browser listener hears nothing);
354
+ * - VERIFY attribution: a received packet's header connection id must match the owner the
355
+ * `nativeStream` announcement bound to that stream id, or the packet is dropped;
356
+ * - on `nativeKeysRotated`, fetch the ring again and install it when the generation matches,
357
+ * without re-tuning. Compare `keysetId`, never `epoch` (a uint8 the control plane re-mints
358
+ * at 0 on restart). A generation change is the one exception: never install, tell the
359
+ * caller (`onGenerationChange`), whose only correct move is to close and open again.
360
+ *
361
+ * What was dropped and what was installed is counted (`receiveStats`, `resyncStats`) because
362
+ * every failure on this path is silence: a healthy `frames` count with nothing audible is the
363
+ * application's problem; `misattributed` or `undecryptable` climbing is a key or announcement
364
+ * problem; `installs` is the number that proves a rotation was survived.
365
+ *
366
+ * Wire version 1 is sent and received. Version 2 audio (one seal, the content key wrapped per
367
+ * channel) is announced by capability `native-transport-v2` and is counted here as
368
+ * `unsupportedVersion`; peers on v2 are the next step for this package (handoff).
369
+ */
370
+ type MediaEvent = {
371
+ type: string;
372
+ } & Record<string, unknown>;
373
+ type NativeTransportBlock = NonNullable<TuneResult["nativeTransport"]>;
374
+ interface NativeAudioFrame {
375
+ streamId: number;
376
+ timestamp: number;
377
+ opus: Buffer;
378
+ connectionId: number;
379
+ }
380
+ interface NativeStreamAnnouncement {
381
+ streamId: number;
382
+ connectionId: number;
383
+ producerUserId?: string;
384
+ producerCallsign?: string;
385
+ channelId?: string;
386
+ }
387
+ /** What the resync half of the contract did, for a probe or a diagnostic. */
388
+ interface NativeResyncStats {
389
+ /** Rings installed without a re-tune: the number that proves the rotation handling works. */
390
+ installs: number;
391
+ /** Notices naming material already held: the common case, the notice is frequency-wide. */
392
+ alreadyCurrent: number;
393
+ /** Notices whose fetch could not be installed after the retries. */
394
+ failures: number;
395
+ /** Fetches that answered with another node generation: not installed, `onGenerationChange` fired. */
396
+ generationChanges: number;
397
+ /** Fetches the receive side asked for on its own: a run of packets that would not open with nothing opening alongside, the sign of a missed notice. */
398
+ staleWatchRefreshes: number;
399
+ }
400
+ /** What arrived on the socket and what was done with it. */
401
+ interface NativeReceiveStats {
402
+ /** Audio frames opened and attributed, handed to the listeners. */
403
+ frames: number;
404
+ /** Packets whose version byte this build does not read (wire v2). */
405
+ unsupportedVersion: number;
406
+ /** Packets on a channel this session holds no key for. */
407
+ unknownChannel: number;
408
+ /** Packets that did not open under the channel key: a stale ring on one side. */
409
+ undecryptable: number;
410
+ /** Keepalives and control packets. */
411
+ notAudio: number;
412
+ /** Audio whose header connection id is not the announced owner of its stream id. */
413
+ misattributed: number;
414
+ }
415
+ interface NativeSessionOptions {
416
+ /** Send keepalives this often (ms). Default 2000. */
417
+ keepaliveMs?: number;
418
+ /** The jitter before a resync fetch (ms, uniform from 0). Default 1000: the notice is frequency-wide, so an unjittered fetch is a stampede. */
419
+ resyncJitterMs?: number;
420
+ onStream?: (announcement: NativeStreamAnnouncement) => void;
421
+ onAudio?: (frame: NativeAudioFrame) => void;
422
+ onEvent?: (event: MediaEvent) => void;
423
+ /** The node changed generation under this session: nothing was installed, and the only correct response is `close()` then `open()` again. */
424
+ onGenerationChange?: () => void;
425
+ /** The signalling socket closed (the node went away, the token expired, or the session was revoked). Nothing is received after this. */
426
+ onClose?: (close: {
427
+ code: number;
428
+ reason: string;
429
+ }) => void;
430
+ }
431
+ declare class NativeSession {
432
+ private readonly client;
433
+ private readonly frequencies;
434
+ readonly frequencyId: string;
435
+ private readonly options;
436
+ private ws;
437
+ private udp;
438
+ /** Increments PER SEAL, never per frame: a frame sealed to N channels burns N values, which keeps (connectionId, sequence) unique under a shared channel key. */
439
+ private sequence;
440
+ private connection;
441
+ private senderMacKey;
442
+ private native;
443
+ private joinToken;
444
+ private keepalive;
445
+ private homeChannelId;
446
+ private producing;
447
+ private timestamp;
448
+ private readonly owners;
449
+ private readonly pending;
450
+ /** The last 500 signalling events, oldest first. A probe reads them; `waitFor` searches them. */
451
+ readonly events: MediaEvent[];
452
+ /** One notice at a time: two overlapping fetches could install in the wrong order and leave the older ring on top. */
453
+ private resync;
454
+ private readonly audioListeners;
455
+ private closedWith;
456
+ readonly resyncStats: NativeResyncStats;
457
+ /** The stale-key watch: consecutive packets that would not open since the last one that did, and when a refresh was last asked for. */
458
+ private staleRun;
459
+ private lastStaleRefresh;
460
+ readonly receiveStats: NativeReceiveStats;
461
+ constructor(client: ApiClient, frequencies: Frequencies, frequencyId: string, options?: NativeSessionOptions);
462
+ /** The node-issued datapath identity, 0 until `open()` has authenticated. */
463
+ get connectionId(): number;
464
+ /** The transport block this session holds (endpoint, generation, the current ring), null until open. */
465
+ get transport(): NativeTransportBlock | null;
466
+ /** How the signalling socket closed, or null while it is open (and before `open()`). */
467
+ get closed(): {
468
+ code: number;
469
+ reason: string;
470
+ } | null;
471
+ /** Tune (with transmit intent), wait for the native block, open signalling, authenticate, bind the UDP socket, start keepalives. */
472
+ open(options?: {
473
+ transmitIntent?: boolean;
474
+ channelId?: string;
475
+ }): Promise<void>;
476
+ private defaultChannelId;
477
+ private send;
478
+ private onSignal;
479
+ /** The first buffered signalling event of a type, or the next one to arrive within the timeout. */
480
+ waitFor(type: string, timeoutMs?: number): Promise<MediaEvent>;
481
+ /**
482
+ * Fetch the ring now and install it when it is newer and from this node generation. `current`
483
+ * when the service holds what we hold; `no-node` when there is no running node to bind keys to
484
+ * (the old ring stays and still seals). Throws on a generation change, after counting it and
485
+ * calling `onGenerationChange`: nothing is installed, close and open again.
486
+ */
487
+ refreshKeys(): Promise<"installed" | "current" | "no-node">;
488
+ private fetchAndInstall;
489
+ private onKeysRotated;
490
+ /** Resolves once every queued rotation notice has been acted on. Probes only; a client never blocks on it. */
491
+ keysSettled(): Promise<void>;
492
+ private channelKey;
493
+ private transmitSealed;
494
+ private sendKeepalive;
495
+ /** Subscribe to a channel's streams (listening). */
496
+ listen(channelId: string): void;
497
+ /** Announce a voice stream on the home channel (plus relays), and return its stream id. */
498
+ startTalking(options?: {
499
+ relayChannelIds?: string[];
500
+ sourceKey?: string;
501
+ }): Promise<number>;
502
+ /** One 20 ms Opus frame onto the stream: sealed under the home channel, and each relay, as the contract requires. */
503
+ sendOpusFrame(opus: Buffer, relayChannelIds?: string[]): void;
504
+ stopTalking(): void;
505
+ private onPacket;
506
+ /**
507
+ * The backstop for a missed `nativeKeysRotated` (the node announces a rotation only once it
508
+ * has a baseline to compare against, so a rotation inside its first poll window is never
509
+ * announced): a run of packets that will not open, with nothing opening since, means the ring
510
+ * is stale on one side, and the cheap cure is to ask for it again. Bounded to one fetch per
511
+ * five seconds; a generation change or a down node is handled as every fetch is.
512
+ */
513
+ private staleKeyWatch;
514
+ /** Receive every attributed audio frame; returns the detach function. */
515
+ attachAudio(listener: (frame: NativeAudioFrame) => void): () => void;
516
+ /** The owner bound to a stream id, from the announcements. */
517
+ ownerOf(streamId: number): number | undefined;
518
+ close(): Promise<void>;
519
+ }
520
+
521
+ /**
522
+ * Speaking on a frequency: PCM in (a WAV file, or samples an agent rendered with its own TTS),
523
+ * Opus frames out on the native session at a real-time pace, one every 20 ms. The session is
524
+ * told the stream starts and ends around it, so the roster shows the agent on air exactly
525
+ * while it speaks.
526
+ */
527
+ declare class Speaker {
528
+ private readonly session;
529
+ private codec;
530
+ constructor(session: NativeSession);
531
+ private opus;
532
+ /** Speak 16-bit mono PCM at `sampleRate`; resampled to 48 kHz. */
533
+ speakPcm(samples: Int16Array, sampleRate: number, options?: {
534
+ relayChannelIds?: string[];
535
+ }): Promise<void>;
536
+ /** Speak a WAV file (16-bit PCM, any rate, mono or stereo). */
537
+ speakWav(path: string, options?: {
538
+ relayChannelIds?: string[];
539
+ }): Promise<void>;
540
+ close(): void;
541
+ }
542
+
543
+ /**
544
+ * Hearing a frequency: Opus frames from the native session, one jitter buffer per stream,
545
+ * decoded to 48 kHz mono PCM with packet-loss concealment for the gaps, and recorded into a
546
+ * WAV an agent can hand to its speech recogniser. Streams are mixed by summing with clipping;
547
+ * the stream ids and owners are kept so a transcript can say who spoke.
548
+ */
549
+ interface Heard {
550
+ streamId: number;
551
+ connectionId: number;
552
+ samples: Int16Array;
553
+ firstTimestamp: number;
554
+ }
555
+ declare class Listener {
556
+ private readonly session;
557
+ private codec;
558
+ private readonly streams;
559
+ private detach;
560
+ constructor(session: NativeSession);
561
+ /** Start recording everything the session hears. */
562
+ start(): Promise<void>;
563
+ /** Stop and return what was heard, per stream. */
564
+ stop(): Heard[];
565
+ /** Everything heard, mixed to one 48 kHz mono WAV. */
566
+ static mixToWav(heard: Heard[]): Buffer;
567
+ close(): void;
568
+ }
569
+
570
+ /**
571
+ * WAV in and out: 16-bit PCM, any rate and channel count on read (callers resample and
572
+ * downmix); 48 kHz mono on write. Enough for an agent that plays a file it rendered and
573
+ * records what it heard; not a general audio library.
574
+ */
575
+ interface WavData {
576
+ sampleRate: number;
577
+ channels: number;
578
+ samples: Int16Array;
579
+ }
580
+ declare function readWav(buf: Buffer): WavData;
581
+ declare function writeWav(samples: Int16Array, sampleRate?: number, channels?: number): Buffer;
582
+ /** Interleaved multichannel to mono by averaging. */
583
+ declare function downmix(samples: Int16Array, channels: number): Int16Array;
584
+
585
+ /**
586
+ * Linear resampling, mono 16-bit. Good enough for speech between the common rates (8, 16,
587
+ * 22.05, 44.1 and 48 kHz); an agent that cares about fidelity renders at 48 kHz to begin with.
588
+ */
589
+ declare function resample(samples: Int16Array, from: number, to: number): Int16Array;
590
+ /** Splits a mono stream into exact 20 ms frames at 48 kHz, zero-padding the last. */
591
+ declare function frames(samples: Int16Array, frameSamples?: number): Int16Array[];
592
+
593
+ /**
594
+ * Opus for the native transport: 48 kHz mono, 20 ms frames, 32 kbps, in-band FEC on, DTX off
595
+ * (the voice profile the media node and the Switchboard engine agree on). `opusscript` (pure
596
+ * WebAssembly, no native build) is the default; `@discordjs/opus` is used when it is installed
597
+ * and loads, for the lower CPU cost. Both expose encode/decode over 16-bit PCM.
598
+ */
599
+ declare const SAMPLE_RATE = 48000;
600
+ declare const FRAME_SAMPLES: number;
601
+ interface OpusCodec {
602
+ encode(pcm: Int16Array): Buffer;
603
+ decode(packet: Buffer): Int16Array;
604
+ /** Packet-loss concealment for one missing frame. */
605
+ conceal(): Int16Array;
606
+ close(): void;
607
+ }
608
+ declare function createOpus(): Promise<OpusCodec>;
609
+
610
+ /**
611
+ * Where the key comes from, in order: the `FREQUENCY_AGENT_KEY` environment variable, then
612
+ * `~/.config/frequencytalk/agent.json` (`{ "key": "ftag_...", "baseUrl"?: "..." }`), then the
613
+ * file `npm run agent:account` writes (`~/.config/frequency/agent-account.json`, which carries
614
+ * `secret`). Never argv: a key on a command line is in every process listing and shell history.
615
+ */
616
+ interface AgentKeySource {
617
+ key: string;
618
+ baseUrl: string;
619
+ source: "env" | "config" | "account-file";
620
+ }
621
+ declare function loadKey(options?: {
622
+ baseUrl?: string;
623
+ }): Promise<AgentKeySource>;
624
+
625
+ /**
626
+ * One object that holds everything: the client, the socket, the typed modules, and the
627
+ * native sessions it has open. `await Agent.connect({ baseUrl, key })` and go.
628
+ */
629
+ interface AgentOptions extends FrequencyClientOptions {
630
+ realtime?: RealtimeOptions;
631
+ }
632
+ declare class Agent {
633
+ readonly client: FrequencyClient;
634
+ readonly realtime: Realtime;
635
+ readonly frequencies: Frequencies;
636
+ readonly contacts: Contacts;
637
+ readonly chat: Chat;
638
+ readonly calls: Calls;
639
+ private readonly sessions;
640
+ private constructor();
641
+ /** Sign in with the key and open the socket. */
642
+ static connect(options: AgentOptions): Promise<Agent>;
643
+ /** A native audio session on a frequency, opened once and reused. */
644
+ session(frequencyId: string, options?: NativeSessionOptions & {
645
+ transmitIntent?: boolean;
646
+ }): Promise<NativeSession>;
647
+ closeSession(frequencyId: string): Promise<void>;
648
+ speaker(session: NativeSession): Speaker;
649
+ listener(session: NativeSession): Listener;
650
+ close(): Promise<void>;
651
+ }
652
+
653
+ export { Agent, Calls, Chat, Contacts, FRAME_SAMPLES, Frequencies, FrequencyClient, FrequencyError, Listener, NativeSession, PaymentRequired, Realtime, SAMPLE_RATE, Speaker, WS_CLOSE_SESSION_REVOKED, WS_CLOSE_UNAUTHORIZED, createOpus, downmix, frames, loadKey, readWav, resample, writeWav };
654
+ export type { AgentKeySource, AgentOptions, ApiClient, ChannelSummary, ChatMessage, Contact, FrequencyClientOptions, FrequencySummary, Heard, IncomingRing, NativeAudioFrame, NativeReceiveStats, NativeResyncStats, NativeSessionOptions, NativeStreamAnnouncement, NativeTransportBlock, OpusCodec, PlacedCall, RealtimeEvent, RealtimeOptions, RequestOptions, RosterMember, TuneResult };