pi-roundtable 0.50.2 → 0.51.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -32,15 +32,7 @@ export type ContextSourceMessage = ChannelContextSource;
32
32
  /** A file attached to a fetched message, as Discord describes it. */
33
33
  export type ContextSourceAttachment = ChannelContextSourceAttachment;
34
34
 
35
- function attachmentLabel(contentType: string | null | undefined): string {
36
- const type = contentType ?? "";
37
- if (type.startsWith("image/")) return "image";
38
- if (type.startsWith("video/")) return "video";
39
- if (type.startsWith("audio/")) return "audio";
40
- return "file";
41
- }
42
-
43
- /** The facts of a fetched Discord message channel context reads: mentions by name, stickers and files as text, never their bytes. */
35
+ /** The facts of a fetched Discord message channel context reads: mentions by name and stickers as text, its files described, never their bytes. */
44
36
  export function contextSourceOf(
45
37
  message: Message,
46
38
  { botId, applicationId }: BotIdentity,
@@ -55,10 +47,6 @@ export function contextSourceOf(
55
47
  const parts = [text.trim(), embeds].filter(Boolean);
56
48
  for (const sticker of message.stickers.values())
57
49
  parts.push(`[sticker: ${sticker.name}]`);
58
- for (const file of message.attachments.values())
59
- parts.push(
60
- `[${attachmentLabel(file.contentType)}: ${file.name} ${file.url}]`,
61
- );
62
50
  const ownWebhook =
63
51
  message.webhookId !== null &&
64
52
  message.applicationId !== null &&
@@ -78,7 +66,10 @@ export function contextSourceOf(
78
66
  at: message.createdTimestamp,
79
67
  text: parts.join(" "),
80
68
  attachments: [...message.attachments.values()].map((file) => ({
69
+ id: file.id,
81
70
  name: file.name,
71
+ ...(file.title ? { title: file.title } : {}),
72
+ ...(file.description ? { description: file.description } : {}),
82
73
  contentType: file.contentType ?? "",
83
74
  size: file.size,
84
75
  url: file.url,
@@ -111,9 +102,22 @@ function similarity(a: string, b: string): number {
111
102
  return longest / longer.length;
112
103
  }
113
104
 
105
+ /** Whether two messages carry the same files, by name and size: a repost's files have new ids. */
106
+ function sameFiles(a: ContextSourceMessage, b: ContextSourceMessage): boolean {
107
+ const files = (message: ContextSourceMessage) =>
108
+ (message.attachments ?? []).map((file) => `${file.name}\u0000${file.size}`);
109
+ const [x, y] = [files(a), files(b)];
110
+ return x.length === y.length && x.every((file, i) => file === y[i]);
111
+ }
112
+
113
+ /** A message that says something: text, or a file. */
114
+ const saysSomething = (message: ContextSourceMessage) =>
115
+ message.text !== "" || (message.attachments?.length ?? 0) > 0;
116
+
114
117
  /**
115
- * Consecutive messages of one author at least `threshold` alike become the later one. A `foreign`
116
- * message is one of a webhook that carries many people, so it also needs the same name.
118
+ * Consecutive messages of one author at least `threshold` alike, with the same files, become the
119
+ * later one. A `foreign` message is one of a webhook that carries many people, so it also needs
120
+ * the same name.
117
121
  */
118
122
  function merged(
119
123
  messages: readonly ContextSourceMessage[],
@@ -127,6 +131,7 @@ function merged(
127
131
  last &&
128
132
  last.authorId === message.authorId &&
129
133
  (!foreign(message) || last.authorName === message.authorName) &&
134
+ sameFiles(last, message) &&
130
135
  similarity(last.text, message.text) >= threshold
131
136
  )
132
137
  out[out.length - 1] = message;
@@ -150,7 +155,7 @@ export interface ChannelContextSelection {
150
155
  /**
151
156
  * The thread's opening message when `ChannelContextOptions.starter` asked for it: it comes first,
152
157
  * outside `keep`, whether or not the fetched window holds it, unless a filter drops it (the
153
- * `authors` verdict, the assistant's own post, an empty text, a message delivered before).
158
+ * `authors` verdict, the assistant's own post, a message with neither text nor files, a message delivered before).
154
159
  */
155
160
  starter?: ContextSourceMessage;
156
161
  /** What the selection reads of the settings; without `foreignWebhook` every webhook of the application is the assistant's. */
@@ -186,7 +191,7 @@ function limitOf(
186
191
 
187
192
  /**
188
193
  * The window of fetched messages (all before the addressed one): those after the assistant's
189
- * latest post, without its own posts, those already delivered, and empty ones; near repeats merged,
194
+ * latest post, without its own posts, those already delivered, and those with neither text nor files; near repeats merged,
190
195
  * the newest `keep`, oldest first. `window` is every message it considered, kept or not.
191
196
  */
192
197
  export function selectChannelContext(
@@ -224,7 +229,7 @@ export function selectChannelContext(
224
229
  const opening =
225
230
  starter &&
226
231
  !seen.has(starter.id) &&
227
- starter.text !== "" &&
232
+ saysSomething(starter) &&
228
233
  verdict(starter) === "keep"
229
234
  ? [{ ...starter, text: cut(starter.text, limitOf(starter, selection)) }]
230
235
  : [];
@@ -237,7 +242,7 @@ export function selectChannelContext(
237
242
  message.id !== starter?.id &&
238
243
  !assistants(message) &&
239
244
  !seen.has(message.id) &&
240
- message.text !== "",
245
+ saysSomething(message),
241
246
  )
242
247
  .map((message) => ({
243
248
  ...message,
@@ -28,7 +28,7 @@ const DEADLINE_MS = 20_000;
28
28
  const CONCURRENCY = 2;
29
29
 
30
30
  /** The bytes of a response, or undefined once they pass `max`. */
31
- async function boundedBody(
31
+ export async function boundedBody(
32
32
  response: Response,
33
33
  max: number,
34
34
  ): Promise<Uint8Array | undefined> {
@@ -46,7 +46,7 @@ import { readMessagesBefore, readThreadStarter } from "./context-reading.ts";
46
46
  import { DiscordThreadHost } from "./dispatch-thread-host.ts";
47
47
  import { DISCORD_FORMATTING, pickFormatting } from "./formatting.ts";
48
48
  import { DEFAULT_FRESH_MARKER, postFreshMarker } from "./fresh-marker.ts";
49
- import { lateAnswerMessage } from "./inbound-message.ts";
49
+ import { lateAnswerMessage, threadOf } from "./inbound-message.ts";
50
50
  import type { IntercomTexts } from "./intercom-cards.ts";
51
51
  import {
52
52
  explainIntents,
@@ -409,8 +409,10 @@ export class DiscordSurface
409
409
  /** Where the owner's cards in a channel are posted. */
410
410
  async cardChannel(channelId: string): Promise<CardChannel> {
411
411
  const target = await this.#sendable(`${PREFIX}${channelId}`);
412
+ const parent = await threadOf(target);
412
413
  return {
413
414
  thread: target.isThread(),
415
+ ...(parent ? { parent } : {}),
414
416
  send: async (payload) => {
415
417
  const message = await target.send(payload);
416
418
  return { edit: (change) => message.edit(change) };
@@ -18,14 +18,20 @@ export interface BotIdentity {
18
18
  applicationId: string | undefined;
19
19
  }
20
20
 
21
+ /** The files of `message`, carried by the message `carrier` (a forward's by the forwarding message). */
21
22
  function attachmentRefs(
22
23
  message: Pick<Message, "attachments">,
24
+ carrier: string,
23
25
  ): AttachmentRef[] {
24
26
  return [...message.attachments.values()].map((attachment) => ({
25
27
  url: attachment.url,
26
28
  name: attachment.name,
27
29
  ...(attachment.contentType ? { contentType: attachment.contentType } : {}),
28
30
  size: attachment.size,
31
+ id: attachment.id,
32
+ messageId: carrier,
33
+ ...(attachment.title ? { title: attachment.title } : {}),
34
+ ...(attachment.description ? { description: attachment.description } : {}),
29
35
  }));
30
36
  }
31
37
 
@@ -34,7 +40,7 @@ function referenceOf(referenced: Message, mention: RegExp) {
34
40
  text: withEmbeds(referenced.content, referenced.embeds)
35
41
  .replace(mention, "")
36
42
  .trim(),
37
- attachments: attachmentRefs(referenced),
43
+ attachments: attachmentRefs(referenced, referenced.id),
38
44
  authorId: referenced.author.id,
39
45
  ...(referenced.webhookId
40
46
  ? { webhookName: referenced.author.username }
@@ -42,16 +48,12 @@ function referenceOf(referenced: Message, mention: RegExp) {
42
48
  };
43
49
  }
44
50
 
45
- /** What a thread's parent is: a text channel, a forum, or something else (also a parent that cannot be read). */
46
- export async function threadOf(
47
- channel: Channel | null | undefined,
48
- ): Promise<InboundMessage["thread"] | undefined> {
49
- if (!channel?.isThread() || !channel.parentId) return undefined;
50
- const parent =
51
- channel.parent ??
52
- (await channel.guild.channels.fetch(channel.parentId).catch(() => null));
51
+ function threadFacts(
52
+ parentId: string,
53
+ parent: Pick<Channel, "type"> | null | undefined,
54
+ ): NonNullable<InboundMessage["thread"]> {
53
55
  return {
54
- parentId: channel.parentId,
56
+ parentId,
55
57
  parentKind:
56
58
  parent?.type === ChannelType.GuildText
57
59
  ? "text"
@@ -61,6 +63,28 @@ export async function threadOf(
61
63
  };
62
64
  }
63
65
 
66
+ /** What a thread's parent is: a text channel, a forum, or something else (also a parent that cannot be read). */
67
+ export async function threadOf(
68
+ channel: Channel | null | undefined,
69
+ ): Promise<InboundMessage["thread"] | undefined> {
70
+ if (!channel?.isThread() || !channel.parentId) return undefined;
71
+ const parent =
72
+ channel.parent ??
73
+ (await channel.guild.channels.fetch(channel.parentId).catch(() => null));
74
+ return threadFacts(channel.parentId, parent);
75
+ }
76
+
77
+ /**
78
+ * `threadOf` from the client's cache alone, never fetching: for an interaction, which must answer
79
+ * Discord within three seconds. A parent that is not cached reads as "other".
80
+ */
81
+ export function cachedThreadOf(
82
+ channel: Channel | null | undefined,
83
+ ): InboundMessage["thread"] | undefined {
84
+ if (!channel?.isThread() || !channel.parentId) return undefined;
85
+ return threadFacts(channel.parentId, channel.parent);
86
+ }
87
+
64
88
  /**
65
89
  * The facts of one Discord message, as the neutral `InboundMessage`; undefined for the bot's own
66
90
  * messages and before the client is ready. A forward reports the channel it came from as a
@@ -132,8 +156,8 @@ export async function toInbound(
132
156
  .replace(mention, "")
133
157
  .trim(),
134
158
  attachments: [
135
- ...attachmentRefs(message),
136
- ...(forward ? attachmentRefs(forward) : []),
159
+ ...attachmentRefs(message, message.id),
160
+ ...(forward ? attachmentRefs(forward, message.id) : []),
137
161
  ],
138
162
  ...(forward && reference?.channelId
139
163
  ? {
@@ -23,7 +23,12 @@ const ephemeral = (content: string) => ({
23
23
  flags: MessageFlags.Ephemeral as const,
24
24
  });
25
25
 
26
- /** The single-question card's controls: a menu pick, "Write answer…", and the answer form. */
26
+ /**
27
+ * The single-question card's controls: a menu pick, "Write answer…", and the answer form. A press
28
+ * that opens the form shows it at once, before anything is read (Discord takes no deferral in
29
+ * front of a form); whoever submits it is checked then. Any other press is deferred before the
30
+ * audience is read, and someone the card is not for is told so with the card unchanged.
31
+ */
27
32
  export async function answerSingle(
28
33
  card: OpenCard,
29
34
  id: string,
@@ -33,8 +38,9 @@ export async function answerSingle(
33
38
  ): Promise<void> {
34
39
  const question = card.question;
35
40
  if (!question) return;
41
+ const userId = by.user.id;
36
42
  if (interaction.isButton() && action === "write") {
37
- card.picked = [];
43
+ card.picked.set(userId, []);
38
44
  await interaction.showModal(answerModal(id));
39
45
  return;
40
46
  }
@@ -44,24 +50,42 @@ export async function answerSingle(
44
50
  values.includes(String(i)) ? [option.label] : [],
45
51
  );
46
52
  if (values.includes(OTHER)) {
47
- card.picked = choices;
53
+ card.picked.set(userId, choices);
48
54
  await interaction.showModal(answerModal(id));
49
55
  return;
50
56
  }
57
+ await interaction.deferUpdate();
58
+ if (!(await card.audience.allows(by.user))) {
59
+ await interaction.followUp(ephemeral(card.audience.refusal));
60
+ // Their menu shows the refused pick until the card is drawn again.
61
+ if (card.isOpen())
62
+ await interaction.editReply(card.view(card.footer, false));
63
+ return;
64
+ }
51
65
  const answer = { choices };
52
- card.end(answer, by);
53
- await interaction.update(card.view(answeredLine(answer)));
66
+ if (!card.end(answer, by)) {
67
+ await interaction.followUp(ephemeral(messages().cardInactive));
68
+ return;
69
+ }
70
+ await interaction.editReply(card.view(answeredLine(answer)));
54
71
  return;
55
72
  }
56
73
  if (interaction.isModalSubmit() && action === "text") {
74
+ await interaction.deferUpdate();
75
+ if (!(await card.audience.allows(by.user))) {
76
+ await interaction.followUp(ephemeral(card.audience.refusal));
77
+ return;
78
+ }
57
79
  const answer = {
58
- choices: card.picked ?? [],
80
+ choices: card.picked.get(userId) ?? [],
59
81
  text: interaction.fields.getTextInputValue(TEXT_FIELD),
60
82
  };
61
- card.end(answer, by);
83
+ if (!card.end(answer, by)) {
84
+ await interaction.followUp(ephemeral(messages().cardInactive));
85
+ return;
86
+ }
62
87
  if (interaction.isFromMessage())
63
- await interaction.update(card.view(answeredLine(answer)));
64
- else await interaction.deferUpdate();
88
+ await interaction.editReply(card.view(answeredLine(answer)));
65
89
  }
66
90
  }
67
91
 
@@ -164,7 +188,10 @@ export async function answerDeferred(
164
188
  await interaction.editReply(card.view(endedFooter(card)));
165
189
  }
166
190
 
167
- /** "Write answers / note…": opens the form, which a modal cannot defer; the audience was checked. */
191
+ /**
192
+ * "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`).
194
+ */
168
195
  export async function answerForm(
169
196
  card: OpenCard,
170
197
  id: string,
@@ -0,0 +1,108 @@
1
+ import { type Interaction, MessageFlags } from "discord.js";
2
+ import { messages } from "../i18n/index.ts";
3
+ import type { Logger } from "../kernel/log.ts";
4
+ import type { DiscordUser } from "./discord-owners.ts";
5
+ import type { Answerer, OpenCard } from "./owner-card-types.ts";
6
+
7
+ const ephemeral = (content: string) => ({
8
+ content,
9
+ flags: MessageFlags.Ephemeral as const,
10
+ });
11
+
12
+ /** The interaction methods one of which is a press's first response to Discord. */
13
+ const RESPONSES = [
14
+ "reply",
15
+ "update",
16
+ "showModal",
17
+ "deferUpdate",
18
+ "deferReply",
19
+ ] as const;
20
+
21
+ /**
22
+ * Calls `first` once, as the press makes its first response to Discord, whichever it is. Discord
23
+ * drops a press with no response within three seconds ("This interaction failed"), so this is
24
+ * what the card's press log times.
25
+ */
26
+ export function onFirstResponse(
27
+ interaction: Interaction,
28
+ first: () => void,
29
+ ): void {
30
+ let called = false;
31
+ const target = interaction as unknown as Record<string, unknown>;
32
+ for (const name of RESPONSES) {
33
+ const method = target[name];
34
+ if (typeof method !== "function") continue;
35
+ target[name] = (...args: unknown[]) => {
36
+ if (!called) {
37
+ called = true;
38
+ first();
39
+ }
40
+ return (method as (...a: unknown[]) => unknown).apply(interaction, args);
41
+ };
42
+ }
43
+ }
44
+
45
+ /**
46
+ * Approve or Decline on an approval card. The press is deferred before the audience and the
47
+ * approver are read, which may take a while; someone else is told so and the card is unchanged.
48
+ */
49
+ export async function answerApproval(
50
+ card: OpenCard,
51
+ approved: boolean,
52
+ interaction: Interaction,
53
+ user: DiscordUser,
54
+ by: Answerer,
55
+ logger: Logger,
56
+ ): Promise<void> {
57
+ if (!interaction.isButton()) return;
58
+ await interaction.deferUpdate();
59
+ if (!(await card.audience.allows(user))) {
60
+ await interaction.followUp(ephemeral(card.audience.refusal));
61
+ return;
62
+ }
63
+ const approver = approved
64
+ ? await card.audience.approver?.(user).catch((error: unknown) => {
65
+ logger.warn(
66
+ { err: error },
67
+ "could not tell who approved; the call runs without an approver",
68
+ );
69
+ return undefined;
70
+ })
71
+ : undefined;
72
+ const accepted = card.end(
73
+ approved ? "approved" : "declined",
74
+ approver ? { ...by, approver } : by,
75
+ );
76
+ // The plugin withdrew the call, or another press answered, while this one was being checked.
77
+ if (!accepted) {
78
+ await interaction.followUp(ephemeral(messages().cardInactive));
79
+ return;
80
+ }
81
+ await interaction.editReply(
82
+ card.view(
83
+ approved
84
+ ? (card.outcomes?.approved ?? messages().cardApproved)
85
+ : (card.outcomes?.declined ?? messages().cardDeclined),
86
+ ),
87
+ );
88
+ }
89
+
90
+ /** A question card's Cancel, deferred before the audience is read. */
91
+ export async function cancelQuestion(
92
+ card: OpenCard,
93
+ interaction: Interaction,
94
+ user: DiscordUser,
95
+ ): Promise<void> {
96
+ if (!interaction.isButton()) return;
97
+ await interaction.deferUpdate();
98
+ if (!(await card.audience.allows(user))) {
99
+ await interaction.followUp(ephemeral(card.audience.refusal));
100
+ return;
101
+ }
102
+ // Another press, a stop or a withdrawal ended it while this one was being checked.
103
+ if (!card.decline()) {
104
+ await interaction.followUp(ephemeral(messages().cardInactive));
105
+ return;
106
+ }
107
+ await interaction.editReply(card.view(messages().cardQuestionCancelled));
108
+ }
@@ -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