omp-superagent 0.0.0-stage → 0.1.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/DESIGN.md +1361 -0
- package/LICENSE +21 -0
- package/README.ko.md +184 -0
- package/README.md +205 -2
- package/THIRD_PARTY_NOTICES.md +313 -0
- package/assets/architecture.mmd +24 -0
- package/assets/architecture.svg +126 -0
- package/assets/superagent-avatar.jpg +0 -0
- package/assets/superagent-mascot.webp +0 -0
- package/config.example.json +26 -0
- package/docs/OPERATIONS.md +1030 -0
- package/docs/releases/0.1.0.md +222 -0
- package/docs/releases/0.1.1.md +60 -0
- package/package.json +59 -4
- package/scripts/check-omp.ts +4 -0
- package/scripts/ci.ts +28 -0
- package/scripts/prepare-ulw.ts +18 -0
- package/scripts/release.ts +50 -0
- package/scripts/setup.sh +25 -0
- package/skills/head/SKILL.md +259 -0
- package/skills/head/references/model-selection.md +263 -0
- package/skills/head/references/routing.md +356 -0
- package/skills/head/references/supervision.md +312 -0
- package/skills/lane/SKILL.md +188 -0
- package/skills/lane/references/workflow.md +349 -0
- package/src/autostart.ts +295 -0
- package/src/board-extension.ts +217 -0
- package/src/board.ts +396 -0
- package/src/cli.ts +167 -0
- package/src/config.ts +191 -0
- package/src/contracts.ts +317 -0
- package/src/credentials.ts +172 -0
- package/src/delivery.ts +7 -0
- package/src/dialog.ts +73 -0
- package/src/discord-command-registration.ts +201 -0
- package/src/discord-commands.ts +29 -0
- package/src/discord-markdown.ts +172 -0
- package/src/discord.ts +745 -0
- package/src/extension.ts +289 -0
- package/src/gateway-client.ts +222 -0
- package/src/gateway-protocol.ts +85 -0
- package/src/gateway-restart.ts +151 -0
- package/src/gateway-server.ts +392 -0
- package/src/gateway-store.ts +237 -0
- package/src/gateway.ts +638 -0
- package/src/head-recovery.ts +61 -0
- package/src/host-extension.ts +449 -0
- package/src/host-owner.ts +350 -0
- package/src/host-protocol.ts +136 -0
- package/src/host.ts +414 -0
- package/src/installed-omp.ts +63 -0
- package/src/lane-extension.ts +179 -0
- package/src/lane-models.ts +75 -0
- package/src/lane-report.ts +70 -0
- package/src/managed-ulw-probe.ts +172 -0
- package/src/managed-ulw.ts +471 -0
- package/src/message-order.ts +21 -0
- package/src/messenger-commands.ts +16 -0
- package/src/messengers.ts +114 -0
- package/src/native-presets.ts +282 -0
- package/src/native-sessions.ts +32 -0
- package/src/native-settings.ts +129 -0
- package/src/repository.ts +12 -0
- package/src/runtime.ts +3864 -0
- package/src/setup-judge.ts +34 -0
- package/src/setup-memory.ts +39 -0
- package/src/setup-profiles.ts +84 -0
- package/src/setup.ts +300 -0
- package/src/slack-command-registration.ts +217 -0
- package/src/slack-commands.ts +18 -0
- package/src/slack.ts +776 -0
- package/src/store.ts +806 -0
- package/src/telegram-command-registration.ts +155 -0
- package/src/telegram.ts +661 -0
- package/src/workflow.ts +94 -0
- package/upstream/ulw.json +9 -0
package/src/discord.ts
ADDED
|
@@ -0,0 +1,745 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import {
|
|
3
|
+
ActionRowBuilder, AttachmentBuilder, ButtonBuilder, ButtonStyle, ChannelFlagsBitField, ChannelType, Client,
|
|
4
|
+
Events, GatewayIntentBits, MessageFlags, ModalBuilder, Partials, PermissionFlagsBits, StringSelectMenuBuilder,
|
|
5
|
+
Routes, TextInputBuilder, TextInputStyle,
|
|
6
|
+
type ChatInputCommandInteraction, type ForumChannel, type Interaction, type MediaChannel, type Message, type MessageCreateOptions, type PartialMessage,
|
|
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";
|
|
9
|
+
import { parseDialog, type Dialog } from "./dialog.ts";
|
|
10
|
+
import { DeliveryError } from "./delivery.ts";
|
|
11
|
+
import { parseDiscordCommand } from "./discord-commands.ts";
|
|
12
|
+
import { renderDiscordMarkdown } from "./discord-markdown.ts";
|
|
13
|
+
|
|
14
|
+
// Reference (not copied): gimso2x/ompbot @ 4d2eb28d0bf66644892dc0fc333580d0eb7e7780,
|
|
15
|
+
// src/discord/{adapter,attachments,channel,transport}.ts (MIT, ompbot contributors).
|
|
16
|
+
// discord.js owns Gateway/REST, including nonce serialization. Nonces are only a
|
|
17
|
+
// short-window server dedupe aid, never an exactly-once delivery guarantee.
|
|
18
|
+
const NO_MENTIONS = { parse: [] as never[], repliedUser: false };
|
|
19
|
+
const FILE_LIMIT = 8 * 1024 * 1024;
|
|
20
|
+
const MESSAGE_LIMIT = 2000;
|
|
21
|
+
type Handlers = Parameters<Messenger["start"]>[0];
|
|
22
|
+
type Controls = ActionRowBuilder<ButtonBuilder | StringSelectMenuBuilder>[];
|
|
23
|
+
type Answer = NonNullable<DialogResponse["answers"]>[number];
|
|
24
|
+
interface Pending {
|
|
25
|
+
approval: Approval; token: string; dialog: Dialog; messageId: string | null;
|
|
26
|
+
active: boolean; busy: boolean; question: number; answers: Answer[];
|
|
27
|
+
selected: string[]; customInput?: string;
|
|
28
|
+
}
|
|
29
|
+
interface Admission {
|
|
30
|
+
ready: Promise<boolean>;
|
|
31
|
+
resolvedReady: boolean;
|
|
32
|
+
stopped: boolean;
|
|
33
|
+
stop(): void;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export interface DiscordMessengerOptions {
|
|
37
|
+
token: string;
|
|
38
|
+
ownerId: string;
|
|
39
|
+
allowedGuildIds: string[];
|
|
40
|
+
allowedChannelIds: string[];
|
|
41
|
+
/** A supported discord.js Client, primarily for deterministic transport tests. */
|
|
42
|
+
client?: Client;
|
|
43
|
+
/** Attachment HTTP boundary; Discord credentials are never sent to the CDN. */
|
|
44
|
+
fetch?: (input: string | URL | Request, init?: RequestInit) => Promise<Response>;
|
|
45
|
+
onError?: (error: unknown) => void;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** Only an explicit client-side or HTTP rejection establishes non-delivery. */
|
|
49
|
+
export function deliveryError(error: unknown): DeliveryError {
|
|
50
|
+
if (error instanceof DeliveryError) return error;
|
|
51
|
+
const record = error !== null && typeof error === "object" ? error as Record<string, unknown> : {};
|
|
52
|
+
const status = typeof record.status === "number" ? record.status : undefined;
|
|
53
|
+
const retryAfter = typeof record.retryAfter === "number" ? record.retryAfter : undefined;
|
|
54
|
+
const rejected = record.name === "RateLimitError" || (status !== undefined && status >= 400 && status < 500 && status !== 408);
|
|
55
|
+
return new DeliveryError(error instanceof Error ? error.message : "Discord delivery failed", rejected ? "rejected" : "uncertain", retryAfter, { cause: error });
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function hash(value: string): string { return createHash("sha256").update(value).digest("hex").slice(0, 24); }
|
|
59
|
+
export function discordNonce(id: string, route: Route, part = 0): string { return hash(JSON.stringify([id, routeKey(route), part])); }
|
|
60
|
+
|
|
61
|
+
export function discordAttachmentAllowed(value: string): boolean {
|
|
62
|
+
try {
|
|
63
|
+
const url = new URL(value);
|
|
64
|
+
return url.protocol === "https:" && !url.username && !url.password && (!url.port || url.port === "443") &&
|
|
65
|
+
!url.hash && (url.hostname === "cdn.discordapp.com" || url.hostname === "media.discordapp.net") &&
|
|
66
|
+
/^\/attachments\/[0-9]+\/[0-9]+\/[^/]+$/.test(url.pathname) && !/%(?:2f|5c)/i.test(url.pathname);
|
|
67
|
+
} catch { return false; }
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export function parseDiscordControl(value: string): { token: string; action: string } | null {
|
|
71
|
+
const match = /^omp:([a-f0-9]{24}):([a-z]+(?:-[0-9]+)?)$/.exec(value);
|
|
72
|
+
return match?.[0] === value ? { token: match[1]!, action: match[2]! } : null;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function object(value: unknown): value is Record<string, unknown> { return !!value && typeof value === "object" && !Array.isArray(value); }
|
|
76
|
+
function unsupported(reason: string): never { throw new Error(reason); }
|
|
77
|
+
|
|
78
|
+
/** Keep Discord capacity checks separate from shared native dialog semantics. */
|
|
79
|
+
function discordDialog(request: Record<string, unknown>): Dialog {
|
|
80
|
+
if (request.secret === true) return parseDialog(request); // Reject before inspecting any secret content.
|
|
81
|
+
// Reserve room for question labels, controls, and a 4000-character free-text
|
|
82
|
+
// response when a request must be displayed through a text attachment.
|
|
83
|
+
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
|
+
const dialog = parseDialog(request);
|
|
85
|
+
if (dialog.method === "ask") for (const question of dialog.questions) {
|
|
86
|
+
if (question.options.length > 25) unsupported("Ask options exceed Discord limits.");
|
|
87
|
+
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.");
|
|
90
|
+
}
|
|
91
|
+
}
|
|
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
|
+
if (dialog.method === "input" || dialog.method === "editor") {
|
|
97
|
+
if (dialog.title.length > 45 || dialog.title.length === 0) unsupported("Input title cannot fit a Discord modal.");
|
|
98
|
+
if (dialog.placeholder && dialog.placeholder.length > 100) unsupported("Input placeholder cannot fit a Discord modal.");
|
|
99
|
+
if (dialog.prefill && dialog.prefill.length > 4000) unsupported("Editor content exceeds Discord's 4000-character modal limit.");
|
|
100
|
+
}
|
|
101
|
+
return dialog;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
export class DiscordMessenger implements Messenger {
|
|
105
|
+
readonly client: Client;
|
|
106
|
+
private readonly guilds: Set<string>;
|
|
107
|
+
private readonly channels: Set<string>;
|
|
108
|
+
private handlers: Handlers | null = null;
|
|
109
|
+
private connected = false;
|
|
110
|
+
private admission: Admission | null = null;
|
|
111
|
+
private intake: Promise<void> = Promise.resolve();
|
|
112
|
+
private readonly pending = new Map<string, Pending>();
|
|
113
|
+
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); };
|
|
116
|
+
private readonly onInteraction = (interaction: Interaction) => { void this.interact(interaction).catch(this.report); };
|
|
117
|
+
private readonly onReconnect = () => {
|
|
118
|
+
if (!this.connected) return;
|
|
119
|
+
const admission = this.admission;
|
|
120
|
+
this.intake = this.intake.then(async () => {
|
|
121
|
+
if (await this.admitted(admission)) await this.handlers?.reconnect?.();
|
|
122
|
+
}).catch(this.report);
|
|
123
|
+
};
|
|
124
|
+
|
|
125
|
+
constructor(private readonly options: DiscordMessengerOptions) {
|
|
126
|
+
this.guilds = new Set(options.allowedGuildIds);
|
|
127
|
+
this.channels = new Set(options.allowedChannelIds);
|
|
128
|
+
this.report = options.onError ?? (error => console.error("Discord event failed:", error));
|
|
129
|
+
this.client = options.client ?? new Client({
|
|
130
|
+
intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.DirectMessages, GatewayIntentBits.MessageContent],
|
|
131
|
+
partials: [Partials.Channel, Partials.Message],
|
|
132
|
+
allowedMentions: NO_MENTIONS,
|
|
133
|
+
rest: { retries: 0, rejectOnRateLimit: () => true },
|
|
134
|
+
});
|
|
135
|
+
// Disable discord.js's default retries even on an injected supported Client.
|
|
136
|
+
this.client.rest.options.retries = 0;
|
|
137
|
+
this.client.rest.options.rejectOnRateLimit = () => true;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
async start(handlers: Handlers): Promise<void> {
|
|
141
|
+
if (this.handlers) throw new Error("Discord messenger is already started");
|
|
142
|
+
this.handlers = handlers;
|
|
143
|
+
const stopped = Promise.withResolvers<boolean>();
|
|
144
|
+
this.admission = {
|
|
145
|
+
ready: Promise.race([
|
|
146
|
+
(handlers.ready ?? Promise.resolve()).then(() => true, () => {
|
|
147
|
+
this.report(new Error("Discord startup readiness failed; intake remains disabled"));
|
|
148
|
+
return false;
|
|
149
|
+
}),
|
|
150
|
+
stopped.promise,
|
|
151
|
+
]),
|
|
152
|
+
resolvedReady: handlers.ready === undefined,
|
|
153
|
+
stopped: false,
|
|
154
|
+
stop: () => { stopped.resolve(false); },
|
|
155
|
+
};
|
|
156
|
+
const admission = this.admission;
|
|
157
|
+
void admission.ready.then(ready => { admission.resolvedReady = ready; });
|
|
158
|
+
this.client.on(Events.MessageCreate, this.onMessage);
|
|
159
|
+
this.client.on(Events.MessageUpdate, this.onEdit);
|
|
160
|
+
this.client.on(Events.InteractionCreate, this.onInteraction);
|
|
161
|
+
this.client.on(Events.ShardResume, this.onReconnect);
|
|
162
|
+
this.client.on(Events.ShardReady, this.onReconnect);
|
|
163
|
+
this.client.on(Events.Error, this.report);
|
|
164
|
+
try {
|
|
165
|
+
if (!this.client.isReady()) {
|
|
166
|
+
const { promise, resolve } = Promise.withResolvers<void>();
|
|
167
|
+
const ready = () => { resolve(); };
|
|
168
|
+
this.client.once(Events.ClientReady, ready);
|
|
169
|
+
try { await this.client.login(this.options.token); await promise; }
|
|
170
|
+
finally { this.client.off(Events.ClientReady, ready); }
|
|
171
|
+
}
|
|
172
|
+
this.connected = true;
|
|
173
|
+
} catch (error) { await this.stop(); throw error; }
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
private async admitted(admission = this.admission): Promise<boolean> {
|
|
177
|
+
return !!admission && await admission.ready && !admission.stopped && this.admission === admission;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
private route(channel: { id: string; isThread(): boolean; parentId?: string | null; guildId?: string | null }): Route | null {
|
|
181
|
+
const accountId = this.client.user?.id;
|
|
182
|
+
if (!accountId) return null;
|
|
183
|
+
const guildId = channel.guildId ?? null;
|
|
184
|
+
const threadId = channel.isThread() ? channel.id : null;
|
|
185
|
+
const channelId = threadId ? channel.parentId : channel.id;
|
|
186
|
+
if (!channelId || (guildId && (!this.guilds.has(guildId) || !this.channels.has(channelId)))) return null;
|
|
187
|
+
return { platform: "discord", accountId, authorityId: this.options.ownerId, guildId, channelId, threadId };
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
private enqueue(message: Message | PartialMessage): void {
|
|
191
|
+
const admission = this.admission;
|
|
192
|
+
this.intake = this.intake.then(async () => {
|
|
193
|
+
if (!await this.admitted(admission)) return;
|
|
194
|
+
// Check destination and known author before even fetching a partial message.
|
|
195
|
+
if (!this.route(message.channel) || (message.author && (message.author.bot || message.author.id !== this.options.ownerId))) return;
|
|
196
|
+
if (!message.guildId && "recipientId" in message.channel && message.channel.recipientId !== this.options.ownerId) return;
|
|
197
|
+
const full = message.partial ? await message.fetch() : message;
|
|
198
|
+
const inbound = this.normalize(full);
|
|
199
|
+
if (inbound) {
|
|
200
|
+
await this.resolveReply(full, inbound);
|
|
201
|
+
await this.handlers?.message(inbound);
|
|
202
|
+
}
|
|
203
|
+
}).catch(this.report);
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/** Pure normalization of an already fetched Discord message; no attachment downloads. */
|
|
207
|
+
normalize(message: Message): Inbound | null {
|
|
208
|
+
if (message.author.bot || message.author.id !== this.options.ownerId || message.webhookId) return null;
|
|
209
|
+
const route = this.route(message.channel);
|
|
210
|
+
if (!route || (message.type !== 0 && message.type !== 19)) return null;
|
|
211
|
+
if (!route.guildId && (message.channel.type !== ChannelType.DM || message.channel.recipientId !== this.options.ownerId)) return null;
|
|
212
|
+
const attachments = [...message.attachments.values()].filter(file => discordAttachmentAllowed(file.url) &&
|
|
213
|
+
typeof file.size === "number" && Number.isSafeInteger(file.size) && file.size >= 0).map(file => ({
|
|
214
|
+
id: file.id, name: file.name, url: file.url, size: file.size,
|
|
215
|
+
...(file.contentType ? { contentType: file.contentType } : {}),
|
|
216
|
+
...(message.flags?.has(MessageFlags.IsVoiceMessage) ? { voice: true as const } : {}),
|
|
217
|
+
...(typeof file.duration === "number" && Number.isFinite(file.duration) && file.duration >= 0 ? { durationSeconds: file.duration } : {}),
|
|
218
|
+
}));
|
|
219
|
+
// Stickers, whitespace, and filtered attachments are not instructions. This
|
|
220
|
+
// also ignores contentless edits instead of replacing an admitted intent.
|
|
221
|
+
if (!message.content.trim() && attachments.length === 0) return null;
|
|
222
|
+
const reply = this.replyPointer(message);
|
|
223
|
+
if (reply) this.snapshotReply(message, message.channel.messages.cache?.get(reply.messageId), reply);
|
|
224
|
+
// CDN URLs carry expiring signatures; refreshing one must not create a new
|
|
225
|
+
// input revision for an unchanged Discord edit.
|
|
226
|
+
// 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]))}`;
|
|
229
|
+
return {
|
|
230
|
+
id: `discord:${route.accountId}:${message.id}:${revision}`, route, messageId: message.id,
|
|
231
|
+
text: message.content, receivedAt: message.editedTimestamp ?? message.createdTimestamp, attachments,
|
|
232
|
+
...(reply ? { reply } : {}),
|
|
233
|
+
};
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
private replyPointer(message: Message): ReplyContext | undefined {
|
|
237
|
+
const reference = message.reference;
|
|
238
|
+
// discord.js caches embedded referenced_message in this channel's manager.
|
|
239
|
+
// Never use fetchReference(): it follows the reference's channel selector.
|
|
240
|
+
if (message.type !== 19 || !reference?.messageId || !/^[0-9]{1,20}$/.test(reference.messageId) ||
|
|
241
|
+
reference.channelId !== message.channelId || (reference.guildId !== undefined && reference.guildId !== message.guildId)) return;
|
|
242
|
+
return { messageId: reference.messageId, authorId: null, text: null };
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
private snapshotReply(message: Message, referenced: Message | undefined, reply: ReplyContext): boolean {
|
|
246
|
+
if (!referenced || referenced.partial || referenced.id !== reply.messageId ||
|
|
247
|
+
referenced.channelId !== message.channelId || referenced.guildId !== message.guildId) return false;
|
|
248
|
+
reply.authorId = referenced.author?.id ?? null;
|
|
249
|
+
reply.text = typeof referenced.content === "string" ? referenced.content : null;
|
|
250
|
+
return true;
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
private async resolveReply(message: Message, input: Inbound): Promise<void> {
|
|
254
|
+
if (!input.reply || this.snapshotReply(message, message.channel.messages.cache?.get(input.reply.messageId), input.reply)) return;
|
|
255
|
+
try {
|
|
256
|
+
const referenced = await message.channel.messages.fetch({ message: input.reply.messageId, cache: false });
|
|
257
|
+
this.snapshotReply(message, referenced, input.reply);
|
|
258
|
+
} catch {
|
|
259
|
+
// Missing/deleted/inaccessible originals retain only their same-channel
|
|
260
|
+
// pointer; failure to obtain context must not lose the owner's message.
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
private assertRoute(route: Route): void {
|
|
265
|
+
if (route.platform !== "discord" || route.accountId !== this.client.user?.id || route.authorityId !== this.options.ownerId ||
|
|
266
|
+
!route.channelId || (!route.guildId && route.threadId !== null) ||
|
|
267
|
+
(route.guildId && (!this.guilds.has(route.guildId) || !this.channels.has(route.channelId)))) {
|
|
268
|
+
throw new DeliveryError("Discord route is not authorized for this bot and owner", "rejected");
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
private async channel(route: Route, force = false) {
|
|
273
|
+
this.assertRoute(route);
|
|
274
|
+
const channel = await this.client.channels.fetch(route.threadId ?? route.channelId, { force });
|
|
275
|
+
if (!channel) throw new DeliveryError("Discord destination cannot receive messages", "rejected");
|
|
276
|
+
const actual = this.route(channel);
|
|
277
|
+
if (!actual || physicalRouteKey(actual) !== physicalRouteKey(route)) throw new DeliveryError("Discord destination identity changed", "rejected");
|
|
278
|
+
if (!route.guildId && (channel.type !== ChannelType.DM || channel.recipientId !== this.options.ownerId)) throw new DeliveryError("Discord DM does not belong to the owner", "rejected");
|
|
279
|
+
return channel;
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
private async destination(route: Route) {
|
|
283
|
+
const channel = await this.channel(route);
|
|
284
|
+
if (!channel.isSendable()) throw new DeliveryError("Discord destination cannot receive messages", "rejected");
|
|
285
|
+
return channel;
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
async openAttachment(route: Route, attachment: Attachment, signal: AbortSignal): Promise<Response> {
|
|
289
|
+
this.assertRoute(route);
|
|
290
|
+
if (typeof attachment.size !== "number" || !Number.isSafeInteger(attachment.size) || attachment.size < 0 ||
|
|
291
|
+
!discordAttachmentAllowed(attachment.url)) throw new DeliveryError("Attachment is not an authorized Discord CDN attachment", "rejected");
|
|
292
|
+
const url = new URL(attachment.url);
|
|
293
|
+
const [, , channelId, attachmentId] = url.pathname.split("/");
|
|
294
|
+
if (channelId !== (route.threadId ?? route.channelId) || attachmentId !== attachment.id) {
|
|
295
|
+
throw new DeliveryError("Discord attachment does not belong to this destination and resource", "rejected");
|
|
296
|
+
}
|
|
297
|
+
await this.destination(route);
|
|
298
|
+
try {
|
|
299
|
+
// The CDN uses its signed resource URL, never the bot's API credential.
|
|
300
|
+
return await (this.options.fetch ?? fetch)(url, { redirect: "error", credentials: "omit", signal });
|
|
301
|
+
} catch {
|
|
302
|
+
throw new DeliveryError("Discord attachment download failed", "rejected");
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
private payload(text: string, nonce: string, components?: Controls): MessageCreateOptions {
|
|
307
|
+
// Discord renders no markdown tables, so outbound tables become aligned fences.
|
|
308
|
+
// The stored OutputRecord text is never modified; only this payload changes.
|
|
309
|
+
const content = renderDiscordMarkdown(text, FILE_LIMIT);
|
|
310
|
+
if (Buffer.byteLength(content, "utf8") > FILE_LIMIT) throw new DeliveryError("Discord text attachment exceeds the safe 8 MiB upload limit", "rejected");
|
|
311
|
+
return {
|
|
312
|
+
...(content.length <= MESSAGE_LIMIT ? { content: content || "(empty output)" } : {
|
|
313
|
+
content: "Full text is attached (exceeds Discord's message limit).",
|
|
314
|
+
files: [new AttachmentBuilder(Buffer.from(content, "utf8"), { name: `omp-${nonce}.txt` })],
|
|
315
|
+
}),
|
|
316
|
+
allowedMentions: NO_MENTIONS, nonce, enforceNonce: true, ...(components ? { components } : {}),
|
|
317
|
+
};
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
async send(output: OutputRecord): Promise<string> {
|
|
321
|
+
try {
|
|
322
|
+
const channel = await this.destination(output.route);
|
|
323
|
+
const message = await channel.send(this.payload(output.text, discordNonce(output.id, output.route)));
|
|
324
|
+
return message.id;
|
|
325
|
+
} catch (error) { throw deliveryError(error); }
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
async setActivity(message: MessageReference, activity: MessageActivity): Promise<void> {
|
|
329
|
+
try {
|
|
330
|
+
if (!/^[0-9]{1,20}$/.test(message.messageId)) throw new DeliveryError("Activity requires a Discord message snowflake", "rejected");
|
|
331
|
+
const channel = await this.destination(message.route);
|
|
332
|
+
const emoji = activity === "received" ? "\u{1F440}" : "\u{1F4AD}";
|
|
333
|
+
const reaction = Routes.channelMessageOwnReaction(channel.id, message.messageId, encodeURIComponent(emoji));
|
|
334
|
+
if (activity === "idle") await this.client.rest.delete(reaction);
|
|
335
|
+
else await this.client.rest.put(reaction);
|
|
336
|
+
} catch (error) {
|
|
337
|
+
const failure = deliveryError(error);
|
|
338
|
+
throw new DeliveryError("Discord activity update failed", failure.certainty, failure.retryAfterMs);
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
private control(pending: Pending, action: string): string { return `omp:${pending.token}:${action}`; }
|
|
343
|
+
private button(pending: Pending, action: string, label: string, style = ButtonStyle.Secondary): ButtonBuilder {
|
|
344
|
+
return new ButtonBuilder().setCustomId(this.control(pending, action)).setLabel(label).setStyle(style);
|
|
345
|
+
}
|
|
346
|
+
private view(pending: Pending): { content: string; components: Controls } {
|
|
347
|
+
const dialog = pending.dialog;
|
|
348
|
+
const cancel = this.button(pending, "cancel", "Cancel");
|
|
349
|
+
if (dialog.method === "confirm") return {
|
|
350
|
+
content: `${dialog.title}\n\n${dialog.message}`,
|
|
351
|
+
components: [new ActionRowBuilder<ButtonBuilder>().addComponents(this.button(pending, "yes", "Confirm", ButtonStyle.Danger), this.button(pending, "no", "Decline"), cancel)],
|
|
352
|
+
};
|
|
353
|
+
if (dialog.method === "input" || dialog.method === "editor") return {
|
|
354
|
+
content: `${dialog.title}\nOpen the editor to respond. Discord inputs are not secret; maximum 4000 characters.`,
|
|
355
|
+
components: [new ActionRowBuilder<ButtonBuilder>().addComponents(this.button(pending, "open", "Respond", ButtonStyle.Primary), cancel)],
|
|
356
|
+
};
|
|
357
|
+
if (dialog.method === "select") {
|
|
358
|
+
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.` : "";
|
|
360
|
+
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)],
|
|
363
|
+
};
|
|
364
|
+
}
|
|
365
|
+
const question = dialog.questions[pending.question]!;
|
|
366
|
+
const components: Controls = [];
|
|
367
|
+
if (question.options.length) components.push(new ActionRowBuilder<StringSelectMenuBuilder>().addComponents(
|
|
368
|
+
new StringSelectMenuBuilder().setCustomId(this.control(pending, `choose-${pending.question}`)).setMinValues(0).setMaxValues(question.multi ? question.options.length : 1)
|
|
369
|
+
.addOptions(question.options.map((option, index) => ({ label: option.label, value: String(index), default: pending.selected.includes(option.label), ...(option.description ? { description: option.description } : {}) }))),
|
|
370
|
+
));
|
|
371
|
+
components.push(new ActionRowBuilder<ButtonBuilder>().addComponents(
|
|
372
|
+
this.button(pending, `other-${pending.question}`, "Other / free text"),
|
|
373
|
+
this.button(pending, `next-${pending.question}`, pending.question + 1 === dialog.questions.length ? "Submit all answers" : "Next question", ButtonStyle.Primary), cancel,
|
|
374
|
+
));
|
|
375
|
+
const previews = question.options.map((option, index) => `${index + 1}. ${option.label}${index === question.recommended ? " (recommended, not preselected)" : ""}${option.preview ? `\n${option.preview}` : ""}`).join("\n");
|
|
376
|
+
return { content: `Question ${pending.question + 1}/${dialog.questions.length}${question.header ? ` — ${question.header}` : ""}\n${question.question}\n${question.multi ? "Multiple answers allowed." : "Choose one option OR free text."}\n${previews}\n${pending.customInput ? `Free text: ${pending.customInput}` : ""}`, components };
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
async showApproval(approval: Approval): Promise<string> {
|
|
380
|
+
this.assertRoute(approval.route);
|
|
381
|
+
if (!this.handlers) throw new DeliveryError("Discord messenger is not started", "rejected");
|
|
382
|
+
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)]));
|
|
384
|
+
const existing = this.pending.get(token);
|
|
385
|
+
if (existing?.active && existing.messageId) {
|
|
386
|
+
if (approval.remoteId && approval.remoteId !== existing.messageId) throw new DeliveryError("Discord approval receipt does not match its active control", "rejected");
|
|
387
|
+
return existing.messageId;
|
|
388
|
+
}
|
|
389
|
+
for (const pending of this.pending.values()) if (pending.approval.id === approval.id) await this.dismissApproval(pending.approval);
|
|
390
|
+
let dialog: Dialog;
|
|
391
|
+
try { dialog = discordDialog(approval.request); }
|
|
392
|
+
catch (error) {
|
|
393
|
+
const channel = await this.destination(approval.route);
|
|
394
|
+
const notice = `Request cancelled: ${error instanceof Error ? error.message : "Unsupported dialog."}`;
|
|
395
|
+
let message: Message;
|
|
396
|
+
try {
|
|
397
|
+
const payload = this.payload(notice, discordNonce(`approval-cancel:${token}`, approval.route));
|
|
398
|
+
if (approval.remoteId) {
|
|
399
|
+
message = await channel.messages.fetch(approval.remoteId);
|
|
400
|
+
this.assertApprovalMessage(message, approval, token);
|
|
401
|
+
await message.edit({ content: payload.content, files: payload.files, attachments: [], components: [], allowedMentions: NO_MENTIONS });
|
|
402
|
+
} else message = await channel.send(payload);
|
|
403
|
+
}
|
|
404
|
+
catch (failure) { throw deliveryError(failure); }
|
|
405
|
+
await this.handlers.answer(approval.id, { cancelled: true }, approval.route);
|
|
406
|
+
return message.id;
|
|
407
|
+
}
|
|
408
|
+
const pending: Pending = { approval: { ...approval, route: { ...approval.route } }, token, dialog, messageId: approval.remoteId, active: false, busy: false, question: 0, answers: [], selected: [] };
|
|
409
|
+
const view = this.view(pending);
|
|
410
|
+
this.pending.set(token, pending);
|
|
411
|
+
try {
|
|
412
|
+
const channel = await this.destination(approval.route);
|
|
413
|
+
const payload = this.payload(view.content, discordNonce(`approval:${token}`, approval.route), view.components);
|
|
414
|
+
let message: Message;
|
|
415
|
+
if (approval.remoteId) {
|
|
416
|
+
message = await channel.messages.fetch(approval.remoteId);
|
|
417
|
+
this.assertApprovalMessage(message, approval, token);
|
|
418
|
+
await message.edit({ content: payload.content, files: payload.files, attachments: [], components: view.components, allowedMentions: NO_MENTIONS });
|
|
419
|
+
} else message = await channel.send(payload);
|
|
420
|
+
pending.messageId = message.id;
|
|
421
|
+
pending.active = true;
|
|
422
|
+
return message.id;
|
|
423
|
+
} catch (error) { pending.active = false; this.pending.delete(token); throw deliveryError(error); }
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
private assertApprovalMessage(message: Message, approval: Approval, token: string): void {
|
|
427
|
+
const source: Route = {
|
|
428
|
+
...physicalRoute(approval.route), accountId: message.author.id, guildId: message.guildId,
|
|
429
|
+
channelId: approval.route.threadId ? approval.route.channelId : message.channelId,
|
|
430
|
+
threadId: approval.route.threadId ? message.channelId : null,
|
|
431
|
+
};
|
|
432
|
+
if ((approval.remoteId && message.id !== approval.remoteId) || message.author.id !== this.client.user?.id || physicalRouteKey(source) !== physicalRouteKey(approval.route)) {
|
|
433
|
+
throw new DeliveryError("Discord approval message does not belong to this bot and destination", "rejected");
|
|
434
|
+
}
|
|
435
|
+
for (const row of message.components) {
|
|
436
|
+
if (!("components" in row)) continue;
|
|
437
|
+
for (const component of row.components) {
|
|
438
|
+
if ("customId" in component && component.customId && parseDiscordControl(component.customId)?.token !== token) {
|
|
439
|
+
throw new DeliveryError("Discord message belongs to a different approval identity", "rejected");
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
private async refresh(pending: Pending): Promise<void> {
|
|
446
|
+
if (!pending.messageId || !pending.active) return;
|
|
447
|
+
const channel = await this.destination(pending.approval.route);
|
|
448
|
+
const message = await channel.messages.fetch(pending.messageId);
|
|
449
|
+
this.assertApprovalMessage(message, pending.approval, pending.token);
|
|
450
|
+
const view = this.view(pending);
|
|
451
|
+
const payload = this.payload(view.content, discordNonce(`approval:${pending.token}`, pending.approval.route), view.components);
|
|
452
|
+
await message.edit({ content: payload.content, files: payload.files, attachments: [], components: view.components, allowedMentions: NO_MENTIONS });
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
async dismissApproval(approval: Approval): Promise<void> {
|
|
456
|
+
this.assertRoute(approval.route);
|
|
457
|
+
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
|
+
for (const pending of matches) pending.active = false;
|
|
459
|
+
const messageIds = new Set([approval.remoteId, ...matches.map(pending => pending.messageId)].filter((id): id is string => !!id));
|
|
460
|
+
try {
|
|
461
|
+
const channel = await this.destination(approval.route);
|
|
462
|
+
for (const id of messageIds) {
|
|
463
|
+
try {
|
|
464
|
+
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
|
+
this.assertApprovalMessage(message, approval, token);
|
|
467
|
+
await message.edit({ components: [], allowedMentions: NO_MENTIONS });
|
|
468
|
+
}
|
|
469
|
+
catch (error) {
|
|
470
|
+
if (object(error) && (error.code === 10008 || error.code === 10003)) continue; // Already deleted.
|
|
471
|
+
throw error;
|
|
472
|
+
}
|
|
473
|
+
}
|
|
474
|
+
for (const pending of matches) this.pending.delete(pending.token);
|
|
475
|
+
} catch (error) { throw deliveryError(error); }
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
private modal(pending: Pending, action: string): ModalBuilder {
|
|
479
|
+
const dialog = pending.dialog;
|
|
480
|
+
const ask = dialog.method === "ask";
|
|
481
|
+
const title = ask ? "Other answer" : (dialog as Extract<Dialog, { method: "input" | "editor" }>).title;
|
|
482
|
+
const input = new TextInputBuilder().setCustomId("value").setLabel(ask ? "Your answer (not secret)" : "Response (not secret)").setRequired(false).setMaxLength(4000)
|
|
483
|
+
.setStyle(dialog.method === "input" ? TextInputStyle.Short : TextInputStyle.Paragraph);
|
|
484
|
+
if (dialog.method === "input" && dialog.placeholder) input.setPlaceholder(dialog.placeholder);
|
|
485
|
+
const prefill = ask ? pending.customInput : dialog.method === "editor" ? dialog.prefill : undefined;
|
|
486
|
+
if (prefill) input.setValue(prefill);
|
|
487
|
+
return new ModalBuilder().setCustomId(this.control(pending, action)).setTitle(title).addComponents(new ActionRowBuilder<TextInputBuilder>().addComponents(input));
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
private async finish(pending: Pending, response: DialogResponse, interaction: { deferUpdate(): Promise<unknown> }): Promise<void> {
|
|
491
|
+
// The handler's receipt is the durable admission boundary. Until it resolves,
|
|
492
|
+
// leave the original control and draft actionable, without acknowledging it.
|
|
493
|
+
await this.handlers!.answer(pending.approval.id, response, pending.approval.route);
|
|
494
|
+
// Admission succeeded: ACK/cleanup failures must never resubmit the answer.
|
|
495
|
+
pending.active = false;
|
|
496
|
+
try { await interaction.deferUpdate(); }
|
|
497
|
+
finally { await this.dismissApproval(pending.approval); }
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
private async commandReply(interaction: ChatInputCommandInteraction, content: string): Promise<void> {
|
|
501
|
+
try { await interaction.reply({ content, flags: MessageFlags.Ephemeral, allowedMentions: NO_MENTIONS }); }
|
|
502
|
+
catch {
|
|
503
|
+
// SDK errors can contain the interaction response URL and its secret token.
|
|
504
|
+
// A failed/expired ACK never replays admission or falls back to a followup.
|
|
505
|
+
this.report(new Error("Discord command acknowledgement failed; admission was not retried"));
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
private async command(interaction: ChatInputCommandInteraction): Promise<void> {
|
|
510
|
+
const handlers = this.handlers;
|
|
511
|
+
const admission = this.admission;
|
|
512
|
+
const deny = (content: string) => this.commandReply(interaction, content);
|
|
513
|
+
if (!this.client.application?.id || interaction.applicationId !== this.client.application.id || !this.client.user?.id) {
|
|
514
|
+
await deny("This command does not belong to the connected Superagent application."); return;
|
|
515
|
+
}
|
|
516
|
+
if (interaction.user.bot || interaction.user.id !== this.options.ownerId) {
|
|
517
|
+
await deny("Only the configured owner can use Superagent commands."); return;
|
|
518
|
+
}
|
|
519
|
+
const text = parseDiscordCommand(interaction.commandName, interaction.options.data);
|
|
520
|
+
if (text === null) {
|
|
521
|
+
await deny("This Superagent command or its options are unsupported or stale; nothing was admitted."); return;
|
|
522
|
+
}
|
|
523
|
+
// Commands have a three-second initial response deadline. Unlike ordinary
|
|
524
|
+
// messages/components, never wait for readiness or the serialized intake.
|
|
525
|
+
if (!this.connected || !handlers || !admission?.resolvedReady || admission.stopped) {
|
|
526
|
+
await deny("Superagent is not ready to accept commands; nothing was admitted."); return;
|
|
527
|
+
}
|
|
528
|
+
if (!/^[0-9]{1,20}$/.test(interaction.id) || !Number.isFinite(interaction.createdTimestamp) || !interaction.channelId ||
|
|
529
|
+
(interaction.guildId !== null && !this.guilds.has(interaction.guildId))) {
|
|
530
|
+
await deny("This conversation is not authorized for Superagent commands."); return;
|
|
531
|
+
}
|
|
532
|
+
let route: Route | null;
|
|
533
|
+
try {
|
|
534
|
+
// This resolves a channel, never a command's interaction ID as a message.
|
|
535
|
+
const channel = interaction.channel ?? await this.client.channels.fetch(interaction.channelId);
|
|
536
|
+
route = channel ? this.route(channel) : null;
|
|
537
|
+
if (!channel || channel.id !== interaction.channelId || !route || route.guildId !== interaction.guildId ||
|
|
538
|
+
!channel.isSendable() || (!route.guildId && (channel.type !== ChannelType.DM || channel.recipientId !== this.options.ownerId))) {
|
|
539
|
+
await deny("This conversation is not authorized for Superagent commands."); return;
|
|
540
|
+
}
|
|
541
|
+
} catch {
|
|
542
|
+
this.report(new Error("Discord command destination verification failed; nothing was admitted"));
|
|
543
|
+
await deny("Superagent could not verify this conversation; nothing was admitted."); return;
|
|
544
|
+
}
|
|
545
|
+
if (!this.connected || this.handlers !== handlers || this.admission !== admission || admission.stopped || !admission.resolvedReady) {
|
|
546
|
+
await deny("Superagent is not ready to accept commands; nothing was admitted."); return;
|
|
547
|
+
}
|
|
548
|
+
try {
|
|
549
|
+
// The captured handler resolves only after durable admission. Do not
|
|
550
|
+
// defer an apparent success before this boundary or persist response tokens.
|
|
551
|
+
await handlers.message({
|
|
552
|
+
id: `discord:${route.accountId}:interaction:${interaction.id}`, route, messageId: null,
|
|
553
|
+
interactionId: interaction.id, text, receivedAt: interaction.createdTimestamp, attachments: [],
|
|
554
|
+
});
|
|
555
|
+
} catch {
|
|
556
|
+
this.report(new Error("Discord command durable admission could not be confirmed; admission was not retried"));
|
|
557
|
+
await deny("Superagent could not confirm acceptance. This command may already have been recorded; no automatic retry was made. Check this conversation and service status before taking further action.");
|
|
558
|
+
return;
|
|
559
|
+
}
|
|
560
|
+
await this.commandReply(interaction, "Superagent accepted this command. Its result will be sent to this conversation.");
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
private async interact(interaction: Interaction): Promise<void> {
|
|
564
|
+
if (interaction.isChatInputCommand()) { await this.command(interaction); return; }
|
|
565
|
+
if (!interaction.isButton() && !interaction.isStringSelectMenu() && !interaction.isModalSubmit()) return;
|
|
566
|
+
const parsed = parseDiscordControl(interaction.customId);
|
|
567
|
+
if (!parsed) return;
|
|
568
|
+
if (!await this.admitted()) return;
|
|
569
|
+
const pending = this.pending.get(parsed.token);
|
|
570
|
+
const deny = async (content: string) => { await interaction.reply({ content, flags: MessageFlags.Ephemeral, allowedMentions: NO_MENTIONS }); };
|
|
571
|
+
if (interaction.user.id !== this.options.ownerId) { await deny("Only the configured owner can answer this request."); return; }
|
|
572
|
+
if (!pending?.active || pending.busy || !this.handlers) { await deny("This request is expired or already being handled."); return; }
|
|
573
|
+
const route = pending.approval.route;
|
|
574
|
+
const message = interaction.isModalSubmit() ? (interaction.isFromMessage() ? interaction.message : null) : interaction.message;
|
|
575
|
+
const source: Route = {
|
|
576
|
+
...physicalRoute(route), accountId: message?.author.id ?? "", authorityId: interaction.user.id, guildId: interaction.guildId,
|
|
577
|
+
channelId: route.threadId ? route.channelId : interaction.channelId ?? "",
|
|
578
|
+
threadId: route.threadId ? interaction.channelId : null,
|
|
579
|
+
};
|
|
580
|
+
if (!message || message.id !== pending.messageId || physicalRouteKey(source) !== physicalRouteKey(route) ||
|
|
581
|
+
message.channelId !== (route.threadId ?? route.channelId) || message.guildId !== route.guildId) {
|
|
582
|
+
await deny("This control does not belong to this destination or request."); return;
|
|
583
|
+
}
|
|
584
|
+
this.assertRoute(route);
|
|
585
|
+
const action = parsed.action;
|
|
586
|
+
const dialog = pending.dialog;
|
|
587
|
+
if (interaction.isButton() && action === "open" && (dialog.method === "input" || dialog.method === "editor")) {
|
|
588
|
+
await interaction.showModal(this.modal(pending, "value")); return;
|
|
589
|
+
}
|
|
590
|
+
if (interaction.isButton() && dialog.method === "ask" && action === `other-${pending.question}`) {
|
|
591
|
+
await interaction.showModal(this.modal(pending, `custom-${pending.question}`)); return;
|
|
592
|
+
}
|
|
593
|
+
pending.busy = true;
|
|
594
|
+
try {
|
|
595
|
+
if (interaction.isButton() && action === "cancel") { await this.finish(pending, { cancelled: true }, interaction); return; }
|
|
596
|
+
if (dialog.method === "confirm" && interaction.isButton() && (action === "yes" || action === "no")) {
|
|
597
|
+
await this.finish(pending, { confirmed: action === "yes" }, interaction); return;
|
|
598
|
+
}
|
|
599
|
+
if (dialog.method === "select" && interaction.isStringSelectMenu() && action === "select") {
|
|
600
|
+
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;
|
|
603
|
+
}
|
|
604
|
+
if ((dialog.method === "input" || dialog.method === "editor") && interaction.isModalSubmit() && action === "value") {
|
|
605
|
+
await this.finish(pending, { value: interaction.fields.getTextInputValue("value") }, interaction); return;
|
|
606
|
+
}
|
|
607
|
+
if (dialog.method === "ask") {
|
|
608
|
+
const question = dialog.questions[pending.question]!;
|
|
609
|
+
if (interaction.isStringSelectMenu() && action === `choose-${pending.question}`) {
|
|
610
|
+
if ((!question.multi && interaction.values.length > 1) || new Set(interaction.values).size !== interaction.values.length || interaction.values.some(value => !/^(0|[1-9][0-9]*)$/.test(value) || !question.options[Number(value)])) throw new Error("Invalid Discord ask selection");
|
|
611
|
+
await interaction.deferUpdate(); // Partial draft progress, not a final answer.
|
|
612
|
+
pending.selected = interaction.values.map(value => question.options[Number(value)]!.label);
|
|
613
|
+
if (!question.multi && pending.selected.length) pending.customInput = undefined;
|
|
614
|
+
} else if (interaction.isModalSubmit() && action === `custom-${pending.question}`) {
|
|
615
|
+
await interaction.deferUpdate();
|
|
616
|
+
pending.customInput = interaction.fields.getTextInputValue("value").trim() || undefined;
|
|
617
|
+
if (!question.multi && pending.customInput) pending.selected = [];
|
|
618
|
+
} else if (interaction.isButton() && action === `next-${pending.question}`) {
|
|
619
|
+
const answer: Answer = { id: question.id, selectedOptions: [...pending.selected], ...(pending.customInput ? { customInput: pending.customInput } : {}) };
|
|
620
|
+
if (pending.question + 1 === dialog.questions.length) {
|
|
621
|
+
await this.finish(pending, { answers: [...pending.answers, answer] }, interaction); return;
|
|
622
|
+
}
|
|
623
|
+
await interaction.deferUpdate();
|
|
624
|
+
pending.answers.push(answer);
|
|
625
|
+
pending.question++;
|
|
626
|
+
pending.selected = [];
|
|
627
|
+
pending.customInput = undefined;
|
|
628
|
+
} else return;
|
|
629
|
+
await this.refresh(pending);
|
|
630
|
+
}
|
|
631
|
+
} finally { pending.busy = false; }
|
|
632
|
+
}
|
|
633
|
+
|
|
634
|
+
/** Only the caller's stored, already-authorized cursor; never bootstrap history. */
|
|
635
|
+
async fetchAfter(route: Route, messageId: string): Promise<Inbound[]> {
|
|
636
|
+
if (!/^[0-9]{1,20}$/.test(messageId)) throw new DeliveryError("Catchup requires a stored Discord message snowflake", "rejected");
|
|
637
|
+
const channel = await this.destination(physicalRoute(route));
|
|
638
|
+
const inputs: Inbound[] = [];
|
|
639
|
+
let cursor = messageId;
|
|
640
|
+
for (;;) {
|
|
641
|
+
const page = await channel.messages.fetch({ after: cursor, limit: 100, cache: false });
|
|
642
|
+
const messages = [...page.values()].sort((left, right) => BigInt(left.id) < BigInt(right.id) ? -1 : 1);
|
|
643
|
+
if (!messages.length) break;
|
|
644
|
+
for (const message of messages) {
|
|
645
|
+
const input = this.normalize(message);
|
|
646
|
+
if (input && physicalRouteKey(input.route) === physicalRouteKey(route)) {
|
|
647
|
+
await this.resolveReply(message, input);
|
|
648
|
+
inputs.push(input);
|
|
649
|
+
}
|
|
650
|
+
}
|
|
651
|
+
const next = messages[messages.length - 1]!.id;
|
|
652
|
+
if (BigInt(next) <= BigInt(cursor)) throw new Error("Discord catchup cursor did not advance");
|
|
653
|
+
cursor = next;
|
|
654
|
+
if (page.size < 100) break;
|
|
655
|
+
}
|
|
656
|
+
return inputs;
|
|
657
|
+
}
|
|
658
|
+
|
|
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");
|
|
662
|
+
}
|
|
663
|
+
const member = await channel.guild.members.fetchMe({ force: true });
|
|
664
|
+
const permissions = channel.permissionsFor(member);
|
|
665
|
+
if (!permissions) throw new DeliveryError("Discord bot channel permissions could not be resolved", "rejected");
|
|
666
|
+
// Forum/media posts require SEND_MESSAGES, not CREATE_PUBLIC_THREADS.
|
|
667
|
+
// Reading and replying must also work for the resulting native topic.
|
|
668
|
+
// https://docs.discord.com/developers/topics/threads#creating-threads-in-forum-and-media-channels
|
|
669
|
+
return permissions.has([PermissionFlagsBits.ViewChannel, PermissionFlagsBits.ReadMessageHistory,
|
|
670
|
+
PermissionFlagsBits.SendMessages, PermissionFlagsBits.SendMessagesInThreads]);
|
|
671
|
+
}
|
|
672
|
+
|
|
673
|
+
/** Read-only capability checks never enable features or choose forum tags. */
|
|
674
|
+
async canCreateThread(route: Route): Promise<boolean> {
|
|
675
|
+
this.assertRoute(route);
|
|
676
|
+
if (!route.guildId || route.threadId !== null) return false;
|
|
677
|
+
try {
|
|
678
|
+
const channel = await this.channel(route, true);
|
|
679
|
+
if (channel.type === ChannelType.GuildForum || channel.type === ChannelType.GuildMedia) return await this.forumThreadAllowed(channel);
|
|
680
|
+
if (channel.type !== ChannelType.GuildText && channel.type !== ChannelType.GuildAnnouncement) return false;
|
|
681
|
+
const member = await channel.guild.members.fetchMe({ force: true });
|
|
682
|
+
const permissions = channel.permissionsFor(member);
|
|
683
|
+
if (!permissions) throw new DeliveryError("Discord bot channel permissions could not be resolved", "rejected");
|
|
684
|
+
// A new announcement thread needs a starter message; both destinations
|
|
685
|
+
// must also allow the bot to participate in the thread it creates.
|
|
686
|
+
// https://docs.discord.com/developers/topics/threads#permissions
|
|
687
|
+
return permissions.has([PermissionFlagsBits.ViewChannel, PermissionFlagsBits.SendMessages,
|
|
688
|
+
PermissionFlagsBits.CreatePublicThreads, PermissionFlagsBits.SendMessagesInThreads]);
|
|
689
|
+
} catch (error) { throw deliveryError(error); }
|
|
690
|
+
}
|
|
691
|
+
|
|
692
|
+
async createThread(route: Route, title: string, sourceMessageId?: string): Promise<Route> {
|
|
693
|
+
this.assertRoute(route);
|
|
694
|
+
if (!route.guildId) throw new DeliveryError("Discord DMs cannot create threads; provide an explicit authorized guild target", "rejected");
|
|
695
|
+
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");
|
|
697
|
+
try {
|
|
698
|
+
// Forum/media roots cannot receive ordinary messages, but can create
|
|
699
|
+
// native starter-message posts within this same authorized destination.
|
|
700
|
+
const channel = await this.channel(route, true);
|
|
701
|
+
let thread;
|
|
702
|
+
if (channel.type === ChannelType.GuildForum || channel.type === ChannelType.GuildMedia) {
|
|
703
|
+
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 } });
|
|
706
|
+
} else if (channel.type !== ChannelType.GuildText && channel.type !== ChannelType.GuildAnnouncement) {
|
|
707
|
+
throw new DeliveryError("This guild channel cannot create a public conversation thread", "rejected");
|
|
708
|
+
} else if (sourceMessageId) {
|
|
709
|
+
if (!/^[0-9]{1,20}$/.test(sourceMessageId)) throw new DeliveryError("Invalid thread source message ID", "rejected");
|
|
710
|
+
const source = await channel.messages.fetch(sourceMessageId);
|
|
711
|
+
if (source.id !== sourceMessageId || source.channelId !== route.channelId || source.guildId !== route.guildId) throw new DeliveryError("Discord thread source does not belong to this destination", "rejected");
|
|
712
|
+
thread = await source.startThread({ name: title });
|
|
713
|
+
} else if (channel.type === ChannelType.GuildAnnouncement) {
|
|
714
|
+
// Announcement threads can only be started from a real message.
|
|
715
|
+
const starter = await channel.send({ content: title, allowedMentions: NO_MENTIONS });
|
|
716
|
+
if (starter.channelId !== route.channelId || starter.guildId !== route.guildId || starter.author.id !== this.client.user?.id) throw new DeliveryError("Discord thread starter had an unexpected destination", "uncertain");
|
|
717
|
+
thread = await starter.startThread({ name: title });
|
|
718
|
+
} else {
|
|
719
|
+
thread = await channel.threads.create({ name: title, type: ChannelType.PublicThread });
|
|
720
|
+
}
|
|
721
|
+
const created = this.route(thread);
|
|
722
|
+
if (!created || created.threadId === null || created.guildId !== route.guildId || created.channelId !== route.channelId) throw new DeliveryError("Created Discord thread had an unexpected destination", "uncertain");
|
|
723
|
+
return created;
|
|
724
|
+
} catch (error) { throw deliveryError(error); }
|
|
725
|
+
}
|
|
726
|
+
|
|
727
|
+
async stop(): Promise<void> {
|
|
728
|
+
this.connected = false;
|
|
729
|
+
if (this.admission) {
|
|
730
|
+
this.admission.stopped = true;
|
|
731
|
+
this.admission.stop();
|
|
732
|
+
}
|
|
733
|
+
this.client.off(Events.MessageCreate, this.onMessage);
|
|
734
|
+
this.client.off(Events.MessageUpdate, this.onEdit);
|
|
735
|
+
this.client.off(Events.InteractionCreate, this.onInteraction);
|
|
736
|
+
this.client.off(Events.ShardResume, this.onReconnect);
|
|
737
|
+
this.client.off(Events.ShardReady, this.onReconnect);
|
|
738
|
+
this.client.off(Events.Error, this.report);
|
|
739
|
+
await this.intake;
|
|
740
|
+
this.handlers = null;
|
|
741
|
+
for (const pending of this.pending.values()) pending.active = false;
|
|
742
|
+
this.pending.clear();
|
|
743
|
+
await this.client.destroy();
|
|
744
|
+
}
|
|
745
|
+
}
|