omp-superagent 0.0.0-stage → 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.
- package/DESIGN.md +1502 -0
- package/LICENSE +21 -0
- package/README.ko.md +198 -0
- package/README.md +224 -2
- package/THIRD_PARTY_NOTICES.md +388 -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 +1178 -0
- package/docs/discord-voice.md +96 -0
- package/docs/releases/0.1.0.md +222 -0
- package/docs/releases/0.1.1.md +60 -0
- package/docs/releases/0.1.2.md +53 -0
- package/package.json +65 -4
- package/scripts/ci.ts +33 -0
- package/scripts/prepare-ulw.ts +18 -0
- package/scripts/release.ts +58 -0
- package/scripts/setup.sh +25 -0
- package/scripts/test-omp.sh +36 -0
- package/skills/head/SKILL.md +100 -0
- package/skills/head/references/model-selection.md +83 -0
- package/skills/head/references/routing.md +181 -0
- package/skills/head/references/supervision.md +122 -0
- package/skills/lane/SKILL.md +66 -0
- package/skills/lane/references/workflow.md +95 -0
- package/src/autostart.ts +295 -0
- package/src/board-extension.ts +217 -0
- package/src/board.ts +396 -0
- package/src/cli.ts +253 -0
- package/src/codex-live-bridge.py +73 -0
- package/src/codex-live.ts +244 -0
- package/src/codex-voice-requirements.txt +5 -0
- package/src/codex_live_auth.py +192 -0
- package/src/codex_live_media.py +219 -0
- package/src/codex_live_provider.py +192 -0
- package/src/config.ts +266 -0
- package/src/contracts.ts +381 -0
- package/src/credentials.ts +172 -0
- package/src/decision-tool.ts +59 -0
- package/src/decisions.ts +143 -0
- package/src/delivery.ts +17 -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-context.ts +118 -0
- package/src/discord-markdown.ts +172 -0
- package/src/discord-voice-draft.ts +124 -0
- package/src/discord-voice-link.ts +270 -0
- package/src/discord-voice.ts +150 -0
- package/src/discord.ts +1012 -0
- package/src/extension.ts +446 -0
- package/src/gateway-client.ts +229 -0
- package/src/gateway-protocol.ts +85 -0
- package/src/gateway-restart.ts +151 -0
- package/src/gateway-server.ts +440 -0
- package/src/gateway-store.ts +251 -0
- package/src/gateway.ts +654 -0
- package/src/head-recovery.ts +61 -0
- package/src/host-broker-services.ts +108 -0
- package/src/host-extension.ts +561 -0
- package/src/host-owner.ts +366 -0
- package/src/host-protocol.ts +144 -0
- package/src/host-services.ts +54 -0
- package/src/host.ts +415 -0
- package/src/installed-omp.ts +71 -0
- package/src/lane-extension.ts +184 -0
- package/src/lane-models.ts +75 -0
- package/src/lane-report.ts +70 -0
- package/src/lane-rows.ts +12 -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 +143 -0
- package/src/native-presets.ts +370 -0
- package/src/native-sessions.ts +32 -0
- package/src/native-settings.ts +131 -0
- package/src/openai-live.ts +377 -0
- package/src/pr-github-schema.ts +110 -0
- package/src/pr-github.ts +170 -0
- package/src/pr-watch.ts +200 -0
- package/src/repository.ts +12 -0
- package/src/runtime.ts +4229 -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 +779 -0
- package/src/store.ts +862 -0
- package/src/telegram-command-registration.ts +155 -0
- package/src/telegram.ts +677 -0
- package/src/workflow.ts +94 -0
- package/upstream/ulw.json +9 -0
package/src/discord.ts
ADDED
|
@@ -0,0 +1,1012 @@
|
|
|
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, type PermissionsBitField,
|
|
7
|
+
} from "discord.js";
|
|
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";
|
|
11
|
+
import { parseDialog, type Dialog } from "./dialog.ts";
|
|
12
|
+
import { approvalCardToken, DeliveryError } from "./delivery.ts";
|
|
13
|
+
import { parseDiscordCommand } from "./discord-commands.ts";
|
|
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";
|
|
18
|
+
|
|
19
|
+
// Reference (not copied): gimso2x/ompbot @ 4d2eb28d0bf66644892dc0fc333580d0eb7e7780,
|
|
20
|
+
// src/discord/{adapter,attachments,channel,transport}.ts (MIT, ompbot contributors).
|
|
21
|
+
// discord.js owns Gateway/REST, including nonce serialization. Nonces are only a
|
|
22
|
+
// short-window server dedupe aid, never an exactly-once delivery guarantee.
|
|
23
|
+
const NO_MENTIONS = { parse: [] as never[], repliedUser: false };
|
|
24
|
+
const FILE_LIMIT = 8 * 1024 * 1024;
|
|
25
|
+
const MESSAGE_LIMIT = 2000;
|
|
26
|
+
const SELECT_PAGE_SIZE = 25;
|
|
27
|
+
const SELECT_TEXT_LIMIT = 100;
|
|
28
|
+
type Handlers = Parameters<Messenger["start"]>[0];
|
|
29
|
+
type Controls = ActionRowBuilder<ButtonBuilder | StringSelectMenuBuilder>[];
|
|
30
|
+
type Answer = NonNullable<DialogResponse["answers"]>[number];
|
|
31
|
+
interface Pending {
|
|
32
|
+
approval: Approval; token: string; dialog: Dialog; messageId: string | null;
|
|
33
|
+
active: boolean; busy: boolean; question: number; answers: Answer[];
|
|
34
|
+
selected: string[]; customInput?: string;
|
|
35
|
+
}
|
|
36
|
+
interface Admission {
|
|
37
|
+
ready: Promise<boolean>;
|
|
38
|
+
resolvedReady: boolean;
|
|
39
|
+
stopped: boolean;
|
|
40
|
+
stop(): void;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export interface DiscordMessengerOptions {
|
|
44
|
+
token: string;
|
|
45
|
+
ownerId: string;
|
|
46
|
+
allowedGuildIds: string[];
|
|
47
|
+
allowedChannelIds: string[];
|
|
48
|
+
voice?: DiscordVoiceConfig;
|
|
49
|
+
voiceApiKey?: string;
|
|
50
|
+
/** A supported discord.js Client, primarily for deterministic transport tests. */
|
|
51
|
+
client?: Client;
|
|
52
|
+
/** Attachment HTTP boundary; Discord credentials are never sent to the CDN. */
|
|
53
|
+
fetch?: (input: string | URL | Request, init?: RequestInit) => Promise<Response>;
|
|
54
|
+
store?: Pick<StorePort, "getMeta" | "setMeta">;
|
|
55
|
+
onError?: (error: unknown) => void;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Only an explicit client-side or HTTP rejection establishes non-delivery. */
|
|
59
|
+
export function deliveryError(error: unknown): DeliveryError {
|
|
60
|
+
if (error instanceof DeliveryError) return error;
|
|
61
|
+
const record = error !== null && typeof error === "object" ? error as Record<string, unknown> : {};
|
|
62
|
+
const status = typeof record.status === "number" ? record.status : undefined;
|
|
63
|
+
const retryAfter = typeof record.retryAfter === "number" ? record.retryAfter : undefined;
|
|
64
|
+
const rejected = record.name === "RateLimitError" || (status !== undefined && status >= 400 && status < 500 && status !== 408);
|
|
65
|
+
return new DeliveryError(error instanceof Error ? error.message : "Discord delivery failed", rejected ? "rejected" : "uncertain", retryAfter, { cause: error });
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function hash(value: string): string { return createHash("sha256").update(value).digest("hex").slice(0, 24); }
|
|
69
|
+
export function discordNonce(id: string, route: Route, part = 0): string { return hash(JSON.stringify([id, routeKey(route), part])); }
|
|
70
|
+
|
|
71
|
+
export function discordAttachmentAllowed(value: string): boolean {
|
|
72
|
+
try {
|
|
73
|
+
const url = new URL(value);
|
|
74
|
+
return url.protocol === "https:" && !url.username && !url.password && (!url.port || url.port === "443") &&
|
|
75
|
+
!url.hash && (url.hostname === "cdn.discordapp.com" || url.hostname === "media.discordapp.net") &&
|
|
76
|
+
/^\/attachments\/[0-9]+\/[0-9]+\/[^/]+$/.test(url.pathname) && !/%(?:2f|5c)/i.test(url.pathname);
|
|
77
|
+
} catch { return false; }
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export function parseDiscordControl(value: string): { token: string; action: string } | null {
|
|
81
|
+
const match = /^omp:([a-f0-9]{24}):([a-z]+(?:-[0-9]+)?)$/.exec(value);
|
|
82
|
+
return match?.[0] === value ? { token: match[1]!, action: match[2]! } : null;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function object(value: unknown): value is Record<string, unknown> { return !!value && typeof value === "object" && !Array.isArray(value); }
|
|
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
|
+
}
|
|
90
|
+
|
|
91
|
+
/** Keep Discord capacity checks separate from shared native dialog semantics. */
|
|
92
|
+
function discordDialog(request: Record<string, unknown>): Dialog {
|
|
93
|
+
if (request.secret === true) return parseDialog(request); // Reject before inspecting any secret content.
|
|
94
|
+
// Reserve room for question labels, controls, and a 4000-character free-text
|
|
95
|
+
// response when a request must be displayed through a text attachment.
|
|
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.");
|
|
97
|
+
const dialog = parseDialog(request);
|
|
98
|
+
if (dialog.method === "ask") for (const question of dialog.questions) {
|
|
99
|
+
if (question.options.length > SELECT_PAGE_SIZE) unsupported("Ask options exceed Discord limits.");
|
|
100
|
+
for (const option of question.options) {
|
|
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.");
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
if (dialog.method === "input" || dialog.method === "editor") {
|
|
106
|
+
if (dialog.title.length > 45 || dialog.title.length === 0) unsupported("Input title cannot fit a Discord modal.");
|
|
107
|
+
if (dialog.placeholder && dialog.placeholder.length > 100) unsupported("Input placeholder cannot fit a Discord modal.");
|
|
108
|
+
if (dialog.prefill && dialog.prefill.length > 4000) unsupported("Editor content exceeds Discord's 4000-character modal limit.");
|
|
109
|
+
}
|
|
110
|
+
return dialog;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
export class DiscordMessenger implements Messenger {
|
|
114
|
+
readonly client: Client;
|
|
115
|
+
private readonly guilds: Set<string>;
|
|
116
|
+
private readonly channels: Set<string>;
|
|
117
|
+
private handlers: Handlers | null = null;
|
|
118
|
+
private connected = false;
|
|
119
|
+
private admission: Admission | null = null;
|
|
120
|
+
private intake: Promise<void> = Promise.resolve();
|
|
121
|
+
private readonly pending = new Map<string, Pending>();
|
|
122
|
+
private readonly report: (error: unknown) => void;
|
|
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); };
|
|
144
|
+
private readonly onInteraction = (interaction: Interaction) => { void this.interact(interaction).catch(this.report); };
|
|
145
|
+
private readonly onReconnect = () => {
|
|
146
|
+
if (!this.connected) return;
|
|
147
|
+
this.voiceConnected = true;
|
|
148
|
+
const admission = this.admission;
|
|
149
|
+
this.intake = this.intake.then(async () => {
|
|
150
|
+
if (await this.admitted(admission)) await this.handlers?.reconnect?.();
|
|
151
|
+
}).catch(this.report);
|
|
152
|
+
};
|
|
153
|
+
|
|
154
|
+
constructor(private readonly options: DiscordMessengerOptions) {
|
|
155
|
+
this.guilds = new Set(options.allowedGuildIds);
|
|
156
|
+
this.channels = new Set(options.allowedChannelIds);
|
|
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);
|
|
160
|
+
this.client = options.client ?? new Client({
|
|
161
|
+
intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.DirectMessages, GatewayIntentBits.MessageContent,
|
|
162
|
+
...(options.voice ? [GatewayIntentBits.GuildVoiceStates] : [])],
|
|
163
|
+
partials: [Partials.Channel, Partials.Message],
|
|
164
|
+
allowedMentions: NO_MENTIONS,
|
|
165
|
+
rest: { retries: 0, rejectOnRateLimit: () => true },
|
|
166
|
+
});
|
|
167
|
+
// Disable discord.js's default retries even on an injected supported Client.
|
|
168
|
+
this.client.rest.options.retries = 0;
|
|
169
|
+
this.client.rest.options.rejectOnRateLimit = () => true;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
async start(handlers: Handlers): Promise<void> {
|
|
173
|
+
if (this.handlers) throw new Error("Discord messenger is already started");
|
|
174
|
+
this.handlers = handlers;
|
|
175
|
+
const stopped = Promise.withResolvers<boolean>();
|
|
176
|
+
this.admission = {
|
|
177
|
+
ready: Promise.race([
|
|
178
|
+
(handlers.ready ?? Promise.resolve()).then(() => true, () => {
|
|
179
|
+
this.report(new Error("Discord startup readiness failed; intake remains disabled"));
|
|
180
|
+
return false;
|
|
181
|
+
}),
|
|
182
|
+
stopped.promise,
|
|
183
|
+
]),
|
|
184
|
+
resolvedReady: handlers.ready === undefined,
|
|
185
|
+
stopped: false,
|
|
186
|
+
stop: () => { stopped.resolve(false); },
|
|
187
|
+
};
|
|
188
|
+
const admission = this.admission;
|
|
189
|
+
void admission.ready.then(ready => { admission.resolvedReady = ready; });
|
|
190
|
+
this.client.on(Events.MessageCreate, this.onMessage);
|
|
191
|
+
this.client.on(Events.MessageUpdate, this.onEdit);
|
|
192
|
+
this.client.on(Events.InteractionCreate, this.onInteraction);
|
|
193
|
+
this.client.on(Events.ShardResume, this.onReconnect);
|
|
194
|
+
this.client.on(Events.ShardDisconnect, this.onVoiceDisconnect);
|
|
195
|
+
this.client.on(Events.ShardReconnecting, this.onVoiceDisconnect);
|
|
196
|
+
this.client.on(Events.ShardReady, this.onReconnect);
|
|
197
|
+
this.client.on(Events.Error, this.report);
|
|
198
|
+
try {
|
|
199
|
+
if (!this.client.isReady()) {
|
|
200
|
+
const { promise, resolve } = Promise.withResolvers<void>();
|
|
201
|
+
const ready = () => { resolve(); };
|
|
202
|
+
this.client.once(Events.ClientReady, ready);
|
|
203
|
+
try { await this.client.login(this.options.token); await promise; }
|
|
204
|
+
finally { this.client.off(Events.ClientReady, ready); }
|
|
205
|
+
}
|
|
206
|
+
this.connected = true;
|
|
207
|
+
this.voiceConnected = true;
|
|
208
|
+
} catch (error) { await this.stop(); throw error; }
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
private async admitted(admission = this.admission): Promise<boolean> {
|
|
212
|
+
return !!admission && await admission.ready && !admission.stopped && this.admission === admission;
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
private route(channel: { id: string; isThread(): boolean; parentId?: string | null; guildId?: string | null }): Route | null {
|
|
216
|
+
const accountId = this.client.user?.id;
|
|
217
|
+
if (!accountId) return null;
|
|
218
|
+
const guildId = channel.guildId ?? null;
|
|
219
|
+
const threadId = channel.isThread() ? channel.id : null;
|
|
220
|
+
const channelId = threadId ? channel.parentId : channel.id;
|
|
221
|
+
if (!channelId || (guildId && (!this.guilds.has(guildId) || !this.channels.has(channelId)))) return null;
|
|
222
|
+
return { platform: "discord", accountId, authorityId: this.options.ownerId, guildId, channelId, threadId };
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
private enqueue(message: Message | PartialMessage, fresh: boolean): void {
|
|
226
|
+
const admission = this.admission;
|
|
227
|
+
const voiceEpoch = this.voiceConnected && admission?.resolvedReady ? this.voiceEpoch : null;
|
|
228
|
+
this.intake = this.intake.then(async () => {
|
|
229
|
+
if (!await this.admitted(admission)) return;
|
|
230
|
+
// Check destination and known author before even fetching a partial message.
|
|
231
|
+
if (!this.route(message.channel) || (message.author && (message.author.bot || message.author.id !== this.options.ownerId))) return;
|
|
232
|
+
if (!message.guildId && "recipientId" in message.channel && message.channel.recipientId !== this.options.ownerId) return;
|
|
233
|
+
const full = message.partial ? await message.fetch() : message;
|
|
234
|
+
const inbound = this.normalize(full, "pointer");
|
|
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
|
+
}
|
|
242
|
+
await this.resolveReply(full, inbound);
|
|
243
|
+
await this.handlers?.message(inbound);
|
|
244
|
+
}
|
|
245
|
+
}).catch(this.report);
|
|
246
|
+
}
|
|
247
|
+
|
|
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 {
|
|
250
|
+
if (message.author.bot || message.author.id !== this.options.ownerId || message.webhookId) return null;
|
|
251
|
+
const route = this.route(message.channel);
|
|
252
|
+
if (!route || (message.type !== 0 && message.type !== 19)) return null;
|
|
253
|
+
if (!route.guildId && (message.channel.type !== ChannelType.DM || message.channel.recipientId !== this.options.ownerId)) return null;
|
|
254
|
+
const attachments = [...message.attachments.values()].filter(file => discordAttachmentAllowed(file.url) &&
|
|
255
|
+
typeof file.size === "number" && Number.isSafeInteger(file.size) && file.size >= 0).map(file => ({
|
|
256
|
+
id: file.id, name: file.name, url: file.url, size: file.size,
|
|
257
|
+
...(file.contentType ? { contentType: file.contentType } : {}),
|
|
258
|
+
...(message.flags?.has(MessageFlags.IsVoiceMessage) ? { voice: true as const } : {}),
|
|
259
|
+
...(typeof file.duration === "number" && Number.isFinite(file.duration) && file.duration >= 0 ? { durationSeconds: file.duration } : {}),
|
|
260
|
+
}));
|
|
261
|
+
// Stickers, whitespace, and filtered attachments are not instructions. This
|
|
262
|
+
// also ignores contentless edits instead of replacing an admitted intent.
|
|
263
|
+
if (!message.content.trim() && attachments.length === 0) return null;
|
|
264
|
+
const reply = this.replyPointer(message);
|
|
265
|
+
if (reply && replyContext === "cached") this.snapshotReply(message, message.channel.messages.cache?.get(reply.messageId), reply);
|
|
266
|
+
// CDN URLs carry expiring signatures; refreshing one must not create a new
|
|
267
|
+
// input revision for an unchanged Discord edit.
|
|
268
|
+
// Reply/voice snapshots are context, not a new edit or download identity.
|
|
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
|
+
}
|
|
275
|
+
return {
|
|
276
|
+
id: `discord:${route.accountId}:${message.id}:${revision}`, route, messageId: message.id,
|
|
277
|
+
text: message.content, receivedAt: message.editedTimestamp ?? message.createdTimestamp, attachments,
|
|
278
|
+
...(reply ? { reply } : {}),
|
|
279
|
+
discordContext: this.context(route, message.channel),
|
|
280
|
+
};
|
|
281
|
+
}
|
|
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
|
+
|
|
345
|
+
private replyPointer(message: Message): ReplyContext | undefined {
|
|
346
|
+
const reference = message.reference;
|
|
347
|
+
// discord.js caches embedded referenced_message in this channel's manager.
|
|
348
|
+
// Never use fetchReference(): it follows the reference's channel selector.
|
|
349
|
+
if (message.type !== 19 || !reference?.messageId || !/^[0-9]{1,20}$/.test(reference.messageId) ||
|
|
350
|
+
reference.channelId !== message.channelId || (reference.guildId !== undefined && reference.guildId !== message.guildId)) return;
|
|
351
|
+
return { messageId: reference.messageId, authorId: null, text: null };
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
private snapshotReply(message: Message, referenced: Message | undefined, reply: ReplyContext): boolean {
|
|
355
|
+
if (!referenced || referenced.partial || referenced.id !== reply.messageId ||
|
|
356
|
+
referenced.channelId !== message.channelId || referenced.guildId !== message.guildId) return false;
|
|
357
|
+
reply.authorId = referenced.author?.id ?? 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;
|
|
361
|
+
return true;
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
private async resolveReply(message: Message, input: Inbound): Promise<void> {
|
|
365
|
+
if (!input.reply || this.snapshotReply(message, message.channel.messages.cache?.get(input.reply.messageId), input.reply)) return;
|
|
366
|
+
try {
|
|
367
|
+
const referenced = await message.channel.messages.fetch({ message: input.reply.messageId, cache: false });
|
|
368
|
+
this.snapshotReply(message, referenced, input.reply);
|
|
369
|
+
} catch {
|
|
370
|
+
// Missing/deleted/inaccessible originals retain only their same-channel
|
|
371
|
+
// pointer; failure to obtain context must not lose the owner's message.
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
private assertRoute(route: Route): void {
|
|
376
|
+
if (route.platform !== "discord" || route.accountId !== this.client.user?.id || route.authorityId !== this.options.ownerId ||
|
|
377
|
+
!route.channelId || (!route.guildId && route.threadId !== null) ||
|
|
378
|
+
(route.guildId && (!this.guilds.has(route.guildId) || !this.channels.has(route.channelId)))) {
|
|
379
|
+
throw new DeliveryError("Discord route is not authorized for this bot and owner", "rejected");
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
private async channel(route: Route, force = false) {
|
|
384
|
+
this.assertRoute(route);
|
|
385
|
+
const channel = await this.client.channels.fetch(route.threadId ?? route.channelId, { force });
|
|
386
|
+
if (!channel) throw new DeliveryError("Discord destination cannot receive messages", "rejected");
|
|
387
|
+
const actual = this.route(channel);
|
|
388
|
+
if (!actual || physicalRouteKey(actual) !== physicalRouteKey(route)) throw new DeliveryError("Discord destination identity changed", "rejected");
|
|
389
|
+
if (!route.guildId && (channel.type !== ChannelType.DM || channel.recipientId !== this.options.ownerId)) throw new DeliveryError("Discord DM does not belong to the owner", "rejected");
|
|
390
|
+
return channel;
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
private async destination(route: Route) {
|
|
394
|
+
const channel = await this.channel(route);
|
|
395
|
+
if (!channel.isSendable()) throw new DeliveryError("Discord destination cannot receive messages", "rejected");
|
|
396
|
+
return channel;
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
async openAttachment(route: Route, attachment: Attachment, signal: AbortSignal): Promise<Response> {
|
|
400
|
+
this.assertRoute(route);
|
|
401
|
+
if (typeof attachment.size !== "number" || !Number.isSafeInteger(attachment.size) || attachment.size < 0 ||
|
|
402
|
+
!discordAttachmentAllowed(attachment.url)) throw new DeliveryError("Attachment is not an authorized Discord CDN attachment", "rejected");
|
|
403
|
+
const url = new URL(attachment.url);
|
|
404
|
+
const [, , channelId, attachmentId] = url.pathname.split("/");
|
|
405
|
+
if (channelId !== (route.threadId ?? route.channelId) || attachmentId !== attachment.id) {
|
|
406
|
+
throw new DeliveryError("Discord attachment does not belong to this destination and resource", "rejected");
|
|
407
|
+
}
|
|
408
|
+
await this.destination(route);
|
|
409
|
+
try {
|
|
410
|
+
// The CDN uses its signed resource URL, never the bot's API credential.
|
|
411
|
+
return await (this.options.fetch ?? fetch)(url, { redirect: "error", credentials: "omit", signal });
|
|
412
|
+
} catch {
|
|
413
|
+
throw new DeliveryError("Discord attachment download failed", "rejected");
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
private payload(text: string, nonce: string, components?: Controls): MessageCreateOptions {
|
|
418
|
+
// Discord renders no markdown tables, so outbound tables become aligned fences.
|
|
419
|
+
// The stored OutputRecord text is never modified; only this payload changes.
|
|
420
|
+
const content = renderDiscordMarkdown(text, FILE_LIMIT);
|
|
421
|
+
if (Buffer.byteLength(content, "utf8") > FILE_LIMIT) throw new DeliveryError("Discord text attachment exceeds the safe 8 MiB upload limit", "rejected");
|
|
422
|
+
return {
|
|
423
|
+
...(content.length <= MESSAGE_LIMIT ? { content: content || "(empty output)" } : {
|
|
424
|
+
content: "Full text is attached (exceeds Discord's message limit).",
|
|
425
|
+
files: [new AttachmentBuilder(Buffer.from(content, "utf8"), { name: `omp-${nonce}.txt` })],
|
|
426
|
+
}),
|
|
427
|
+
allowedMentions: NO_MENTIONS, nonce, enforceNonce: true, ...(components ? { components } : {}),
|
|
428
|
+
};
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
async send(output: OutputRecord): Promise<string> {
|
|
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
|
+
}
|
|
438
|
+
const channel = await this.destination(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);
|
|
446
|
+
return message.id;
|
|
447
|
+
} catch (error) { throw deliveryError(error); }
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
async setActivity(message: MessageReference, activity: MessageActivity): Promise<void> {
|
|
451
|
+
try {
|
|
452
|
+
if (!/^[0-9]{1,20}$/.test(message.messageId)) throw new DeliveryError("Activity requires a Discord message snowflake", "rejected");
|
|
453
|
+
const channel = await this.destination(message.route);
|
|
454
|
+
const emoji = activity === "received" ? "\u{1F440}" : "\u{1F4AD}";
|
|
455
|
+
const reaction = Routes.channelMessageOwnReaction(channel.id, message.messageId, encodeURIComponent(emoji));
|
|
456
|
+
if (activity === "idle") await this.client.rest.delete(reaction);
|
|
457
|
+
else await this.client.rest.put(reaction);
|
|
458
|
+
} catch (error) {
|
|
459
|
+
const failure = deliveryError(error);
|
|
460
|
+
throw new DeliveryError("Discord activity update failed", failure.certainty, failure.retryAfterMs);
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
private control(pending: Pending, action: string): string { return `omp:${pending.token}:${action}`; }
|
|
465
|
+
private button(pending: Pending, action: string, label: string, style = ButtonStyle.Secondary): ButtonBuilder {
|
|
466
|
+
return new ButtonBuilder().setCustomId(this.control(pending, action)).setLabel(label).setStyle(style);
|
|
467
|
+
}
|
|
468
|
+
private view(pending: Pending, selectPage?: number): { content: string; components: Controls } {
|
|
469
|
+
const dialog = pending.dialog;
|
|
470
|
+
const cancel = this.button(pending, "cancel", "Cancel");
|
|
471
|
+
if (dialog.method === "confirm") return {
|
|
472
|
+
content: `${dialog.title}\n\n${dialog.message}`,
|
|
473
|
+
components: [new ActionRowBuilder<ButtonBuilder>().addComponents(this.button(pending, "yes", "Confirm", ButtonStyle.Danger), this.button(pending, "no", "Decline"), cancel)],
|
|
474
|
+
};
|
|
475
|
+
if (dialog.method === "input" || dialog.method === "editor") return {
|
|
476
|
+
content: `${dialog.title}\nOpen the editor to respond. Discord inputs are not secret; maximum 4000 characters.`,
|
|
477
|
+
components: [new ActionRowBuilder<ButtonBuilder>().addComponents(this.button(pending, "open", "Respond", ButtonStyle.Primary), cancel)],
|
|
478
|
+
};
|
|
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);
|
|
486
|
+
const marker = (index: number) => index >= dialog.markableCount || !dialog.marker ? "" : dialog.marker === "checkbox" ? (dialog.checked.includes(index) ? "☑️" : "⬜") : "⚪";
|
|
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);
|
|
503
|
+
return {
|
|
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],
|
|
509
|
+
};
|
|
510
|
+
}
|
|
511
|
+
const question = dialog.questions[pending.question]!;
|
|
512
|
+
const components: Controls = [];
|
|
513
|
+
if (question.options.length) components.push(new ActionRowBuilder<StringSelectMenuBuilder>().addComponents(
|
|
514
|
+
new StringSelectMenuBuilder().setCustomId(this.control(pending, `choose-${pending.question}`)).setMinValues(0).setMaxValues(question.multi ? question.options.length : 1)
|
|
515
|
+
.addOptions(question.options.map((option, index) => ({ label: option.label, value: String(index), default: pending.selected.includes(option.label), ...(option.description ? { description: option.description } : {}) }))),
|
|
516
|
+
));
|
|
517
|
+
components.push(new ActionRowBuilder<ButtonBuilder>().addComponents(
|
|
518
|
+
this.button(pending, `other-${pending.question}`, "Other / free text"),
|
|
519
|
+
this.button(pending, `next-${pending.question}`, pending.question + 1 === dialog.questions.length ? "Submit all answers" : "Next question", ButtonStyle.Primary), cancel,
|
|
520
|
+
));
|
|
521
|
+
const previews = question.options.map((option, index) => `${index + 1}. ${option.label}${index === question.recommended ? " (recommended, not preselected)" : ""}${option.preview ? `\n${option.preview}` : ""}`).join("\n");
|
|
522
|
+
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 };
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
async showApproval(approval: Approval): Promise<string> {
|
|
526
|
+
this.assertRoute(approval.route);
|
|
527
|
+
if (!this.handlers) throw new DeliveryError("Discord messenger is not started", "rejected");
|
|
528
|
+
if (approval.state !== "pending") throw new DeliveryError("Discord approval is no longer pending", "rejected");
|
|
529
|
+
const token = approvalCardToken(approval);
|
|
530
|
+
const existing = this.pending.get(token);
|
|
531
|
+
if (existing?.active && existing.messageId) {
|
|
532
|
+
if (approval.remoteId && approval.remoteId !== existing.messageId) throw new DeliveryError("Discord approval receipt does not match its active control", "rejected");
|
|
533
|
+
return existing.messageId;
|
|
534
|
+
}
|
|
535
|
+
for (const pending of this.pending.values()) if (pending.approval.id === approval.id) await this.dismissApproval(pending.approval);
|
|
536
|
+
let dialog: Dialog;
|
|
537
|
+
try { dialog = discordDialog(approval.request); }
|
|
538
|
+
catch (error) {
|
|
539
|
+
const channel = await this.destination(approval.route);
|
|
540
|
+
const notice = `Request cancelled: ${error instanceof Error ? error.message : "Unsupported dialog."}`;
|
|
541
|
+
let message: Message;
|
|
542
|
+
try {
|
|
543
|
+
const payload = this.payload(notice, discordNonce(`approval-cancel:${token}`, approval.route));
|
|
544
|
+
if (approval.remoteId) {
|
|
545
|
+
message = await channel.messages.fetch(approval.remoteId);
|
|
546
|
+
this.assertApprovalMessage(message, approval, token);
|
|
547
|
+
await message.edit({ content: payload.content, files: payload.files, attachments: [], components: [], allowedMentions: NO_MENTIONS });
|
|
548
|
+
} else message = await channel.send(payload);
|
|
549
|
+
}
|
|
550
|
+
catch (failure) { throw deliveryError(failure); }
|
|
551
|
+
await this.handlers.answer(approval.id, { cancelled: true }, approval.route);
|
|
552
|
+
return message.id;
|
|
553
|
+
}
|
|
554
|
+
const pending: Pending = { approval: { ...approval, route: { ...approval.route } }, token, dialog, messageId: approval.remoteId, active: false, busy: false, question: 0, answers: [], selected: [] };
|
|
555
|
+
const view = this.view(pending);
|
|
556
|
+
this.pending.set(token, pending);
|
|
557
|
+
try {
|
|
558
|
+
const channel = await this.destination(approval.route);
|
|
559
|
+
const payload = this.payload(view.content, discordNonce(`approval:${token}`, approval.route), view.components);
|
|
560
|
+
let message: Message;
|
|
561
|
+
if (approval.remoteId) {
|
|
562
|
+
message = await channel.messages.fetch(approval.remoteId);
|
|
563
|
+
this.assertApprovalMessage(message, approval, token);
|
|
564
|
+
await message.edit({ content: payload.content, files: payload.files, attachments: [], components: view.components, allowedMentions: NO_MENTIONS });
|
|
565
|
+
} else message = await channel.send(payload);
|
|
566
|
+
pending.messageId = message.id;
|
|
567
|
+
pending.active = true;
|
|
568
|
+
return message.id;
|
|
569
|
+
} catch (error) { pending.active = false; this.pending.delete(token); throw deliveryError(error); }
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
private assertApprovalMessage(message: Message, approval: Approval, token: string): void {
|
|
573
|
+
const source: Route = {
|
|
574
|
+
...physicalRoute(approval.route), accountId: message.author.id, guildId: message.guildId,
|
|
575
|
+
channelId: approval.route.threadId ? approval.route.channelId : message.channelId,
|
|
576
|
+
threadId: approval.route.threadId ? message.channelId : null,
|
|
577
|
+
};
|
|
578
|
+
if ((approval.remoteId && message.id !== approval.remoteId) || message.author.id !== this.client.user?.id || physicalRouteKey(source) !== physicalRouteKey(approval.route)) {
|
|
579
|
+
throw new DeliveryError("Discord approval message does not belong to this bot and destination", "rejected");
|
|
580
|
+
}
|
|
581
|
+
for (const row of message.components) {
|
|
582
|
+
if (!("components" in row)) continue;
|
|
583
|
+
for (const component of row.components) {
|
|
584
|
+
if ("customId" in component && component.customId && parseDiscordControl(component.customId)?.token !== token) {
|
|
585
|
+
throw new DeliveryError("Discord message belongs to a different approval identity", "rejected");
|
|
586
|
+
}
|
|
587
|
+
}
|
|
588
|
+
}
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
private async refresh(pending: Pending, selectPage?: number): Promise<void> {
|
|
592
|
+
if (!pending.messageId || !pending.active) return;
|
|
593
|
+
const channel = await this.destination(pending.approval.route);
|
|
594
|
+
const message = await channel.messages.fetch(pending.messageId);
|
|
595
|
+
this.assertApprovalMessage(message, pending.approval, pending.token);
|
|
596
|
+
const view = this.view(pending, selectPage);
|
|
597
|
+
const payload = this.payload(view.content, discordNonce(`approval:${pending.token}`, pending.approval.route), view.components);
|
|
598
|
+
await message.edit({ content: payload.content, files: payload.files, attachments: [], components: view.components, allowedMentions: NO_MENTIONS });
|
|
599
|
+
}
|
|
600
|
+
|
|
601
|
+
async dismissApproval(approval: Approval): Promise<void> {
|
|
602
|
+
this.assertRoute(approval.route);
|
|
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));
|
|
604
|
+
for (const pending of matches) pending.active = false;
|
|
605
|
+
const messageIds = new Set([approval.remoteId, ...matches.map(pending => pending.messageId)].filter((id): id is string => !!id));
|
|
606
|
+
const token = approvalCardToken(approval);
|
|
607
|
+
try {
|
|
608
|
+
const channel = await this.destination(approval.route);
|
|
609
|
+
for (const id of messageIds) {
|
|
610
|
+
try {
|
|
611
|
+
const message = await channel.messages.fetch(id);
|
|
612
|
+
this.assertApprovalMessage(message, approval, token);
|
|
613
|
+
await message.edit({ components: [], allowedMentions: NO_MENTIONS });
|
|
614
|
+
}
|
|
615
|
+
catch (error) {
|
|
616
|
+
if (object(error) && (error.code === 10008 || error.code === 10003)) continue; // Already deleted.
|
|
617
|
+
throw error;
|
|
618
|
+
}
|
|
619
|
+
}
|
|
620
|
+
for (const pending of matches) this.pending.delete(pending.token);
|
|
621
|
+
} catch (error) { throw deliveryError(error); }
|
|
622
|
+
}
|
|
623
|
+
|
|
624
|
+
private modal(pending: Pending, action: string): ModalBuilder {
|
|
625
|
+
const dialog = pending.dialog;
|
|
626
|
+
const ask = dialog.method === "ask";
|
|
627
|
+
const title = ask ? "Other answer" : (dialog as Extract<Dialog, { method: "input" | "editor" }>).title;
|
|
628
|
+
const input = new TextInputBuilder().setCustomId("value").setLabel(ask ? "Your answer (not secret)" : "Response (not secret)").setRequired(false).setMaxLength(4000)
|
|
629
|
+
.setStyle(dialog.method === "input" ? TextInputStyle.Short : TextInputStyle.Paragraph);
|
|
630
|
+
if (dialog.method === "input" && dialog.placeholder) input.setPlaceholder(dialog.placeholder);
|
|
631
|
+
const prefill = ask ? pending.customInput : dialog.method === "editor" ? dialog.prefill : undefined;
|
|
632
|
+
if (prefill) input.setValue(prefill);
|
|
633
|
+
return new ModalBuilder().setCustomId(this.control(pending, action)).setTitle(title).addComponents(new ActionRowBuilder<TextInputBuilder>().addComponents(input));
|
|
634
|
+
}
|
|
635
|
+
|
|
636
|
+
private async finish(pending: Pending, response: DialogResponse, interaction: { deferUpdate(): Promise<unknown> }): Promise<void> {
|
|
637
|
+
validateDecisionResponse(pending.approval, response);
|
|
638
|
+
// The handler's receipt is the durable admission boundary. Until it resolves,
|
|
639
|
+
// leave the original control and draft actionable, without acknowledging it.
|
|
640
|
+
await this.handlers!.answer(pending.approval.id, response, pending.approval.route);
|
|
641
|
+
// Admission succeeded: ACK/cleanup failures must never resubmit the answer.
|
|
642
|
+
pending.active = false;
|
|
643
|
+
try { await interaction.deferUpdate(); }
|
|
644
|
+
finally { await this.dismissApproval(pending.approval); }
|
|
645
|
+
}
|
|
646
|
+
|
|
647
|
+
private async commandReply(interaction: ChatInputCommandInteraction, content: string): Promise<void> {
|
|
648
|
+
try { await interaction.reply({ content, flags: MessageFlags.Ephemeral, allowedMentions: NO_MENTIONS }); }
|
|
649
|
+
catch {
|
|
650
|
+
// SDK errors can contain the interaction response URL and its secret token.
|
|
651
|
+
// A failed/expired ACK never replays admission or falls back to a followup.
|
|
652
|
+
this.report(new Error("Discord command acknowledgement failed; admission was not retried"));
|
|
653
|
+
}
|
|
654
|
+
}
|
|
655
|
+
|
|
656
|
+
private async command(interaction: ChatInputCommandInteraction): Promise<void> {
|
|
657
|
+
const handlers = this.handlers;
|
|
658
|
+
const admission = this.admission;
|
|
659
|
+
const deny = (content: string) => this.commandReply(interaction, content);
|
|
660
|
+
if (!this.client.application?.id || interaction.applicationId !== this.client.application.id || !this.client.user?.id) {
|
|
661
|
+
await deny("This command does not belong to the connected Superagent application."); return;
|
|
662
|
+
}
|
|
663
|
+
if (interaction.user.bot || interaction.user.id !== this.options.ownerId) {
|
|
664
|
+
await deny("Only the configured owner can use Superagent commands."); return;
|
|
665
|
+
}
|
|
666
|
+
const text = parseDiscordCommand(interaction.commandName, interaction.options.data);
|
|
667
|
+
if (text === null) {
|
|
668
|
+
await deny("This Superagent command or its options are unsupported or stale; nothing was admitted."); return;
|
|
669
|
+
}
|
|
670
|
+
// Commands have a three-second initial response deadline. Unlike ordinary
|
|
671
|
+
// messages/components, never wait for readiness or the serialized intake.
|
|
672
|
+
if (!this.connected || !handlers || !admission?.resolvedReady || admission.stopped) {
|
|
673
|
+
await deny("Superagent is not ready to accept commands; nothing was admitted."); return;
|
|
674
|
+
}
|
|
675
|
+
if (!/^[0-9]{1,20}$/.test(interaction.id) || !Number.isFinite(interaction.createdTimestamp) || !interaction.channelId ||
|
|
676
|
+
(interaction.guildId !== null && !this.guilds.has(interaction.guildId))) {
|
|
677
|
+
await deny("This conversation is not authorized for Superagent commands."); return;
|
|
678
|
+
}
|
|
679
|
+
let route: Route | null;
|
|
680
|
+
let discordContext: DiscordContext | undefined;
|
|
681
|
+
try {
|
|
682
|
+
// This resolves a channel, never a command's interaction ID as a message.
|
|
683
|
+
const channel = interaction.channel ?? await this.client.channels.fetch(interaction.channelId);
|
|
684
|
+
route = channel ? this.route(channel) : null;
|
|
685
|
+
if (!channel || channel.id !== interaction.channelId || !route || route.guildId !== interaction.guildId ||
|
|
686
|
+
!channel.isSendable() || (!route.guildId && (channel.type !== ChannelType.DM || channel.recipientId !== this.options.ownerId))) {
|
|
687
|
+
await deny("This conversation is not authorized for Superagent commands."); return;
|
|
688
|
+
}
|
|
689
|
+
discordContext = this.context(route, channel);
|
|
690
|
+
} catch {
|
|
691
|
+
this.report(new Error("Discord command destination verification failed; nothing was admitted"));
|
|
692
|
+
await deny("Superagent could not verify this conversation; nothing was admitted."); return;
|
|
693
|
+
}
|
|
694
|
+
if (!this.connected || this.handlers !== handlers || this.admission !== admission || admission.stopped || !admission.resolvedReady) {
|
|
695
|
+
await deny("Superagent is not ready to accept commands; nothing was admitted."); return;
|
|
696
|
+
}
|
|
697
|
+
try {
|
|
698
|
+
// The captured handler resolves only after durable admission. Do not
|
|
699
|
+
// defer an apparent success before this boundary or persist response tokens.
|
|
700
|
+
await handlers.message({
|
|
701
|
+
id: `discord:${route.accountId}:interaction:${interaction.id}`, route, messageId: null,
|
|
702
|
+
interactionId: interaction.id, text, receivedAt: interaction.createdTimestamp, attachments: [],
|
|
703
|
+
...(discordContext ? { discordContext } : {}),
|
|
704
|
+
});
|
|
705
|
+
} catch {
|
|
706
|
+
this.report(new Error("Discord command durable admission could not be confirmed; admission was not retried"));
|
|
707
|
+
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.");
|
|
708
|
+
return;
|
|
709
|
+
}
|
|
710
|
+
await this.commandReply(interaction, "Superagent accepted this command. Its result will be sent to this conversation.");
|
|
711
|
+
}
|
|
712
|
+
|
|
713
|
+
private async interact(interaction: Interaction): Promise<void> {
|
|
714
|
+
if (interaction.isChatInputCommand()) { await this.command(interaction); return; }
|
|
715
|
+
if (!interaction.isButton() && !interaction.isStringSelectMenu() && !interaction.isModalSubmit()) return;
|
|
716
|
+
const parsed = parseDiscordControl(interaction.customId);
|
|
717
|
+
if (!parsed) return;
|
|
718
|
+
if (!await this.admitted()) return;
|
|
719
|
+
const pending = this.pending.get(parsed.token);
|
|
720
|
+
const deny = async (content: string) => { await interaction.reply({ content, flags: MessageFlags.Ephemeral, allowedMentions: NO_MENTIONS }); };
|
|
721
|
+
if (interaction.user.id !== this.options.ownerId) { await deny("Only the configured owner can answer this request."); return; }
|
|
722
|
+
if (!pending?.active || pending.busy || !this.handlers) { await deny("This request is expired or already being handled."); return; }
|
|
723
|
+
const route = pending.approval.route;
|
|
724
|
+
const message = interaction.isModalSubmit() ? (interaction.isFromMessage() ? interaction.message : null) : interaction.message;
|
|
725
|
+
const source: Route = {
|
|
726
|
+
...physicalRoute(route), accountId: message?.author.id ?? "", authorityId: interaction.user.id, guildId: interaction.guildId,
|
|
727
|
+
channelId: route.threadId ? route.channelId : interaction.channelId ?? "",
|
|
728
|
+
threadId: route.threadId ? interaction.channelId : null,
|
|
729
|
+
};
|
|
730
|
+
if (!message || message.id !== pending.messageId || physicalRouteKey(source) !== physicalRouteKey(route) ||
|
|
731
|
+
message.channelId !== (route.threadId ?? route.channelId) || message.guildId !== route.guildId) {
|
|
732
|
+
await deny("This control does not belong to this destination or request."); return;
|
|
733
|
+
}
|
|
734
|
+
this.assertRoute(route);
|
|
735
|
+
const action = parsed.action;
|
|
736
|
+
const dialog = pending.dialog;
|
|
737
|
+
if (interaction.isButton() && action === "open" && (dialog.method === "input" || dialog.method === "editor")) {
|
|
738
|
+
await interaction.showModal(this.modal(pending, "value")); return;
|
|
739
|
+
}
|
|
740
|
+
if (interaction.isButton() && dialog.method === "ask" && action === `other-${pending.question}`) {
|
|
741
|
+
await interaction.showModal(this.modal(pending, `custom-${pending.question}`)); return;
|
|
742
|
+
}
|
|
743
|
+
pending.busy = true;
|
|
744
|
+
try {
|
|
745
|
+
if (interaction.isButton() && action === "cancel") { await this.finish(pending, { cancelled: true }, interaction); return; }
|
|
746
|
+
if (dialog.method === "confirm" && interaction.isButton() && (action === "yes" || action === "no")) {
|
|
747
|
+
await this.finish(pending, { confirmed: action === "yes" }, interaction); return;
|
|
748
|
+
}
|
|
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;
|
|
759
|
+
const index = interaction.values[0];
|
|
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;
|
|
765
|
+
}
|
|
766
|
+
if ((dialog.method === "input" || dialog.method === "editor") && interaction.isModalSubmit() && action === "value") {
|
|
767
|
+
await this.finish(pending, { value: interaction.fields.getTextInputValue("value") }, interaction); return;
|
|
768
|
+
}
|
|
769
|
+
if (dialog.method === "ask") {
|
|
770
|
+
const question = dialog.questions[pending.question]!;
|
|
771
|
+
if (interaction.isStringSelectMenu() && action === `choose-${pending.question}`) {
|
|
772
|
+
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");
|
|
773
|
+
await interaction.deferUpdate(); // Partial draft progress, not a final answer.
|
|
774
|
+
pending.selected = interaction.values.map(value => question.options[Number(value)]!.label);
|
|
775
|
+
if (!question.multi && pending.selected.length) pending.customInput = undefined;
|
|
776
|
+
} else if (interaction.isModalSubmit() && action === `custom-${pending.question}`) {
|
|
777
|
+
await interaction.deferUpdate();
|
|
778
|
+
pending.customInput = interaction.fields.getTextInputValue("value").trim() || undefined;
|
|
779
|
+
if (!question.multi && pending.customInput) pending.selected = [];
|
|
780
|
+
} else if (interaction.isButton() && action === `next-${pending.question}`) {
|
|
781
|
+
const answer: Answer = { id: question.id, selectedOptions: [...pending.selected], ...(pending.customInput ? { customInput: pending.customInput } : {}) };
|
|
782
|
+
if (pending.approval.decision) validateDecisionAnswer(question, answer);
|
|
783
|
+
if (pending.question + 1 === dialog.questions.length) {
|
|
784
|
+
await this.finish(pending, { answers: [...pending.answers, answer] }, interaction); return;
|
|
785
|
+
}
|
|
786
|
+
await interaction.deferUpdate();
|
|
787
|
+
pending.answers.push(answer);
|
|
788
|
+
pending.question++;
|
|
789
|
+
pending.selected = [];
|
|
790
|
+
pending.customInput = undefined;
|
|
791
|
+
} else return;
|
|
792
|
+
await this.refresh(pending);
|
|
793
|
+
}
|
|
794
|
+
} finally { pending.busy = false; }
|
|
795
|
+
}
|
|
796
|
+
|
|
797
|
+
/** Only the caller's stored, already-authorized cursor; never bootstrap history. */
|
|
798
|
+
async fetchAfter(route: Route, messageId: string): Promise<Inbound[]> {
|
|
799
|
+
if (!/^[0-9]{1,20}$/.test(messageId)) throw new DeliveryError("Catchup requires a stored Discord message snowflake", "rejected");
|
|
800
|
+
const channel = await this.destination(physicalRoute(route));
|
|
801
|
+
const inputs: Inbound[] = [];
|
|
802
|
+
let cursor = messageId;
|
|
803
|
+
for (;;) {
|
|
804
|
+
const page = await channel.messages.fetch({ after: cursor, limit: 100, cache: false });
|
|
805
|
+
const messages = [...page.values()].sort((left, right) => BigInt(left.id) < BigInt(right.id) ? -1 : 1);
|
|
806
|
+
if (!messages.length) break;
|
|
807
|
+
for (const message of messages) {
|
|
808
|
+
const input = this.normalize(message, "pointer");
|
|
809
|
+
if (input && !this.isVoiceControl(input) && physicalRouteKey(input.route) === physicalRouteKey(route)) {
|
|
810
|
+
await this.resolveReply(message, input);
|
|
811
|
+
inputs.push(input);
|
|
812
|
+
}
|
|
813
|
+
}
|
|
814
|
+
const next = messages[messages.length - 1]!.id;
|
|
815
|
+
if (BigInt(next) <= BigInt(cursor)) throw new Error("Discord catchup cursor did not advance");
|
|
816
|
+
cursor = next;
|
|
817
|
+
if (page.size < 100) break;
|
|
818
|
+
}
|
|
819
|
+
return inputs;
|
|
820
|
+
}
|
|
821
|
+
|
|
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
|
+
}
|
|
836
|
+
}
|
|
837
|
+
}
|
|
838
|
+
|
|
839
|
+
private async forumThreadAllowed(channel: ForumChannel | MediaChannel, appliedTags?: readonly string[]): Promise<boolean> {
|
|
840
|
+
const member = await channel.guild.members.fetchMe({ force: true });
|
|
841
|
+
const permissions = channel.permissionsFor(member);
|
|
842
|
+
if (!permissions) throw new DeliveryError("Discord bot channel permissions could not be resolved", "rejected");
|
|
843
|
+
this.forumTags(channel, appliedTags, permissions);
|
|
844
|
+
// Forum/media posts require SEND_MESSAGES, not CREATE_PUBLIC_THREADS.
|
|
845
|
+
// Reading and replying must also work for the resulting native topic.
|
|
846
|
+
// https://docs.discord.com/developers/topics/threads#creating-threads-in-forum-and-media-channels
|
|
847
|
+
return permissions.has([PermissionFlagsBits.ViewChannel, PermissionFlagsBits.ReadMessageHistory,
|
|
848
|
+
PermissionFlagsBits.SendMessages, PermissionFlagsBits.SendMessagesInThreads]);
|
|
849
|
+
}
|
|
850
|
+
|
|
851
|
+
/** Read-only capability checks never enable features or choose forum tags. */
|
|
852
|
+
async canCreateThread(route: Route, appliedTags?: readonly string[]): Promise<boolean> {
|
|
853
|
+
this.assertRoute(route);
|
|
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
|
+
}
|
|
858
|
+
try {
|
|
859
|
+
const channel = await this.channel(route, true);
|
|
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");
|
|
862
|
+
if (channel.type !== ChannelType.GuildText && channel.type !== ChannelType.GuildAnnouncement) return false;
|
|
863
|
+
const member = await channel.guild.members.fetchMe({ force: true });
|
|
864
|
+
const permissions = channel.permissionsFor(member);
|
|
865
|
+
if (!permissions) throw new DeliveryError("Discord bot channel permissions could not be resolved", "rejected");
|
|
866
|
+
// A new announcement thread needs a starter message; both destinations
|
|
867
|
+
// must also allow the bot to participate in the thread it creates.
|
|
868
|
+
// https://docs.discord.com/developers/topics/threads#permissions
|
|
869
|
+
return permissions.has([PermissionFlagsBits.ViewChannel, PermissionFlagsBits.SendMessages,
|
|
870
|
+
PermissionFlagsBits.CreatePublicThreads, PermissionFlagsBits.SendMessagesInThreads]);
|
|
871
|
+
} catch (error) { throw deliveryError(error); }
|
|
872
|
+
}
|
|
873
|
+
|
|
874
|
+
async createThread(route: Route, title: string, sourceMessageId?: string, appliedTags?: readonly string[]): Promise<Route> {
|
|
875
|
+
this.assertRoute(route);
|
|
876
|
+
if (!route.guildId) throw new DeliveryError("Discord DMs cannot create threads; provide an explicit authorized guild target", "rejected");
|
|
877
|
+
if (route.threadId) throw new DeliveryError("Discord cannot nest threads; provide an explicit parent-channel target", "rejected");
|
|
878
|
+
if (typeof title !== "string" || !title.trim() || title.length > 100) throw new DeliveryError("Discord thread title must contain 1–100 characters", "rejected");
|
|
879
|
+
try {
|
|
880
|
+
// Forum/media roots cannot receive ordinary messages, but can create
|
|
881
|
+
// native starter-message posts within this same authorized destination.
|
|
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
|
+
}
|
|
886
|
+
let thread;
|
|
887
|
+
if (channel.type === ChannelType.GuildForum || channel.type === ChannelType.GuildMedia) {
|
|
888
|
+
if (sourceMessageId !== undefined) throw new DeliveryError("Discord forum/media topics cannot reuse a source message; provide the authorized parent without a source", "rejected");
|
|
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 } });
|
|
892
|
+
} else if (channel.type !== ChannelType.GuildText && channel.type !== ChannelType.GuildAnnouncement) {
|
|
893
|
+
throw new DeliveryError("This guild channel cannot create a public conversation thread", "rejected");
|
|
894
|
+
} else if (sourceMessageId) {
|
|
895
|
+
if (!/^[0-9]{1,20}$/.test(sourceMessageId)) throw new DeliveryError("Invalid thread source message ID", "rejected");
|
|
896
|
+
const source = await channel.messages.fetch(sourceMessageId);
|
|
897
|
+
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");
|
|
898
|
+
thread = await source.startThread({ name: title });
|
|
899
|
+
} else if (channel.type === ChannelType.GuildAnnouncement) {
|
|
900
|
+
// Announcement threads can only be started from a real message.
|
|
901
|
+
const starter = await channel.send({ content: title, allowedMentions: NO_MENTIONS });
|
|
902
|
+
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");
|
|
903
|
+
thread = await starter.startThread({ name: title });
|
|
904
|
+
} else {
|
|
905
|
+
thread = await channel.threads.create({ name: title, type: ChannelType.PublicThread });
|
|
906
|
+
}
|
|
907
|
+
const created = this.route(thread);
|
|
908
|
+
if (!created || created.threadId === null || created.guildId !== route.guildId || created.channelId !== route.channelId) throw new DeliveryError("Created Discord thread had an unexpected destination", "uncertain");
|
|
909
|
+
return created;
|
|
910
|
+
} catch (error) { throw deliveryError(error); }
|
|
911
|
+
}
|
|
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
|
+
|
|
991
|
+
async stop(): Promise<void> {
|
|
992
|
+
this.connected = false;
|
|
993
|
+
this.onVoiceDisconnect();
|
|
994
|
+
if (this.admission) {
|
|
995
|
+
this.admission.stopped = true;
|
|
996
|
+
this.admission.stop();
|
|
997
|
+
}
|
|
998
|
+
this.client.off(Events.MessageCreate, this.onMessage);
|
|
999
|
+
this.client.off(Events.MessageUpdate, this.onEdit);
|
|
1000
|
+
this.client.off(Events.InteractionCreate, this.onInteraction);
|
|
1001
|
+
this.client.off(Events.ShardResume, this.onReconnect);
|
|
1002
|
+
this.client.off(Events.ShardDisconnect, this.onVoiceDisconnect);
|
|
1003
|
+
this.client.off(Events.ShardReconnecting, this.onVoiceDisconnect);
|
|
1004
|
+
this.client.off(Events.ShardReady, this.onReconnect);
|
|
1005
|
+
this.client.off(Events.Error, this.report);
|
|
1006
|
+
await this.intake;
|
|
1007
|
+
this.handlers = null;
|
|
1008
|
+
for (const pending of this.pending.values()) pending.active = false;
|
|
1009
|
+
this.pending.clear();
|
|
1010
|
+
await this.client.destroy();
|
|
1011
|
+
}
|
|
1012
|
+
}
|