pi-roundtable 0.51.2 → 0.52.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 CHANGED
@@ -5,6 +5,28 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
5
5
 
6
6
  ## [Unreleased]
7
7
 
8
+ ## [0.52.1] - 2026-11-17
9
+
10
+ ### Fixed
11
+
12
+ - `discord.catchUp`: a message addressed to the bot that the old process does not run as it shuts down, whether it arrives during the shutdown or waits behind a running turn, is no longer refused with "please send this again". It is recorded as left in the journal (new migration `discord-inbound-journal-left`), and the channel is told once that the message will be answered after the restart. The next process answers it whatever was posted in the channel since, if it starts within a day. Restart notices are recorded, so catch-up does not take one for an answer. A process that loses a claim to another tries once more two seconds later, and delivers what it then takes marked `caughtUp`. A message still waiting behind a turn when the drain ends is now refused before the services stop, so its channel is told (and, with catch-up, it is left for the next process) instead of nothing. A chat surface takes such a message through the new optional `ChatSurface.refuseStopping`.
13
+ - `discord.catchUp`: when the member fetch for a caught-up message fails for any reason other than the author having left (Discord code 10007), catch-up skips the message without recording it, so a later restart can retry it. Before this fix, the message was answered without the author's roles and was never retried.
14
+ - `discord.catchUp`: a message the live connection delivered without a record, because the database was down at startup, is not caught up a second time by the same process.
15
+ - `discord.catchUp`: the inbound journal is pruned to 30 days every six hours while the host runs, not only at restart. The docs now say what happens when `catchUp` is turned off later.
16
+ - `discord.catchUp`: a mention that has a thread started from it, or a reaction from the bot, counts as answered. Before this fix, the first restart after catch-up was enabled re-delivered mentions answered in a thread, and the bot then posted a false "could not open a thread" notice.
17
+ - `discord.catchUp`: caught-up messages reach routing before the newer live messages in the same channel. A live message waits until catch-up has listed the channels it may read (one database query). In one of those channels, it also waits until catch-up is done.
18
+
19
+ ## [0.52.0] - 2026-11-17
20
+
21
+ ### Added
22
+
23
+ - `discord.catchUp: { windowMinutes?, maxMessages? }` (off by default) answers, once the connection is ready after a restart, the messages addressed to the bot that came while no process was listening, which Discord does not deliver again: a person's mention, reply to the bot, or direct message from the last `windowMinutes` (default 10) that the bot did not answer, the newest `maxMessages` (default 20), oldest first, through the usual claims and gates. Each addressed message is recorded in the new `discord_inbound_journal` table before routing hears it, so neither a second restart nor the live gateway answers it again.
24
+ - `InboundMessage.caughtUp` is set on a message delivered that way, so a claim may say its answer comes late.
25
+
26
+ ### Changed
27
+
28
+ - The Discord surface hands a channel's messages to routing in the order they arrived, even when one takes longer to read, such as a reply whose referenced message is fetched or, with `discord.catchUp`, the record written before it is delivered; a slow read holds up the channel's later messages until it is done. A message that cannot be read is logged and skipped as before.
29
+
8
30
  ## [0.51.2] - 2026-11-17
9
31
 
10
32
  ### Fixed
package/docs/plugins.md CHANGED
@@ -2487,6 +2487,8 @@ The router records the author, such as linking them at their first contact, only
2487
2487
  One exception: an author already linked whom the access rules now refuse is recorded as seen at no tier when the message is resolved, whether or not a claim takes it, at most once every few minutes, so their background turns stop with them.
2488
2488
  When that record finds the author someone else than the claim admitted, such as linked to another principal meanwhile or refused now, or cannot be made, the router drops the message: a turn admission's optional `dropped()` is called instead of `run`, so the claim frees what it holds for it, and a background admission's `unanswered` hears it skipped.
2489
2489
 
2490
+ A message the Discord surface delivers late, after a restart (see [`discord.catchUp`](#missed-messages-after-a-restart-discordcatchup)), carries `caughtUp: true` and is otherwise routed like any other.
2491
+
2490
2492
  A claim may also hear that a message it owns changed, through `onMessageDeleted(channel, messageId)` and `onMessageEdited(message)`, which a surface reports with the second argument of its `start` (`{ deleted, edited }`, a `SurfaceMessageEvents`). Discord reports both, including for a message the bot had not cached; a surface that cannot tell never calls them. The router delivers each as it comes, to the claim that owns the channel and no other, outside the channel's queue, so a running turn does not hold it up; a throw or rejection is logged and never fails the router. A delete carries only ids, and Discord's delete event does not say who wrote the message, so the claim hears the deletion of the bot's own messages too and ignores an id it does not know. An edit carries the message as it reads now, as an `InboundMessage`, without `speaker` or `peerBot` because nobody is resolved or admitted for it; the bot's own edits are not reported, nor is a change that leaves the text, the embeds and the attachments as they were, such as a pin. A bulk delete is reported as one delete per message.
2491
2493
 
2492
2494
  A message sent while a turn runs is first offered to that turn (`busy.steer`); one the turn does not take waits in the channel's queue with `QUEUED_MARK`, and until its own turn starts the conversation port can list, cancel and edit it: `queued(channel)` returns its waiting messages oldest first (`messageId`, the author's `principalId`, the `text` its turn will use, `queuedAt`); `cancelQueued(channel, messageId, { principalId })` makes its turn never run, calling the admission's `dropped` and removing the mark; `editQueued(channel, messageId, { principalId }, text)` admits the message again with the new text through the claim's `admit`, drops the old admission, and the turn runs on the new one. Only the message's author may (a different principal gets `forbidden`, and a message with no resolved author can be changed by no one). A message whose turn has started, was steered into the running turn, or was cancelled is `unknown`; an edit the claim would no longer admit is `refused` and the old text stays. The decision is made in one synchronous step, so a cancel or an edit and the start of the turn never both win. The surface's own copy of the message is the caller's to change. When a surface reports a queued message deleted or edited (`onMessageDeleted`, `onMessageEdited` above), the router cancels it or changes its text itself, without the author check since the surface says it happened: that is how deleting a queued Discord message cancels it. The three methods are optional on `ConversationPort`, as `messageDeleted` is.
@@ -2927,6 +2929,47 @@ const statusClaim: ChannelClaim = {
2927
2929
  A reply that contains `<@id>` of a peer pings it, since replies allow user mentions; without that the peer's `mentionsBot` stays false.
2928
2930
  In a test, `testPlugin({ peerBots: { allow: [...] } })` puts the same list on the test router.
2929
2931
 
2932
+ ### Missed messages after a restart: `discord.catchUp`
2933
+
2934
+ Discord does not deliver again what was posted while no process held the connection, so a mention sent during a restart or a deploy would go unanswered.
2935
+ A host that sets `discord.catchUp` (or passes `catchUp` to `discordPlugin`) answers those messages once the connection is ready again:
2936
+
2937
+ ```ts
2938
+ discord: { token: process.env.DISCORD_TOKEN ?? "", catchUp: { windowMinutes: 10, maxMessages: 20 } },
2939
+ ```
2940
+
2941
+ It is off by default and needs the host's database.
2942
+ Once every service has started, the Discord plugin reads the channels where something was posted within `windowMinutes` (default 10, at most 1440) before the connection became ready.
2943
+ It reads the server text channels, live threads and forum posts the bot can read, which it picks from the client's cache without a request, and the direct-message channels that brought the bot a message in the last 30 days.
2944
+ It looks into at most the 25 direct-message channels that brought a message most recently, one request each, and reads at most 50 channels, one page of 100 messages each, before the ready time; Discord's rate limits pace the requests.
2945
+ A message counts when a person wrote it (not a bot, a webhook or Discord itself) to the bot: a mention, a reply to one of the bot's messages, or a direct message.
2946
+ It is left alone when it is older than the window, when it was already taken in, or when it shows an answer: the bot or one of its own webhooks posted in that channel after it, a thread was started from it (by anyone, as the bot answers a mention in a thread), or the bot reacted to it.
2947
+ The thread and the reaction matter at the first restart after `catchUp` is turned on, when nothing was recorded yet; a mention a person started a thread from is therefore not answered, since one missed answer is preferred to two.
2948
+ Of what is left, the newest `maxMessages` (default 20, at most 100) go to routing oldest first.
2949
+ They go once every service has started; a live message that came after the connection became ready waits until catch-up has listed the channels it may read (one database query, before any request), and, in one of those, until catch-up is done, so the caught-up messages of a channel reach routing before its newer live ones.
2950
+ Each one passes through the same claims, identity resolution and gates as a live message, with `InboundMessage.caughtUp` set, so a claim may say its answer comes late, for example that the assistant just restarted.
2951
+ The log carries only counts and ids, never text.
2952
+
2953
+ Nothing is answered twice.
2954
+ With catch-up on, every addressed message is recorded in the `discord_inbound_journal` table before routing hears it: by the live connection as it arrives, or by catch-up before it hands the message on.
2955
+ Whichever records a message first delivers it; the other drops it, so a second restart, or a message the gateway delivers while catch-up runs, is not answered again.
2956
+ A message that catch-up cannot record is skipped, and a crash after the record but before the turn leaves it unanswered: one missed answer is preferred to two.
2957
+ The live connection still delivers a message it cannot record, such as while the database is down, and logs it; catch-up in the same process leaves it alone, so only a later restart that finds no answer to it in its channel could answer it again.
2958
+ Catch-up reads the author of a server message as a member first; when that fails for any reason but the author having left the server, the message is skipped unrecorded, so a later restart may still answer it with the author's roles.
2959
+ Once the old process begins to shut down it runs no new turn, and an addressed message it has not started, whether it arrives then or already waits behind a running turn, is recorded as left (a `left_at` time in the journal), and its channel is told once that the message will be answered after the restart.
2960
+ The next process answers each message left within the last day first, whatever was posted in its channel since and whatever `windowMinutes`, the page and `maxMessages` say, and takes it from the journal as it does, so it is answered once.
2961
+ A message still waiting behind a turn that outlives the drain is refused, and so left, once the drain ends and before the services stop, within 15 seconds for all of them; this covers turns whose admission has a `busy` mark, as every turn the core's own claims admit does, while a plugin claim's turn without one is refused only when the turn ahead of it ends, which may be after the process has stopped. A message another process already took in is left alone, with no notice.
2962
+ A message that cannot be recorded as left gets the notice to send it again instead.
2963
+ Any other person's message that routing refuses then tells its channel once to send it again, as without catch-up.
2964
+ The Discord surface does this through the optional `ChatSurface.refuseStopping(message)`, which routing calls for a person's message it refuses while the host stops; a surface a plugin contributes may implement it too, and returns true when it told the channel itself, so routing posts no restart notice.
2965
+ Each notice is recorded in the journal, so the next process does not take it for an answer; a notice that cannot be recorded is deleted again, and when catch-up cannot look the notices up it leaves that channel unread rather than guess.
2966
+ A process that finds a message already recorded by another, as when two processes overlap during a deploy, claims it once more two seconds later, apart from the channel's other messages, so one the other leaves as it begins to shut down is still answered, marked `caughtUp` and after the channel's newer messages; one left later than that is answered by the next process to start, not by the one already running.
2967
+ A person who sends the message again anyway gets both answered, the copy live and the original by catch-up, since nothing tells the two apart.
2968
+ Records are kept 30 days: the plugin forgets older ones every six hours while it runs and once catch-up has run.
2969
+ Turning `catchUp` off later leaves the `discord_inbound_journal` table and its rows as they are, with nothing pruning them; turning it on again finds them and prunes them as usual, or a host may drop the table by hand.
2970
+ The first restart after `catchUp` is turned on has no records from before: a message the old process handled with no post in its channel after it, no thread from it and no reaction, such as one answered by a direct message, may be answered again.
2971
+ A first direct message sent during the restart is not found, since Discord does not list a bot's direct-message channels.
2972
+
2930
2973
  ### Reading a file's bytes: `DISCORD.readAttachment`
2931
2974
 
2932
2975
  Channel context and `InboundMessage.attachments` describe files; a plugin whose assistant needs one's content reads it with `DISCORD.readAttachment({ channelId, messageId, attachmentId, maxBytes? })` from `pi-roundtable/discord`.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-roundtable",
3
- "version": "0.51.2",
3
+ "version": "0.52.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",
@@ -19,6 +19,9 @@ import {
19
19
  validReadCap,
20
20
  } from "../discord/attachment-read.ts";
21
21
  import { CardCopies } from "../discord/card-copies.ts";
22
+ import { type CatchUpOptions, catchUpSettings } from "../discord/catch-up.ts";
23
+ import { PgInboundJournal } from "../discord/catch-up-journal.ts";
24
+ import { catchUpWiring } from "../discord/catch-up-service.ts";
22
25
  import { ChannelContextReader } from "../discord/channel-context.ts";
23
26
  import { CommandCollection } from "../discord/command-collection.ts";
24
27
  import type { DiscordConnection } from "../discord/connection.ts";
@@ -184,6 +187,15 @@ export interface DiscordOptions {
184
187
  * cards follow the same choice and `keepDays`, the newest 300, in `intercom-texts.json`.
185
188
  */
186
189
  cardCopies?: { keepDays?: number; keep?: number } | false;
190
+ /**
191
+ * Answers, once the connection is ready again, the messages addressed to the bot (a person's
192
+ * mention, reply to the bot, or direct message) that came while the host was down, as the
193
+ * gateway does not deliver them: those of the last `windowMinutes` (default 10) the bot did not
194
+ * answer, the newest `maxMessages` (default 20), oldest first, each marked
195
+ * `InboundMessage.caughtUp`. Each addressed message is recorded in the database before routing
196
+ * hears it, so none is answered twice. Needs the host's database. Default: off.
197
+ */
198
+ catchUp?: CatchUpOptions;
187
199
  }
188
200
 
189
201
  /** How many agent message cards keep their whole text for the open button, the newest. */
@@ -203,19 +215,45 @@ export function discordPlugin(options: DiscordOptions): RoundtablePlugin {
203
215
  throw new ConfigError(
204
216
  `discord.attachmentRead.maxBytes must be a whole number from 1 to ${ATTACHMENT_READ_LIMIT_BYTES}`,
205
217
  );
218
+ const catchUpWith = options.catchUp && catchUpSettings(options.catchUp);
206
219
  const collection = new CommandCollection();
207
220
  let surface: DiscordSurface | undefined;
208
221
  return {
209
222
  name: "discord",
210
223
  provides: [DISCORD],
224
+ ...(catchUpWith ? { migrations: PgInboundJournal.migrations } : {}),
211
225
  preflight: () => {
212
226
  // The host has applied its environment by now, so the description is in its language.
213
227
  surface?.setCommands(
214
228
  collection.compose(ownerRootCommand(options.rootCommand)),
215
229
  );
216
230
  },
217
- setup: async ({ conversations, services, logger, events, dashboard }) => {
231
+ setup: async ({
232
+ conversations,
233
+ services,
234
+ logger,
235
+ events,
236
+ dashboard,
237
+ database,
238
+ }) => {
218
239
  const identity = services.find(IDENTITY);
240
+ // What came in, recorded only when catch-up is on, so it answers nothing twice.
241
+ const journal = catchUpWith
242
+ ? PgInboundJournal.attach(database())
243
+ : undefined;
244
+ // The journal's gate and the catch-up service, over the surface's client once it connects.
245
+ const caughtUp =
246
+ journal && catchUpWith
247
+ ? catchUpWiring({
248
+ journal,
249
+ settings: catchUpWith,
250
+ logger,
251
+ client: () => connected.client(),
252
+ deliver: (message) => {
253
+ void conversations.handle(message);
254
+ },
255
+ })
256
+ : undefined;
219
257
  // A host that keeps no copy texts on disk drops what an earlier run left.
220
258
  if (options.cardCopies === false)
221
259
  for (const name of ["card-copies.json", "intercom-texts.json"]) {
@@ -270,6 +308,12 @@ export function discordPlugin(options: DiscordOptions): RoundtablePlugin {
270
308
  : { formatting: options.formatting }),
271
309
  ...(options.memberEvents ? { memberEvents: true } : {}),
272
310
  ...(options.voice ? { voice: true } : {}),
311
+ ...(caughtUp
312
+ ? {
313
+ inboundGate: caughtUp.gate,
314
+ refuseStopping: caughtUp.refused,
315
+ }
316
+ : {}),
273
317
  });
274
318
  surface = connected;
275
319
  // Voice sessions over the same client; nothing of the voice packages is loaded before its service starts.
@@ -390,6 +434,7 @@ export function discordPlugin(options: DiscordOptions): RoundtablePlugin {
390
434
  await intercomTexts.stop();
391
435
  },
392
436
  },
437
+ ...(caughtUp ? [caughtUp.service] : []),
393
438
  // Fails the start when the voice packages cannot be loaded; ends every session as the host stops.
394
439
  ...(voice
395
440
  ? [
@@ -125,6 +125,16 @@ export interface DiscordConfig {
125
125
  * 100 MiB) is the most bytes of one file; a larger file is refused as `too-large`.
126
126
  */
127
127
  attachmentRead?: { maxBytes?: number };
128
+ /**
129
+ * Answers, after a restart, the messages addressed to the bot that came while no process was
130
+ * listening, which Discord does not deliver again: a person's mention, reply to the bot, or
131
+ * direct message from the last `windowMinutes` (default 10, at most 1440) before the connection
132
+ * is ready that the bot did not answer, the newest `maxMessages` (default 20, at most 100),
133
+ * oldest first, through the usual claims and gates and marked `InboundMessage.caughtUp`. Each
134
+ * addressed message is recorded in the database as it comes in, so none is answered twice.
135
+ * Left out, nothing missed is answered.
136
+ */
137
+ catchUp?: { windowMinutes?: number; maxMessages?: number };
128
138
  }
129
139
 
130
140
  /** The Discord settings with every default filled in. */
@@ -153,6 +163,8 @@ export interface ResolvedDiscord {
153
163
  attachmentDownload?: NonNullable<DiscordConfig["attachmentDownload"]>;
154
164
  /** As configured: left out unless set, so the default applies. */
155
165
  attachmentRead?: NonNullable<DiscordConfig["attachmentRead"]>;
166
+ /** As configured: left out when off. */
167
+ catchUp?: NonNullable<DiscordConfig["catchUp"]>;
156
168
  }
157
169
 
158
170
  /** The configured Discord settings, defaults filled in; `rootCommand` is the host's slug. */
@@ -195,6 +207,7 @@ export function resolvedDiscord(
195
207
  ...(discord.attachmentRead === undefined
196
208
  ? {}
197
209
  : { attachmentRead: discord.attachmentRead }),
210
+ ...(discord.catchUp === undefined ? {} : { catchUp: discord.catchUp }),
198
211
  };
199
212
  }
200
213
 
@@ -273,6 +286,12 @@ export const discordShape = shape({
273
286
  attachmentRead: optional(
274
287
  shape({ maxBytes: optional(integer(1, 100 * 1024 * 1024)) }),
275
288
  ),
289
+ catchUp: optional(
290
+ shape({
291
+ windowMinutes: optional(integer(1, 1440)),
292
+ maxMessages: optional(integer(1, 100)),
293
+ }),
294
+ ),
276
295
  });
277
296
 
278
297
  /** The adapters `adapters` takes, by the name their factory gives them. */
@@ -122,6 +122,12 @@ export interface InboundMessage {
122
122
  /** The name a webhook posted the referenced message under, such as an agent's. */
123
123
  webhookName?: string;
124
124
  };
125
+ /**
126
+ * Set when the surface delivers the message late, after the host restarted, because it came
127
+ * while no process was listening (Discord's `discord.catchUp`). It is routed like any other; a
128
+ * claim may say the answer is late, such as that the assistant just restarted.
129
+ */
130
+ caughtUp?: true;
125
131
  /** The message the author forwarded with this one; its attachments are in `attachments`. */
126
132
  forwarded?: {
127
133
  text: string;
@@ -179,6 +179,13 @@ export interface ChatSurface {
179
179
  ): Promise<void>;
180
180
  /** Runs when the host stops, after the services started later have stopped. */
181
181
  stop?(): Promise<void>;
182
+ /**
183
+ * A person's message routing does not run because the host is shutting down: the surface may
184
+ * take care of it, for example leave it for the next process to answer, and tell its channel
185
+ * itself. True = it did, and routing posts no restart notice. Absent, false, or a rejection
186
+ * (logged) = routing tells the channel once to send it again.
187
+ */
188
+ refuseStopping?(message: InboundMessage): Promise<boolean>;
182
189
  sendReply(channel: ChannelKey, reply: OutboundReply): Promise<void>;
183
190
  /** Shows a typing indicator until the returned function is called; absent = none shown. */
184
191
  startTyping?(channel: ChannelKey): () => void;
@@ -0,0 +1,207 @@
1
+ import type { InboundMessage } from "../contract/channels.ts";
2
+ import type { Logger } from "../kernel/log.ts";
3
+ import { addressed } from "./catch-up.ts";
4
+ import type { InboundJournal } from "./catch-up-journal.ts";
5
+
6
+ /** Which restart notice a channel is told: that its message is answered after the restart, or that it should be sent again. */
7
+ export type NoticeKind = "later" | "resend";
8
+
9
+ /** A notice posted in a channel. */
10
+ export interface PostedNotice {
11
+ id: string;
12
+ /** Deletes it again. */
13
+ retract(): Promise<void>;
14
+ }
15
+
16
+ /** What the live gateway's journal gate works with. */
17
+ export interface GateOptions {
18
+ journal: InboundJournal;
19
+ logger: Logger;
20
+ /** True once the host shuts down: from then on routing refuses what it hears. */
21
+ draining?: () => boolean;
22
+ /** Posts a restart notice in a channel. */
23
+ notify?: (channelId: string, kind: NoticeKind) => Promise<PostedNotice>;
24
+ /** Waits, once a message is recorded, until it may reach routing after the caught-up messages of its channel. */
25
+ wait?: (channelId: string) => Promise<void>;
26
+ /** The ids of messages delivered without a record, which catch-up in this process leaves alone. */
27
+ unrecorded?: Pick<Set<string>, "add">;
28
+ /**
29
+ * How long a message another process recorded first is given before it is claimed once more,
30
+ * since a process that begins to shut down leaves what it recorded. Default 2000; 0 = never.
31
+ */
32
+ retryMs?: number;
33
+ /** Hands a message the retry claimed to routing; without it there is no retry. */
34
+ redeliver?: (message: InboundMessage) => void;
35
+ }
36
+
37
+ /** The gate: whether a live message reaches routing, and `refused`, for one routing refuses as the host stops. */
38
+ export type JournalGate = ((
39
+ message: InboundMessage,
40
+ botId: string,
41
+ ) => Promise<boolean>) & {
42
+ /** Takes care of a message routing refuses because the host stops; true when it did, so routing posts nothing. */
43
+ refused(message: InboundMessage, botId: string): Promise<boolean>;
44
+ };
45
+
46
+ const DEFAULT_RETRY_MS = 2000;
47
+
48
+ /**
49
+ * Records each addressed message the live gateway delivers before routing hears it, so catch-up
50
+ * after a restart leaves it alone; false for one already recorded, which is not delivered again.
51
+ * A message that cannot be recorded is still delivered, logged, and kept in `unrecorded`.
52
+ * Once the host drains, an addressed message that has not run is recorded as left, and the next
53
+ * process answers it whatever its channel shows since; its channel is told so once. Any other message
54
+ * routing refuses then tells its channel once to send it again. Each notice is recorded, so
55
+ * catch-up does not take it for an answer, and deleted again when it cannot be.
56
+ */
57
+ export function journalGate({
58
+ journal,
59
+ logger,
60
+ draining = () => false,
61
+ notify,
62
+ wait,
63
+ unrecorded,
64
+ retryMs = DEFAULT_RETRY_MS,
65
+ redeliver,
66
+ }: GateOptions): JournalGate {
67
+ const told = { later: new Set<string>(), resend: new Set<string>() };
68
+ const channelOf = (message: InboundMessage) =>
69
+ message.channel.slice("discord:".length);
70
+ const tell = async (
71
+ kind: NoticeKind,
72
+ message: InboundMessage,
73
+ botId: string,
74
+ ) => {
75
+ const channelId = channelOf(message);
76
+ if (!notify || told[kind].has(channelId)) return;
77
+ told[kind].add(channelId);
78
+ let notice: PostedNotice;
79
+ try {
80
+ notice = await notify(channelId, kind);
81
+ } catch (error) {
82
+ logger.warn({ channelId, err: error }, "restart notice not posted");
83
+ return;
84
+ }
85
+ try {
86
+ await journal.claim({
87
+ botId,
88
+ messageId: notice.id,
89
+ channelId,
90
+ direct: message.isDirect,
91
+ });
92
+ } catch (error) {
93
+ // Unrecorded, catch-up would take it for an answer.
94
+ logger.warn(
95
+ { channelId, err: error },
96
+ "restart notice not recorded; deleting it",
97
+ );
98
+ await notice
99
+ .retract()
100
+ .catch((retractError: unknown) =>
101
+ logger.warn(
102
+ { channelId, err: retractError },
103
+ "unrecorded restart notice not deleted",
104
+ ),
105
+ );
106
+ }
107
+ };
108
+ const entry = (message: InboundMessage, botId: string) => ({
109
+ botId,
110
+ messageId: message.messageId,
111
+ channelId: channelOf(message),
112
+ direct: message.isDirect,
113
+ });
114
+ // Left in the journal, the next process answers it whatever its channel shows; unrecorded, the channel is told to send it again.
115
+ const leave = async (
116
+ message: InboundMessage,
117
+ botId: string,
118
+ taken = true,
119
+ ) => {
120
+ const where = {
121
+ channelId: channelOf(message),
122
+ messageId: message.messageId,
123
+ };
124
+ try {
125
+ if (taken) await journal.leave(entry(message, botId));
126
+ else if (!(await journal.leaveNew(entry(message, botId)))) {
127
+ // Another process took it in, and answers it.
128
+ logger.info(
129
+ where,
130
+ "shutting down; another process took this message in",
131
+ );
132
+ return;
133
+ }
134
+ } catch (error) {
135
+ logger.warn(
136
+ { ...where, err: error },
137
+ "could not leave a message for the next process; its channel is told to send it again",
138
+ );
139
+ await tell("resend", message, botId);
140
+ return;
141
+ }
142
+ logger.info(where, "shutting down; the next process answers this message");
143
+ await tell("later", message, botId);
144
+ };
145
+ // Off the channel's chain: a process that begins to stop leaves what it recorded, and this one then takes it.
146
+ const retry = (message: InboundMessage, botId: string) => {
147
+ if (!redeliver || retryMs <= 0) return;
148
+ const timer = setTimeout(async () => {
149
+ if (draining()) return;
150
+ let first = false;
151
+ try {
152
+ first = await journal.claim(entry(message, botId));
153
+ if (!first) return;
154
+ await wait?.(channelOf(message));
155
+ // Late, and after newer messages of its channel.
156
+ redeliver({ ...message, caughtUp: true });
157
+ } catch (error) {
158
+ logger.warn(
159
+ { messageId: message.messageId, err: error },
160
+ "could not claim or deliver a message again",
161
+ );
162
+ // Taken but not delivered: left, a later process answers it.
163
+ if (first)
164
+ await journal.leave(entry(message, botId)).catch(() => undefined);
165
+ }
166
+ }, retryMs);
167
+ timer.unref?.();
168
+ };
169
+ const pass = async (message: InboundMessage, botId: string) => {
170
+ if (!addressed(message)) return true;
171
+ if (draining()) {
172
+ await leave(message, botId, false);
173
+ return false;
174
+ }
175
+ const channelId = channelOf(message);
176
+ const { messageId } = message;
177
+ try {
178
+ if (!(await journal.claim(entry(message, botId)))) {
179
+ logger.info(
180
+ { channelId, messageId },
181
+ "message already taken in; not delivered again",
182
+ );
183
+ retry(message, botId);
184
+ return false;
185
+ }
186
+ await wait?.(channelId);
187
+ if (!draining()) return true;
188
+ // The drain began while it was recorded: routing would refuse it, so the next process takes it.
189
+ await leave(message, botId);
190
+ return false;
191
+ } catch (error) {
192
+ unrecorded?.add(messageId);
193
+ logger.warn(
194
+ { channelId, messageId, err: error },
195
+ "could not record an addressed message; delivered anyway",
196
+ );
197
+ return true;
198
+ }
199
+ };
200
+ const refused = async (message: InboundMessage, botId: string) => {
201
+ if (!notify || message.authorIsBot || message.integration) return false;
202
+ if (addressed(message)) await leave(message, botId);
203
+ else await tell("resend", message, botId);
204
+ return true;
205
+ };
206
+ return Object.assign(pass, { refused });
207
+ }
@@ -0,0 +1,134 @@
1
+ import type { SQL } from "bun";
2
+ import type { Migration } from "../db/migrations.ts";
3
+
4
+ /** One addressed message the host took in. */
5
+ export interface JournalEntry {
6
+ /** The bot that took it in, so two hosts on one database keep their records apart. */
7
+ botId: string;
8
+ messageId: string;
9
+ channelId: string;
10
+ /** Whether it came in a direct message, whose channel catch-up cannot list. */
11
+ direct: boolean;
12
+ }
13
+
14
+ /**
15
+ * The addressed messages the host took in, recorded before each is handed on: whoever records a
16
+ * message first, the live gateway or catch-up after a restart, is the only one that delivers it.
17
+ */
18
+ export interface InboundJournal {
19
+ /** Records the message as taken in, or takes one a stopping process left; false when it is taken. */
20
+ claim(entry: JournalEntry): Promise<boolean>;
21
+ /** The bot's direct-message channels with a message recorded since `since`, the most recent first. */
22
+ directChannels(botId: string, since: Date, limit: number): Promise<string[]>;
23
+ /** Records a message this process took in as left, as it stops before running it, for the next process to take. */
24
+ leave(entry: JournalEntry): Promise<void>;
25
+ /** Records a message no one took in yet as left; false when someone did, and it is theirs. */
26
+ leaveNew(entry: JournalEntry): Promise<boolean>;
27
+ /** The messages left since `since`, the oldest first. */
28
+ left(botId: string, since: Date): Promise<JournalEntry[]>;
29
+ /**
30
+ * Which of the bot's own messages `ids` are recorded: the notices it posted while it shut down,
31
+ * which say a message will be answered after the restart rather than answer it. No other message
32
+ * of the bot's is recorded, since only a person's is ever taken in.
33
+ */
34
+ recordedAmong(botId: string, ids: string[]): Promise<Set<string>>;
35
+ /** Forgets what was recorded before `before`. */
36
+ prune(before: Date): Promise<void>;
37
+ }
38
+
39
+ const migration: Migration = {
40
+ name: "discord-inbound-journal",
41
+ up: async (sql) => {
42
+ await sql`
43
+ CREATE TABLE IF NOT EXISTS discord_inbound_journal (
44
+ bot_id text NOT NULL,
45
+ message_id text NOT NULL,
46
+ channel_id text NOT NULL,
47
+ direct boolean NOT NULL,
48
+ recorded_at timestamptz NOT NULL DEFAULT now(),
49
+ PRIMARY KEY (bot_id, message_id)
50
+ )`;
51
+ await sql`
52
+ CREATE INDEX IF NOT EXISTS discord_inbound_journal_recorded
53
+ ON discord_inbound_journal (recorded_at)`;
54
+ },
55
+ };
56
+
57
+ /**
58
+ * The journal over the host's pool, built from closures rather than private fields, so a test
59
+ * proxy can carry it. One insert that does nothing on a conflict decides who records a message.
60
+ */
61
+ /** Marks a message left by a stopping process, so the next one answers it whatever the channel shows. */
62
+ const leftMigration: Migration = {
63
+ name: "discord-inbound-journal-left",
64
+ up: async (sql) => {
65
+ await sql`
66
+ ALTER TABLE discord_inbound_journal ADD COLUMN IF NOT EXISTS left_at timestamptz`;
67
+ },
68
+ };
69
+
70
+ export const PgInboundJournal = {
71
+ migrations: [migration, leftMigration],
72
+ attach(sql: SQL): InboundJournal {
73
+ return {
74
+ async claim({ botId, messageId, channelId, direct }) {
75
+ const rows: unknown[] = await sql`
76
+ INSERT INTO discord_inbound_journal (bot_id, message_id, channel_id, direct)
77
+ VALUES (${botId}, ${messageId}, ${channelId}, ${direct})
78
+ ON CONFLICT (bot_id, message_id) DO UPDATE SET left_at = NULL
79
+ WHERE discord_inbound_journal.left_at IS NOT NULL
80
+ RETURNING message_id`;
81
+ return rows.length > 0;
82
+ },
83
+ async leave({ botId, messageId, channelId, direct }) {
84
+ await sql`
85
+ INSERT INTO discord_inbound_journal (bot_id, message_id, channel_id, direct, left_at)
86
+ VALUES (${botId}, ${messageId}, ${channelId}, ${direct}, now())
87
+ ON CONFLICT (bot_id, message_id) DO UPDATE SET left_at = now()`;
88
+ },
89
+ async leaveNew({ botId, messageId, channelId, direct }) {
90
+ const rows: unknown[] = await sql`
91
+ INSERT INTO discord_inbound_journal (bot_id, message_id, channel_id, direct, left_at)
92
+ VALUES (${botId}, ${messageId}, ${channelId}, ${direct}, now())
93
+ ON CONFLICT (bot_id, message_id) DO NOTHING
94
+ RETURNING message_id`;
95
+ return rows.length > 0;
96
+ },
97
+ async left(botId, since) {
98
+ const rows: {
99
+ message_id: string;
100
+ channel_id: string;
101
+ direct: boolean;
102
+ }[] = await sql`
103
+ SELECT message_id, channel_id, direct FROM discord_inbound_journal
104
+ WHERE bot_id = ${botId} AND left_at >= ${since}
105
+ ORDER BY left_at`;
106
+ return rows.map((row) => ({
107
+ botId,
108
+ messageId: row.message_id,
109
+ channelId: row.channel_id,
110
+ direct: row.direct,
111
+ }));
112
+ },
113
+ async directChannels(botId, since, limit) {
114
+ const rows: { channel_id: string }[] = await sql`
115
+ SELECT channel_id FROM discord_inbound_journal
116
+ WHERE bot_id = ${botId} AND direct AND recorded_at >= ${since}
117
+ GROUP BY channel_id
118
+ ORDER BY max(recorded_at) DESC
119
+ LIMIT ${limit}`;
120
+ return rows.map((row) => row.channel_id);
121
+ },
122
+ async recordedAmong(botId, ids) {
123
+ if (ids.length === 0) return new Set();
124
+ const rows: { message_id: string }[] = await sql`
125
+ SELECT message_id FROM discord_inbound_journal
126
+ WHERE bot_id = ${botId} AND message_id IN ${sql(ids)}`;
127
+ return new Set(rows.map((row) => row.message_id));
128
+ },
129
+ async prune(before) {
130
+ await sql`DELETE FROM discord_inbound_journal WHERE recorded_at < ${before}`;
131
+ },
132
+ };
133
+ },
134
+ };