pi-roundtable 0.48.0 → 0.49.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -5,6 +5,21 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
5
5
 
6
6
  ## [Unreleased]
7
7
 
8
+ ## [0.49.0] - 2026-11-16
9
+
10
+ ### Added
11
+
12
+ - `ChannelContextOptions.starter` (also `discord.channelContext.starter`, default false): in a thread, the context always includes the thread's opening message, a forum post's first message or the message a text channel's thread started from, even when it lies outside the fetched window. It comes first, outside `keep`, follows the same filters (`authors`, empty text, own posts, messages handed over before) and is dropped silently when the thread has none or Discord will not return it.
13
+
14
+ ## [0.48.1] - 2026-11-16
15
+
16
+ ### Fixed
17
+
18
+ - 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.
19
+ - 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.
20
+ - 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.
21
+ - 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.
22
+
8
23
  ## [0.48.0] - 2026-11-15
9
24
 
10
25
  ### Added
package/README.md CHANGED
@@ -232,6 +232,7 @@ Tune it under `discord.channelContext`, or set `channelContext: false` to turn i
232
232
  | `botMessageChars` | `80` | Where another bot's message is cut |
233
233
  | `peerMessageChars` | `4000` | Where a peer bot's message is cut (a bot `discord.peerBots` lists for the channel) |
234
234
  | `foreignWebhook` | none | `(webhookId) => boolean \| "skip"`: posts through the webhooks it returns true for are read as other people's messages, not the assistant's; `"skip"` drops a webhook's posts as if absent, without ending the window (code only) |
235
+ | `starter` | `false` | In a thread, always include its opening message (a forum post's first message, or the message a text channel's thread started from), even outside the `fetch` window; subject to the same filters, handed over once, outside `keep` |
235
236
  | `attachments` | `{ images: 0, maxBytes: 10 MiB }` | `images`: how many images of the kept messages are fetched for the turn, at most 4 |
236
237
 
237
238
  By default the assistant ignores every other bot. To let separate bots talk, list the ones to answer by user id under `discord.peerBots`:
package/docs/plugins.md CHANGED
@@ -2771,6 +2771,7 @@ It reads Discord, not the host's history, so it survives restarts:
2771
2771
  - Other bots and integrations are kept and marked as bots; the host's owners (the primary owner and every other owner's Discord identities) are marked as owners.
2772
2772
  - Consecutive messages of one author at least `similarity` alike (default 0.8, by their longest common run of text) count as one, the later kept.
2773
2773
  - It keeps the newest `keep` (default 15), oldest first. Mentions read as names, and stickers and files as text with their names and links; by default nothing is downloaded or shown to the model as an image (see `attachments` below). A message is cut at `messageChars` (default 500), another bot's at `botMessageChars` (default 80), and a peer bot's (one `discord.peerBots` lists for the channel, see below) at `peerMessageChars` (default 4000).
2774
+ - With `starter: true` (default false) a thread's opening message is always part of the context, even when it lies outside the `fetch` messages: a forum post's first message (its id is the thread's), or the message a text channel's thread was started from (`fetchStarterMessage`). It comes first, outside `keep` (a context may hold `keep` messages plus the starter), is cut at the same limits as any message by its author, and is not repeated when the window holds it already. It passes the same filters as every other message: `authors` (or `foreignWebhook`) answering `"skip"` or `"end"` for it, an empty text, the assistant's own post, and a message handed over or addressed before drop it, so it comes in the first turn that reads it and not again (the conversation's history carries it from then on); it is also dropped when it is the addressed message itself. It stays even when the assistant's last post lies after it. A channel that is not a thread, a thread without a starter (private, or its starter deleted) and a starter Discord will not return add nothing and never fail the turn (an unexpected refusal is logged at debug). A chat surface of another network that implements `channelContext` reads `starter` itself.
2774
2775
  - It never fails the turn over Discord: a Discord error, such as a channel the bot cannot read, is logged and the turn runs without context.
2775
2776
 
2776
2777
  A plugin may mirror an outside chat into a channel through a webhook of its own, created by the bot, so that the application owns it; by default such a post counts as the assistant's own, which ends the window and is left out, and the people mirrored never reach a turn. `foreignWebhook(webhookId)` changes that for the webhooks it returns true for: a post through one is another author's, kept like another bot's (`bot: true`, `authorName` the post's username, `authorId` the webhook's id) and no longer ends the window, which then ends only at the assistant's own posts: its bot user's and every webhook `foreignWebhook` returns false for, such as an agent's voice. It may also return `"skip"` for a webhook that is neither, such as one the plugin posts its own status notices through: a post through it is dropped from the context and does not end the window, as if it were not in the channel, so notices between two mirrored posts neither appear as someone's words nor cut the window, and they are not counted among the messages delivered. Any answer other than `true` and `"skip"` reads as false. A skipped post is still one of the `fetch` messages read, so it uses the budget the window is chosen from. The host sets it as `discord.channelContext.foreignWebhook` and a call overrides it for that call; being a function, it can be set only in code. `authors(message)` is the same decision for any surface and any message, not only a webhook's: it receives the fetched message (`ChannelContextSource`: `id`, `authorId`, `authorName`, `bot`, `own`, `webhookId?`, `external?`, `attachments?`, `at`, `text`) and answers `"keep"` (another author's, which does not end the window; `foreignWebhook` returning `true`), `"skip"` (dropped as if it were not in the channel, without ending the window; `"skip"` of `foreignWebhook`), `"end"` (the assistant's own, which ends the window and is left out; `foreignWebhook` returning `false` for an application webhook) or `undefined`, which leaves the default: the assistant's own posts end the window and everything else is kept. Where it answers, it wins over `foreignWebhook`; it is a function, so it can be set only in code, as a host default (`discord.channelContext.authors`) or per call. Posts through a webhook that `foreignWebhook` returns true for are merged as near repeats only when the poster's name is the same too, since one webhook carries many people; every other message merges by author alone, as before. An edited message reads as Discord now holds it.
@@ -2782,7 +2783,7 @@ Every returned message has `attachments` (`ChannelContextAttachment`: `name`, `c
2782
2783
  `DISCORD.channelContext` resolves undefined in a direct message, on another surface, when nothing new was said, and when the host's `discord.channelContext` is `false`, which turns it off for the agent server and every claim.
2783
2784
  The configuration's values are the host's defaults, and a call's `options` override them for that call.
2784
2785
  Call it once per answered message: what it returns is remembered as handed over.
2785
- A call's `options` are validated like the configuration (`fetch`, `keep`, `messageChars`, `botMessageChars` and `peerMessageChars` positive integers, `similarity` from 0 to 1, `foreignWebhook` a function of a webhook id returning `true`, `false` or `"skip"`, `authors` a function of a message returning `"keep"`, `"skip"`, `"end"` or `undefined`, `attachments.images` an integer from 0 to 4, `attachments.maxBytes` an integer from 1 to 25 MiB); an invalid one makes the call reject, a programming error, so `keep: 0` is not "none" (skip the call for that).
2786
+ A call's `options` are validated like the configuration (`fetch`, `keep`, `messageChars`, `botMessageChars` and `peerMessageChars` positive integers, `similarity` from 0 to 1, `starter` a boolean, `foreignWebhook` a function of a webhook id returning `true`, `false` or `"skip"`, `authors` a function of a message returning `"keep"`, `"skip"`, `"end"` or `undefined`, `attachments.images` an integer from 0 to 4, `attachments.maxBytes` an integer from 1 to 25 MiB); an invalid one makes the call reject, a programming error, so `keep: 0` is not "none" (skip the call for that).
2786
2787
  It remembers what it handed over and what addressed the assistant, not every message that ran a turn: a post a claim answered some other way, such as a webhook report turn or a steered message, can also come in the context of a later turn if the assistant has not posted since.
2787
2788
 
2788
2789
  What it returns is public channel text, visible to everyone in the channel; it is not private memory, carries no `privateTo`, and goes into the turn's text, so it lives in the conversation's history, not in the system prompt.
@@ -3010,8 +3011,8 @@ await session.leave();
3010
3011
  - **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
3012
  - **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
3013
  - **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.
3014
+ - **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.
3015
+ - **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
3016
  - **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
 
3017
3018
  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 +3168,7 @@ The agent server claims `discord:` keys, and, only on a surface that declares `a
3167
3168
  | `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
3169
  | `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
3170
  | `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 it cannot do with forms, option buttons and checklists, so core adds no line about them | core adds the line whenever the surface does not draw every interactive kind |
3171
+ | `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
3172
  | `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
3173
  | `startTyping(channel)` | Shows a typing indicator until the returned function is called | none is shown |
3173
3174
  | `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 +3314,7 @@ The team writes through the providers too. At start it calls `ensure` for each a
3313
3314
 
3314
3315
  ### Display blocks in a reply
3315
3316
 
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 cannot show forms, option buttons or checklists, to ask in plain text, and that such a block is shown as text for the user to answer by typing; `blockNote: false` leaves it 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
+ 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
3318
  `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
3319
 
3319
3320
  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
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-roundtable",
3
- "version": "0.48.0",
3
+ "version": "0.49.0",
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",
@@ -281,6 +281,7 @@ export function discordPlugin(options: DiscordOptions): RoundtablePlugin {
281
281
  const context = new ChannelContextReader({
282
282
  read: (channelId, before, limit) =>
283
283
  connected.messagesBefore(channelId, before, limit),
284
+ starter: (channelId) => connected.threadStarter(channelId),
284
285
  owners: () => owners.ids(),
285
286
  ...(peers
286
287
  ? {
@@ -191,6 +191,7 @@ const channelContextShape = shape({
191
191
  messageChars: optional(integer(1, 4000)),
192
192
  botMessageChars: optional(integer(1, 4000)),
193
193
  peerMessageChars: optional(integer(1, 4000)),
194
+ starter: optional(bool),
194
195
  foreignWebhook: optional(
195
196
  guarded(
196
197
  "a function of a webhook id",
@@ -56,6 +56,22 @@ export interface ChannelContextOptions {
56
56
  authors?: (
57
57
  message: ChannelContextSource,
58
58
  ) => ChannelContextVerdict | undefined;
59
+ /**
60
+ * Whether a thread's opening message is always part of the context, even when it lies outside
61
+ * the `fetch` messages read; default false. In a forum post the opening message is the post's
62
+ * first message (its id is the thread's); in a text channel's thread it is the message the
63
+ * thread was started from. A thread that has none (a private thread, a deleted starter) or one
64
+ * Discord cannot return adds nothing, and never fails the turn; so does any channel that is not
65
+ * a thread. The starter is subject to every filter of the other messages: `authors` (or
66
+ * `foreignWebhook`) saying `"skip"` or `"end"` for it drops it, as do an empty text, the
67
+ * assistant's own post and a message handed over (or addressed to the assistant) before, so it
68
+ * comes in the first turn's context and not again. It is also dropped when it is the addressed
69
+ * message itself. It comes first, oldest first, outside `keep` (a context may hold `keep` plus
70
+ * the starter), is cut at the same limits as another message by its author, and never merges as
71
+ * a near repeat; when the window holds it already it is not repeated, and it stays even when
72
+ * the assistant's last post lies after it.
73
+ */
74
+ starter?: boolean;
59
75
  /** Which attachments of the kept messages are fetched for the turn; none by default. */
60
76
  attachments?: ChannelContextAttachmentOptions;
61
77
  }
@@ -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 it cannot show forms, option buttons or checklists (see `blockNote`).
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 it cannot do with forms, option
161
- * buttons and checklists, so core adds no line about them. Absent = core adds one to the
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
  /**
@@ -0,0 +1,105 @@
1
+ import type {
2
+ ChannelContextAttachmentOptions,
3
+ ChannelContextOptions,
4
+ } from "../contract/channel-context.ts";
5
+ import { MAX_TURN_IMAGES } from "../domain/attachment.ts";
6
+
7
+ /** The most bytes one image may be: the core's limit for any attachment. */
8
+ const MAX_IMAGE_BYTES = 25 * 1024 * 1024;
9
+
10
+ /** The options with every default filled in, the attachments' too. */
11
+ export type ChannelContextSettings = Required<
12
+ Omit<ChannelContextOptions, "attachments">
13
+ > & { attachments: Required<ChannelContextAttachmentOptions> };
14
+
15
+ /** The defaults of `ChannelContextOptions`. */
16
+ export const CHANNEL_CONTEXT_DEFAULTS: Readonly<
17
+ Omit<Required<ChannelContextOptions>, "attachments"> & {
18
+ attachments: Readonly<Required<ChannelContextAttachmentOptions>>;
19
+ }
20
+ > = Object.freeze({
21
+ fetch: 50,
22
+ keep: 15,
23
+ similarity: 0.8,
24
+ messageChars: 500,
25
+ botMessageChars: 80,
26
+ peerMessageChars: 4_000,
27
+ foreignWebhook: () => false,
28
+ authors: () => undefined,
29
+ starter: false,
30
+ attachments: Object.freeze({ images: 0, maxBytes: 10 * 1024 * 1024 }),
31
+ });
32
+
33
+ /** The host's options, then the call's, over the defaults; the attachments' members merge one by one. */
34
+ export function resolvedSettings(
35
+ host: ChannelContextOptions,
36
+ call: ChannelContextOptions,
37
+ ): ChannelContextSettings {
38
+ const merged = {
39
+ ...CHANNEL_CONTEXT_DEFAULTS,
40
+ ...defined(host),
41
+ ...defined(call),
42
+ };
43
+ return {
44
+ ...merged,
45
+ attachments: {
46
+ ...CHANNEL_CONTEXT_DEFAULTS.attachments,
47
+ ...defined(host.attachments ?? {}),
48
+ ...defined(call.attachments ?? {}),
49
+ } as Required<ChannelContextAttachmentOptions>,
50
+ };
51
+ }
52
+
53
+ /** Throws on a value outside what the configuration accepts: a programming error of the caller. */
54
+ export function assertChannelContextSettings(
55
+ settings: ChannelContextSettings,
56
+ ): void {
57
+ const {
58
+ fetch,
59
+ keep,
60
+ similarity,
61
+ messageChars,
62
+ botMessageChars,
63
+ peerMessageChars,
64
+ } = settings;
65
+ const { images, maxBytes } = settings.attachments;
66
+ const positive = {
67
+ fetch,
68
+ keep,
69
+ messageChars,
70
+ botMessageChars,
71
+ peerMessageChars,
72
+ };
73
+ for (const [name, value] of Object.entries(positive))
74
+ if (!Number.isInteger(value) || value < 1)
75
+ throw new RangeError(
76
+ `channel context option ${name} must be a positive integer, got ${value}`,
77
+ );
78
+ if (!(similarity >= 0 && similarity <= 1))
79
+ throw new RangeError(
80
+ `channel context option similarity must be between 0 and 1, got ${similarity}`,
81
+ );
82
+ if (typeof settings.foreignWebhook !== "function")
83
+ throw new TypeError(
84
+ "channel context option foreignWebhook must be a function",
85
+ );
86
+ if (typeof settings.authors !== "function")
87
+ throw new TypeError("channel context option authors must be a function");
88
+ if (typeof settings.starter !== "boolean")
89
+ throw new TypeError("channel context option starter must be a boolean");
90
+ if (!Number.isInteger(images) || images < 0 || images > MAX_TURN_IMAGES)
91
+ throw new RangeError(
92
+ `channel context option attachments.images must be an integer from 0 to ${MAX_TURN_IMAGES}, got ${images}`,
93
+ );
94
+ if (!Number.isInteger(maxBytes) || maxBytes < 1 || maxBytes > MAX_IMAGE_BYTES)
95
+ throw new RangeError(
96
+ `channel context option attachments.maxBytes must be an integer from 1 to ${MAX_IMAGE_BYTES}, got ${maxBytes}`,
97
+ );
98
+ }
99
+
100
+ /** The options that were given: a key set to undefined is the same as a missing one. */
101
+ function defined<T extends object>(options: T): Partial<T> {
102
+ return Object.fromEntries(
103
+ Object.entries(options).filter(([, value]) => value !== undefined),
104
+ ) as Partial<T>;
105
+ }
@@ -1,7 +1,6 @@
1
1
  import type { Message } from "discord.js";
2
2
  import {
3
3
  type ChannelContext,
4
- type ChannelContextAttachmentOptions,
5
4
  type ChannelContextMessage,
6
5
  type ChannelContextOptions,
7
6
  type ChannelContextSource,
@@ -11,99 +10,21 @@ import {
11
10
  } from "../contract/channel-context.ts";
12
11
  import type { InboundMessage } from "../contract/channels.ts";
13
12
  import { parseChannelKey } from "../contract/surface.ts";
14
- import { MAX_TURN_IMAGES } from "../domain/attachment.ts";
15
13
  import type { Logger } from "../kernel/log.ts";
14
+ import {
15
+ assertChannelContextSettings,
16
+ CHANNEL_CONTEXT_DEFAULTS,
17
+ type ChannelContextSettings,
18
+ resolvedSettings,
19
+ } from "./channel-context-settings.ts";
16
20
  import { contextImages, type SkippedImage } from "./context-images.ts";
17
21
  import { embedText } from "./embed-text.ts";
18
22
  import type { BotIdentity } from "./inbound-message.ts";
19
23
 
20
- /** The most bytes one image may be: the core's limit for any attachment. */
21
- const MAX_IMAGE_BYTES = 25 * 1024 * 1024;
22
-
23
- /** The options with every default filled in, the attachments' too. */
24
- export type ChannelContextSettings = Required<
25
- Omit<ChannelContextOptions, "attachments">
26
- > & { attachments: Required<ChannelContextAttachmentOptions> };
27
-
28
- /** The defaults of `ChannelContextOptions`. */
29
- export const CHANNEL_CONTEXT_DEFAULTS: Readonly<
30
- Omit<Required<ChannelContextOptions>, "attachments"> & {
31
- attachments: Readonly<Required<ChannelContextAttachmentOptions>>;
32
- }
33
- > = Object.freeze({
34
- fetch: 50,
35
- keep: 15,
36
- similarity: 0.8,
37
- messageChars: 500,
38
- botMessageChars: 80,
39
- peerMessageChars: 4_000,
40
- foreignWebhook: () => false,
41
- authors: () => undefined,
42
- attachments: Object.freeze({ images: 0, maxBytes: 10 * 1024 * 1024 }),
43
- });
44
-
45
- /** The host's options, then the call's, over the defaults; the attachments' members merge one by one. */
46
- function resolvedSettings(
47
- host: ChannelContextOptions,
48
- call: ChannelContextOptions,
49
- ): ChannelContextSettings {
50
- const merged = {
51
- ...CHANNEL_CONTEXT_DEFAULTS,
52
- ...defined(host),
53
- ...defined(call),
54
- };
55
- return {
56
- ...merged,
57
- attachments: {
58
- ...CHANNEL_CONTEXT_DEFAULTS.attachments,
59
- ...defined(host.attachments ?? {}),
60
- ...defined(call.attachments ?? {}),
61
- } as Required<ChannelContextAttachmentOptions>,
62
- };
63
- }
64
-
65
- /** Throws on a value outside what the configuration accepts: a programming error of the caller. */
66
- function assertChannelContextSettings(settings: ChannelContextSettings): void {
67
- const {
68
- fetch,
69
- keep,
70
- similarity,
71
- messageChars,
72
- botMessageChars,
73
- peerMessageChars,
74
- } = settings;
75
- const { images, maxBytes } = settings.attachments;
76
- const positive = {
77
- fetch,
78
- keep,
79
- messageChars,
80
- botMessageChars,
81
- peerMessageChars,
82
- };
83
- for (const [name, value] of Object.entries(positive))
84
- if (!Number.isInteger(value) || value < 1)
85
- throw new RangeError(
86
- `channel context option ${name} must be a positive integer, got ${value}`,
87
- );
88
- if (!(similarity >= 0 && similarity <= 1))
89
- throw new RangeError(
90
- `channel context option similarity must be between 0 and 1, got ${similarity}`,
91
- );
92
- if (typeof settings.foreignWebhook !== "function")
93
- throw new TypeError(
94
- "channel context option foreignWebhook must be a function",
95
- );
96
- if (typeof settings.authors !== "function")
97
- throw new TypeError("channel context option authors must be a function");
98
- if (!Number.isInteger(images) || images < 0 || images > MAX_TURN_IMAGES)
99
- throw new RangeError(
100
- `channel context option attachments.images must be an integer from 0 to ${MAX_TURN_IMAGES}, got ${images}`,
101
- );
102
- if (!Number.isInteger(maxBytes) || maxBytes < 1 || maxBytes > MAX_IMAGE_BYTES)
103
- throw new RangeError(
104
- `channel context option attachments.maxBytes must be an integer from 1 to ${MAX_IMAGE_BYTES}, got ${maxBytes}`,
105
- );
106
- }
24
+ export {
25
+ CHANNEL_CONTEXT_DEFAULTS,
26
+ type ChannelContextSettings,
27
+ } from "./channel-context-settings.ts";
107
28
 
108
29
  /** What channel context reads of one fetched message. */
109
30
  export type ContextSourceMessage = ChannelContextSource;
@@ -111,13 +32,6 @@ export type ContextSourceMessage = ChannelContextSource;
111
32
  /** A file attached to a fetched message, as Discord describes it. */
112
33
  export type ContextSourceAttachment = ChannelContextSourceAttachment;
113
34
 
114
- /** The options that were given: a key set to undefined is the same as a missing one. */
115
- function defined<T extends object>(options: T): Partial<T> {
116
- return Object.fromEntries(
117
- Object.entries(options).filter(([, value]) => value !== undefined),
118
- ) as Partial<T>;
119
- }
120
-
121
35
  function attachmentLabel(contentType: string | null | undefined): string {
122
36
  const type = contentType ?? "";
123
37
  if (type.startsWith("image/")) return "image";
@@ -233,10 +147,20 @@ export interface ChannelContextSelection {
233
147
  owners: readonly string[];
234
148
  /** Whether a bot author is a peer the host talks with here, cut at `peerMessageChars`; without it none is. */
235
149
  peer?: (authorId: string) => boolean;
150
+ /**
151
+ * The thread's opening message when `ChannelContextOptions.starter` asked for it: it comes first,
152
+ * outside `keep`, whether or not the fetched window holds it, unless a filter drops it (the
153
+ * `authors` verdict, the assistant's own post, an empty text, a message delivered before).
154
+ */
155
+ starter?: ContextSourceMessage;
236
156
  /** What the selection reads of the settings; without `foreignWebhook` every webhook of the application is the assistant's. */
237
157
  settings: Omit<
238
158
  ChannelContextSettings,
239
- "foreignWebhook" | "authors" | "attachments" | "peerMessageChars"
159
+ | "foreignWebhook"
160
+ | "authors"
161
+ | "attachments"
162
+ | "peerMessageChars"
163
+ | "starter"
240
164
  > &
241
165
  Partial<
242
166
  Pick<
@@ -268,7 +192,7 @@ export function selectChannelContext(
268
192
  fetched: readonly ContextSourceMessage[],
269
193
  selection: ChannelContextSelection,
270
194
  ): { messages: ChannelContextMessage[]; window: string[] } {
271
- const { seen, owners, settings } = selection;
195
+ const { seen, owners, settings, starter } = selection;
272
196
  // `authors` says whose a message is; without an answer, a webhook of the application that the
273
197
  // host calls foreign (`foreignWebhook`) speaks for other people, one it calls "skip" speaks for
274
198
  // no one, and the rest is the assistant's when it posted it. A skipped post is not in the channel
@@ -295,21 +219,33 @@ export function selectChannelContext(
295
219
  message.webhookId !== undefined && verdicts.get(message.id) === "keep";
296
220
  const assistants = (message: ContextSourceMessage) =>
297
221
  verdicts.get(message.id) === "end";
222
+ // The starter stands apart from the window: the window never carries it, so it neither competes for `keep` nor merges.
223
+ const opening =
224
+ starter &&
225
+ !seen.has(starter.id) &&
226
+ starter.text !== "" &&
227
+ verdict(starter) === "keep"
228
+ ? [{ ...starter, text: cut(starter.text, limitOf(starter, selection)) }]
229
+ : [];
298
230
  const lastOwn = ordered.findLastIndex(assistants);
299
231
  const window = ordered.slice(lastOwn + 1);
300
232
  // Cut before comparing: the comparison is quadratic in the text lengths.
301
233
  const fresh = window
302
234
  .filter(
303
235
  (message) =>
304
- !assistants(message) && !seen.has(message.id) && message.text !== "",
236
+ message.id !== starter?.id &&
237
+ !assistants(message) &&
238
+ !seen.has(message.id) &&
239
+ message.text !== "",
305
240
  )
306
241
  .map((message) => ({
307
242
  ...message,
308
243
  text: cut(message.text, limitOf(message, selection)),
309
244
  }));
310
- const kept = merged(fresh, settings.similarity, foreign).slice(
311
- -settings.keep,
312
- );
245
+ const kept = [
246
+ ...opening,
247
+ ...merged(fresh, settings.similarity, foreign).slice(-settings.keep),
248
+ ];
313
249
  return {
314
250
  window: window.map((message) => message.id),
315
251
  messages: kept.map((message) => ({
@@ -358,6 +294,12 @@ export interface ChannelContextReaderOptions {
358
294
  ): Promise<readonly ContextSourceMessage[] | undefined>;
359
295
  /** The owners' Discord user ids. */
360
296
  owners(): Promise<readonly string[]>;
297
+ /**
298
+ * A thread's opening message, for `ChannelContextOptions.starter`: undefined for a channel that
299
+ * is not a thread, and for a thread with none (a private thread, or a post whose opening message
300
+ * was deleted). May reject; the reader then goes without it.
301
+ */
302
+ starter?(channelId: string): Promise<ContextSourceMessage | undefined>;
361
303
  /** Whether a bot is a peer the host lists for the addressed message's channel (`discord.peerBots`); without it no bot is. */
362
304
  peer?: (authorId: string, message: InboundMessage) => boolean;
363
305
  /** The host's settings; `false` turns channel context off for every claim. */
@@ -406,15 +348,20 @@ export class ChannelContextReader {
406
348
  if (!fetched) return undefined;
407
349
  const owners = await this.#owners();
408
350
  const peer = this.#options.peer;
351
+ const starter = settings.starter
352
+ ? await this.#starter(channelId, message.messageId)
353
+ : undefined;
409
354
  const { messages, window } = selectChannelContext(fetched, {
410
355
  seen,
411
356
  owners,
412
357
  settings,
358
+ ...(starter ? { starter } : {}),
413
359
  ...(peer
414
360
  ? { peer: (authorId: string) => peer(authorId, message) }
415
361
  : {}),
416
362
  });
417
363
  for (const id of window) seen.add(id);
364
+ for (const { id } of messages) seen.add(id);
418
365
  this.#trim(seen);
419
366
  if (messages.length === 0) return undefined;
420
367
  const { images, skipped } = await this.#images(messages, settings);
@@ -454,6 +401,23 @@ export class ChannelContextReader {
454
401
  });
455
402
  }
456
403
 
404
+ /** The thread's opening message; none for a thread without one, the addressed message itself, or when it cannot be read (logged at debug). */
405
+ async #starter(
406
+ channelId: string,
407
+ addressed: string,
408
+ ): Promise<ContextSourceMessage | undefined> {
409
+ try {
410
+ const found = await this.#options.starter?.(channelId);
411
+ return found?.id === addressed ? undefined : found;
412
+ } catch (error) {
413
+ this.#options.logger.debug(
414
+ { channelId, err: error },
415
+ "thread starter not read; channel context goes without it",
416
+ );
417
+ return undefined;
418
+ }
419
+ }
420
+
457
421
  /** The owners' user ids; none, logged, when they cannot be read, since marking them is not worth failing for. */
458
422
  async #owners(): Promise<readonly string[]> {
459
423
  try {
@@ -0,0 +1,60 @@
1
+ import type { Client } from "discord.js";
2
+ import {
3
+ type ContextSourceMessage,
4
+ contextSourceOf,
5
+ } from "./channel-context.ts";
6
+
7
+ /** The identity channel context tells the assistant's posts by. */
8
+ function identityOf(client: Client<true>) {
9
+ return { botId: client.user.id, applicationId: client.application.id };
10
+ }
11
+
12
+ /**
13
+ * A server text channel's messages before one, as channel context reads them; undefined for a
14
+ * direct message or a channel that holds no messages. Throws while the connection is not ready or
15
+ * when Discord refuses, such as for a channel the bot cannot read.
16
+ */
17
+ export async function readMessagesBefore(
18
+ client: Client,
19
+ channelId: string,
20
+ before: string,
21
+ limit: number,
22
+ ): Promise<ContextSourceMessage[] | undefined> {
23
+ if (!client.isReady()) throw new Error("Discord is not connected");
24
+ const channel = await client.channels.fetch(channelId);
25
+ if (!channel?.isTextBased() || channel.isDMBased()) return undefined;
26
+ const fetched = await channel.messages.fetch({ before, limit });
27
+ const self = identityOf(client);
28
+ return [...fetched.values()].map((message) => contextSourceOf(message, self));
29
+ }
30
+
31
+ /**
32
+ * The opening message of a thread: a forum post's first message (its id is the thread's) or the
33
+ * message in the parent channel a text channel's thread was started from; undefined for a channel
34
+ * that is not a thread, and for a thread without one (a private thread, a deleted starter).
35
+ * Throws while the connection is not ready or when Discord refuses for another reason.
36
+ */
37
+ export async function readThreadStarter(
38
+ client: Client,
39
+ channelId: string,
40
+ ): Promise<ContextSourceMessage | undefined> {
41
+ if (!client.isReady()) throw new Error("Discord is not connected");
42
+ const channel = await client.channels.fetch(channelId);
43
+ if (!channel?.isThread()) return undefined;
44
+ let starter: Awaited<ReturnType<typeof channel.fetchStarterMessage>>;
45
+ try {
46
+ starter = await channel.fetchStarterMessage();
47
+ } catch (error) {
48
+ // Unknown Message (10008): the starter was deleted; a thread made without a message has no
49
+ // starter, which discord.js reports the same way.
50
+ if (isMissing(error)) return undefined;
51
+ throw error;
52
+ }
53
+ return starter ? contextSourceOf(starter, identityOf(client)) : undefined;
54
+ }
55
+
56
+ /** Discord's "Unknown Message" (10008) or "Unknown Channel" (10003): there is nothing to read. */
57
+ function isMissing(error: unknown): boolean {
58
+ const code = (error as { code?: unknown } | null)?.code;
59
+ return code === 10008 || code === 10003;
60
+ }