@arnilo/prism-hosts 0.13.1 → 0.14.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +2 -0
- package/a2a/README.md +195 -0
- package/a2a/src/card.ts +208 -0
- package/a2a/src/codec.ts +523 -0
- package/a2a/src/connect.ts +415 -0
- package/a2a/src/errors.ts +87 -0
- package/a2a/src/index.ts +40 -0
- package/a2a/src/limits.ts +43 -0
- package/a2a/src/pending.ts +28 -0
- package/a2a/src/proxy.ts +526 -0
- package/a2a/src/serve.ts +886 -0
- package/acp/README.md +3 -1
- package/acp/src/limits.ts +3 -16
- package/acp/src/mapper.ts +26 -5
- package/acp/src/serve.ts +6 -5
- package/ag-ui/README.md +2 -1
- package/ag-ui/src/a2ui.ts +8 -31
- package/ag-ui/src/ag-ui-mapper.ts +27 -1
- package/ag-ui/src/encrypted-value.ts +3 -3
- package/ag-ui/src/handler.ts +4 -4
- package/ag-ui/src/index.ts +0 -33
- package/ag-ui/src/limits.ts +5 -88
- package/ag-ui/src/projectors.ts +8 -6
- package/ag-ui/src/renderer/bind.ts +2 -1
- package/channels/README.md +61 -5
- package/channels/src/discord-gateway.ts +354 -0
- package/channels/src/discord.ts +873 -0
- package/channels/src/index.ts +4 -2
- package/channels/src/limits.ts +3 -19
- package/channels/src/pairing.ts +1 -2
- package/channels/src/runtime-turn.ts +10 -2
- package/channels/src/signal.ts +11 -19
- package/channels/src/slack.ts +854 -0
- package/channels/src/telegram.ts +22 -44
- package/channels/src/types.ts +5 -2
- package/devtools/README.md +1 -1
- package/driver-process/src/driver.ts +3 -1
- package/driver-process/src/testing.ts +1 -1
- package/driver-process/src/turn.ts +5 -1
- package/evals/README.md +11 -7
- package/evals/src/calibration.ts +5 -13
- package/evals/src/compare-experiments.ts +1 -2
- package/evals/src/comparison.ts +7 -25
- package/evals/src/curate.ts +3 -9
- package/evals/src/dataset.ts +0 -2
- package/evals/src/index.ts +3 -20
- package/evals/src/injection.ts +33 -6
- package/evals/src/judge.ts +9 -13
- package/evals/src/limits.ts +0 -17
- package/evals/src/rubric-judge.ts +5 -10
- package/evals/src/scenario-runner.ts +8 -4
- package/evals/src/scenarios.ts +5 -5
- package/evals/src/score.ts +3 -5
- package/evals/src/stats.ts +0 -2
- package/evals/src/threshold.ts +3 -3
- package/evals/src/toolless-session.ts +7 -3
- package/evals/src/trace.ts +8 -14
- package/evals/src/trajectory.ts +45 -11
- package/evals/src/types.ts +2 -2
- package/evals/src/user-simulator.ts +1 -7
- package/evals/src/util.ts +3 -9
- package/headless/README.md +20 -1
- package/headless/src/authority.ts +14 -1
- package/headless/src/errors.ts +3 -1
- package/headless/src/index.ts +10 -1
- package/headless/src/limits.ts +2 -2
- package/headless/src/pending.ts +4 -3
- package/headless/src/recover.ts +126 -0
- package/headless/src/resume.ts +1 -1
- package/host-builder/data/api.json +1271 -1360
- package/host-builder/data/errors.json +199 -185
- package/host-builder/data/examples/a2a-client.ts +125 -0
- package/host-builder/data/examples/a2a-server.ts +133 -0
- package/host-builder/data/examples/autonomous-coding-loop.ts +1 -1
- package/host-builder/data/examples/build-workflow.ts +2 -2
- package/host-builder/data/examples/caveman-ponytail.ts +1 -1
- package/host-builder/data/examples/channel-discord.ts +176 -0
- package/host-builder/data/examples/channel-slack.ts +146 -0
- package/host-builder/data/examples/continue-after-failure.ts +80 -0
- package/host-builder/data/examples/custom-adapter.ts +1 -1
- package/host-builder/data/examples/decision-models.ts +1 -1
- package/host-builder/data/examples/define-package.ts +1 -1
- package/host-builder/data/examples/delegate.ts +74 -9
- package/host-builder/data/examples/durable-loops-and-approvals.ts +11 -10
- package/host-builder/data/examples/governance-deny.ts +1 -1
- package/host-builder/data/examples/guardrail-content.ts +126 -0
- package/host-builder/data/examples/headless-host.ts +1 -1
- package/host-builder/data/examples/long-running-job.ts +129 -0
- package/host-builder/data/examples/long-term-memory.ts +1 -1
- package/host-builder/data/examples/mcp-oauth.ts +197 -0
- package/host-builder/data/examples/mcp-trust.ts +1 -1
- package/host-builder/data/examples/memory-and-wiki.ts +2 -2
- package/host-builder/data/examples/memory-system.ts +19 -9
- package/host-builder/data/examples/model-router-aggregate-budgets.ts +1 -1
- package/host-builder/data/examples/parallel-tools.ts +70 -0
- package/host-builder/data/examples/remote-agent.ts +1 -1
- package/host-builder/data/examples/serve-tools.ts +1 -1
- package/host-builder/data/examples/session-memory.ts +18 -16
- package/host-builder/data/examples/side-call.ts +1 -1
- package/host-builder/data/examples/sqlite-resume.ts +1 -1
- package/host-builder/data/examples/structured-output.ts +57 -0
- package/host-builder/data/examples.json +14 -4
- package/host-builder/skills/prism-host-builder/SKILL.md +1 -1
- package/host-builder/skills/prism-host-builder/references/choosing.md +14 -10
- package/host-builder/skills/prism-host-builder/references/pitfalls.md +5 -3
- package/host-builder/skills/prism-host-builder/references/recipes.md +5 -5
- package/host-builder/skills/prism-host-builder/references/verification.md +1 -1
- package/host-builder/src/check/runner.ts +2 -3
- package/host-builder/src/server.ts +2 -2
- package/mcp-server/README.md +3 -3
- package/mcp-server/src/bounds.ts +3 -3
- package/mcp-server/src/serve-tools.ts +2 -9
- package/mcp-server/src/serve.ts +2 -4
- package/mcp-server/src/server.ts +10 -20
- package/package.json +12 -6
- package/remote/README.md +7 -4
- package/remote/src/channel.ts +6 -2
- package/remote/src/connect.ts +9 -3
- package/remote/src/errors.ts +3 -1
- package/remote/src/limits.ts +3 -13
- package/remote/src/mirror.ts +2 -1
- package/remote/src/pending.ts +4 -3
- package/remote/src/protocol.ts +3 -0
- package/remote/src/serve.ts +43 -5
- package/remote/src/session-proxy.ts +28 -5
- package/remote/src/testing.ts +3 -1
- package/remote/src/wire.ts +74 -14
|
@@ -0,0 +1,873 @@
|
|
|
1
|
+
// Plan 236 Task 5: native-fetch Discord adapter on the shared channel runtime. Importing and
|
|
2
|
+
// constructing are inert; the Gateway opens only in `start`, and the optional Interactions endpoint
|
|
3
|
+
// is host-mounted. Messages and component clicks feed one parser and await `admit`.
|
|
4
|
+
import { createPublicKey, type KeyObject, verify } from "node:crypto";
|
|
5
|
+
import type { Agent } from "@arnilo/prism";
|
|
6
|
+
import type { CheckpointStore, LeaseStore } from "./checkpoint-contract.js";
|
|
7
|
+
import { createDiscordGateway, DISCORD_GATEWAY_INTENTS, type DiscordGateway, type DiscordSocket } from "./discord-gateway.js";
|
|
8
|
+
import { bindChannelHostUi } from "./host-ui.js";
|
|
9
|
+
import { retryableAdmission } from "./admission.js";
|
|
10
|
+
import { type ChannelSecretSource, resolveChannelSecretRef, createChannelRedactor } from "./secret-ref.js";
|
|
11
|
+
import { createMemoryCheckpointStore, createMemoryLeaseStore } from "./memory-stores.js";
|
|
12
|
+
import { createChannelRuntime } from "./runtime.js";
|
|
13
|
+
import type {
|
|
14
|
+
ChannelAdapter,
|
|
15
|
+
ChannelAssistantDelta,
|
|
16
|
+
ChannelAuthorizeInput,
|
|
17
|
+
ChannelAuthorization,
|
|
18
|
+
ChannelConnectionHandle,
|
|
19
|
+
ChannelInboundEvent,
|
|
20
|
+
ChannelLimits,
|
|
21
|
+
ChannelReceive,
|
|
22
|
+
ChannelReplyControl,
|
|
23
|
+
} from "./types.js";
|
|
24
|
+
|
|
25
|
+
export type { ChannelConnectionHandle, ChannelSecretSource, DiscordSocket };
|
|
26
|
+
export { DISCORD_GATEWAY_INTENTS };
|
|
27
|
+
|
|
28
|
+
const DEFAULT_API_ORIGIN = "https://discord.com";
|
|
29
|
+
const API_PATH = "/api/v10";
|
|
30
|
+
/** A message's `content` holds at most 2,000 characters. */
|
|
31
|
+
const DISCORD_TEXT_CODE_UNITS = 2_000;
|
|
32
|
+
/** Discord's replay window is not specified; signed interactions older than this are refused. */
|
|
33
|
+
const SIGNATURE_WINDOW_SECONDS = 300;
|
|
34
|
+
const DEFAULT_MAX_REQUEST_BYTES = 128 * 1024;
|
|
35
|
+
const DEFAULT_MAX_FRAME_BYTES = 1024 * 1024;
|
|
36
|
+
const MAX_SEND_ATTEMPTS = 5;
|
|
37
|
+
const MAX_RETRY_AFTER_SECONDS = 60;
|
|
38
|
+
const DEFAULT_DRAFT_INTERVAL_MS = 1_000;
|
|
39
|
+
const MAX_PREVIEWS = 256;
|
|
40
|
+
const MAX_CONTROLS = 8;
|
|
41
|
+
const BUTTONS_PER_ROW = 5;
|
|
42
|
+
/** `SUPPRESS_EMBEDS`: model text never unfurls links. */
|
|
43
|
+
const SUPPRESS_EMBEDS = 1 << 2;
|
|
44
|
+
const SNOWFLAKE = /^\d{1,20}$/;
|
|
45
|
+
/** No `..` segment, so a token can never walk the callback path. */
|
|
46
|
+
const INTERACTION_TOKEN = /^(?!.*\.\.)[A-Za-z0-9_-][A-Za-z0-9_.-]{0,511}$/;
|
|
47
|
+
const MESSAGE_TYPES = new Set([0, 19]);
|
|
48
|
+
/** Commands the runtime understands; `!new` works where a client would open the slash-command picker. */
|
|
49
|
+
const BANG_COMMAND = /^!(help|status|new|cancel|approve|deny|answer)(?=\s|$)/i;
|
|
50
|
+
const INTERACTION_PING = 1;
|
|
51
|
+
const INTERACTION_COMPONENT = 3;
|
|
52
|
+
const CALLBACK_PONG = 1;
|
|
53
|
+
const CALLBACK_DEFERRED_UPDATE = 6;
|
|
54
|
+
|
|
55
|
+
export interface DiscordAdapterOptions {
|
|
56
|
+
/** Stable host-selected connection id; it is never read from Discord input. */
|
|
57
|
+
readonly connectionId: string;
|
|
58
|
+
/** Bot token, resolved only for REST calls and the Gateway handshake; it never reaches events or errors. */
|
|
59
|
+
readonly botToken: ChannelSecretSource;
|
|
60
|
+
/** Application id; it is also the bot user id until READY reports one. */
|
|
61
|
+
readonly applicationId: string;
|
|
62
|
+
/** Admit messages from other bots and webhooks. The bot's own messages are always ignored. */
|
|
63
|
+
readonly allowBots?: boolean;
|
|
64
|
+
/** Opt-in preview message, edited at most once per `draftIntervalMs` and deleted after the reply. */
|
|
65
|
+
readonly sendDrafts?: boolean;
|
|
66
|
+
/** Minimum interval between preview writes (default 1,000 ms, 100–60,000). */
|
|
67
|
+
readonly draftIntervalMs?: number;
|
|
68
|
+
/** Bounds Interactions endpoint bodies and REST response bodies (default 128 KiB, hard 1 MiB). */
|
|
69
|
+
readonly maxRequestBytes?: number;
|
|
70
|
+
/** Bounds one Gateway frame (default 1 MiB, hard 8 MiB). */
|
|
71
|
+
readonly maxFrameBytes?: number;
|
|
72
|
+
/** Trusted exact HTTPS API origin; defaults to `https://discord.com`. */
|
|
73
|
+
readonly apiOrigin?: string;
|
|
74
|
+
readonly fetch?: typeof globalThis.fetch;
|
|
75
|
+
/** Socket factory for the Gateway; defaults to the global `WebSocket`. */
|
|
76
|
+
readonly webSocket?: (url: string) => DiscordSocket;
|
|
77
|
+
/** First Gateway reconnect delay (default 1,000 ms, doubling to 30 s). */
|
|
78
|
+
readonly reconnectBaseMs?: number;
|
|
79
|
+
/** Heartbeat jitter source in [0, 1); defaults to `Math.random`. */
|
|
80
|
+
readonly random?: () => number;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** Channel adapter with Discord's rate-bounded preview message and Interactions endpoint. */
|
|
84
|
+
export interface DiscordAdapter extends ChannelAdapter {
|
|
85
|
+
/** Fire-and-forget preview of the answer being produced. No-op unless `sendDrafts` is on. */
|
|
86
|
+
sendDraft(delta: ChannelAssistantDelta): void;
|
|
87
|
+
/** One Gateway dispatch (`MESSAGE_CREATE`, `INTERACTION_CREATE`); the Gateway and scripted hosts call it. */
|
|
88
|
+
handleDispatch(type: string, data: unknown, receive: ChannelReceive): Promise<unknown>;
|
|
89
|
+
/** Verified Interactions endpoint. Without a public key it answers 401. */
|
|
90
|
+
handleRequest(request: Request, receive: ChannelReceive, publicKey: KeyObject | undefined): Promise<Response>;
|
|
91
|
+
/** The Gateway's view of the bot (`botUserId` falls back to `applicationId`). */
|
|
92
|
+
gatewayState(): {
|
|
93
|
+
readonly botUserId: string;
|
|
94
|
+
readonly sessionId?: string;
|
|
95
|
+
readonly sequence: number | null;
|
|
96
|
+
readonly connected: boolean;
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
class DiscordApiError extends Error {
|
|
101
|
+
readonly status?: number;
|
|
102
|
+
readonly retryAfter?: number;
|
|
103
|
+
readonly kind: "api" | "credential" | "network" | "response";
|
|
104
|
+
|
|
105
|
+
constructor(shape: { kind: DiscordApiError["kind"]; status?: number; retryAfter?: number }) {
|
|
106
|
+
super("Discord API request failed");
|
|
107
|
+
this.name = "DiscordApiError";
|
|
108
|
+
this.kind = shape.kind;
|
|
109
|
+
this.status = shape.status;
|
|
110
|
+
this.retryAfter = shape.retryAfter;
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
class DiscordDeliveryUnknownError extends Error {
|
|
115
|
+
constructor() {
|
|
116
|
+
super("Discord delivery outcome unknown");
|
|
117
|
+
this.name = "DiscordDeliveryUnknownError";
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
function asRecord(value: unknown): Record<string, unknown> | undefined {
|
|
122
|
+
return typeof value === "object" && value !== null && !Array.isArray(value) ? (value as Record<string, unknown>) : undefined;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
function asSnowflake(value: unknown): string | undefined {
|
|
126
|
+
return typeof value === "string" && SNOWFLAKE.test(value) ? value : undefined;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
function apiOrigin(value: string | undefined): string {
|
|
130
|
+
const raw = value ?? DEFAULT_API_ORIGIN;
|
|
131
|
+
let parsed: URL;
|
|
132
|
+
try {
|
|
133
|
+
parsed = new URL(raw);
|
|
134
|
+
} catch {
|
|
135
|
+
throw new TypeError("Discord apiOrigin must be an exact HTTPS origin");
|
|
136
|
+
}
|
|
137
|
+
if (
|
|
138
|
+
parsed.protocol !== "https:" ||
|
|
139
|
+
parsed.username ||
|
|
140
|
+
parsed.password ||
|
|
141
|
+
parsed.pathname !== "/" ||
|
|
142
|
+
parsed.search ||
|
|
143
|
+
parsed.hash ||
|
|
144
|
+
parsed.origin !== raw
|
|
145
|
+
) {
|
|
146
|
+
throw new TypeError("Discord apiOrigin must be an exact HTTPS origin");
|
|
147
|
+
}
|
|
148
|
+
return parsed.origin;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** A host-set adapter limit, at least `min`. The host's value is the cap (plan 239 Task 5). */
|
|
152
|
+
function boundedInteger(value: number | undefined, fallback: number, min: number, name: string): number {
|
|
153
|
+
const resolved = value ?? fallback;
|
|
154
|
+
if (!Number.isSafeInteger(resolved) || resolved < min) {
|
|
155
|
+
throw new TypeError(`Discord ${name} must be an integer of at least ${min}`);
|
|
156
|
+
}
|
|
157
|
+
return resolved;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/** Split on code points so no chunk exceeds `limit` and no surrogate pair is split. */
|
|
161
|
+
export function chunkDiscordText(text: string, limit: number = DISCORD_TEXT_CODE_UNITS): readonly string[] {
|
|
162
|
+
const chunks: string[] = [];
|
|
163
|
+
let chunk = "";
|
|
164
|
+
for (const codePoint of text) {
|
|
165
|
+
if (chunk.length > 0 && chunk.length + codePoint.length > limit) {
|
|
166
|
+
chunks.push(chunk);
|
|
167
|
+
chunk = "";
|
|
168
|
+
}
|
|
169
|
+
chunk += codePoint;
|
|
170
|
+
}
|
|
171
|
+
if (chunk.length) chunks.push(chunk);
|
|
172
|
+
return chunks;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
function draftText(text: string): string {
|
|
176
|
+
let start = Math.max(0, text.length - DISCORD_TEXT_CODE_UNITS);
|
|
177
|
+
const code = text.charCodeAt(start);
|
|
178
|
+
if (start > 0 && code >= 0xdc00 && code <= 0xdfff) start += 1;
|
|
179
|
+
return text.slice(start);
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/** `<guild>:<channel>` or `dm:<channel>`; a thread is its own channel. Only the adapter builds it. */
|
|
183
|
+
function destination(conversationId: string): string | undefined {
|
|
184
|
+
const [scope, channel, extra] = conversationId.split(":");
|
|
185
|
+
if (extra !== undefined || (scope !== "dm" && asSnowflake(scope) === undefined)) return undefined;
|
|
186
|
+
return asSnowflake(channel);
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
function conversationOf(guildId: string | undefined, channelId: string): string {
|
|
190
|
+
return `${guildId ?? "dm"}:${channelId}`;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
function commandText(text: string): string {
|
|
194
|
+
const trimmed = text.replace(/^(?:\s*<@!?\d{1,20}>)+\s*/, "").trim();
|
|
195
|
+
return BANG_COMMAND.test(trimmed) ? `/${trimmed.slice(1)}` : trimmed;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
function mentions(data: Record<string, unknown>, botUserId: string): boolean {
|
|
199
|
+
if (Array.isArray(data.mentions) && data.mentions.some((user) => asRecord(user)?.id === botUserId)) return true;
|
|
200
|
+
return typeof data.content === "string" && (data.content.includes(`<@${botUserId}>`) || data.content.includes(`<@!${botUserId}>`));
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/**
|
|
204
|
+
* Parse one `MESSAGE_CREATE`. Guild messages are admitted only when they mention the bot; DMs always.
|
|
205
|
+
* The bot's own messages are always ignored, and other bots and webhooks unless `allowBots`.
|
|
206
|
+
*/
|
|
207
|
+
export function parseDiscordMessage(
|
|
208
|
+
connectionId: string,
|
|
209
|
+
data: unknown,
|
|
210
|
+
options: { readonly botUserId: string; readonly allowBots?: boolean },
|
|
211
|
+
): ChannelInboundEvent | undefined {
|
|
212
|
+
const message = asRecord(data);
|
|
213
|
+
const author = asRecord(message?.author);
|
|
214
|
+
if (message === undefined || author === undefined) return undefined;
|
|
215
|
+
const id = asSnowflake(message.id);
|
|
216
|
+
const channelId = asSnowflake(message.channel_id);
|
|
217
|
+
const authorId = asSnowflake(author.id);
|
|
218
|
+
if (id === undefined || channelId === undefined || authorId === undefined || typeof message.content !== "string") return undefined;
|
|
219
|
+
if (authorId === options.botUserId) return undefined;
|
|
220
|
+
if ((author.bot === true || author.system === true || message.webhook_id !== undefined) && options.allowBots !== true) return undefined;
|
|
221
|
+
if (typeof message.type === "number" && !MESSAGE_TYPES.has(message.type)) return undefined;
|
|
222
|
+
const guildId = message.guild_id === undefined ? undefined : asSnowflake(message.guild_id);
|
|
223
|
+
if (message.guild_id !== undefined && guildId === undefined) return undefined;
|
|
224
|
+
if (guildId !== undefined && !mentions(message, options.botUserId)) return undefined;
|
|
225
|
+
const text = commandText(message.content);
|
|
226
|
+
if (text.length === 0) return undefined;
|
|
227
|
+
return {
|
|
228
|
+
connectionId,
|
|
229
|
+
externalConversationId: conversationOf(guildId, channelId),
|
|
230
|
+
externalActorId: authorId,
|
|
231
|
+
eventId: `m:${id}`,
|
|
232
|
+
text,
|
|
233
|
+
receivedAt: new Date().toISOString(),
|
|
234
|
+
claims: {
|
|
235
|
+
platform: "discord",
|
|
236
|
+
...(guildId === undefined ? {} : { guildId }),
|
|
237
|
+
channelType: guildId === undefined ? "dm" : "guild",
|
|
238
|
+
eventType: "message",
|
|
239
|
+
},
|
|
240
|
+
};
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
/** Parse one component interaction whose `custom_id` is a server-issued approval or host-UI control. */
|
|
244
|
+
export function parseDiscordInteraction(
|
|
245
|
+
connectionId: string,
|
|
246
|
+
data: unknown,
|
|
247
|
+
): { readonly event?: ChannelInboundEvent; readonly id: string; readonly token: string } | undefined {
|
|
248
|
+
const interaction = asRecord(data);
|
|
249
|
+
const id = asSnowflake(interaction?.id);
|
|
250
|
+
const token = typeof interaction?.token === "string" && INTERACTION_TOKEN.test(interaction.token) ? interaction.token : undefined;
|
|
251
|
+
if (interaction === undefined || id === undefined || token === undefined || interaction.type !== INTERACTION_COMPONENT) return undefined;
|
|
252
|
+
const ack = { id, token };
|
|
253
|
+
const component = asRecord(interaction.data);
|
|
254
|
+
const user = asRecord(asRecord(interaction.member)?.user) ?? asRecord(interaction.user);
|
|
255
|
+
const userId = asSnowflake(user?.id);
|
|
256
|
+
const channelId = asSnowflake(interaction.channel_id) ?? asSnowflake(asRecord(interaction.channel)?.id);
|
|
257
|
+
const guildId = interaction.guild_id === undefined ? undefined : asSnowflake(interaction.guild_id);
|
|
258
|
+
const value = component?.component_type === 2 && typeof component.custom_id === "string" ? component.custom_id : undefined;
|
|
259
|
+
if (
|
|
260
|
+
userId === undefined ||
|
|
261
|
+
channelId === undefined ||
|
|
262
|
+
value === undefined ||
|
|
263
|
+
(interaction.guild_id !== undefined && guildId === undefined)
|
|
264
|
+
)
|
|
265
|
+
return ack;
|
|
266
|
+
const uiMatch = /^q:([A-Za-z0-9_-]{43}):([0-7])$/.exec(value);
|
|
267
|
+
const match = /^p:([ad]):([A-Za-z0-9_-]{32,64})$/.exec(value);
|
|
268
|
+
if (uiMatch === null && match === null) return ack;
|
|
269
|
+
return {
|
|
270
|
+
...ack,
|
|
271
|
+
event: {
|
|
272
|
+
connectionId,
|
|
273
|
+
externalConversationId: conversationOf(guildId, channelId),
|
|
274
|
+
externalActorId: userId,
|
|
275
|
+
eventId: `i:${id}`,
|
|
276
|
+
text: uiMatch ? `/answer ${uiMatch[1]} ${uiMatch[2]}` : "",
|
|
277
|
+
...(match
|
|
278
|
+
? { approval: { token: match[2] as string, outcome: match[1] === "a" ? ("allow_once" as const) : ("reject_once" as const) } }
|
|
279
|
+
: {}),
|
|
280
|
+
receivedAt: new Date().toISOString(),
|
|
281
|
+
claims: {
|
|
282
|
+
platform: "discord",
|
|
283
|
+
...(guildId === undefined ? {} : { guildId }),
|
|
284
|
+
channelType: guildId === undefined ? "dm" : "guild",
|
|
285
|
+
control: "approval",
|
|
286
|
+
},
|
|
287
|
+
},
|
|
288
|
+
};
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
function actionRows(controls: readonly ChannelReplyControl[] | undefined): Record<string, unknown>[] | null | undefined {
|
|
292
|
+
if (controls === undefined) return undefined;
|
|
293
|
+
if (controls.length === 0 || controls.length > MAX_CONTROLS) return null;
|
|
294
|
+
const rows: Array<{ type: 1; components: Record<string, unknown>[] }> = [];
|
|
295
|
+
for (const [index, control] of controls.entries()) {
|
|
296
|
+
if (
|
|
297
|
+
typeof control?.label !== "string" ||
|
|
298
|
+
typeof control.value !== "string" ||
|
|
299
|
+
control.label.length === 0 ||
|
|
300
|
+
control.label.length > 80 ||
|
|
301
|
+
control.value.length > 100
|
|
302
|
+
) {
|
|
303
|
+
return null;
|
|
304
|
+
}
|
|
305
|
+
if (index % BUTTONS_PER_ROW === 0) rows.push({ type: 1, components: [] });
|
|
306
|
+
rows[rows.length - 1]?.components.push({ type: 2, style: index === 0 ? 1 : 2, label: control.label, custom_id: control.value });
|
|
307
|
+
}
|
|
308
|
+
return rows;
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
function knownSendFailure(error: DiscordApiError): string {
|
|
312
|
+
if (error.status === 429) return "discord_rate_limited";
|
|
313
|
+
if (error.kind === "credential" || error.status === 401) return "discord_unauthorized";
|
|
314
|
+
if (error.status === 403 || error.status === 404) return "discord_forbidden";
|
|
315
|
+
return "discord_api_error";
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
function delay(ms: number, signal: AbortSignal): Promise<void> {
|
|
319
|
+
return new Promise((resolve) => {
|
|
320
|
+
if (signal.aborted || ms <= 0) return resolve();
|
|
321
|
+
const timer = setTimeout(done, ms);
|
|
322
|
+
function done() {
|
|
323
|
+
clearTimeout(timer);
|
|
324
|
+
signal.removeEventListener("abort", done);
|
|
325
|
+
resolve();
|
|
326
|
+
}
|
|
327
|
+
signal.addEventListener("abort", done, { once: true });
|
|
328
|
+
});
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
async function readBody(body: ReadableStream<Uint8Array> | null, maxBytes: number): Promise<Buffer> {
|
|
332
|
+
const reader = body?.getReader();
|
|
333
|
+
if (reader === undefined) return Buffer.alloc(0);
|
|
334
|
+
const chunks: Uint8Array[] = [];
|
|
335
|
+
let size = 0;
|
|
336
|
+
try {
|
|
337
|
+
for (;;) {
|
|
338
|
+
const next = await reader.read();
|
|
339
|
+
if (next.done) break;
|
|
340
|
+
size += next.value.byteLength;
|
|
341
|
+
if (size > maxBytes) {
|
|
342
|
+
await reader.cancel();
|
|
343
|
+
throw new RangeError("body too large");
|
|
344
|
+
}
|
|
345
|
+
chunks.push(next.value);
|
|
346
|
+
}
|
|
347
|
+
} finally {
|
|
348
|
+
reader.releaseLock();
|
|
349
|
+
}
|
|
350
|
+
return Buffer.concat(chunks);
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
function seconds(value: unknown): number | undefined {
|
|
354
|
+
const parsed = typeof value === "number" ? value : typeof value === "string" ? Number(value) : Number.NaN;
|
|
355
|
+
return Number.isFinite(parsed) && parsed >= 0 ? Math.min(parsed, MAX_RETRY_AFTER_SECONDS) : undefined;
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
interface DiscordApi {
|
|
359
|
+
call(
|
|
360
|
+
method: "GET" | "POST" | "PATCH" | "DELETE",
|
|
361
|
+
path: string,
|
|
362
|
+
body: Record<string, unknown> | undefined,
|
|
363
|
+
signal: AbortSignal,
|
|
364
|
+
options?: { readonly auth?: boolean },
|
|
365
|
+
): Promise<Record<string, unknown>>;
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
/** Route key for bucket tracking: major parameters (channel id) stay, message ids collapse. */
|
|
369
|
+
function routeKey(method: string, path: string): string {
|
|
370
|
+
if (path.startsWith("/interactions/")) return `${method} /interactions`;
|
|
371
|
+
return `${method} ${path.replace(/\/messages\/\d+/, "/messages/:id")}`;
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
/**
|
|
375
|
+
* REST client that honors Discord's per-route buckets: an exhausted bucket (`X-RateLimit-Remaining: 0`)
|
|
376
|
+
* blocks its route until `X-RateLimit-Reset-After`, and a 429 blocks its route (or every route when
|
|
377
|
+
* `global`) for `retry_after` seconds before the caller retries.
|
|
378
|
+
*/
|
|
379
|
+
function discordApi(options: {
|
|
380
|
+
botToken: ChannelSecretSource;
|
|
381
|
+
apiOrigin?: string;
|
|
382
|
+
fetch?: typeof globalThis.fetch;
|
|
383
|
+
maxResponseBytes: number;
|
|
384
|
+
}): DiscordApi {
|
|
385
|
+
const origin = apiOrigin(options.apiOrigin);
|
|
386
|
+
const fetcher = options.fetch ?? globalThis.fetch;
|
|
387
|
+
const routes = new Map<string, string>();
|
|
388
|
+
const blockedUntil = new Map<string, number>();
|
|
389
|
+
let globalUntil = 0;
|
|
390
|
+
|
|
391
|
+
function block(key: string, until: number): void {
|
|
392
|
+
if (blockedUntil.size >= 1024 && !blockedUntil.has(key)) blockedUntil.clear();
|
|
393
|
+
blockedUntil.set(key, Math.max(until, blockedUntil.get(key) ?? 0));
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
return {
|
|
397
|
+
async call(method, path, body, signal, callOptions = {}) {
|
|
398
|
+
const route = routeKey(method, path);
|
|
399
|
+
const bucketOf = () => routes.get(route) ?? route;
|
|
400
|
+
await delay(Math.max(globalUntil, blockedUntil.get(bucketOf()) ?? 0) - Date.now(), signal);
|
|
401
|
+
const headers: Record<string, string> = {};
|
|
402
|
+
if (callOptions.auth !== false) {
|
|
403
|
+
let secret: string;
|
|
404
|
+
try {
|
|
405
|
+
secret = await options.botToken();
|
|
406
|
+
} catch {
|
|
407
|
+
throw new DiscordApiError({ kind: "credential" });
|
|
408
|
+
}
|
|
409
|
+
if (!secret || Buffer.byteLength(secret, "utf8") > 1024) throw new DiscordApiError({ kind: "credential" });
|
|
410
|
+
headers.authorization = `Bot ${secret}`;
|
|
411
|
+
}
|
|
412
|
+
if (body !== undefined) headers["content-type"] = "application/json";
|
|
413
|
+
let response: Response;
|
|
414
|
+
try {
|
|
415
|
+
response = await fetcher(`${origin}${API_PATH}${path}`, {
|
|
416
|
+
method,
|
|
417
|
+
headers,
|
|
418
|
+
...(body === undefined ? {} : { body: JSON.stringify(body) }),
|
|
419
|
+
redirect: "error",
|
|
420
|
+
signal,
|
|
421
|
+
});
|
|
422
|
+
} catch {
|
|
423
|
+
throw new DiscordApiError({ kind: "network" });
|
|
424
|
+
}
|
|
425
|
+
const bucket = response.headers.get("x-ratelimit-bucket");
|
|
426
|
+
if (bucket !== null && /^[A-Za-z0-9_-]{1,128}$/.test(bucket)) {
|
|
427
|
+
if (routes.size >= 1024 && !routes.has(route)) routes.clear();
|
|
428
|
+
routes.set(route, bucket);
|
|
429
|
+
}
|
|
430
|
+
const resetAfter = seconds(response.headers.get("x-ratelimit-reset-after"));
|
|
431
|
+
if (response.headers.get("x-ratelimit-remaining") === "0" && resetAfter !== undefined)
|
|
432
|
+
block(bucketOf(), Date.now() + resetAfter * 1000);
|
|
433
|
+
let payload: Record<string, unknown> | undefined;
|
|
434
|
+
let parsed = true;
|
|
435
|
+
try {
|
|
436
|
+
const raw = await readBody(response.body, options.maxResponseBytes);
|
|
437
|
+
payload = raw.length === 0 ? {} : asRecord(JSON.parse(raw.toString("utf8")));
|
|
438
|
+
} catch {
|
|
439
|
+
parsed = false;
|
|
440
|
+
}
|
|
441
|
+
if (response.status === 429) {
|
|
442
|
+
const retryAfter = seconds(payload?.retry_after) ?? seconds(response.headers.get("retry-after")) ?? 1;
|
|
443
|
+
if (payload?.global === true || response.headers.get("x-ratelimit-global") === "true") globalUntil = Date.now() + retryAfter * 1000;
|
|
444
|
+
else block(bucketOf(), Date.now() + retryAfter * 1000);
|
|
445
|
+
throw new DiscordApiError({ kind: "api", status: 429, retryAfter });
|
|
446
|
+
}
|
|
447
|
+
if (!parsed || payload === undefined) throw new DiscordApiError({ kind: "response", status: response.status });
|
|
448
|
+
if (!response.ok) throw new DiscordApiError({ kind: response.status >= 500 ? "response" : "api", status: response.status });
|
|
449
|
+
return payload;
|
|
450
|
+
},
|
|
451
|
+
};
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
interface Preview {
|
|
455
|
+
readonly channel: string;
|
|
456
|
+
messageId?: string;
|
|
457
|
+
text?: string;
|
|
458
|
+
lastAt: number;
|
|
459
|
+
timer?: ReturnType<typeof setTimeout>;
|
|
460
|
+
inFlight?: Promise<void>;
|
|
461
|
+
closed: boolean;
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
/**
|
|
465
|
+
* Creates the Discord adapter. `start` opens the Gateway (messages, and component interactions while no
|
|
466
|
+
* Interactions endpoint is configured); `handleRequest` is the optional Interactions endpoint. Neither
|
|
467
|
+
* holds a receiver lease: the runtime deduplicates by message and interaction id.
|
|
468
|
+
*/
|
|
469
|
+
export function createDiscordAdapter(options: DiscordAdapterOptions): DiscordAdapter {
|
|
470
|
+
if (
|
|
471
|
+
typeof options.connectionId !== "string" ||
|
|
472
|
+
options.connectionId.length === 0 ||
|
|
473
|
+
Buffer.byteLength(options.connectionId, "utf8") > 256
|
|
474
|
+
) {
|
|
475
|
+
throw new TypeError("Discord connectionId must be a bounded non-empty string");
|
|
476
|
+
}
|
|
477
|
+
if (typeof options.botToken !== "function") throw new TypeError("Discord botToken must be a secret source, not a literal");
|
|
478
|
+
const applicationId = asSnowflake(options.applicationId);
|
|
479
|
+
if (applicationId === undefined) throw new TypeError("Discord applicationId must be a snowflake");
|
|
480
|
+
const maxRequestBytes = boundedInteger(options.maxRequestBytes, DEFAULT_MAX_REQUEST_BYTES, 1024, "maxRequestBytes");
|
|
481
|
+
const maxFrameBytes = boundedInteger(options.maxFrameBytes, DEFAULT_MAX_FRAME_BYTES, 4096, "maxFrameBytes");
|
|
482
|
+
const draftIntervalMs = boundedInteger(options.draftIntervalMs, DEFAULT_DRAFT_INTERVAL_MS, 100, "draftIntervalMs");
|
|
483
|
+
const reconnectBaseMs = boundedInteger(options.reconnectBaseMs, 1_000, 1, "reconnectBaseMs");
|
|
484
|
+
const api = discordApi({
|
|
485
|
+
botToken: options.botToken,
|
|
486
|
+
apiOrigin: options.apiOrigin,
|
|
487
|
+
fetch: options.fetch,
|
|
488
|
+
maxResponseBytes: maxRequestBytes,
|
|
489
|
+
});
|
|
490
|
+
const openSocket = options.webSocket ?? ((url: string) => new WebSocket(url) as unknown as DiscordSocket);
|
|
491
|
+
const connectionId = options.connectionId;
|
|
492
|
+
const sendDrafts = options.sendDrafts === true;
|
|
493
|
+
const previews = new Map<string, Preview>();
|
|
494
|
+
let controller: AbortController | undefined;
|
|
495
|
+
let gateway: DiscordGateway | undefined;
|
|
496
|
+
let started = false;
|
|
497
|
+
let stopped = false;
|
|
498
|
+
|
|
499
|
+
function signal(): AbortSignal {
|
|
500
|
+
return controller?.signal ?? new AbortController().signal;
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
function botUserId(): string {
|
|
504
|
+
return gateway?.state().botUserId ?? (applicationId as string);
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
/** Waits out a 429's `retry_after` and retries a send Discord refused before accepting it. */
|
|
508
|
+
async function createMessage(channel: string, body: Record<string, unknown>, abort: AbortSignal): Promise<Record<string, unknown>> {
|
|
509
|
+
for (let attempt = 1; ; attempt += 1) {
|
|
510
|
+
try {
|
|
511
|
+
return await api.call("POST", `/channels/${channel}/messages`, body, abort);
|
|
512
|
+
} catch (error) {
|
|
513
|
+
if (!(error instanceof DiscordApiError) || error.status !== 429 || attempt >= MAX_SEND_ATTEMPTS || abort.aborted) throw error;
|
|
514
|
+
// The bucket now blocks this route for `retry_after`; the next call waits for it.
|
|
515
|
+
}
|
|
516
|
+
}
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
function schedulePreview(preview: Preview): void {
|
|
520
|
+
if (preview.timer !== undefined || preview.inFlight !== undefined || preview.closed || preview.text === undefined) return;
|
|
521
|
+
const wait = Math.max(0, preview.lastAt + draftIntervalMs - Date.now());
|
|
522
|
+
preview.timer = setTimeout(() => {
|
|
523
|
+
preview.timer = undefined;
|
|
524
|
+
flushPreview(preview);
|
|
525
|
+
}, wait);
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
function flushPreview(preview: Preview): void {
|
|
529
|
+
const text = preview.text;
|
|
530
|
+
if (preview.closed || stopped || text === undefined) return;
|
|
531
|
+
preview.text = undefined;
|
|
532
|
+
preview.lastAt = Date.now();
|
|
533
|
+
preview.inFlight = (async () => {
|
|
534
|
+
try {
|
|
535
|
+
if (preview.messageId === undefined) {
|
|
536
|
+
const result = await api.call(
|
|
537
|
+
"POST",
|
|
538
|
+
`/channels/${preview.channel}/messages`,
|
|
539
|
+
{ content: text, allowed_mentions: { parse: [] }, flags: SUPPRESS_EMBEDS },
|
|
540
|
+
signal(),
|
|
541
|
+
);
|
|
542
|
+
preview.messageId = asSnowflake(result.id);
|
|
543
|
+
} else {
|
|
544
|
+
await api.call(
|
|
545
|
+
"PATCH",
|
|
546
|
+
`/channels/${preview.channel}/messages/${preview.messageId}`,
|
|
547
|
+
{ content: text, allowed_mentions: { parse: [] } },
|
|
548
|
+
signal(),
|
|
549
|
+
);
|
|
550
|
+
}
|
|
551
|
+
} catch {
|
|
552
|
+
// A preview is best effort: a refused or rate-limited write is dropped, never retried.
|
|
553
|
+
}
|
|
554
|
+
})().finally(() => {
|
|
555
|
+
preview.inFlight = undefined;
|
|
556
|
+
schedulePreview(preview);
|
|
557
|
+
});
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
/** Stops one conversation's preview and deletes its message once the reply has landed. */
|
|
561
|
+
async function closePreview(key: string): Promise<void> {
|
|
562
|
+
const preview = previews.get(key);
|
|
563
|
+
if (preview === undefined) return;
|
|
564
|
+
previews.delete(key);
|
|
565
|
+
preview.closed = true;
|
|
566
|
+
if (preview.timer !== undefined) clearTimeout(preview.timer);
|
|
567
|
+
await preview.inFlight;
|
|
568
|
+
if (preview.messageId === undefined) return;
|
|
569
|
+
try {
|
|
570
|
+
await api.call("DELETE", `/channels/${preview.channel}/messages/${preview.messageId}`, undefined, signal());
|
|
571
|
+
} catch {
|
|
572
|
+
// Best effort: a preview that cannot be deleted stays as an earlier partial answer.
|
|
573
|
+
}
|
|
574
|
+
}
|
|
575
|
+
|
|
576
|
+
async function acknowledge(id: string, token: string): Promise<void> {
|
|
577
|
+
try {
|
|
578
|
+
await api.call(
|
|
579
|
+
"POST",
|
|
580
|
+
`/interactions/${id}/${token}/callback`,
|
|
581
|
+
{ type: CALLBACK_DEFERRED_UPDATE },
|
|
582
|
+
AbortSignal.any([signal(), AbortSignal.timeout(3_000)]),
|
|
583
|
+
{
|
|
584
|
+
auth: false,
|
|
585
|
+
},
|
|
586
|
+
);
|
|
587
|
+
} catch {
|
|
588
|
+
// A missed acknowledgement shows "interaction failed" to the user; the click itself was admitted.
|
|
589
|
+
}
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
async function handleDispatch(type: string, data: unknown, receive: ChannelReceive): Promise<unknown> {
|
|
593
|
+
if (type === "MESSAGE_CREATE") {
|
|
594
|
+
const event = parseDiscordMessage(connectionId, data, { botUserId: botUserId(), allowBots: options.allowBots });
|
|
595
|
+
return event === undefined ? undefined : await receive(event);
|
|
596
|
+
}
|
|
597
|
+
if (type === "INTERACTION_CREATE") {
|
|
598
|
+
const parsed = parseDiscordInteraction(connectionId, data);
|
|
599
|
+
if (parsed === undefined) return undefined;
|
|
600
|
+
// The 3-second deadline runs alongside admission, which settles before the run starts.
|
|
601
|
+
const [admission] = await Promise.all([
|
|
602
|
+
parsed.event === undefined ? undefined : receive(parsed.event),
|
|
603
|
+
acknowledge(parsed.id, parsed.token),
|
|
604
|
+
]);
|
|
605
|
+
return admission;
|
|
606
|
+
}
|
|
607
|
+
return undefined;
|
|
608
|
+
}
|
|
609
|
+
|
|
610
|
+
return {
|
|
611
|
+
connectionId,
|
|
612
|
+
capabilities: { acknowledgement: "deadline", controls: "callback", maxTextCodeUnits: DISCORD_TEXT_CODE_UNITS },
|
|
613
|
+
async start(receive) {
|
|
614
|
+
if (stopped) throw new Error("Discord adapter is stopped");
|
|
615
|
+
if (started) throw new Error("Discord adapter is already started");
|
|
616
|
+
started = true;
|
|
617
|
+
controller = new AbortController();
|
|
618
|
+
gateway = createDiscordGateway({
|
|
619
|
+
token: options.botToken,
|
|
620
|
+
intents: DISCORD_GATEWAY_INTENTS,
|
|
621
|
+
gatewayUrl: async () => {
|
|
622
|
+
const result = await api.call("GET", "/gateway/bot", undefined, signal());
|
|
623
|
+
if (typeof result.url !== "string") throw new Error("Discord Gateway URL missing");
|
|
624
|
+
return result.url;
|
|
625
|
+
},
|
|
626
|
+
webSocket: openSocket,
|
|
627
|
+
onDispatch: (type, data) => handleDispatch(type, data, receive),
|
|
628
|
+
maxFrameBytes,
|
|
629
|
+
reconnectBaseMs,
|
|
630
|
+
...(options.random === undefined ? {} : { random: options.random }),
|
|
631
|
+
});
|
|
632
|
+
try {
|
|
633
|
+
await gateway.start();
|
|
634
|
+
} catch (error) {
|
|
635
|
+
started = false;
|
|
636
|
+
gateway = undefined;
|
|
637
|
+
throw error;
|
|
638
|
+
}
|
|
639
|
+
},
|
|
640
|
+
async send(reply) {
|
|
641
|
+
const channel =
|
|
642
|
+
reply.connectionId === connectionId && reply.threadId === undefined ? destination(reply.externalConversationId) : undefined;
|
|
643
|
+
if (channel === undefined) return { delivered: false, reason: "invalid_destination" };
|
|
644
|
+
const components = actionRows(reply.controls);
|
|
645
|
+
if (components === null) return { delivered: false, reason: "invalid_controls" };
|
|
646
|
+
const chunks = chunkDiscordText(reply.text);
|
|
647
|
+
if (chunks.length === 0) return { delivered: false, reason: "empty_reply" };
|
|
648
|
+
const abort = signal();
|
|
649
|
+
let messageId: string | undefined;
|
|
650
|
+
let sent = false;
|
|
651
|
+
try {
|
|
652
|
+
for (const [index, content] of chunks.entries()) {
|
|
653
|
+
const last = index + 1 === chunks.length;
|
|
654
|
+
const result = await createMessage(
|
|
655
|
+
channel,
|
|
656
|
+
{
|
|
657
|
+
content,
|
|
658
|
+
allowed_mentions: { parse: [] },
|
|
659
|
+
flags: SUPPRESS_EMBEDS,
|
|
660
|
+
...(last && components !== undefined ? { components } : {}),
|
|
661
|
+
},
|
|
662
|
+
abort,
|
|
663
|
+
);
|
|
664
|
+
messageId = asSnowflake(result.id) ?? messageId;
|
|
665
|
+
sent = true;
|
|
666
|
+
}
|
|
667
|
+
} catch (error) {
|
|
668
|
+
// A network or server error, or any failure after a chunk landed, cannot prove non-delivery.
|
|
669
|
+
if (sent || !(error instanceof DiscordApiError) || error.kind === "network" || error.kind === "response")
|
|
670
|
+
throw new DiscordDeliveryUnknownError();
|
|
671
|
+
return { delivered: false, reason: knownSendFailure(error) };
|
|
672
|
+
}
|
|
673
|
+
await closePreview(reply.externalConversationId);
|
|
674
|
+
return { delivered: true, ...(messageId === undefined ? {} : { messageId }) };
|
|
675
|
+
},
|
|
676
|
+
async stop() {
|
|
677
|
+
stopped = true;
|
|
678
|
+
gateway?.stop();
|
|
679
|
+
for (const preview of previews.values()) {
|
|
680
|
+
preview.closed = true;
|
|
681
|
+
if (preview.timer !== undefined) clearTimeout(preview.timer);
|
|
682
|
+
}
|
|
683
|
+
previews.clear();
|
|
684
|
+
controller?.abort(new Error("Discord adapter stopped"));
|
|
685
|
+
},
|
|
686
|
+
sendDraft(delta) {
|
|
687
|
+
if (!sendDrafts || stopped || delta.connectionId !== connectionId || delta.threadId !== undefined) return;
|
|
688
|
+
const channel = destination(delta.externalConversationId);
|
|
689
|
+
if (channel === undefined) return;
|
|
690
|
+
const text = draftText(delta.text);
|
|
691
|
+
if (text.trim().length === 0) return;
|
|
692
|
+
let preview = previews.get(delta.externalConversationId);
|
|
693
|
+
if (preview === undefined) {
|
|
694
|
+
if (previews.size >= MAX_PREVIEWS) return;
|
|
695
|
+
preview = { channel, lastAt: 0, closed: false };
|
|
696
|
+
previews.set(delta.externalConversationId, preview);
|
|
697
|
+
}
|
|
698
|
+
preview.text = text;
|
|
699
|
+
schedulePreview(preview);
|
|
700
|
+
},
|
|
701
|
+
handleDispatch,
|
|
702
|
+
async handleRequest(request, receive, publicKey) {
|
|
703
|
+
if (request.method !== "POST") return new Response("Method not allowed", { status: 405 });
|
|
704
|
+
if (publicKey === undefined) return new Response("Unauthorized", { status: 401 });
|
|
705
|
+
let raw: Buffer;
|
|
706
|
+
try {
|
|
707
|
+
raw = await readBody(request.body, maxRequestBytes);
|
|
708
|
+
} catch (error) {
|
|
709
|
+
return new Response(error instanceof RangeError ? "Payload too large" : "Malformed request", {
|
|
710
|
+
status: error instanceof RangeError ? 413 : 400,
|
|
711
|
+
});
|
|
712
|
+
}
|
|
713
|
+
// Verify before parsing anything: the signature covers the timestamp and the raw body.
|
|
714
|
+
const timestamp = request.headers.get("x-signature-timestamp") ?? "";
|
|
715
|
+
const signatureHex = request.headers.get("x-signature-ed25519") ?? "";
|
|
716
|
+
if (
|
|
717
|
+
!/^\d{1,12}$/.test(timestamp) ||
|
|
718
|
+
Math.abs(Date.now() / 1000 - Number(timestamp)) > SIGNATURE_WINDOW_SECONDS ||
|
|
719
|
+
!/^[0-9a-f]{128}$/i.test(signatureHex)
|
|
720
|
+
) {
|
|
721
|
+
return new Response("Unauthorized", { status: 401 });
|
|
722
|
+
}
|
|
723
|
+
let valid = false;
|
|
724
|
+
try {
|
|
725
|
+
valid = verify(null, Buffer.concat([Buffer.from(timestamp, "utf8"), raw]), publicKey, Buffer.from(signatureHex, "hex"));
|
|
726
|
+
} catch {
|
|
727
|
+
valid = false;
|
|
728
|
+
}
|
|
729
|
+
if (!valid) return new Response("Unauthorized", { status: 401 });
|
|
730
|
+
let body: Record<string, unknown> | undefined;
|
|
731
|
+
try {
|
|
732
|
+
body = asRecord(JSON.parse(raw.toString("utf8")));
|
|
733
|
+
} catch {
|
|
734
|
+
return new Response("Malformed request", { status: 400 });
|
|
735
|
+
}
|
|
736
|
+
if (body?.type === INTERACTION_PING) return Response.json({ type: CALLBACK_PONG });
|
|
737
|
+
const parsed = parseDiscordInteraction(connectionId, body);
|
|
738
|
+
if (parsed === undefined) return new Response("Unsupported interaction", { status: 400 });
|
|
739
|
+
try {
|
|
740
|
+
if (parsed.event !== undefined && retryableAdmission(await receive(parsed.event)))
|
|
741
|
+
return new Response("Unavailable", { status: 503 });
|
|
742
|
+
} catch {
|
|
743
|
+
return new Response("Unavailable", { status: 503 });
|
|
744
|
+
}
|
|
745
|
+
// The HTTP response is the acknowledgement: no follow-up callback is sent.
|
|
746
|
+
return Response.json({ type: CALLBACK_DEFERRED_UPDATE });
|
|
747
|
+
},
|
|
748
|
+
gatewayState() {
|
|
749
|
+
const state = gateway?.state();
|
|
750
|
+
return {
|
|
751
|
+
botUserId: botUserId(),
|
|
752
|
+
...(state?.sessionId === undefined ? {} : { sessionId: state.sessionId }),
|
|
753
|
+
sequence: state?.sequence ?? null,
|
|
754
|
+
connected: state?.connected ?? false,
|
|
755
|
+
};
|
|
756
|
+
},
|
|
757
|
+
};
|
|
758
|
+
}
|
|
759
|
+
|
|
760
|
+
/** Parses a hex Ed25519 application public key (it is public, not a secret). */
|
|
761
|
+
function parsePublicKey(hex: string): KeyObject {
|
|
762
|
+
if (!/^[0-9a-f]{64}$/i.test(hex)) throw new TypeError("Discord publicKey must be the application's 64-character hex Ed25519 key");
|
|
763
|
+
return createPublicKey({ key: { kty: "OKP", crv: "Ed25519", x: Buffer.from(hex, "hex").toString("base64url") }, format: "jwk" });
|
|
764
|
+
}
|
|
765
|
+
|
|
766
|
+
export interface DiscordConnectOptions {
|
|
767
|
+
/** Bot token reference (`env:` or `keyring:`). A literal fails with `ChannelTokenLiteralError`. */
|
|
768
|
+
readonly token: string;
|
|
769
|
+
/** The application id (a snowflake); the bot user id until READY reports one. */
|
|
770
|
+
readonly applicationId: string;
|
|
771
|
+
/**
|
|
772
|
+
* Application public key (hex, or an `env:`/`keyring:` ref) for the Interactions endpoint. Needed only
|
|
773
|
+
* when the host sets an Interactions Endpoint URL and mounts `handle(request)`; otherwise component
|
|
774
|
+
* clicks arrive over the Gateway.
|
|
775
|
+
*/
|
|
776
|
+
readonly publicKey?: string;
|
|
777
|
+
/**
|
|
778
|
+
* Maps a sender (`externalActorId` = the Discord user id, `claims.guildId`) to a verified grant.
|
|
779
|
+
* Without it, every event is denied: Discord never falls back to the runtime's open default.
|
|
780
|
+
*/
|
|
781
|
+
readonly authorize: (
|
|
782
|
+
input: ChannelAuthorizeInput,
|
|
783
|
+
) => ChannelAuthorization | false | undefined | Promise<ChannelAuthorization | false | undefined>;
|
|
784
|
+
/** Admit messages from other bots and webhooks (default false). */
|
|
785
|
+
readonly allowBots?: boolean;
|
|
786
|
+
readonly connectionId?: string;
|
|
787
|
+
readonly checkpoints?: CheckpointStore;
|
|
788
|
+
readonly leases?: LeaseStore;
|
|
789
|
+
readonly limits?: ChannelLimits;
|
|
790
|
+
readonly sendDrafts?: boolean;
|
|
791
|
+
readonly draftIntervalMs?: number;
|
|
792
|
+
readonly maxRequestBytes?: number;
|
|
793
|
+
readonly maxFrameBytes?: number;
|
|
794
|
+
readonly apiOrigin?: string;
|
|
795
|
+
readonly fetch?: typeof globalThis.fetch;
|
|
796
|
+
readonly webSocket?: (url: string) => DiscordSocket;
|
|
797
|
+
readonly reconnectBaseMs?: number;
|
|
798
|
+
readonly random?: () => number;
|
|
799
|
+
}
|
|
800
|
+
|
|
801
|
+
/** Binds one agent to a Discord application over the Gateway, with an optional Interactions endpoint. */
|
|
802
|
+
export async function connectDiscord(agent: Agent, options: DiscordConnectOptions): Promise<ChannelConnectionHandle> {
|
|
803
|
+
const resolvedToken = await resolveChannelSecretRef(agent, options.token);
|
|
804
|
+
const publicKeyText =
|
|
805
|
+
options.publicKey === undefined
|
|
806
|
+
? undefined
|
|
807
|
+
: /^(env|keyring):/.test(options.publicKey)
|
|
808
|
+
? await resolveChannelSecretRef(agent, options.publicKey)
|
|
809
|
+
: options.publicKey;
|
|
810
|
+
const publicKey = publicKeyText === undefined ? undefined : parsePublicKey(publicKeyText);
|
|
811
|
+
const redactor = createChannelRedactor([resolvedToken], agent.config?.redactor);
|
|
812
|
+
const connectionId = options.connectionId ?? "discord-default";
|
|
813
|
+
const checkpoints = options.checkpoints ?? createMemoryCheckpointStore();
|
|
814
|
+
const leases = options.leases ?? createMemoryLeaseStore();
|
|
815
|
+
|
|
816
|
+
const adapter = createDiscordAdapter({
|
|
817
|
+
connectionId,
|
|
818
|
+
botToken: async () => resolvedToken,
|
|
819
|
+
applicationId: options.applicationId,
|
|
820
|
+
allowBots: options.allowBots,
|
|
821
|
+
sendDrafts: options.sendDrafts,
|
|
822
|
+
draftIntervalMs: options.draftIntervalMs,
|
|
823
|
+
maxRequestBytes: options.maxRequestBytes,
|
|
824
|
+
maxFrameBytes: options.maxFrameBytes,
|
|
825
|
+
apiOrigin: options.apiOrigin,
|
|
826
|
+
fetch: options.fetch,
|
|
827
|
+
webSocket: options.webSocket,
|
|
828
|
+
reconnectBaseMs: options.reconnectBaseMs,
|
|
829
|
+
random: options.random,
|
|
830
|
+
});
|
|
831
|
+
const authorize = typeof options.authorize === "function" ? options.authorize : () => false as const;
|
|
832
|
+
const runtime = createChannelRuntime(agent, {
|
|
833
|
+
deliver: (reply) => adapter.send(reply),
|
|
834
|
+
checkpoints,
|
|
835
|
+
leases,
|
|
836
|
+
redactor,
|
|
837
|
+
authorize,
|
|
838
|
+
limits: options.limits,
|
|
839
|
+
onAssistantDelta: options.sendDrafts ? (delta) => adapter.sendDraft(delta) : undefined,
|
|
840
|
+
});
|
|
841
|
+
const receive: ChannelReceive = (event) => runtime.admit(event);
|
|
842
|
+
|
|
843
|
+
const handle: ChannelConnectionHandle = {
|
|
844
|
+
async handle(update: unknown): Promise<unknown> {
|
|
845
|
+
if (update instanceof Request) return await adapter.handleRequest(update, receive, publicKey);
|
|
846
|
+
const record = asRecord(update);
|
|
847
|
+
if (record === undefined) return undefined;
|
|
848
|
+
if ("connectionId" in record && "externalActorId" in record && "eventId" in record)
|
|
849
|
+
return await runtime.admit(record as unknown as ChannelInboundEvent);
|
|
850
|
+
// A scripted Gateway dispatch: `{ t: "MESSAGE_CREATE" | "INTERACTION_CREATE", d }`.
|
|
851
|
+
return typeof record.t === "string" ? await adapter.handleDispatch(record.t, record.d, receive) : undefined;
|
|
852
|
+
},
|
|
853
|
+
async start() {
|
|
854
|
+
await adapter.start(receive);
|
|
855
|
+
},
|
|
856
|
+
async close() {
|
|
857
|
+
const stopping = runtime.stop();
|
|
858
|
+
try {
|
|
859
|
+
await adapter.stop();
|
|
860
|
+
} finally {
|
|
861
|
+
await stopping;
|
|
862
|
+
}
|
|
863
|
+
},
|
|
864
|
+
async stop() {
|
|
865
|
+
await handle.close();
|
|
866
|
+
},
|
|
867
|
+
async drain(opts) {
|
|
868
|
+
return await runtime.drain(opts);
|
|
869
|
+
},
|
|
870
|
+
};
|
|
871
|
+
bindChannelHostUi(handle, runtime, connectionId);
|
|
872
|
+
return handle;
|
|
873
|
+
}
|