@aiwg/cli 2026.10.14 → 2026.10.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (210) hide show
  1. package/agentic/code/addons/aiwg-utils/rules/anti-laziness.core.md +13 -0
  2. package/agentic/code/addons/aiwg-utils/rules/anti-laziness.md +118 -0
  3. package/agentic/code/providers/pi/aiwg-bridge.ts +45 -7
  4. package/dist/src/artifacts/citation-parser.js +7 -6
  5. package/dist/src/artifacts/corpus-tools/citation-densify.js +4 -2
  6. package/dist/src/artifacts/corpus-tools/cli.js +37 -0
  7. package/dist/src/artifacts/corpus-tools/discovery-log.js +27 -25
  8. package/dist/src/artifacts/corpus-tools/expand-cli.js +90 -0
  9. package/dist/src/artifacts/corpus-tools/expand-dates.js +107 -0
  10. package/dist/src/artifacts/corpus-tools/expand-queue.js +41 -0
  11. package/dist/src/artifacts/corpus-tools/expand-review.js +104 -0
  12. package/dist/src/artifacts/corpus-tools/expand-state.js +56 -0
  13. package/dist/src/artifacts/corpus-tools/expand.js +124 -0
  14. package/dist/src/artifacts/corpus-tools/induction-audit.js +7 -6
  15. package/dist/src/artifacts/corpus-tools/integrity-scan.js +3 -3
  16. package/dist/src/artifacts/corpus-tools/radar-shared.js +7 -9
  17. package/dist/src/artifacts/corpus-tools/ref-files.js +11 -0
  18. package/dist/src/artifacts/corpus-tools/resolve-cli.js +99 -0
  19. package/dist/src/artifacts/corpus-tools/resolve-corpus.js +41 -0
  20. package/dist/src/artifacts/corpus-tools/resolve.js +119 -0
  21. package/dist/src/artifacts/corpus-tools/retrieval-lab.js +2 -1
  22. package/dist/src/artifacts/corpus-tools/sidecar-lint.js +4 -4
  23. package/dist/src/artifacts/corpus-tools/sidecar-repair.js +2 -1
  24. package/dist/src/artifacts/corpus-views/ref-parser.js +3 -17
  25. package/dist/src/artifacts/graph-query.js +5 -3
  26. package/dist/src/artifacts/hybrid-query.js +11 -2
  27. package/dist/src/artifacts/index-refresh.js +2 -0
  28. package/dist/src/cli/handlers/daemon.js +17 -1
  29. package/dist/src/cli/handlers/doctor-args.js +45 -0
  30. package/dist/src/cli/handlers/doctor-help.js +8 -3
  31. package/dist/src/cli/handlers/index.js +2 -2
  32. package/dist/src/cli/handlers/models-resource-sample.js +10 -0
  33. package/dist/src/cli/handlers/models.js +3 -2
  34. package/dist/src/cli/handlers/regenerate.js +8 -16
  35. package/dist/src/cli/handlers/sessions.js +7 -7
  36. package/dist/src/cli/handlers/subcommands.js +8 -0
  37. package/dist/src/cli/handlers/update.js +157 -0
  38. package/dist/src/cli/handlers/use.js +14 -4
  39. package/dist/src/cli/handlers/utilities.js +3 -586
  40. package/dist/src/cli/handlers/utility-doctor.js +412 -0
  41. package/dist/src/cli/services/deployment-verification.js +0 -1
  42. package/dist/src/config/aiwg-config.js +2 -1
  43. package/dist/src/config/authorization-cli.js +7 -3
  44. package/dist/src/config/dispatch-thresholds-runtime.d.mts +3 -2
  45. package/dist/src/config/dispatch-thresholds-runtime.mjs +17 -7
  46. package/dist/src/config/framework-aliases.js +12 -0
  47. package/dist/src/config/host-resource-report.d.mts +19 -0
  48. package/dist/src/config/host-resource-report.mjs +80 -0
  49. package/dist/src/config/host-resource-runtime.d.mts +34 -0
  50. package/dist/src/config/host-resource-runtime.mjs +293 -0
  51. package/dist/src/config/installed-selection.js +22 -0
  52. package/dist/src/config/worker-context.js +33 -4
  53. package/dist/src/config/worker-invocation-marker.d.mts +1 -0
  54. package/dist/src/config/worker-invocation-marker.mjs +2 -0
  55. package/dist/src/decision/heldout/access.js +74 -0
  56. package/dist/src/decision/heldout/calibration.js +1 -0
  57. package/dist/src/decision/heldout/collector.js +9 -2
  58. package/dist/src/effects/verifiers/file.js +22 -5
  59. package/dist/src/extensions/claude-attribution.js +82 -0
  60. package/dist/src/extensions/claude-hooks-installer.js +115 -69
  61. package/dist/src/extensions/commands/daemon.js +109 -0
  62. package/dist/src/extensions/commands/definitions.js +5 -89
  63. package/dist/src/features/catalog.js +1 -1
  64. package/dist/src/gates/evaluate.js +2 -2
  65. package/dist/src/gates/heldout.js +52 -0
  66. package/dist/src/gates/index.js +2 -1
  67. package/dist/src/lint/check-patterns.js +163 -0
  68. package/dist/src/lint/checks.js +268 -0
  69. package/dist/src/lint/reference-resolution.js +54 -0
  70. package/dist/src/lint/runner.js +3 -465
  71. package/dist/src/mcp/helpers.mjs +11 -1
  72. package/dist/src/memory/project-registry.js +44 -4
  73. package/dist/src/models/worker-installation-store.mjs +228 -0
  74. package/dist/src/models/worker-installation.mjs +7 -162
  75. package/dist/src/models/worker-plan.js +36 -5
  76. package/dist/src/models/wrapper-deployment.js +25 -12
  77. package/dist/src/models/wrapper-enforcement.js +47 -7
  78. package/dist/src/network-analysis/research.js +2 -1
  79. package/dist/src/policy/hitl-check.js +14 -4
  80. package/dist/src/policy/hitl-consume.js +54 -0
  81. package/dist/src/policy/hitl-receipt.js +2 -0
  82. package/dist/src/policy/hitl.js +11 -3
  83. package/dist/src/providers/provider-context-contracts.js +162 -0
  84. package/dist/src/providers/provider-definition-schema.js +136 -0
  85. package/dist/src/providers/provider-definitions.js +8 -1298
  86. package/dist/src/providers/provider-seeds-1.js +360 -0
  87. package/dist/src/providers/provider-seeds-2.js +387 -0
  88. package/dist/src/providers/provider-seeds-3.js +262 -0
  89. package/dist/src/research/clients/arxiv.js +14 -34
  90. package/dist/src/research/clients/base.js +53 -26
  91. package/dist/src/research/clients/crossref.js +9 -1
  92. package/dist/src/research/clients/semantic-scholar.js +73 -44
  93. package/dist/src/research/identity.js +117 -0
  94. package/dist/src/research/index.js +1 -0
  95. package/dist/src/research/query-cli.js +3 -87
  96. package/dist/src/research/query-options.js +87 -0
  97. package/dist/src/research/reference-match.js +135 -0
  98. package/dist/src/research/services/acquisition.js +9 -7
  99. package/dist/src/research/services/citation.js +5 -2
  100. package/dist/src/research/types.js +2 -0
  101. package/dist/src/rules/core-startup.d.mts +2 -0
  102. package/dist/src/rules/core-startup.mjs +31 -0
  103. package/dist/src/serve/mission-conductor.js +48 -4
  104. package/dist/src/sessions/adapters/grok-build-native.js +23 -0
  105. package/dist/src/sessions/adapters/grok-build.js +14 -7
  106. package/dist/src/sessions/workspace-discovery.js +5 -5
  107. package/dist/src/smiths/context-pipeline/agents-md.js +34 -0
  108. package/dist/src/smiths/context-pipeline/aiwg-md.js +19 -46
  109. package/dist/src/smiths/context-pipeline/bridge-ownership.js +50 -0
  110. package/dist/src/smiths/context-pipeline/claude-hook.js +1 -1
  111. package/dist/src/smiths/context-pipeline/code-regions.js +28 -0
  112. package/dist/src/smiths/context-pipeline/finalization.js +81 -51
  113. package/dist/src/smiths/context-pipeline/generator.js +49 -114
  114. package/dist/src/smiths/context-pipeline/managed-hook.js +11 -1
  115. package/dist/src/smiths/context-pipeline/muse-bridge.js +2 -2
  116. package/dist/src/smiths/context-pipeline/provider-policy.js +6 -12
  117. package/dist/src/smiths/context-pipeline/workspace-audit.js +299 -0
  118. package/dist/src/smiths/context-pipeline/workspace-bootstrap.js +148 -0
  119. package/dist/src/smiths/context-pipeline/workspace-context-shared.js +111 -0
  120. package/dist/src/smiths/context-pipeline/workspace-context.js +8 -1373
  121. package/dist/src/smiths/context-pipeline/workspace-doctor.js +192 -0
  122. package/dist/src/smiths/context-pipeline/workspace-document.js +201 -0
  123. package/dist/src/smiths/context-pipeline/workspace-extraction.js +205 -0
  124. package/dist/src/smiths/context-pipeline/workspace-migration.js +250 -0
  125. package/package.json +13 -2
  126. package/schemas/decision/D29Study.v10.schema.json +65 -0
  127. package/tools/agents/deploy-agents.mjs +12 -123
  128. package/tools/agents/providers/antigravity.mjs +1 -1
  129. package/tools/agents/providers/claude-post-deploy.mjs +12 -1
  130. package/tools/agents/providers/context-write.mjs +16 -0
  131. package/tools/agents/providers/grok-build.mjs +8 -5
  132. package/tools/agents/providers/hermes-skill-lifecycle.mjs +144 -0
  133. package/tools/agents/providers/hermes-startup.mjs +209 -0
  134. package/tools/agents/providers/hermes.mjs +9 -359
  135. package/tools/agents/providers/model-wrapper.mjs +5 -1
  136. package/tools/agents/providers/muse.mjs +3 -3
  137. package/tools/agents/providers/pi.mjs +4 -2
  138. package/tools/agents/providers/rule-delivery-surface.mjs +332 -0
  139. package/tools/agents/providers/rule-delivery.mjs +20 -1346
  140. package/tools/agents/providers/rule-deployment-commit.mjs +144 -0
  141. package/tools/agents/providers/rule-deployment-prepare.mjs +452 -0
  142. package/tools/agents/providers/rule-deployment-state.mjs +300 -0
  143. package/tools/agents/providers/rule-presentation.mjs +13 -4
  144. package/tools/agents/providers/rule-projection.mjs +119 -0
  145. package/tools/agents/providers/rule-startup.mjs +70 -0
  146. package/tools/agents/providers/stale-artifact-prune.mjs +128 -0
  147. package/tools/agents/providers/warp.mjs +2 -2
  148. package/tools/agents/providers/windsurf.mjs +11 -57
  149. package/tools/daemon/README.md +511 -0
  150. package/tools/daemon/adapters/base-adapter.mjs +84 -0
  151. package/tools/daemon/adapters/webhook-adapter.mjs +107 -0
  152. package/tools/daemon/agent-supervisor.mjs +299 -0
  153. package/tools/daemon/automation-engine.mjs +310 -0
  154. package/tools/daemon/autonomous-engine.mjs +346 -0
  155. package/tools/daemon/behavior-loader.mjs +316 -0
  156. package/tools/daemon/behavior.mjs +174 -0
  157. package/tools/daemon/concierge/intent-router.mjs +401 -0
  158. package/tools/daemon/concierge/orchestrator.mjs +272 -0
  159. package/tools/daemon/concierge/response-translator.mjs +462 -0
  160. package/tools/daemon/config.mjs +377 -0
  161. package/tools/daemon/cron-scheduler.mjs +178 -0
  162. package/tools/daemon/daemon-main.mjs +1169 -0
  163. package/tools/daemon/event-router.mjs +84 -0
  164. package/tools/daemon/file-watcher.mjs +383 -0
  165. package/tools/daemon/index.mjs +1181 -0
  166. package/tools/daemon/init-profile.mjs +124 -0
  167. package/tools/daemon/ipc-client.mjs +197 -0
  168. package/tools/daemon/ipc-ops-handlers.mjs +236 -0
  169. package/tools/daemon/ipc-server.mjs +275 -0
  170. package/tools/daemon/maintenance-owner.mjs +79 -0
  171. package/tools/daemon/memory-manager.mjs +386 -0
  172. package/tools/daemon/message-router.mjs +194 -0
  173. package/tools/daemon/provider-watcher.mjs +585 -0
  174. package/tools/daemon/pty-adapter.mjs +420 -0
  175. package/tools/daemon/repl-chat.mjs +359 -0
  176. package/tools/daemon/resource-bounds.mjs +88 -0
  177. package/tools/daemon/sandbox-transport.mjs +295 -0
  178. package/tools/daemon/scheduled-task-runner.mjs +535 -0
  179. package/tools/daemon/task-store.mjs +450 -0
  180. package/tools/daemon/tmux-manager.mjs +324 -0
  181. package/tools/daemon/update-policy.mjs +517 -0
  182. package/tools/daemon/web-server.mjs +399 -0
  183. package/tools/daemon/web-ui/index.html +585 -0
  184. package/tools/daemon/web-ui/styles.css +156 -0
  185. package/tools/docker/Dockerfile.daemon +35 -0
  186. package/tools/docker/container-manager.mjs +291 -0
  187. package/tools/messaging/adapter-registry.mjs +230 -0
  188. package/tools/messaging/adapters/base.mjs +326 -0
  189. package/tools/messaging/adapters/discord.mjs +462 -0
  190. package/tools/messaging/adapters/slack.mjs +402 -0
  191. package/tools/messaging/adapters/telegram.mjs +552 -0
  192. package/tools/messaging/chat-handler.mjs +297 -0
  193. package/tools/messaging/command-router.mjs +269 -0
  194. package/tools/messaging/event-bus.mjs +199 -0
  195. package/tools/messaging/index.mjs +456 -0
  196. package/tools/messaging/message-formatter.mjs +320 -0
  197. package/tools/messaging/room-manager.mjs +277 -0
  198. package/tools/messaging/types.mjs +94 -0
  199. package/tools/plugin/plugin-links.mjs +3 -0
  200. package/tools/providers/pi-bridge-policy.mjs +4 -0
  201. package/tools/ralph-external/daemon-supervisor.mjs +394 -0
  202. package/tools/ralph-external/lib/behavior-registry.mjs +270 -0
  203. package/tools/ralph-external/lib/worker-invocation-processes.mjs +3 -2
  204. package/tools/ralph-external/lib/worker-isolation-args.mjs +217 -0
  205. package/tools/ralph-external/lib/worker-isolation-status.mjs +19 -0
  206. package/tools/ralph-external/lib/worker-isolation.mjs +11 -237
  207. package/tools/ralph-external/lib/worker-overflow.mjs +10 -2
  208. package/tools/ralph-external/lib/worker-unit-cleanup.mjs +72 -0
  209. package/tools/ralph-external/session-launcher.mjs +7 -7
  210. package/tools/scripts/resource-preflight.mjs +3 -242
@@ -0,0 +1,462 @@
1
+ /**
2
+ * Discord adapter for AIWG messaging bot.
3
+ *
4
+ * Implements Discord integration using REST API (no discord.js dependency).
5
+ * Uses native fetch() to minimize external dependencies.
6
+ *
7
+ * @implements @.aiwg/architecture/adrs/ADR-messaging-bot-mode.md
8
+ */
9
+
10
+ import { BaseAdapter } from './base.mjs';
11
+ import { getSeverityColor } from '../message-formatter.mjs';
12
+
13
+ /**
14
+ * Discord severity colors (decimal format for embeds)
15
+ */
16
+ const DISCORD_COLORS = {
17
+ info: 0x36a64f, // Green
18
+ warning: 0xdaa520, // Goldenrod
19
+ critical: 0xdc3545, // Red
20
+ };
21
+
22
+ /**
23
+ * Discord API base URL (v10)
24
+ */
25
+ const DISCORD_API_BASE = 'https://discord.com/api/v10';
26
+
27
+ /**
28
+ * @typedef {Object} DiscordRoomConfig
29
+ * @property {string} channel_id - Discord channel ID (also accepts channelId)
30
+ * @property {string} [label] - Human-readable name for this channel
31
+ * @property {boolean} [is_default] - Whether this channel receives broadcast messages (also accepts isDefault)
32
+ * @property {string} [purpose] - "interactive" | "notifications" | "logs"
33
+ */
34
+
35
+ /**
36
+ * @typedef {Object} DiscordConfig
37
+ * @property {string} [botToken] - Discord bot token
38
+ * @property {string} [defaultChannelId] - Default channel ID (single-channel fallback)
39
+ * @property {string} [guildId] - Discord guild (server) ID
40
+ * @property {DiscordRoomConfig[]} [rooms] - Multi-channel configuration
41
+ */
42
+
43
+ /**
44
+ * Discord adapter implementation.
45
+ *
46
+ * Configuration:
47
+ * - botToken: Discord bot token
48
+ * - defaultChannelId: Default channel for messages (single-channel mode)
49
+ * - guildId: Discord guild (server) ID
50
+ * - rooms: Array of channel configs for multi-channel mode
51
+ *
52
+ * Environment variables:
53
+ * - AIWG_DISCORD_TOKEN: Bot token (fallback)
54
+ * - AIWG_DISCORD_CHANNEL_ID: Default channel (fallback)
55
+ * - AIWG_DISCORD_GUILD_ID: Guild ID (fallback)
56
+ */
57
+ export class DiscordAdapter extends BaseAdapter {
58
+ /** @type {string} */
59
+ #botToken;
60
+
61
+ /** @type {string} */
62
+ #defaultChannelId;
63
+
64
+ /** @type {string} */
65
+ #guildId;
66
+
67
+ /** @type {Map<string, string>} Thread ID to channel ID mapping */
68
+ #threadChannels = new Map();
69
+
70
+ /** @type {Map<string, number>} Rate limit tracking per channel */
71
+ #rateLimits = new Map();
72
+
73
+ /**
74
+ * Create a Discord adapter.
75
+ *
76
+ * @param {DiscordConfig} config
77
+ */
78
+ constructor(config = {}) {
79
+ super('discord');
80
+
81
+ this.#botToken = config.botToken || process.env.AIWG_DISCORD_TOKEN;
82
+ this._setSensitiveValues(this.#botToken);
83
+ this.#defaultChannelId = config.defaultChannelId || process.env.AIWG_DISCORD_CHANNEL_ID;
84
+ this.#guildId = config.guildId || process.env.AIWG_DISCORD_GUILD_ID;
85
+
86
+ if (!this.#botToken) {
87
+ throw new Error('Discord bot token required (config.botToken or AIWG_DISCORD_TOKEN)');
88
+ }
89
+
90
+ // Multi-room: register rooms from config, or use defaultChannelId as single room
91
+ if (Array.isArray(config.rooms) && config.rooms.length > 0) {
92
+ for (const room of config.rooms) {
93
+ const channelId = room.channel_id || room.channelId;
94
+ if (channelId) {
95
+ this.addRoom(channelId, {
96
+ label: room.label || room.name || channelId,
97
+ isDefault: room.is_default ?? room.isDefault ?? false,
98
+ purpose: room.purpose || 'interactive',
99
+ });
100
+ }
101
+ }
102
+ // Use first default room or first room as the fallback defaultChannelId
103
+ if (!this.#defaultChannelId) {
104
+ const defaultRoom = config.rooms.find(r => r.is_default || r.isDefault) || config.rooms[0];
105
+ this._setSensitiveValues(this.#botToken);
106
+ this.#defaultChannelId = defaultRoom.channel_id || defaultRoom.channelId;
107
+ }
108
+ }
109
+
110
+ if (!this.#defaultChannelId && this.getRooms().size === 0) {
111
+ throw new Error('Discord requires at least one channel ID (config.defaultChannelId, config.rooms, or AIWG_DISCORD_CHANNEL_ID)');
112
+ }
113
+
114
+ // If we have a defaultChannelId but no rooms registered, auto-create a single room
115
+ if (this.#defaultChannelId && this.getRooms().size === 0) {
116
+ this.addRoom(this.#defaultChannelId, {
117
+ label: 'default',
118
+ isDefault: true,
119
+ purpose: 'interactive',
120
+ });
121
+ }
122
+ }
123
+
124
+ /**
125
+ * Initialize Discord connection by validating bot token.
126
+ *
127
+ * @returns {Promise<void>}
128
+ */
129
+ async initialize() {
130
+ try {
131
+ // Validate token by fetching bot user info
132
+ const response = await this.#apiRequest('GET', '/users/@me');
133
+
134
+ if (!response.ok) {
135
+ const error = await response.json().catch(() => ({ message: 'Unknown error' }));
136
+ throw new Error(`Discord authentication failed: ${error.message || response.statusText}`);
137
+ }
138
+
139
+ const botUser = await response.json();
140
+ console.log(this._redactText(`[discord] Connected as ${botUser.username}#${botUser.discriminator}`));
141
+
142
+ this._setConnected();
143
+ } catch (error) {
144
+ error = this._redactError(error);
145
+ this._recordError(error);
146
+ throw new Error(`Discord initialization failed: ${error.message}`);
147
+ }
148
+ }
149
+
150
+ /**
151
+ * Shutdown Discord connection.
152
+ *
153
+ * @returns {Promise<void>}
154
+ */
155
+ async shutdown() {
156
+ this._setDisconnected();
157
+ this.#threadChannels.clear();
158
+ this.#rateLimits.clear();
159
+ console.log('[discord] Disconnected');
160
+ }
161
+
162
+ /**
163
+ * Send a message to a Discord channel.
164
+ *
165
+ * @param {import('../message-formatter.mjs').AiwgMessage} message
166
+ * @param {string} [channel] - Channel ID (defaults to config channel)
167
+ * @returns {Promise<import('./base.mjs').MessageResult>}
168
+ */
169
+ async send(message, channel) {
170
+ const channelId = channel || this.#defaultChannelId;
171
+
172
+ try {
173
+ // Check rate limit
174
+ await this.#waitForRateLimit(channelId);
175
+
176
+ const payload = this.#buildMessagePayload(message);
177
+
178
+ const response = await this.#apiRequest(
179
+ 'POST',
180
+ `/channels/${channelId}/messages`,
181
+ payload
182
+ );
183
+
184
+ if (!response.ok) {
185
+ const error = await response.json().catch(() => ({ message: 'Unknown error' }));
186
+ throw new Error(`Discord API error: ${error.message || response.statusText}`);
187
+ }
188
+
189
+ const sentMessage = await response.json();
190
+
191
+ // If message has threadId, create or use existing thread
192
+ if (message.threadId) {
193
+ await this.#ensureThread(channelId, sentMessage.id, message.threadId, message.title);
194
+ }
195
+
196
+ this._recordSend();
197
+
198
+ return {
199
+ messageId: sentMessage.id,
200
+ channelId: channelId,
201
+ success: true,
202
+ };
203
+ } catch (error) {
204
+ error = this._redactError(error);
205
+ this._recordError(error);
206
+ return {
207
+ messageId: '',
208
+ channelId: channelId,
209
+ success: false,
210
+ error: error.message,
211
+ };
212
+ }
213
+ }
214
+
215
+ /**
216
+ * Update an existing Discord message.
217
+ *
218
+ * @param {string} messageId
219
+ * @param {import('../message-formatter.mjs').AiwgMessage} message
220
+ * @returns {Promise<void>}
221
+ */
222
+ async update(messageId, message) {
223
+ try {
224
+ // Parse messageId which may be "channelId/messageId"
225
+ const [channelId, msgId] = messageId.includes('/')
226
+ ? messageId.split('/')
227
+ : [this.#defaultChannelId, messageId];
228
+
229
+ await this.#waitForRateLimit(channelId);
230
+
231
+ const payload = this.#buildMessagePayload(message);
232
+
233
+ const response = await this.#apiRequest(
234
+ 'PATCH',
235
+ `/channels/${channelId}/messages/${msgId}`,
236
+ payload
237
+ );
238
+
239
+ if (!response.ok) {
240
+ const error = await response.json().catch(() => ({ message: 'Unknown error' }));
241
+ throw new Error(`Discord update failed: ${error.message || response.statusText}`);
242
+ }
243
+
244
+ this._recordSend();
245
+ } catch (error) {
246
+ error = this._redactError(error);
247
+ this._recordError(error);
248
+ throw error;
249
+ }
250
+ }
251
+
252
+ /**
253
+ * Build Discord message payload from AiwgMessage.
254
+ *
255
+ * @param {import('../message-formatter.mjs').AiwgMessage} message
256
+ * @returns {Object}
257
+ */
258
+ #buildMessagePayload(message) {
259
+ const embed = {
260
+ title: message.title,
261
+ description: message.body,
262
+ color: DISCORD_COLORS[message.severity] || DISCORD_COLORS.info,
263
+ fields: message.fields.map((field) => ({
264
+ name: field.label,
265
+ value: field.value || '\u200b', // Zero-width space for empty
266
+ inline: field.inline ?? false,
267
+ })),
268
+ footer: {
269
+ text: `${message.project} • ${new Date(message.timestamp).toLocaleString()}`,
270
+ },
271
+ timestamp: message.timestamp,
272
+ };
273
+
274
+ // Add code block if present
275
+ if (message.codeBlock) {
276
+ embed.fields.push({
277
+ name: 'Details',
278
+ value: `\`\`\`\n${message.codeBlock.slice(0, 1000)}\n\`\`\``,
279
+ inline: false,
280
+ });
281
+ }
282
+
283
+ // Add link if present
284
+ if (message.linkUrl && message.linkText) {
285
+ embed.fields.push({
286
+ name: message.linkText,
287
+ value: message.linkUrl,
288
+ inline: false,
289
+ });
290
+ }
291
+
292
+ const payload = {
293
+ embeds: [embed],
294
+ };
295
+
296
+ // Add components (buttons) if actions present
297
+ if (message.actions && message.actions.length > 0) {
298
+ payload.components = [
299
+ {
300
+ type: 1, // Action Row
301
+ components: message.actions.slice(0, 5).map((action) => ({
302
+ type: 2, // Button
303
+ custom_id: action.id,
304
+ label: action.label,
305
+ style: this.#mapButtonStyle(action.style),
306
+ })),
307
+ },
308
+ ];
309
+ }
310
+
311
+ return payload;
312
+ }
313
+
314
+ /**
315
+ * Map AIWG button style to Discord button style.
316
+ *
317
+ * @param {string} style
318
+ * @returns {number}
319
+ */
320
+ #mapButtonStyle(style) {
321
+ const BUTTON_STYLES = {
322
+ primary: 1, // Blurple
323
+ secondary: 2, // Grey
324
+ success: 3, // Green
325
+ danger: 4, // Red
326
+ link: 5, // Link button
327
+ };
328
+
329
+ return BUTTON_STYLES[style] || BUTTON_STYLES.secondary;
330
+ }
331
+
332
+ /**
333
+ * Ensure a thread exists for the given message.
334
+ *
335
+ * @param {string} channelId
336
+ * @param {string} messageId
337
+ * @param {string} threadId
338
+ * @param {string} threadName
339
+ * @returns {Promise<void>}
340
+ */
341
+ async #ensureThread(channelId, messageId, threadId, threadName) {
342
+ // Check if thread already exists
343
+ if (this.#threadChannels.has(threadId)) {
344
+ return;
345
+ }
346
+
347
+ try {
348
+ // Create thread from message
349
+ const response = await this.#apiRequest(
350
+ 'POST',
351
+ `/channels/${channelId}/messages/${messageId}/threads`,
352
+ {
353
+ name: threadName.slice(0, 100), // Max 100 chars
354
+ auto_archive_duration: 1440, // 24 hours
355
+ }
356
+ );
357
+
358
+ if (response.ok) {
359
+ const thread = await response.json();
360
+ this.#threadChannels.set(threadId, thread.id);
361
+ console.log(`[discord] Created thread: ${threadName}`);
362
+ }
363
+ } catch (error) {
364
+ error = this._redactError(error);
365
+ console.warn(`[discord] Thread creation failed:`, error.message);
366
+ // Non-fatal - message was still sent
367
+ }
368
+ }
369
+
370
+ /**
371
+ * Wait if rate limited for a channel.
372
+ *
373
+ * @param {string} channelId
374
+ * @returns {Promise<void>}
375
+ */
376
+ async #waitForRateLimit(channelId) {
377
+ const resetTime = this.#rateLimits.get(channelId);
378
+ if (!resetTime) return;
379
+
380
+ const now = Date.now();
381
+ if (now < resetTime) {
382
+ const waitMs = resetTime - now;
383
+ console.log(`[discord] Rate limited on channel ${channelId}, waiting ${waitMs}ms`);
384
+ await new Promise((resolve) => setTimeout(resolve, waitMs));
385
+ }
386
+
387
+ this.#rateLimits.delete(channelId);
388
+ }
389
+
390
+ /**
391
+ * Make a Discord API request.
392
+ *
393
+ * @param {string} method - HTTP method
394
+ * @param {string} path - API path (e.g., "/users/@me")
395
+ * @param {Object} [body] - Request body
396
+ * @returns {Promise<Response>}
397
+ */
398
+ async #apiRequest(method, path, body) {
399
+ const url = `${DISCORD_API_BASE}${path}`;
400
+
401
+ const headers = {
402
+ 'Authorization': `Bot ${this.#botToken}`,
403
+ 'User-Agent': 'AIWG-Bot/1.0',
404
+ };
405
+
406
+ const options = {
407
+ method,
408
+ headers,
409
+ };
410
+
411
+ if (body) {
412
+ headers['Content-Type'] = 'application/json';
413
+ options.body = JSON.stringify(body);
414
+ }
415
+
416
+ const response = await fetch(url, options);
417
+
418
+ // Handle rate limiting
419
+ if (response.status === 429) {
420
+ const retryAfter = response.headers.get('Retry-After');
421
+ const resetAfter = response.headers.get('X-RateLimit-Reset-After');
422
+
423
+ const waitMs = retryAfter
424
+ ? parseInt(retryAfter) * 1000
425
+ : resetAfter
426
+ ? parseFloat(resetAfter) * 1000
427
+ : 1000;
428
+
429
+ // Extract channel ID from path if possible
430
+ const channelMatch = path.match(/\/channels\/(\d+)/);
431
+ if (channelMatch) {
432
+ this.#rateLimits.set(channelMatch[1], Date.now() + waitMs);
433
+ }
434
+
435
+ console.warn(`[discord] Rate limited, retry after ${waitMs}ms`);
436
+
437
+ // Wait and retry
438
+ await new Promise((resolve) => setTimeout(resolve, waitMs));
439
+ return this.#apiRequest(method, path, body);
440
+ }
441
+
442
+ return response;
443
+ }
444
+
445
+ /**
446
+ * Register webhook handler for Discord interactions.
447
+ *
448
+ * This would be called by an HTTP server receiving Discord webhooks.
449
+ * For now, it's a placeholder for future webhook integration.
450
+ *
451
+ * @param {Function} handler - Express-like handler (req, res) => void
452
+ * @returns {void}
453
+ */
454
+ registerWebhook(handler) {
455
+ // TODO: Implement webhook handling for slash commands and button interactions
456
+ // This requires running an HTTP server to receive Discord interaction webhooks
457
+ console.log('[discord] Webhook registration not yet implemented');
458
+ }
459
+ }
460
+
461
+ // Export as both default and named export
462
+ export default DiscordAdapter;