pi-roundtable 0.51.0 → 0.51.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -5,6 +5,16 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
5
5
 
6
6
  ## [Unreleased]
7
7
 
8
+ ## [0.51.1] - 2026-11-17
9
+
10
+ ### Fixed
11
+
12
+ - 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).
13
+ - `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.
14
+ - 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.
15
+ - 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`.
16
+ - `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`.
17
+
8
18
  ## [0.51.0] - 2026-11-17
9
19
 
10
20
  ### 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,23 @@ 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
+ 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.
2964
+
2965
+ ```ts
2966
+ import { AttachmentTextError, readAttachmentText } from "pi-roundtable/discord";
2967
+
2968
+ const piece = await readAttachmentText({ ...read, offset: 0 });
2969
+ // piece.nextOffset, when set, is the offset of the next piece
2970
+ ```
2971
+
2959
2972
  ### Posting through `DISCORD.poster`
2960
2973
 
2961
2974
  `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 +5208,11 @@ Import from the entries listed below; source area files are internal.
5195
5208
  | `AttachmentReadError` | `pi-roundtable/discord` | value |
5196
5209
  | `AttachmentReadErrorCode` | `pi-roundtable/discord` | type |
5197
5210
  | `AttachmentReadRequest` | `pi-roundtable/discord` | type |
5211
+ | `ATTACHMENT_TEXT_LIMIT` | `pi-roundtable/discord` | value |
5212
+ | `AttachmentText` | `pi-roundtable/discord` | type |
5213
+ | `AttachmentTextError` | `pi-roundtable/discord` | value |
5214
+ | `AttachmentTextErrorCode` | `pi-roundtable/discord` | type |
5215
+ | `AttachmentTextRequest` | `pi-roundtable/discord` | type |
5198
5216
  | `CHANNEL_CONTEXT_DEFAULTS` | `pi-roundtable/discord` | value |
5199
5217
  | `CONTEXT_ATTACHMENT_LINES` | `pi-roundtable/discord` | value |
5200
5218
  | `CHANNEL_OPERATIONS` | `pi-roundtable/discord` | value |
@@ -5288,9 +5306,11 @@ Import from the entries listed below; source area files are internal.
5288
5306
  | `ownerCommandModule` | `pi-roundtable/discord` | value |
5289
5307
  | `ownerPanel` | `pi-roundtable/discord` | value |
5290
5308
  | `ownerPanels` | `pi-roundtable/discord` | value |
5309
+ | `ownerRefusal` | `pi-roundtable/discord` | value |
5291
5310
  | `ownerRootCommand` | `pi-roundtable/discord` | value |
5292
5311
  | `parseChannelTool` | `pi-roundtable/discord` | value |
5293
5312
  | `plain` | `pi-roundtable/discord` | value |
5313
+ | `readAttachmentText` | `pi-roundtable/discord` | value |
5294
5314
  | `replyWithPanels` | `pi-roundtable/discord` | value |
5295
5315
  | `withChannelContext` | `pi-roundtable/discord` | value |
5296
5316
  | `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.1",
4
4
  "description": "A plugin-driven Pi agent server for one owner, reached through Discord or the web",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -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,11 @@ export async function answerDeferred(
167
168
  const { texts, note } = formFields(form, (field) =>
168
169
  interaction.fields.getTextInputValue(field),
169
170
  );
171
+ const own: Written = { texts: [] };
170
172
  for (const [i, value] of texts)
171
- form.draft.texts[i] = value.trim() || undefined;
172
- form.draft.note = note.trim() || undefined;
173
+ form.draft.texts[i] = own.texts[i] = value.trim() || undefined;
174
+ form.draft.note = own.note = note.trim() || undefined;
175
+ form.written.set(by.user.id, own);
173
176
  }
174
177
  if (!submits) {
175
178
  card.touch();
@@ -190,18 +193,20 @@ export async function answerDeferred(
190
193
 
191
194
  /**
192
195
  * "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`).
196
+ * shown; the audience is checked when it is submitted (`answerDeferred`). The form holds only
197
+ * what this user wrote before, so it shows no one else's unsent text.
194
198
  */
195
199
  export async function answerForm(
196
200
  card: OpenCard,
197
201
  id: string,
198
202
  action: string,
199
203
  interaction: Interaction,
204
+ by: Answerer,
200
205
  ): Promise<void> {
201
206
  if (!card.form || !interaction.isButton() || action !== "notes") return;
202
207
  if (!card.isOpen()) {
203
208
  await interaction.reply(ephemeral(messages().cardInactive));
204
209
  return;
205
210
  }
206
- await interaction.showModal(questionnaireModal(id, card.form));
211
+ await interaction.showModal(questionnaireModal(id, card.form, by.user.id));
207
212
  }
@@ -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,17 @@ 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.
41
+ */
42
+ written: Map<string, Written>;
43
+ }
44
+
45
+ /** What one user wrote in the form. */
46
+ export interface Written {
47
+ texts: (string | undefined)[];
48
+ note?: string;
38
49
  }
39
50
 
40
51
  export const newDraft = (questions: number): Draft => ({
@@ -188,8 +199,13 @@ export function questionnaireCard(args: {
188
199
  }
189
200
 
190
201
  /** The form for what the menus cannot take: each question's own answer, and the note. */
191
- export function questionnaireModal(id: string, form: QuestionnaireForm) {
202
+ export function questionnaireModal(
203
+ id: string,
204
+ form: QuestionnaireForm,
205
+ userId: string,
206
+ ) {
192
207
  const { questions } = form.questionnaire;
208
+ const own = form.written.get(userId);
193
209
  const labelled = (
194
210
  label: string,
195
211
  field: string,
@@ -219,16 +235,11 @@ export function questionnaireModal(id: string, form: QuestionnaireForm) {
219
235
  questions.length === 1
220
236
  ? messages().cardModalField
221
237
  : `${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
- );
238
+ const field = labelled(label, `t${i}`, own?.texts[i], question.question);
228
239
  modal.addLabelComponents(field);
229
240
  }
230
241
  return modal.addLabelComponents(
231
- labelled(messages().cardNoteField, "note", form.draft.note),
242
+ labelled(messages().cardNoteField, "note", own?.note),
232
243
  );
233
244
  }
234
245
 
@@ -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,174 @@
1
+ import { extractText, getDocumentProxy } from "unpdf";
2
+ import { plainText } from "../attachments/attachment-name.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
+ function looksLikeText(bytes: Uint8Array): boolean {
56
+ const sample = bytes.subarray(0, 4096);
57
+ if (sample.includes(0)) return false;
58
+ try {
59
+ new TextDecoder("utf-8", { fatal: true }).decode(sample);
60
+ return true;
61
+ } catch {
62
+ return false;
63
+ }
64
+ }
65
+
66
+ /** A file to read as text: its name, its media type when known, and its bytes. */
67
+ export interface AttachmentTextRequest {
68
+ name: string;
69
+ contentType?: string | null;
70
+ bytes: Uint8Array;
71
+ /** The character to start from; default 0. */
72
+ offset?: number;
73
+ /** The most characters returned; default `ATTACHMENT_TEXT_LIMIT`, 60,000. */
74
+ limit?: number;
75
+ }
76
+
77
+ /** One piece of a file's text. */
78
+ export interface AttachmentText {
79
+ /** `pdf` when the text was extracted from a PDF, else `text`. */
80
+ kind: "text" | "pdf";
81
+ /** The characters from `offset`, at most `limit` of them; a PDF's text starts with `[PDF, <n> pages]`. */
82
+ text: string;
83
+ /** Where this piece starts. */
84
+ offset: number;
85
+ /** Where the next piece starts; absent when this piece reaches the end. */
86
+ nextOffset?: number;
87
+ /** Characters in the whole text. */
88
+ total: number;
89
+ /** A PDF's page count. */
90
+ pages?: number;
91
+ }
92
+
93
+ /**
94
+ * 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).
97
+ */
98
+ export type AttachmentTextErrorCode = "unsupported" | "unreadable" | "invalid";
99
+
100
+ /** What `readAttachmentText` rejects with; `message` names the file, never its bytes. */
101
+ export class AttachmentTextError extends Error {
102
+ readonly code: AttachmentTextErrorCode;
103
+ constructor(code: AttachmentTextErrorCode, message: string) {
104
+ super(message);
105
+ this.name = "AttachmentTextError";
106
+ this.code = code;
107
+ }
108
+ }
109
+
110
+ /**
111
+ * A file's bytes as text, one piece at a time: a text file is decoded as UTF-8, a PDF's text is
112
+ * extracted, and anything else is refused with an `AttachmentTextError`. It is how the core's
113
+ * `read_attachment` tool reads, so a plugin that has a file's bytes (for example from
114
+ * `DISCORD.readAttachment`) reads it the same way.
115
+ */
116
+ export async function readAttachmentText(
117
+ request: AttachmentTextRequest,
118
+ ): Promise<AttachmentText> {
119
+ const { name, bytes } = request;
120
+ const offset = request.offset ?? 0;
121
+ const limit = request.limit ?? ATTACHMENT_TEXT_LIMIT;
122
+ if (!Number.isInteger(offset) || offset < 0)
123
+ throw new AttachmentTextError(
124
+ "invalid",
125
+ "offset must be a whole number from 0",
126
+ );
127
+ if (!Number.isInteger(limit) || limit < 1)
128
+ throw new AttachmentTextError(
129
+ "invalid",
130
+ "limit must be a positive whole number",
131
+ );
132
+ const type = mediaType(request.contentType);
133
+ let kind: AttachmentText["kind"];
134
+ let text: string;
135
+ let pages: number | undefined;
136
+ if (isPdf(name, type, bytes)) {
137
+ let result: { totalPages: number; text: string };
138
+ try {
139
+ result = await extractText(await getDocumentProxy(bytes), {
140
+ mergePages: true,
141
+ });
142
+ } catch {
143
+ throw new AttachmentTextError(
144
+ "unreadable",
145
+ `"${plainText(name)}" could not be read as a PDF`,
146
+ );
147
+ }
148
+ kind = "pdf";
149
+ pages = result.totalPages;
150
+ text = `[PDF, ${result.totalPages} pages]\n${result.text}`;
151
+ } else if (
152
+ TEXT_EXTENSIONS.has(extension(name)) ||
153
+ type.startsWith("text/") ||
154
+ TEXT_TYPES.has(type) ||
155
+ looksLikeText(bytes)
156
+ ) {
157
+ kind = "text";
158
+ text = new TextDecoder().decode(bytes);
159
+ } else {
160
+ throw new AttachmentTextError(
161
+ "unsupported",
162
+ `"${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
+ );
164
+ }
165
+ const end = Math.min(text.length, offset + limit);
166
+ return {
167
+ kind,
168
+ text: text.slice(offset, end),
169
+ offset,
170
+ ...(end < text.length ? { nextOffset: end } : {}),
171
+ total: text.length,
172
+ ...(pages === undefined ? {} : { pages }),
173
+ };
174
+ }
@@ -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";