omp-superagent 0.1.1 → 0.1.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.
Files changed (60) hide show
  1. package/DESIGN.md +189 -48
  2. package/README.ko.md +30 -16
  3. package/README.md +39 -20
  4. package/THIRD_PARTY_NOTICES.md +81 -6
  5. package/docs/OPERATIONS.md +178 -30
  6. package/docs/discord-voice.md +96 -0
  7. package/docs/releases/0.1.2.md +53 -0
  8. package/package.json +13 -7
  9. package/scripts/ci.ts +10 -5
  10. package/scripts/release.ts +14 -6
  11. package/scripts/test-omp.sh +36 -0
  12. package/skills/head/SKILL.md +82 -241
  13. package/skills/head/references/model-selection.md +81 -261
  14. package/skills/head/references/routing.md +179 -354
  15. package/skills/head/references/supervision.md +120 -310
  16. package/skills/lane/SKILL.md +53 -175
  17. package/skills/lane/references/workflow.md +93 -347
  18. package/src/cli.ts +96 -10
  19. package/src/codex-live-bridge.py +73 -0
  20. package/src/codex-live.ts +244 -0
  21. package/src/codex-voice-requirements.txt +5 -0
  22. package/src/codex_live_auth.py +192 -0
  23. package/src/codex_live_media.py +219 -0
  24. package/src/codex_live_provider.py +192 -0
  25. package/src/config.ts +77 -2
  26. package/src/contracts.ts +70 -6
  27. package/src/decision-tool.ts +59 -0
  28. package/src/decisions.ts +143 -0
  29. package/src/delivery.ts +10 -0
  30. package/src/discord-context.ts +118 -0
  31. package/src/discord-voice-draft.ts +124 -0
  32. package/src/discord-voice-link.ts +270 -0
  33. package/src/discord-voice.ts +150 -0
  34. package/src/discord.ts +312 -45
  35. package/src/extension.ts +178 -21
  36. package/src/gateway-client.ts +11 -4
  37. package/src/gateway-server.ts +52 -4
  38. package/src/gateway-store.ts +16 -2
  39. package/src/gateway.ts +27 -11
  40. package/src/host-broker-services.ts +108 -0
  41. package/src/host-extension.ts +159 -47
  42. package/src/host-owner.ts +16 -0
  43. package/src/host-protocol.ts +9 -1
  44. package/src/host-services.ts +54 -0
  45. package/src/host.ts +3 -2
  46. package/src/installed-omp.ts +34 -26
  47. package/src/lane-extension.ts +5 -0
  48. package/src/lane-rows.ts +12 -0
  49. package/src/messengers.ts +38 -9
  50. package/src/native-presets.ts +91 -3
  51. package/src/native-settings.ts +3 -1
  52. package/src/openai-live.ts +377 -0
  53. package/src/pr-github-schema.ts +110 -0
  54. package/src/pr-github.ts +170 -0
  55. package/src/pr-watch.ts +200 -0
  56. package/src/runtime.ts +419 -54
  57. package/src/slack.ts +14 -11
  58. package/src/store.ts +86 -30
  59. package/src/telegram.ts +28 -12
  60. package/scripts/check-omp.ts +0 -4
package/src/discord.ts CHANGED
@@ -3,13 +3,18 @@ import {
3
3
  ActionRowBuilder, AttachmentBuilder, ButtonBuilder, ButtonStyle, ChannelFlagsBitField, ChannelType, Client,
4
4
  Events, GatewayIntentBits, MessageFlags, ModalBuilder, Partials, PermissionFlagsBits, StringSelectMenuBuilder,
5
5
  Routes, TextInputBuilder, TextInputStyle,
6
- type ChatInputCommandInteraction, type ForumChannel, type Interaction, type MediaChannel, type Message, type MessageCreateOptions, type PartialMessage,
6
+ type ChatInputCommandInteraction, type ForumChannel, type Interaction, type MediaChannel, type Message, type MessageCreateOptions, type PartialMessage, type PermissionsBitField,
7
7
  } from "discord.js";
8
- import { physicalRoute, physicalRouteKey, routeKey, type Approval, type Attachment, type DialogResponse, type Inbound, type MessageActivity, type MessageReference, type Messenger, type OutputRecord, type ReplyContext, type Route } from "./contracts.ts";
8
+ import { physicalRoute, physicalRouteKey, routeKey, type Approval, type Attachment, type DialogResponse, type DiscordContext, type DiscordPurposeNote, type DiscordPurposeRequest, type Inbound, type MessageActivity, type MessageReference, type Messenger, type OutputRecord, type ReplyContext, type Route, type StorePort, type ThreadInfo, type ThreadUpdate } from "./contracts.ts";
9
+ import { changeDiscordPurpose, discordPurposeNotes, discordPurposeRequest } from "./discord-context";
10
+ import { validateDecisionAnswer, validateDecisionResponse } from "./decisions";
9
11
  import { parseDialog, type Dialog } from "./dialog.ts";
10
- import { DeliveryError } from "./delivery.ts";
12
+ import { approvalCardToken, DeliveryError } from "./delivery.ts";
11
13
  import { parseDiscordCommand } from "./discord-commands.ts";
12
14
  import { renderDiscordMarkdown } from "./discord-markdown.ts";
15
+ import { DiscordVoice } from "./discord-voice";
16
+ import { VOICE_DRAFT_HEADER } from "./discord-voice-draft";
17
+ import type { DiscordVoiceConfig } from "./config";
13
18
 
14
19
  // Reference (not copied): gimso2x/ompbot @ 4d2eb28d0bf66644892dc0fc333580d0eb7e7780,
15
20
  // src/discord/{adapter,attachments,channel,transport}.ts (MIT, ompbot contributors).
@@ -18,6 +23,8 @@ import { renderDiscordMarkdown } from "./discord-markdown.ts";
18
23
  const NO_MENTIONS = { parse: [] as never[], repliedUser: false };
19
24
  const FILE_LIMIT = 8 * 1024 * 1024;
20
25
  const MESSAGE_LIMIT = 2000;
26
+ const SELECT_PAGE_SIZE = 25;
27
+ const SELECT_TEXT_LIMIT = 100;
21
28
  type Handlers = Parameters<Messenger["start"]>[0];
22
29
  type Controls = ActionRowBuilder<ButtonBuilder | StringSelectMenuBuilder>[];
23
30
  type Answer = NonNullable<DialogResponse["answers"]>[number];
@@ -38,10 +45,13 @@ export interface DiscordMessengerOptions {
38
45
  ownerId: string;
39
46
  allowedGuildIds: string[];
40
47
  allowedChannelIds: string[];
48
+ voice?: DiscordVoiceConfig;
49
+ voiceApiKey?: string;
41
50
  /** A supported discord.js Client, primarily for deterministic transport tests. */
42
51
  client?: Client;
43
52
  /** Attachment HTTP boundary; Discord credentials are never sent to the CDN. */
44
53
  fetch?: (input: string | URL | Request, init?: RequestInit) => Promise<Response>;
54
+ store?: Pick<StorePort, "getMeta" | "setMeta">;
45
55
  onError?: (error: unknown) => void;
46
56
  }
47
57
 
@@ -74,6 +84,9 @@ export function parseDiscordControl(value: string): { token: string; action: str
74
84
 
75
85
  function object(value: unknown): value is Record<string, unknown> { return !!value && typeof value === "object" && !Array.isArray(value); }
76
86
  function unsupported(reason: string): never { throw new Error(reason); }
87
+ function menuText(value: string): string {
88
+ return value.length <= SELECT_TEXT_LIMIT ? value : `${value.slice(0, SELECT_TEXT_LIMIT - 1).replace(/[\uD800-\uDBFF]$/, "")}…`;
89
+ }
77
90
 
78
91
  /** Keep Discord capacity checks separate from shared native dialog semantics. */
79
92
  function discordDialog(request: Record<string, unknown>): Dialog {
@@ -83,16 +96,12 @@ function discordDialog(request: Record<string, unknown>): Dialog {
83
96
  if (Buffer.byteLength(JSON.stringify(request), "utf8") > FILE_LIMIT - 64 * 1024) unsupported("Dialog content exceeds the safe Discord attachment limit; use the local OMP interface.");
84
97
  const dialog = parseDialog(request);
85
98
  if (dialog.method === "ask") for (const question of dialog.questions) {
86
- if (question.options.length > 25) unsupported("Ask options exceed Discord limits.");
99
+ if (question.options.length > SELECT_PAGE_SIZE) unsupported("Ask options exceed Discord limits.");
87
100
  for (const option of question.options) {
88
- if (option.label.length > 100) unsupported("Ask option cannot fit a Discord select menu.");
89
- if (option.description && option.description.length > 100) unsupported("Ask description cannot fit a Discord select menu.");
101
+ if (option.label.length > SELECT_TEXT_LIMIT) unsupported("Ask option cannot fit a Discord select menu.");
102
+ if (option.description && option.description.length > SELECT_TEXT_LIMIT) unsupported("Ask description cannot fit a Discord select menu.");
90
103
  }
91
104
  }
92
- if (dialog.method === "select") {
93
- if (dialog.options.length > 25 || dialog.options.some(option => option.length > 100)) unsupported("Select options cannot fit a Discord select menu.");
94
- if (dialog.details.some(detail => detail && detail.length > 100)) unsupported("Select description cannot fit a Discord select menu.");
95
- }
96
105
  if (dialog.method === "input" || dialog.method === "editor") {
97
106
  if (dialog.title.length > 45 || dialog.title.length === 0) unsupported("Input title cannot fit a Discord modal.");
98
107
  if (dialog.placeholder && dialog.placeholder.length > 100) unsupported("Input placeholder cannot fit a Discord modal.");
@@ -111,11 +120,31 @@ export class DiscordMessenger implements Messenger {
111
120
  private intake: Promise<void> = Promise.resolve();
112
121
  private readonly pending = new Map<string, Pending>();
113
122
  private readonly report: (error: unknown) => void;
114
- private readonly onMessage = (message: Message) => { this.enqueue(message); };
115
- private readonly onEdit = (_old: Message | PartialMessage, message: Message | PartialMessage) => { this.enqueue(message); };
123
+ private readonly voice?: DiscordVoice;
124
+ private voiceConnected = false;
125
+ private voiceEpoch = 0;
126
+ private readonly onVoiceDisconnect = () => {
127
+ this.voiceConnected = false;
128
+ this.voiceEpoch++;
129
+ this.voice?.close();
130
+ };
131
+ private readonly onMessage = (message: Message) => {
132
+ // Revocation must not wait behind a slow reply fetch or HEAD intake. command()
133
+ // checks origin/identity and fences older queued starts by real snowflake.
134
+ if (this.voice && this.voiceConnected && this.admission?.resolvedReady && !this.admission.stopped &&
135
+ !message.partial && message.content === "/voice stop" && message.channelId === this.options.voice?.textChannelId &&
136
+ this.route(message.channel)?.guildId) {
137
+ const input = this.normalize(message);
138
+ if (input) this.voice.command(message, input);
139
+ return;
140
+ }
141
+ this.enqueue(message, true);
142
+ };
143
+ private readonly onEdit = (_old: Message | PartialMessage, message: Message | PartialMessage) => { this.enqueue(message, false); };
116
144
  private readonly onInteraction = (interaction: Interaction) => { void this.interact(interaction).catch(this.report); };
117
145
  private readonly onReconnect = () => {
118
146
  if (!this.connected) return;
147
+ this.voiceConnected = true;
119
148
  const admission = this.admission;
120
149
  this.intake = this.intake.then(async () => {
121
150
  if (await this.admitted(admission)) await this.handlers?.reconnect?.();
@@ -126,8 +155,11 @@ export class DiscordMessenger implements Messenger {
126
155
  this.guilds = new Set(options.allowedGuildIds);
127
156
  this.channels = new Set(options.allowedChannelIds);
128
157
  this.report = options.onError ?? (error => console.error("Discord event failed:", error));
158
+ if (options.voice) this.voice = new DiscordVoice(options.voice, options.ownerId,
159
+ options.voiceApiKey !== options.token ? options.voiceApiKey : undefined, this.report);
129
160
  this.client = options.client ?? new Client({
130
- intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.DirectMessages, GatewayIntentBits.MessageContent],
161
+ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.DirectMessages, GatewayIntentBits.MessageContent,
162
+ ...(options.voice ? [GatewayIntentBits.GuildVoiceStates] : [])],
131
163
  partials: [Partials.Channel, Partials.Message],
132
164
  allowedMentions: NO_MENTIONS,
133
165
  rest: { retries: 0, rejectOnRateLimit: () => true },
@@ -159,6 +191,8 @@ export class DiscordMessenger implements Messenger {
159
191
  this.client.on(Events.MessageUpdate, this.onEdit);
160
192
  this.client.on(Events.InteractionCreate, this.onInteraction);
161
193
  this.client.on(Events.ShardResume, this.onReconnect);
194
+ this.client.on(Events.ShardDisconnect, this.onVoiceDisconnect);
195
+ this.client.on(Events.ShardReconnecting, this.onVoiceDisconnect);
162
196
  this.client.on(Events.ShardReady, this.onReconnect);
163
197
  this.client.on(Events.Error, this.report);
164
198
  try {
@@ -170,6 +204,7 @@ export class DiscordMessenger implements Messenger {
170
204
  finally { this.client.off(Events.ClientReady, ready); }
171
205
  }
172
206
  this.connected = true;
207
+ this.voiceConnected = true;
173
208
  } catch (error) { await this.stop(); throw error; }
174
209
  }
175
210
 
@@ -187,24 +222,31 @@ export class DiscordMessenger implements Messenger {
187
222
  return { platform: "discord", accountId, authorityId: this.options.ownerId, guildId, channelId, threadId };
188
223
  }
189
224
 
190
- private enqueue(message: Message | PartialMessage): void {
225
+ private enqueue(message: Message | PartialMessage, fresh: boolean): void {
191
226
  const admission = this.admission;
227
+ const voiceEpoch = this.voiceConnected && admission?.resolvedReady ? this.voiceEpoch : null;
192
228
  this.intake = this.intake.then(async () => {
193
229
  if (!await this.admitted(admission)) return;
194
230
  // Check destination and known author before even fetching a partial message.
195
231
  if (!this.route(message.channel) || (message.author && (message.author.bot || message.author.id !== this.options.ownerId))) return;
196
232
  if (!message.guildId && "recipientId" in message.channel && message.channel.recipientId !== this.options.ownerId) return;
197
233
  const full = message.partial ? await message.fetch() : message;
198
- const inbound = this.normalize(full);
234
+ const inbound = this.normalize(full, "pointer");
199
235
  if (inbound) {
236
+ if (this.isVoiceControl(inbound)) {
237
+ if (!fresh || message.partial || voiceEpoch !== this.voiceEpoch || !this.voiceConnected) return;
238
+ const work = this.voice?.command(full, inbound);
239
+ if (work) await this.handlers?.message({ ...inbound, text: work, attachments: [], reply: undefined });
240
+ return;
241
+ }
200
242
  await this.resolveReply(full, inbound);
201
243
  await this.handlers?.message(inbound);
202
244
  }
203
245
  }).catch(this.report);
204
246
  }
205
247
 
206
- /** Pure normalization of an already fetched Discord message; no attachment downloads. */
207
- normalize(message: Message): Inbound | null {
248
+ /** Use only a reply pointer when the caller will resolve cache and API together. */
249
+ normalize(message: Message, replyContext: "cached" | "pointer" = "cached"): Inbound | null {
208
250
  if (message.author.bot || message.author.id !== this.options.ownerId || message.webhookId) return null;
209
251
  const route = this.route(message.channel);
210
252
  if (!route || (message.type !== 0 && message.type !== 19)) return null;
@@ -220,19 +262,86 @@ export class DiscordMessenger implements Messenger {
220
262
  // also ignores contentless edits instead of replacing an admitted intent.
221
263
  if (!message.content.trim() && attachments.length === 0) return null;
222
264
  const reply = this.replyPointer(message);
223
- if (reply) this.snapshotReply(message, message.channel.messages.cache?.get(reply.messageId), reply);
265
+ if (reply && replyContext === "cached") this.snapshotReply(message, message.channel.messages.cache?.get(reply.messageId), reply);
224
266
  // CDN URLs carry expiring signatures; refreshing one must not create a new
225
267
  // input revision for an unchanged Discord edit.
226
268
  // Reply/voice snapshots are context, not a new edit or download identity.
227
- const attachmentIdentity = attachments.map(file => [file.id, file.name, file.size, file.contentType]).sort((left, right) => String(left[0]).localeCompare(String(right[0])));
228
- const revision = message.editedTimestamp === null ? "original" : `edit:${message.editedTimestamp}:${hash(JSON.stringify([message.content, attachmentIdentity]))}`;
269
+ let revision = "original";
270
+ if (message.editedTimestamp !== null) {
271
+ const attachmentIdentity = attachments.map(file => [file.id, file.name, file.size, file.contentType])
272
+ .sort((left, right) => String(left[0]).localeCompare(String(right[0])));
273
+ revision = `edit:${message.editedTimestamp}:${hash(JSON.stringify([message.content, attachmentIdentity]))}`;
274
+ }
229
275
  return {
230
276
  id: `discord:${route.accountId}:${message.id}:${revision}`, route, messageId: message.id,
231
277
  text: message.content, receivedAt: message.editedTimestamp ?? message.createdTimestamp, attachments,
232
278
  ...(reply ? { reply } : {}),
279
+ discordContext: this.context(route, message.channel),
233
280
  };
234
281
  }
235
282
 
283
+ private isVoiceControl(input: Inbound): boolean {
284
+ return input.route.guildId !== null && input.route.threadId === null &&
285
+ input.route.channelId === this.options.voice?.textChannelId && DiscordVoice.isControl(input.text);
286
+ }
287
+
288
+ /** Cached objects only: optional metadata must never delay or discard intake. */
289
+ private context(route: Route, channel?: unknown): DiscordContext {
290
+ const context: DiscordContext = {
291
+ kind: route.guildId ? "guild" : "dm", channel: { id: route.channelId },
292
+ ...(route.threadId ? { thread: { id: route.threadId, parentId: route.channelId } } : {}),
293
+ };
294
+ let observed = context;
295
+ try {
296
+ if (object(channel) && channel.id === (route.threadId ?? route.channelId)) {
297
+ const parent = route.threadId ? channel.parent : channel;
298
+ const metadata = object(parent) && parent.id === route.channelId &&
299
+ (parent.guildId ?? null) === route.guildId ? parent : undefined;
300
+ observed = {
301
+ ...context,
302
+ channel: { ...context.channel,
303
+ ...(metadata && typeof metadata.name === "string" ? { name: metadata.name } : {}),
304
+ ...(metadata && (metadata.topic === null || typeof metadata.topic === "string") ? { topic: metadata.topic } : {}),
305
+ },
306
+ ...(context.thread ? { thread: { ...context.thread,
307
+ ...(typeof channel.name === "string" ? { name: channel.name } : {}),
308
+ } } : {}),
309
+ };
310
+ }
311
+ } catch {
312
+ this.report(new Error("Discord channel metadata unavailable; owner intake preserved"));
313
+ }
314
+ try {
315
+ const notes = this.options.store ? discordPurposeNotes(this.options.store, route) : [];
316
+ const parent = notes.find(note => note.route.threadId === null);
317
+ const thread = notes.find(note => note.route.threadId === route.threadId && route.threadId !== null);
318
+ return { ...observed, channel: { ...observed.channel, ...(parent ? { purpose: parent.purpose } : {}) },
319
+ ...(observed.thread ? { thread: { ...observed.thread, ...(thread ? { purpose: thread.purpose } : {}) } } : {}) };
320
+ } catch {
321
+ this.report(new Error("Discord purpose metadata unavailable; owner intake preserved"));
322
+ return observed;
323
+ }
324
+ }
325
+
326
+ async inspectDiscordContext(route: Route): Promise<DiscordContext> {
327
+ this.assertRoute(route);
328
+ try { return this.context(route, await this.channel(route)); }
329
+ catch (error) {
330
+ if (error instanceof DeliveryError && error.certainty === "rejected") throw error;
331
+ this.report(new Error("Discord channel inspection unavailable"));
332
+ return this.context(route);
333
+ }
334
+ }
335
+
336
+ async discordPurpose(input: DiscordPurposeRequest): Promise<readonly DiscordPurposeNote[]> {
337
+ const request = discordPurposeRequest(input);
338
+ this.assertRoute(request.route);
339
+ if (!this.options.store) throw new DeliveryError("Discord purpose storage is unavailable", "rejected");
340
+ // A DM route needs live recipient verification; guild routes use the configured exact allowlist.
341
+ if (!request.route.guildId) await this.channel(request.route);
342
+ return changeDiscordPurpose(this.options.store, request);
343
+ }
344
+
236
345
  private replyPointer(message: Message): ReplyContext | undefined {
237
346
  const reference = message.reference;
238
347
  // discord.js caches embedded referenced_message in this channel's manager.
@@ -246,7 +355,9 @@ export class DiscordMessenger implements Messenger {
246
355
  if (!referenced || referenced.partial || referenced.id !== reply.messageId ||
247
356
  referenced.channelId !== message.channelId || referenced.guildId !== message.guildId) return false;
248
357
  reply.authorId = referenced.author?.id ?? null;
249
- reply.text = typeof referenced.content === "string" ? referenced.content : null;
358
+ reply.text = typeof referenced.content === "string" &&
359
+ !(referenced.author?.id === this.client.user?.id && referenced.content.startsWith(VOICE_DRAFT_HEADER))
360
+ ? referenced.content : null;
250
361
  return true;
251
362
  }
252
363
 
@@ -319,8 +430,19 @@ export class DiscordMessenger implements Messenger {
319
430
 
320
431
  async send(output: OutputRecord): Promise<string> {
321
432
  try {
433
+ if (output.replyTo !== undefined && (!object(output.replyTo) || !object(output.replyTo.route)
434
+ || typeof output.replyTo.messageId !== "string" || !/^[0-9]{1,20}$/.test(output.replyTo.messageId)
435
+ || physicalRouteKey(output.replyTo.route) !== physicalRouteKey(output.route))) {
436
+ throw new DeliveryError("Discord reply requires a real message in the exact destination conversation", "rejected");
437
+ }
322
438
  const channel = await this.destination(output.route);
323
- const message = await channel.send(this.payload(output.text, discordNonce(output.id, output.route)));
439
+ const message = await channel.send({
440
+ ...this.payload(output.text, discordNonce(output.id, output.route)),
441
+ // Discord may omit a deleted reference in this same send. Never retry
442
+ // without a reference: an ambiguous first attempt may already exist.
443
+ ...(output.replyTo ? { reply: { messageReference: output.replyTo.messageId, failIfNotExists: false } } : {}),
444
+ });
445
+ this.voice?.textDelivered(output);
324
446
  return message.id;
325
447
  } catch (error) { throw deliveryError(error); }
326
448
  }
@@ -343,7 +465,7 @@ export class DiscordMessenger implements Messenger {
343
465
  private button(pending: Pending, action: string, label: string, style = ButtonStyle.Secondary): ButtonBuilder {
344
466
  return new ButtonBuilder().setCustomId(this.control(pending, action)).setLabel(label).setStyle(style);
345
467
  }
346
- private view(pending: Pending): { content: string; components: Controls } {
468
+ private view(pending: Pending, selectPage?: number): { content: string; components: Controls } {
347
469
  const dialog = pending.dialog;
348
470
  const cancel = this.button(pending, "cancel", "Cancel");
349
471
  if (dialog.method === "confirm") return {
@@ -355,11 +477,35 @@ export class DiscordMessenger implements Messenger {
355
477
  components: [new ActionRowBuilder<ButtonBuilder>().addComponents(this.button(pending, "open", "Respond", ButtonStyle.Primary), cancel)],
356
478
  };
357
479
  if (dialog.method === "select") {
480
+ const page = selectPage ?? Math.floor((dialog.initialIndex ?? 0) / SELECT_PAGE_SIZE);
481
+ const first = page * SELECT_PAGE_SIZE;
482
+ const labels = dialog.options.slice(first, first + SELECT_PAGE_SIZE);
483
+ const pages = Math.ceil(dialog.options.length / SELECT_PAGE_SIZE);
484
+ const numbered = pages > 1 || labels.some((label, offset) => label.length > SELECT_TEXT_LIMIT
485
+ || (dialog.details[first + offset]?.length ?? 0) > SELECT_TEXT_LIMIT);
358
486
  const marker = (index: number) => index >= dialog.markableCount || !dialog.marker ? "" : dialog.marker === "checkbox" ? (dialog.checked.includes(index) ? "☑️" : "⬜") : "⚪";
359
- const state = dialog.marker ? `\n${dialog.options.map((label, index) => `${marker(index)} ${label}${index === dialog.initialIndex ? " (initial focus)" : ""}`).join("\n")}\nChoose one row per response; OMP supplies the checked state on each request.` : "";
487
+ const rows = labels.map((label, offset) => {
488
+ const index = first + offset;
489
+ const detail = dialog.details[index];
490
+ const emoji = marker(index);
491
+ const name = numbered ? `#${index + 1}: ${label}` : label;
492
+ return {
493
+ text: `${emoji ? `${emoji} ` : ""}${name}${index === dialog.initialIndex ? " (initial focus)" : ""}${numbered && detail ? `\n${detail}` : ""}`,
494
+ option: { label: menuText(name), value: String(index), ...(emoji ? { emoji: { name: emoji } } : {}),
495
+ ...(detail ? { description: menuText(detail) } : {}) },
496
+ };
497
+ });
498
+ const state = numbered || dialog.marker ? `\n${rows.map(row => row.text).join("\n")}` : "";
499
+ const navigation = new ActionRowBuilder<ButtonBuilder>();
500
+ if (page > 0) navigation.addComponents(this.button(pending, `page-${page - 1}`, "Previous"));
501
+ if (page + 1 < pages) navigation.addComponents(this.button(pending, `page-${page + 1}`, "Next"));
502
+ navigation.addComponents(cancel);
360
503
  return {
361
- content: dialog.title + state,
362
- components: [new ActionRowBuilder<StringSelectMenuBuilder>().addComponents(new StringSelectMenuBuilder().setCustomId(this.control(pending, "select")).setMinValues(1).setMaxValues(1).addOptions(dialog.options.map((label, index) => ({ label, value: String(index), ...(marker(index) ? { emoji: { name: marker(index) } } : {}), ...(dialog.details[index] ? { description: dialog.details[index] } : {}) })))), new ActionRowBuilder<ButtonBuilder>().addComponents(cancel)],
504
+ content: dialog.title + (pages > 1 ? `\nPage ${page + 1}/${pages}` : "") + state
505
+ + (dialog.marker ? "\nChoose one row per response; OMP supplies the checked state on each request." : ""),
506
+ components: [new ActionRowBuilder<StringSelectMenuBuilder>().addComponents(new StringSelectMenuBuilder()
507
+ .setCustomId(this.control(pending, page === 0 ? "select" : `select-${page}`))
508
+ .setMinValues(1).setMaxValues(1).addOptions(rows.map(row => row.option))), navigation],
363
509
  };
364
510
  }
365
511
  const question = dialog.questions[pending.question]!;
@@ -380,7 +526,7 @@ export class DiscordMessenger implements Messenger {
380
526
  this.assertRoute(approval.route);
381
527
  if (!this.handlers) throw new DeliveryError("Discord messenger is not started", "rejected");
382
528
  if (approval.state !== "pending") throw new DeliveryError("Discord approval is no longer pending", "rejected");
383
- const token = hash(JSON.stringify([approval.id, approval.generation, approval.target, approval.requestId, routeKey(approval.route)]));
529
+ const token = approvalCardToken(approval);
384
530
  const existing = this.pending.get(token);
385
531
  if (existing?.active && existing.messageId) {
386
532
  if (approval.remoteId && approval.remoteId !== existing.messageId) throw new DeliveryError("Discord approval receipt does not match its active control", "rejected");
@@ -442,12 +588,12 @@ export class DiscordMessenger implements Messenger {
442
588
  }
443
589
  }
444
590
 
445
- private async refresh(pending: Pending): Promise<void> {
591
+ private async refresh(pending: Pending, selectPage?: number): Promise<void> {
446
592
  if (!pending.messageId || !pending.active) return;
447
593
  const channel = await this.destination(pending.approval.route);
448
594
  const message = await channel.messages.fetch(pending.messageId);
449
595
  this.assertApprovalMessage(message, pending.approval, pending.token);
450
- const view = this.view(pending);
596
+ const view = this.view(pending, selectPage);
451
597
  const payload = this.payload(view.content, discordNonce(`approval:${pending.token}`, pending.approval.route), view.components);
452
598
  await message.edit({ content: payload.content, files: payload.files, attachments: [], components: view.components, allowedMentions: NO_MENTIONS });
453
599
  }
@@ -457,12 +603,12 @@ export class DiscordMessenger implements Messenger {
457
603
  const matches = [...this.pending.values()].filter(pending => pending.approval.id === approval.id && pending.approval.generation === approval.generation && routeKey(pending.approval.route) === routeKey(approval.route));
458
604
  for (const pending of matches) pending.active = false;
459
605
  const messageIds = new Set([approval.remoteId, ...matches.map(pending => pending.messageId)].filter((id): id is string => !!id));
606
+ const token = approvalCardToken(approval);
460
607
  try {
461
608
  const channel = await this.destination(approval.route);
462
609
  for (const id of messageIds) {
463
610
  try {
464
611
  const message = await channel.messages.fetch(id);
465
- const token = hash(JSON.stringify([approval.id, approval.generation, approval.target, approval.requestId, routeKey(approval.route)]));
466
612
  this.assertApprovalMessage(message, approval, token);
467
613
  await message.edit({ components: [], allowedMentions: NO_MENTIONS });
468
614
  }
@@ -488,6 +634,7 @@ export class DiscordMessenger implements Messenger {
488
634
  }
489
635
 
490
636
  private async finish(pending: Pending, response: DialogResponse, interaction: { deferUpdate(): Promise<unknown> }): Promise<void> {
637
+ validateDecisionResponse(pending.approval, response);
491
638
  // The handler's receipt is the durable admission boundary. Until it resolves,
492
639
  // leave the original control and draft actionable, without acknowledging it.
493
640
  await this.handlers!.answer(pending.approval.id, response, pending.approval.route);
@@ -530,6 +677,7 @@ export class DiscordMessenger implements Messenger {
530
677
  await deny("This conversation is not authorized for Superagent commands."); return;
531
678
  }
532
679
  let route: Route | null;
680
+ let discordContext: DiscordContext | undefined;
533
681
  try {
534
682
  // This resolves a channel, never a command's interaction ID as a message.
535
683
  const channel = interaction.channel ?? await this.client.channels.fetch(interaction.channelId);
@@ -538,6 +686,7 @@ export class DiscordMessenger implements Messenger {
538
686
  !channel.isSendable() || (!route.guildId && (channel.type !== ChannelType.DM || channel.recipientId !== this.options.ownerId))) {
539
687
  await deny("This conversation is not authorized for Superagent commands."); return;
540
688
  }
689
+ discordContext = this.context(route, channel);
541
690
  } catch {
542
691
  this.report(new Error("Discord command destination verification failed; nothing was admitted"));
543
692
  await deny("Superagent could not verify this conversation; nothing was admitted."); return;
@@ -551,6 +700,7 @@ export class DiscordMessenger implements Messenger {
551
700
  await handlers.message({
552
701
  id: `discord:${route.accountId}:interaction:${interaction.id}`, route, messageId: null,
553
702
  interactionId: interaction.id, text, receivedAt: interaction.createdTimestamp, attachments: [],
703
+ ...(discordContext ? { discordContext } : {}),
554
704
  });
555
705
  } catch {
556
706
  this.report(new Error("Discord command durable admission could not be confirmed; admission was not retried"));
@@ -596,10 +746,22 @@ export class DiscordMessenger implements Messenger {
596
746
  if (dialog.method === "confirm" && interaction.isButton() && (action === "yes" || action === "no")) {
597
747
  await this.finish(pending, { confirmed: action === "yes" }, interaction); return;
598
748
  }
599
- if (dialog.method === "select" && interaction.isStringSelectMenu() && action === "select") {
749
+ if (dialog.method === "select" && interaction.isButton() && action.startsWith("page-")) {
750
+ const page = Number(action.slice("page-".length));
751
+ if (page * SELECT_PAGE_SIZE >= dialog.options.length) throw new Error("Invalid Discord select page");
752
+ // Navigation only edits this card. It never admits or resolves a native answer.
753
+ await interaction.deferUpdate();
754
+ await this.refresh(pending, page);
755
+ return;
756
+ }
757
+ if (dialog.method === "select" && interaction.isStringSelectMenu() && (action === "select" || action.startsWith("select-"))) {
758
+ const first = action === "select" ? 0 : Number(action.slice("select-".length)) * SELECT_PAGE_SIZE;
600
759
  const index = interaction.values[0];
601
- if (interaction.values.length !== 1 || !index || !/^(0|[1-9][0-9]*)$/.test(index) || !dialog.options[Number(index)]) throw new Error("Invalid Discord select value");
602
- await this.finish(pending, { value: dialog.options[Number(index)]! }, interaction); return;
760
+ const position = Number(index);
761
+ const label = dialog.options[position];
762
+ if (interaction.values.length !== 1 || !index || !/^(0|[1-9][0-9]*)$/.test(index)
763
+ || position < first || position >= first + SELECT_PAGE_SIZE || label === undefined) throw new Error("Invalid Discord select value");
764
+ await this.finish(pending, { value: label }, interaction); return;
603
765
  }
604
766
  if ((dialog.method === "input" || dialog.method === "editor") && interaction.isModalSubmit() && action === "value") {
605
767
  await this.finish(pending, { value: interaction.fields.getTextInputValue("value") }, interaction); return;
@@ -617,6 +779,7 @@ export class DiscordMessenger implements Messenger {
617
779
  if (!question.multi && pending.customInput) pending.selected = [];
618
780
  } else if (interaction.isButton() && action === `next-${pending.question}`) {
619
781
  const answer: Answer = { id: question.id, selectedOptions: [...pending.selected], ...(pending.customInput ? { customInput: pending.customInput } : {}) };
782
+ if (pending.approval.decision) validateDecisionAnswer(question, answer);
620
783
  if (pending.question + 1 === dialog.questions.length) {
621
784
  await this.finish(pending, { answers: [...pending.answers, answer] }, interaction); return;
622
785
  }
@@ -642,8 +805,8 @@ export class DiscordMessenger implements Messenger {
642
805
  const messages = [...page.values()].sort((left, right) => BigInt(left.id) < BigInt(right.id) ? -1 : 1);
643
806
  if (!messages.length) break;
644
807
  for (const message of messages) {
645
- const input = this.normalize(message);
646
- if (input && physicalRouteKey(input.route) === physicalRouteKey(route)) {
808
+ const input = this.normalize(message, "pointer");
809
+ if (input && !this.isVoiceControl(input) && physicalRouteKey(input.route) === physicalRouteKey(route)) {
647
810
  await this.resolveReply(message, input);
648
811
  inputs.push(input);
649
812
  }
@@ -656,13 +819,28 @@ export class DiscordMessenger implements Messenger {
656
819
  return inputs;
657
820
  }
658
821
 
659
- private async forumThreadAllowed(channel: ForumChannel | MediaChannel): Promise<boolean> {
660
- if (channel.flags.has(ChannelFlagsBitField.Flags.RequireTag)) {
661
- throw new DeliveryError("Discord forum/media topics require an explicitly selected tag in this channel; this interface cannot select tags", "rejected");
822
+ private forumTags(channel: ForumChannel | MediaChannel, appliedTags: readonly string[] | undefined, permissions: Readonly<PermissionsBitField>): void {
823
+ if (appliedTags !== undefined && (!Array.isArray(appliedTags) || appliedTags.length > 5 ||
824
+ new Set(appliedTags).size !== appliedTags.length || appliedTags.some(id => typeof id !== "string"))) {
825
+ throw new DeliveryError("Discord forum/media tags must be at most five unique tag IDs", "rejected");
826
+ }
827
+ if (channel.flags.has(ChannelFlagsBitField.Flags.RequireTag) && !appliedTags?.length) {
828
+ throw new DeliveryError("Discord forum/media topics require an explicitly selected tag in this channel", "rejected");
829
+ }
830
+ for (const id of appliedTags ?? []) {
831
+ const tag = channel.availableTags.find(tag => tag.id === id);
832
+ if (!tag) throw new DeliveryError("Discord tag ID is not available in this forum/media channel", "rejected");
833
+ if (tag.moderated && !permissions.has(PermissionFlagsBits.ManageThreads)) {
834
+ throw new DeliveryError("Discord moderated tags require ManageThreads permission", "rejected");
835
+ }
662
836
  }
837
+ }
838
+
839
+ private async forumThreadAllowed(channel: ForumChannel | MediaChannel, appliedTags?: readonly string[]): Promise<boolean> {
663
840
  const member = await channel.guild.members.fetchMe({ force: true });
664
841
  const permissions = channel.permissionsFor(member);
665
842
  if (!permissions) throw new DeliveryError("Discord bot channel permissions could not be resolved", "rejected");
843
+ this.forumTags(channel, appliedTags, permissions);
666
844
  // Forum/media posts require SEND_MESSAGES, not CREATE_PUBLIC_THREADS.
667
845
  // Reading and replying must also work for the resulting native topic.
668
846
  // https://docs.discord.com/developers/topics/threads#creating-threads-in-forum-and-media-channels
@@ -671,12 +849,16 @@ export class DiscordMessenger implements Messenger {
671
849
  }
672
850
 
673
851
  /** Read-only capability checks never enable features or choose forum tags. */
674
- async canCreateThread(route: Route): Promise<boolean> {
852
+ async canCreateThread(route: Route, appliedTags?: readonly string[]): Promise<boolean> {
675
853
  this.assertRoute(route);
676
- if (!route.guildId || route.threadId !== null) return false;
854
+ if (!route.guildId || route.threadId !== null) {
855
+ if (appliedTags !== undefined) throw new DeliveryError("Discord tags can only be selected for forum/media topic creation", "rejected");
856
+ return false;
857
+ }
677
858
  try {
678
859
  const channel = await this.channel(route, true);
679
- if (channel.type === ChannelType.GuildForum || channel.type === ChannelType.GuildMedia) return await this.forumThreadAllowed(channel);
860
+ if (channel.type === ChannelType.GuildForum || channel.type === ChannelType.GuildMedia) return await this.forumThreadAllowed(channel, appliedTags);
861
+ if (appliedTags !== undefined) throw new DeliveryError("Discord tags can only be selected for forum/media topic creation", "rejected");
680
862
  if (channel.type !== ChannelType.GuildText && channel.type !== ChannelType.GuildAnnouncement) return false;
681
863
  const member = await channel.guild.members.fetchMe({ force: true });
682
864
  const permissions = channel.permissionsFor(member);
@@ -689,20 +871,24 @@ export class DiscordMessenger implements Messenger {
689
871
  } catch (error) { throw deliveryError(error); }
690
872
  }
691
873
 
692
- async createThread(route: Route, title: string, sourceMessageId?: string): Promise<Route> {
874
+ async createThread(route: Route, title: string, sourceMessageId?: string, appliedTags?: readonly string[]): Promise<Route> {
693
875
  this.assertRoute(route);
694
876
  if (!route.guildId) throw new DeliveryError("Discord DMs cannot create threads; provide an explicit authorized guild target", "rejected");
695
877
  if (route.threadId) throw new DeliveryError("Discord cannot nest threads; provide an explicit parent-channel target", "rejected");
696
- if (!title.trim() || title.length > 100) throw new DeliveryError("Discord thread title must contain 1–100 characters", "rejected");
878
+ if (typeof title !== "string" || !title.trim() || title.length > 100) throw new DeliveryError("Discord thread title must contain 1–100 characters", "rejected");
697
879
  try {
698
880
  // Forum/media roots cannot receive ordinary messages, but can create
699
881
  // native starter-message posts within this same authorized destination.
700
882
  const channel = await this.channel(route, true);
883
+ if (appliedTags !== undefined && channel.type !== ChannelType.GuildForum && channel.type !== ChannelType.GuildMedia) {
884
+ throw new DeliveryError("Discord tags can only be selected for forum/media topic creation", "rejected");
885
+ }
701
886
  let thread;
702
887
  if (channel.type === ChannelType.GuildForum || channel.type === ChannelType.GuildMedia) {
703
888
  if (sourceMessageId !== undefined) throw new DeliveryError("Discord forum/media topics cannot reuse a source message; provide the authorized parent without a source", "rejected");
704
- if (!await this.forumThreadAllowed(channel)) throw new DeliveryError("Discord bot lacks permissions to create and use a forum/media topic", "rejected");
705
- thread = await channel.threads.create({ name: title, message: { content: title, allowedMentions: NO_MENTIONS } });
889
+ if (!await this.forumThreadAllowed(channel, appliedTags)) throw new DeliveryError("Discord bot lacks permissions to create and use a forum/media topic", "rejected");
890
+ thread = await channel.threads.create({ name: title, ...(appliedTags === undefined ? {} : { appliedTags: [...appliedTags] }),
891
+ message: { content: title, allowedMentions: NO_MENTIONS } });
706
892
  } else if (channel.type !== ChannelType.GuildText && channel.type !== ChannelType.GuildAnnouncement) {
707
893
  throw new DeliveryError("This guild channel cannot create a public conversation thread", "rejected");
708
894
  } else if (sourceMessageId) {
@@ -724,8 +910,87 @@ export class DiscordMessenger implements Messenger {
724
910
  } catch (error) { throw deliveryError(error); }
725
911
  }
726
912
 
913
+ private async threadContext(route: Route) {
914
+ this.assertRoute(route);
915
+ if (!route.guildId) throw new DeliveryError("Discord thread inspection requires an authorized guild destination", "rejected");
916
+ const channel = await this.channel(route, true);
917
+ const parent = channel.isThread() ? await this.channel({ ...route, threadId: null }, true) : channel;
918
+ if (parent.type !== ChannelType.GuildText && parent.type !== ChannelType.GuildAnnouncement &&
919
+ parent.type !== ChannelType.GuildForum && parent.type !== ChannelType.GuildMedia) {
920
+ throw new DeliveryError("Discord destination is not a supported thread parent", "rejected");
921
+ }
922
+ const member = await parent.guild.members.fetchMe({ force: true });
923
+ const parentPermissions = parent.permissionsFor(member);
924
+ const permissions = channel.isThread() ? channel.permissionsFor(member) : parentPermissions;
925
+ if (!parentPermissions || !permissions) throw new DeliveryError("Discord bot channel permissions could not be resolved", "rejected");
926
+ if (!parentPermissions.has([PermissionFlagsBits.ViewChannel, PermissionFlagsBits.ReadMessageHistory]) ||
927
+ !permissions.has([PermissionFlagsBits.ViewChannel, PermissionFlagsBits.ReadMessageHistory])) {
928
+ throw new DeliveryError("Discord bot lacks permissions to inspect this thread destination", "rejected");
929
+ }
930
+ return { channel, parent, permissions };
931
+ }
932
+
933
+ async inspectThread(route: Route): Promise<ThreadInfo> {
934
+ try {
935
+ const { channel, parent } = await this.threadContext(route);
936
+ const forum = parent.type === ChannelType.GuildForum || parent.type === ChannelType.GuildMedia;
937
+ return {
938
+ route: physicalRoute(route),
939
+ title: channel.isThread() ? channel.name : parent.name,
940
+ archived: channel.isThread() ? channel.archived : null,
941
+ requiresTag: forum && parent.flags.has(ChannelFlagsBitField.Flags.RequireTag),
942
+ availableTags: forum ? parent.availableTags.map(tag => ({ id: tag.id, name: tag.name, moderated: tag.moderated })) : [],
943
+ appliedTags: channel.isThread() ? [...channel.appliedTags] : [],
944
+ };
945
+ } catch (error) { throw deliveryError(error); }
946
+ }
947
+
948
+ async updateThread(route: Route, update: ThreadUpdate): Promise<ThreadInfo> {
949
+ this.assertRoute(route);
950
+ if (!route.guildId || !route.threadId) throw new DeliveryError("Discord thread updates require an existing guild thread", "rejected");
951
+ if (typeof update !== "object" || update === null || Array.isArray(update) || !Object.keys(update).length ||
952
+ Object.keys(update).some(key => key !== "title" && key !== "appliedTags" && key !== "archived") ||
953
+ ("title" in update && (typeof update.title !== "string" || !update.title.trim() || update.title.length > 100)) ||
954
+ ("archived" in update && typeof update.archived !== "boolean") ||
955
+ ("appliedTags" in update && !Array.isArray(update.appliedTags))) {
956
+ throw new DeliveryError("Discord thread update requires only a title of 1-100 characters, tag IDs, or a boolean archived value", "rejected");
957
+ }
958
+ let edited = false;
959
+ try {
960
+ const { channel, parent, permissions } = await this.threadContext(route);
961
+ if (!channel.isThread()) throw new DeliveryError("Discord thread updates require an existing guild thread", "rejected");
962
+ if (!permissions.has(PermissionFlagsBits.ManageThreads)) throw new DeliveryError("Discord thread updates require ManageThreads permission", "rejected");
963
+ if ("appliedTags" in update) {
964
+ if (parent.type !== ChannelType.GuildForum && parent.type !== ChannelType.GuildMedia) {
965
+ throw new DeliveryError("Discord tags can only be updated on forum/media threads", "rejected");
966
+ }
967
+ this.forumTags(parent, update.appliedTags, permissions);
968
+ }
969
+ // discord.js sends these fields together in one PATCH. Omitted fields
970
+ // stay omitted: never unarchive, lock, or change tags as a side effect.
971
+ await channel.edit({
972
+ ...(update.title === undefined ? {} : { name: update.title }),
973
+ ...(update.appliedTags === undefined ? {} : { appliedTags: [...update.appliedTags] }),
974
+ ...(update.archived === undefined ? {} : { archived: update.archived }),
975
+ });
976
+ edited = true;
977
+ const result = await this.inspectThread(route);
978
+ if ((update.title !== undefined && result.title !== update.title) ||
979
+ (update.archived !== undefined && result.archived !== update.archived) ||
980
+ (update.appliedTags !== undefined && (result.appliedTags.length !== update.appliedTags.length ||
981
+ update.appliedTags.some(id => !result.appliedTags.includes(id))))) {
982
+ throw new DeliveryError("Discord thread update readback did not match the requested state", "uncertain");
983
+ }
984
+ return result;
985
+ } catch (error) {
986
+ if (edited) throw new DeliveryError("Discord thread update was sent but authoritative readback could not be confirmed", "uncertain", undefined, { cause: error });
987
+ throw deliveryError(error);
988
+ }
989
+ }
990
+
727
991
  async stop(): Promise<void> {
728
992
  this.connected = false;
993
+ this.onVoiceDisconnect();
729
994
  if (this.admission) {
730
995
  this.admission.stopped = true;
731
996
  this.admission.stop();
@@ -734,6 +999,8 @@ export class DiscordMessenger implements Messenger {
734
999
  this.client.off(Events.MessageUpdate, this.onEdit);
735
1000
  this.client.off(Events.InteractionCreate, this.onInteraction);
736
1001
  this.client.off(Events.ShardResume, this.onReconnect);
1002
+ this.client.off(Events.ShardDisconnect, this.onVoiceDisconnect);
1003
+ this.client.off(Events.ShardReconnecting, this.onVoiceDisconnect);
737
1004
  this.client.off(Events.ShardReady, this.onReconnect);
738
1005
  this.client.off(Events.Error, this.report);
739
1006
  await this.intake;