pi-roundtable 0.48.0 → 0.48.1
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/CHANGELOG.md +9 -0
- package/docs/plugins.md +4 -4
- package/package.json +1 -1
- package/src/core/contract/surface.ts +5 -4
- package/src/core/discord/voice/voice-discord.ts +15 -0
- package/src/core/discord/voice/voice-hearing.ts +357 -0
- package/src/core/discord/voice/voice-link.ts +109 -13
- package/src/core/discord/voice/voice-service.ts +31 -3
- package/src/core/discord/voice/voice.ts +1 -1
- package/src/core/domain/block-support.ts +15 -9
- package/src/core/testing/fake-voice.ts +2 -0
package/CHANGELOG.md
CHANGED
|
@@ -5,6 +5,15 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
|
|
|
5
5
|
|
|
6
6
|
## [Unreleased]
|
|
7
7
|
|
|
8
|
+
## [0.48.1] - 2026-11-16
|
|
9
|
+
|
|
10
|
+
### Fixed
|
|
11
|
+
|
|
12
|
+
- Discord voice: a session no longer stays in a channel hearing nothing. After the voice library resumed a dropped voice socket, Discord's audio could stop arriving while the connection said it was ready, and the session heard nobody until it was left. A session now checks that audio arrives, from a speaker Discord has named to it, in two cases: within 2 seconds of Discord saying that someone in the channel is speaking (unless audio was heard in the 2 seconds before), and within 5 seconds of such a resume in a channel that was heard in the two minutes before. When none arrives, the voice connection is set up again, which nobody in the channel notices. When a speaker is still not heard 10 seconds later, the bot leaves the channel and joins it again, and the session keeps its members, its listeners and what it was hearing. A speaker who is not heard after that ends the session with `connection_lost`. Each step is a warning in the log. Silence alone never makes the bot leave the channel or ends the session, and neither does a bot that a moderator deafened in the server.
|
|
13
|
+
- Discord voice: a session reads who is in its channel again when the bot's gateway connection to Discord is resumed or made again, not only when its voice connection came back, so `members()` stays right after Discord sent the guild's voice states anew.
|
|
14
|
+
- Discord voice: a rejoin that throws as a live voice connection drops is logged and asked for again every 3 seconds, as a later one already was, and is no longer thrown into the voice library.
|
|
15
|
+
- The line a turn is given about forms, option buttons and checklists now speaks only of display blocks written in a reply, and says that a tool that asks the user, such as `ask_user`, works as its description says. Since 0.40 it read "This chat cannot show forms, option buttons or checklists. Ask in plain text.", which could keep a model from `ask_user` on Discord, where that tool posts a card with buttons.
|
|
16
|
+
|
|
8
17
|
## [0.48.0] - 2026-11-15
|
|
9
18
|
|
|
10
19
|
### Added
|
package/docs/plugins.md
CHANGED
|
@@ -3010,8 +3010,8 @@ await session.leave();
|
|
|
3010
3010
|
- **Joining.** `join({ guildId, channelId }, options?)` answers `{ ok: true, session }` or `{ ok: false, failure, message }` and never rejects for something Discord refuses. The failures (`VoiceJoinFailure`) are `forbidden` (the bot may not see the channel or connect to it), `channel_gone` (the guild has no such channel), `not_voice` (neither a voice nor a stage channel), `full` (at its user limit, and the bot may not move members), `unavailable` (Discord is not connected, the host is stopping, or the voice connection did not come up in 20 seconds; asking again may work) and `already_joined`. Discord allows a bot one voice connection per guild, so a guild has one session: a second `join` there, to the same channel or another, answers `already_joined` until the first ended. `voice.session(guildId)` is the open session of a guild, if any. Call `join` from a service's `start`, a tool, or a command, not from `setup`.
|
|
3011
3011
|
- **Utterances.** A session cuts each speaker's audio into utterances and hands each to `onUtterance` when it is complete: `{ userId, pcm, startedAt, endedAt, continues }`. `pcm` is decoded audio in the format `VOICE_PCM` names: 48 kHz, signed 16-bit little-endian, one channel (Discord's stereo is mixed down to mono). It holds what Discord sent and nothing for the pauses inside the utterance, so it may be shorter than `endedAt - startedAt`; both times are the host's clock in milliseconds since the epoch, taken when the first and the last audio arrived. An utterance ends when its speaker was quiet for `silenceMs` (option, 200 to 5,000, default 800), when it holds `maxUtteranceMs` of audio and the speaker goes on (1,000 to 300,000, default 30,000, about 2.9 MB), when the speaker leaves the channel, and when the session ends, so nothing heard is dropped. A full utterance is handed over with `continues: true` as the speaker's next audio arrives, and that audio starts their next utterance: a run of `continues` utterances always ends with one that has `continues: false`, and an utterance that is full just as its speaker stops is that last one. An option out of its range throws a `RangeError`.
|
|
3012
3012
|
- **Speaking.** `onSpeaking` reports `{ userId, speaking, at }`: `true` with the first audio of an utterance and `false` when it ends, just before the utterance is delivered. Use it to show who is talking; the audio comes with the utterance.
|
|
3013
|
-
- **Members.** `session.members()` lists who is in the channel now as `{ userId, bot, displayName }` (the server nickname, else the account's display name), without the bot itself; `onMember` reports `{ kind: "joined" | "left", member }` as people enter and leave. Other bots are listed with `bot: true`. When a dropped connection comes back, the session reads the channel again and reports whoever entered or left in the meantime then.
|
|
3014
|
-
- **The end.** `session.leave()` leaves the channel. `onDisconnect` reports `{ reason }` once, however the session ended: `left` (your `leave()`), `removed` (someone disconnected the bot, or the channel was deleted), `moved` (someone moved the bot to another channel; a session never follows, so it hears nothing its plugin did not ask for), `connection_lost` and `stopped` (the host is stopping). A connection that drops has up to 20 seconds to come back, which the session does not report; after that it ends with `connection_lost`. After the end `session.ended()` is the reason, `members()` is empty, nothing more is reported, and the guild can be joined again; a listener added after the end is called at once. Every `on…` returns a function that removes the listener, and a listener that throws is logged and does not stop the others.
|
|
3013
|
+
- **Members.** `session.members()` lists who is in the channel now as `{ userId, bot, displayName }` (the server nickname, else the account's display name), without the bot itself; `onMember` reports `{ kind: "joined" | "left", member }` as people enter and leave. Other bots are listed with `bot: true`. When a dropped connection comes back, the session reads the channel again and reports whoever entered or left in the meantime then; it does the same when the bot's gateway connection to Discord is resumed or made again, since Discord then sends who is in the channel without saying what changed.
|
|
3014
|
+
- **The end.** `session.leave()` leaves the channel. `onDisconnect` reports `{ reason }` once, however the session ended: `left` (your `leave()`), `removed` (someone disconnected the bot, or the channel was deleted), `moved` (someone moved the bot to another channel; a session never follows, so it hears nothing its plugin did not ask for), `connection_lost` and `stopped` (the host is stopping). A connection that drops has up to 20 seconds to come back, which the session does not report; after that it ends with `connection_lost`. A connection can also stay up and hear nothing, which has happened after a short network loss, so the session checks that audio arrives in two cases; only audio of a speaker Discord has named to the bot counts, since no other reaches a listener. When Discord says someone in the channel is speaking, no audio was heard in the 2 seconds before, and none arrives for 2 seconds, or when no audio arrives for 5 seconds after such a loss in a channel that was heard within the two minutes before, the session sets its voice connection up again, which nobody in the channel notices. When a speaker is still not heard 10 seconds later (up to 12 when they began to speak in the last 2), the bot leaves the channel and joins it again, with Discord's leave and join sounds; the session, its members and its listeners stay as they are. A speaker who is not heard after that ends the session with `connection_lost`. The host logs a warning at each step. A quiet channel starts none of them: the bot does not leave it and the session does not end because nobody spoke. The same holds while a moderator has server-deafened the bot, since Discord sends it no audio then. After the end `session.ended()` is the reason, `members()` is empty, nothing more is reported, and the guild can be joined again; a listener added after the end is called at once. Every `on…` returns a function that removes the listener, and a listener that throws is logged and does not stop the others.
|
|
3015
3015
|
- **Privacy.** Discord encrypts voice end to end (DAVE), and the host is one of the ends: the audio is decrypted and decoded in the host's memory, handed to your listeners, and kept nowhere else. The core writes no audio to disk and none to its logs or errors; what your plugin does with an utterance is its own to answer for, and Discord shows the bot in the channel to everyone in it. Tell the people in the channel before you record them.
|
|
3016
3016
|
|
|
3017
3017
|
In a test, `fakeDiscordVoice()` is a `DiscordVoice` in memory, and `fakeDiscord({ voice })` or `testHost({ discord: { voice } })` gives it to the plugin; see [Testing a plugin](#testing-a-plugin). The real voice and the fake run the same scenarios, the real one over a stand-in for the discord.js client and the voice connection.
|
|
@@ -3167,7 +3167,7 @@ The agent server claims `discord:` keys, and, only on a surface that declares `a
|
|
|
3167
3167
|
| `blocks` | The [display-block](#display-blocks-in-a-reply) kinds the surface draws itself, such as `["table", "mermaid"]` (`BlockKind` of `pi-better-show`); a reply reaches `sendReply` whole, with the fences of those kinds intact. Every other block arrives as text. Listing an interactive kind (`options`, `suggest`, `form`, `checklist`, `review`) also promises that the reader's answer reaches the agent as a message from them, as typing it would | none: every block arrives as text |
|
|
3168
3168
|
| `blockText` | How a block the surface does not draw reads as text: `"discord"` (Markdown, with Discord's native `diff` fence), `"line"` (plain text without Markdown markup) or `"plain"` | `"discord"` |
|
|
3169
3169
|
| `lang` | The language (`"en"` or `"zh-TW"`) a block the surface does not draw asks its reader to answer in, such as "Reply with a number." | the host's locale |
|
|
3170
|
-
| `blockNote` | `false` when the surface's own `formatting` already says what
|
|
3170
|
+
| `blockNote` | `false` when the surface's own `formatting` already says what becomes of a form, option-button or checklist block it does not draw, so core adds no line about them | core adds the line whenever the surface does not draw every interactive kind |
|
|
3171
3171
|
| `support(channel)` | What differs in one channel of the surface: a `formatting`, `blocks`, `blockText`, `lang` or `blockNote` that replaces the surface's own for a turn that replies there, such as a host's room on a surface that draws blocks only in its own rooms. Return `undefined` for a channel that is like the rest | every channel is like the surface |
|
|
3172
3172
|
| `startTyping(channel)` | Shows a typing indicator until the returned function is called | none is shown |
|
|
3173
3173
|
| `showStop(channel)` | Shows the owner a stop control until the returned function is called; using it calls `conversations.stop(channel)`. A group's round shows it for the whole round, and stopping ends the round: the member speaking is stopped and the members still waiting do not speak | none is shown |
|
|
@@ -3313,7 +3313,7 @@ The team writes through the providers too. At start it calls `ensure` for each a
|
|
|
3313
3313
|
|
|
3314
3314
|
### Display blocks in a reply
|
|
3315
3315
|
|
|
3316
|
-
An agent may write a *display block* in a reply: a fenced block whose first word is a kind (`cards`, `table`, `steps`, `stats`, `mindmap`, `mermaid`, `diff`, `options`, `form`, ...) or a GitHub alert (`> [!NOTE]`), as `pi-better-show` defines. A block is YAML or source that only a surface that draws it should show, so the host cuts agent text with `chunksFor(surface, text)` (from `pi-roundtable/kit`), never `splitReply` alone: a block whose kind the surface does not list in `blocks` becomes text first (Discord's flavor by default, `blockText: "line"` for plain text; a diagram is drawn as Unicode boxes, unless its source is over 3 KB or the drawing, which runs in a worker the host waits on for at most 500 ms, is not done by then, and then the source is shown), and the result is split into messages within Discord's limit. A surface that lists any kind in `blocks` gets the text whole in one chunk, because cutting a fence breaks the block. `textFor(surface, text)` does the conversion alone, for a surface that shows a message of any length in one piece (the web chat's replies and inbox notices) and so needs no cutting. A block that is not closed at the end of the reply is still a block: a text surface gets it as text, and a surface that draws it gets it as written. A block that does not parse becomes a plain code block. The same applies to interim posts: the host's surface port copies the surface's `blocks` and `blockText` onto the `InterimPosts` it returns, so the poster cuts for the right surface. A surface whose channels differ (a host's room, read on a page that does not draw blocks) answers `support(channel)` with what is different, and `supportOf(surface, channel)` (from `pi-roundtable/kit`) reads the result; the formatting guidance a turn gets follows it too. A surface that does not draw every interactive kind (`options`, `suggest`, `form`, `checklist`, `review`) gets one more line, closing its `formatting`, which tells the model the chat
|
|
3316
|
+
An agent may write a *display block* in a reply: a fenced block whose first word is a kind (`cards`, `table`, `steps`, `stats`, `mindmap`, `mermaid`, `diff`, `options`, `form`, ...) or a GitHub alert (`> [!NOTE]`), as `pi-better-show` defines. A block is YAML or source that only a surface that draws it should show, so the host cuts agent text with `chunksFor(surface, text)` (from `pi-roundtable/kit`), never `splitReply` alone: a block whose kind the surface does not list in `blocks` becomes text first (Discord's flavor by default, `blockText: "line"` for plain text; a diagram is drawn as Unicode boxes, unless its source is over 3 KB or the drawing, which runs in a worker the host waits on for at most 500 ms, is not done by then, and then the source is shown), and the result is split into messages within Discord's limit. A surface that lists any kind in `blocks` gets the text whole in one chunk, because cutting a fence breaks the block. `textFor(surface, text)` does the conversion alone, for a surface that shows a message of any length in one piece (the web chat's replies and inbox notices) and so needs no cutting. A block that is not closed at the end of the reply is still a block: a text surface gets it as text, and a surface that draws it gets it as written. A block that does not parse becomes a plain code block. The same applies to interim posts: the host's surface port copies the surface's `blocks` and `blockText` onto the `InterimPosts` it returns, so the poster cuts for the right surface. A surface whose channels differ (a host's room, read on a page that does not draw blocks) answers `support(channel)` with what is different, and `supportOf(surface, channel)` (from `pi-roundtable/kit`) reads the result; the formatting guidance a turn gets follows it too. A surface that does not draw every interactive kind (`options`, `suggest`, `form`, `checklist`, `review`) gets one more line, closing its `formatting`, which tells the model that such a block written in a reply is not drawn in the chat and reaches the user as text to answer by typing, so the question belongs in plain words. The line is about blocks only, and says that a tool that asks the user, such as `ask_user`, works as its description says: on Discord `ask_user` posts a card with buttons, which is no display block. `blockNote: false` leaves the line out. A block that reads as text asks in the host's language: `supportOf(surface, channel, surfaces.lang)` carries the locale the host was defined with, and the surface's own `lang` wins. Host notices and error reports are the host's own text and keep `splitReply`.
|
|
3317
3317
|
`describeSurfaceContract` checks that a surface listing `blocks` delivers a block of a declared kind longer than a message whole; `describeBlocksContract(name, make)` registers only that check, for a surface that cannot run the whole contract (the subject needs `surface`, `channel` and `observations()` of the replies its person has seen).
|
|
3318
3318
|
|
|
3319
3319
|
Each message a surface delivers says who wrote it in `actor`, the `ActorFacts` the identity service resolves: `provider` and `subject`, such as `discord` and the user id, `name`, `roles` written `<surface>:role:<name>` (left out where the surface does not know them, such as a Discord DM, which is not the same as none), and `legacyId`, the speaker id 0.8 gave the person, so someone carried over keeps their principal.
|
package/package.json
CHANGED
|
@@ -143,7 +143,8 @@ export interface ChatSurface {
|
|
|
143
143
|
* text. Absent = none. Listing an interactive kind (`options`, `suggest`, `form`, `checklist`,
|
|
144
144
|
* `review`) also promises that the surface hands the reader's answer to the agent as a message
|
|
145
145
|
* from them, the way typing it would; a surface that cannot promise that leaves the kind out,
|
|
146
|
-
* and core tells the model
|
|
146
|
+
* and core tells the model that such a block written in a reply is not drawn here (see
|
|
147
|
+
* `blockNote`), which says nothing against a tool that asks the user, such as `ask_user`.
|
|
147
148
|
*/
|
|
148
149
|
readonly blocks?: readonly BlockKind[];
|
|
149
150
|
/**
|
|
@@ -157,9 +158,9 @@ export interface ChatSurface {
|
|
|
157
158
|
*/
|
|
158
159
|
readonly lang?: TextLang;
|
|
159
160
|
/**
|
|
160
|
-
* `false` = this surface's `formatting` already says what
|
|
161
|
-
*
|
|
162
|
-
* guidance of a turn when the surface does not draw every interactive kind.
|
|
161
|
+
* `false` = this surface's `formatting` already says what becomes of a form, option-button or
|
|
162
|
+
* checklist block it does not draw, so core adds no line about them. Absent = core adds one to
|
|
163
|
+
* the guidance of a turn when the surface does not draw every interactive kind.
|
|
163
164
|
*/
|
|
164
165
|
readonly blockNote?: false;
|
|
165
166
|
/**
|
|
@@ -150,6 +150,18 @@ export function discordVoiceGateway(
|
|
|
150
150
|
}
|
|
151
151
|
});
|
|
152
152
|
},
|
|
153
|
+
onReady(listener) {
|
|
154
|
+
const ready = () => {
|
|
155
|
+
try {
|
|
156
|
+
listener();
|
|
157
|
+
} catch (error) {
|
|
158
|
+
logger.error({ err: error }, "voice gateway handler failed");
|
|
159
|
+
}
|
|
160
|
+
};
|
|
161
|
+
// Ready once the shard has its guilds again, so their voice states are the new ones.
|
|
162
|
+
client.on(Events.ShardReady, ready);
|
|
163
|
+
client.on(Events.ShardResume, ready);
|
|
164
|
+
},
|
|
153
165
|
async prepare() {
|
|
154
166
|
await loaded();
|
|
155
167
|
},
|
|
@@ -164,6 +176,9 @@ export function discordVoiceGateway(
|
|
|
164
176
|
decoder,
|
|
165
177
|
logger,
|
|
166
178
|
...(options.clock ? { clock: options.clock } : {}),
|
|
179
|
+
deafened: () =>
|
|
180
|
+
guild.voiceStates.cache.get(client.user?.id ?? "")?.serverDeaf ===
|
|
181
|
+
true,
|
|
167
182
|
});
|
|
168
183
|
},
|
|
169
184
|
};
|
|
@@ -0,0 +1,357 @@
|
|
|
1
|
+
import type { VoiceConnection, VoiceConnectionState } from "@discordjs/voice";
|
|
2
|
+
import type { Logger } from "../../kernel/log.ts";
|
|
3
|
+
import type { VoiceClock } from "./voice-clock.ts";
|
|
4
|
+
|
|
5
|
+
// Whether a voice link hears. A connection's state says nothing of its audio: after the library
|
|
6
|
+
// resumed a dropped voice socket, the connection is ready again over the media socket it had,
|
|
7
|
+
// and Discord's audio may no longer arrive there. Nothing but a datagram shows that it does, and
|
|
8
|
+
// silence shows nothing, so the watch goes by what contradicts silence: the voice socket naming
|
|
9
|
+
// someone who speaks, and a resume that cut into a channel that was being heard.
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* How long after the voice socket says someone speaks a datagram must have come. A speaker's
|
|
13
|
+
* audio is a datagram every 20 ms from that moment, so 2 s without one is a hundred missing in
|
|
14
|
+
* a row, which no jitter or loss explains; and 2 s is all a recorder loses before the remedy.
|
|
15
|
+
*/
|
|
16
|
+
const SPEAKING_PROOF_MS = 2_000;
|
|
17
|
+
/**
|
|
18
|
+
* How long after a resume a datagram must have come, in a channel that was heard shortly before.
|
|
19
|
+
* Nothing says anyone speaks then, so the pause between two sentences has to fit in it: 5 s
|
|
20
|
+
* keeps most pauses from being taken for deafness, and bounds what is lost when it is deafness.
|
|
21
|
+
*/
|
|
22
|
+
const RESUME_PROOF_MS = 5_000;
|
|
23
|
+
/**
|
|
24
|
+
* How long before its voice socket dropped a channel counts as heard. Whoever was speaking is
|
|
25
|
+
* cut off when the network goes, and the socket follows later: the library closes it after
|
|
26
|
+
* three missed heartbeats of some 14 s each, checked at the fourth, and a socket that cannot
|
|
27
|
+
* say goodbye takes up to 30 s more to close, 85 s in all. Two minutes span that, and a channel
|
|
28
|
+
* quiet for longer is left alone.
|
|
29
|
+
*/
|
|
30
|
+
const RECENT_MS = 120_000;
|
|
31
|
+
/**
|
|
32
|
+
* How long a media path is up before a speaking state counts as someone speaking. To a
|
|
33
|
+
* connection that just came up or resumed, Discord may repeat the states it sent before; those
|
|
34
|
+
* name speakers and say nothing of now.
|
|
35
|
+
*/
|
|
36
|
+
const SETTLE_MS = 3_000;
|
|
37
|
+
/** How long a remedy has to bring audio before the next one. */
|
|
38
|
+
const VERIFY_MS = 10_000;
|
|
39
|
+
/** How many datagrams of a speaker the voice socket never named are worth a line: two seconds of audio. */
|
|
40
|
+
const UNNAMED_DATAGRAMS = 100;
|
|
41
|
+
|
|
42
|
+
export interface HearingOptions {
|
|
43
|
+
clock: VoiceClock;
|
|
44
|
+
logger: Logger;
|
|
45
|
+
/** What every line of the watch names; never audio. */
|
|
46
|
+
fields: { guildId: string; channelId: string };
|
|
47
|
+
/** Whether the user is a person in the channel, not a bot; with no user, whether any person is. */
|
|
48
|
+
person(userId?: string): boolean;
|
|
49
|
+
/** Whether a moderator deafened the bot: Discord then sends it no audio, which no remedy mends. */
|
|
50
|
+
deafened(): boolean;
|
|
51
|
+
/** Sets the media path up again without leaving the channel; false when that could not be started. */
|
|
52
|
+
rebuild(): boolean;
|
|
53
|
+
/** Leaves the channel and joins it again. */
|
|
54
|
+
rejoin(): void;
|
|
55
|
+
/** Nothing made the link hear: it is closed. */
|
|
56
|
+
giveUp(): void;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** What a link tells the watch of its connection. */
|
|
60
|
+
export interface HearingWatch {
|
|
61
|
+
/** The connection is ready over a media path it did not have before. */
|
|
62
|
+
up(): void;
|
|
63
|
+
/** The connection is ready over the media path it had: its voice socket was resumed. */
|
|
64
|
+
resumed(): void;
|
|
65
|
+
/** The connection is no longer ready. */
|
|
66
|
+
down(): void;
|
|
67
|
+
/** The voice socket says the user is speaking. */
|
|
68
|
+
speaking(userId: string): void;
|
|
69
|
+
/**
|
|
70
|
+
* An audio datagram arrived; `named` is whether the voice socket said whose it is. Only a named
|
|
71
|
+
* one is heard: the receiver hands nobody the audio of a speaker it cannot name.
|
|
72
|
+
*/
|
|
73
|
+
audio(named: boolean): void;
|
|
74
|
+
stop(): void;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Watches whether a link hears, and remedies a link that does not: first the media path is set
|
|
79
|
+
* up again, which nobody in the channel notices; a speaker still not heard 10 s later has the
|
|
80
|
+
* bot leave the channel and join it again; a speaker not heard after that closes the link.
|
|
81
|
+
* A datagram of a speaker the voice socket named ends it all. Silence alone goes no further than the first remedy, and that one
|
|
82
|
+
* only after a resume: a quiet channel is never left, and never closed.
|
|
83
|
+
*/
|
|
84
|
+
export function hearingWatch(options: HearingOptions): HearingWatch {
|
|
85
|
+
const { clock, logger, fields } = options;
|
|
86
|
+
let ready = false;
|
|
87
|
+
let stopped = false;
|
|
88
|
+
/** When the media path came up or was resumed. */
|
|
89
|
+
let since = 0;
|
|
90
|
+
/** When the media path last carried audio of a speaker the voice socket named. */
|
|
91
|
+
let lastAudioAt: number | undefined;
|
|
92
|
+
/** How long the media path had carried none when the connection last stopped being ready; undefined when it never had. */
|
|
93
|
+
let quietAtDrop: number | undefined;
|
|
94
|
+
/** Whether audio came while the connection was not ready: the media path never stopped. */
|
|
95
|
+
let heardAway = false;
|
|
96
|
+
/** The remedies used since audio was last heard: 1 the media path, 2 the rejoin. */
|
|
97
|
+
let remedies: 0 | 1 | 2 = 0;
|
|
98
|
+
/** Whether someone was said to speak and was not heard, since audio was last heard. */
|
|
99
|
+
let evidenced = false;
|
|
100
|
+
/** Datagrams of speakers the voice socket has not named, since the media path came up or was resumed. */
|
|
101
|
+
let unnamed = 0;
|
|
102
|
+
/** When someone was first said to speak while the first remedy is waited on: its 10 s are not cut short for them. */
|
|
103
|
+
let saidAt: number | undefined;
|
|
104
|
+
/** The one deadline that runs: for a datagram after a speaking state or a resume, or after a remedy. */
|
|
105
|
+
let timer: unknown;
|
|
106
|
+
let waitsFor: "speaking" | "resume" | "remedy" | undefined;
|
|
107
|
+
|
|
108
|
+
const disarm = (): void => {
|
|
109
|
+
clock.clearTimeout(timer);
|
|
110
|
+
timer = undefined;
|
|
111
|
+
waitsFor = undefined;
|
|
112
|
+
};
|
|
113
|
+
const arm = (what: NonNullable<typeof waitsFor>, ms: number): void => {
|
|
114
|
+
disarm();
|
|
115
|
+
waitsFor = what;
|
|
116
|
+
timer = clock.setTimeout(() => due(what), ms);
|
|
117
|
+
};
|
|
118
|
+
|
|
119
|
+
/** The next remedy, of a link that does not hear. */
|
|
120
|
+
const remedy = (after: "speaking" | "resume"): void => {
|
|
121
|
+
if (remedies === 0) {
|
|
122
|
+
remedies = 1;
|
|
123
|
+
if (options.rebuild()) {
|
|
124
|
+
logger.warn(
|
|
125
|
+
{ ...fields, after },
|
|
126
|
+
"voice hears nothing: its networking is set up again",
|
|
127
|
+
);
|
|
128
|
+
return;
|
|
129
|
+
}
|
|
130
|
+
// Without word of a speaker the channel is not left: the next one who is not heard takes it from here.
|
|
131
|
+
if (!evidenced) {
|
|
132
|
+
logger.warn(
|
|
133
|
+
{ ...fields, after },
|
|
134
|
+
"voice hears nothing, and its networking could not be set up again",
|
|
135
|
+
);
|
|
136
|
+
return;
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
if (remedies === 1) {
|
|
140
|
+
remedies = 2;
|
|
141
|
+
logger.warn(
|
|
142
|
+
fields,
|
|
143
|
+
"voice hears nothing: the channel is left and joined again",
|
|
144
|
+
);
|
|
145
|
+
options.rejoin();
|
|
146
|
+
return;
|
|
147
|
+
}
|
|
148
|
+
logger.warn(fields, "voice audio not recovered");
|
|
149
|
+
options.giveUp();
|
|
150
|
+
};
|
|
151
|
+
|
|
152
|
+
const due = (what: NonNullable<typeof waitsFor>): void => {
|
|
153
|
+
timer = undefined;
|
|
154
|
+
waitsFor = undefined;
|
|
155
|
+
// A deafened bot was sent nothing to hear: its silence shows no fault.
|
|
156
|
+
if (stopped || !ready || options.deafened()) return;
|
|
157
|
+
if (what === "speaking") {
|
|
158
|
+
evidenced = true;
|
|
159
|
+
remedy("speaking");
|
|
160
|
+
} else if (what === "resume") remedy("resume");
|
|
161
|
+
// A remedy brought no audio in its time: the next one is for a speaker, never for silence.
|
|
162
|
+
else if (remedies === 1 && (evidenced || saidAt !== undefined)) {
|
|
163
|
+
// Someone named while it was waited on has their own 2 s to be heard, like anyone.
|
|
164
|
+
const left =
|
|
165
|
+
evidenced || saidAt === undefined
|
|
166
|
+
? 0
|
|
167
|
+
: SPEAKING_PROOF_MS - (clock.now() - saidAt);
|
|
168
|
+
saidAt = undefined;
|
|
169
|
+
if (left > 0) arm("speaking", left);
|
|
170
|
+
else {
|
|
171
|
+
evidenced = true;
|
|
172
|
+
remedy("speaking");
|
|
173
|
+
}
|
|
174
|
+
} else
|
|
175
|
+
logger.warn(
|
|
176
|
+
{ ...fields, remedies },
|
|
177
|
+
"voice has heard nothing since its remedy",
|
|
178
|
+
);
|
|
179
|
+
};
|
|
180
|
+
|
|
181
|
+
return {
|
|
182
|
+
up() {
|
|
183
|
+
ready = true;
|
|
184
|
+
since = clock.now();
|
|
185
|
+
lastAudioAt = undefined;
|
|
186
|
+
unnamed = 0;
|
|
187
|
+
saidAt = undefined;
|
|
188
|
+
if (remedies > 0) arm("remedy", VERIFY_MS);
|
|
189
|
+
},
|
|
190
|
+
resumed() {
|
|
191
|
+
ready = true;
|
|
192
|
+
since = clock.now();
|
|
193
|
+
unnamed = 0;
|
|
194
|
+
if (remedies > 0) {
|
|
195
|
+
arm("remedy", VERIFY_MS);
|
|
196
|
+
return;
|
|
197
|
+
}
|
|
198
|
+
const heard = quietAtDrop !== undefined && quietAtDrop <= RECENT_MS;
|
|
199
|
+
if (heard && !heardAway && options.person())
|
|
200
|
+
arm("resume", RESUME_PROOF_MS);
|
|
201
|
+
},
|
|
202
|
+
down() {
|
|
203
|
+
if (ready) {
|
|
204
|
+
quietAtDrop =
|
|
205
|
+
lastAudioAt === undefined ? undefined : clock.now() - lastAudioAt;
|
|
206
|
+
heardAway = false;
|
|
207
|
+
}
|
|
208
|
+
ready = false;
|
|
209
|
+
saidAt = undefined;
|
|
210
|
+
disarm();
|
|
211
|
+
},
|
|
212
|
+
speaking(userId) {
|
|
213
|
+
if (stopped || !ready || waitsFor === "speaking") return;
|
|
214
|
+
if (clock.now() - since < SETTLE_MS || !options.person(userId)) return;
|
|
215
|
+
if (options.deafened()) return;
|
|
216
|
+
const now = clock.now();
|
|
217
|
+
// The word of a speaker can come after their audio: the voice socket resends what it lost, a
|
|
218
|
+
// datagram is never resent. Whoever was heard this shortly before is no evidence of deafness.
|
|
219
|
+
if (lastAudioAt !== undefined && now - lastAudioAt < SPEAKING_PROOF_MS)
|
|
220
|
+
return;
|
|
221
|
+
// The first remedy keeps its time: the speaker is weighed when it is over.
|
|
222
|
+
if (waitsFor === "remedy" && remedies === 1) {
|
|
223
|
+
saidAt ??= now;
|
|
224
|
+
return;
|
|
225
|
+
}
|
|
226
|
+
arm("speaking", SPEAKING_PROOF_MS);
|
|
227
|
+
},
|
|
228
|
+
audio(named) {
|
|
229
|
+
// Audio nobody is handed is not hearing: it ends no deadline and no remedy.
|
|
230
|
+
if (!named) {
|
|
231
|
+
if (++unnamed === UNNAMED_DATAGRAMS)
|
|
232
|
+
logger.warn(
|
|
233
|
+
{ ...fields, datagrams: unnamed },
|
|
234
|
+
"voice audio arrives from a speaker the voice socket has not named",
|
|
235
|
+
);
|
|
236
|
+
return;
|
|
237
|
+
}
|
|
238
|
+
lastAudioAt = clock.now();
|
|
239
|
+
if (!ready) heardAway = true;
|
|
240
|
+
saidAt = undefined;
|
|
241
|
+
if (timer !== undefined) disarm();
|
|
242
|
+
if (remedies === 0) return;
|
|
243
|
+
logger.info({ ...fields, remedies }, "voice hears again");
|
|
244
|
+
remedies = 0;
|
|
245
|
+
evidenced = false;
|
|
246
|
+
},
|
|
247
|
+
stop() {
|
|
248
|
+
stopped = true;
|
|
249
|
+
disarm();
|
|
250
|
+
},
|
|
251
|
+
};
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
/** The voice opcode of someone's speaking state. */
|
|
255
|
+
const SPEAKING = 5;
|
|
256
|
+
/** The flag of a speaking state that says the microphone is sending; the others are for sound shared with a video and for priority. */
|
|
257
|
+
const MICROPHONE = 1;
|
|
258
|
+
/** The RTP payload type of Opus, as Discord sends audio. */
|
|
259
|
+
const OPUS = 120;
|
|
260
|
+
|
|
261
|
+
/** An event source of @discordjs/voice: a networking, its voice socket, its media socket. */
|
|
262
|
+
interface Source {
|
|
263
|
+
on(event: string, listener: (...given: never[]) => void): unknown;
|
|
264
|
+
off(event: string, listener: (...given: never[]) => void): unknown;
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
/** A member of a state the library types by its status: `networking` of a connection's, `ws` and `udp` of a networking's. */
|
|
268
|
+
function partOf(state: object | undefined, key: string): Source | undefined {
|
|
269
|
+
const part: unknown = state ? Reflect.get(state, key) : undefined;
|
|
270
|
+
return typeof part === "object" && part !== null
|
|
271
|
+
? (part as Source)
|
|
272
|
+
: undefined;
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
/** The networking a connection's state holds: a resume keeps it, a new media path is a new one. */
|
|
276
|
+
export function networkingOf(state: VoiceConnectionState): object | undefined {
|
|
277
|
+
return partOf(state, "networking");
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
/** Whether a datagram on the media socket is audio: RTP version 2 that carries Opus, which neither a keep-alive, an IP discovery nor RTCP is. */
|
|
281
|
+
function isAudio(message: Uint8Array): boolean {
|
|
282
|
+
return (
|
|
283
|
+
message.length > 12 &&
|
|
284
|
+
(message[0] ?? 0) >> 6 === 2 &&
|
|
285
|
+
((message[1] ?? 0) & 0x7f) === OPUS
|
|
286
|
+
);
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
/**
|
|
290
|
+
* Hands the watch what a connection's sockets carry: each speaking state of the voice socket and
|
|
291
|
+
* each audio datagram of the media socket. The library replaces the voice socket on a resume and
|
|
292
|
+
* both with a new networking, so `follow` is called with each state of the connection and the
|
|
293
|
+
* sockets are followed from there, as the library's own receiver follows them.
|
|
294
|
+
*/
|
|
295
|
+
export function hearingTaps(
|
|
296
|
+
connection: VoiceConnection,
|
|
297
|
+
watch: HearingWatch,
|
|
298
|
+
): { follow(state: VoiceConnectionState): void; stop(): void } {
|
|
299
|
+
let networking: Source | undefined;
|
|
300
|
+
let voice: Source | undefined;
|
|
301
|
+
let media: Source | undefined;
|
|
302
|
+
const packet = (given: {
|
|
303
|
+
op?: unknown;
|
|
304
|
+
d?: { user_id?: unknown; speaking?: unknown } | null;
|
|
305
|
+
}): void => {
|
|
306
|
+
if (given.op !== SPEAKING || !given.d) return;
|
|
307
|
+
const { user_id: userId, speaking } = given.d;
|
|
308
|
+
if (typeof userId !== "string" || typeof speaking !== "number") return;
|
|
309
|
+
if (speaking & MICROPHONE) watch.speaking(userId);
|
|
310
|
+
};
|
|
311
|
+
const datagram = (message: Uint8Array): void => {
|
|
312
|
+
if (!isAudio(message)) return;
|
|
313
|
+
const ssrc = new DataView(
|
|
314
|
+
message.buffer,
|
|
315
|
+
message.byteOffset,
|
|
316
|
+
message.byteLength,
|
|
317
|
+
).getUint32(8);
|
|
318
|
+
// A stand-in receiver keeps no such map: its audio is its speakers'.
|
|
319
|
+
const named = connection.receiver.ssrcMap;
|
|
320
|
+
watch.audio(!named || named.get(ssrc) !== undefined);
|
|
321
|
+
};
|
|
322
|
+
const bind = (): void => {
|
|
323
|
+
const state: unknown = networking
|
|
324
|
+
? Reflect.get(networking, "state")
|
|
325
|
+
: undefined;
|
|
326
|
+
const sockets = typeof state === "object" && state ? state : undefined;
|
|
327
|
+
const nextVoice = partOf(sockets, "ws");
|
|
328
|
+
const nextMedia = partOf(sockets, "udp");
|
|
329
|
+
if (nextVoice !== voice) {
|
|
330
|
+
voice?.off("packet", packet);
|
|
331
|
+
nextVoice?.on("packet", packet);
|
|
332
|
+
voice = nextVoice;
|
|
333
|
+
}
|
|
334
|
+
if (nextMedia !== media) {
|
|
335
|
+
media?.off("message", datagram);
|
|
336
|
+
nextMedia?.on("message", datagram);
|
|
337
|
+
media = nextMedia;
|
|
338
|
+
}
|
|
339
|
+
};
|
|
340
|
+
return {
|
|
341
|
+
follow(state) {
|
|
342
|
+
const next = partOf(state, "networking");
|
|
343
|
+
if (next !== networking) {
|
|
344
|
+
networking?.off("stateChange", bind);
|
|
345
|
+
next?.on("stateChange", bind);
|
|
346
|
+
networking = next;
|
|
347
|
+
}
|
|
348
|
+
bind();
|
|
349
|
+
},
|
|
350
|
+
stop() {
|
|
351
|
+
networking?.off("stateChange", bind);
|
|
352
|
+
voice?.off("packet", packet);
|
|
353
|
+
media?.off("message", datagram);
|
|
354
|
+
networking = voice = media = undefined;
|
|
355
|
+
},
|
|
356
|
+
};
|
|
357
|
+
}
|
|
@@ -5,6 +5,7 @@ import type {
|
|
|
5
5
|
} from "@discordjs/voice";
|
|
6
6
|
import type { Logger } from "../../kernel/log.ts";
|
|
7
7
|
import { systemClock, type VoiceClock } from "./voice-clock.ts";
|
|
8
|
+
import { hearingTaps, hearingWatch, networkingOf } from "./voice-hearing.ts";
|
|
8
9
|
import type {
|
|
9
10
|
VoiceLink,
|
|
10
11
|
VoiceLinkHandlers,
|
|
@@ -99,6 +100,11 @@ export interface VoiceLinkOptions {
|
|
|
99
100
|
logger: Logger;
|
|
100
101
|
/** What the rejoin attempts wait by. Default: the host's clock. */
|
|
101
102
|
clock?: VoiceClock;
|
|
103
|
+
/**
|
|
104
|
+
* Whether a moderator deafened the bot in the guild. Discord then sends it no audio, so a
|
|
105
|
+
* speaker it does not hear is no fault of the connection. Default: never.
|
|
106
|
+
*/
|
|
107
|
+
deafened?: () => boolean;
|
|
102
108
|
}
|
|
103
109
|
|
|
104
110
|
/**
|
|
@@ -152,8 +158,12 @@ function linkOver(
|
|
|
152
158
|
let closed = false;
|
|
153
159
|
/** The timer of the next rejoin, while the last one was refused. */
|
|
154
160
|
let rejoin: unknown;
|
|
155
|
-
/** Whether
|
|
156
|
-
let
|
|
161
|
+
/** Whether the connection is being asked for something right now, which it reports as a state change before it answers. */
|
|
162
|
+
let asking = false;
|
|
163
|
+
/** Whether the link itself left the channel to join it again, and the gateway has yet to report that leave. */
|
|
164
|
+
let leaving = false;
|
|
165
|
+
/** The networking the connection was last ready over: ready over it again is a resume, over another a new media path. */
|
|
166
|
+
let path: object | undefined;
|
|
157
167
|
|
|
158
168
|
const statusOf = (state: VoiceConnectionState): VoiceLinkStatus => {
|
|
159
169
|
if (state.status === Status.Ready) return "ready";
|
|
@@ -167,7 +177,7 @@ function linkOver(
|
|
|
167
177
|
*/
|
|
168
178
|
const recover = (state: VoiceConnectionState): void => {
|
|
169
179
|
// `rejoin()` reports its own outcome as a state change before it answers: that one is not a drop to recover from.
|
|
170
|
-
if (
|
|
180
|
+
if (asking) return;
|
|
171
181
|
clock.clearTimeout(rejoin);
|
|
172
182
|
rejoin = undefined;
|
|
173
183
|
if (closed || state.status !== Status.Disconnected) return;
|
|
@@ -176,17 +186,22 @@ function linkOver(
|
|
|
176
186
|
state.closeCode === DISCONNECTED;
|
|
177
187
|
if (refused) return;
|
|
178
188
|
let carried: boolean;
|
|
179
|
-
|
|
189
|
+
asking = true;
|
|
180
190
|
try {
|
|
181
|
-
|
|
191
|
+
// The link's own channel, which the connection no longer names once the link left it to join again.
|
|
192
|
+
carried = connection.rejoin({
|
|
193
|
+
channelId,
|
|
194
|
+
selfDeaf: false,
|
|
195
|
+
selfMute: true,
|
|
196
|
+
});
|
|
182
197
|
} finally {
|
|
183
|
-
|
|
198
|
+
asking = false;
|
|
184
199
|
}
|
|
185
200
|
if (carried) return;
|
|
186
201
|
rejoin = clock.setTimeout(() => retry(), REJOIN_MS);
|
|
187
202
|
};
|
|
188
203
|
|
|
189
|
-
/** A
|
|
204
|
+
/** A rejoin that throws, after the join itself, is a refused one: warned, no audio, asked for again. */
|
|
190
205
|
const retry = (): void => {
|
|
191
206
|
try {
|
|
192
207
|
recover(connection.state);
|
|
@@ -279,9 +294,74 @@ function linkOver(
|
|
|
279
294
|
});
|
|
280
295
|
};
|
|
281
296
|
|
|
297
|
+
/** What the connection is asked for a link that does not hear; a failure is warned and never thrown into the watch's timer. */
|
|
298
|
+
const attempt = (what: string, run: () => void): void => {
|
|
299
|
+
asking = true;
|
|
300
|
+
try {
|
|
301
|
+
run();
|
|
302
|
+
} catch (error) {
|
|
303
|
+
logger.warn(
|
|
304
|
+
{
|
|
305
|
+
guildId,
|
|
306
|
+
channelId,
|
|
307
|
+
reason: error instanceof Error ? error.message : String(error),
|
|
308
|
+
},
|
|
309
|
+
`voice ${what} failed`,
|
|
310
|
+
);
|
|
311
|
+
} finally {
|
|
312
|
+
asking = false;
|
|
313
|
+
}
|
|
314
|
+
};
|
|
315
|
+
const watch = hearingWatch({
|
|
316
|
+
clock,
|
|
317
|
+
logger,
|
|
318
|
+
fields: { guildId, channelId },
|
|
319
|
+
person: (userId) => handlers?.person(userId) ?? false,
|
|
320
|
+
deafened: () => options.deafened?.() ?? false,
|
|
321
|
+
rebuild: () => {
|
|
322
|
+
const before = networkingOf(connection.state);
|
|
323
|
+
attempt("networking", () => connection.configureNetworking());
|
|
324
|
+
return networkingOf(connection.state) !== before;
|
|
325
|
+
},
|
|
326
|
+
rejoin: () => {
|
|
327
|
+
leaving = true;
|
|
328
|
+
// Leaves the channel; `retry` then finds the connection disconnected and asks for the channel again.
|
|
329
|
+
attempt("leave", () => connection.disconnect());
|
|
330
|
+
retry();
|
|
331
|
+
},
|
|
332
|
+
giveUp: () => {
|
|
333
|
+
attempt("leave", close);
|
|
334
|
+
// A connection that could not be destroyed reports nothing: the session ends all the same.
|
|
335
|
+
if (connection.state.status !== Status.Destroyed)
|
|
336
|
+
attempt("leave", () => handlers?.status("closed"));
|
|
337
|
+
},
|
|
338
|
+
});
|
|
339
|
+
const taps = hearingTaps(connection, watch);
|
|
340
|
+
/** The watch is told when the connection can hear: over a new media path, or the one it had. */
|
|
341
|
+
const heardOver = (
|
|
342
|
+
before: VoiceConnectionState,
|
|
343
|
+
state: VoiceConnectionState,
|
|
344
|
+
): void => {
|
|
345
|
+
if (state.status !== Status.Ready) {
|
|
346
|
+
if (before.status === Status.Ready) watch.down();
|
|
347
|
+
return;
|
|
348
|
+
}
|
|
349
|
+
if (before.status === Status.Ready) return;
|
|
350
|
+
leaving = false;
|
|
351
|
+
const networking = networkingOf(state);
|
|
352
|
+
if (networking !== undefined && networking === path) {
|
|
353
|
+
watch.resumed();
|
|
354
|
+
return;
|
|
355
|
+
}
|
|
356
|
+
path = networking;
|
|
357
|
+
watch.up();
|
|
358
|
+
};
|
|
359
|
+
|
|
282
360
|
connection.receiver.speaking.on("start", hear);
|
|
283
|
-
connection.on("stateChange", (
|
|
284
|
-
|
|
361
|
+
connection.on("stateChange", (before, state) => {
|
|
362
|
+
taps.follow(state);
|
|
363
|
+
heardOver(before, state);
|
|
364
|
+
retry();
|
|
285
365
|
if (state.status === Status.Destroyed) release();
|
|
286
366
|
handlers?.status(statusOf(state));
|
|
287
367
|
});
|
|
@@ -293,6 +373,8 @@ function linkOver(
|
|
|
293
373
|
if (closed) return;
|
|
294
374
|
closed = true;
|
|
295
375
|
clock.clearTimeout(rejoin);
|
|
376
|
+
watch.stop();
|
|
377
|
+
taps.stop();
|
|
296
378
|
connection.receiver.speaking.off("start", hear);
|
|
297
379
|
for (const stream of connection.receiver.subscriptions.values())
|
|
298
380
|
stream.destroy();
|
|
@@ -306,6 +388,19 @@ function linkOver(
|
|
|
306
388
|
);
|
|
307
389
|
};
|
|
308
390
|
|
|
391
|
+
const close = (): void => {
|
|
392
|
+
release();
|
|
393
|
+
// Tells Discord the bot left the channel; reports `closed` through the state change.
|
|
394
|
+
if (connection.state.status !== Status.Destroyed) connection.destroy();
|
|
395
|
+
};
|
|
396
|
+
|
|
397
|
+
taps.follow(connection.state);
|
|
398
|
+
// A connection the library already had ready is heard over the networking it has.
|
|
399
|
+
if (connection.state.status === Status.Ready) {
|
|
400
|
+
path = networkingOf(connection.state);
|
|
401
|
+
watch.up();
|
|
402
|
+
}
|
|
403
|
+
// The join's own first request is not caught: a connection whose setup throws is not joined.
|
|
309
404
|
recover(connection.state);
|
|
310
405
|
return {
|
|
311
406
|
status: () => (closed ? "closed" : statusOf(connection.state)),
|
|
@@ -313,10 +408,11 @@ function linkOver(
|
|
|
313
408
|
handlers = given;
|
|
314
409
|
},
|
|
315
410
|
forget,
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
411
|
+
leftItself: () => {
|
|
412
|
+
if (!leaving || closed) return false;
|
|
413
|
+
leaving = false;
|
|
414
|
+
return true;
|
|
320
415
|
},
|
|
416
|
+
close,
|
|
321
417
|
};
|
|
322
418
|
}
|
|
@@ -38,6 +38,8 @@ export interface VoiceLinkHandlers {
|
|
|
38
38
|
status(status: VoiceLinkStatus): void;
|
|
39
39
|
/** One decoded frame of a speaker, in the `VOICE_PCM` format, which the link keeps no reference to. */
|
|
40
40
|
frame(userId: string, pcm: Uint8Array): void;
|
|
41
|
+
/** Whether the user is a person in the channel, not a bot; with no user, whether any person is. */
|
|
42
|
+
person(userId?: string): boolean;
|
|
41
43
|
}
|
|
42
44
|
|
|
43
45
|
/** One voice connection: the bot in a channel, muted and not deafened. */
|
|
@@ -47,6 +49,12 @@ export interface VoiceLink {
|
|
|
47
49
|
listen(handlers: VoiceLinkHandlers): void;
|
|
48
50
|
/** Someone left the channel: what the link kept to hear them is freed, and made again if they are heard after all. */
|
|
49
51
|
forget(userId: string): void;
|
|
52
|
+
/**
|
|
53
|
+
* Whether the bot's leaving the channel, as the gateway now reports it, is the link's own on
|
|
54
|
+
* its way to join again, as it does for a speaker it does not hear. True once for each such leave: a second one before the link is back
|
|
55
|
+
* is someone removing the bot.
|
|
56
|
+
*/
|
|
57
|
+
leftItself(): boolean;
|
|
50
58
|
/** Leaves the channel and frees the decoders; does nothing the second time. */
|
|
51
59
|
close(): void;
|
|
52
60
|
}
|
|
@@ -61,6 +69,11 @@ export interface VoiceGateway {
|
|
|
61
69
|
channel(channelId: string): Promise<VoiceChannelFacts | "gone" | "forbidden">;
|
|
62
70
|
/** Reports every voice channel change in every guild. */
|
|
63
71
|
onVoiceState(listener: (change: VoiceStateChange) => void): void;
|
|
72
|
+
/**
|
|
73
|
+
* Reports each time the gateway connection is up again, resumed or identified anew: who is in
|
|
74
|
+
* a channel may have changed meanwhile with no word of it.
|
|
75
|
+
*/
|
|
76
|
+
onReady(listener: () => void): void;
|
|
64
77
|
/** Loads what a connection needs, so a host that cannot hear fails as it starts. */
|
|
65
78
|
prepare(): Promise<void>;
|
|
66
79
|
/** Opens the voice connection; rejects when it cannot be opened at all. */
|
|
@@ -169,9 +182,9 @@ export function voiceService(options: VoiceServiceOptions): VoiceService {
|
|
|
169
182
|
};
|
|
170
183
|
|
|
171
184
|
/**
|
|
172
|
-
* A dropped connection is back: who is in the channel is read
|
|
173
|
-
* entered meanwhile is reported now. A gateway that had to identify
|
|
174
|
-
* voice states anew, with no word of what changed.
|
|
185
|
+
* A dropped connection is back, the voice one or the gateway's: who is in the channel is read
|
|
186
|
+
* again, and whoever left or entered meanwhile is reported now. A gateway that had to identify
|
|
187
|
+
* again is sent the guild's voice states anew, with no word of what changed.
|
|
175
188
|
*/
|
|
176
189
|
const reread = async (entry: Joined): Promise<void> => {
|
|
177
190
|
const { session } = entry;
|
|
@@ -190,6 +203,11 @@ export function voiceService(options: VoiceServiceOptions): VoiceService {
|
|
|
190
203
|
}
|
|
191
204
|
};
|
|
192
205
|
|
|
206
|
+
// A gateway that identified again holds the guild's voice states anew, whatever the voice connection did meanwhile.
|
|
207
|
+
gateway.onReady(() => {
|
|
208
|
+
for (const entry of [...joined.values()]) void reread(entry);
|
|
209
|
+
});
|
|
210
|
+
|
|
193
211
|
gateway.onVoiceState((change) => {
|
|
194
212
|
const entry = joined.get(change.guildId);
|
|
195
213
|
if (!entry) return;
|
|
@@ -197,6 +215,8 @@ export function voiceService(options: VoiceServiceOptions): VoiceService {
|
|
|
197
215
|
if (change.userId === gateway.botId()) {
|
|
198
216
|
// Its own way into the channel is the join's to wait for.
|
|
199
217
|
if (!entry.open || change.channelId === session.channelId) return;
|
|
218
|
+
// A link that left to join again, for a speaker it does not hear, was not removed.
|
|
219
|
+
if (change.channelId === undefined && entry.link?.leftItself()) return;
|
|
200
220
|
return end(entry, change.channelId === undefined ? "removed" : "moved");
|
|
201
221
|
}
|
|
202
222
|
if (change.channelId === session.channelId)
|
|
@@ -219,6 +239,14 @@ export function voiceService(options: VoiceServiceOptions): VoiceService {
|
|
|
219
239
|
onStatus(entry, status);
|
|
220
240
|
},
|
|
221
241
|
frame: (userId, pcm) => entry.session.frame(userId, pcm),
|
|
242
|
+
person: (userId) =>
|
|
243
|
+
entry.session
|
|
244
|
+
.members()
|
|
245
|
+
.some(
|
|
246
|
+
(member) =>
|
|
247
|
+
!member.bot &&
|
|
248
|
+
(userId === undefined || member.userId === userId),
|
|
249
|
+
),
|
|
222
250
|
});
|
|
223
251
|
settle(link.status());
|
|
224
252
|
});
|
|
@@ -15,7 +15,7 @@ export type VoiceDisconnectReason =
|
|
|
15
15
|
| "left" // the plugin called `leave()`
|
|
16
16
|
| "removed" // the bot was disconnected from the channel: someone disconnected it, or the channel was deleted
|
|
17
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
|
|
18
|
+
| "connection_lost" // the voice connection dropped and did not come back within the resume time, or it heard nothing while someone spoke and neither setting it up again nor rejoining the channel brought the audio back
|
|
19
19
|
| "stopped"; // the host is stopping
|
|
20
20
|
|
|
21
21
|
/** Someone in a voice channel. */
|
|
@@ -19,9 +19,9 @@ export interface BlockSupport {
|
|
|
19
19
|
*/
|
|
20
20
|
readonly lang?: TextLang;
|
|
21
21
|
/**
|
|
22
|
-
* `false` = the surface's own guidance already says what
|
|
23
|
-
*
|
|
24
|
-
* surface does not draw every interactive kind.
|
|
22
|
+
* `false` = the surface's own guidance already says what becomes of a form, option-button or
|
|
23
|
+
* checklist block it does not draw, so core adds no line about them. Absent = core adds one
|
|
24
|
+
* whenever the surface does not draw every interactive kind.
|
|
25
25
|
*/
|
|
26
26
|
readonly blockNote?: false;
|
|
27
27
|
}
|
|
@@ -37,7 +37,9 @@ export interface ChannelSupport extends BlockSupport {
|
|
|
37
37
|
* channel's `support` lays what differs (a host's room on an app, which draws no blocks). A
|
|
38
38
|
* surface that does not draw every interactive kind (`options`, `suggest`, `form`, `checklist`,
|
|
39
39
|
* `review`) gets a closing line in its `formatting` that says so, so the model does not expect
|
|
40
|
-
* its reader to fill one in.
|
|
40
|
+
* its reader to fill one in. The line speaks of blocks written in a reply and of nothing else:
|
|
41
|
+
* a tool that asks the user on the surface's own cards, as `ask_user` does, is not a block.
|
|
42
|
+
* `lang` is the host's language for the text form of a block.
|
|
41
43
|
*/
|
|
42
44
|
export function supportOf(
|
|
43
45
|
surface:
|
|
@@ -73,16 +75,20 @@ export function supportOf(
|
|
|
73
75
|
|
|
74
76
|
/**
|
|
75
77
|
* What the model is told about the interactive kinds a surface does not draw: none when it draws
|
|
76
|
-
* them all. Such a block reaches the reader as a question to answer by typing.
|
|
78
|
+
* them all. Such a block reaches the reader as a question to answer by typing. It names blocks
|
|
79
|
+
* written in a reply only, and says so: read as "this chat has no buttons", it kept a model from
|
|
80
|
+
* `ask_user`, whose card with buttons the same chat shows.
|
|
77
81
|
*/
|
|
78
82
|
function interactiveNote(
|
|
79
83
|
blocks: readonly BlockKind[] | undefined,
|
|
80
84
|
): string | undefined {
|
|
81
85
|
const missing = INTERACTIVE_KINDS.filter((kind) => !blocks?.includes(kind));
|
|
82
86
|
if (missing.length === 0) return undefined;
|
|
83
|
-
const
|
|
87
|
+
const notDrawn =
|
|
84
88
|
missing.length === INTERACTIVE_KINDS.length
|
|
85
|
-
? "
|
|
86
|
-
:
|
|
87
|
-
|
|
89
|
+
? "Display blocks that ask for input (a form, option buttons or a checklist written as a fenced block in a reply) are"
|
|
90
|
+
: missing.length === 1
|
|
91
|
+
? `The display block \`${missing[0]}\` is`
|
|
92
|
+
: `The display blocks ${missing.map((kind) => `\`${kind}\``).join(", ")} are`;
|
|
93
|
+
return `${notDrawn} not drawn in this chat: the user sees one as text and answers by typing, so put the question in plain words instead of writing one. This is about blocks written in a reply only: a tool that asks the user, such as ask_user, works as its description says.`;
|
|
88
94
|
}
|
|
@@ -122,6 +122,7 @@ export function fakeDiscordVoice(
|
|
|
122
122
|
onVoiceState: (listener) => {
|
|
123
123
|
report = listener;
|
|
124
124
|
},
|
|
125
|
+
onReady: () => undefined,
|
|
125
126
|
prepare: async () => undefined,
|
|
126
127
|
connect: async ({ guildId, channelId }) => {
|
|
127
128
|
let status: VoiceLinkStatus = "ready";
|
|
@@ -136,6 +137,7 @@ export function fakeDiscordVoice(
|
|
|
136
137
|
link.handlers = handlers;
|
|
137
138
|
},
|
|
138
139
|
forget: () => undefined,
|
|
140
|
+
leftItself: () => false,
|
|
139
141
|
close: () => {
|
|
140
142
|
status = "closed";
|
|
141
143
|
if (links.get(guildId) === link) links.delete(guildId);
|