@theokit/gateway-discord 0.3.0 → 0.5.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 CHANGED
@@ -1,5 +1,98 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.5.0
4
+
5
+ ### Minor Changes
6
+
7
+ - e5a2603: Group messages that do not mention the bot are no longer delivered by default on Discord, Matrix
8
+ and Teams; pass `requireMention: false` to keep the old behaviour.
9
+
10
+ Discord, Matrix and Teams gain a `requireMention` option that defaults to `true`. With it on, a
11
+ group or thread message reaches the handler only when it mentions the bot, and a DM always does.
12
+ Discord reads the bot's id in `mentions.users` (a direct mention or a reply that pings it; not
13
+ `@everyone`, `@here` or roles), and drops group messages with one stderr line until the client is
14
+ ready. Matrix reads `m.mentions.user_ids`, and falls back to the full user id in `body` or
15
+ `formatted_body` when a client sends no `m.mentions`. Teams reads `mention` entities against the
16
+ activity's `recipient.id`, and drops a group activity that names no recipient with one stderr line.
17
+
18
+ LINE's `deliver()` now applies the mention guard its webhook route already applied.
19
+
20
+ On all four adapters `deliver()` and the adapter's own inbound path use one rule, and `deliver()`
21
+ answers `"ok"` for an event the rule drops, with or without a handler subscribed.
22
+
23
+ ### Patch Changes
24
+
25
+ - 3f1788d: Send an image from a gateway handler, and refuse it wherever a platform cannot show one.
26
+
27
+ `@theokit/gateway` exports `OutboundAttachment` (`kind: "image"`, `mediaType`, `data`, optional
28
+ `filename`). `OutboundMessage` gains an optional `attachments` list, `ctx.reply(text, { attachments })`
29
+ carries it to the adapter (an empty list is left out), and `BasePlatformAdapter` declares
30
+ `supportsAttachments`, `false` by default. `DeliveryRouter.send` takes the same `attachments`
31
+ field. The runner and the router refuse an outbound carrying attachments as
32
+ `attachments_unsupported`, with no `sendMessage` call, when the adapter does not declare
33
+ `supportsAttachments`.
34
+
35
+ `@theokit/gateway-telegram` reports `supportsAttachments: true` and sends each image through
36
+ `sendPhoto`, the text as the first photo's caption up to 1024 UTF-16 units and after the photos
37
+ when longer. A non-image kind is refused as `attachments_unsupported`; a missing image, more
38
+ than 10 images or an image over 10 MiB as `invalid_attachment`; all with no request.
39
+
40
+ Every other adapter, and every adapter's `editMessage`, refuses an outbound carrying attachments
41
+ with `attachments_unsupported` and makes no platform call, instead of sending the text and
42
+ dropping the image.
43
+
44
+ The runner's auto-reply to a blocking `pre_inbound` hook no longer discards a `sendMessage` that
45
+ throws: the error reaches the `on_error` hooks with the event and is written to stderr, redacted,
46
+ as a handler error is. Dispatch still does not throw.
47
+
48
+ - 17c0713: Keep Markdown table rows whole when Discord, Slack, Teams, Telegram, WhatsApp and Mattermost split a long reply. A cut that fell inside a table row now moves back to the start of that row when the row fits in a part, so each row reaches the platform byte-identical. `chunkText` gains the opt-in `keepTableRows` option; text with no table row splits into the same chunks as before.
49
+
50
+ ## 0.4.0
51
+
52
+ ### Minor Changes
53
+
54
+ - 05e7fdd: Edit a message an adapter sent, so a reply can stream as a preview that the final text replaces.
55
+
56
+ `BasePlatformAdapter` gains `supportsEdit` (`false` by default) and
57
+ `editMessage(messageId, out)`, whose default refuses with `edit_unsupported`, makes no platform
58
+ call and never throws. A third-party subclass that already declares a member with either name and
59
+ a different type no longer compiles against this release, and under `noImplicitOverride` one
60
+ that declares it without `override` does not either.
61
+
62
+ Telegram (`editMessageText`), Discord (one REST `PATCH` of the message, without fetching the
63
+ channel), Slack (`chat.update`), Mattermost (`patchPost`), Matrix (an `m.replace` event) and Teams
64
+ (`updateActivity`, or `activities(conversationId).update` on `@microsoft/teams.api` below 2.0.14)
65
+ set `supportsEdit` to `true` and replace the text of a message they sent, honouring `format` as
66
+ `sendMessage` does (Slack's `chat.update` takes no `mrkdwn` argument, so its edit sends the text
67
+ as it is for every format), and return `{ ok: true, messageId }` with the same id. E-mail, SMS, LINE and
68
+ WhatsApp keep the default.
69
+
70
+ An edit is refused with no request as `edit_too_long` when the text would need more than one
71
+ platform message (Matrix has no length check), as `invalid_message_id` for an empty id (and on
72
+ Telegram one that is not a safe positive integer), and as `empty_text` and `not_connected` where
73
+ `sendMessage` answers those. Telegram answers its "message is not modified" refusal as a success.
74
+ On Discord an unknown channel is answered by the platform, as `discord_10003`. On Matrix a
75
+ `#alias` the adapter never resolved costs one lookup before the edit. Teams and Matrix do not
76
+ retry a refused markup as plain text on an edit, as they do on a send.
77
+
78
+ The six adapters keep `>=0.9.0` as their peer range on `@theokit/gateway` in this release. At run
79
+ time they work against any core in that range, since no adapter calls the base `editMessage`. Their
80
+ sources declare both members with `override`, so building them against a core older than this one
81
+ reports TS4113. The floor rises to this core in the next release, once it is on npm
82
+ (`docs/adr/0008-edit-capable-adapters-raise-their-core-floor-after-the-core-ships.md`). A
83
+ consumer's own typecheck reads the published declarations, which carry no `override`, and passes
84
+ on an older core.
85
+
86
+ ### Patch Changes
87
+
88
+ - 13117af: A `plain` text full of markup characters no longer goes out as a message longer than the
89
+ platform allows. The text was split on its own length and escaped afterwards, and escaping can
90
+ double a part, so 995 copies of `*a` went to Discord as one 2985-character message and came back
91
+ `discord_50035`, and 8000 copies went to Mattermost as one 24000-character post and came back
92
+ `invalid_request`. A part whose escaped body passes the cap is now split again at half the cap.
93
+ `editMessage` sends the same parts, so on both platforms an edit is refused as `edit_too_long`
94
+ for exactly the texts a send delivers as more than one message.
95
+
3
96
  ## 0.3.0
4
97
 
5
98
  ### Minor Changes
package/README.md CHANGED
@@ -38,6 +38,20 @@ const runner = new GatewayRunner({
38
38
  await runner.start();
39
39
  ```
40
40
 
41
+ ## Group messages and mentions
42
+
43
+ `requireMention` decides which guild and thread messages reach your handler. It defaults to
44
+ `true`: a message there is delivered only when it mentions the bot, meaning the bot's user id is
45
+ in the message's `mentions.users`. A direct `<@id>` counts, and so does a reply that pings the
46
+ bot. `@everyone`, `@here` and role mentions do not. A DM is always delivered.
47
+
48
+ Until the client is ready the bot's user id is unknown, so group messages are dropped and one
49
+ stderr line says why. `deliver()` and the socket path apply the same rule, and `deliver()` answers
50
+ `"ok"` for a message it drops.
51
+
52
+ **Upgrading:** before this option the adapter delivered every group message. Pass
53
+ `requireMention: false` to keep that behaviour.
54
+
41
55
  ## Limitations (v0.1)
42
56
 
43
57
  - **Text-trigger commands only.** Proper Discord slash commands (registered via Application Commands API) are out of scope — use `event.text.startsWith("!cmd")` for now.
package/dist/index.cjs CHANGED
@@ -4,15 +4,35 @@ var gateway = require('@theokit/gateway');
4
4
  var discord_js = require('discord.js');
5
5
 
6
6
  // src/adapter.ts
7
+
8
+ // src/refuse-attachments.ts
9
+ function refuseAttachments(out) {
10
+ if (out.attachments == null || out.attachments.length === 0) return void 0;
11
+ return {
12
+ ok: false,
13
+ error: { code: "attachments_unsupported", message: "discord adapter cannot send attachments" }
14
+ };
15
+ }
7
16
  var DISCORD_MAX_MESSAGE = 2e3;
8
17
  var SAFE_DISCORD_CHUNK = 1900;
18
+ var BOUNDARIES = {
19
+ boundaries: ["\n\n", "\n"],
20
+ lastResort: "window",
21
+ stripLeading: /^\n+/,
22
+ keepTableRows: true
23
+ };
9
24
  function splitForDiscord(text) {
10
25
  return gateway.chunkText(text, {
11
26
  limit: DISCORD_MAX_MESSAGE,
12
27
  safeLimit: SAFE_DISCORD_CHUNK,
13
- boundaries: ["\n\n", "\n"],
14
- lastResort: "window",
15
- stripLeading: /^\n+/
28
+ ...BOUNDARIES
29
+ });
30
+ }
31
+ function splitForEscapedDiscord(text) {
32
+ return gateway.chunkText(text, {
33
+ limit: DISCORD_MAX_MESSAGE / 2,
34
+ safeLimit: SAFE_DISCORD_CHUNK / 2,
35
+ ...BOUNDARIES
16
36
  });
17
37
  }
18
38
 
@@ -30,9 +50,12 @@ var DiscordAdapter = class extends gateway.BasePlatformAdapter {
30
50
  token;
31
51
  handler;
32
52
  connected = false;
53
+ requireMention;
54
+ warnedMissingBotId = false;
33
55
  constructor(opts) {
34
56
  super();
35
57
  this.token = opts.token;
58
+ this.requireMention = opts.requireMention ?? true;
36
59
  const intents = opts.intents ?? DEFAULT_DISCORD_INTENTS;
37
60
  if (intents.length === 0) {
38
61
  process.stderr.write(
@@ -82,6 +105,9 @@ var DiscordAdapter = class extends gateway.BasePlatformAdapter {
82
105
  return this.client;
83
106
  }
84
107
  async sendMessage(out) {
108
+ return refuseAttachments(out) ?? this.sendText(out);
109
+ }
110
+ async sendText(out) {
85
111
  if (out.text.length === 0) {
86
112
  return { ok: false, error: { code: "empty_text", message: "text is empty" } };
87
113
  }
@@ -104,7 +130,7 @@ var DiscordAdapter = class extends gateway.BasePlatformAdapter {
104
130
  }
105
131
  };
106
132
  }
107
- const chunks = splitForDiscord(out.text).map((chunk) => bodyFor(out.format, chunk));
133
+ const chunks = renderMessages(out);
108
134
  let lastId;
109
135
  for (const chunk of chunks) {
110
136
  try {
@@ -119,6 +145,39 @@ var DiscordAdapter = class extends gateway.BasePlatformAdapter {
119
145
  }
120
146
  return { ok: true, ...lastId !== void 0 ? { messageId: lastId } : {} };
121
147
  }
148
+ /** Discord edits a sent message's text with one REST call. */
149
+ supportsEdit = true;
150
+ /**
151
+ * Replace the text of a message this bot sent, with one `PATCH /channels/{id}/messages/{id}`.
152
+ *
153
+ * That PATCH is the request `channel.messages.edit` makes. It is sent through `client.rest`
154
+ * without fetching the channel first, so a success is one request whatever the channel cache
155
+ * holds; an unknown channel is answered by Discord itself (`discord_10003`). The text is split
156
+ * and escaped by the same `renderMessages` that `sendMessage` uses, and a text a send would
157
+ * deliver as more than one message is refused as `edit_too_long` with no request.
158
+ */
159
+ async editMessage(messageId, out) {
160
+ return refuseAttachments(out) ?? this.editText(messageId, out);
161
+ }
162
+ async editText(messageId, out) {
163
+ if (out.text.length === 0) {
164
+ return { ok: false, error: { code: "empty_text", message: "text is empty" } };
165
+ }
166
+ if (messageId.length === 0) {
167
+ return { ok: false, error: { code: "invalid_message_id", message: "message id is empty" } };
168
+ }
169
+ const messages = renderMessages(out);
170
+ if (messages.length !== 1) return editPartsRefusal(messages.length);
171
+ const content = messages[0];
172
+ try {
173
+ await this.client.rest.patch(discord_js.Routes.channelMessage(out.channel.id, messageId), {
174
+ body: { content }
175
+ });
176
+ } catch (err) {
177
+ return mapSendError(err);
178
+ }
179
+ return { ok: true, messageId };
180
+ }
122
181
  onInbound(handler) {
123
182
  this.handler = handler;
124
183
  return () => {
@@ -128,7 +187,33 @@ var DiscordAdapter = class extends gateway.BasePlatformAdapter {
128
187
  async handleInbound(msg) {
129
188
  if (this.handler === void 0) return;
130
189
  if (msg.author.bot) return;
131
- await this.dispatchEvent(normalizeEvent(msg));
190
+ const event = normalizeEvent(msg);
191
+ if (!this.passesMentionGate(event)) return;
192
+ await this.dispatchEvent(event);
193
+ }
194
+ /**
195
+ * Whether an event may reach the handler: always for a DM or with `requireMention` off,
196
+ * otherwise only when the message mentions the bot. Both `deliver()` and the socket path call
197
+ * it, so the two entries cannot disagree.
198
+ */
199
+ passesMentionGate(event) {
200
+ if (event.channel.type === "dm" || !this.requireMention) return true;
201
+ const botId = this.client.user?.id;
202
+ if (botId === void 0) {
203
+ this.warnMissingBotIdOnce();
204
+ return false;
205
+ }
206
+ const raw = event.platform === "discord" ? event.discord.raw : void 0;
207
+ const mentionedUsers = raw?.mentions?.users;
208
+ if (typeof mentionedUsers?.has === "function") return mentionedUsers.has(botId) === true;
209
+ return event.text.includes(`<@${botId}>`) || event.text.includes(`<@!${botId}>`);
210
+ }
211
+ warnMissingBotIdOnce() {
212
+ if (this.warnedMissingBotId) return;
213
+ this.warnedMissingBotId = true;
214
+ process.stderr.write(
215
+ "[discord] dropping every group message: requireMention is on and the bot user id is not known until the client is ready\n"
216
+ );
132
217
  }
133
218
  /**
134
219
  * Dispatch a pre-built event to the current handler, honouring EC-H replace
@@ -159,10 +244,12 @@ var DiscordAdapter = class extends gateway.BasePlatformAdapter {
159
244
  /**
160
245
  * Deliver an event that arrived out of band — the ingest `onInbound` had no counterpart for (#83).
161
246
  *
162
- * One line over `runHandler`, which owns the containment: a handler is user code, its throw is
163
- * named as the handler's failure rather than the platform's, and delivery continues.
247
+ * The mention gate runs first, as on the socket path: an event it drops answers `"ok"`, with or
248
+ * without a handler subscribed. `runHandler` owns the containment: a handler is user code, its
249
+ * throw is named as the handler's failure rather than the platform's, and delivery continues.
164
250
  */
165
251
  async deliver(event) {
252
+ if (!this.passesMentionGate(event)) return "ok";
166
253
  return this.runHandler(this.handler, event);
167
254
  }
168
255
  };
@@ -200,6 +287,18 @@ function normalizeEvent(msg) {
200
287
  }
201
288
  };
202
289
  }
290
+ function editPartsRefusal(partCount) {
291
+ if (partCount > 1) {
292
+ return {
293
+ ok: false,
294
+ error: {
295
+ code: "edit_too_long",
296
+ message: `text needs ${partCount} Discord messages; an edit replaces one`
297
+ }
298
+ };
299
+ }
300
+ return { ok: false, error: { code: "empty_text", message: "text reduced to zero parts" } };
301
+ }
203
302
  function mapSendError(err) {
204
303
  if (err instanceof discord_js.DiscordAPIError) {
205
304
  const codeStr = String(err.code);
@@ -216,6 +315,13 @@ function mapSendError(err) {
216
315
  }
217
316
  return { ok: false, error: { code: "unknown", message: err.message } };
218
317
  }
318
+ function renderMessages(out) {
319
+ return splitForDiscord(out.text).flatMap((part) => {
320
+ const body = bodyFor(out.format, part);
321
+ if (body.length <= DISCORD_MAX_MESSAGE) return [body];
322
+ return splitForEscapedDiscord(part).map((half) => bodyFor(out.format, half));
323
+ });
324
+ }
219
325
  function bodyFor(format, text) {
220
326
  return format === "plain" ? escapeMarkdown(text) : text;
221
327
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/split.ts","../src/adapter.ts"],"names":["chunkText","GatewayIntentBits","BasePlatformAdapter","Client","Events","DiscordAPIError"],"mappings":";;;;;;AAeA,IAAM,mBAAA,GAAsB,GAAA;AAC5B,IAAM,kBAAA,GAAqB,IAAA;AAEpB,SAAS,gBAAgB,IAAA,EAAwB;AACtD,EAAA,OAAOA,kBAAU,IAAA,EAAM;AAAA,IACrB,KAAA,EAAO,mBAAA;AAAA,IACP,SAAA,EAAW,kBAAA;AAAA,IACX,UAAA,EAAY,CAAC,MAAA,EAAQ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aA,SAAS,eAAe,IAAA,EAAsB;AAM5C,EAAA,OAAO,IAAA,CAAK,OAAA,CAAQ,aAAA,EAAe,MAAM,CAAA;AAC3C","file":"index.cjs","sourcesContent":["/**\n * Discord's 2000-char per-message hard limit. Split agent responses on safe\n * boundaries before sending (T6.1).\n *\n * Thin wrapper over core `chunkText` (roadmap M1). Telegram family (minus\n * markdown balancing): 2000 hard cap, 1900 soft window, `\\n\\n` → `\\n` → window\n * boundary preference, newline-only leading strip, no surrogate guard. Output\n * is byte-identical to the previous implementation (pinned by\n * `tests/split.test.ts`).\n *\n * @internal\n */\n\nimport { chunkText } from \"@theokit/gateway\";\n\nconst DISCORD_MAX_MESSAGE = 2000;\nconst SAFE_DISCORD_CHUNK = 1900;\n\nexport function splitForDiscord(text: string): string[] {\n return chunkText(text, {\n limit: DISCORD_MAX_MESSAGE,\n safeLimit: SAFE_DISCORD_CHUNK,\n boundaries: [\"\\n\\n\", \"\\n\"],\n lastResort: \"window\",\n stripLeading: /^\\n+/,\n });\n}\n","/**\n * `DiscordAdapter` — wraps discord.js in the `@theokit/gateway`\n * `BasePlatformAdapter` contract (T6.1, ADRs D171, D179).\n *\n * - `connect()` calls `client.login(token)` and awaits the `ready` event.\n * - WebSocket Gateway only (D179) — no webhook variant in v0.1.\n * - Default intents include `MessageContent` (EC-C silent-failure guard).\n * - Bot-to-bot messages ignored at adapter level (`msg.author.bot`).\n * - 2000-char message split (Discord's hard limit).\n *\n * @public\n */\n\nimport type { DiscordMessageEvent, MessageEvent as GatewayMessageEvent } from \"@theokit/gateway\";\nimport { BasePlatformAdapter, type OutboundMessage, type SendResult } from \"@theokit/gateway\";\nimport { Client, DiscordAPIError, Events, GatewayIntentBits, type Message } from \"discord.js\";\n\nimport { splitForDiscord } from \"./split.js\";\n\nexport interface DiscordAdapterOptions {\n /**\n * The Discord bot token.\n *\n * @platform-term Discord calls this a **bot token** and `discord.js` names the field `token`, so\n * the name here is theirs.\n * @issued-at The Discord Developer Portal, under the application's Bot tab.\n */\n readonly token: string;\n /**\n * Default: [Guilds, GuildMessages, MessageContent, DirectMessages,\n * DirectMessageReactions]. Without MessageContent the bot receives\n * empty `msg.content` (EC-C silent failure).\n */\n readonly intents?: GatewayIntentBits[];\n}\n\nexport const DEFAULT_DISCORD_INTENTS: ReadonlyArray<GatewayIntentBits> = [\n GatewayIntentBits.Guilds,\n GatewayIntentBits.GuildMessages,\n GatewayIntentBits.MessageContent,\n GatewayIntentBits.DirectMessages,\n GatewayIntentBits.DirectMessageReactions,\n];\n\n/**\n * Discord gateway adapter — holds a websocket the bot opens, so inbound needs no public URL.\n *\n * Reading message CONTENT requires the privileged `MessageContent` intent, which must be enabled in\n * the Discord developer portal as well as requested here; without it every `event.text` arrives\n * empty and nothing in the API says why. `DEFAULT_DISCORD_INTENTS` requests it.\n */\nexport class DiscordAdapter extends BasePlatformAdapter {\n readonly platform = \"discord\" as const;\n private readonly client: Client;\n private readonly token: string;\n private handler?: (event: GatewayMessageEvent) => Promise<void>;\n private connected = false;\n\n constructor(opts: DiscordAdapterOptions) {\n super();\n this.token = opts.token;\n const intents = (opts.intents ?? DEFAULT_DISCORD_INTENTS) as GatewayIntentBits[];\n if (intents.length === 0) {\n process.stderr.write(\n \"[discord] WARN — intents:[] passed; bot will not receive message content. Pass at least [Guilds, GuildMessages, MessageContent] (EC-C).\\n\",\n );\n }\n this.client = new Client({ intents });\n this.client.on(Events.MessageCreate, async (msg) => this.handleInbound(msg));\n this.client.on(Events.Error, (err) => {\n process.stderr.write(`[discord] client error: ${err.message}\\n`);\n });\n }\n\n override async connect(): Promise<boolean> {\n if (this.connected) return true;\n try {\n await new Promise<void>((resolve, reject) => {\n this.client.once(Events.ClientReady, () => resolve());\n this.client.login(this.token).catch(reject);\n });\n this.connected = true;\n return true;\n } catch (err) {\n process.stderr.write(`[discord] connect failed: ${(err as Error).message}\\n`);\n return false;\n }\n }\n\n override async disconnect(): Promise<void> {\n if (!this.connected) return;\n this.connected = false;\n try {\n await this.client.destroy();\n } catch {\n /* ignore */\n }\n }\n\n /**\n * Expose the underlying discord.js `Client` so consumers can register\n * platform-specific events that don't fit the portable contract —\n * `interactionCreate` (slash commands via Application Commands),\n * `error` event boundary, presence updates, etc. Register BEFORE\n * calling `runner.start()`.\n *\n * @public\n */\n getBot(): Client {\n return this.client;\n }\n\n override async sendMessage(out: OutboundMessage): Promise<SendResult> {\n if (out.text.length === 0) {\n return { ok: false, error: { code: \"empty_text\", message: \"text is empty\" } };\n }\n let channel: unknown;\n try {\n channel = await this.client.channels.fetch(out.channel.id);\n } catch (err) {\n return {\n ok: false,\n error: { code: \"channel_fetch_failed\", message: (err as Error).message },\n };\n }\n const sendable = channel as {\n send?: (input: { content: string; reply?: unknown }) => Promise<Message>;\n };\n if (sendable === null || typeof sendable.send !== \"function\") {\n return {\n ok: false,\n error: {\n code: \"channel_not_sendable\",\n message: `channel \"${out.channel.id}\" not text-based or missing`,\n },\n };\n }\n // Split FIRST, escape each chunk. The other order lets `splitForDiscord`'s hard window cut\n // land between a backslash and the character it guards: message 1 ends in a stray backslash\n // the user never typed, and message 2 opens with a bare `*` that Discord parses as markup.\n // Demonstrated in review against the real splitter.\n const chunks = splitForDiscord(out.text).map((chunk) => bodyFor(out.format, chunk));\n let lastId: string | undefined;\n for (const chunk of chunks) {\n try {\n const msg = await sendable.send({\n content: chunk,\n ...(out.replyTo !== undefined ? { reply: { messageReference: out.replyTo } } : {}),\n });\n lastId = msg.id;\n } catch (err) {\n return mapSendError(err);\n }\n }\n return { ok: true, ...(lastId !== undefined ? { messageId: lastId } : {}) };\n }\n\n override onInbound(handler: (event: GatewayMessageEvent) => Promise<void>): () => void {\n // EC-H: replace previous handler.\n this.handler = handler;\n return () => {\n if (this.handler === handler) this.handler = undefined;\n };\n }\n\n private async handleInbound(msg: Message): Promise<void> {\n if (this.handler === undefined) return;\n if (msg.author.bot) return;\n await this.dispatchEvent(normalizeEvent(msg));\n }\n\n /**\n * Dispatch a pre-built event to the current handler, honouring EC-H replace\n * semantics.\n *\n * Mirrors the seam `gateway-sms` already exposes. It exists because the EC-H\n * contract had no honest test without it: a real `discord.js` Message cannot\n * be synthesized, `handler` is private, and the test that claimed to cover\n * replacement asserted two counters were 0 — true whether onInbound replaces,\n * stacks, or discards. If it had regressed to `handlers.push(handler)`, the\n * agent would have replied twice to every message, double-billing tokens,\n * with the suite green.\n *\n * @internal\n */\n async dispatchEvent(event: GatewayMessageEvent): Promise<\"ok\" | \"no_handler\" | \"handler_threw\"> {\n if (this.handler === undefined) return \"no_handler\";\n try {\n await this.handler(event);\n } catch (err) {\n // Left uncaught, the rejection escaped into the platform's own error channel and was reported\n // as a client error — so a bug in the consumer's handler read as a fault in the platform\n // library, sending whoever debugged it to the wrong repository (#41). A handler is user code:\n // its failure is named as such, and delivery continues.\n const m = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[discord] handler threw: ${m}\\n`);\n return \"handler_threw\";\n }\n return \"ok\";\n }\n\n /**\n * Deliver an event that arrived out of band — the ingest `onInbound` had no counterpart for (#83).\n *\n * One line over `runHandler`, which owns the containment: a handler is user code, its throw is\n * named as the handler's failure rather than the platform's, and delivery continues.\n */\n override async deliver(\n event: GatewayMessageEvent,\n ): Promise<\"ok\" | \"no_handler\" | \"handler_threw\"> {\n return this.runHandler(this.handler, event);\n }\n}\n\nfunction normalizeEvent(msg: Message): DiscordMessageEvent {\n let channelType: \"dm\" | \"group\" | \"thread\";\n if (msg.guildId === null) {\n channelType = \"dm\";\n } else if (msg.channel.isThread()) {\n channelType = \"thread\";\n } else {\n channelType = \"group\";\n }\n\n const displayName = msg.author.globalName !== null ? msg.author.globalName : msg.author.username;\n\n return {\n id: `dc-${msg.channelId}-${msg.id}`,\n platform: \"discord\",\n sender: {\n id: msg.author.id,\n username: msg.author.username,\n displayName,\n },\n channel: {\n id: msg.channelId,\n type: channelType,\n ...(msg.channel.isThread() ? { topicId: msg.channel.id } : {}),\n },\n text: msg.content,\n receivedAt: msg.createdTimestamp,\n ...(msg.reference?.messageId !== undefined ? { replyTo: msg.reference.messageId } : {}),\n discord: {\n guildId: msg.guildId,\n channelId: msg.channelId,\n messageId: msg.id,\n raw: msg,\n },\n };\n}\n\nfunction mapSendError(err: unknown): SendResult {\n if (err instanceof DiscordAPIError) {\n const codeStr = String(err.code);\n if (codeStr === \"50007\") {\n return { ok: false, error: { code: \"dm_blocked\", message: err.message } };\n }\n if (codeStr === \"50001\" || codeStr === \"50013\") {\n return { ok: false, error: { code: \"no_permission\", message: err.message } };\n }\n if (err.status === 429) {\n return { ok: false, error: { code: \"rate_limited\", message: err.message } };\n }\n return { ok: false, error: { code: `discord_${codeStr}`, message: err.message } };\n }\n return { ok: false, error: { code: \"unknown\", message: (err as Error).message } };\n}\n\n/**\n * The text to send, with the caller's declared format applied.\n *\n * Discord parses markdown natively, so `markdown` needs no flag. `plain` is the caller stating\n * the text is NOT markup, and sending it raw would parse it anyway — a user's literal\n * `*asterisks*` arriving as italic.\n */\nfunction bodyFor(format: OutboundMessage[\"format\"], text: string): string {\n return format === \"plain\" ? escapeMarkdown(text) : text;\n}\n\n/**\n * Escape the characters this platform would otherwise parse as markup.\n *\n * Called only when the caller declared `format: \"plain\"` — an explicit statement that the text\n * is NOT markup. Without it, a user's literal `*asterisks*` render as italic on a platform that\n * parses markdown natively, which is the caller's intent being silently inverted.\n *\n * Deliberately narrow: the four characters that open an inline span. A full markdown escaper\n * would also touch `#`, `>` and `-` at line starts, which are far more common in ordinary prose\n * and whose escaping is more visible than the problem it solves.\n */\nfunction escapeMarkdown(text: string): string {\n // The backslash comes FIRST, and that ordering is the whole correctness of this function.\n // Without it a backslash already in the caller's text is left bare: `a\\*b` escapes to `a\\\\*b`,\n // the renderer consumes `\\\\` as one literal backslash, and the `*` it was guarding is left\n // naked — so text sent explicitly as `plain` arrives italicised, the exact inversion this\n // function exists to prevent. Caught in review.\n return text.replace(/([\\\\*_`~])/g, \"\\\\$1\");\n}\n"]}
1
+ {"version":3,"sources":["../src/refuse-attachments.ts","../src/split.ts","../src/adapter.ts"],"names":["chunkText","GatewayIntentBits","BasePlatformAdapter","Client","Events","Routes","DiscordAPIError"],"mappings":";;;;;;;;AAmBO,SAAS,kBAAkB,GAAA,EAA8C;AAC9E,EAAA,IAAI,IAAI,WAAA,IAAe,IAAA,IAAQ,IAAI,WAAA,CAAY,MAAA,KAAW,GAAG,OAAO,MAAA;AACpE,EAAA,OAAO;AAAA,IACL,EAAA,EAAI,KAAA;AAAA,IACJ,KAAA,EAAO,EAAE,IAAA,EAAM,yBAAA,EAA2B,SAAS,yCAAA;AAA0C,GAC/F;AACF;ACVO,IAAM,mBAAA,GAAsB,GAAA;AACnC,IAAM,kBAAA,GAAqB,IAAA;AAC3B,IAAM,UAAA,GAAa;AAAA,EACjB,UAAA,EAAY,CAAC,MAAA,EAAQ,IAAI,CAAA;AAAA,EACzB,UAAA,EAAY,QAAA;AAAA,EACZ,YAAA,EAAc,MAAA;AAAA,EACd,aAAA,EAAe;AACjB,CAAA;AAaO,SAAS,gBAAgB,IAAA,EAAwB;AACtD,EAAA,OAAOA,kBAAU,IAAA,EAAM;AAAA,IACrB,KAAA,EAAO,mBAAA;AAAA,IACP,SAAA,EAAW,kBAAA;AAAA,IACX,GAAG;AAAA,GACJ,CAAA;AACH;AASO,SAAS,uBAAuB,IAAA,EAAwB;AAC7D,EAAA,OAAOA,kBAAU,IAAA,EAAM;AAAA,IACrB,OAAO,mBAAA,GAAsB,CAAA;AAAA,IAC7B,WAAW,kBAAA,GAAqB,CAAA;AAAA,IAChC,GAAG;AAAA,GACJ,CAAA;AACH;;;ACDO,IAAM,uBAAA,GAA4D;AAAA,EACvEC,4BAAA,CAAkB,MAAA;AAAA,EAClBA,4BAAA,CAAkB,aAAA;AAAA,EAClBA,4BAAA,CAAkB,cAAA;AAAA,EAClBA,4BAAA,CAAkB,cAAA;AAAA,EAClBA,4BAAA,CAAkB;AACpB,CAAA;AASO,IAAM,cAAA,GAAN,cAA6BC,2BAAA,CAAoB;AAAA,EAC7C,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AAgB,GAAA,CAAI,IAAI,CAAA,CAAE,OAAA,CAAQ,CAAC,IAAA,KAAS;AACjD,IAAA,MAAM,IAAA,GAAO,OAAA,CAAQ,GAAA,CAAI,MAAA,EAAQ,IAAI,CAAA;AACrC,IAAA,IAAI,IAAA,CAAK,MAAA,IAAU,mBAAA,EAAqB,OAAO,CAAC,IAAI,CAAA;AACpD,IAAA,OAAO,sBAAA,CAAuB,IAAI,CAAA,CAAE,GAAA,CAAI,CAAC,SAAS,OAAA,CAAQ,GAAA,CAAI,MAAA,EAAQ,IAAI,CAAC,CAAA;AAAA,EAC7E,CAAC,CAAA;AACH;AASA,SAAS,OAAA,CAAQ,QAAmC,IAAA,EAAsB;AACxE,EAAA,OAAO,MAAA,KAAW,OAAA,GAAU,cAAA,CAAe,IAAI,CAAA,GAAI,IAAA;AACrD;AAaA,SAAS,eAAe,IAAA,EAAsB;AAM5C,EAAA,OAAO,IAAA,CAAK,OAAA,CAAQ,aAAA,EAAe,MAAM,CAAA;AAC3C","file":"index.cjs","sourcesContent":["/**\n * The refusal this adapter answers for an outbound that carries attachments (B-674).\n *\n * This adapter sends text only, so an outbound carrying attachments is refused rather than sent without its images.\n *\n * The check runs before any other, so a refusal makes no platform call. It lives in this package\n * rather than in `@theokit/gateway` so that the adapter calls nothing its declared core floor\n * lacks; only the `OutboundMessage` type is imported.\n */\n\nimport type { OutboundMessage, SendResult } from \"@theokit/gateway\";\n\n/**\n * `attachments_unsupported` when `out` carries attachments, otherwise `undefined`.\n *\n * Absent, `null` and an empty list carry nothing. `!== 0`, not `> 0`: any other non-array value\n * from a JavaScript caller has no numeric length and is refused rather than taken for an empty\n * list (EC-1).\n */\nexport function refuseAttachments(out: OutboundMessage): SendResult | undefined {\n if (out.attachments == null || out.attachments.length === 0) return undefined;\n return {\n ok: false,\n error: { code: \"attachments_unsupported\", message: \"discord adapter cannot send attachments\" },\n };\n}\n","/**\n * Discord's 2000-char per-message hard limit. Split agent responses on safe\n * boundaries before sending (T6.1).\n *\n * Thin wrapper over core `chunkText` (roadmap M1). Telegram family (minus\n * markdown balancing): 2000 hard cap, 1900 soft window, `\\n\\n` → `\\n` → window\n * boundary preference, newline-only leading strip, no surrogate guard. Output\n * is byte-identical to the previous implementation (pinned by\n * `tests/split.test.ts`).\n *\n * @internal\n */\n\nimport { chunkText } from \"@theokit/gateway\";\n\nexport const DISCORD_MAX_MESSAGE = 2000;\nconst SAFE_DISCORD_CHUNK = 1900;\nconst BOUNDARIES = {\n boundaries: [\"\\n\\n\", \"\\n\"],\n lastResort: \"window\",\n stripLeading: /^\\n+/,\n keepTableRows: true,\n} as const;\n\n/**\n * Split `text` into chunks Discord accepts as separate messages.\n *\n * Each chunk is at most {@link DISCORD_MAX_MESSAGE} characters. The cut prefers\n * a blank line, then a newline, inside a 1900-character window, and falls back\n * to the window edge when the text has neither.\n *\n * @param text - The full outbound reply.\n * @returns The chunks in order; sending them one after another reproduces `text`\n * minus the leading newlines stripped at each cut.\n */\nexport function splitForDiscord(text: string): string[] {\n return chunkText(text, {\n limit: DISCORD_MAX_MESSAGE,\n safeLimit: SAFE_DISCORD_CHUNK,\n ...BOUNDARIES,\n });\n}\n\n/**\n * Split a text that is escaped after the split, at half the cap.\n *\n * Escaping adds at most one backslash per character, so a part of at most 1000 characters fits\n * one message once escaped. The adapter calls this only for a part whose escaped body passed the\n * cap, so the parts of an ordinary text are the ones `splitForDiscord` returns.\n */\nexport function splitForEscapedDiscord(text: string): string[] {\n return chunkText(text, {\n limit: DISCORD_MAX_MESSAGE / 2,\n safeLimit: SAFE_DISCORD_CHUNK / 2,\n ...BOUNDARIES,\n });\n}\n","/**\n * `DiscordAdapter` — wraps discord.js in the `@theokit/gateway`\n * `BasePlatformAdapter` contract (T6.1, ADRs D171, D179).\n *\n * - `connect()` calls `client.login(token)` and awaits the `ready` event.\n * - WebSocket Gateway only (D179) — no webhook variant in v0.1.\n * - Default intents include `MessageContent` (EC-C silent-failure guard).\n * - Bot-to-bot messages ignored at adapter level (`msg.author.bot`).\n * - 2000-char message split (Discord's hard limit).\n *\n * @public\n */\n\nimport type { DiscordMessageEvent, MessageEvent as GatewayMessageEvent } from \"@theokit/gateway\";\nimport { BasePlatformAdapter, type OutboundMessage, type SendResult } from \"@theokit/gateway\";\nimport {\n Client,\n DiscordAPIError,\n Events,\n GatewayIntentBits,\n type Message,\n Routes,\n} from \"discord.js\";\nimport { refuseAttachments } from \"./refuse-attachments.js\";\nimport { DISCORD_MAX_MESSAGE, splitForDiscord, splitForEscapedDiscord } from \"./split.js\";\n\nexport interface DiscordAdapterOptions {\n /**\n * The Discord bot token.\n *\n * @platform-term Discord calls this a **bot token** and `discord.js` names the field `token`, so\n * the name here is theirs.\n * @issued-at The Discord Developer Portal, under the application's Bot tab.\n */\n readonly token: string;\n /**\n * Default: [Guilds, GuildMessages, MessageContent, DirectMessages,\n * DirectMessageReactions]. Without MessageContent the bot receives\n * empty `msg.content` (EC-C silent failure).\n */\n readonly intents?: GatewayIntentBits[];\n /**\n * Deliver a guild or thread message only when it mentions the bot. Default `true`.\n *\n * A mention is the bot's user id in the message's `mentions.users`: a direct `<@id>`, and a\n * reply that pings the bot (Discord lists the pinged author there; a reply with the ping off is\n * not a mention). `@everyone`, `@here` and role mentions do not count. An event with no\n * discord.js mentions collection (one built by hand for `deliver()`) is read for `<@id>` or\n * `<@!id>` in its text. A DM is always delivered. Until the client is ready the bot id is\n * unknown, so every group message is dropped and one stderr line says why. Pass `false` to\n * deliver every message, as the adapter did before this option existed.\n */\n readonly requireMention?: boolean;\n}\n\nexport const DEFAULT_DISCORD_INTENTS: ReadonlyArray<GatewayIntentBits> = [\n GatewayIntentBits.Guilds,\n GatewayIntentBits.GuildMessages,\n GatewayIntentBits.MessageContent,\n GatewayIntentBits.DirectMessages,\n GatewayIntentBits.DirectMessageReactions,\n];\n\n/**\n * Discord gateway adapter — holds a websocket the bot opens, so inbound needs no public URL.\n *\n * Reading message CONTENT requires the privileged `MessageContent` intent, which must be enabled in\n * the Discord developer portal as well as requested here; without it every `event.text` arrives\n * empty and nothing in the API says why. `DEFAULT_DISCORD_INTENTS` requests it.\n */\nexport class DiscordAdapter extends BasePlatformAdapter {\n readonly platform = \"discord\" as const;\n private readonly client: Client;\n private readonly token: string;\n private handler?: (event: GatewayMessageEvent) => Promise<void>;\n private connected = false;\n private readonly requireMention: boolean;\n private warnedMissingBotId = false;\n\n constructor(opts: DiscordAdapterOptions) {\n super();\n this.token = opts.token;\n this.requireMention = opts.requireMention ?? true;\n const intents = (opts.intents ?? DEFAULT_DISCORD_INTENTS) as GatewayIntentBits[];\n if (intents.length === 0) {\n process.stderr.write(\n \"[discord] WARN — intents:[] passed; bot will not receive message content. Pass at least [Guilds, GuildMessages, MessageContent] (EC-C).\\n\",\n );\n }\n this.client = new Client({ intents });\n this.client.on(Events.MessageCreate, async (msg) => this.handleInbound(msg));\n this.client.on(Events.Error, (err) => {\n process.stderr.write(`[discord] client error: ${err.message}\\n`);\n });\n }\n\n override async connect(): Promise<boolean> {\n if (this.connected) return true;\n try {\n await new Promise<void>((resolve, reject) => {\n this.client.once(Events.ClientReady, () => resolve());\n this.client.login(this.token).catch(reject);\n });\n this.connected = true;\n return true;\n } catch (err) {\n process.stderr.write(`[discord] connect failed: ${(err as Error).message}\\n`);\n return false;\n }\n }\n\n override async disconnect(): Promise<void> {\n if (!this.connected) return;\n this.connected = false;\n try {\n await this.client.destroy();\n } catch {\n /* ignore */\n }\n }\n\n /**\n * Expose the underlying discord.js `Client` so consumers can register\n * platform-specific events that don't fit the portable contract —\n * `interactionCreate` (slash commands via Application Commands),\n * `error` event boundary, presence updates, etc. Register BEFORE\n * calling `runner.start()`.\n *\n * @public\n */\n getBot(): Client {\n return this.client;\n }\n\n override async sendMessage(out: OutboundMessage): Promise<SendResult> {\n return refuseAttachments(out) ?? this.sendText(out);\n }\n\n private async sendText(out: OutboundMessage): Promise<SendResult> {\n if (out.text.length === 0) {\n return { ok: false, error: { code: \"empty_text\", message: \"text is empty\" } };\n }\n let channel: unknown;\n try {\n channel = await this.client.channels.fetch(out.channel.id);\n } catch (err) {\n return {\n ok: false,\n error: { code: \"channel_fetch_failed\", message: (err as Error).message },\n };\n }\n const sendable = channel as {\n send?: (input: { content: string; reply?: unknown }) => Promise<Message>;\n };\n if (sendable === null || typeof sendable.send !== \"function\") {\n return {\n ok: false,\n error: {\n code: \"channel_not_sendable\",\n message: `channel \"${out.channel.id}\" not text-based or missing`,\n },\n };\n }\n const chunks = renderMessages(out);\n let lastId: string | undefined;\n for (const chunk of chunks) {\n try {\n const msg = await sendable.send({\n content: chunk,\n ...(out.replyTo !== undefined ? { reply: { messageReference: out.replyTo } } : {}),\n });\n lastId = msg.id;\n } catch (err) {\n return mapSendError(err);\n }\n }\n return { ok: true, ...(lastId !== undefined ? { messageId: lastId } : {}) };\n }\n\n /** Discord edits a sent message's text with one REST call. */\n override readonly supportsEdit = true;\n\n /**\n * Replace the text of a message this bot sent, with one `PATCH /channels/{id}/messages/{id}`.\n *\n * That PATCH is the request `channel.messages.edit` makes. It is sent through `client.rest`\n * without fetching the channel first, so a success is one request whatever the channel cache\n * holds; an unknown channel is answered by Discord itself (`discord_10003`). The text is split\n * and escaped by the same `renderMessages` that `sendMessage` uses, and a text a send would\n * deliver as more than one message is refused as `edit_too_long` with no request.\n */\n override async editMessage(messageId: string, out: OutboundMessage): Promise<SendResult> {\n return refuseAttachments(out) ?? this.editText(messageId, out);\n }\n\n private async editText(messageId: string, out: OutboundMessage): Promise<SendResult> {\n if (out.text.length === 0) {\n return { ok: false, error: { code: \"empty_text\", message: \"text is empty\" } };\n }\n if (messageId.length === 0) {\n return { ok: false, error: { code: \"invalid_message_id\", message: \"message id is empty\" } };\n }\n const messages = renderMessages(out);\n if (messages.length !== 1) return editPartsRefusal(messages.length);\n const content = messages[0] as string;\n try {\n await this.client.rest.patch(Routes.channelMessage(out.channel.id, messageId), {\n body: { content },\n });\n } catch (err) {\n return mapSendError(err);\n }\n return { ok: true, messageId };\n }\n\n override onInbound(handler: (event: GatewayMessageEvent) => Promise<void>): () => void {\n // EC-H: replace previous handler.\n this.handler = handler;\n return () => {\n if (this.handler === handler) this.handler = undefined;\n };\n }\n\n private async handleInbound(msg: Message): Promise<void> {\n if (this.handler === undefined) return;\n if (msg.author.bot) return;\n const event = normalizeEvent(msg);\n if (!this.passesMentionGate(event)) return;\n await this.dispatchEvent(event);\n }\n\n /**\n * Whether an event may reach the handler: always for a DM or with `requireMention` off,\n * otherwise only when the message mentions the bot. Both `deliver()` and the socket path call\n * it, so the two entries cannot disagree.\n */\n private passesMentionGate(event: GatewayMessageEvent): boolean {\n if (event.channel.type === \"dm\" || !this.requireMention) return true;\n const botId = this.client.user?.id;\n if (botId === undefined) {\n this.warnMissingBotIdOnce();\n return false;\n }\n const raw = event.platform === \"discord\" ? event.discord.raw : undefined;\n const mentionedUsers = (raw as { mentions?: { users?: { has?: unknown } } } | undefined)\n ?.mentions?.users;\n if (typeof mentionedUsers?.has === \"function\") return mentionedUsers.has(botId) === true;\n // A hand-built event carries no discord.js collection; the mention syntax is the evidence left.\n return event.text.includes(`<@${botId}>`) || event.text.includes(`<@!${botId}>`);\n }\n\n private warnMissingBotIdOnce(): void {\n if (this.warnedMissingBotId) return;\n this.warnedMissingBotId = true;\n process.stderr.write(\n \"[discord] dropping every group message: requireMention is on and the bot user id is not known until the client is ready\\n\",\n );\n }\n\n /**\n * Dispatch a pre-built event to the current handler, honouring EC-H replace\n * semantics.\n *\n * Mirrors the seam `gateway-sms` already exposes. It exists because the EC-H\n * contract had no honest test without it: a real `discord.js` Message cannot\n * be synthesized, `handler` is private, and the test that claimed to cover\n * replacement asserted two counters were 0 — true whether onInbound replaces,\n * stacks, or discards. If it had regressed to `handlers.push(handler)`, the\n * agent would have replied twice to every message, double-billing tokens,\n * with the suite green.\n *\n * @internal\n */\n async dispatchEvent(event: GatewayMessageEvent): Promise<\"ok\" | \"no_handler\" | \"handler_threw\"> {\n if (this.handler === undefined) return \"no_handler\";\n try {\n await this.handler(event);\n } catch (err) {\n // Left uncaught, the rejection escaped into the platform's own error channel and was reported\n // as a client error — so a bug in the consumer's handler read as a fault in the platform\n // library, sending whoever debugged it to the wrong repository (#41). A handler is user code:\n // its failure is named as such, and delivery continues.\n const m = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[discord] handler threw: ${m}\\n`);\n return \"handler_threw\";\n }\n return \"ok\";\n }\n\n /**\n * Deliver an event that arrived out of band — the ingest `onInbound` had no counterpart for (#83).\n *\n * The mention gate runs first, as on the socket path: an event it drops answers `\"ok\"`, with or\n * without a handler subscribed. `runHandler` owns the containment: a handler is user code, its\n * throw is named as the handler's failure rather than the platform's, and delivery continues.\n */\n override async deliver(\n event: GatewayMessageEvent,\n ): Promise<\"ok\" | \"no_handler\" | \"handler_threw\"> {\n if (!this.passesMentionGate(event)) return \"ok\";\n return this.runHandler(this.handler, event);\n }\n}\n\nfunction normalizeEvent(msg: Message): DiscordMessageEvent {\n let channelType: \"dm\" | \"group\" | \"thread\";\n if (msg.guildId === null) {\n channelType = \"dm\";\n } else if (msg.channel.isThread()) {\n channelType = \"thread\";\n } else {\n channelType = \"group\";\n }\n\n const displayName = msg.author.globalName !== null ? msg.author.globalName : msg.author.username;\n\n return {\n id: `dc-${msg.channelId}-${msg.id}`,\n platform: \"discord\",\n sender: {\n id: msg.author.id,\n username: msg.author.username,\n displayName,\n },\n channel: {\n id: msg.channelId,\n type: channelType,\n ...(msg.channel.isThread() ? { topicId: msg.channel.id } : {}),\n },\n text: msg.content,\n receivedAt: msg.createdTimestamp,\n ...(msg.reference?.messageId !== undefined ? { replyTo: msg.reference.messageId } : {}),\n discord: {\n guildId: msg.guildId,\n channelId: msg.channelId,\n messageId: msg.id,\n raw: msg,\n },\n };\n}\n\n/**\n * The refusal for a text that is not exactly one Discord message.\n *\n * More than one part is `edit_too_long`. No parts cannot happen today, since `splitForDiscord`\n * returns at least one part for any non-empty text and empty text is refused earlier; the arm\n * keeps a later splitter that returns `[]` from editing with `undefined`.\n */\nfunction editPartsRefusal(partCount: number): SendResult {\n if (partCount > 1) {\n return {\n ok: false,\n error: {\n code: \"edit_too_long\",\n message: `text needs ${partCount} Discord messages; an edit replaces one`,\n },\n };\n }\n return { ok: false, error: { code: \"empty_text\", message: \"text reduced to zero parts\" } };\n}\n\nfunction mapSendError(err: unknown): SendResult {\n if (err instanceof DiscordAPIError) {\n const codeStr = String(err.code);\n if (codeStr === \"50007\") {\n return { ok: false, error: { code: \"dm_blocked\", message: err.message } };\n }\n if (codeStr === \"50001\" || codeStr === \"50013\") {\n return { ok: false, error: { code: \"no_permission\", message: err.message } };\n }\n if (err.status === 429) {\n return { ok: false, error: { code: \"rate_limited\", message: err.message } };\n }\n return { ok: false, error: { code: `discord_${codeStr}`, message: err.message } };\n }\n return { ok: false, error: { code: \"unknown\", message: (err as Error).message } };\n}\n\n/**\n * The message bodies a text goes out as, each within `DISCORD_MAX_MESSAGE`.\n *\n * Split FIRST, escape each part. The other order lets the splitter's hard window cut land between\n * a backslash and the character it guards: message 1 ends in a stray backslash the user never\n * typed, and message 2 opens with a bare `*` that Discord parses as markup. Demonstrated in review\n * against the real splitter. The splitter measures the caller's text, and escaping a `plain` part\n * can double it, so a part whose body passes the cap is split again at half the cap, which every\n * escaped body fits. `sendMessage` and `editMessage` both send what this returns, so an edit is\n * refused for exactly the texts a send delivers as more than one message.\n */\nfunction renderMessages(out: OutboundMessage): string[] {\n return splitForDiscord(out.text).flatMap((part) => {\n const body = bodyFor(out.format, part);\n if (body.length <= DISCORD_MAX_MESSAGE) return [body];\n return splitForEscapedDiscord(part).map((half) => bodyFor(out.format, half));\n });\n}\n\n/**\n * The text to send, with the caller's declared format applied.\n *\n * Discord parses markdown natively, so `markdown` needs no flag. `plain` is the caller stating\n * the text is NOT markup, and sending it raw would parse it anyway — a user's literal\n * `*asterisks*` arriving as italic.\n */\nfunction bodyFor(format: OutboundMessage[\"format\"], text: string): string {\n return format === \"plain\" ? escapeMarkdown(text) : text;\n}\n\n/**\n * Escape the characters this platform would otherwise parse as markup.\n *\n * Called only when the caller declared `format: \"plain\"` — an explicit statement that the text\n * is NOT markup. Without it, a user's literal `*asterisks*` render as italic on a platform that\n * parses markdown natively, which is the caller's intent being silently inverted.\n *\n * Deliberately narrow: the four characters that open an inline span. A full markdown escaper\n * would also touch `#`, `>` and `-` at line starts, which are far more common in ordinary prose\n * and whose escaping is more visible than the problem it solves.\n */\nfunction escapeMarkdown(text: string): string {\n // The backslash comes FIRST, and that ordering is the whole correctness of this function.\n // Without it a backslash already in the caller's text is left bare: `a\\*b` escapes to `a\\\\*b`,\n // the renderer consumes `\\\\` as one literal backslash, and the `*` it was guarding is left\n // naked — so text sent explicitly as `plain` arrives italicised, the exact inversion this\n // function exists to prevent. Caught in review.\n return text.replace(/([\\\\*_`~])/g, \"\\\\$1\");\n}\n"]}
package/dist/index.d.cts CHANGED
@@ -29,6 +29,18 @@ interface DiscordAdapterOptions {
29
29
  * empty `msg.content` (EC-C silent failure).
30
30
  */
31
31
  readonly intents?: GatewayIntentBits[];
32
+ /**
33
+ * Deliver a guild or thread message only when it mentions the bot. Default `true`.
34
+ *
35
+ * A mention is the bot's user id in the message's `mentions.users`: a direct `<@id>`, and a
36
+ * reply that pings the bot (Discord lists the pinged author there; a reply with the ping off is
37
+ * not a mention). `@everyone`, `@here` and role mentions do not count. An event with no
38
+ * discord.js mentions collection (one built by hand for `deliver()`) is read for `<@id>` or
39
+ * `<@!id>` in its text. A DM is always delivered. Until the client is ready the bot id is
40
+ * unknown, so every group message is dropped and one stderr line says why. Pass `false` to
41
+ * deliver every message, as the adapter did before this option existed.
42
+ */
43
+ readonly requireMention?: boolean;
32
44
  }
33
45
  /**
34
46
  * Discord gateway adapter — holds a websocket the bot opens, so inbound needs no public URL.
@@ -43,6 +55,8 @@ declare class DiscordAdapter extends BasePlatformAdapter {
43
55
  private readonly token;
44
56
  private handler?;
45
57
  private connected;
58
+ private readonly requireMention;
59
+ private warnedMissingBotId;
46
60
  constructor(opts: DiscordAdapterOptions);
47
61
  connect(): Promise<boolean>;
48
62
  disconnect(): Promise<void>;
@@ -57,28 +71,49 @@ declare class DiscordAdapter extends BasePlatformAdapter {
57
71
  */
58
72
  getBot(): Client;
59
73
  sendMessage(out: OutboundMessage): Promise<SendResult>;
74
+ private sendText;
75
+ /** Discord edits a sent message's text with one REST call. */
76
+ readonly supportsEdit = true;
77
+ /**
78
+ * Replace the text of a message this bot sent, with one `PATCH /channels/{id}/messages/{id}`.
79
+ *
80
+ * That PATCH is the request `channel.messages.edit` makes. It is sent through `client.rest`
81
+ * without fetching the channel first, so a success is one request whatever the channel cache
82
+ * holds; an unknown channel is answered by Discord itself (`discord_10003`). The text is split
83
+ * and escaped by the same `renderMessages` that `sendMessage` uses, and a text a send would
84
+ * deliver as more than one message is refused as `edit_too_long` with no request.
85
+ */
86
+ editMessage(messageId: string, out: OutboundMessage): Promise<SendResult>;
87
+ private editText;
60
88
  onInbound(handler: (event: MessageEvent) => Promise<void>): () => void;
61
89
  private handleInbound;
90
+ /**
91
+ * Whether an event may reach the handler: always for a DM or with `requireMention` off,
92
+ * otherwise only when the message mentions the bot. Both `deliver()` and the socket path call
93
+ * it, so the two entries cannot disagree.
94
+ */
95
+ private passesMentionGate;
96
+ private warnMissingBotIdOnce;
62
97
  /**
63
98
  * Deliver an event that arrived out of band — the ingest `onInbound` had no counterpart for (#83).
64
99
  *
65
- * One line over `runHandler`, which owns the containment: a handler is user code, its throw is
66
- * named as the handler's failure rather than the platform's, and delivery continues.
100
+ * The mention gate runs first, as on the socket path: an event it drops answers `"ok"`, with or
101
+ * without a handler subscribed. `runHandler` owns the containment: a handler is user code, its
102
+ * throw is named as the handler's failure rather than the platform's, and delivery continues.
67
103
  */
68
104
  deliver(event: MessageEvent): Promise<"ok" | "no_handler" | "handler_threw">;
69
105
  }
70
106
 
71
107
  /**
72
- * Discord's 2000-char per-message hard limit. Split agent responses on safe
73
- * boundaries before sending (T6.1).
108
+ * Split `text` into chunks Discord accepts as separate messages.
74
109
  *
75
- * Thin wrapper over core `chunkText` (roadmap M1). Telegram family (minus
76
- * markdown balancing): 2000 hard cap, 1900 soft window, `\n\n` → `\n` → window
77
- * boundary preference, newline-only leading strip, no surrogate guard. Output
78
- * is byte-identical to the previous implementation (pinned by
79
- * `tests/split.test.ts`).
110
+ * Each chunk is at most {@link DISCORD_MAX_MESSAGE} characters. The cut prefers
111
+ * a blank line, then a newline, inside a 1900-character window, and falls back
112
+ * to the window edge when the text has neither.
80
113
  *
81
- * @internal
114
+ * @param text - The full outbound reply.
115
+ * @returns The chunks in order; sending them one after another reproduces `text`
116
+ * minus the leading newlines stripped at each cut.
82
117
  */
83
118
  declare function splitForDiscord(text: string): string[];
84
119
 
package/dist/index.d.ts CHANGED
@@ -29,6 +29,18 @@ interface DiscordAdapterOptions {
29
29
  * empty `msg.content` (EC-C silent failure).
30
30
  */
31
31
  readonly intents?: GatewayIntentBits[];
32
+ /**
33
+ * Deliver a guild or thread message only when it mentions the bot. Default `true`.
34
+ *
35
+ * A mention is the bot's user id in the message's `mentions.users`: a direct `<@id>`, and a
36
+ * reply that pings the bot (Discord lists the pinged author there; a reply with the ping off is
37
+ * not a mention). `@everyone`, `@here` and role mentions do not count. An event with no
38
+ * discord.js mentions collection (one built by hand for `deliver()`) is read for `<@id>` or
39
+ * `<@!id>` in its text. A DM is always delivered. Until the client is ready the bot id is
40
+ * unknown, so every group message is dropped and one stderr line says why. Pass `false` to
41
+ * deliver every message, as the adapter did before this option existed.
42
+ */
43
+ readonly requireMention?: boolean;
32
44
  }
33
45
  /**
34
46
  * Discord gateway adapter — holds a websocket the bot opens, so inbound needs no public URL.
@@ -43,6 +55,8 @@ declare class DiscordAdapter extends BasePlatformAdapter {
43
55
  private readonly token;
44
56
  private handler?;
45
57
  private connected;
58
+ private readonly requireMention;
59
+ private warnedMissingBotId;
46
60
  constructor(opts: DiscordAdapterOptions);
47
61
  connect(): Promise<boolean>;
48
62
  disconnect(): Promise<void>;
@@ -57,28 +71,49 @@ declare class DiscordAdapter extends BasePlatformAdapter {
57
71
  */
58
72
  getBot(): Client;
59
73
  sendMessage(out: OutboundMessage): Promise<SendResult>;
74
+ private sendText;
75
+ /** Discord edits a sent message's text with one REST call. */
76
+ readonly supportsEdit = true;
77
+ /**
78
+ * Replace the text of a message this bot sent, with one `PATCH /channels/{id}/messages/{id}`.
79
+ *
80
+ * That PATCH is the request `channel.messages.edit` makes. It is sent through `client.rest`
81
+ * without fetching the channel first, so a success is one request whatever the channel cache
82
+ * holds; an unknown channel is answered by Discord itself (`discord_10003`). The text is split
83
+ * and escaped by the same `renderMessages` that `sendMessage` uses, and a text a send would
84
+ * deliver as more than one message is refused as `edit_too_long` with no request.
85
+ */
86
+ editMessage(messageId: string, out: OutboundMessage): Promise<SendResult>;
87
+ private editText;
60
88
  onInbound(handler: (event: MessageEvent) => Promise<void>): () => void;
61
89
  private handleInbound;
90
+ /**
91
+ * Whether an event may reach the handler: always for a DM or with `requireMention` off,
92
+ * otherwise only when the message mentions the bot. Both `deliver()` and the socket path call
93
+ * it, so the two entries cannot disagree.
94
+ */
95
+ private passesMentionGate;
96
+ private warnMissingBotIdOnce;
62
97
  /**
63
98
  * Deliver an event that arrived out of band — the ingest `onInbound` had no counterpart for (#83).
64
99
  *
65
- * One line over `runHandler`, which owns the containment: a handler is user code, its throw is
66
- * named as the handler's failure rather than the platform's, and delivery continues.
100
+ * The mention gate runs first, as on the socket path: an event it drops answers `"ok"`, with or
101
+ * without a handler subscribed. `runHandler` owns the containment: a handler is user code, its
102
+ * throw is named as the handler's failure rather than the platform's, and delivery continues.
67
103
  */
68
104
  deliver(event: MessageEvent): Promise<"ok" | "no_handler" | "handler_threw">;
69
105
  }
70
106
 
71
107
  /**
72
- * Discord's 2000-char per-message hard limit. Split agent responses on safe
73
- * boundaries before sending (T6.1).
108
+ * Split `text` into chunks Discord accepts as separate messages.
74
109
  *
75
- * Thin wrapper over core `chunkText` (roadmap M1). Telegram family (minus
76
- * markdown balancing): 2000 hard cap, 1900 soft window, `\n\n` → `\n` → window
77
- * boundary preference, newline-only leading strip, no surrogate guard. Output
78
- * is byte-identical to the previous implementation (pinned by
79
- * `tests/split.test.ts`).
110
+ * Each chunk is at most {@link DISCORD_MAX_MESSAGE} characters. The cut prefers
111
+ * a blank line, then a newline, inside a 1900-character window, and falls back
112
+ * to the window edge when the text has neither.
80
113
  *
81
- * @internal
114
+ * @param text - The full outbound reply.
115
+ * @returns The chunks in order; sending them one after another reproduces `text`
116
+ * minus the leading newlines stripped at each cut.
82
117
  */
83
118
  declare function splitForDiscord(text: string): string[];
84
119
 
package/dist/index.js CHANGED
@@ -1,16 +1,36 @@
1
1
  import { chunkText, BasePlatformAdapter } from '@theokit/gateway';
2
- import { GatewayIntentBits, Client, Events, DiscordAPIError } from 'discord.js';
2
+ import { GatewayIntentBits, Client, Events, Routes, DiscordAPIError } from 'discord.js';
3
3
 
4
4
  // src/adapter.ts
5
+
6
+ // src/refuse-attachments.ts
7
+ function refuseAttachments(out) {
8
+ if (out.attachments == null || out.attachments.length === 0) return void 0;
9
+ return {
10
+ ok: false,
11
+ error: { code: "attachments_unsupported", message: "discord adapter cannot send attachments" }
12
+ };
13
+ }
5
14
  var DISCORD_MAX_MESSAGE = 2e3;
6
15
  var SAFE_DISCORD_CHUNK = 1900;
16
+ var BOUNDARIES = {
17
+ boundaries: ["\n\n", "\n"],
18
+ lastResort: "window",
19
+ stripLeading: /^\n+/,
20
+ keepTableRows: true
21
+ };
7
22
  function splitForDiscord(text) {
8
23
  return chunkText(text, {
9
24
  limit: DISCORD_MAX_MESSAGE,
10
25
  safeLimit: SAFE_DISCORD_CHUNK,
11
- boundaries: ["\n\n", "\n"],
12
- lastResort: "window",
13
- stripLeading: /^\n+/
26
+ ...BOUNDARIES
27
+ });
28
+ }
29
+ function splitForEscapedDiscord(text) {
30
+ return chunkText(text, {
31
+ limit: DISCORD_MAX_MESSAGE / 2,
32
+ safeLimit: SAFE_DISCORD_CHUNK / 2,
33
+ ...BOUNDARIES
14
34
  });
15
35
  }
16
36
 
@@ -28,9 +48,12 @@ var DiscordAdapter = class extends BasePlatformAdapter {
28
48
  token;
29
49
  handler;
30
50
  connected = false;
51
+ requireMention;
52
+ warnedMissingBotId = false;
31
53
  constructor(opts) {
32
54
  super();
33
55
  this.token = opts.token;
56
+ this.requireMention = opts.requireMention ?? true;
34
57
  const intents = opts.intents ?? DEFAULT_DISCORD_INTENTS;
35
58
  if (intents.length === 0) {
36
59
  process.stderr.write(
@@ -80,6 +103,9 @@ var DiscordAdapter = class extends BasePlatformAdapter {
80
103
  return this.client;
81
104
  }
82
105
  async sendMessage(out) {
106
+ return refuseAttachments(out) ?? this.sendText(out);
107
+ }
108
+ async sendText(out) {
83
109
  if (out.text.length === 0) {
84
110
  return { ok: false, error: { code: "empty_text", message: "text is empty" } };
85
111
  }
@@ -102,7 +128,7 @@ var DiscordAdapter = class extends BasePlatformAdapter {
102
128
  }
103
129
  };
104
130
  }
105
- const chunks = splitForDiscord(out.text).map((chunk) => bodyFor(out.format, chunk));
131
+ const chunks = renderMessages(out);
106
132
  let lastId;
107
133
  for (const chunk of chunks) {
108
134
  try {
@@ -117,6 +143,39 @@ var DiscordAdapter = class extends BasePlatformAdapter {
117
143
  }
118
144
  return { ok: true, ...lastId !== void 0 ? { messageId: lastId } : {} };
119
145
  }
146
+ /** Discord edits a sent message's text with one REST call. */
147
+ supportsEdit = true;
148
+ /**
149
+ * Replace the text of a message this bot sent, with one `PATCH /channels/{id}/messages/{id}`.
150
+ *
151
+ * That PATCH is the request `channel.messages.edit` makes. It is sent through `client.rest`
152
+ * without fetching the channel first, so a success is one request whatever the channel cache
153
+ * holds; an unknown channel is answered by Discord itself (`discord_10003`). The text is split
154
+ * and escaped by the same `renderMessages` that `sendMessage` uses, and a text a send would
155
+ * deliver as more than one message is refused as `edit_too_long` with no request.
156
+ */
157
+ async editMessage(messageId, out) {
158
+ return refuseAttachments(out) ?? this.editText(messageId, out);
159
+ }
160
+ async editText(messageId, out) {
161
+ if (out.text.length === 0) {
162
+ return { ok: false, error: { code: "empty_text", message: "text is empty" } };
163
+ }
164
+ if (messageId.length === 0) {
165
+ return { ok: false, error: { code: "invalid_message_id", message: "message id is empty" } };
166
+ }
167
+ const messages = renderMessages(out);
168
+ if (messages.length !== 1) return editPartsRefusal(messages.length);
169
+ const content = messages[0];
170
+ try {
171
+ await this.client.rest.patch(Routes.channelMessage(out.channel.id, messageId), {
172
+ body: { content }
173
+ });
174
+ } catch (err) {
175
+ return mapSendError(err);
176
+ }
177
+ return { ok: true, messageId };
178
+ }
120
179
  onInbound(handler) {
121
180
  this.handler = handler;
122
181
  return () => {
@@ -126,7 +185,33 @@ var DiscordAdapter = class extends BasePlatformAdapter {
126
185
  async handleInbound(msg) {
127
186
  if (this.handler === void 0) return;
128
187
  if (msg.author.bot) return;
129
- await this.dispatchEvent(normalizeEvent(msg));
188
+ const event = normalizeEvent(msg);
189
+ if (!this.passesMentionGate(event)) return;
190
+ await this.dispatchEvent(event);
191
+ }
192
+ /**
193
+ * Whether an event may reach the handler: always for a DM or with `requireMention` off,
194
+ * otherwise only when the message mentions the bot. Both `deliver()` and the socket path call
195
+ * it, so the two entries cannot disagree.
196
+ */
197
+ passesMentionGate(event) {
198
+ if (event.channel.type === "dm" || !this.requireMention) return true;
199
+ const botId = this.client.user?.id;
200
+ if (botId === void 0) {
201
+ this.warnMissingBotIdOnce();
202
+ return false;
203
+ }
204
+ const raw = event.platform === "discord" ? event.discord.raw : void 0;
205
+ const mentionedUsers = raw?.mentions?.users;
206
+ if (typeof mentionedUsers?.has === "function") return mentionedUsers.has(botId) === true;
207
+ return event.text.includes(`<@${botId}>`) || event.text.includes(`<@!${botId}>`);
208
+ }
209
+ warnMissingBotIdOnce() {
210
+ if (this.warnedMissingBotId) return;
211
+ this.warnedMissingBotId = true;
212
+ process.stderr.write(
213
+ "[discord] dropping every group message: requireMention is on and the bot user id is not known until the client is ready\n"
214
+ );
130
215
  }
131
216
  /**
132
217
  * Dispatch a pre-built event to the current handler, honouring EC-H replace
@@ -157,10 +242,12 @@ var DiscordAdapter = class extends BasePlatformAdapter {
157
242
  /**
158
243
  * Deliver an event that arrived out of band — the ingest `onInbound` had no counterpart for (#83).
159
244
  *
160
- * One line over `runHandler`, which owns the containment: a handler is user code, its throw is
161
- * named as the handler's failure rather than the platform's, and delivery continues.
245
+ * The mention gate runs first, as on the socket path: an event it drops answers `"ok"`, with or
246
+ * without a handler subscribed. `runHandler` owns the containment: a handler is user code, its
247
+ * throw is named as the handler's failure rather than the platform's, and delivery continues.
162
248
  */
163
249
  async deliver(event) {
250
+ if (!this.passesMentionGate(event)) return "ok";
164
251
  return this.runHandler(this.handler, event);
165
252
  }
166
253
  };
@@ -198,6 +285,18 @@ function normalizeEvent(msg) {
198
285
  }
199
286
  };
200
287
  }
288
+ function editPartsRefusal(partCount) {
289
+ if (partCount > 1) {
290
+ return {
291
+ ok: false,
292
+ error: {
293
+ code: "edit_too_long",
294
+ message: `text needs ${partCount} Discord messages; an edit replaces one`
295
+ }
296
+ };
297
+ }
298
+ return { ok: false, error: { code: "empty_text", message: "text reduced to zero parts" } };
299
+ }
201
300
  function mapSendError(err) {
202
301
  if (err instanceof DiscordAPIError) {
203
302
  const codeStr = String(err.code);
@@ -214,6 +313,13 @@ function mapSendError(err) {
214
313
  }
215
314
  return { ok: false, error: { code: "unknown", message: err.message } };
216
315
  }
316
+ function renderMessages(out) {
317
+ return splitForDiscord(out.text).flatMap((part) => {
318
+ const body = bodyFor(out.format, part);
319
+ if (body.length <= DISCORD_MAX_MESSAGE) return [body];
320
+ return splitForEscapedDiscord(part).map((half) => bodyFor(out.format, half));
321
+ });
322
+ }
217
323
  function bodyFor(format, text) {
218
324
  return format === "plain" ? escapeMarkdown(text) : text;
219
325
  }
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/split.ts","../src/adapter.ts"],"names":[],"mappings":";;;;AAeA,IAAM,mBAAA,GAAsB,GAAA;AAC5B,IAAM,kBAA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GAAA,CAAc,OAAA,EAAQ,EAAE;AAClF;AASA,SAAS,OAAA,CAAQ,QAAmC,IAAA,EAAsB;AACxE,EAAA,OAAO,MAAA,KAAW,OAAA,GAAU,cAAA,CAAe,IAAI,CAAA,GAAI,IAAA;AACrD;AAaA,SAAS,eAAe,IAAA,EAAsB;AAM5C,EAAA,OAAO,IAAA,CAAK,OAAA,CAAQ,aAAA,EAAe,MAAM,CAAA;AAC3C","file":"index.js","sourcesContent":["/**\n * Discord's 2000-char per-message hard limit. Split agent responses on safe\n * boundaries before sending (T6.1).\n *\n * Thin wrapper over core `chunkText` (roadmap M1). Telegram family (minus\n * markdown balancing): 2000 hard cap, 1900 soft window, `\\n\\n` → `\\n` → window\n * boundary preference, newline-only leading strip, no surrogate guard. Output\n * is byte-identical to the previous implementation (pinned by\n * `tests/split.test.ts`).\n *\n * @internal\n */\n\nimport { chunkText } from \"@theokit/gateway\";\n\nconst DISCORD_MAX_MESSAGE = 2000;\nconst SAFE_DISCORD_CHUNK = 1900;\n\nexport function splitForDiscord(text: string): string[] {\n return chunkText(text, {\n limit: DISCORD_MAX_MESSAGE,\n safeLimit: SAFE_DISCORD_CHUNK,\n boundaries: [\"\\n\\n\", \"\\n\"],\n lastResort: \"window\",\n stripLeading: /^\\n+/,\n });\n}\n","/**\n * `DiscordAdapter` — wraps discord.js in the `@theokit/gateway`\n * `BasePlatformAdapter` contract (T6.1, ADRs D171, D179).\n *\n * - `connect()` calls `client.login(token)` and awaits the `ready` event.\n * - WebSocket Gateway only (D179) — no webhook variant in v0.1.\n * - Default intents include `MessageContent` (EC-C silent-failure guard).\n * - Bot-to-bot messages ignored at adapter level (`msg.author.bot`).\n * - 2000-char message split (Discord's hard limit).\n *\n * @public\n */\n\nimport type { DiscordMessageEvent, MessageEvent as GatewayMessageEvent } from \"@theokit/gateway\";\nimport { BasePlatformAdapter, type OutboundMessage, type SendResult } from \"@theokit/gateway\";\nimport { Client, DiscordAPIError, Events, GatewayIntentBits, type Message } from \"discord.js\";\n\nimport { splitForDiscord } from \"./split.js\";\n\nexport interface DiscordAdapterOptions {\n /**\n * The Discord bot token.\n *\n * @platform-term Discord calls this a **bot token** and `discord.js` names the field `token`, so\n * the name here is theirs.\n * @issued-at The Discord Developer Portal, under the application's Bot tab.\n */\n readonly token: string;\n /**\n * Default: [Guilds, GuildMessages, MessageContent, DirectMessages,\n * DirectMessageReactions]. Without MessageContent the bot receives\n * empty `msg.content` (EC-C silent failure).\n */\n readonly intents?: GatewayIntentBits[];\n}\n\nexport const DEFAULT_DISCORD_INTENTS: ReadonlyArray<GatewayIntentBits> = [\n GatewayIntentBits.Guilds,\n GatewayIntentBits.GuildMessages,\n GatewayIntentBits.MessageContent,\n GatewayIntentBits.DirectMessages,\n GatewayIntentBits.DirectMessageReactions,\n];\n\n/**\n * Discord gateway adapter — holds a websocket the bot opens, so inbound needs no public URL.\n *\n * Reading message CONTENT requires the privileged `MessageContent` intent, which must be enabled in\n * the Discord developer portal as well as requested here; without it every `event.text` arrives\n * empty and nothing in the API says why. `DEFAULT_DISCORD_INTENTS` requests it.\n */\nexport class DiscordAdapter extends BasePlatformAdapter {\n readonly platform = \"discord\" as const;\n private readonly client: Client;\n private readonly token: string;\n private handler?: (event: GatewayMessageEvent) => Promise<void>;\n private connected = false;\n\n constructor(opts: DiscordAdapterOptions) {\n super();\n this.token = opts.token;\n const intents = (opts.intents ?? DEFAULT_DISCORD_INTENTS) as GatewayIntentBits[];\n if (intents.length === 0) {\n process.stderr.write(\n \"[discord] WARN — intents:[] passed; bot will not receive message content. Pass at least [Guilds, GuildMessages, MessageContent] (EC-C).\\n\",\n );\n }\n this.client = new Client({ intents });\n this.client.on(Events.MessageCreate, async (msg) => this.handleInbound(msg));\n this.client.on(Events.Error, (err) => {\n process.stderr.write(`[discord] client error: ${err.message}\\n`);\n });\n }\n\n override async connect(): Promise<boolean> {\n if (this.connected) return true;\n try {\n await new Promise<void>((resolve, reject) => {\n this.client.once(Events.ClientReady, () => resolve());\n this.client.login(this.token).catch(reject);\n });\n this.connected = true;\n return true;\n } catch (err) {\n process.stderr.write(`[discord] connect failed: ${(err as Error).message}\\n`);\n return false;\n }\n }\n\n override async disconnect(): Promise<void> {\n if (!this.connected) return;\n this.connected = false;\n try {\n await this.client.destroy();\n } catch {\n /* ignore */\n }\n }\n\n /**\n * Expose the underlying discord.js `Client` so consumers can register\n * platform-specific events that don't fit the portable contract —\n * `interactionCreate` (slash commands via Application Commands),\n * `error` event boundary, presence updates, etc. Register BEFORE\n * calling `runner.start()`.\n *\n * @public\n */\n getBot(): Client {\n return this.client;\n }\n\n override async sendMessage(out: OutboundMessage): Promise<SendResult> {\n if (out.text.length === 0) {\n return { ok: false, error: { code: \"empty_text\", message: \"text is empty\" } };\n }\n let channel: unknown;\n try {\n channel = await this.client.channels.fetch(out.channel.id);\n } catch (err) {\n return {\n ok: false,\n error: { code: \"channel_fetch_failed\", message: (err as Error).message },\n };\n }\n const sendable = channel as {\n send?: (input: { content: string; reply?: unknown }) => Promise<Message>;\n };\n if (sendable === null || typeof sendable.send !== \"function\") {\n return {\n ok: false,\n error: {\n code: \"channel_not_sendable\",\n message: `channel \"${out.channel.id}\" not text-based or missing`,\n },\n };\n }\n // Split FIRST, escape each chunk. The other order lets `splitForDiscord`'s hard window cut\n // land between a backslash and the character it guards: message 1 ends in a stray backslash\n // the user never typed, and message 2 opens with a bare `*` that Discord parses as markup.\n // Demonstrated in review against the real splitter.\n const chunks = splitForDiscord(out.text).map((chunk) => bodyFor(out.format, chunk));\n let lastId: string | undefined;\n for (const chunk of chunks) {\n try {\n const msg = await sendable.send({\n content: chunk,\n ...(out.replyTo !== undefined ? { reply: { messageReference: out.replyTo } } : {}),\n });\n lastId = msg.id;\n } catch (err) {\n return mapSendError(err);\n }\n }\n return { ok: true, ...(lastId !== undefined ? { messageId: lastId } : {}) };\n }\n\n override onInbound(handler: (event: GatewayMessageEvent) => Promise<void>): () => void {\n // EC-H: replace previous handler.\n this.handler = handler;\n return () => {\n if (this.handler === handler) this.handler = undefined;\n };\n }\n\n private async handleInbound(msg: Message): Promise<void> {\n if (this.handler === undefined) return;\n if (msg.author.bot) return;\n await this.dispatchEvent(normalizeEvent(msg));\n }\n\n /**\n * Dispatch a pre-built event to the current handler, honouring EC-H replace\n * semantics.\n *\n * Mirrors the seam `gateway-sms` already exposes. It exists because the EC-H\n * contract had no honest test without it: a real `discord.js` Message cannot\n * be synthesized, `handler` is private, and the test that claimed to cover\n * replacement asserted two counters were 0 — true whether onInbound replaces,\n * stacks, or discards. If it had regressed to `handlers.push(handler)`, the\n * agent would have replied twice to every message, double-billing tokens,\n * with the suite green.\n *\n * @internal\n */\n async dispatchEvent(event: GatewayMessageEvent): Promise<\"ok\" | \"no_handler\" | \"handler_threw\"> {\n if (this.handler === undefined) return \"no_handler\";\n try {\n await this.handler(event);\n } catch (err) {\n // Left uncaught, the rejection escaped into the platform's own error channel and was reported\n // as a client error — so a bug in the consumer's handler read as a fault in the platform\n // library, sending whoever debugged it to the wrong repository (#41). A handler is user code:\n // its failure is named as such, and delivery continues.\n const m = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[discord] handler threw: ${m}\\n`);\n return \"handler_threw\";\n }\n return \"ok\";\n }\n\n /**\n * Deliver an event that arrived out of band — the ingest `onInbound` had no counterpart for (#83).\n *\n * One line over `runHandler`, which owns the containment: a handler is user code, its throw is\n * named as the handler's failure rather than the platform's, and delivery continues.\n */\n override async deliver(\n event: GatewayMessageEvent,\n ): Promise<\"ok\" | \"no_handler\" | \"handler_threw\"> {\n return this.runHandler(this.handler, event);\n }\n}\n\nfunction normalizeEvent(msg: Message): DiscordMessageEvent {\n let channelType: \"dm\" | \"group\" | \"thread\";\n if (msg.guildId === null) {\n channelType = \"dm\";\n } else if (msg.channel.isThread()) {\n channelType = \"thread\";\n } else {\n channelType = \"group\";\n }\n\n const displayName = msg.author.globalName !== null ? msg.author.globalName : msg.author.username;\n\n return {\n id: `dc-${msg.channelId}-${msg.id}`,\n platform: \"discord\",\n sender: {\n id: msg.author.id,\n username: msg.author.username,\n displayName,\n },\n channel: {\n id: msg.channelId,\n type: channelType,\n ...(msg.channel.isThread() ? { topicId: msg.channel.id } : {}),\n },\n text: msg.content,\n receivedAt: msg.createdTimestamp,\n ...(msg.reference?.messageId !== undefined ? { replyTo: msg.reference.messageId } : {}),\n discord: {\n guildId: msg.guildId,\n channelId: msg.channelId,\n messageId: msg.id,\n raw: msg,\n },\n };\n}\n\nfunction mapSendError(err: unknown): SendResult {\n if (err instanceof DiscordAPIError) {\n const codeStr = String(err.code);\n if (codeStr === \"50007\") {\n return { ok: false, error: { code: \"dm_blocked\", message: err.message } };\n }\n if (codeStr === \"50001\" || codeStr === \"50013\") {\n return { ok: false, error: { code: \"no_permission\", message: err.message } };\n }\n if (err.status === 429) {\n return { ok: false, error: { code: \"rate_limited\", message: err.message } };\n }\n return { ok: false, error: { code: `discord_${codeStr}`, message: err.message } };\n }\n return { ok: false, error: { code: \"unknown\", message: (err as Error).message } };\n}\n\n/**\n * The text to send, with the caller's declared format applied.\n *\n * Discord parses markdown natively, so `markdown` needs no flag. `plain` is the caller stating\n * the text is NOT markup, and sending it raw would parse it anyway — a user's literal\n * `*asterisks*` arriving as italic.\n */\nfunction bodyFor(format: OutboundMessage[\"format\"], text: string): string {\n return format === \"plain\" ? escapeMarkdown(text) : text;\n}\n\n/**\n * Escape the characters this platform would otherwise parse as markup.\n *\n * Called only when the caller declared `format: \"plain\"` — an explicit statement that the text\n * is NOT markup. Without it, a user's literal `*asterisks*` render as italic on a platform that\n * parses markdown natively, which is the caller's intent being silently inverted.\n *\n * Deliberately narrow: the four characters that open an inline span. A full markdown escaper\n * would also touch `#`, `>` and `-` at line starts, which are far more common in ordinary prose\n * and whose escaping is more visible than the problem it solves.\n */\nfunction escapeMarkdown(text: string): string {\n // The backslash comes FIRST, and that ordering is the whole correctness of this function.\n // Without it a backslash already in the caller's text is left bare: `a\\*b` escapes to `a\\\\*b`,\n // the renderer consumes `\\\\` as one literal backslash, and the `*` it was guarding is left\n // naked — so text sent explicitly as `plain` arrives italicised, the exact inversion this\n // function exists to prevent. Caught in review.\n return text.replace(/([\\\\*_`~])/g, \"\\\\$1\");\n}\n"]}
1
+ {"version":3,"sources":["../src/refuse-attachments.ts","../src/split.ts","../src/adapter.ts"],"names":[],"mappings":";;;;;;AAmBO,SAAS,kBAAkB,GAAA,EAA8C;AAC9E,EAAA,IAAI,IAAI,WAAA,IAAe,IAAA,IAAQ,IAAI,WAAA,CAAY,MAAA,KAAW,GAAG,OAAO,MAAA;AACpE,EAAA,OAAO;AAAA,IACL,EAAA,EAAI,KAAA;AAAA,IACJ,KAAA,EAAO,EAAE,IAAA,EAAM,yBAAA,EAA2B,SAAS,yCAAA;AAA0C,GAC/F;AACF;ACVO,IAAM,mBAAA,GAAsB,GAAA;AACnC,IAAM,kBAAA,GAAqB,IAAA;AAC3B,IAAM,UAAA,GAAa;AAAA,EACjB,UAAA,EAAY,CAAC,MAAA,EAAQ,IAAI,CAAA;AAAA,EACzB,UAAA,EAAY,QAAA;AAAA,EACZ,YAAA,EAAc,MAAA;AAAA,EACd,aAAA,EAAe;AACjB,CAAA;AAaO,SAAS,gBAAgB,IAAA,EAAwB;AACtD,EAAA,OAAO,UAAU,IAAA,EAAM;AAAA,IACrB,KAAA,EAAO,mBAAA;AAAA,IACP,SAAA,EAAW,kBAAA;AAAA,IACX,GAAG;AAAA,GACJ,CAAA;AACH;AASO,SAAS,uBAAuB,IAAA,EAAwB;AAC7D,EAAA,OAAO,UAAU,IAAA,EAAM;AAAA,IACrB,OAAO,mBAAA,GAAsB,CAAA;AAAA,IAC7B,WAAW,kBAAA,GAAqB,CAAA;AAAA,IAChC,GAAG;AAAA,GACJ,CAAA;AACH;;;ACDO,IAAM,uBAAA,GAA4D;AAAA,EACvE,iBAAA,CAAkB,MAAA;AAAA,EAClB,iBAAA,CAAkB,aAAA;AAAA,EAClB,iBAAA,CAAkB,cAAA;AAAA,EAClB,iBAAA,CAAkB,cAAA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CAAc,OAAA,EAAQ,EAAE;AAClF;AAaA,SAAS,eAAe,GAAA,EAAgC;AACtD,EAAA,OAAO,gBAAgB,GAAA,CAAI,IAAI,CAAA,CAAE,OAAA,CAAQ,CAAC,IAAA,KAAS;AACjD,IAAA,MAAM,IAAA,GAAO,OAAA,CAAQ,GAAA,CAAI,MAAA,EAAQ,IAAI,CAAA;AACrC,IAAA,IAAI,IAAA,CAAK,MAAA,IAAU,mBAAA,EAAqB,OAAO,CAAC,IAAI,CAAA;AACpD,IAAA,OAAO,sBAAA,CAAuB,IAAI,CAAA,CAAE,GAAA,CAAI,CAAC,SAAS,OAAA,CAAQ,GAAA,CAAI,MAAA,EAAQ,IAAI,CAAC,CAAA;AAAA,EAC7E,CAAC,CAAA;AACH;AASA,SAAS,OAAA,CAAQ,QAAmC,IAAA,EAAsB;AACxE,EAAA,OAAO,MAAA,KAAW,OAAA,GAAU,cAAA,CAAe,IAAI,CAAA,GAAI,IAAA;AACrD;AAaA,SAAS,eAAe,IAAA,EAAsB;AAM5C,EAAA,OAAO,IAAA,CAAK,OAAA,CAAQ,aAAA,EAAe,MAAM,CAAA;AAC3C","file":"index.js","sourcesContent":["/**\n * The refusal this adapter answers for an outbound that carries attachments (B-674).\n *\n * This adapter sends text only, so an outbound carrying attachments is refused rather than sent without its images.\n *\n * The check runs before any other, so a refusal makes no platform call. It lives in this package\n * rather than in `@theokit/gateway` so that the adapter calls nothing its declared core floor\n * lacks; only the `OutboundMessage` type is imported.\n */\n\nimport type { OutboundMessage, SendResult } from \"@theokit/gateway\";\n\n/**\n * `attachments_unsupported` when `out` carries attachments, otherwise `undefined`.\n *\n * Absent, `null` and an empty list carry nothing. `!== 0`, not `> 0`: any other non-array value\n * from a JavaScript caller has no numeric length and is refused rather than taken for an empty\n * list (EC-1).\n */\nexport function refuseAttachments(out: OutboundMessage): SendResult | undefined {\n if (out.attachments == null || out.attachments.length === 0) return undefined;\n return {\n ok: false,\n error: { code: \"attachments_unsupported\", message: \"discord adapter cannot send attachments\" },\n };\n}\n","/**\n * Discord's 2000-char per-message hard limit. Split agent responses on safe\n * boundaries before sending (T6.1).\n *\n * Thin wrapper over core `chunkText` (roadmap M1). Telegram family (minus\n * markdown balancing): 2000 hard cap, 1900 soft window, `\\n\\n` → `\\n` → window\n * boundary preference, newline-only leading strip, no surrogate guard. Output\n * is byte-identical to the previous implementation (pinned by\n * `tests/split.test.ts`).\n *\n * @internal\n */\n\nimport { chunkText } from \"@theokit/gateway\";\n\nexport const DISCORD_MAX_MESSAGE = 2000;\nconst SAFE_DISCORD_CHUNK = 1900;\nconst BOUNDARIES = {\n boundaries: [\"\\n\\n\", \"\\n\"],\n lastResort: \"window\",\n stripLeading: /^\\n+/,\n keepTableRows: true,\n} as const;\n\n/**\n * Split `text` into chunks Discord accepts as separate messages.\n *\n * Each chunk is at most {@link DISCORD_MAX_MESSAGE} characters. The cut prefers\n * a blank line, then a newline, inside a 1900-character window, and falls back\n * to the window edge when the text has neither.\n *\n * @param text - The full outbound reply.\n * @returns The chunks in order; sending them one after another reproduces `text`\n * minus the leading newlines stripped at each cut.\n */\nexport function splitForDiscord(text: string): string[] {\n return chunkText(text, {\n limit: DISCORD_MAX_MESSAGE,\n safeLimit: SAFE_DISCORD_CHUNK,\n ...BOUNDARIES,\n });\n}\n\n/**\n * Split a text that is escaped after the split, at half the cap.\n *\n * Escaping adds at most one backslash per character, so a part of at most 1000 characters fits\n * one message once escaped. The adapter calls this only for a part whose escaped body passed the\n * cap, so the parts of an ordinary text are the ones `splitForDiscord` returns.\n */\nexport function splitForEscapedDiscord(text: string): string[] {\n return chunkText(text, {\n limit: DISCORD_MAX_MESSAGE / 2,\n safeLimit: SAFE_DISCORD_CHUNK / 2,\n ...BOUNDARIES,\n });\n}\n","/**\n * `DiscordAdapter` — wraps discord.js in the `@theokit/gateway`\n * `BasePlatformAdapter` contract (T6.1, ADRs D171, D179).\n *\n * - `connect()` calls `client.login(token)` and awaits the `ready` event.\n * - WebSocket Gateway only (D179) — no webhook variant in v0.1.\n * - Default intents include `MessageContent` (EC-C silent-failure guard).\n * - Bot-to-bot messages ignored at adapter level (`msg.author.bot`).\n * - 2000-char message split (Discord's hard limit).\n *\n * @public\n */\n\nimport type { DiscordMessageEvent, MessageEvent as GatewayMessageEvent } from \"@theokit/gateway\";\nimport { BasePlatformAdapter, type OutboundMessage, type SendResult } from \"@theokit/gateway\";\nimport {\n Client,\n DiscordAPIError,\n Events,\n GatewayIntentBits,\n type Message,\n Routes,\n} from \"discord.js\";\nimport { refuseAttachments } from \"./refuse-attachments.js\";\nimport { DISCORD_MAX_MESSAGE, splitForDiscord, splitForEscapedDiscord } from \"./split.js\";\n\nexport interface DiscordAdapterOptions {\n /**\n * The Discord bot token.\n *\n * @platform-term Discord calls this a **bot token** and `discord.js` names the field `token`, so\n * the name here is theirs.\n * @issued-at The Discord Developer Portal, under the application's Bot tab.\n */\n readonly token: string;\n /**\n * Default: [Guilds, GuildMessages, MessageContent, DirectMessages,\n * DirectMessageReactions]. Without MessageContent the bot receives\n * empty `msg.content` (EC-C silent failure).\n */\n readonly intents?: GatewayIntentBits[];\n /**\n * Deliver a guild or thread message only when it mentions the bot. Default `true`.\n *\n * A mention is the bot's user id in the message's `mentions.users`: a direct `<@id>`, and a\n * reply that pings the bot (Discord lists the pinged author there; a reply with the ping off is\n * not a mention). `@everyone`, `@here` and role mentions do not count. An event with no\n * discord.js mentions collection (one built by hand for `deliver()`) is read for `<@id>` or\n * `<@!id>` in its text. A DM is always delivered. Until the client is ready the bot id is\n * unknown, so every group message is dropped and one stderr line says why. Pass `false` to\n * deliver every message, as the adapter did before this option existed.\n */\n readonly requireMention?: boolean;\n}\n\nexport const DEFAULT_DISCORD_INTENTS: ReadonlyArray<GatewayIntentBits> = [\n GatewayIntentBits.Guilds,\n GatewayIntentBits.GuildMessages,\n GatewayIntentBits.MessageContent,\n GatewayIntentBits.DirectMessages,\n GatewayIntentBits.DirectMessageReactions,\n];\n\n/**\n * Discord gateway adapter — holds a websocket the bot opens, so inbound needs no public URL.\n *\n * Reading message CONTENT requires the privileged `MessageContent` intent, which must be enabled in\n * the Discord developer portal as well as requested here; without it every `event.text` arrives\n * empty and nothing in the API says why. `DEFAULT_DISCORD_INTENTS` requests it.\n */\nexport class DiscordAdapter extends BasePlatformAdapter {\n readonly platform = \"discord\" as const;\n private readonly client: Client;\n private readonly token: string;\n private handler?: (event: GatewayMessageEvent) => Promise<void>;\n private connected = false;\n private readonly requireMention: boolean;\n private warnedMissingBotId = false;\n\n constructor(opts: DiscordAdapterOptions) {\n super();\n this.token = opts.token;\n this.requireMention = opts.requireMention ?? true;\n const intents = (opts.intents ?? DEFAULT_DISCORD_INTENTS) as GatewayIntentBits[];\n if (intents.length === 0) {\n process.stderr.write(\n \"[discord] WARN — intents:[] passed; bot will not receive message content. Pass at least [Guilds, GuildMessages, MessageContent] (EC-C).\\n\",\n );\n }\n this.client = new Client({ intents });\n this.client.on(Events.MessageCreate, async (msg) => this.handleInbound(msg));\n this.client.on(Events.Error, (err) => {\n process.stderr.write(`[discord] client error: ${err.message}\\n`);\n });\n }\n\n override async connect(): Promise<boolean> {\n if (this.connected) return true;\n try {\n await new Promise<void>((resolve, reject) => {\n this.client.once(Events.ClientReady, () => resolve());\n this.client.login(this.token).catch(reject);\n });\n this.connected = true;\n return true;\n } catch (err) {\n process.stderr.write(`[discord] connect failed: ${(err as Error).message}\\n`);\n return false;\n }\n }\n\n override async disconnect(): Promise<void> {\n if (!this.connected) return;\n this.connected = false;\n try {\n await this.client.destroy();\n } catch {\n /* ignore */\n }\n }\n\n /**\n * Expose the underlying discord.js `Client` so consumers can register\n * platform-specific events that don't fit the portable contract —\n * `interactionCreate` (slash commands via Application Commands),\n * `error` event boundary, presence updates, etc. Register BEFORE\n * calling `runner.start()`.\n *\n * @public\n */\n getBot(): Client {\n return this.client;\n }\n\n override async sendMessage(out: OutboundMessage): Promise<SendResult> {\n return refuseAttachments(out) ?? this.sendText(out);\n }\n\n private async sendText(out: OutboundMessage): Promise<SendResult> {\n if (out.text.length === 0) {\n return { ok: false, error: { code: \"empty_text\", message: \"text is empty\" } };\n }\n let channel: unknown;\n try {\n channel = await this.client.channels.fetch(out.channel.id);\n } catch (err) {\n return {\n ok: false,\n error: { code: \"channel_fetch_failed\", message: (err as Error).message },\n };\n }\n const sendable = channel as {\n send?: (input: { content: string; reply?: unknown }) => Promise<Message>;\n };\n if (sendable === null || typeof sendable.send !== \"function\") {\n return {\n ok: false,\n error: {\n code: \"channel_not_sendable\",\n message: `channel \"${out.channel.id}\" not text-based or missing`,\n },\n };\n }\n const chunks = renderMessages(out);\n let lastId: string | undefined;\n for (const chunk of chunks) {\n try {\n const msg = await sendable.send({\n content: chunk,\n ...(out.replyTo !== undefined ? { reply: { messageReference: out.replyTo } } : {}),\n });\n lastId = msg.id;\n } catch (err) {\n return mapSendError(err);\n }\n }\n return { ok: true, ...(lastId !== undefined ? { messageId: lastId } : {}) };\n }\n\n /** Discord edits a sent message's text with one REST call. */\n override readonly supportsEdit = true;\n\n /**\n * Replace the text of a message this bot sent, with one `PATCH /channels/{id}/messages/{id}`.\n *\n * That PATCH is the request `channel.messages.edit` makes. It is sent through `client.rest`\n * without fetching the channel first, so a success is one request whatever the channel cache\n * holds; an unknown channel is answered by Discord itself (`discord_10003`). The text is split\n * and escaped by the same `renderMessages` that `sendMessage` uses, and a text a send would\n * deliver as more than one message is refused as `edit_too_long` with no request.\n */\n override async editMessage(messageId: string, out: OutboundMessage): Promise<SendResult> {\n return refuseAttachments(out) ?? this.editText(messageId, out);\n }\n\n private async editText(messageId: string, out: OutboundMessage): Promise<SendResult> {\n if (out.text.length === 0) {\n return { ok: false, error: { code: \"empty_text\", message: \"text is empty\" } };\n }\n if (messageId.length === 0) {\n return { ok: false, error: { code: \"invalid_message_id\", message: \"message id is empty\" } };\n }\n const messages = renderMessages(out);\n if (messages.length !== 1) return editPartsRefusal(messages.length);\n const content = messages[0] as string;\n try {\n await this.client.rest.patch(Routes.channelMessage(out.channel.id, messageId), {\n body: { content },\n });\n } catch (err) {\n return mapSendError(err);\n }\n return { ok: true, messageId };\n }\n\n override onInbound(handler: (event: GatewayMessageEvent) => Promise<void>): () => void {\n // EC-H: replace previous handler.\n this.handler = handler;\n return () => {\n if (this.handler === handler) this.handler = undefined;\n };\n }\n\n private async handleInbound(msg: Message): Promise<void> {\n if (this.handler === undefined) return;\n if (msg.author.bot) return;\n const event = normalizeEvent(msg);\n if (!this.passesMentionGate(event)) return;\n await this.dispatchEvent(event);\n }\n\n /**\n * Whether an event may reach the handler: always for a DM or with `requireMention` off,\n * otherwise only when the message mentions the bot. Both `deliver()` and the socket path call\n * it, so the two entries cannot disagree.\n */\n private passesMentionGate(event: GatewayMessageEvent): boolean {\n if (event.channel.type === \"dm\" || !this.requireMention) return true;\n const botId = this.client.user?.id;\n if (botId === undefined) {\n this.warnMissingBotIdOnce();\n return false;\n }\n const raw = event.platform === \"discord\" ? event.discord.raw : undefined;\n const mentionedUsers = (raw as { mentions?: { users?: { has?: unknown } } } | undefined)\n ?.mentions?.users;\n if (typeof mentionedUsers?.has === \"function\") return mentionedUsers.has(botId) === true;\n // A hand-built event carries no discord.js collection; the mention syntax is the evidence left.\n return event.text.includes(`<@${botId}>`) || event.text.includes(`<@!${botId}>`);\n }\n\n private warnMissingBotIdOnce(): void {\n if (this.warnedMissingBotId) return;\n this.warnedMissingBotId = true;\n process.stderr.write(\n \"[discord] dropping every group message: requireMention is on and the bot user id is not known until the client is ready\\n\",\n );\n }\n\n /**\n * Dispatch a pre-built event to the current handler, honouring EC-H replace\n * semantics.\n *\n * Mirrors the seam `gateway-sms` already exposes. It exists because the EC-H\n * contract had no honest test without it: a real `discord.js` Message cannot\n * be synthesized, `handler` is private, and the test that claimed to cover\n * replacement asserted two counters were 0 — true whether onInbound replaces,\n * stacks, or discards. If it had regressed to `handlers.push(handler)`, the\n * agent would have replied twice to every message, double-billing tokens,\n * with the suite green.\n *\n * @internal\n */\n async dispatchEvent(event: GatewayMessageEvent): Promise<\"ok\" | \"no_handler\" | \"handler_threw\"> {\n if (this.handler === undefined) return \"no_handler\";\n try {\n await this.handler(event);\n } catch (err) {\n // Left uncaught, the rejection escaped into the platform's own error channel and was reported\n // as a client error — so a bug in the consumer's handler read as a fault in the platform\n // library, sending whoever debugged it to the wrong repository (#41). A handler is user code:\n // its failure is named as such, and delivery continues.\n const m = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[discord] handler threw: ${m}\\n`);\n return \"handler_threw\";\n }\n return \"ok\";\n }\n\n /**\n * Deliver an event that arrived out of band — the ingest `onInbound` had no counterpart for (#83).\n *\n * The mention gate runs first, as on the socket path: an event it drops answers `\"ok\"`, with or\n * without a handler subscribed. `runHandler` owns the containment: a handler is user code, its\n * throw is named as the handler's failure rather than the platform's, and delivery continues.\n */\n override async deliver(\n event: GatewayMessageEvent,\n ): Promise<\"ok\" | \"no_handler\" | \"handler_threw\"> {\n if (!this.passesMentionGate(event)) return \"ok\";\n return this.runHandler(this.handler, event);\n }\n}\n\nfunction normalizeEvent(msg: Message): DiscordMessageEvent {\n let channelType: \"dm\" | \"group\" | \"thread\";\n if (msg.guildId === null) {\n channelType = \"dm\";\n } else if (msg.channel.isThread()) {\n channelType = \"thread\";\n } else {\n channelType = \"group\";\n }\n\n const displayName = msg.author.globalName !== null ? msg.author.globalName : msg.author.username;\n\n return {\n id: `dc-${msg.channelId}-${msg.id}`,\n platform: \"discord\",\n sender: {\n id: msg.author.id,\n username: msg.author.username,\n displayName,\n },\n channel: {\n id: msg.channelId,\n type: channelType,\n ...(msg.channel.isThread() ? { topicId: msg.channel.id } : {}),\n },\n text: msg.content,\n receivedAt: msg.createdTimestamp,\n ...(msg.reference?.messageId !== undefined ? { replyTo: msg.reference.messageId } : {}),\n discord: {\n guildId: msg.guildId,\n channelId: msg.channelId,\n messageId: msg.id,\n raw: msg,\n },\n };\n}\n\n/**\n * The refusal for a text that is not exactly one Discord message.\n *\n * More than one part is `edit_too_long`. No parts cannot happen today, since `splitForDiscord`\n * returns at least one part for any non-empty text and empty text is refused earlier; the arm\n * keeps a later splitter that returns `[]` from editing with `undefined`.\n */\nfunction editPartsRefusal(partCount: number): SendResult {\n if (partCount > 1) {\n return {\n ok: false,\n error: {\n code: \"edit_too_long\",\n message: `text needs ${partCount} Discord messages; an edit replaces one`,\n },\n };\n }\n return { ok: false, error: { code: \"empty_text\", message: \"text reduced to zero parts\" } };\n}\n\nfunction mapSendError(err: unknown): SendResult {\n if (err instanceof DiscordAPIError) {\n const codeStr = String(err.code);\n if (codeStr === \"50007\") {\n return { ok: false, error: { code: \"dm_blocked\", message: err.message } };\n }\n if (codeStr === \"50001\" || codeStr === \"50013\") {\n return { ok: false, error: { code: \"no_permission\", message: err.message } };\n }\n if (err.status === 429) {\n return { ok: false, error: { code: \"rate_limited\", message: err.message } };\n }\n return { ok: false, error: { code: `discord_${codeStr}`, message: err.message } };\n }\n return { ok: false, error: { code: \"unknown\", message: (err as Error).message } };\n}\n\n/**\n * The message bodies a text goes out as, each within `DISCORD_MAX_MESSAGE`.\n *\n * Split FIRST, escape each part. The other order lets the splitter's hard window cut land between\n * a backslash and the character it guards: message 1 ends in a stray backslash the user never\n * typed, and message 2 opens with a bare `*` that Discord parses as markup. Demonstrated in review\n * against the real splitter. The splitter measures the caller's text, and escaping a `plain` part\n * can double it, so a part whose body passes the cap is split again at half the cap, which every\n * escaped body fits. `sendMessage` and `editMessage` both send what this returns, so an edit is\n * refused for exactly the texts a send delivers as more than one message.\n */\nfunction renderMessages(out: OutboundMessage): string[] {\n return splitForDiscord(out.text).flatMap((part) => {\n const body = bodyFor(out.format, part);\n if (body.length <= DISCORD_MAX_MESSAGE) return [body];\n return splitForEscapedDiscord(part).map((half) => bodyFor(out.format, half));\n });\n}\n\n/**\n * The text to send, with the caller's declared format applied.\n *\n * Discord parses markdown natively, so `markdown` needs no flag. `plain` is the caller stating\n * the text is NOT markup, and sending it raw would parse it anyway — a user's literal\n * `*asterisks*` arriving as italic.\n */\nfunction bodyFor(format: OutboundMessage[\"format\"], text: string): string {\n return format === \"plain\" ? escapeMarkdown(text) : text;\n}\n\n/**\n * Escape the characters this platform would otherwise parse as markup.\n *\n * Called only when the caller declared `format: \"plain\"` — an explicit statement that the text\n * is NOT markup. Without it, a user's literal `*asterisks*` render as italic on a platform that\n * parses markdown natively, which is the caller's intent being silently inverted.\n *\n * Deliberately narrow: the four characters that open an inline span. A full markdown escaper\n * would also touch `#`, `>` and `-` at line starts, which are far more common in ordinary prose\n * and whose escaping is more visible than the problem it solves.\n */\nfunction escapeMarkdown(text: string): string {\n // The backslash comes FIRST, and that ordering is the whole correctness of this function.\n // Without it a backslash already in the caller's text is left bare: `a\\*b` escapes to `a\\\\*b`,\n // the renderer consumes `\\\\` as one literal backslash, and the `*` it was guarding is left\n // naked — so text sent explicitly as `plain` arrives italicised, the exact inversion this\n // function exists to prevent. Caught in review.\n return text.replace(/([\\\\*_`~])/g, \"\\\\$1\");\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@theokit/gateway-discord",
3
- "version": "0.3.0",
3
+ "version": "0.5.0",
4
4
  "description": "Discord (discord.js) platform adapter for @theokit/gateway. ADRs D171, D179.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -48,7 +48,7 @@
48
48
  "typescript": "5.9.3",
49
49
  "vitest": "^4.1.11",
50
50
  "zod": "^4.0.0",
51
- "@theokit/gateway": "0.10.0"
51
+ "@theokit/gateway": "0.14.0"
52
52
  },
53
53
  "publishConfig": {
54
54
  "access": "public",