pi-roundtable 0.47.2 → 0.48.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,230 @@
1
+ import type { Logger } from "../../kernel/log.ts";
2
+ import {
3
+ VOICE_PCM,
4
+ type VoiceDisconnectEvent,
5
+ type VoiceDisconnectReason,
6
+ type VoiceMember,
7
+ type VoiceMemberEvent,
8
+ type VoiceSession,
9
+ type VoiceSpeakingEvent,
10
+ type VoiceUtterance,
11
+ } from "./voice.ts";
12
+ import type { VoiceClock } from "./voice-clock.ts";
13
+
14
+ /** Bytes of `VOICE_PCM` audio in one millisecond. */
15
+ const BYTES_PER_MS =
16
+ (VOICE_PCM.sampleRate * VOICE_PCM.channels * VOICE_PCM.bytesPerSample) /
17
+ 1_000;
18
+
19
+ export interface VoiceSessionOptions {
20
+ guildId: string;
21
+ channelId: string;
22
+ members: readonly VoiceMember[];
23
+ silenceMs: number;
24
+ maxUtteranceMs: number;
25
+ clock: VoiceClock;
26
+ logger: Logger;
27
+ /** What `leave()` does: the service closes the connection and ends the session. */
28
+ leave: () => void;
29
+ }
30
+
31
+ /** One speaker's utterance while it is still heard. */
32
+ interface OpenUtterance {
33
+ chunks: Uint8Array[];
34
+ bytes: number;
35
+ startedAt: number;
36
+ lastAt: number;
37
+ timer: unknown;
38
+ }
39
+
40
+ class Listeners<T> {
41
+ readonly #listeners = new Set<(event: T) => void>();
42
+ readonly #logger: Logger;
43
+ readonly #what: string;
44
+ constructor(logger: Logger, what: string) {
45
+ this.#logger = logger;
46
+ this.#what = what;
47
+ }
48
+ add(listener: (event: T) => void): () => void {
49
+ this.#listeners.add(listener);
50
+ return () => {
51
+ this.#listeners.delete(listener);
52
+ };
53
+ }
54
+ emit(event: T): void {
55
+ for (const listener of [...this.#listeners]) this.call(listener, event);
56
+ }
57
+ /** Never logs the event: an utterance holds audio. */
58
+ call(listener: (event: T) => void, event: T): void {
59
+ try {
60
+ listener(event);
61
+ } catch (error) {
62
+ this.#logger.error({ err: error }, `voice ${this.#what} listener failed`);
63
+ }
64
+ }
65
+ clear(): void {
66
+ this.#listeners.clear();
67
+ }
68
+ }
69
+
70
+ /**
71
+ * A voice session's own state: who is in the channel, and each speaker's audio cut into
72
+ * utterances. Whatever holds the connection (the Discord service, or a test's stand-in) feeds it
73
+ * members and decoded frames and ends it; it keeps audio only until the utterance is delivered.
74
+ */
75
+ export class VoiceSessionState implements VoiceSession {
76
+ readonly guildId: string;
77
+ readonly channelId: string;
78
+ readonly #options: VoiceSessionOptions;
79
+ readonly #members = new Map<string, VoiceMember>();
80
+ readonly #open = new Map<string, OpenUtterance>();
81
+ readonly #maxBytes: number;
82
+ readonly #member: Listeners<VoiceMemberEvent>;
83
+ readonly #speaking: Listeners<VoiceSpeakingEvent>;
84
+ readonly #utterance: Listeners<VoiceUtterance>;
85
+ readonly #disconnect: Listeners<VoiceDisconnectEvent>;
86
+ #ended: VoiceDisconnectReason | undefined;
87
+
88
+ constructor(options: VoiceSessionOptions) {
89
+ this.#options = options;
90
+ this.guildId = options.guildId;
91
+ this.channelId = options.channelId;
92
+ this.#maxBytes = options.maxUtteranceMs * BYTES_PER_MS;
93
+ for (const member of options.members)
94
+ this.#members.set(member.userId, member);
95
+ this.#member = new Listeners(options.logger, "member");
96
+ this.#speaking = new Listeners(options.logger, "speaking");
97
+ this.#utterance = new Listeners(options.logger, "utterance");
98
+ this.#disconnect = new Listeners(options.logger, "disconnect");
99
+ }
100
+
101
+ members(): VoiceMember[] {
102
+ return [...this.#members.values()];
103
+ }
104
+
105
+ onMember(listener: (event: VoiceMemberEvent) => void): () => void {
106
+ return this.#member.add(listener);
107
+ }
108
+
109
+ onSpeaking(listener: (event: VoiceSpeakingEvent) => void): () => void {
110
+ return this.#speaking.add(listener);
111
+ }
112
+
113
+ onUtterance(listener: (utterance: VoiceUtterance) => void): () => void {
114
+ return this.#utterance.add(listener);
115
+ }
116
+
117
+ onDisconnect(listener: (event: VoiceDisconnectEvent) => void): () => void {
118
+ const reason = this.#ended;
119
+ if (reason === undefined) return this.#disconnect.add(listener);
120
+ queueMicrotask(() => this.#disconnect.call(listener, { reason }));
121
+ return () => undefined;
122
+ }
123
+
124
+ ended(): VoiceDisconnectReason | undefined {
125
+ return this.#ended;
126
+ }
127
+
128
+ async leave(): Promise<void> {
129
+ if (this.#ended === undefined) this.#options.leave();
130
+ }
131
+
132
+ /** Someone is in the channel: reported as joined unless they already were. */
133
+ memberJoined(member: VoiceMember): void {
134
+ if (this.#ended !== undefined) return;
135
+ const known = this.#members.has(member.userId);
136
+ this.#members.set(member.userId, member);
137
+ if (!known) this.#member.emit({ kind: "joined", member });
138
+ }
139
+
140
+ /** Someone is no longer in the channel: what they were saying is delivered first. */
141
+ memberLeft(userId: string): void {
142
+ const member = this.#members.get(userId);
143
+ if (this.#ended !== undefined || !member) return;
144
+ this.#finish(userId);
145
+ this.#members.delete(userId);
146
+ this.#member.emit({ kind: "left", member });
147
+ }
148
+
149
+ /** One decoded frame of a speaker, in the `VOICE_PCM` format; the caller keeps no reference to it. */
150
+ frame(userId: string, pcm: Uint8Array): void {
151
+ if (this.#ended !== undefined || pcm.byteLength === 0) return;
152
+ const { clock, silenceMs } = this.#options;
153
+ const now = clock.now();
154
+ let open = this.#open.get(userId);
155
+ /** The utterance this frame cuts off, when the one before it was full. */
156
+ let cut: OpenUtterance | undefined;
157
+ if (!open) {
158
+ open = { chunks: [], bytes: 0, startedAt: now, lastAt: now, timer: 0 };
159
+ open.timer = clock.setTimeout(() => this.#quiet(userId), silenceMs);
160
+ this.#open.set(userId, open);
161
+ this.#speaking.emit({ userId, speaking: true, at: now });
162
+ } else if (open.bytes >= this.#maxBytes) {
163
+ // Full, and only now known to go on: this frame starts the next utterance, in the same breath.
164
+ cut = { ...open };
165
+ open.chunks = [];
166
+ open.bytes = 0;
167
+ open.startedAt = now;
168
+ }
169
+ open.chunks.push(pcm);
170
+ open.bytes += pcm.byteLength;
171
+ open.lastAt = now;
172
+ // Handed over last, with the open utterance already holding what follows: a listener that
173
+ // ends the session here is handed the rest once, and none of this audio again.
174
+ if (cut) this.#deliver(userId, cut, true);
175
+ }
176
+
177
+ /** Ends the session, once: every open utterance is delivered, then the disconnect is reported. */
178
+ end(reason: VoiceDisconnectReason): void {
179
+ if (this.#ended !== undefined) return;
180
+ for (const userId of [...this.#open.keys()]) this.#finish(userId);
181
+ this.#ended = reason;
182
+ this.#members.clear();
183
+ this.#disconnect.emit({ reason });
184
+ for (const listeners of [
185
+ this.#member,
186
+ this.#speaking,
187
+ this.#utterance,
188
+ this.#disconnect,
189
+ ])
190
+ listeners.clear();
191
+ }
192
+
193
+ /** The silence timer fired: the utterance ends if nothing came since, else the timer waits out the rest. */
194
+ #quiet(userId: string): void {
195
+ const open = this.#open.get(userId);
196
+ if (!open) return;
197
+ const { clock, silenceMs } = this.#options;
198
+ const left = open.lastAt + silenceMs - clock.now();
199
+ if (left > 0) {
200
+ open.timer = clock.setTimeout(() => this.#quiet(userId), left);
201
+ return;
202
+ }
203
+ this.#finish(userId);
204
+ }
205
+
206
+ #finish(userId: string): void {
207
+ const open = this.#open.get(userId);
208
+ if (!open) return;
209
+ this.#open.delete(userId);
210
+ this.#options.clock.clearTimeout(open.timer);
211
+ this.#speaking.emit({ userId, speaking: false, at: open.lastAt });
212
+ if (open.bytes > 0) this.#deliver(userId, open, false);
213
+ }
214
+
215
+ #deliver(userId: string, open: OpenUtterance, continues: boolean): void {
216
+ const pcm = new Uint8Array(open.bytes);
217
+ let offset = 0;
218
+ for (const chunk of open.chunks) {
219
+ pcm.set(chunk, offset);
220
+ offset += chunk.byteLength;
221
+ }
222
+ this.#utterance.emit({
223
+ userId,
224
+ pcm,
225
+ startedAt: open.startedAt,
226
+ endedAt: open.lastAt,
227
+ continues,
228
+ });
229
+ }
230
+ }
@@ -0,0 +1,144 @@
1
+ // Discord voice as plugins use it: joining a guild's voice channel to hear who speaks. It names
2
+ // no discord.js type, so a test stands in for it with `fakeDiscordVoice()`.
3
+
4
+ /** Why a voice channel was not joined. */
5
+ export type VoiceJoinFailure =
6
+ | "forbidden" // the bot may not see the channel or connect to it
7
+ | "channel_gone" // the guild has no such channel (any more)
8
+ | "not_voice" // the channel is neither a voice nor a stage channel
9
+ | "full" // the channel is at its user limit, and the bot may not move members
10
+ | "unavailable" // Discord is not connected, the host is stopping, or the voice connection did not come up in time; asking again may work
11
+ | "already_joined"; // the bot has a session in this guild, or is joining one: Discord allows one per guild
12
+
13
+ /** Why a session ended. */
14
+ export type VoiceDisconnectReason =
15
+ | "left" // the plugin called `leave()`
16
+ | "removed" // the bot was disconnected from the channel: someone disconnected it, or the channel was deleted
17
+ | "moved" // someone moved the bot to another channel; a session never follows
18
+ | "connection_lost" // the voice connection dropped and did not come back within the resume time
19
+ | "stopped"; // the host is stopping
20
+
21
+ /** Someone in a voice channel. */
22
+ export interface VoiceMember {
23
+ /** Their Discord user id. */
24
+ userId: string;
25
+ bot: boolean;
26
+ /** What the guild shows for them: the server nickname, else the account's display name. */
27
+ displayName: string;
28
+ }
29
+
30
+ /** Someone entered or left the session's channel. */
31
+ export interface VoiceMemberEvent {
32
+ kind: "joined" | "left";
33
+ member: VoiceMember;
34
+ }
35
+
36
+ /** Someone started or stopped speaking, as the session's utterances are cut. */
37
+ export interface VoiceSpeakingEvent {
38
+ /** The speaker's Discord user id. */
39
+ userId: string;
40
+ speaking: boolean;
41
+ /** When, by the host's clock, in milliseconds since the epoch. */
42
+ at: number;
43
+ }
44
+
45
+ /** The format of every utterance's `pcm`. */
46
+ export const VOICE_PCM = Object.freeze({
47
+ sampleRate: 48_000,
48
+ /** Discord sends stereo; the two channels are mixed down to one. */
49
+ channels: 1,
50
+ /** Signed 16-bit, little-endian. */
51
+ bytesPerSample: 2,
52
+ } as const);
53
+
54
+ /** What one person said from when they started until they went quiet. */
55
+ export interface VoiceUtterance {
56
+ /** The speaker's Discord user id. */
57
+ userId: string;
58
+ /**
59
+ * The decoded audio, in the format `VOICE_PCM` names: 48 kHz, signed 16-bit little-endian,
60
+ * mono. It holds the audio Discord sent and nothing for the pauses inside it, so its length
61
+ * may be shorter than `endedAt - startedAt`. The session keeps no copy.
62
+ */
63
+ pcm: Uint8Array;
64
+ /** When its first audio arrived, by the host's clock, in milliseconds since the epoch. */
65
+ startedAt: number;
66
+ /** When its last audio arrived. */
67
+ endedAt: number;
68
+ /**
69
+ * True when it holds `maxUtteranceMs` of audio and the speaker went on: the rest is their next
70
+ * utterance, which always follows, so a run of `continues` utterances ends with one that says
71
+ * false. One that is full just as its speaker stops says false.
72
+ */
73
+ continues: boolean;
74
+ }
75
+
76
+ /** How a session cuts what it hears into utterances. */
77
+ export interface VoiceJoinOptions {
78
+ /** How long a speaker is quiet before their utterance ends, in milliseconds: 200 to 5,000. Default 800. */
79
+ silenceMs?: number;
80
+ /** The most audio one utterance holds, in milliseconds: 1,000 to 300,000. Default 30,000, about 2.9 MB. */
81
+ maxUtteranceMs?: number;
82
+ }
83
+
84
+ /** The session ended; it reports nothing after this. */
85
+ export interface VoiceDisconnectEvent {
86
+ reason: VoiceDisconnectReason;
87
+ }
88
+
89
+ /** What `join` answers: the session, or why there is none. */
90
+ export type VoiceJoinResult =
91
+ | { ok: true; session: VoiceSession }
92
+ | {
93
+ ok: false;
94
+ failure: VoiceJoinFailure;
95
+ /** The failure in words, for a log or the person who asked; never audio. */
96
+ message: string;
97
+ };
98
+
99
+ /**
100
+ * The bot in one voice channel, muted and listening. Every `on…` returns a function that removes
101
+ * the listener; a listener that throws is logged and never stops the next.
102
+ */
103
+ export interface VoiceSession {
104
+ readonly guildId: string;
105
+ readonly channelId: string;
106
+ /** Who is in the channel now, without the bot itself; empty once the session ended. */
107
+ members(): VoiceMember[];
108
+ /** Someone entered or left the channel. */
109
+ onMember(listener: (event: VoiceMemberEvent) => void): () => void;
110
+ /**
111
+ * Someone started or stopped speaking: `speaking: true` with the first audio of an utterance,
112
+ * `speaking: false` once they were quiet for `silenceMs`, just before the utterance is delivered.
113
+ */
114
+ onSpeaking(listener: (event: VoiceSpeakingEvent) => void): () => void;
115
+ /**
116
+ * A finished utterance of one speaker. One arrives when the speaker went quiet, when their
117
+ * utterance is full at `maxUtteranceMs` and they go on (`continues: true`), when they left the
118
+ * channel, and when the session ends, so no audio heard is dropped.
119
+ */
120
+ onUtterance(listener: (utterance: VoiceUtterance) => void): () => void;
121
+ /** The session ended, once; a listener added after the end is called at once. */
122
+ onDisconnect(listener: (event: VoiceDisconnectEvent) => void): () => void;
123
+ /** Why the session ended; undefined while it is open. */
124
+ ended(): VoiceDisconnectReason | undefined;
125
+ /** Leaves the channel and ends the session with `left`; does nothing once it ended. */
126
+ leave(): Promise<void>;
127
+ }
128
+
129
+ /**
130
+ * Discord voice for plugins: `DISCORD.voice`, there only when the host's `discord.voice` is on.
131
+ * The bot joins muted and not deafened, hears each speaker apart, and never speaks.
132
+ */
133
+ export interface DiscordVoice {
134
+ /**
135
+ * Joins a voice or stage channel of a guild. Never rejects for something Discord refuses: the
136
+ * answer names the failure. Throws a RangeError for an option out of its range.
137
+ */
138
+ join(
139
+ target: { guildId: string; channelId: string },
140
+ options?: VoiceJoinOptions,
141
+ ): Promise<VoiceJoinResult>;
142
+ /** The open session in a guild, if there is one. */
143
+ session(guildId: string): VoiceSession | undefined;
144
+ }
@@ -170,6 +170,7 @@ function discordAssembly(
170
170
  ? {}
171
171
  : { formatting: discord.formatting }),
172
172
  ...(discord.memberEvents ? { memberEvents: true } : {}),
173
+ ...(discord.voice ? { voice: true } : {}),
173
174
  cardGraceMs: discord.cardGraceSeconds * 1_000,
174
175
  cardCopies: discord.cardCopies,
175
176
  }),
@@ -8,6 +8,7 @@ import type {
8
8
  } from "../discord/interaction-module.ts";
9
9
  import { commandGuard, ownerRootCommand } from "../discord/owner-command.ts";
10
10
  import type { DiscordPoster } from "../discord/poster/poster.ts";
11
+ import type { DiscordVoice } from "../discord/voice/voice.ts";
11
12
  import { silentLogger } from "../kernel/log.ts";
12
13
  import { fakeDiscordPoster } from "./fake-poster.ts";
13
14
  import { type ServicePair, servicePair } from "./service-pair.ts";
@@ -32,8 +33,10 @@ export interface FakeDiscord {
32
33
  * A `DISCORD` service for a plugin that adds slash commands, without a Discord connection: the
33
34
  * plugin's `commands.add` calls are recorded, and `compose()` shows the tree Discord would get.
34
35
  * `rootCommand` is the root command's name, `roundtable` by default. `channelContext` is what
35
- * `DISCORD.channelContext` answers, by default no context, as on a host with it off. Only
36
- * `commands`, `guard`, `poster`, and `channelContext` are given; reading another member throws.
36
+ * `DISCORD.channelContext` answers, by default no context, as on a host with it off. `voice` is
37
+ * what `DISCORD.voice` is, such as a `fakeDiscordVoice()`; without it the plugin reads none, as on
38
+ * a host with `discord.voice` off. Only `commands`, `guard`, `poster`, `channelContext`, and
39
+ * `voice` are given; reading another member throws.
37
40
  */
38
41
  export function fakeDiscord(
39
42
  options: {
@@ -41,6 +44,7 @@ export function fakeDiscord(
41
44
  rootCommand?: string;
42
45
  channelContext?: DiscordServices["channelContext"];
43
46
  poster?: DiscordPoster;
47
+ voice?: DiscordVoice;
44
48
  } = {},
45
49
  ): FakeDiscord {
46
50
  const collection = new CommandCollection();
@@ -57,6 +61,7 @@ export function fakeDiscord(
57
61
  guard,
58
62
  poster,
59
63
  channelContext: options.channelContext ?? (async () => undefined),
64
+ voice: options.voice,
60
65
  }),
61
66
  poster,
62
67
  commands: collection.registrar,
@@ -0,0 +1,227 @@
1
+ import type {
2
+ DiscordVoice,
3
+ VoiceDisconnectReason,
4
+ VoiceMember,
5
+ } from "../discord/voice/voice.ts";
6
+ import { manualVoiceClock } from "../discord/voice/voice-clock.ts";
7
+ import {
8
+ type VoiceLinkHandlers,
9
+ type VoiceLinkStatus,
10
+ type VoiceStateChange,
11
+ voiceService,
12
+ } from "../discord/voice/voice-service.ts";
13
+ import { silentLogger } from "../kernel/log.ts";
14
+
15
+ /** A channel of the fake's Discord. */
16
+ export interface FakeVoiceChannel {
17
+ guildId: string;
18
+ /** Default `voice`; `text` stands for every channel that is not joined by voice. */
19
+ kind?: "voice" | "stage" | "text";
20
+ /** Who is in it; `enter` and `exit` change it. Default nobody. */
21
+ members?: VoiceMember[];
22
+ /** The bot may not see it or connect to it. */
23
+ forbidden?: boolean;
24
+ /** It is at its user limit. */
25
+ full?: boolean;
26
+ }
27
+
28
+ /** What a test reads and drives on the fake voice, besides the `DiscordVoice` calls. */
29
+ export interface FakeDiscordVoice extends DiscordVoice {
30
+ /** The channels that exist, by id; a join of any other answers `channel_gone`. */
31
+ readonly channels: Map<string, FakeVoiceChannel>;
32
+ /** Whether Discord is connected; `false` makes a join answer `unavailable`. */
33
+ available: boolean;
34
+ /** Every join asked for, in order, whatever it answered. */
35
+ readonly joins: { guildId: string; channelId: string }[];
36
+ /** Every session that ended, in order, with why: `left` for the plugin's own `leave()`. */
37
+ readonly ended: {
38
+ guildId: string;
39
+ channelId: string;
40
+ reason: VoiceDisconnectReason;
41
+ }[];
42
+ /** The bot's user id, which is never among a session's members. */
43
+ readonly botId: string;
44
+ /** Someone enters a channel, leaving the one they were in. */
45
+ enter(channelId: string, member: VoiceMember): void;
46
+ /** Someone leaves a channel. */
47
+ exit(channelId: string, userId: string): void;
48
+ /**
49
+ * One frame of someone speaking in a channel, as 48 kHz 16-bit mono PCM; they must be in it.
50
+ * A session in that channel hears it, and its clock moves on by the frame's length. Their
51
+ * utterance stays open until `quiet()`.
52
+ */
53
+ audio(channelId: string, userId: string, pcm: Uint8Array): void;
54
+ /** Everyone stops speaking: five seconds pass, so every open utterance ends. */
55
+ quiet(): void;
56
+ /** `audio` for each frame, then `quiet()`: one whole utterance. */
57
+ say(channelId: string, userId: string, ...frames: Uint8Array[]): void;
58
+ /** Ends the guild's session from outside: the bot is disconnected, moved elsewhere, or loses its connection for good. */
59
+ drop(guildId: string, how: "removed" | "moved" | "connection_lost"): void;
60
+ /** The host stops: every session ends with `stopped`, and joins answer `unavailable`. */
61
+ stop(): Promise<void>;
62
+ }
63
+
64
+ const BOT: VoiceMember = {
65
+ userId: "900000000000000001",
66
+ bot: true,
67
+ displayName: "bot",
68
+ };
69
+ /** Bytes of a millisecond of 48 kHz 16-bit mono. */
70
+ const BYTES_PER_MS = 96;
71
+ /** Longer than any `silenceMs` a join may ask for. */
72
+ const QUIET_MS = 5_000;
73
+
74
+ /**
75
+ * `DISCORD.voice` in memory, for a plugin's tests: the real session logic (members, utterances,
76
+ * one session per guild, the join failures) over a Discord the test drives. Give it to
77
+ * `fakeDiscord({ voice })` or `testHost({ discord: { voice } })`. `now` is where its clock starts.
78
+ */
79
+ export function fakeDiscordVoice(
80
+ options: { now?: number } = {},
81
+ ): FakeDiscordVoice {
82
+ const clock = manualVoiceClock(options.now);
83
+ const channels = new Map<string, FakeVoiceChannel>();
84
+ const joins: FakeDiscordVoice["joins"] = [];
85
+ const ended: FakeDiscordVoice["ended"] = [];
86
+ /** The open connection of each guild: where the bot is, and who listens. */
87
+ const links = new Map<
88
+ string,
89
+ { channelId: string; handlers: VoiceLinkHandlers | undefined }
90
+ >();
91
+ let report: (change: VoiceStateChange) => void = () => undefined;
92
+ let available = true;
93
+
94
+ const channelOf = (channelId: string, call: string): FakeVoiceChannel => {
95
+ const channel = channels.get(channelId);
96
+ if (!channel)
97
+ throw new Error(
98
+ `fakeDiscordVoice ${call}: there is no channel ${channelId}. Add it first: voice.channels.set("${channelId}", { guildId: "..." }).`,
99
+ );
100
+ return channel;
101
+ };
102
+ const without = (channel: FakeVoiceChannel, userId: string) =>
103
+ (channel.members ?? []).filter((member) => member.userId !== userId);
104
+
105
+ const service = voiceService({
106
+ clock,
107
+ logger: silentLogger(),
108
+ gateway: {
109
+ ready: () => available,
110
+ botId: () => BOT.userId,
111
+ channel: async (channelId) => {
112
+ const channel = channels.get(channelId);
113
+ if (!channel) return "gone";
114
+ return {
115
+ guildId: channel.guildId,
116
+ kind: channel.kind === "text" ? "other" : (channel.kind ?? "voice"),
117
+ connectable: !channel.forbidden,
118
+ full: channel.full ?? false,
119
+ members: without(channel, BOT.userId),
120
+ };
121
+ },
122
+ onVoiceState: (listener) => {
123
+ report = listener;
124
+ },
125
+ prepare: async () => undefined,
126
+ connect: async ({ guildId, channelId }) => {
127
+ let status: VoiceLinkStatus = "ready";
128
+ const link = {
129
+ channelId,
130
+ handlers: undefined as VoiceLinkHandlers | undefined,
131
+ };
132
+ links.set(guildId, link);
133
+ return {
134
+ status: () => status,
135
+ listen: (handlers) => {
136
+ link.handlers = handlers;
137
+ },
138
+ forget: () => undefined,
139
+ close: () => {
140
+ status = "closed";
141
+ if (links.get(guildId) === link) links.delete(guildId);
142
+ },
143
+ };
144
+ },
145
+ },
146
+ });
147
+
148
+ const fake: FakeDiscordVoice = {
149
+ channels,
150
+ get available() {
151
+ return available;
152
+ },
153
+ set available(value: boolean) {
154
+ available = value;
155
+ },
156
+ joins,
157
+ ended,
158
+ botId: BOT.userId,
159
+ join: async (target, given) => {
160
+ joins.push({ guildId: target.guildId, channelId: target.channelId });
161
+ const answer = await service.join(target, given);
162
+ if (answer.ok)
163
+ answer.session.onDisconnect(({ reason }) =>
164
+ ended.push({ ...target, reason }),
165
+ );
166
+ return answer;
167
+ },
168
+ session: (guildId) => service.session(guildId),
169
+ enter(channelId, member) {
170
+ const channel = channelOf(channelId, "enter");
171
+ for (const [id, other] of channels)
172
+ if (id !== channelId && other.guildId === channel.guildId)
173
+ other.members = without(other, member.userId);
174
+ channel.members = [...without(channel, member.userId), member];
175
+ report({
176
+ guildId: channel.guildId,
177
+ userId: member.userId,
178
+ channelId,
179
+ member,
180
+ });
181
+ },
182
+ exit(channelId, userId) {
183
+ const channel = channelOf(channelId, "exit");
184
+ const member = channel.members?.find((one) => one.userId === userId);
185
+ if (!member) return;
186
+ channel.members = without(channel, userId);
187
+ report({
188
+ guildId: channel.guildId,
189
+ userId,
190
+ channelId: undefined,
191
+ member,
192
+ });
193
+ },
194
+ audio(channelId, userId, pcm) {
195
+ const channel = channelOf(channelId, "audio");
196
+ if (!channel.members?.some((member) => member.userId === userId))
197
+ throw new Error(
198
+ `fakeDiscordVoice audio: ${userId} is not in the channel ${channelId}. Call enter("${channelId}", { userId: "${userId}", ... }) first.`,
199
+ );
200
+ const link = links.get(channel.guildId);
201
+ // Copied, as a decoder hands the session a frame of its own.
202
+ if (link?.channelId === channelId)
203
+ link.handlers?.frame(userId, pcm.slice());
204
+ clock.advance(pcm.byteLength / BYTES_PER_MS);
205
+ },
206
+ quiet() {
207
+ clock.advance(QUIET_MS);
208
+ },
209
+ say(channelId, userId, ...frames) {
210
+ for (const frame of frames) fake.audio(channelId, userId, frame);
211
+ fake.quiet();
212
+ },
213
+ drop(guildId, how) {
214
+ const link = links.get(guildId);
215
+ if (!link) return;
216
+ if (how === "connection_lost") return link.handlers?.status("closed");
217
+ report({
218
+ guildId,
219
+ userId: BOT.userId,
220
+ channelId: how === "moved" ? `${link.channelId}-elsewhere` : undefined,
221
+ member: BOT,
222
+ });
223
+ },
224
+ stop: () => service.stop(),
225
+ };
226
+ return fake;
227
+ }
@@ -4,7 +4,14 @@ import type { ServiceKey } from "../contract/services.ts";
4
4
  import type { PendingConfirmation } from "../domain/conversation.ts";
5
5
  import type { ChannelKey } from "../domain/sessions.ts";
6
6
  import { NotLinkedError, PluginError } from "../kernel/errors.ts";
7
+ import type {
8
+ EventSink,
9
+ TurnEndEvent,
10
+ TurnEvent,
11
+ TurnProgressEvent,
12
+ } from "../plugin-api/plugin.ts";
7
13
  import type { ChannelRouter } from "../routing/channel-router.ts";
14
+ import type { RecordedEvent } from "./test-plugin-types.ts";
8
15
 
9
16
  /** The same pre-link failures and wording the host exposes during setup. */
10
17
  export const NOT_LINKED = {
@@ -45,6 +52,26 @@ export function partialService<T extends object>(
45
52
  });
46
53
  }
47
54
 
55
+ /** What `testPlugin` reports the plugin's own events to: each is kept in `events` and delivered to the plugin's handlers. */
56
+ export function recordedSink(events: RecordedEvent[], sink: EventSink) {
57
+ return {
58
+ turnStarted: (turn: TurnEvent) => {
59
+ events.push({ name: "turnStarted", turn });
60
+ sink.turnStarted(turn);
61
+ },
62
+ turnEnded: (turn: TurnEndEvent) => {
63
+ events.push({ name: "turnEnded", turn });
64
+ sink.turnEnded(turn);
65
+ },
66
+ // Delivered to the plugin's handlers, not recorded: a turn reports many.
67
+ turnProgress: (event: TurnProgressEvent) => sink.turnProgress?.(event),
68
+ changed: () => {
69
+ events.push({ name: "changed" });
70
+ sink.changed();
71
+ },
72
+ };
73
+ }
74
+
48
75
  /** Held actions kept in memory, for the runtime a plugin's provider builds under test. */
49
76
  export function memoryHeldActions(): HeldActionStore {
50
77
  const held = new Map<ChannelKey, PendingConfirmation>();