pi-roundtable 0.51.0 → 0.51.2

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,25 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
5
5
 
6
6
  ## [Unreleased]
7
7
 
8
+ ## [0.51.2] - 2026-11-17
9
+
10
+ ### Fixed
11
+
12
+ - `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`.
13
+ - 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.
14
+ - `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.
15
+ - 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`.
16
+
17
+ ## [0.51.1] - 2026-11-17
18
+
19
+ ### Fixed
20
+
21
+ - A questionnaire card's "Write answers / note…" form no longer shows the open draft to whoever presses it: each person's form is prefilled only with the text answers and note they wrote themselves, so someone the card is not for no longer sees the owner's unsent text (a regression in 0.51.0).
22
+ - `DISCORD.readAttachment` rejects a call's `maxBytes` that is not a positive whole number with an `AttachmentReadError` whose code is the new `invalid`, instead of a `RangeError`; `discordPlugin` throws a `ConfigError` for an `attachmentRead.maxBytes` outside 1 byte to 100 MiB, the bound the config file already had.
23
+ - The agent panel's buttons open their forms (edit, model) as the interaction's first answer, with nothing awaited before them: the model form uses the host's models from the last time it asked, and the owner check moves to the submit, where someone else now gets the refusal instead of no answer.
24
+ - pi-roundtable-mcp: `/<root> connector add` shows its form before the owner check, through the new `OwnerCommandHandlers.form`, and a member who submits it gets the refusal. `ownerCommandModule` gains the optional `form` handler, and `ownerRefusal` (the refusal panel for a guard's hint) is exported from `pi-roundtable/discord`.
25
+ - `readAttachmentText` (`readAttachmentText({ name, contentType?, bytes, offset?, limit? })`) from `pi-roundtable/discord` reads a file's bytes as text the way the core's `read_attachment` tool does: a text file decoded, a PDF's text extracted, in pieces of `ATTACHMENT_TEXT_LIMIT` (60,000) characters with `nextOffset` for the next. It resolves with `AttachmentText` (`kind`, `text`, `offset`, `nextOffset?`, `total`, `pages?`) and rejects with an `AttachmentTextError` whose `code` is `unsupported`, `unreadable` or `invalid` (`AttachmentTextErrorCode`; the request is an `AttachmentTextRequest`). Pair it with `DISCORD.readAttachment` to read a Discord file's text in a plugin's own tool. The `read_attachment` tool now names a binary it refuses with the name escaped, and a PDF it cannot parse as `could not be read as a PDF`.
26
+
8
27
  ## [0.51.0] - 2026-11-17
9
28
 
10
29
  ### Added
package/docs/plugins.md CHANGED
@@ -2080,7 +2080,8 @@ Use `services.find(DISCORD)` if your plugin can work without Discord.
2080
2080
  When the service is absent, the rest of your plugin can run without commands.
2081
2081
 
2082
2082
  Build a feature's part of the root command with `ownerCommandModule(guard, handlers)` from `pi-roundtable/discord`; only the owners may use it, it defers interactions, and supplies a failure panel.
2083
- That entry also exports `groupOption` for subcommand groups, the panel helpers (`ownerPanel`, `ownerPanels`, `ephemeralPanel`, `replyWithPanels`, `plain`, `OwnerFacingError`), and `agentPanel({ guard, agents })` for an agent's profile panel.
2083
+ A subcommand that opens a form gives it as `handlers.form(interaction)`, which returns a `ModalBuilder` or undefined: the form is shown as the interaction's first answer before the owner check, because Discord takes a form only first and within 3 seconds, and the check may ask `IDENTITY`. Anyone who runs the subcommand sees the form, so it must hold nothing private; its submit reaches `handlers.component`, which checks `guard.allows` and answers someone else with `ownerRefusal(guard.refusalHint)`.
2084
+ That entry also exports `groupOption` for subcommand groups, the panel helpers (`ownerRefusal`, `ownerPanel`, `ownerPanels`, `ephemeralPanel`, `replyWithPanels`, `plain`, `OwnerFacingError`), and `agentPanel({ guard, agents })` for an agent's profile panel.
2084
2085
  `DISCORD.guard` is the `CommandGuard`; `await guard.allows(actor)` is whether the actor is an owner now: the primary owner by user id, and every other owner principal by their Discord identity, checked through `IDENTITY` each time, so an owner granted or revoked with the CLI is seen at once and a stranger is never resolved. It accepts an interaction or anything with `user.id` (a `DiscordActor`), so a test needs no cast.
2085
2086
  `guard.isOwner(actor)` is deprecated until 1.0: it is the primary owner only, by user id, so a component handler that still asks it refuses the other owners.
2086
2087
  `commandGuard({ ownerId, identity?, root, logger, refusalHint? })` makes one; without `identity` the primary owner is the only owner.
@@ -2932,7 +2933,7 @@ Channel context and `InboundMessage.attachments` describe files; a plugin whose
2932
2933
  `InboundMessage.attachments` (`AttachmentRef`) carry `id`, `messageId` (the message itself, the one a reply quotes in `reference.attachments`, or, for a forward, the forwarding message), `title?` and `description?` beside `url`, `name`, `contentType?` and `size`; channel context gives the same as an attachment line's `id` and `message`.
2933
2934
  The call fetches the message again from Discord in the channel the caller names, finds the file by its id, its own or a forwarded message's, and downloads it from the fresh address Discord gives (only `https` on Discord's CDN), so no URL a caller or a model supplies is ever fetched and an expired link does not matter.
2934
2935
  It resolves with `AttachmentBytes` (`id`, `name`, `contentType`, empty when Discord does not say, `size` as read, `bytes` a `Uint8Array`, `title?`, `description?`) and rejects with an `AttachmentReadError` whose `code` is `not-found` (no such channel or message the bot can read, a message of another channel, no such file on it, or an id that is no Discord id), `too-large` (over the cap, by Discord's size before any download or by what arrives), `gone` (the CDN answers 403, 404 or 410) or `unavailable` (Discord is not connected, the download failed or took over 30 seconds, or another answer); its message names the request, never the file's address.
2935
- At most the host's `discord.attachmentRead.maxBytes` (default `ATTACHMENT_READ_MAX_BYTES`, 10 MiB; at most 100 MiB) is read, and a call's `maxBytes` may lower that, never raise it.
2936
+ At most the host's `discord.attachmentRead.maxBytes` (default `ATTACHMENT_READ_MAX_BYTES`, 10 MiB; at most 100 MiB) is read, and a call's `maxBytes` may lower that, never raise it; a `maxBytes` that is not a positive whole number rejects with the code `invalid`. `discordPlugin` throws a `ConfigError` for an `attachmentRead.maxBytes` outside 1 to 100 MiB, as the config file does.
2936
2937
  Nothing is parsed, stored or logged: what the bytes are for (text extraction, an image for the model, a file in the workspace) is the plugin's call.
2937
2938
  The core checks nothing about who may read which channel beyond what the bot can see: pass the channel of the conversation the file was posted in, such as the addressed message's channel, never one a model names in a tool call.
2938
2939
 
@@ -2951,11 +2952,26 @@ if (file?.id && file.messageId) {
2951
2952
  // read.bytes is a Uint8Array of read.size bytes
2952
2953
  } catch (error) {
2953
2954
  if (!(error instanceof AttachmentReadError)) throw error;
2954
- // error.code: "not-found" | "too-large" | "gone" | "unavailable"
2955
+ // error.code: "not-found" | "too-large" | "gone" | "unavailable" | "invalid"
2955
2956
  }
2956
2957
  }
2957
2958
  ```
2958
2959
 
2960
+ 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
+ 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
+ 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
+ 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.
2964
+ It leaves `bytes` as it was, so the pieces of one file are read from one array.
2965
+ 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.
2966
+ 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.
2967
+
2968
+ ```ts
2969
+ import { AttachmentTextError, readAttachmentText } from "pi-roundtable/discord";
2970
+
2971
+ const piece = await readAttachmentText({ ...read, offset: 0 });
2972
+ // piece.nextOffset, when set, is the offset of the next piece
2973
+ ```
2974
+
2959
2975
  ### Posting through `DISCORD.poster`
2960
2976
 
2961
2977
  `DISCORD.poster` (`DiscordPoster`, from `pi-roundtable/discord`) is Discord's REST API for a plugin's own posts, over the Discord plugin's own client.
@@ -5195,6 +5211,11 @@ Import from the entries listed below; source area files are internal.
5195
5211
  | `AttachmentReadError` | `pi-roundtable/discord` | value |
5196
5212
  | `AttachmentReadErrorCode` | `pi-roundtable/discord` | type |
5197
5213
  | `AttachmentReadRequest` | `pi-roundtable/discord` | type |
5214
+ | `ATTACHMENT_TEXT_LIMIT` | `pi-roundtable/discord` | value |
5215
+ | `AttachmentText` | `pi-roundtable/discord` | type |
5216
+ | `AttachmentTextError` | `pi-roundtable/discord` | value |
5217
+ | `AttachmentTextErrorCode` | `pi-roundtable/discord` | type |
5218
+ | `AttachmentTextRequest` | `pi-roundtable/discord` | type |
5198
5219
  | `CHANNEL_CONTEXT_DEFAULTS` | `pi-roundtable/discord` | value |
5199
5220
  | `CONTEXT_ATTACHMENT_LINES` | `pi-roundtable/discord` | value |
5200
5221
  | `CHANNEL_OPERATIONS` | `pi-roundtable/discord` | value |
@@ -5288,9 +5309,11 @@ Import from the entries listed below; source area files are internal.
5288
5309
  | `ownerCommandModule` | `pi-roundtable/discord` | value |
5289
5310
  | `ownerPanel` | `pi-roundtable/discord` | value |
5290
5311
  | `ownerPanels` | `pi-roundtable/discord` | value |
5312
+ | `ownerRefusal` | `pi-roundtable/discord` | value |
5291
5313
  | `ownerRootCommand` | `pi-roundtable/discord` | value |
5292
5314
  | `parseChannelTool` | `pi-roundtable/discord` | value |
5293
5315
  | `plain` | `pi-roundtable/discord` | value |
5316
+ | `readAttachmentText` | `pi-roundtable/discord` | value |
5294
5317
  | `replyWithPanels` | `pi-roundtable/discord` | value |
5295
5318
  | `withChannelContext` | `pi-roundtable/discord` | value |
5296
5319
  | `withChannelContextImages` | `pi-roundtable/discord` | value |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-roundtable",
3
- "version": "0.51.0",
3
+ "version": "0.51.2",
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",
@@ -10,11 +10,13 @@ import { type ServiceKey, serviceKey } from "../contract/services.ts";
10
10
  import { discordAgentGuild } from "../discord/agent-guild.ts";
11
11
  import { discordChannelOps, discordTeamReads } from "../discord/agent-tools.ts";
12
12
  import {
13
+ ATTACHMENT_READ_LIMIT_BYTES,
13
14
  ATTACHMENT_READ_MAX_BYTES,
14
15
  type AttachmentBytes,
15
16
  type AttachmentReadRequest,
16
17
  discordAttachmentSource,
17
18
  readAttachment,
19
+ validReadCap,
18
20
  } from "../discord/attachment-read.ts";
19
21
  import { CardCopies } from "../discord/card-copies.ts";
20
22
  import { ChannelContextReader } from "../discord/channel-context.ts";
@@ -79,7 +81,8 @@ export interface DiscordServices {
79
81
  * line's `id` and `message` in channel context). At most the host's
80
82
  * `discord.attachmentRead.maxBytes` (default 10 MiB) is read, or less when `maxBytes` asks.
81
83
  * Nothing is parsed, stored or logged. Rejects with an `AttachmentReadError` whose `code` is
82
- * `not-found`, `too-large`, `gone` or `unavailable`. Which channels a plugin reads is its own
84
+ * `not-found`, `too-large`, `gone`, `unavailable`, or `invalid` for a `maxBytes` that is not a
85
+ * positive whole number. Which channels a plugin reads is its own
83
86
  * call: pass the channel of the conversation the file was posted in, not one a model names.
84
87
  */
85
88
  readAttachment(request: AttachmentReadRequest): Promise<AttachmentBytes>;
@@ -160,7 +163,11 @@ export interface DiscordOptions {
160
163
  * loaded as the host starts, and only then. Default: off.
161
164
  */
162
165
  voice?: boolean;
163
- /** The most bytes `DISCORD.readAttachment` reads of one file; default `ATTACHMENT_READ_MAX_BYTES`, 10 MiB. */
166
+ /**
167
+ * The most bytes `DISCORD.readAttachment` reads of one file: a whole number from 1 to
168
+ * 100 MiB, else `discordPlugin` throws a `ConfigError`; default
169
+ * `ATTACHMENT_READ_MAX_BYTES`, 10 MiB.
170
+ */
164
171
  attachmentRead?: { maxBytes?: number };
165
172
  /** What the model is told about how replies render in Discord; `false` tells it nothing. Default: Markdown renders, except tables. */
166
173
  formatting?: string | false;
@@ -191,6 +198,11 @@ const INTERCOM_KEEP = 300;
191
198
  export function discordPlugin(options: DiscordOptions): RoundtablePlugin {
192
199
  if (options.entryChannel !== undefined && options.agentGuild === undefined)
193
200
  throw new ConfigError(ENTRY_CHANNEL_WITHOUT_GUILD);
201
+ const readCap = options.attachmentRead?.maxBytes;
202
+ if (readCap !== undefined && !validReadCap(readCap))
203
+ throw new ConfigError(
204
+ `discord.attachmentRead.maxBytes must be a whole number from 1 to ${ATTACHMENT_READ_LIMIT_BYTES}`,
205
+ );
194
206
  const collection = new CommandCollection();
195
207
  let surface: DiscordSurface | undefined;
196
208
  return {
@@ -112,11 +112,29 @@ export function skillsText({ skills, missing }: SkillSet): string {
112
112
  /** `/<root> profile`: an agent's prompt, avatar, model, and skills, with buttons and forms to change them. */
113
113
  export class AgentCommands {
114
114
  readonly #options: AgentCommandsOptions;
115
+ /**
116
+ * The models the host could run when last asked: the model form is drawn from these, since a
117
+ * form must be an interaction's first answer with nothing awaited before it.
118
+ */
119
+ #usable: readonly string[] | undefined;
115
120
 
116
121
  constructor(options: AgentCommandsOptions) {
117
122
  this.#options = options;
118
123
  }
119
124
 
125
+ /** Asks the host again for the models it can run, in the background; a failure keeps the last answer. */
126
+ #refreshModels(): void {
127
+ const { team } = this.#options;
128
+ Promise.resolve()
129
+ .then(() => team.usableModels())
130
+ .then(
131
+ (models) => {
132
+ this.#usable = models;
133
+ },
134
+ () => undefined,
135
+ );
136
+ }
137
+
120
138
  /** The panel for the agent of a channel; an error when the channel has none. */
121
139
  panel(channelId: string, note?: string): AgentPanelMessage {
122
140
  const { store } = this.#options;
@@ -127,6 +145,7 @@ export class AgentCommands {
127
145
  ? messages().agentGroupChannel
128
146
  : messages().agentNoAgent,
129
147
  );
148
+ this.#refreshModels();
130
149
  return this.#panel(agent, note);
131
150
  }
132
151
 
@@ -259,7 +278,11 @@ export class AgentCommands {
259
278
  );
260
279
  }
261
280
 
262
- /** A panel button: a form opens. */
281
+ /**
282
+ * A panel button: its form opens as the first answer, with nothing awaited before it, so it is
283
+ * shown to anyone who can press it; the form shows only what the panel shows, and what is
284
+ * submitted is checked against the owners (`agentPanel`).
285
+ */
263
286
  async button(interaction: ButtonInteraction): Promise<void> {
264
287
  const [action, name] = interaction.customId
265
288
  .slice(AGENT_BUTTON_PREFIX.length)
@@ -270,17 +293,20 @@ export class AgentCommands {
270
293
  if (!ACTIONS.includes(action as Action))
271
294
  throw new OwnerFacingError(messages().agentPanelOutdated);
272
295
  await interaction.showModal(
273
- action === "model"
274
- ? await this.#modelModal(agent)
275
- : this.#editModal(agent),
296
+ action === "model" ? this.#modelModal(agent) : this.#editModal(agent),
276
297
  );
298
+ if (action === "model") this.#refreshModels();
277
299
  }
278
300
 
279
- /** Two dropdowns: the model and the thinking level, each with "follow the assistant" first. */
280
- async #modelModal(agent: Agent): Promise<ModalBuilder> {
301
+ /**
302
+ * Two dropdowns: the model and the thinking level, each with "follow the assistant" first.
303
+ * Before the host has answered which models it runs, every form model is offered; saving one
304
+ * it cannot run is refused when the form is submitted.
305
+ */
306
+ #modelModal(agent: Agent): ModalBuilder {
281
307
  const { team } = this.#options;
282
308
  const fallback = team.defaultModel();
283
- const models = formModels(await team.usableModels(), agent.model);
309
+ const models = formModels(this.#usable ?? FORM_MODELS, agent.model);
284
310
  const option = (label: string, value: string, chosen: boolean) =>
285
311
  new StringSelectMenuOptionBuilder()
286
312
  .setLabel(label.slice(0, 100))
@@ -7,6 +7,7 @@ import {
7
7
  type AgentPanelMessage,
8
8
  } from "./agent-commands.ts";
9
9
  import type { CommandGuard } from "./interaction-module.ts";
10
+ import { ownerRefusal } from "./owner-command.ts";
10
11
 
11
12
  export interface AgentPanelOptions {
12
13
  /** Who may press the panel's buttons and submit its forms. */
@@ -25,7 +26,9 @@ export interface AgentPanel {
25
26
  */
26
27
  open(channelId: string): AgentPanelMessage;
27
28
  /**
28
- * Answers the panel's own buttons, dropdowns and form, for the owner only and deferred as Discord needs;
29
+ * Answers the panel's own buttons, dropdowns and form, deferred as Discord needs. A button opens its
30
+ * form for anyone at once, since a form must come first; only an owner's dropdown or submitted form
31
+ * changes the agent, and anyone else's submitted form is refused;
29
32
  * true when it handled the interaction. The custom ids are fixed, so panels already posted keep working.
30
33
  */
31
34
  handles(interaction: Interaction): Promise<boolean>;
@@ -47,7 +50,7 @@ export function agentPanel(options: AgentPanelOptions): AgentPanel {
47
50
  interaction.isButton() &&
48
51
  interaction.customId.startsWith(AGENT_BUTTON_PREFIX)
49
52
  ) {
50
- if (!(await guard.allows(interaction))) return true;
53
+ // The form is the first answer, with nothing awaited before it; the submit is checked.
51
54
  await guard.run(interaction, () => commands.button(interaction));
52
55
  return true;
53
56
  }
@@ -64,7 +67,10 @@ export function agentPanel(options: AgentPanelOptions): AgentPanel {
64
67
  interaction.isModalSubmit() &&
65
68
  interaction.customId.startsWith(AGENT_MODAL_PREFIX)
66
69
  ) {
67
- if (!(await guard.allows(interaction))) return true;
70
+ if (!(await guard.allows(interaction))) {
71
+ await interaction.reply(ownerRefusal(guard.refusalHint));
72
+ return true;
73
+ }
68
74
  await interaction.deferReply({ flags: MessageFlags.Ephemeral });
69
75
  await guard.run(interaction, () => commands.submit(interaction));
70
76
  return true;
@@ -33,9 +33,11 @@ export interface AttachmentBytes {
33
33
  * Why a file was not read: `not-found` (no such channel, message, or file on the message, or one
34
34
  * the bot cannot see), `too-large` (over the cap, by Discord's size or by what arrived), `gone`
35
35
  * (Discord's CDN no longer serves it), `unavailable` (Discord is not connected, did not answer in
36
- * time, or answered with another error; trying later may work).
36
+ * time, or answered with another error; trying later may work), `invalid` (the call's `maxBytes` is
37
+ * not a positive whole number).
37
38
  */
38
39
  export type AttachmentReadErrorCode =
40
+ | "invalid"
39
41
  | "not-found"
40
42
  | "too-large"
41
43
  | "gone"
@@ -53,6 +55,12 @@ export class AttachmentReadError extends Error {
53
55
 
54
56
  /** The host's cap on one read when `discord.attachmentRead.maxBytes` is left out: 10 MiB. */
55
57
  export const ATTACHMENT_READ_MAX_BYTES = 10 * 1024 * 1024;
58
+ /** The highest cap a host may set, in its config or in `discordPlugin`'s options: 100 MiB. */
59
+ export const ATTACHMENT_READ_LIMIT_BYTES = 100 * 1024 * 1024;
60
+
61
+ /** Whether `bytes` is a cap a host may set: a whole number from 1 to `ATTACHMENT_READ_LIMIT_BYTES`. */
62
+ export const validReadCap = (bytes: number) =>
63
+ Number.isInteger(bytes) && bytes >= 1 && bytes <= ATTACHMENT_READ_LIMIT_BYTES;
56
64
  /** How long one file's download may take. */
57
65
  const READ_TIMEOUT_MS = 30_000;
58
66
 
@@ -102,14 +110,17 @@ export async function readAttachment(
102
110
  }))
103
111
  if (typeof value !== "string" || !/^\d{1,25}$/.test(value))
104
112
  throw new AttachmentReadError("not-found", `${name} is not a Discord id`);
105
- const max = Math.min(
106
- options.maxBytes,
107
- request.maxBytes === undefined
108
- ? Number.POSITIVE_INFINITY
109
- : request.maxBytes,
110
- );
111
- if (!Number.isInteger(max) || max < 1)
112
- throw new RangeError("maxBytes must be a positive integer");
113
+ if (!validReadCap(options.maxBytes))
114
+ throw new RangeError(
115
+ `the host's maxBytes must be a whole number from 1 to ${ATTACHMENT_READ_LIMIT_BYTES}`,
116
+ );
117
+ const asked = request.maxBytes;
118
+ if (asked !== undefined && !(Number.isInteger(asked) && asked >= 1))
119
+ throw new AttachmentReadError(
120
+ "invalid",
121
+ "maxBytes must be a positive whole number",
122
+ );
123
+ const max = Math.min(options.maxBytes, asked ?? Number.POSITIVE_INFINITY);
113
124
  let files: readonly AttachmentFacts[] | undefined;
114
125
  try {
115
126
  files = await source.files(channelId, messageId);
@@ -9,6 +9,7 @@ import {
9
9
  formFields,
10
10
  previewReplies,
11
11
  questionnaireModal,
12
+ type Written,
12
13
  } from "./owner-card-questionnaire.ts";
13
14
  import {
14
15
  answeredLine,
@@ -167,9 +168,17 @@ export async function answerDeferred(
167
168
  const { texts, note } = formFields(form, (field) =>
168
169
  interaction.fields.getTextInputValue(field),
169
170
  );
170
- for (const [i, value] of texts)
171
- form.draft.texts[i] = value.trim() || undefined;
172
- form.draft.note = note.trim() || undefined;
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);
174
+ const own: Written = { texts: [] };
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;
181
+ form.written.set(by.user.id, own);
173
182
  }
174
183
  if (!submits) {
175
184
  card.touch();
@@ -190,18 +199,20 @@ export async function answerDeferred(
190
199
 
191
200
  /**
192
201
  * "Write answers / note…": opens the form at once, since nothing may be awaited before a form is
193
- * shown; the audience is checked when it is submitted (`answerDeferred`).
202
+ * shown; the audience is checked when it is submitted (`answerDeferred`). The form holds only
203
+ * what this user wrote before, so it shows no one else's unsent text.
194
204
  */
195
205
  export async function answerForm(
196
206
  card: OpenCard,
197
207
  id: string,
198
208
  action: string,
199
209
  interaction: Interaction,
210
+ by: Answerer,
200
211
  ): Promise<void> {
201
212
  if (!card.form || !interaction.isButton() || action !== "notes") return;
202
213
  if (!card.isOpen()) {
203
214
  await interaction.reply(ephemeral(messages().cardInactive));
204
215
  return;
205
216
  }
206
- await interaction.showModal(questionnaireModal(id, card.form));
217
+ await interaction.showModal(questionnaireModal(id, card.form, by.user.id));
207
218
  }
@@ -117,6 +117,7 @@ export function askPrompts(args: {
117
117
  const form: QuestionnaireForm = {
118
118
  questionnaire,
119
119
  draft: newDraft(questionnaire.questions.length),
120
+ written: new Map(),
120
121
  };
121
122
  return post<QuestionnaireAnswer | "pending" | "declined" | undefined>(
122
123
  channelId,
@@ -35,6 +35,19 @@ export interface Draft {
35
35
  export interface QuestionnaireForm {
36
36
  questionnaire: Questionnaire;
37
37
  draft: Draft;
38
+ /**
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. 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.
43
+ */
44
+ written: Map<string, Written>;
45
+ }
46
+
47
+ /** What one user wrote in the form. */
48
+ export interface Written {
49
+ texts: (string | undefined)[];
50
+ note?: string;
38
51
  }
39
52
 
40
53
  export const newDraft = (questions: number): Draft => ({
@@ -188,8 +201,13 @@ export function questionnaireCard(args: {
188
201
  }
189
202
 
190
203
  /** The form for what the menus cannot take: each question's own answer, and the note. */
191
- export function questionnaireModal(id: string, form: QuestionnaireForm) {
204
+ export function questionnaireModal(
205
+ id: string,
206
+ form: QuestionnaireForm,
207
+ userId: string,
208
+ ) {
192
209
  const { questions } = form.questionnaire;
210
+ const own = form.written.get(userId);
193
211
  const labelled = (
194
212
  label: string,
195
213
  field: string,
@@ -219,16 +237,11 @@ export function questionnaireModal(id: string, form: QuestionnaireForm) {
219
237
  questions.length === 1
220
238
  ? messages().cardModalField
221
239
  : `${i + 1}. ${question.header ?? messages().cardQuestionName(i + 1)}`;
222
- const field = labelled(
223
- label,
224
- `t${i}`,
225
- form.draft.texts[i],
226
- question.question,
227
- );
240
+ const field = labelled(label, `t${i}`, own?.texts[i], question.question);
228
241
  modal.addLabelComponents(field);
229
242
  }
230
243
  return modal.addLabelComponents(
231
- labelled(messages().cardNoteField, "note", form.draft.note),
244
+ labelled(messages().cardNoteField, "note", own?.note),
232
245
  );
233
246
  }
234
247
 
@@ -450,6 +450,6 @@ export class OwnerCards implements InteractionModule {
450
450
  if (!card.form) return answerSingle(card, id, action, interaction, by);
451
451
  if (action === "qpick" || action === "submit" || action === "qtext")
452
452
  return answerDeferred(card, action, index, interaction, by);
453
- return answerForm(card, id, action, interaction);
453
+ return answerForm(card, id, action, interaction, by);
454
454
  }
455
455
  }
@@ -4,6 +4,7 @@ import {
4
4
  type Interaction,
5
5
  InteractionContextType,
6
6
  MessageFlags,
7
+ type ModalBuilder,
7
8
  SlashCommandSubcommandGroupBuilder,
8
9
  } from "discord.js";
9
10
  import { messages } from "../i18n/index.ts";
@@ -121,7 +122,14 @@ export interface OwnerCommandHandlers {
121
122
  /** Whether a root subcommand, in its group or null at the top level, is this feature's. */
122
123
  owns(group: string | null, subcommand: string): boolean;
123
124
  autocomplete?(interaction: AutocompleteInteraction): Promise<void>;
124
- /** An answer that must be the interaction's first, such as a form; true when it answered. */
125
+ /**
126
+ * A form the subcommand opens, or undefined: shown as the interaction's first answer before the
127
+ * owner check, which may ask the identity service, since Discord takes a form only within 3 s and
128
+ * only before anything else. It is shown to anyone who runs the subcommand, so it holds nothing
129
+ * private; what is submitted reaches `component`, which checks the owner.
130
+ */
131
+ form?(interaction: ChatInputCommandInteraction): ModalBuilder | undefined;
132
+ /** An answer that must be the interaction's first, given to an owner only; true when it answered. */
125
133
  open?(interaction: ChatInputCommandInteraction): Promise<boolean>;
126
134
  /** Answers a subcommand; the reply is already deferred and ephemeral. */
127
135
  command(interaction: ChatInputCommandInteraction): Promise<void>;
@@ -129,7 +137,8 @@ export interface OwnerCommandHandlers {
129
137
  component?(interaction: Interaction): Promise<boolean>;
130
138
  }
131
139
 
132
- const refusal = (hint: string | undefined) =>
140
+ /** What someone who is not an owner is told, with the guard's `refusalHint`. */
141
+ export const ownerRefusal = (hint: string | undefined) =>
133
142
  ephemeralPanel({
134
143
  title: messages().ownerRefusalTitle,
135
144
  sections: [`${messages().ownerRefusalBody}${hint ?? ""}`],
@@ -160,8 +169,13 @@ export function ownerCommandModule(
160
169
  if (await handlers.component?.(interaction)) return true;
161
170
  if (!interaction.isChatInputCommand() || !owned(interaction))
162
171
  return false;
172
+ const form = handlers.form?.(interaction);
173
+ if (form) {
174
+ await interaction.showModal(form);
175
+ return true;
176
+ }
163
177
  if (!(await guard.allows(interaction))) {
164
- await interaction.reply(refusal(guard.refusalHint));
178
+ await interaction.reply(ownerRefusal(guard.refusalHint));
165
179
  return true;
166
180
  }
167
181
  if (await handlers.open?.(interaction)) return true;
@@ -1,58 +1,15 @@
1
1
  import { join } from "node:path";
2
- import { extractText, getDocumentProxy } from "unpdf";
3
2
  import { wasExpired } from "../attachments/attachment-expiry.ts";
4
3
  import { MAX_ATTACHMENT_BYTES } from "../attachments/attachment-fetcher.ts";
5
4
  import { isAttachmentName, plainText } from "../attachments/attachment-name.ts";
6
5
  import { AttachmentExpiredError } from "../attachments/tool-attachment.ts";
6
+ import {
7
+ ATTACHMENT_TEXT_LIMIT,
8
+ readAttachmentText,
9
+ } from "./attachment-text.ts";
7
10
 
8
11
  /** Characters returned per read; the model can ask for a later offset. */
9
- export const READ_LIMIT = 60_000;
10
-
11
- const TEXT_EXTENSIONS = new Set([
12
- ".txt",
13
- ".md",
14
- ".markdown",
15
- ".csv",
16
- ".tsv",
17
- ".json",
18
- ".yaml",
19
- ".yml",
20
- ".xml",
21
- ".html",
22
- ".htm",
23
- ".log",
24
- ".ts",
25
- ".js",
26
- ".py",
27
- ".sh",
28
- ".toml",
29
- ".ini",
30
- ".srt",
31
- ".vtt",
32
- ]);
33
-
34
- function extension(name: string): string {
35
- const dot = name.lastIndexOf(".");
36
- return dot < 0 ? "" : name.slice(dot).toLowerCase();
37
- }
38
-
39
- function isPdf(name: string, head: Uint8Array): boolean {
40
- return (
41
- extension(name) === ".pdf" ||
42
- new TextDecoder().decode(head.subarray(0, 5)) === "%PDF-"
43
- );
44
- }
45
-
46
- function looksLikeText(bytes: Uint8Array): boolean {
47
- const sample = bytes.subarray(0, 4096);
48
- if (sample.includes(0)) return false;
49
- try {
50
- new TextDecoder("utf-8", { fatal: true }).decode(sample);
51
- return true;
52
- } catch {
53
- return false;
54
- }
55
- }
12
+ export const READ_LIMIT = ATTACHMENT_TEXT_LIMIT;
56
13
 
57
14
  export interface ReadResult {
58
15
  text: string;
@@ -91,18 +48,11 @@ export async function readAttachment(
91
48
  // A file system error names the path on the host; the model sees only the attachment's name.
92
49
  throw new Error(`"${plainText(file)}" could not be read`);
93
50
  }
94
- let text: string;
95
- if (isPdf(file, bytes)) {
96
- const pdf = await getDocumentProxy(bytes);
97
- const result = await extractText(pdf, { mergePages: true });
98
- text = `[PDF, ${result.totalPages} pages]\n${result.text}`;
99
- } else if (TEXT_EXTENSIONS.has(extension(file)) || looksLikeText(bytes)) {
100
- text = new TextDecoder().decode(bytes);
101
- } else {
102
- throw new Error(
103
- `"${file}" 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.`,
104
- );
105
- }
106
- const start = Math.max(0, Math.floor(offset));
107
- return { text: text.slice(start, start + READ_LIMIT), total: text.length };
51
+ const { text, total } = await readAttachmentText({
52
+ name: file,
53
+ bytes,
54
+ offset: Math.max(0, Math.floor(offset)),
55
+ limit: READ_LIMIT,
56
+ });
57
+ return { text, total };
108
58
  }
@@ -0,0 +1,222 @@
1
+ import { plainText } from "../attachments/attachment-name.ts";
2
+ import { PDF_LIMITS, PdfTextError, pdfText } from "./pdf-text.ts";
3
+
4
+ /** Characters one read returns by default, as the core's `read_attachment` tool reads; ask for a later `offset` for more. */
5
+ export const ATTACHMENT_TEXT_LIMIT = 60_000;
6
+
7
+ const TEXT_EXTENSIONS = new Set([
8
+ ".txt",
9
+ ".md",
10
+ ".markdown",
11
+ ".csv",
12
+ ".tsv",
13
+ ".json",
14
+ ".yaml",
15
+ ".yml",
16
+ ".xml",
17
+ ".html",
18
+ ".htm",
19
+ ".log",
20
+ ".ts",
21
+ ".js",
22
+ ".py",
23
+ ".sh",
24
+ ".toml",
25
+ ".ini",
26
+ ".srt",
27
+ ".vtt",
28
+ ]);
29
+
30
+ const TEXT_TYPES = new Set([
31
+ "application/json",
32
+ "application/xml",
33
+ "application/yaml",
34
+ "application/x-yaml",
35
+ "application/toml",
36
+ ]);
37
+
38
+ function extension(name: string): string {
39
+ const dot = name.lastIndexOf(".");
40
+ return dot < 0 ? "" : name.slice(dot).toLowerCase();
41
+ }
42
+
43
+ /** The media type without its parameters, lowercased; empty when none is given. */
44
+ const mediaType = (contentType: string | null | undefined) =>
45
+ (contentType ?? "").split(";")[0]?.trim().toLowerCase() ?? "";
46
+
47
+ function isPdf(name: string, type: string, head: Uint8Array): boolean {
48
+ return (
49
+ extension(name) === ".pdf" ||
50
+ type === "application/pdf" ||
51
+ new TextDecoder().decode(head.subarray(0, 5)) === "%PDF-"
52
+ );
53
+ }
54
+
55
+ const isHighSurrogate = (unit: number) => unit >= 0xd800 && unit <= 0xdbff;
56
+
57
+ function looksLikeText(bytes: Uint8Array): boolean {
58
+ const sample = bytes.subarray(0, 4096);
59
+ if (sample.includes(0)) return false;
60
+ try {
61
+ new TextDecoder("utf-8", { fatal: true }).decode(sample);
62
+ return true;
63
+ } catch {
64
+ return false;
65
+ }
66
+ }
67
+
68
+ /** A file to read as text: its name, its media type when known, and its bytes. */
69
+ export interface AttachmentTextRequest {
70
+ name: string;
71
+ contentType?: string | null;
72
+ bytes: Uint8Array;
73
+ /** The character (UTF-16 unit) to start from; default 0. */
74
+ offset?: number;
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
+ */
80
+ limit?: number;
81
+ }
82
+
83
+ /** One piece of a file's text. */
84
+ export interface AttachmentText {
85
+ /** `pdf` when the text was extracted from a PDF, else `text`. */
86
+ kind: "text" | "pdf";
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
+ */
92
+ text: string;
93
+ /** Where this piece starts. */
94
+ offset: number;
95
+ /** Where the next piece starts; absent when this piece reaches the end. */
96
+ nextOffset?: number;
97
+ /** Characters (UTF-16 units, as `offset` and `limit` count) in the whole text. */
98
+ total: number;
99
+ /** A PDF's page count. */
100
+ pages?: number;
101
+ }
102
+
103
+ /**
104
+ * Why a file was not read as text: `unsupported` (not text or a PDF, such as an image, audio or an
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).
108
+ */
109
+ export type AttachmentTextErrorCode =
110
+ | "unsupported"
111
+ | "unreadable"
112
+ | "invalid"
113
+ | "tooLarge";
114
+
115
+ /** What `readAttachmentText` rejects with; `message` names the file, never its bytes. */
116
+ export class AttachmentTextError extends Error {
117
+ readonly code: AttachmentTextErrorCode;
118
+ constructor(code: AttachmentTextErrorCode, message: string) {
119
+ super(message);
120
+ this.name = "AttachmentTextError";
121
+ this.code = code;
122
+ }
123
+ }
124
+
125
+ /**
126
+ * A file's bytes as text, one piece at a time: a text file is decoded as UTF-8, a PDF's text is
127
+ * extracted, and anything else is refused with an `AttachmentTextError`. It is how the core's
128
+ * `read_attachment` tool reads, so a plugin that has a file's bytes (for example from
129
+ * `DISCORD.readAttachment`) reads it the same way.
130
+ */
131
+ export async function readAttachmentText(
132
+ request: AttachmentTextRequest,
133
+ ): Promise<AttachmentText> {
134
+ const { name } = request;
135
+ const offset = request.offset ?? 0;
136
+ const limit = request.limit ?? ATTACHMENT_TEXT_LIMIT;
137
+ if (!Number.isInteger(offset) || offset < 0)
138
+ throw new AttachmentTextError(
139
+ "invalid",
140
+ "offset must be a whole number from 0",
141
+ );
142
+ if (!Number.isInteger(limit) || limit < 1)
143
+ throw new AttachmentTextError(
144
+ "invalid",
145
+ "limit must be a positive whole number",
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;
164
+ const type = mediaType(request.contentType);
165
+ let kind: AttachmentText["kind"];
166
+ let text: string;
167
+ let pages: number | undefined;
168
+ if (isPdf(name, type, bytes)) {
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>>;
175
+ try {
176
+ result = await pdfText(bytes);
177
+ } catch (error) {
178
+ throw new AttachmentTextError(
179
+ "unreadable",
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`,
183
+ );
184
+ }
185
+ kind = "pdf";
186
+ pages = result.totalPages;
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}`;
191
+ } else if (
192
+ TEXT_EXTENSIONS.has(extension(name)) ||
193
+ type.startsWith("text/") ||
194
+ TEXT_TYPES.has(type) ||
195
+ looksLikeText(bytes)
196
+ ) {
197
+ kind = "text";
198
+ text = new TextDecoder().decode(bytes);
199
+ } else {
200
+ throw new AttachmentTextError(
201
+ "unsupported",
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.`,
203
+ );
204
+ }
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;
214
+ return {
215
+ kind,
216
+ text: text.slice(offset, end),
217
+ offset,
218
+ ...(end < text.length ? { nextOffset: end } : {}),
219
+ total: text.length,
220
+ ...(pages === undefined ? {} : { pages }),
221
+ };
222
+ }
@@ -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
+ }
@@ -84,6 +84,7 @@ export {
84
84
  commandGuard,
85
85
  groupOption,
86
86
  ownerCommandModule,
87
+ ownerRefusal,
87
88
  ownerRootCommand,
88
89
  } from "../core/discord/owner-command.ts";
89
90
  export type { PanelContent } from "../core/discord/owner-panel.ts";
@@ -144,3 +145,13 @@ export type {
144
145
  export { VOICE_PCM } from "../core/discord/voice/voice.ts";
145
146
  export type { OwnerOperations } from "../core/modules/discord-admin/discord-admin.ts";
146
147
  export { DISCORD_ADMIN_TOOLS } from "../core/modules/discord-admin/discord-admin.ts";
148
+ export type {
149
+ AttachmentText,
150
+ AttachmentTextErrorCode,
151
+ AttachmentTextRequest,
152
+ } from "../core/shared/attachment-text.ts";
153
+ export {
154
+ ATTACHMENT_TEXT_LIMIT,
155
+ AttachmentTextError,
156
+ readAttachmentText,
157
+ } from "../core/shared/attachment-text.ts";