pi-roundtable 0.48.1 → 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,12 @@ 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
+
8
14
  ## [0.48.1] - 2026-11-16
9
15
 
10
16
  ### Fixed
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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-roundtable",
3
- "version": "0.48.1",
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
  }
@@ -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
+ }
@@ -36,15 +36,13 @@ import type { MemberJoinedEvent } from "../plugin-api/event-types.ts";
36
36
  import { chunksFor } from "../presentation/reply-chunks.ts";
37
37
  import { threadsOfHost } from "../threads/host-threads.ts";
38
38
  import { DiscordAgentChannels, DiscordDashboard } from "./agent-discord.ts";
39
- import {
40
- type ContextSourceMessage,
41
- contextSourceOf,
42
- } from "./channel-context.ts";
39
+ import type { ContextSourceMessage } from "./channel-context.ts";
43
40
  import { discordChannelExecutor } from "./channel-executor.ts";
44
41
  import { channelInfoOf } from "./channel-info.ts";
45
42
  import type { ChannelExecutor } from "./channel-operations.ts";
46
43
  import type { ComposedCommands } from "./compose-commands.ts";
47
44
  import type { ChannelInfo, DiscordConnection } from "./connection.ts";
45
+ import { readMessagesBefore, readThreadStarter } from "./context-reading.ts";
48
46
  import { DiscordThreadHost } from "./dispatch-thread-host.ts";
49
47
  import { DISCORD_FORMATTING, pickFormatting } from "./formatting.ts";
50
48
  import { DEFAULT_FRESH_MARKER, postFreshMarker } from "./fresh-marker.ts";
@@ -202,22 +200,21 @@ export class DiscordSurface
202
200
  * direct message or a channel that holds no messages. Throws while the connection is not ready
203
201
  * or when Discord refuses, such as for a channel the bot cannot read.
204
202
  */
205
- async messagesBefore(
203
+ messagesBefore(
206
204
  channelId: string,
207
205
  before: string,
208
206
  limit: number,
209
207
  ): Promise<ContextSourceMessage[] | undefined> {
210
- if (!this.#client.isReady()) throw new Error("Discord is not connected");
211
- const channel = await this.#client.channels.fetch(channelId);
212
- if (!channel?.isTextBased() || channel.isDMBased()) return undefined;
213
- const fetched = await channel.messages.fetch({ before, limit });
214
- const self = {
215
- botId: this.#client.user.id,
216
- applicationId: this.#client.application.id,
217
- };
218
- return [...fetched.values()].map((message) =>
219
- contextSourceOf(message, self),
220
- );
208
+ return readMessagesBefore(this.#client, channelId, before, limit);
209
+ }
210
+
211
+ /**
212
+ * A thread's opening message, as channel context reads it; undefined for a channel that is not
213
+ * a thread and for a thread without one. Throws while the connection is not ready or when
214
+ * Discord refuses.
215
+ */
216
+ threadStarter(channelId: string): Promise<ContextSourceMessage | undefined> {
217
+ return readThreadStarter(this.#client, channelId);
221
218
  }
222
219
 
223
220
  /** Reports deleted server channels by id; register before start. */