pi-roundtable 0.47.3 → 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 +16 -0
- package/README.md +5 -0
- package/docs/plugins.md +57 -6
- package/package.json +6 -1
- package/src/core/builtin/discord.ts +41 -0
- package/src/core/config/adapters.ts +10 -0
- package/src/core/contract/surface.ts +5 -4
- package/src/core/discord/discord-surface.ts +4 -0
- package/src/core/discord/voice/voice-clock.ts +51 -0
- package/src/core/discord/voice/voice-discord.ts +185 -0
- package/src/core/discord/voice/voice-hearing.ts +357 -0
- package/src/core/discord/voice/voice-link.ts +418 -0
- package/src/core/discord/voice/voice-service.ts +336 -0
- package/src/core/discord/voice/voice-session.ts +230 -0
- package/src/core/discord/voice/voice.ts +144 -0
- package/src/core/domain/block-support.ts +15 -9
- package/src/core/host/define-roundtable.ts +1 -0
- package/src/core/testing/fake-discord.ts +7 -2
- package/src/core/testing/fake-voice.ts +229 -0
- package/src/core/testing/plugin-stand-ins.ts +27 -0
- package/src/core/testing/test-host.ts +5 -1
- package/src/discord/index.ts +14 -0
- package/src/testing.ts +7 -19
package/CHANGELOG.md
CHANGED
|
@@ -5,6 +5,22 @@ 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
|
+
|
|
17
|
+
## [0.48.0] - 2026-11-15
|
|
18
|
+
|
|
19
|
+
### Added
|
|
20
|
+
|
|
21
|
+
- Discord voice for plugins, off unless the configuration says `discord: { voice: true }`. With it, the Discord plugin provides `DISCORD.voice` (`DiscordVoice`, from `pi-roundtable/discord`): `join({ guildId, channelId }, options?)` puts the bot in a voice or stage channel, muted and not deafened, and answers a `VoiceSession` or a `VoiceJoinFailure` (`forbidden`, `channel_gone`, `not_voice`, `full`, `unavailable`, `already_joined`; one session per guild) as a `VoiceJoinResult`. A session hands each speaker's audio to `onUtterance` as a `VoiceUtterance` of 48 kHz 16-bit mono PCM (`VOICE_PCM`) with the speaker's Discord user id and the times it started and ended, cut where the speaker went quiet (`VoiceJoinOptions`: `silenceMs`, `maxUtteranceMs`); reports who starts and stops speaking (`VoiceSpeakingEvent`) and who is in the channel (`members()`, `VoiceMember`, `VoiceMemberEvent`); and ends with `leave()` or a `VoiceDisconnectEvent` whose `VoiceDisconnectReason` says why. A dropped connection has 20 seconds to come back. Discord's end-to-end encryption (DAVE) is handled by `@discordjs/voice`; decoded audio stays in memory and is never written to disk or to a log. The bot asks for the Guild Voice States intent, which is not privileged. Without `discord.voice` nothing changes: no intent, and none of the new dependencies (`@discordjs/voice`, `@snazzah/davey`, `opusscript`, `@noble/ciphers`) is loaded.
|
|
22
|
+
- `fakeDiscordVoice` in `pi-roundtable/testing` makes that service in memory for a plugin's tests (`FakeDiscordVoice`, `FakeVoiceChannel`): the test makes channels, moves people, feeds frames of PCM, and ends sessions from outside, and reads the joins asked for and why each session ended. `fakeDiscord({ voice })` and `testHost({ discord: { voice } })` hand it to the plugin.
|
|
23
|
+
|
|
8
24
|
## [0.47.3] - 2026-11-13
|
|
9
25
|
|
|
10
26
|
### Fixed
|
package/README.md
CHANGED
|
@@ -253,6 +253,11 @@ When a conversation is started over in a server channel or thread, the assistant
|
|
|
253
253
|
| `false` | `false` | The bot asks Discord for no privileged intent beyond Message Content |
|
|
254
254
|
| `true` | | Plugins hear each member that joins the server (`memberJoined`). Needs Server Members Intent switched on under Bot in the Developer Portal; `roundtable doctor` checks it |
|
|
255
255
|
|
|
256
|
+
| `discord.voice` | Default | What it is |
|
|
257
|
+
| --- | --- | --- |
|
|
258
|
+
| `false` | `false` | The bot asks Discord for no voice intent and loads no voice package |
|
|
259
|
+
| `true` | | Plugins may join the server's voice channels through `DISCORD.voice` and hear each speaker, such as one that records a meeting. Asks for the Guild Voice States intent, which needs no change in the Developer Portal; the bot needs View Channel and Connect in a channel it joins |
|
|
260
|
+
|
|
256
261
|
| `discord.formatting` | Default | What it is |
|
|
257
262
|
| --- | --- | --- |
|
|
258
263
|
| text | Markdown renders except tables | What the model is told, in English, about how a reply renders in Discord; appended to the system prompt of every turn that replies there |
|
package/docs/plugins.md
CHANGED
|
@@ -277,7 +277,7 @@ The built-in plugins provide these, from the main entry:
|
|
|
277
277
|
|
|
278
278
|
The data types the ports use (`Schedule`, `NewSchedule`, `Agent`, `AgentGroup`, `TeamStatus`, `Memory`, `SkillSet`, `DelegationJob`, and so on) are in the main entry too.
|
|
279
279
|
Your plugins run after the built-ins, so they can read every key above.
|
|
280
|
-
The Discord connection's key, `DISCORD`, is in the Discord entry, because its port names discord.js types: `DiscordServices` has `connection`, `commands`, `guard`, `threads` (the same instance as `THREADS`), `poster` (see [Posting through `DISCORD.poster`](#posting-through-discordposter)) and `
|
|
280
|
+
The Discord connection's key, `DISCORD`, is in the Discord entry, because its port names discord.js types: `DiscordServices` has `connection`, `commands`, `guard`, `threads` (the same instance as `THREADS`), `poster` (see [Posting through `DISCORD.poster`](#posting-through-discordposter)), `channelContext`, and `voice` when the host's `discord.voice` is on (see [Voice](#voice-hearing-a-voice-channel-through-discordvoice)); commands are in [`commands.add`](#slash-commands-commandsadd). A plugin's own stand-in for `DISCORD` (such as one written with `as unknown as DiscordServices`) needs a `poster` too before code that posts runs under it; `fakeDiscord()` and `testHost` give one.
|
|
281
281
|
|
|
282
282
|
To share your own service, export its key as a constant and its port as an interface.
|
|
283
283
|
Plugins registered after yours can read it during setup.
|
|
@@ -2981,6 +2981,41 @@ await poster.postCard(channelId, {
|
|
|
2981
2981
|
|
|
2982
2982
|
In a test, `fakeDiscordPoster()` is a `DiscordPoster` in memory and `fakeDiscord({ poster })` or `testHost({ discord: { poster } })` gives it to the plugin; see [Testing a plugin](#testing-a-plugin). The real poster and the fake run the same scenarios, the real one over a local emulation of Discord's HTTP API.
|
|
2983
2983
|
|
|
2984
|
+
### Voice: hearing a voice channel through `DISCORD.voice`
|
|
2985
|
+
|
|
2986
|
+
`DISCORD.voice` (`DiscordVoice`, from `pi-roundtable/discord`) lets a plugin join a server's voice channel and hear each speaker apart, for a plugin that records a meeting and has it transcribed.
|
|
2987
|
+
It is there only when the host's configuration says `discord: { voice: true }`; without it `DISCORD.voice` is `undefined`, the bot asks Discord for no voice intent, and no voice package is loaded.
|
|
2988
|
+
With it, the bot asks for the Guild Voice States intent, which is not privileged and needs no change in the Developer Portal, and loads its voice packages as the host starts, so a host that cannot hear fails at start and not at the first meeting.
|
|
2989
|
+
The bot needs View Channel and Connect in a channel it joins.
|
|
2990
|
+
It joins muted and not deafened, and never speaks.
|
|
2991
|
+
|
|
2992
|
+
```ts
|
|
2993
|
+
import { DISCORD, VOICE_PCM } from "pi-roundtable/discord";
|
|
2994
|
+
|
|
2995
|
+
const voice = services.get(DISCORD).voice;
|
|
2996
|
+
if (!voice) throw new Error("Set discord.voice to true to record meetings.");
|
|
2997
|
+
const answer = await voice.join({ guildId, channelId });
|
|
2998
|
+
if (!answer.ok) return `Not joined: ${answer.failure}. ${answer.message}`;
|
|
2999
|
+
const { session } = answer;
|
|
3000
|
+
session.onUtterance(({ userId, pcm, startedAt, endedAt }) => {
|
|
3001
|
+
// pcm is 48 kHz signed 16-bit little-endian mono: wrap it as WAV and send it to speech-to-text.
|
|
3002
|
+
transcribe(userId, pcm, VOICE_PCM.sampleRate, startedAt, endedAt);
|
|
3003
|
+
});
|
|
3004
|
+
session.onMember(({ kind, member }) => note(`${member.displayName} ${kind}`));
|
|
3005
|
+
session.onDisconnect(({ reason }) => finish(reason));
|
|
3006
|
+
// Later:
|
|
3007
|
+
await session.leave();
|
|
3008
|
+
```
|
|
3009
|
+
|
|
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
|
+
- **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
|
+
- **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; 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
|
+
- **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
|
+
|
|
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.
|
|
3018
|
+
|
|
2984
3019
|
### `backgroundTargets`: whose turn a schedule or delegated task is
|
|
2985
3020
|
|
|
2986
3021
|
Schedules and delegated tasks return later as turns without a new message in the channel.
|
|
@@ -3132,7 +3167,7 @@ The agent server claims `discord:` keys, and, only on a surface that declares `a
|
|
|
3132
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 |
|
|
3133
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"` |
|
|
3134
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 |
|
|
3135
|
-
| `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 |
|
|
3136
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 |
|
|
3137
3172
|
| `startTyping(channel)` | Shows a typing indicator until the returned function is called | none is shown |
|
|
3138
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 |
|
|
@@ -3278,7 +3313,7 @@ The team writes through the providers too. At start it calls `ensure` for each a
|
|
|
3278
3313
|
|
|
3279
3314
|
### Display blocks in a reply
|
|
3280
3315
|
|
|
3281
|
-
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`.
|
|
3282
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).
|
|
3283
3318
|
|
|
3284
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.
|
|
@@ -4173,9 +4208,10 @@ Use `partial<Port>({ ... })` to stand in for a port your code takes as an argume
|
|
|
4173
4208
|
It provides the members you give it and throws an error naming any missing member you read, so the test needs no `as unknown as Port` cast.
|
|
4174
4209
|
`fakePrecheck(name, answer, { description?, timeoutMs? })` is a precheck that answers `answer` (a `PrecheckResult`, an `Error` it throws, or a function of its context) and records each context in `calls`; `fakePrechecks(...prechecks)` is a real in-memory `PrecheckRegistry` with them registered, which a test gives a plugin as `servicePair(PRECHECKS, registry)` and reads back with `registry.get(name)`.
|
|
4175
4210
|
`fakeScriptRunner(answer, { describe?, timeoutMs? })` is a `PrecheckScriptRunner` that runs nothing and answers `answer` (a result, an `Error` it throws, or a function of the script and its context), recording each call in `calls`; give it to `registry.useScriptRunner`.
|
|
4176
|
-
`fakeDiscord({ ownerId?, rootCommand?, channelContext?, poster? })` is the `DISCORD` service for a plugin that adds slash commands, reads channel context or
|
|
4177
|
-
Only `commands`, `guard`, `poster` and `
|
|
4211
|
+
`fakeDiscord({ ownerId?, rootCommand?, channelContext?, poster?, voice? })` is the `DISCORD` service for a plugin that adds slash commands, reads channel context, posts through `DISCORD.poster` or listens through `DISCORD.voice`: give it as `services: [discord.service]`, read what the plugin added with `discord.added()`, and compose the tree Discord would get with `discord.compose()`; `channelContext` answers `DISCORD.channelContext`, by default with no context.
|
|
4212
|
+
Only `commands`, `guard`, `poster`, `channelContext` and `voice` are given; `discord.poster` is the poster the test passed, else a new `fakeDiscordPoster()`, and `DISCORD.voice` is the `voice` the test passed, else `undefined`, as on a host with `discord.voice` off. A plugin that reads another member of `DISCORD` in a test gives its own with `servicePair(DISCORD, { ... })`.
|
|
4178
4213
|
`fakeDiscordPoster({ idOffset?, now? })` is a `DiscordPoster` in memory: `channels` with their messages, pins and webhook pictures, `directs`, and the knobs a test turns (`closedDirects`, `goneChannels`, `categories`, `forums` (a forum is an entry `{ tags }` here plus a `channels` entry; a forum post is a channel whose `parentId` is the forum, with `appliedTags`), `memberNames`, `hiddenFrom`, `nonMembers`, `pinNotices`, `canReadAuditLog`, `failNext(operation, error)`, `speak`, `personCloses`, `autoArchives`, `personOpens`, `deleteWebhook`, `recreateWebhook`). `messagesIn(channelId)` lists what a channel holds. It keeps the real poster's argument checks and error kinds, a channel's two renames in ten minutes (by `now`) and the 250 pins. `idOffset` moves every id it makes, so test files that share a database never meet the same id.
|
|
4214
|
+
`fakeDiscordVoice({ now? })` is a `DiscordVoice` in memory (`FakeDiscordVoice`) that runs the real session logic over a Discord the test drives. Make the channels that exist with `voice.channels.set(channelId, { guildId, kind?, members?, forbidden?, full? })` (a `FakeVoiceChannel`; `kind` is `voice`, `stage` or `text`), and set `voice.available = false` for a Discord that is not connected. `enter(channelId, member)` and `exit(channelId, userId)` move people; `audio(channelId, userId, pcm)` is one frame of someone in the channel speaking (48 kHz 16-bit mono PCM, which a session there hears), `quiet()` lets five seconds pass so every open utterance ends, and `say(channelId, userId, ...frames)` is both: one whole utterance. The fake's clock starts at `now` and moves only with the audio a test feeds and with `quiet()`, so `startedAt` and `endedAt` are the same on every run. `drop(guildId, "removed" | "moved" | "connection_lost")` ends a session from outside and `stop()` as a stopping host does. `voice.joins` lists every join asked for, and `voice.ended` every session that ended with its `reason`, `left` for the plugin's own `leave()`.
|
|
4179
4215
|
|
|
4180
4216
|
### `testHost`: the built-in plugins and yours, over PostgreSQL
|
|
4181
4217
|
|
|
@@ -4189,7 +4225,7 @@ It boots `defineRoundtable` over `ROUNDTABLE_TEST_DATABASE_URL`, with stand-ins
|
|
|
4189
4225
|
| `plugins` | Your plugins, placed after the built-in ones as `defineRoundtable` places them |
|
|
4190
4226
|
| `runtime` | The runtime every turn runs on; by default one that answers `""` and builds no Pi session |
|
|
4191
4227
|
| `apiKeys` | The credentials `context.apiKey(provider)` returns, by provider name; a provider not listed reads as having none, whatever login the machine holds |
|
|
4192
|
-
| `discord` | What the stand-in Discord hands out: `agentChannels(guildId)`, `ownerChannel()`, `channelInfo(channelId)
|
|
4228
|
+
| `discord` | What the stand-in Discord hands out: `agentChannels(guildId)`, `ownerChannel()`, `channelInfo(channelId)`, `poster` (what `DISCORD.poster` is; by default a `fakeDiscordPoster()`) and `voice` (what `DISCORD.voice` is; by default none); `false` boots a [host without Discord](#a-host-without-discord), with no `discord`, `http`, or `agents` in the test configuration; give `config: { agents }` and a plugin whose surface declares `agentRooms` to boot an [agent team without Discord](#an-agent-team-without-discord) |
|
|
4193
4229
|
|
|
4194
4230
|
It returns:
|
|
4195
4231
|
|
|
@@ -4908,6 +4944,9 @@ Import from the entries listed below; source area files are internal.
|
|
|
4908
4944
|
| `eagerText` | `pi-roundtable/testing` | value |
|
|
4909
4945
|
| `fakeDiscord` | `pi-roundtable/testing` | value |
|
|
4910
4946
|
| `fakeDiscordPoster` | `pi-roundtable/testing` | value |
|
|
4947
|
+
| `fakeDiscordVoice` | `pi-roundtable/testing` | value |
|
|
4948
|
+
| `FakeDiscordVoice` | `pi-roundtable/testing` | type |
|
|
4949
|
+
| `FakeVoiceChannel` | `pi-roundtable/testing` | type |
|
|
4911
4950
|
| `FakeDiscordPoster` | `pi-roundtable/testing` | type |
|
|
4912
4951
|
| `FakePosterChannel` | `pi-roundtable/testing` | type |
|
|
4913
4952
|
| `FakeForum` | `pi-roundtable/testing` | type |
|
|
@@ -5174,6 +5213,18 @@ Import from the entries listed below; source area files are internal.
|
|
|
5174
5213
|
| `ThreadState` | `pi-roundtable/discord` | type |
|
|
5175
5214
|
| `WebhookCardPost` | `pi-roundtable/discord` | type |
|
|
5176
5215
|
| `WebhookPost` | `pi-roundtable/discord` | type |
|
|
5216
|
+
| `DiscordVoice` | `pi-roundtable/discord` | type |
|
|
5217
|
+
| `VOICE_PCM` | `pi-roundtable/discord` | value |
|
|
5218
|
+
| `VoiceDisconnectEvent` | `pi-roundtable/discord` | type |
|
|
5219
|
+
| `VoiceDisconnectReason` | `pi-roundtable/discord` | type |
|
|
5220
|
+
| `VoiceJoinFailure` | `pi-roundtable/discord` | type |
|
|
5221
|
+
| `VoiceJoinOptions` | `pi-roundtable/discord` | type |
|
|
5222
|
+
| `VoiceJoinResult` | `pi-roundtable/discord` | type |
|
|
5223
|
+
| `VoiceMember` | `pi-roundtable/discord` | type |
|
|
5224
|
+
| `VoiceMemberEvent` | `pi-roundtable/discord` | type |
|
|
5225
|
+
| `VoiceSession` | `pi-roundtable/discord` | type |
|
|
5226
|
+
| `VoiceSpeakingEvent` | `pi-roundtable/discord` | type |
|
|
5227
|
+
| `VoiceUtterance` | `pi-roundtable/discord` | type |
|
|
5177
5228
|
| `InteractionContribution` | `pi-roundtable/discord` | type |
|
|
5178
5229
|
| `InteractionModule` | `pi-roundtable/discord` | type |
|
|
5179
5230
|
| `ManagedChannel` | `pi-roundtable/discord` | type |
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-roundtable",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.48.1",
|
|
4
4
|
"description": "A plugin-driven Pi agent server for one owner, reached through Discord or the web",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -32,6 +32,7 @@
|
|
|
32
32
|
"!src/core/testing/prompt-capture*.ts",
|
|
33
33
|
"!src/core/testing/discord-api-emulator*.ts",
|
|
34
34
|
"!src/core/discord/poster/poster-contract*.ts",
|
|
35
|
+
"!src/core/discord/voice/voice-contract*.ts",
|
|
35
36
|
"!src/core/testing/fixtures",
|
|
36
37
|
"!src/characters/fixtures",
|
|
37
38
|
"!src/m2-acceptance",
|
|
@@ -68,10 +69,14 @@
|
|
|
68
69
|
"dependencies": {
|
|
69
70
|
"@babel/parser": "8.0.7",
|
|
70
71
|
"@babel/types": "8.0.6",
|
|
72
|
+
"@discordjs/voice": "0.19.2",
|
|
71
73
|
"@earendil-works/pi-ai": ">=0.99.2 <2",
|
|
72
74
|
"@earendil-works/pi-coding-agent": ">=0.99.2 <2",
|
|
75
|
+
"@noble/ciphers": "2.4.0",
|
|
76
|
+
"@snazzah/davey": "0.1.9",
|
|
73
77
|
"canvas": "3.2.3",
|
|
74
78
|
"discord.js": "14.27.0",
|
|
79
|
+
"opusscript": "0.1.1",
|
|
75
80
|
"pi-jev-compaction": "1.0.0",
|
|
76
81
|
"pi-better-show": "0.5.0",
|
|
77
82
|
"pi-mcp-adapter": "5.3.0",
|
|
@@ -26,6 +26,9 @@ import { commandGuard, ownerRootCommand } from "../discord/owner-command.ts";
|
|
|
26
26
|
import type { DiscordPoster } from "../discord/poster/poster.ts";
|
|
27
27
|
import { restOf, restPoster } from "../discord/poster/rest-poster.ts";
|
|
28
28
|
import { stopButtonModule } from "../discord/stop-button.ts";
|
|
29
|
+
import type { DiscordVoice } from "../discord/voice/voice.ts";
|
|
30
|
+
import { discordVoiceGateway } from "../discord/voice/voice-discord.ts";
|
|
31
|
+
import { voiceService } from "../discord/voice/voice-service.ts";
|
|
29
32
|
import type { InboundMessage } from "../domain/conversation.ts";
|
|
30
33
|
import { ConfigError } from "../domain/errors.ts";
|
|
31
34
|
import type { FormerChannelOps } from "../plugin-api/agent-ops.ts";
|
|
@@ -62,6 +65,12 @@ export interface DiscordServices {
|
|
|
62
65
|
message: InboundMessage,
|
|
63
66
|
options?: ChannelContextOptions,
|
|
64
67
|
): Promise<ChannelContext | undefined>;
|
|
68
|
+
/**
|
|
69
|
+
* Discord voice: joining a guild's voice channel, muted, to hear each speaker apart. There only
|
|
70
|
+
* when the host's `discord.voice` is on; a join before the connection is ready answers
|
|
71
|
+
* `unavailable`. See `DiscordVoice`.
|
|
72
|
+
*/
|
|
73
|
+
voice?: DiscordVoice;
|
|
65
74
|
}
|
|
66
75
|
|
|
67
76
|
/** The Discord connection, provided by the Discord plugin. */
|
|
@@ -127,6 +136,12 @@ export interface DiscordOptions {
|
|
|
127
136
|
* the connection is refused. Default: off.
|
|
128
137
|
*/
|
|
129
138
|
memberEvents?: boolean;
|
|
139
|
+
/**
|
|
140
|
+
* Asks Discord for the Guild Voice States intent (not privileged) and provides `DISCORD.voice`,
|
|
141
|
+
* with which a plugin joins a voice channel and hears each speaker. The voice packages are
|
|
142
|
+
* loaded as the host starts, and only then. Default: off.
|
|
143
|
+
*/
|
|
144
|
+
voice?: boolean;
|
|
130
145
|
/** What the model is told about how replies render in Discord; `false` tells it nothing. Default: Markdown renders, except tables. */
|
|
131
146
|
formatting?: string | false;
|
|
132
147
|
/**
|
|
@@ -222,8 +237,16 @@ export function discordPlugin(options: DiscordOptions): RoundtablePlugin {
|
|
|
222
237
|
? {}
|
|
223
238
|
: { formatting: options.formatting }),
|
|
224
239
|
...(options.memberEvents ? { memberEvents: true } : {}),
|
|
240
|
+
...(options.voice ? { voice: true } : {}),
|
|
225
241
|
});
|
|
226
242
|
surface = connected;
|
|
243
|
+
// Voice sessions over the same client; nothing of the voice packages is loaded before its service starts.
|
|
244
|
+
const voice = options.voice
|
|
245
|
+
? voiceService({
|
|
246
|
+
gateway: discordVoiceGateway(connected.client(), { logger }),
|
|
247
|
+
logger,
|
|
248
|
+
})
|
|
249
|
+
: undefined;
|
|
227
250
|
// Joins come only with the Server Members intent, which `memberEvents` asks for.
|
|
228
251
|
if (options.memberEvents)
|
|
229
252
|
connected.onMemberJoined((event) => events.memberJoined?.(event));
|
|
@@ -277,6 +300,14 @@ export function discordPlugin(options: DiscordOptions): RoundtablePlugin {
|
|
|
277
300
|
poster: restPoster(restOf(connected.rest())),
|
|
278
301
|
channelContext: (message, given) =>
|
|
279
302
|
connected.channelContext(message, given),
|
|
303
|
+
...(voice
|
|
304
|
+
? {
|
|
305
|
+
voice: {
|
|
306
|
+
join: (target, given) => voice.join(target, given),
|
|
307
|
+
session: (guildId) => voice.session(guildId),
|
|
308
|
+
},
|
|
309
|
+
}
|
|
310
|
+
: {}),
|
|
280
311
|
});
|
|
281
312
|
// Discord's side of the agent guild: the team's channels and threads as its places, their tools, and the dashboard message.
|
|
282
313
|
const agentGuild = options.agentGuild
|
|
@@ -321,6 +352,16 @@ export function discordPlugin(options: DiscordOptions): RoundtablePlugin {
|
|
|
321
352
|
await intercomTexts.stop();
|
|
322
353
|
},
|
|
323
354
|
},
|
|
355
|
+
// Fails the start when the voice packages cannot be loaded; ends every session as the host stops.
|
|
356
|
+
...(voice
|
|
357
|
+
? [
|
|
358
|
+
{
|
|
359
|
+
name: "discord-voice",
|
|
360
|
+
start: () => voice.start(),
|
|
361
|
+
stop: () => voice.stop(),
|
|
362
|
+
},
|
|
363
|
+
]
|
|
364
|
+
: []),
|
|
324
365
|
],
|
|
325
366
|
};
|
|
326
367
|
},
|
|
@@ -78,6 +78,13 @@ export interface DiscordConfig {
|
|
|
78
78
|
* doctor` says so. Default `false`, which needs no portal change.
|
|
79
79
|
*/
|
|
80
80
|
memberEvents?: boolean;
|
|
81
|
+
/**
|
|
82
|
+
* Lets plugins join the server's voice channels through `DISCORD.voice` and hear each speaker:
|
|
83
|
+
* the bot asks Discord for the Guild Voice States intent, which is not privileged and needs no
|
|
84
|
+
* portal change, and loads its voice packages as it starts. The bot needs View Channel and
|
|
85
|
+
* Connect in a channel it joins. Default `false`: no intent, and no voice package is loaded.
|
|
86
|
+
*/
|
|
87
|
+
voice?: boolean;
|
|
81
88
|
/**
|
|
82
89
|
* What the model is told, English, about how a reply renders in Discord, appended to the system
|
|
83
90
|
* prompt of every turn that replies there, after the persona. The default says Markdown
|
|
@@ -127,6 +134,7 @@ export interface ResolvedDiscord {
|
|
|
127
134
|
peerBots?: PeerBotsConfig;
|
|
128
135
|
freshMarker?: string | false;
|
|
129
136
|
memberEvents: boolean;
|
|
137
|
+
voice: boolean;
|
|
130
138
|
formatting?: string | false;
|
|
131
139
|
cardGraceSeconds: number;
|
|
132
140
|
/** As configured: `{}` when left out, so the defaults apply, or `false`. */
|
|
@@ -163,6 +171,7 @@ export function resolvedDiscord(
|
|
|
163
171
|
? {}
|
|
164
172
|
: { freshMarker: discord.freshMarker }),
|
|
165
173
|
memberEvents: discord.memberEvents ?? false,
|
|
174
|
+
voice: discord.voice ?? false,
|
|
166
175
|
...(discord.formatting === undefined
|
|
167
176
|
? {}
|
|
168
177
|
: { formatting: discord.formatting }),
|
|
@@ -211,6 +220,7 @@ export const discordShape = shape({
|
|
|
211
220
|
peerBots: optional(peerBotsShape),
|
|
212
221
|
freshMarker: optional(orOff(text)),
|
|
213
222
|
memberEvents: optional(bool),
|
|
223
|
+
voice: optional(bool),
|
|
214
224
|
formatting: optional(orOff(text)),
|
|
215
225
|
cardGraceSeconds: optional(integer(1, 86_400)),
|
|
216
226
|
cardCopies: optional(
|
|
@@ -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
|
/**
|
|
@@ -59,6 +59,7 @@ import { listenForMessages, reportChanges } from "./message-changes.ts";
|
|
|
59
59
|
import type { CardChannel, LateTurn } from "./owner-cards.ts";
|
|
60
60
|
import { DiscordOwnerOps } from "./owner-discord.ts";
|
|
61
61
|
import { showStopPanel } from "./stop-button.ts";
|
|
62
|
+
import { voiceIntents } from "./voice/voice-discord.ts";
|
|
62
63
|
|
|
63
64
|
const PREFIX = "discord:";
|
|
64
65
|
const TYPING_REFRESH_MS = 8_000;
|
|
@@ -76,6 +77,8 @@ export interface DiscordSurfaceOptions {
|
|
|
76
77
|
freshMarker?: string | false;
|
|
77
78
|
/** Asks Discord for the privileged Server Members intent, so `onMemberJoined` hears joins. Default: off. */
|
|
78
79
|
memberEvents?: boolean;
|
|
80
|
+
/** Asks Discord for the Guild Voice States intent, which `DISCORD.voice` needs. Default: off. */
|
|
81
|
+
voice?: boolean;
|
|
79
82
|
/** What the model is told about how replies render here; `false` tells it nothing. Default: `DISCORD_FORMATTING`. */
|
|
80
83
|
formatting?: string | false;
|
|
81
84
|
/** Where the agents' message cards keep their whole texts for the open button; without it a card posts as text. */
|
|
@@ -122,6 +125,7 @@ export class DiscordSurface
|
|
|
122
125
|
GatewayIntentBits.DirectMessages,
|
|
123
126
|
GatewayIntentBits.MessageContent,
|
|
124
127
|
...memberIntents(options.memberEvents),
|
|
128
|
+
...voiceIntents(options.voice),
|
|
125
129
|
],
|
|
126
130
|
partials: [Partials.Channel, Partials.Message],
|
|
127
131
|
allowedMentions: { parse: [] },
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
/** The time a voice session cuts utterances and waits by; a test gives its own. */
|
|
2
|
+
export interface VoiceClock {
|
|
3
|
+
/** Milliseconds since the epoch. */
|
|
4
|
+
now(): number;
|
|
5
|
+
setTimeout(run: () => void, ms: number): unknown;
|
|
6
|
+
clearTimeout(timer: unknown): void;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
/** The host's clock. */
|
|
10
|
+
export const systemClock: VoiceClock = {
|
|
11
|
+
now: () => Date.now(),
|
|
12
|
+
setTimeout: (run, ms) => setTimeout(run, ms),
|
|
13
|
+
clearTimeout: (timer) => clearTimeout(timer as Timer),
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
/** A clock that moves only when told to, for a stand-in voice connection. */
|
|
17
|
+
export interface ManualVoiceClock extends VoiceClock {
|
|
18
|
+
/** Moves the time on, running each timer that comes due at its own time, in order. */
|
|
19
|
+
advance(ms: number): void;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** A manual clock that starts at `start`, by default now. */
|
|
23
|
+
export function manualVoiceClock(start = Date.now()): ManualVoiceClock {
|
|
24
|
+
let time = start;
|
|
25
|
+
let next = 1;
|
|
26
|
+
const timers = new Map<number, { at: number; run: () => void }>();
|
|
27
|
+
return {
|
|
28
|
+
now: () => time,
|
|
29
|
+
setTimeout: (run, ms) => {
|
|
30
|
+
timers.set(next, { at: time + Math.max(0, ms), run });
|
|
31
|
+
return next++;
|
|
32
|
+
},
|
|
33
|
+
clearTimeout: (timer) => {
|
|
34
|
+
if (typeof timer === "number") timers.delete(timer);
|
|
35
|
+
},
|
|
36
|
+
advance: (ms) => {
|
|
37
|
+
const until = time + ms;
|
|
38
|
+
for (;;) {
|
|
39
|
+
let due: [number, { at: number; run: () => void }] | undefined;
|
|
40
|
+
for (const entry of timers)
|
|
41
|
+
if (entry[1].at <= until && (!due || entry[1].at < due[1].at))
|
|
42
|
+
due = entry;
|
|
43
|
+
if (!due) break;
|
|
44
|
+
timers.delete(due[0]);
|
|
45
|
+
time = due[1].at;
|
|
46
|
+
due[1].run();
|
|
47
|
+
}
|
|
48
|
+
time = until;
|
|
49
|
+
},
|
|
50
|
+
};
|
|
51
|
+
}
|
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
import {
|
|
2
|
+
ChannelType,
|
|
3
|
+
type Client,
|
|
4
|
+
DiscordAPIError,
|
|
5
|
+
Events,
|
|
6
|
+
GatewayIntentBits,
|
|
7
|
+
type Guild,
|
|
8
|
+
type GuildMember,
|
|
9
|
+
PermissionFlagsBits,
|
|
10
|
+
RESTJSONErrorCodes,
|
|
11
|
+
type VoiceState,
|
|
12
|
+
} from "discord.js";
|
|
13
|
+
import type { Logger } from "../../kernel/log.ts";
|
|
14
|
+
import type { VoiceMember } from "./voice.ts";
|
|
15
|
+
import type { VoiceClock } from "./voice-clock.ts";
|
|
16
|
+
import {
|
|
17
|
+
loadOpusDecoders,
|
|
18
|
+
loadVoiceLib,
|
|
19
|
+
type OpusDecoder,
|
|
20
|
+
openVoiceLink,
|
|
21
|
+
type VoiceLib,
|
|
22
|
+
} from "./voice-link.ts";
|
|
23
|
+
import type { VoiceChannelFacts, VoiceGateway } from "./voice-service.ts";
|
|
24
|
+
|
|
25
|
+
/** The Guild Voice States intent, asked for only when the host turns `discord.voice` on; it is not privileged. */
|
|
26
|
+
export function voiceIntents(
|
|
27
|
+
enabled: boolean | undefined,
|
|
28
|
+
): GatewayIntentBits[] {
|
|
29
|
+
return enabled ? [GatewayIntentBits.GuildVoiceStates] : [];
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export interface DiscordVoiceGatewayOptions {
|
|
33
|
+
logger: Logger;
|
|
34
|
+
/** Default: @discordjs/voice, loaded when first asked for. */
|
|
35
|
+
lib?: () => Promise<VoiceLib>;
|
|
36
|
+
/** Default: opusscript, loaded when first asked for. */
|
|
37
|
+
decoders?: () => Promise<() => OpusDecoder>;
|
|
38
|
+
/** What a connection's rejoin attempts wait by. Default: the host's clock. */
|
|
39
|
+
clock?: VoiceClock;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function memberOf(member: GuildMember): VoiceMember {
|
|
43
|
+
return {
|
|
44
|
+
userId: member.id,
|
|
45
|
+
bot: member.user.bot,
|
|
46
|
+
displayName: member.displayName,
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** Who a voice state is of; a member Discord sent no data for is named by their id. */
|
|
51
|
+
function memberOfState(state: VoiceState): VoiceMember {
|
|
52
|
+
return state.member
|
|
53
|
+
? memberOf(state.member)
|
|
54
|
+
: { userId: state.id, bot: false, displayName: state.id };
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** Who is in the channel, without the bot: members the cache lacks are fetched first, then the list is read in one go. */
|
|
58
|
+
async function membersIn(
|
|
59
|
+
guild: Guild,
|
|
60
|
+
channelId: string,
|
|
61
|
+
botId: string,
|
|
62
|
+
): Promise<VoiceMember[]> {
|
|
63
|
+
const inChannel = () =>
|
|
64
|
+
[...guild.voiceStates.cache.values()].filter(
|
|
65
|
+
(state) => state.channelId === channelId && state.id !== botId,
|
|
66
|
+
);
|
|
67
|
+
for (const state of inChannel())
|
|
68
|
+
if (!state.member)
|
|
69
|
+
await guild.members.fetch(state.id).catch(() => undefined);
|
|
70
|
+
return inChannel().map(memberOfState);
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* The voice gateway over the Discord plugin's own client, which must hold the Guild Voice States
|
|
75
|
+
* intent. Nothing of @discordjs/voice or the Opus decoder is loaded until `prepare` or `connect`.
|
|
76
|
+
*/
|
|
77
|
+
export function discordVoiceGateway(
|
|
78
|
+
client: Client,
|
|
79
|
+
options: DiscordVoiceGatewayOptions,
|
|
80
|
+
): VoiceGateway {
|
|
81
|
+
const { logger } = options;
|
|
82
|
+
let lib: Promise<VoiceLib> | undefined;
|
|
83
|
+
let decoders: Promise<() => OpusDecoder> | undefined;
|
|
84
|
+
const loaded = async () => {
|
|
85
|
+
lib ??= (options.lib ?? loadVoiceLib)();
|
|
86
|
+
decoders ??= (options.decoders ?? loadOpusDecoders)();
|
|
87
|
+
return { lib: await lib, decoder: await decoders };
|
|
88
|
+
};
|
|
89
|
+
return {
|
|
90
|
+
ready: () => client.isReady(),
|
|
91
|
+
botId: () => client.user?.id,
|
|
92
|
+
async channel(
|
|
93
|
+
channelId,
|
|
94
|
+
): Promise<VoiceChannelFacts | "gone" | "forbidden"> {
|
|
95
|
+
const refusal = (error: unknown) => {
|
|
96
|
+
if (!(error instanceof DiscordAPIError)) throw error;
|
|
97
|
+
if (error.code === RESTJSONErrorCodes.UnknownChannel) return "gone";
|
|
98
|
+
if (error.code === RESTJSONErrorCodes.MissingAccess) return "forbidden";
|
|
99
|
+
throw error;
|
|
100
|
+
};
|
|
101
|
+
// Asked of Discord, not the cache: a join is rare, and its refusal should be true now.
|
|
102
|
+
const channel = await client.channels
|
|
103
|
+
.fetch(channelId, { force: true })
|
|
104
|
+
.catch(refusal);
|
|
105
|
+
if (channel === "gone" || channel === "forbidden") return channel;
|
|
106
|
+
if (!channel) return "gone";
|
|
107
|
+
if (channel.isDMBased())
|
|
108
|
+
return {
|
|
109
|
+
guildId: "",
|
|
110
|
+
kind: "other",
|
|
111
|
+
connectable: false,
|
|
112
|
+
full: false,
|
|
113
|
+
members: [],
|
|
114
|
+
};
|
|
115
|
+
const kind =
|
|
116
|
+
channel.type === ChannelType.GuildVoice
|
|
117
|
+
? "voice"
|
|
118
|
+
: channel.type === ChannelType.GuildStageVoice
|
|
119
|
+
? "stage"
|
|
120
|
+
: "other";
|
|
121
|
+
const { guild } = channel;
|
|
122
|
+
const me = guild.members.me ?? (await guild.members.fetchMe());
|
|
123
|
+
const may = channel.permissionsFor(me);
|
|
124
|
+
return {
|
|
125
|
+
guildId: guild.id,
|
|
126
|
+
kind,
|
|
127
|
+
connectable:
|
|
128
|
+
may.has(PermissionFlagsBits.ViewChannel) &&
|
|
129
|
+
may.has(PermissionFlagsBits.Connect),
|
|
130
|
+
full:
|
|
131
|
+
channel.isVoiceBased() &&
|
|
132
|
+
channel.full &&
|
|
133
|
+
!may.has(PermissionFlagsBits.MoveMembers),
|
|
134
|
+
members:
|
|
135
|
+
kind === "other" ? [] : await membersIn(guild, channelId, me.id),
|
|
136
|
+
};
|
|
137
|
+
},
|
|
138
|
+
onVoiceState(listener) {
|
|
139
|
+
client.on(Events.VoiceStateUpdate, (before, now) => {
|
|
140
|
+
if (before.channelId === now.channelId) return;
|
|
141
|
+
try {
|
|
142
|
+
listener({
|
|
143
|
+
guildId: now.guild.id,
|
|
144
|
+
userId: now.id,
|
|
145
|
+
channelId: now.channelId ?? undefined,
|
|
146
|
+
member: memberOfState(now),
|
|
147
|
+
});
|
|
148
|
+
} catch (error) {
|
|
149
|
+
logger.error({ err: error }, "voice state handler failed");
|
|
150
|
+
}
|
|
151
|
+
});
|
|
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
|
+
},
|
|
165
|
+
async prepare() {
|
|
166
|
+
await loaded();
|
|
167
|
+
},
|
|
168
|
+
async connect({ guildId, channelId }) {
|
|
169
|
+
const guild = client.guilds.cache.get(guildId);
|
|
170
|
+
if (!guild) throw new Error(`the bot is not in the guild ${guildId}`);
|
|
171
|
+
const { lib, decoder } = await loaded();
|
|
172
|
+
return openVoiceLink(lib, {
|
|
173
|
+
guildId,
|
|
174
|
+
channelId,
|
|
175
|
+
adapterCreator: guild.voiceAdapterCreator,
|
|
176
|
+
decoder,
|
|
177
|
+
logger,
|
|
178
|
+
...(options.clock ? { clock: options.clock } : {}),
|
|
179
|
+
deafened: () =>
|
|
180
|
+
guild.voiceStates.cache.get(client.user?.id ?? "")?.serverDeaf ===
|
|
181
|
+
true,
|
|
182
|
+
});
|
|
183
|
+
},
|
|
184
|
+
};
|
|
185
|
+
}
|