pi-roundtable 0.50.2 → 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.
@@ -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
 
@@ -34,6 +34,11 @@ export interface CardChannel {
34
34
  send(payload: CardPayload): Promise<CardMessage>;
35
35
  /** A thread, where those a card is for are mentioned so they hear of it; a channel mentions no one. */
36
36
  thread?: boolean;
37
+ /**
38
+ * The thread's parent and its kind, read as the card is posted, so a press never waits on
39
+ * Discord to learn it; absent outside a thread.
40
+ */
41
+ parent?: InboundMessage["thread"];
37
42
  }
38
43
 
39
44
  /** A turn a card answered after its turn stopped waiting starts, as a message in its channel. */
@@ -88,8 +93,12 @@ export interface OpenCard {
88
93
  form?: QuestionnaireForm;
89
94
  /** The questions whose previews the Previews button shows, on a card that is not a questionnaire card. */
90
95
  previews?: Questionnaire;
91
- /** Options chosen together with "Other…", kept while its form is open. */
92
- picked?: string[];
96
+ /** Options each user chose together with "Other…", by user id, kept while their form is open. */
97
+ picked: Map<string, string[]>;
98
+ /** The footer the card shows while open, to draw it again unanswered. */
99
+ footer: string;
100
+ /** The thread the card was posted in and its parent, as its channel said when it was posted. */
101
+ thread?: InboundMessage["thread"];
93
102
  /** Posted in a thread, so it leads with the mention of who may answer. */
94
103
  mention?: boolean;
95
104
  /** Who may answer, and what to tell someone else who presses it. */
@@ -53,10 +53,15 @@ export function press(
53
53
  fields?: Record<string, string>;
54
54
  /** Holds `deferUpdate` until it resolves, so the card can change while the press is in flight. */
55
55
  gate?: Promise<void>;
56
- /** The thread the card sits in: its parent and the parent's kind. */
57
- thread?: { parentId: string; forum: boolean };
56
+ /**
57
+ * The thread the card sits in: its parent and the parent's kind. `uncached` leaves the parent
58
+ * out of the client's cache, so reading it is a fetch that never resolves.
59
+ */
60
+ thread?: { parentId: string; forum: boolean; uncached?: boolean };
58
61
  } = {},
59
62
  ) {
63
+ /** Every response and fetch the press made, in the order it was called (not settled). */
64
+ const calls: string[] = [];
60
65
  const replies: string[] = [];
61
66
  /** Everything a reply carried besides its text. */
62
67
  const replied: { files?: unknown[]; flags?: unknown }[] = [];
@@ -66,6 +71,10 @@ export function press(
66
71
  const edited: CardPayload[] = [];
67
72
  const followUps: { content?: string; flags?: unknown }[] = [];
68
73
  const deferred: string[] = [];
74
+ /** The card as the press drew it, by `update` or, once deferred, `editReply`, in order. */
75
+ const drawn: CardPayload[] = [];
76
+ /** What the press told its presser alone, by `reply` or, once deferred, `followUp`, in order. */
77
+ const notices: (string | undefined)[] = [];
69
78
  // SAFETY: the cards read only these members of an interaction.
70
79
  const interaction = {
71
80
  isButton: () => kind === "button",
@@ -80,10 +89,20 @@ export function press(
80
89
  ? {
81
90
  isThread: () => true,
82
91
  parentId: options.thread.parentId,
83
- parent: {
84
- type: options.thread.forum
85
- ? ChannelType.GuildForum
86
- : ChannelType.GuildText,
92
+ parent: options.thread.uncached
93
+ ? null
94
+ : {
95
+ type: options.thread.forum
96
+ ? ChannelType.GuildForum
97
+ : ChannelType.GuildText,
98
+ },
99
+ guild: {
100
+ channels: {
101
+ fetch: () => {
102
+ calls.push("fetch");
103
+ return new Promise(() => {});
104
+ },
105
+ },
87
106
  },
88
107
  }
89
108
  : null,
@@ -101,28 +120,39 @@ export function press(
101
120
  files?: unknown[];
102
121
  flags?: unknown;
103
122
  }) => {
123
+ calls.push("reply");
104
124
  replies.push(answer.content);
125
+ notices.push(answer.content);
105
126
  replied.push(answer);
106
127
  },
107
128
  update: async (payload: CardPayload) => {
129
+ calls.push("update");
108
130
  updates.push(payload);
131
+ drawn.push(payload);
109
132
  },
110
133
  showModal: async (modal: unknown) => {
134
+ calls.push("showModal");
111
135
  modals.push(modal);
112
136
  },
113
137
  deferUpdate: async () => {
138
+ calls.push("deferUpdate");
114
139
  await options.gate;
115
140
  deferred.push("update");
116
141
  },
117
142
  editReply: async (payload: CardPayload) => {
143
+ calls.push("editReply");
118
144
  edited.push(payload);
145
+ drawn.push(payload);
119
146
  },
120
147
  followUp: async (answer: { content?: string; flags?: unknown }) => {
148
+ calls.push("followUp");
121
149
  followUps.push(answer);
150
+ notices.push(answer.content);
122
151
  },
123
152
  } as unknown as Interaction;
124
153
  return {
125
154
  interaction,
155
+ calls,
126
156
  replies,
127
157
  replied,
128
158
  updates,
@@ -130,6 +160,8 @@ export function press(
130
160
  edited,
131
161
  followUps,
132
162
  deferred,
163
+ drawn,
164
+ notices,
133
165
  };
134
166
  }
135
167
 
@@ -1,5 +1,12 @@
1
1
  import { randomUUID } from "node:crypto";
2
- import { type Interaction, MessageFlags, TextDisplayBuilder } from "discord.js";
2
+ import {
3
+ type ButtonInteraction,
4
+ type Interaction,
5
+ MessageFlags,
6
+ type ModalSubmitInteraction,
7
+ type StringSelectMenuInteraction,
8
+ TextDisplayBuilder,
9
+ } from "discord.js";
3
10
  import { parseChannelKey } from "../contract/surface.ts";
4
11
  import type { ChannelKey } from "../domain/conversation.ts";
5
12
  import { messages } from "../i18n/index.ts";
@@ -12,7 +19,7 @@ import type { Logger } from "../kernel/log.ts";
12
19
  import { type CardAudienceOptions, CardAudiences } from "./card-audience.ts";
13
20
  import { CardCopies, copyReply, offeredCopy } from "./card-copies.ts";
14
21
  import { DiscordOwners, discordUser } from "./discord-owners.ts";
15
- import { threadOf } from "./inbound-message.ts";
22
+ import { cachedThreadOf } from "./inbound-message.ts";
16
23
  import type { InteractionModule } from "./interaction-module.ts";
17
24
  import {
18
25
  answerDeferred,
@@ -21,6 +28,11 @@ import {
21
28
  showPreviews,
22
29
  } from "./owner-card-answers.ts";
23
30
  import { askPrompts } from "./owner-card-asks.ts";
31
+ import {
32
+ answerApproval,
33
+ cancelQuestion,
34
+ onFirstResponse,
35
+ } from "./owner-card-press.ts";
24
36
  import {
25
37
  approvalRows,
26
38
  CARD_PREFIX,
@@ -274,6 +286,8 @@ export class OwnerCards implements InteractionModule {
274
286
  timer = arm();
275
287
  },
276
288
  audience: card.audience,
289
+ picked: new Map(),
290
+ footer: card.footer,
277
291
  end: (value, by) => {
278
292
  // Withdrawn or answered already: this answer changes nothing.
279
293
  if (!this.#open.has(id)) return false;
@@ -314,6 +328,7 @@ export class OwnerCards implements InteractionModule {
314
328
  .channel(channelId)
315
329
  .then((channel) => {
316
330
  open.mention = channel.thread === true;
331
+ if (channel.parent) open.thread = channel.parent;
317
332
  return channel.send(view(card.footer, false));
318
333
  })
319
334
  .then((posted) => {
@@ -360,6 +375,37 @@ export class OwnerCards implements InteractionModule {
360
375
  const [id = "", action = "", index = ""] = interaction.customId
361
376
  .slice(CARD_PREFIX.length)
362
377
  .split(":");
378
+ const started = performance.now();
379
+ let firstResponseMs: number | undefined;
380
+ onFirstResponse(interaction, () => {
381
+ firstResponseMs = Math.round(performance.now() - started);
382
+ });
383
+ try {
384
+ await this.#press(interaction, id, action, Number(index));
385
+ } finally {
386
+ // Which card and control, and how soon Discord heard back; never what was answered.
387
+ this.#options.logger.debug(
388
+ { cardId: id, action, firstResponseMs },
389
+ "card press",
390
+ );
391
+ }
392
+ return true;
393
+ }
394
+
395
+ /**
396
+ * One press of a card's control. Its first response to Discord comes before anything that can
397
+ * take a while: a press that opens a form shows it at once, and every other one is answered or
398
+ * deferred before the audience, the thread or anything else is read.
399
+ */
400
+ async #press(
401
+ interaction:
402
+ | ButtonInteraction
403
+ | StringSelectMenuInteraction
404
+ | ModalSubmitInteraction,
405
+ id: string,
406
+ action: string,
407
+ index: number,
408
+ ): Promise<void> {
363
409
  // Copying answers nothing: anyone who sees the card may copy, as often as they like, also
364
410
  // once the card has ended or the process restarted.
365
411
  if (interaction.isButton() && action === "copy") {
@@ -369,7 +415,7 @@ export class OwnerCards implements InteractionModule {
369
415
  ? { content: messages().cardCopyGone, flags: MessageFlags.Ephemeral }
370
416
  : copyReply(text),
371
417
  );
372
- return true;
418
+ return;
373
419
  }
374
420
  const card = this.#open.get(id);
375
421
  if (!card) {
@@ -377,14 +423,12 @@ export class OwnerCards implements InteractionModule {
377
423
  content: messages().cardInactive,
378
424
  flags: MessageFlags.Ephemeral,
379
425
  });
380
- return true;
381
- }
382
- if (action === "previews") {
383
- await showPreviews(card, interaction);
384
- return true;
426
+ return;
385
427
  }
428
+ if (action === "previews") return showPreviews(card, interaction);
386
429
  const user = discordUser(interaction);
387
- const thread = await threadOf(interaction.channel);
430
+ // The thread as it was when the card was posted, else the client's cache: never a fetch.
431
+ const thread = card.thread ?? cachedThreadOf(interaction.channel);
388
432
  const by: Answerer = {
389
433
  user,
390
434
  ...(interaction.message ? { messageId: interaction.message.id } : {}),
@@ -392,67 +436,20 @@ export class OwnerCards implements InteractionModule {
392
436
  isDirect: !interaction.inGuild(),
393
437
  ...(thread ? { thread } : {}),
394
438
  };
395
- // A menu pick or Submit is deferred before the audience is looked up, which may take a while.
396
- if (
397
- card.form &&
398
- (action === "qpick" || action === "submit" || action === "qtext")
399
- ) {
400
- await answerDeferred(card, action, Number(index), interaction, by);
401
- return true;
402
- }
403
- if (!(await card.audience.allows(user))) {
404
- await interaction.reply({
405
- content: card.audience.refusal,
406
- flags: MessageFlags.Ephemeral,
407
- });
408
- return true;
409
- }
410
- if (interaction.isButton() && (action === "yes" || action === "no")) {
411
- const approved = action === "yes";
412
- const approver = approved
413
- ? await card.audience.approver?.(user).catch((error: unknown) => {
414
- this.#options.logger.warn(
415
- { err: error },
416
- "could not tell who approved; the call runs without an approver",
417
- );
418
- return undefined;
419
- })
420
- : undefined;
421
- const accepted = card.end(
422
- approved ? "approved" : "declined",
423
- approver ? { ...by, approver } : by,
424
- );
425
- // The plugin withdrew the call, or another press answered, while this one was being checked.
426
- if (!accepted) {
427
- await interaction.reply({
428
- content: messages().cardInactive,
429
- flags: MessageFlags.Ephemeral,
430
- });
431
- return true;
432
- }
433
- await interaction.update(
434
- card.view(
435
- approved
436
- ? (card.outcomes?.approved ?? messages().cardApproved)
437
- : (card.outcomes?.declined ?? messages().cardDeclined),
438
- ),
439
+ if (interaction.isButton() && (action === "yes" || action === "no"))
440
+ return answerApproval(
441
+ card,
442
+ action === "yes",
443
+ interaction,
444
+ user,
445
+ by,
446
+ this.#options.logger,
439
447
  );
440
- return true;
441
- }
442
- if (interaction.isButton() && action === "cancel") {
443
- // Another press, a stop or a withdrawal ended it while this one was being checked.
444
- if (!card.decline()) {
445
- await interaction.reply({
446
- content: messages().cardInactive,
447
- flags: MessageFlags.Ephemeral,
448
- });
449
- return true;
450
- }
451
- await interaction.update(card.view(messages().cardQuestionCancelled));
452
- return true;
453
- }
454
- if (card.form) await answerForm(card, id, action, interaction);
455
- else await answerSingle(card, id, action, interaction, by);
456
- return true;
448
+ if (interaction.isButton() && action === "cancel")
449
+ return cancelQuestion(card, interaction, user);
450
+ if (!card.form) return answerSingle(card, id, action, interaction, by);
451
+ if (action === "qpick" || action === "submit" || action === "qtext")
452
+ return answerDeferred(card, action, index, interaction, by);
453
+ return answerForm(card, id, action, interaction, by);
457
454
  }
458
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;
@@ -173,6 +173,9 @@ function discordAssembly(
173
173
  ...(discord.voice ? { voice: true } : {}),
174
174
  cardGraceMs: discord.cardGraceSeconds * 1_000,
175
175
  cardCopies: discord.cardCopies,
176
+ ...(discord.attachmentRead
177
+ ? { attachmentRead: discord.attachmentRead }
178
+ : {}),
176
179
  }),
177
180
  admin: discord.admin ? [discordAdminPlugin({ owner })] : [],
178
181
  };
@@ -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
  }