pi-roundtable 0.51.1 → 0.52.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,26 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
5
5
 
6
6
  ## [Unreleased]
7
7
 
8
+ ## [0.52.0] - 2026-11-17
9
+
10
+ ### Added
11
+
12
+ - `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.
13
+ - `InboundMessage.caughtUp` is set on a message delivered that way, so a claim may say its answer comes late.
14
+
15
+ ### Changed
16
+
17
+ - 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.
18
+
19
+ ## [0.51.2] - 2026-11-17
20
+
21
+ ### Fixed
22
+
23
+ - `readAttachmentText` leaves the caller's bytes as they were: reading a PDF emptied the array, so the next piece read from the same bytes failed as `unreadable` or with a raw `TypeError`. Anything that goes wrong inside now rejects with an `AttachmentTextError`.
24
+ - On a questionnaire card that more than one person may answer, a form submit writes only the fields that person changed from what they wrote before: a second owner sending only a note no longer erases the text the first wrote.
25
+ - `readAttachmentText` and `read_attachment` never end a piece between the halves of a surrogate pair, so a piece no longer carries half an emoji; `offset`, `limit` and `total` are documented as UTF-16 units.
26
+ - A PDF is parsed in a worker thread, so a large or crafted file no longer holds every channel's event loop. `readAttachmentText` refuses a PDF over 25 MiB with the new code `tooLarge`, reads at most 2,000 pages and 5,000,000 characters (leading the text with `[PDF, <n> pages; text of the first <m> only]`), and refuses a parse that takes longer than 30 seconds as `unreadable`.
27
+
8
28
  ## [0.51.1] - 2026-11-17
9
29
 
10
30
  ### 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,35 @@ 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 the bot or one of its own webhooks posted in that channel after it, or when it was already taken in.
2947
+ Of what is left, the newest `maxMessages` (default 20, at most 100) go to routing oldest first.
2948
+ They go once every service has started, so a message posted after the connection became ready may be answered before an older caught-up one in the same channel.
2949
+ 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.
2950
+ The log carries only counts and ids, never text.
2951
+
2952
+ Nothing is answered twice.
2953
+ 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.
2954
+ 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.
2955
+ 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.
2956
+ The live connection still delivers a message it cannot record, such as while the database is down, and logs it; only that message could be answered again, by a later restart that finds no answer to it in its channel.
2957
+ Once the old process begins to shut down it records nothing: routing refuses those messages and posts the restart notice once per channel, and the next process catches up the ones that came after that notice.
2958
+ The first restart after `catchUp` is turned on has no records from before: a message the old process handled without posting in its channel afterwards, such as one answered only with a reaction, may be answered again.
2959
+ A first direct message sent during the restart is not found, since Discord does not list a bot's direct-message channels.
2960
+
2930
2961
  ### Reading a file's bytes: `DISCORD.readAttachment`
2931
2962
 
2932
2963
  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`.
@@ -2960,7 +2991,10 @@ if (file?.id && file.messageId) {
2960
2991
  To give the model a file's text, pass the bytes to `readAttachmentText({ name, contentType?, bytes, offset?, limit? })` from the same entry; it reads as the core's `read_attachment` tool does.
2961
2992
  A text file (by its extension, a `text/*` or JSON, XML, YAML or TOML media type, or UTF-8 bytes with no NUL) is decoded; a PDF (by `.pdf`, `application/pdf` or its `%PDF-` start) has its text extracted, led by `[PDF, <n> pages]`.
2962
2993
  It resolves with `AttachmentText`: `kind` (`text` or `pdf`), `text` (at most `limit` characters from `offset`; default `ATTACHMENT_TEXT_LIMIT`, 60,000), `offset`, `nextOffset` when there is more, `total` characters and a PDF's `pages`.
2963
- It rejects with an `AttachmentTextError` whose `code` is `unsupported` (an image, audio, an archive or other binary), `unreadable` (a PDF that cannot be parsed) or `invalid` (an `offset` or `limit` that is not a whole number, or a `limit` below 1); its message names the file only.
2994
+ Characters, `offset`, `limit` and `total` count UTF-16 units, as a JavaScript string's `length` does. A piece never ends between the two halves of a surrogate pair (an emoji, for example): it stops one unit short, or with a `limit` of 1 at a pair takes both halves, and `nextOffset` follows it.
2995
+ It leaves `bytes` as it was, so the pieces of one file are read from one array.
2996
+ A PDF is parsed in a worker thread of its own, so a large or crafted file does not hold the host's event loop. It takes at most 25 MiB, reads at most 2,000 pages and 5,000,000 characters (its text is then led by `[PDF, <n> pages; text of the first <m> only]`, the same for every piece), and is refused when it takes longer than 30 seconds.
2997
+ It rejects with an `AttachmentTextError` whose `code` is `unsupported` (an image, audio, an archive or other binary), `unreadable` (a PDF that cannot be parsed or takes longer than 30 seconds, or bytes that cannot be read at all), `tooLarge` (a PDF over 25 MiB) or `invalid` (an `offset` or `limit` that is not a whole number, or a `limit` below 1); its message names the file only.
2964
2998
 
2965
2999
  ```ts
2966
3000
  import { AttachmentTextError, readAttachmentText } from "pi-roundtable/discord";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-roundtable",
3
- "version": "0.51.1",
3
+ "version": "0.52.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",
@@ -19,6 +19,14 @@ import {
19
19
  validReadCap,
20
20
  } from "../discord/attachment-read.ts";
21
21
  import { CardCopies } from "../discord/card-copies.ts";
22
+ import {
23
+ type CatchUpOptions,
24
+ catchUp,
25
+ catchUpSettings,
26
+ journalGate,
27
+ } from "../discord/catch-up.ts";
28
+ import { PgInboundJournal } from "../discord/catch-up-journal.ts";
29
+ import { clientCatchUpReader } from "../discord/catch-up-reader.ts";
22
30
  import { ChannelContextReader } from "../discord/channel-context.ts";
23
31
  import { CommandCollection } from "../discord/command-collection.ts";
24
32
  import type { DiscordConnection } from "../discord/connection.ts";
@@ -184,6 +192,15 @@ export interface DiscordOptions {
184
192
  * cards follow the same choice and `keepDays`, the newest 300, in `intercom-texts.json`.
185
193
  */
186
194
  cardCopies?: { keepDays?: number; keep?: number } | false;
195
+ /**
196
+ * Answers, once the connection is ready again, the messages addressed to the bot (a person's
197
+ * mention, reply to the bot, or direct message) that came while the host was down, as the
198
+ * gateway does not deliver them: those of the last `windowMinutes` (default 10) the bot did not
199
+ * answer, the newest `maxMessages` (default 20), oldest first, each marked
200
+ * `InboundMessage.caughtUp`. Each addressed message is recorded in the database before routing
201
+ * hears it, so none is answered twice. Needs the host's database. Default: off.
202
+ */
203
+ catchUp?: CatchUpOptions;
187
204
  }
188
205
 
189
206
  /** How many agent message cards keep their whole text for the open button, the newest. */
@@ -203,19 +220,34 @@ export function discordPlugin(options: DiscordOptions): RoundtablePlugin {
203
220
  throw new ConfigError(
204
221
  `discord.attachmentRead.maxBytes must be a whole number from 1 to ${ATTACHMENT_READ_LIMIT_BYTES}`,
205
222
  );
223
+ const catchUpWith = options.catchUp && catchUpSettings(options.catchUp);
206
224
  const collection = new CommandCollection();
207
225
  let surface: DiscordSurface | undefined;
208
226
  return {
209
227
  name: "discord",
210
228
  provides: [DISCORD],
229
+ ...(catchUpWith ? { migrations: [PgInboundJournal.migration] } : {}),
211
230
  preflight: () => {
212
231
  // The host has applied its environment by now, so the description is in its language.
213
232
  surface?.setCommands(
214
233
  collection.compose(ownerRootCommand(options.rootCommand)),
215
234
  );
216
235
  },
217
- setup: async ({ conversations, services, logger, events, dashboard }) => {
236
+ setup: async ({
237
+ conversations,
238
+ services,
239
+ logger,
240
+ events,
241
+ dashboard,
242
+ database,
243
+ }) => {
218
244
  const identity = services.find(IDENTITY);
245
+ // What came in, recorded only when catch-up is on, so it answers nothing twice.
246
+ const journal = catchUpWith
247
+ ? PgInboundJournal.attach(database())
248
+ : undefined;
249
+ // Set as the host begins to shut down; from then on routing refuses messages.
250
+ let draining = false;
219
251
  // A host that keeps no copy texts on disk drops what an earlier run left.
220
252
  if (options.cardCopies === false)
221
253
  for (const name of ["card-copies.json", "intercom-texts.json"]) {
@@ -270,6 +302,11 @@ export function discordPlugin(options: DiscordOptions): RoundtablePlugin {
270
302
  : { formatting: options.formatting }),
271
303
  ...(options.memberEvents ? { memberEvents: true } : {}),
272
304
  ...(options.voice ? { voice: true } : {}),
305
+ ...(journal
306
+ ? {
307
+ inboundGate: journalGate(journal, logger, () => draining),
308
+ }
309
+ : {}),
273
310
  });
274
311
  surface = connected;
275
312
  // Voice sessions over the same client; nothing of the voice packages is loaded before its service starts.
@@ -390,6 +427,29 @@ export function discordPlugin(options: DiscordOptions): RoundtablePlugin {
390
427
  await intercomTexts.stop();
391
428
  },
392
429
  },
430
+ // After every service is up, so the missed messages reach claims that are ready.
431
+ ...(journal && catchUpWith
432
+ ? [
433
+ {
434
+ name: "discord-catch-up",
435
+ startInBackground: async () => {
436
+ await catchUp({
437
+ reader: clientCatchUpReader(connected.client()),
438
+ journal,
439
+ deliver: (message) => {
440
+ void conversations.handle(message);
441
+ },
442
+ settings: catchUpWith,
443
+ logger,
444
+ stopping: () => draining,
445
+ });
446
+ },
447
+ beginDrain: () => {
448
+ draining = true;
449
+ },
450
+ },
451
+ ]
452
+ : []),
393
453
  // Fails the start when the voice packages cannot be loaded; ends every session as the host stops.
394
454
  ...(voice
395
455
  ? [
@@ -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;
@@ -0,0 +1,75 @@
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; false when it already was. */
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
+ /** Forgets what was recorded before `before`. */
24
+ prune(before: Date): Promise<void>;
25
+ }
26
+
27
+ const migration: Migration = {
28
+ name: "discord-inbound-journal",
29
+ up: async (sql) => {
30
+ await sql`
31
+ CREATE TABLE IF NOT EXISTS discord_inbound_journal (
32
+ bot_id text NOT NULL,
33
+ message_id text NOT NULL,
34
+ channel_id text NOT NULL,
35
+ direct boolean NOT NULL,
36
+ recorded_at timestamptz NOT NULL DEFAULT now(),
37
+ PRIMARY KEY (bot_id, message_id)
38
+ )`;
39
+ await sql`
40
+ CREATE INDEX IF NOT EXISTS discord_inbound_journal_recorded
41
+ ON discord_inbound_journal (recorded_at)`;
42
+ },
43
+ };
44
+
45
+ /**
46
+ * The journal over the host's pool, built from closures rather than private fields, so a test
47
+ * proxy can carry it. One insert that does nothing on a conflict decides who records a message.
48
+ */
49
+ export const PgInboundJournal = {
50
+ migration,
51
+ attach(sql: SQL): InboundJournal {
52
+ return {
53
+ async claim({ botId, messageId, channelId, direct }) {
54
+ const rows: unknown[] = await sql`
55
+ INSERT INTO discord_inbound_journal (bot_id, message_id, channel_id, direct)
56
+ VALUES (${botId}, ${messageId}, ${channelId}, ${direct})
57
+ ON CONFLICT (bot_id, message_id) DO NOTHING
58
+ RETURNING message_id`;
59
+ return rows.length > 0;
60
+ },
61
+ async directChannels(botId, since, limit) {
62
+ const rows: { channel_id: string }[] = await sql`
63
+ SELECT channel_id FROM discord_inbound_journal
64
+ WHERE bot_id = ${botId} AND direct AND recorded_at >= ${since}
65
+ GROUP BY channel_id
66
+ ORDER BY max(recorded_at) DESC
67
+ LIMIT ${limit}`;
68
+ return rows.map((row) => row.channel_id);
69
+ },
70
+ async prune(before) {
71
+ await sql`DELETE FROM discord_inbound_journal WHERE recorded_at < ${before}`;
72
+ },
73
+ };
74
+ },
75
+ };
@@ -0,0 +1,79 @@
1
+ import {
2
+ type Client,
3
+ type Message,
4
+ PermissionFlagsBits,
5
+ type TextBasedChannel,
6
+ } from "discord.js";
7
+ import type {
8
+ CatchUpChannel,
9
+ CatchUpReader,
10
+ ScannedMessage,
11
+ } from "./catch-up.ts";
12
+ import { timeOf } from "./catch-up.ts";
13
+ import { toInbound } from "./inbound-message.ts";
14
+
15
+ /** What the bot needs in a server channel to read what was said there before. */
16
+ const READ = [
17
+ PermissionFlagsBits.ViewChannel,
18
+ PermissionFlagsBits.ReadMessageHistory,
19
+ ];
20
+
21
+ function channelView(
22
+ channel: TextBasedChannel,
23
+ ): CatchUpChannel<Message & ScannedMessage> {
24
+ return {
25
+ id: channel.id,
26
+ direct: channel.isDMBased(),
27
+ lastMessageAt: channel.lastMessageId
28
+ ? timeOf(channel.lastMessageId)
29
+ : undefined,
30
+ read: async (before, limit) => [
31
+ ...(await channel.messages.fetch({ before, limit })).values(),
32
+ ],
33
+ };
34
+ }
35
+
36
+ /**
37
+ * Catch-up's view of a ready client. The server channels, threads and forum posts come from the
38
+ * client's cache, which Discord fills as the connection becomes ready, with each channel's last
39
+ * message: choosing what to read costs no request. A message's author is fetched as a member
40
+ * before it is read in full, so its roles are those a live message carries.
41
+ */
42
+ export function clientCatchUpReader(
43
+ client: Client,
44
+ ): CatchUpReader<Message & ScannedMessage> {
45
+ const bot = client.user;
46
+ const readyAt = client.readyTimestamp;
47
+ if (!bot || readyAt === null)
48
+ throw new Error("catch-up needs a ready Discord connection");
49
+ const identity = { botId: bot.id, applicationId: client.application?.id };
50
+ return {
51
+ botId: bot.id,
52
+ applicationId: client.application?.id,
53
+ readyAt,
54
+ channels: () => {
55
+ const found: CatchUpChannel<Message & ScannedMessage>[] = [];
56
+ for (const channel of client.channels.cache.values()) {
57
+ if (!channel.isTextBased()) continue;
58
+ if (channel.isThread() && channel.archived) continue;
59
+ if (!channel.isDMBased() && !channel.permissionsFor(bot)?.has(READ))
60
+ continue;
61
+ found.push(channelView(channel));
62
+ }
63
+ return found;
64
+ },
65
+ direct: async (channelId) => {
66
+ const channel = await client.channels.fetch(channelId);
67
+ return channel?.isDMBased() && channel.isTextBased()
68
+ ? channelView(channel)
69
+ : undefined;
70
+ },
71
+ inbound: async (message) => {
72
+ if (message.inGuild() && !message.member)
73
+ await message.guild.members
74
+ .fetch(message.author.id)
75
+ .catch(() => undefined);
76
+ return toInbound(message, identity);
77
+ },
78
+ };
79
+ }
@@ -0,0 +1,304 @@
1
+ import type { InboundMessage } from "../contract/channels.ts";
2
+ import { ConfigError } from "../domain/errors.ts";
3
+ import type { Logger } from "../kernel/log.ts";
4
+ import type { InboundJournal } from "./catch-up-journal.ts";
5
+
6
+ /** What `discord.catchUp` takes. */
7
+ export interface CatchUpOptions {
8
+ /** How far back, in minutes before the connection is ready, a missed message is still answered: 1 to 1440. Default 10. */
9
+ windowMinutes?: number;
10
+ /** The most missed messages answered after one restart, the newest; 1 to 100. Default 20. */
11
+ maxMessages?: number;
12
+ }
13
+
14
+ /** `CatchUpOptions` with the defaults filled in. */
15
+ export type CatchUpSettings = Required<CatchUpOptions>;
16
+
17
+ const DEFAULT_WINDOW_MINUTES = 10;
18
+ const DEFAULT_MAX_MESSAGES = 20;
19
+ /** How long a direct-message channel is remembered, to be looked into after a restart. */
20
+ const DIRECT_MEMORY_DAYS = 30;
21
+ /** The most remembered direct-message channels fetched to see whether they had a message lately. */
22
+ const DIRECT_PROBES = 25;
23
+ /** The most channels whose messages one catch-up reads, one request each. */
24
+ const MAX_CHANNEL_READS = 50;
25
+ /** The messages read before the ready time in each channel, one page. */
26
+ const PAGE = 100;
27
+ const DAY_MS = 86_400_000;
28
+ const DISCORD_EPOCH = 1_420_070_400_000n;
29
+
30
+ const whole = (value: number | undefined, low: number, high: number) =>
31
+ value === undefined ||
32
+ (Number.isInteger(value) && value >= low && value <= high);
33
+
34
+ /** The settings of `discord.catchUp`; throws a `ConfigError` for a value out of range. */
35
+ export function catchUpSettings(options: CatchUpOptions): CatchUpSettings {
36
+ if (!whole(options.windowMinutes, 1, 1440))
37
+ throw new ConfigError(
38
+ "discord.catchUp.windowMinutes must be a whole number from 1 to 1440",
39
+ );
40
+ if (!whole(options.maxMessages, 1, 100))
41
+ throw new ConfigError(
42
+ "discord.catchUp.maxMessages must be a whole number from 1 to 100",
43
+ );
44
+ return {
45
+ windowMinutes: options.windowMinutes ?? DEFAULT_WINDOW_MINUTES,
46
+ maxMessages: options.maxMessages ?? DEFAULT_MAX_MESSAGES,
47
+ };
48
+ }
49
+
50
+ /** The first snowflake Discord could assign at `ms`, as a bound for reading messages before it. */
51
+ export const snowflakeAt = (ms: number): string =>
52
+ ((BigInt(ms) - DISCORD_EPOCH) << 22n).toString();
53
+
54
+ /** When Discord assigned a snowflake, in epoch milliseconds. */
55
+ export const timeOf = (id: string): number =>
56
+ Number((BigInt(id) >> 22n) + DISCORD_EPOCH);
57
+
58
+ /** A person's message to the bot: a direct message, a mention, or a reply to it; never a bot's or a webhook's. */
59
+ export function addressed(message: InboundMessage): boolean {
60
+ return (
61
+ !message.authorIsBot &&
62
+ !message.integration &&
63
+ (message.isDirect || message.mentionsBot || message.repliesToBot)
64
+ );
65
+ }
66
+
67
+ /** The parts of a Discord message catch-up reads before it reads the message in full; a discord.js `Message` has them. */
68
+ export interface ScannedMessage {
69
+ id: string;
70
+ createdTimestamp: number;
71
+ author: { id: string; bot: boolean };
72
+ webhookId: string | null;
73
+ applicationId: string | null;
74
+ system: boolean;
75
+ mentions: {
76
+ users: { has(id: string): boolean };
77
+ repliedUser: { id: string } | null;
78
+ };
79
+ }
80
+
81
+ /** A channel catch-up may read. */
82
+ export interface CatchUpChannel<M extends ScannedMessage> {
83
+ id: string;
84
+ direct: boolean;
85
+ /** When its last message was posted, as the client knows it; undefined for none. */
86
+ lastMessageAt: number | undefined;
87
+ /** Up to `limit` of its messages before the snowflake `before`, in any order. */
88
+ read(before: string, limit: number): Promise<M[]>;
89
+ }
90
+
91
+ /** Discord as catch-up reads it, once the connection is ready. */
92
+ export interface CatchUpReader<M extends ScannedMessage> {
93
+ botId: string;
94
+ applicationId: string | undefined;
95
+ /** When the connection became ready: from then on the gateway delivers each message. */
96
+ readyAt: number;
97
+ /** The server channels, threads and forum posts the bot can read, and the direct messages the client holds, without a request. */
98
+ channels(): CatchUpChannel<M>[];
99
+ /** A direct-message channel by its id; undefined when it is not one. */
100
+ direct(channelId: string): Promise<CatchUpChannel<M> | undefined>;
101
+ /** The message as the live gateway would deliver it. */
102
+ inbound(message: M): Promise<InboundMessage | undefined>;
103
+ }
104
+
105
+ export interface CatchUpDeps<M extends ScannedMessage> {
106
+ reader: CatchUpReader<M>;
107
+ journal: InboundJournal;
108
+ /** Hands a message to routing, as the live gateway does. */
109
+ deliver(message: InboundMessage): void;
110
+ settings: CatchUpSettings;
111
+ logger: Logger;
112
+ /** True once the host shuts down: nothing more is delivered. */
113
+ stopping?: () => boolean;
114
+ now?: () => number;
115
+ }
116
+
117
+ /** What one catch-up did, in counts; logged, never the messages. */
118
+ export interface CatchUpReport {
119
+ channels: number;
120
+ unread: number;
121
+ missed: number;
122
+ replied: number;
123
+ overCap: number;
124
+ handled: number;
125
+ failed: number;
126
+ delivered: number;
127
+ }
128
+
129
+ /**
130
+ * The channels to read: those the client knows of, and the remembered direct messages, whose last
131
+ * message falls in the window, the most recently active first, at most `MAX_CHANNEL_READS`.
132
+ */
133
+ async function channelsToRead<M extends ScannedMessage>(
134
+ deps: CatchUpDeps<M>,
135
+ since: number,
136
+ now: number,
137
+ ): Promise<CatchUpChannel<M>[]> {
138
+ const { reader, journal, logger } = deps;
139
+ const known = reader.channels();
140
+ const ids = new Set(known.map((channel) => channel.id));
141
+ const directs = await journal
142
+ .directChannels(
143
+ reader.botId,
144
+ new Date(now - DIRECT_MEMORY_DAYS * DAY_MS),
145
+ DIRECT_PROBES,
146
+ )
147
+ .catch((error: unknown) => {
148
+ logger.warn({ err: error }, "catch-up could not list direct messages");
149
+ return [];
150
+ });
151
+ for (const id of directs) {
152
+ if (ids.has(id)) continue;
153
+ const channel = await reader.direct(id).catch(() => undefined);
154
+ if (channel) known.push(channel);
155
+ }
156
+ return known
157
+ .filter((channel) => (channel.lastMessageAt ?? 0) >= since)
158
+ .toSorted((a, b) => (b.lastMessageAt ?? 0) - (a.lastMessageAt ?? 0))
159
+ .slice(0, MAX_CHANNEL_READS);
160
+ }
161
+
162
+ /**
163
+ * Answers the messages addressed to the bot that came while the host was down: after the
164
+ * connection is ready, reads the channels active in the window and hands routing each person's
165
+ * mention, reply to the bot, or direct message from the window that the bot did not answer and
166
+ * that no one recorded, oldest first, marked `caughtUp`. A message is recorded in the journal
167
+ * before it is handed on, so a second restart, or a crash during its turn, never answers it again.
168
+ * Never rejects; reports its counts.
169
+ */
170
+ export async function catchUp<M extends ScannedMessage>(
171
+ deps: CatchUpDeps<M>,
172
+ ): Promise<CatchUpReport> {
173
+ const { reader, journal, settings, logger } = deps;
174
+ const now = deps.now?.() ?? Date.now();
175
+ const { readyAt, botId } = reader;
176
+ const since = readyAt - settings.windowMinutes * 60_000;
177
+ const report: CatchUpReport = {
178
+ channels: 0,
179
+ unread: 0,
180
+ missed: 0,
181
+ replied: 0,
182
+ overCap: 0,
183
+ handled: 0,
184
+ failed: 0,
185
+ delivered: 0,
186
+ };
187
+ await journal
188
+ .prune(new Date(now - DIRECT_MEMORY_DAYS * DAY_MS))
189
+ .catch((error: unknown) =>
190
+ logger.warn({ err: error }, "catch-up could not prune its journal"),
191
+ );
192
+ const own = reader.applicationId ?? botId;
193
+ const byBot = (message: M) =>
194
+ message.author.id === botId ||
195
+ (message.webhookId !== null && message.applicationId === own);
196
+ const missed: { message: M; channel: CatchUpChannel<M> }[] = [];
197
+ for (const channel of await channelsToRead(deps, since, now)) {
198
+ if (deps.stopping?.()) return report;
199
+ report.channels += 1;
200
+ let messages: M[];
201
+ try {
202
+ messages = await channel.read(snowflakeAt(readyAt), PAGE);
203
+ } catch (error) {
204
+ report.unread += 1;
205
+ logger.warn(
206
+ { channelId: channel.id, err: error },
207
+ "catch-up could not read a channel",
208
+ );
209
+ continue;
210
+ }
211
+ const answeredUpTo = messages.filter(byBot).reduce((latest, message) => {
212
+ const id = BigInt(message.id);
213
+ return id > latest ? id : latest;
214
+ }, 0n);
215
+ for (const message of messages) {
216
+ const { author, mentions } = message;
217
+ if (
218
+ message.createdTimestamp < since ||
219
+ message.createdTimestamp >= readyAt ||
220
+ author.bot ||
221
+ message.webhookId !== null ||
222
+ message.system ||
223
+ !(
224
+ channel.direct ||
225
+ mentions.users.has(botId) ||
226
+ mentions.repliedUser?.id === botId
227
+ )
228
+ )
229
+ continue;
230
+ // The bot posted after it, so it was answered then, or told it was restarting.
231
+ if (BigInt(message.id) < answeredUpTo) report.replied += 1;
232
+ else missed.push({ message, channel });
233
+ }
234
+ }
235
+ missed.sort((a, b) => (BigInt(a.message.id) < BigInt(b.message.id) ? -1 : 1));
236
+ report.missed = missed.length;
237
+ report.overCap = Math.max(0, missed.length - settings.maxMessages);
238
+ for (const { message, channel } of missed.slice(report.overCap)) {
239
+ if (deps.stopping?.()) break;
240
+ try {
241
+ const inbound = await reader.inbound(message);
242
+ if (!inbound) continue;
243
+ const first = await journal.claim({
244
+ botId,
245
+ messageId: message.id,
246
+ channelId: channel.id,
247
+ direct: channel.direct,
248
+ });
249
+ if (!first) {
250
+ report.handled += 1;
251
+ continue;
252
+ }
253
+ deps.deliver({ ...inbound, caughtUp: true });
254
+ report.delivered += 1;
255
+ } catch (error) {
256
+ // Unrecorded, it is not answered: a second answer is worse than none.
257
+ report.failed += 1;
258
+ logger.warn(
259
+ { channelId: channel.id, messageId: message.id, err: error },
260
+ "catch-up skipped a missed message it could not read or record",
261
+ );
262
+ }
263
+ }
264
+ logger.info({ ...report }, "discord catch-up done");
265
+ return report;
266
+ }
267
+
268
+ /**
269
+ * Records each addressed message the live gateway delivers before routing hears it, so catch-up
270
+ * after a restart leaves it alone; false for one already recorded, which is not delivered again.
271
+ * A message that cannot be recorded is still delivered, and logged. Once the host drains
272
+ * (`draining`), nothing is recorded: routing refuses those messages, and the next process answers
273
+ * those its restart notice did not.
274
+ */
275
+ export function journalGate(
276
+ journal: InboundJournal,
277
+ logger: Logger,
278
+ draining: () => boolean = () => false,
279
+ ): (message: InboundMessage, botId: string) => Promise<boolean> {
280
+ return async (message, botId) => {
281
+ if (!addressed(message) || draining()) return true;
282
+ const channelId = message.channel.slice("discord:".length);
283
+ try {
284
+ const first = await journal.claim({
285
+ botId,
286
+ messageId: message.messageId,
287
+ channelId,
288
+ direct: message.isDirect,
289
+ });
290
+ if (!first)
291
+ logger.info(
292
+ { channelId, messageId: message.messageId },
293
+ "message already taken in; not delivered again",
294
+ );
295
+ return first;
296
+ } catch (error) {
297
+ logger.warn(
298
+ { channelId, messageId: message.messageId, err: error },
299
+ "could not record an addressed message; delivered anyway",
300
+ );
301
+ return true;
302
+ }
303
+ };
304
+ }
@@ -53,7 +53,11 @@ import {
53
53
  listenForJoins,
54
54
  memberIntents,
55
55
  } from "./member-events.ts";
56
- import { listenForMessages, reportChanges } from "./message-changes.ts";
56
+ import {
57
+ type InboundGate,
58
+ listenForMessages,
59
+ reportChanges,
60
+ } from "./message-changes.ts";
57
61
  import type { CardChannel, LateTurn } from "./owner-cards.ts";
58
62
  import { DiscordOwnerOps } from "./owner-discord.ts";
59
63
  import { showStopPanel } from "./stop-button.ts";
@@ -81,6 +85,8 @@ export interface DiscordSurfaceOptions {
81
85
  formatting?: string | false;
82
86
  /** Where the agents' message cards keep their whole texts for the open button; without it a card posts as text. */
83
87
  intercomTexts?: IntercomTexts;
88
+ /** Decides whether each live message is handed on, such as catch-up's journal; without it every one is. */
89
+ inboundGate?: InboundGate;
84
90
  /** Reads the channel context of an addressed message; without it the surface has none. */
85
91
  channelContext?: (
86
92
  message: InboundMessage,
@@ -274,7 +280,12 @@ export class DiscordSurface
274
280
  const { logger, token } = this.#options;
275
281
  this.#onMessage = onMessage;
276
282
  if (events) reportChanges(this.#client, events, logger);
277
- listenForMessages(this.#client, onMessage, logger);
283
+ listenForMessages(
284
+ this.#client,
285
+ onMessage,
286
+ logger,
287
+ this.#options.inboundGate,
288
+ );
278
289
  this.#client.on(Events.InteractionCreate, (interaction) => {
279
290
  void this.#dispatch(interaction);
280
291
  });
@@ -5,23 +5,52 @@ import { channelKey } from "../contract/surface.ts";
5
5
  import type { Logger } from "../kernel/log.ts";
6
6
  import { toInbound } from "./inbound-message.ts";
7
7
 
8
- /** Hands every message the client sees to `deliver` as the neutral message; the bot's own are left out. */
8
+ /** Decides whether a message the gateway delivered is handed on: false keeps it from routing. */
9
+ export type InboundGate = (
10
+ message: InboundMessage,
11
+ botId: string,
12
+ ) => Promise<boolean>;
13
+
14
+ /**
15
+ * Hands every message the client sees to `deliver` as the neutral message, in the order each
16
+ * channel's messages came, however long reading one takes; the bot's own are left out, and so is
17
+ * one the gate refuses.
18
+ */
9
19
  export function listenForMessages(
10
20
  client: Client,
11
21
  deliver: (message: InboundMessage) => void,
12
22
  logger: Logger,
23
+ gate?: InboundGate,
13
24
  ): void {
25
+ const delivering = new Map<string, Promise<void>>();
14
26
  client.on(Events.MessageCreate, (message) => {
15
- toInbound(message, {
16
- botId: client.user?.id,
27
+ const botId = client.user?.id;
28
+ const read = toInbound(message, {
29
+ botId,
17
30
  applicationId: client.application?.id,
18
31
  })
32
+ .then(async (inbound) => {
33
+ if (!inbound || !botId) return undefined;
34
+ return !gate || (await gate(inbound, botId)) ? inbound : undefined;
35
+ })
36
+ // Handled here, not when its turn comes: a read that fails while an earlier one waits would otherwise go unhandled.
37
+ .catch((error: unknown) => {
38
+ logger.error({ err: error }, "inbound message could not be read");
39
+ return undefined;
40
+ });
41
+ const { channelId } = message;
42
+ const after = (delivering.get(channelId) ?? Promise.resolve())
43
+ .then(() => read)
19
44
  .then((inbound) => {
20
45
  if (inbound) deliver(inbound);
21
46
  })
22
47
  .catch((error: unknown) =>
23
- logger.error({ err: error }, "inbound message could not be read"),
48
+ logger.error({ err: error }, "inbound message could not be delivered"),
24
49
  );
50
+ delivering.set(channelId, after);
51
+ void after.then(() => {
52
+ if (delivering.get(channelId) === after) delivering.delete(channelId);
53
+ });
25
54
  });
26
55
  }
27
56
 
@@ -168,10 +168,16 @@ export async function answerDeferred(
168
168
  const { texts, note } = formFields(form, (field) =>
169
169
  interaction.fields.getTextInputValue(field),
170
170
  );
171
+ // The form opened with what this user wrote before, not the shared draft; a field they left as
172
+ // it was is no change of theirs, so it must not overwrite what another wrote there since.
173
+ const before = form.written.get(by.user.id);
171
174
  const own: Written = { texts: [] };
172
- for (const [i, value] of texts)
173
- form.draft.texts[i] = own.texts[i] = value.trim() || undefined;
174
- form.draft.note = own.note = note.trim() || undefined;
175
+ for (const [i, value] of texts) {
176
+ own.texts[i] = value.trim() || undefined;
177
+ if (own.texts[i] !== before?.texts[i]) form.draft.texts[i] = own.texts[i];
178
+ }
179
+ own.note = note.trim() || undefined;
180
+ if (own.note !== before?.note) form.draft.note = own.note;
175
181
  form.written.set(by.user.id, own);
176
182
  }
177
183
  if (!submits) {
@@ -37,7 +37,9 @@ export interface QuestionnaireForm {
37
37
  draft: Draft;
38
38
  /**
39
39
  * The text answers and note each user last wrote and was allowed to, by user id: their form
40
- * opens with these, never with the shared draft, which may hold someone else's unsent text.
40
+ * opens with these, never with the shared draft, which may hold someone else's unsent text. A
41
+ * submit writes to the draft only the fields that differ from these, so a field a user left as
42
+ * their form showed it keeps what another wrote there.
41
43
  */
42
44
  written: Map<string, Written>;
43
45
  }
@@ -176,6 +176,7 @@ function discordAssembly(
176
176
  ...(discord.attachmentRead
177
177
  ? { attachmentRead: discord.attachmentRead }
178
178
  : {}),
179
+ ...(discord.catchUp ? { catchUp: discord.catchUp } : {}),
179
180
  }),
180
181
  admin: discord.admin ? [discordAdminPlugin({ owner })] : [],
181
182
  };
@@ -1,5 +1,5 @@
1
- import { extractText, getDocumentProxy } from "unpdf";
2
1
  import { plainText } from "../attachments/attachment-name.ts";
2
+ import { PDF_LIMITS, PdfTextError, pdfText } from "./pdf-text.ts";
3
3
 
4
4
  /** Characters one read returns by default, as the core's `read_attachment` tool reads; ask for a later `offset` for more. */
5
5
  export const ATTACHMENT_TEXT_LIMIT = 60_000;
@@ -52,6 +52,8 @@ function isPdf(name: string, type: string, head: Uint8Array): boolean {
52
52
  );
53
53
  }
54
54
 
55
+ const isHighSurrogate = (unit: number) => unit >= 0xd800 && unit <= 0xdbff;
56
+
55
57
  function looksLikeText(bytes: Uint8Array): boolean {
56
58
  const sample = bytes.subarray(0, 4096);
57
59
  if (sample.includes(0)) return false;
@@ -68,9 +70,13 @@ export interface AttachmentTextRequest {
68
70
  name: string;
69
71
  contentType?: string | null;
70
72
  bytes: Uint8Array;
71
- /** The character to start from; default 0. */
73
+ /** The character (UTF-16 unit) to start from; default 0. */
72
74
  offset?: number;
73
- /** The most characters returned; default `ATTACHMENT_TEXT_LIMIT`, 60,000. */
75
+ /**
76
+ * The most characters (UTF-16 units) returned; default `ATTACHMENT_TEXT_LIMIT`, 60,000. A piece
77
+ * never ends between the two halves of a surrogate pair, so it may hold one fewer, or, with a
78
+ * `limit` of 1 at a pair, both halves.
79
+ */
74
80
  limit?: number;
75
81
  }
76
82
 
@@ -78,13 +84,17 @@ export interface AttachmentTextRequest {
78
84
  export interface AttachmentText {
79
85
  /** `pdf` when the text was extracted from a PDF, else `text`. */
80
86
  kind: "text" | "pdf";
81
- /** The characters from `offset`, at most `limit` of them; a PDF's text starts with `[PDF, <n> pages]`. */
87
+ /**
88
+ * The characters from `offset`, at most `limit` of them; a PDF's text starts with
89
+ * `[PDF, <n> pages]`, or `[PDF, <n> pages; text of the first <m> only]` when it stopped after
90
+ * 2,000 pages or 5,000,000 characters.
91
+ */
82
92
  text: string;
83
93
  /** Where this piece starts. */
84
94
  offset: number;
85
95
  /** Where the next piece starts; absent when this piece reaches the end. */
86
96
  nextOffset?: number;
87
- /** Characters in the whole text. */
97
+ /** Characters (UTF-16 units, as `offset` and `limit` count) in the whole text. */
88
98
  total: number;
89
99
  /** A PDF's page count. */
90
100
  pages?: number;
@@ -92,10 +102,15 @@ export interface AttachmentText {
92
102
 
93
103
  /**
94
104
  * Why a file was not read as text: `unsupported` (not text or a PDF, such as an image, audio or an
95
- * archive), `unreadable` (a PDF that could not be parsed), `invalid` (an `offset` or `limit` that
96
- * is not a whole number, or a `limit` below 1).
105
+ * archive), `unreadable` (a PDF that could not be parsed or took longer than 30 seconds, or
106
+ * bytes that could not be read at all), `invalid` (an `offset` or `limit` that is not a whole
107
+ * number, or a `limit` below 1), `tooLarge` (a PDF over 25 MiB).
97
108
  */
98
- export type AttachmentTextErrorCode = "unsupported" | "unreadable" | "invalid";
109
+ export type AttachmentTextErrorCode =
110
+ | "unsupported"
111
+ | "unreadable"
112
+ | "invalid"
113
+ | "tooLarge";
99
114
 
100
115
  /** What `readAttachmentText` rejects with; `message` names the file, never its bytes. */
101
116
  export class AttachmentTextError extends Error {
@@ -116,7 +131,7 @@ export class AttachmentTextError extends Error {
116
131
  export async function readAttachmentText(
117
132
  request: AttachmentTextRequest,
118
133
  ): Promise<AttachmentText> {
119
- const { name, bytes } = request;
134
+ const { name } = request;
120
135
  const offset = request.offset ?? 0;
121
136
  const limit = request.limit ?? ATTACHMENT_TEXT_LIMIT;
122
137
  if (!Number.isInteger(offset) || offset < 0)
@@ -129,25 +144,50 @@ export async function readAttachmentText(
129
144
  "invalid",
130
145
  "limit must be a positive whole number",
131
146
  );
147
+ try {
148
+ return await read(request, offset, limit);
149
+ } catch (error) {
150
+ if (error instanceof AttachmentTextError) throw error;
151
+ throw new AttachmentTextError(
152
+ "unreadable",
153
+ `"${plainText(name)}" could not be read`,
154
+ );
155
+ }
156
+ }
157
+
158
+ async function read(
159
+ request: AttachmentTextRequest,
160
+ offset: number,
161
+ limit: number,
162
+ ): Promise<AttachmentText> {
163
+ const { name, bytes } = request;
132
164
  const type = mediaType(request.contentType);
133
165
  let kind: AttachmentText["kind"];
134
166
  let text: string;
135
167
  let pages: number | undefined;
136
168
  if (isPdf(name, type, bytes)) {
137
- let result: { totalPages: number; text: string };
169
+ if (bytes.byteLength > PDF_LIMITS.bytes)
170
+ throw new AttachmentTextError(
171
+ "tooLarge",
172
+ `"${plainText(name)}" is too large to read as a PDF (${bytes.byteLength} bytes; at most ${PDF_LIMITS.bytes})`,
173
+ );
174
+ let result: Awaited<ReturnType<typeof pdfText>>;
138
175
  try {
139
- result = await extractText(await getDocumentProxy(bytes), {
140
- mergePages: true,
141
- });
142
- } catch {
176
+ result = await pdfText(bytes);
177
+ } catch (error) {
143
178
  throw new AttachmentTextError(
144
179
  "unreadable",
145
- `"${plainText(name)}" could not be read as a PDF`,
180
+ error instanceof PdfTextError && error.reason === "slow"
181
+ ? `"${plainText(name)}" took too long to read as a PDF`
182
+ : `"${plainText(name)}" could not be read as a PDF`,
146
183
  );
147
184
  }
148
185
  kind = "pdf";
149
186
  pages = result.totalPages;
150
- text = `[PDF, ${result.totalPages} pages]\n${result.text}`;
187
+ const head = result.cut
188
+ ? `[PDF, ${result.totalPages} pages; text of the first ${result.pagesRead} only]`
189
+ : `[PDF, ${result.totalPages} pages]`;
190
+ text = `${head}\n${result.text}`;
151
191
  } else if (
152
192
  TEXT_EXTENSIONS.has(extension(name)) ||
153
193
  type.startsWith("text/") ||
@@ -162,7 +202,15 @@ export async function readAttachmentText(
162
202
  `"${plainText(name)}" is not a text or PDF file (${bytes.byteLength} bytes). Images are shown to you directly; audio or video can go to a tool that takes files.`,
163
203
  );
164
204
  }
165
- const end = Math.min(text.length, offset + limit);
205
+ let end = Math.min(text.length, offset + limit);
206
+ // A piece never ends between the halves of a surrogate pair: it stops before the pair, or, when
207
+ // that would leave it empty, takes the whole pair.
208
+ if (
209
+ end < text.length &&
210
+ end > offset &&
211
+ isHighSurrogate(text.charCodeAt(end - 1))
212
+ )
213
+ end += end - 1 > offset ? -1 : 1;
166
214
  return {
167
215
  kind,
168
216
  text: text.slice(offset, end),
@@ -0,0 +1,81 @@
1
+ import { parentPort, workerData } from "node:worker_threads";
2
+ import { getDocumentProxy } from "unpdf";
3
+
4
+ /**
5
+ * Extracts a PDF's text off the host's thread (see `pdf-text.ts`): pdf.js parses in the thread that
6
+ * calls it, so a large or crafted file would hold every channel's event loop. It reads pages in
7
+ * order and stops after `pages` pages or once it holds `chars` characters, so the host is given a
8
+ * bounded text, the same for every read of the same bytes. Loaded outside a worker, which is what
9
+ * importing every module of the core does, it does nothing.
10
+ */
11
+ const limits = (
12
+ workerData as { pdfText?: { pages: number; chars: number } } | null
13
+ )?.pdfText;
14
+
15
+ /** What the worker answers: the text it read, or that pdf.js could not parse the file. */
16
+ export type PdfWorkerAnswer =
17
+ | {
18
+ ok: true;
19
+ totalPages: number;
20
+ pagesRead: number;
21
+ text: string;
22
+ cut: boolean;
23
+ }
24
+ | { ok: false };
25
+
26
+ const isHighSurrogate = (unit: number) => unit >= 0xd800 && unit <= 0xdbff;
27
+
28
+ async function extract(
29
+ bytes: Uint8Array,
30
+ max: { pages: number; chars: number },
31
+ ): Promise<PdfWorkerAnswer> {
32
+ const pdf = await getDocumentProxy(bytes);
33
+ try {
34
+ const texts: string[] = [];
35
+ let chars = 0;
36
+ let pagesRead = 0;
37
+ while (pagesRead < Math.min(pdf.numPages, max.pages) && chars < max.chars) {
38
+ const page = await pdf.getPage(pagesRead + 1);
39
+ const content = await page.getTextContent();
40
+ const text = content.items
41
+ .map((item) =>
42
+ "str" in item && item.str != null
43
+ ? item.str + (item.hasEOL ? "\n" : "")
44
+ : "",
45
+ )
46
+ .join("");
47
+ texts.push(text);
48
+ chars += text.length;
49
+ pagesRead += 1;
50
+ }
51
+ // As unpdf's `mergePages` joins pages: whitespace collapsed, line breaks kept, one blank line at most.
52
+ const merged = texts
53
+ .join("\n")
54
+ .replace(/[^\S\n]+/g, " ")
55
+ .replace(/ ?\n ?/g, "\n")
56
+ .replace(/\n{3,}/g, "\n\n");
57
+ let end = Math.min(merged.length, max.chars);
58
+ // A cut never ends between the halves of a surrogate pair.
59
+ if (end < merged.length && isHighSurrogate(merged.charCodeAt(end - 1)))
60
+ end -= 1;
61
+ return {
62
+ ok: true,
63
+ totalPages: pdf.numPages,
64
+ pagesRead,
65
+ text: merged.slice(0, end),
66
+ cut: pagesRead < pdf.numPages || end < merged.length,
67
+ };
68
+ } finally {
69
+ await pdf.loadingTask.destroy();
70
+ }
71
+ }
72
+
73
+ if (limits && parentPort) {
74
+ const port = parentPort;
75
+ port.on("message", (bytes: Uint8Array) => {
76
+ extract(bytes, limits).then(
77
+ (answer) => port.postMessage(answer),
78
+ () => port.postMessage({ ok: false } satisfies PdfWorkerAnswer),
79
+ );
80
+ });
81
+ }
@@ -0,0 +1,86 @@
1
+ import { Worker } from "node:worker_threads";
2
+ import { MAX_ATTACHMENT_BYTES } from "../attachments/attachment-fetcher.ts";
3
+ import type { PdfWorkerAnswer } from "./pdf-text-worker.ts";
4
+
5
+ /**
6
+ * The bounds of one PDF read. `bytes`: the largest file parsed, as large as the core reads any
7
+ * attachment. `pages` and `chars`: the text stops after this many pages, or once it holds this many
8
+ * characters (UTF-16 units), so every read of the same bytes gives the same text. `ms`: how long a
9
+ * parse may run before its worker is stopped and the read refused.
10
+ */
11
+ export const PDF_LIMITS = {
12
+ bytes: MAX_ATTACHMENT_BYTES,
13
+ pages: 2_000,
14
+ chars: 5_000_000,
15
+ ms: 30_000,
16
+ } as const;
17
+
18
+ /** A PDF's text as the worker read it; `cut` when it stopped at a limit before the end. */
19
+ export interface PdfText {
20
+ totalPages: number;
21
+ pagesRead: number;
22
+ text: string;
23
+ cut: boolean;
24
+ }
25
+
26
+ /** Why `pdfText` gave no text: pdf.js could not parse the file, or did not finish in time. */
27
+ export class PdfTextError extends Error {
28
+ readonly reason: "unreadable" | "slow";
29
+ constructor(reason: "unreadable" | "slow") {
30
+ super(
31
+ reason === "slow" ? "PDF parse timed out" : "PDF could not be parsed",
32
+ );
33
+ this.name = "PdfTextError";
34
+ this.reason = reason;
35
+ }
36
+ }
37
+
38
+ /**
39
+ * A PDF's text, extracted in a worker of its own so the parse never holds the host's event loop,
40
+ * and stopped after `limits.ms`. The worker gets a copy of `bytes`; the caller's array is left as
41
+ * it was.
42
+ */
43
+ export function pdfText(
44
+ bytes: Uint8Array,
45
+ limits: { pages: number; chars: number; ms: number } = PDF_LIMITS,
46
+ ): Promise<PdfText> {
47
+ const copy = bytes.slice();
48
+ const worker = new Worker(new URL("./pdf-text-worker.ts", import.meta.url), {
49
+ workerData: {
50
+ pdfText: { pages: limits.pages, chars: limits.chars },
51
+ },
52
+ });
53
+ return new Promise<PdfText>((resolve, reject) => {
54
+ const timer = setTimeout(
55
+ () => settle(() => reject(new PdfTextError("slow"))),
56
+ limits.ms,
57
+ );
58
+ let done = false;
59
+ const settle = (then: () => void) => {
60
+ if (done) return;
61
+ done = true;
62
+ clearTimeout(timer);
63
+ void worker.terminate();
64
+ then();
65
+ };
66
+ worker.once("message", (answer: PdfWorkerAnswer) =>
67
+ settle(() =>
68
+ answer.ok
69
+ ? resolve({
70
+ totalPages: answer.totalPages,
71
+ pagesRead: answer.pagesRead,
72
+ text: answer.text,
73
+ cut: answer.cut,
74
+ })
75
+ : reject(new PdfTextError("unreadable")),
76
+ ),
77
+ );
78
+ worker.once("error", () =>
79
+ settle(() => reject(new PdfTextError("unreadable"))),
80
+ );
81
+ worker.once("exit", () =>
82
+ settle(() => reject(new PdfTextError("unreadable"))),
83
+ );
84
+ worker.postMessage(copy, [copy.buffer]);
85
+ });
86
+ }