@aiwg/cli 2026.10.15 → 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.
- package/agentic/code/providers/pi/aiwg-bridge.ts +45 -7
- package/dist/src/artifacts/citation-parser.js +7 -6
- package/dist/src/artifacts/corpus-tools/citation-densify.js +4 -2
- package/dist/src/artifacts/corpus-tools/cli.js +8 -3
- package/dist/src/artifacts/corpus-tools/discovery-log.js +26 -24
- package/dist/src/artifacts/corpus-tools/expand-cli.js +3 -2
- package/dist/src/artifacts/corpus-tools/expand-dates.js +107 -0
- package/dist/src/artifacts/corpus-tools/expand-queue.js +4 -1
- package/dist/src/artifacts/corpus-tools/expand-review.js +104 -0
- package/dist/src/artifacts/corpus-tools/expand-state.js +17 -1
- package/dist/src/artifacts/corpus-tools/expand.js +16 -17
- package/dist/src/artifacts/corpus-tools/induction-audit.js +7 -6
- package/dist/src/artifacts/corpus-tools/integrity-scan.js +3 -3
- package/dist/src/artifacts/corpus-tools/radar-shared.js +7 -9
- package/dist/src/artifacts/corpus-tools/ref-files.js +11 -0
- package/dist/src/artifacts/corpus-tools/resolve-cli.js +11 -3
- package/dist/src/artifacts/corpus-tools/resolve.js +23 -9
- package/dist/src/artifacts/corpus-tools/retrieval-lab.js +2 -1
- package/dist/src/artifacts/corpus-tools/sidecar-lint.js +4 -4
- package/dist/src/artifacts/corpus-tools/sidecar-repair.js +2 -1
- package/dist/src/artifacts/corpus-views/ref-parser.js +3 -17
- package/dist/src/artifacts/graph-query.js +5 -3
- package/dist/src/artifacts/hybrid-query.js +11 -2
- package/dist/src/artifacts/index-refresh.js +2 -0
- package/dist/src/cli/handlers/daemon.js +17 -1
- package/dist/src/cli/handlers/doctor-args.js +10 -5
- package/dist/src/cli/handlers/doctor-help.js +4 -1
- package/dist/src/cli/handlers/index.js +2 -2
- package/dist/src/cli/handlers/models-resource-sample.js +10 -0
- package/dist/src/cli/handlers/models.js +3 -2
- package/dist/src/cli/handlers/regenerate.js +8 -16
- package/dist/src/cli/handlers/sessions.js +7 -7
- package/dist/src/cli/handlers/subcommands.js +8 -0
- package/dist/src/cli/handlers/update.js +157 -0
- package/dist/src/cli/handlers/use.js +14 -4
- package/dist/src/cli/handlers/utilities.js +3 -560
- package/dist/src/cli/handlers/utility-doctor.js +412 -0
- package/dist/src/cli/services/deployment-verification.js +0 -1
- package/dist/src/config/aiwg-config.js +2 -1
- package/dist/src/config/authorization-cli.js +7 -3
- package/dist/src/config/dispatch-thresholds-runtime.d.mts +3 -2
- package/dist/src/config/dispatch-thresholds-runtime.mjs +17 -7
- package/dist/src/config/framework-aliases.js +12 -0
- package/dist/src/config/host-resource-report.d.mts +19 -0
- package/dist/src/config/host-resource-report.mjs +80 -0
- package/dist/src/config/host-resource-runtime.d.mts +34 -0
- package/dist/src/config/host-resource-runtime.mjs +293 -0
- package/dist/src/config/installed-selection.js +22 -0
- package/dist/src/config/worker-invocation-marker.d.mts +1 -0
- package/dist/src/config/worker-invocation-marker.mjs +2 -0
- package/dist/src/decision/heldout/access.js +74 -0
- package/dist/src/decision/heldout/calibration.js +1 -0
- package/dist/src/decision/heldout/collector.js +8 -1
- package/dist/src/effects/verifiers/file.js +22 -5
- package/dist/src/extensions/claude-attribution.js +82 -0
- package/dist/src/extensions/claude-hooks-installer.js +115 -69
- package/dist/src/extensions/commands/daemon.js +109 -0
- package/dist/src/extensions/commands/definitions.js +5 -89
- package/dist/src/gates/heldout.js +17 -7
- package/dist/src/lint/check-patterns.js +163 -0
- package/dist/src/lint/checks.js +268 -0
- package/dist/src/lint/reference-resolution.js +54 -0
- package/dist/src/lint/runner.js +3 -465
- package/dist/src/mcp/helpers.mjs +11 -1
- package/dist/src/memory/project-registry.js +44 -4
- package/dist/src/models/worker-plan.js +36 -5
- package/dist/src/models/wrapper-deployment.js +25 -12
- package/dist/src/models/wrapper-enforcement.js +47 -7
- package/dist/src/network-analysis/research.js +2 -1
- package/dist/src/policy/hitl-check.js +14 -4
- package/dist/src/policy/hitl-consume.js +54 -0
- package/dist/src/policy/hitl-receipt.js +2 -0
- package/dist/src/policy/hitl.js +11 -3
- package/dist/src/providers/provider-context-contracts.js +162 -0
- package/dist/src/providers/provider-definition-schema.js +136 -0
- package/dist/src/providers/provider-definitions.js +8 -1298
- package/dist/src/providers/provider-seeds-1.js +360 -0
- package/dist/src/providers/provider-seeds-2.js +387 -0
- package/dist/src/providers/provider-seeds-3.js +262 -0
- package/dist/src/research/clients/arxiv.js +4 -30
- package/dist/src/research/clients/base.js +48 -22
- package/dist/src/research/identity.js +34 -2
- package/dist/src/research/query-cli.js +3 -87
- package/dist/src/research/query-options.js +87 -0
- package/dist/src/research/reference-match.js +70 -24
- package/dist/src/research/services/acquisition.js +9 -7
- package/dist/src/research/services/citation.js +5 -2
- package/dist/src/research/types.js +2 -0
- package/dist/src/serve/mission-conductor.js +48 -4
- package/dist/src/sessions/adapters/grok-build-native.js +23 -0
- package/dist/src/sessions/adapters/grok-build.js +14 -7
- package/dist/src/sessions/workspace-discovery.js +5 -5
- package/dist/src/smiths/context-pipeline/aiwg-md.js +16 -46
- package/dist/src/smiths/context-pipeline/claude-hook.js +1 -1
- package/dist/src/smiths/context-pipeline/code-regions.js +28 -0
- package/dist/src/smiths/context-pipeline/finalization.js +81 -51
- package/dist/src/smiths/context-pipeline/generator.js +9 -10
- package/dist/src/smiths/context-pipeline/managed-hook.js +1 -1
- package/dist/src/smiths/context-pipeline/muse-bridge.js +2 -2
- package/dist/src/smiths/context-pipeline/provider-policy.js +6 -12
- package/dist/src/smiths/context-pipeline/workspace-audit.js +299 -0
- package/dist/src/smiths/context-pipeline/workspace-bootstrap.js +148 -0
- package/dist/src/smiths/context-pipeline/workspace-context-shared.js +111 -0
- package/dist/src/smiths/context-pipeline/workspace-context.js +8 -1373
- package/dist/src/smiths/context-pipeline/workspace-doctor.js +192 -0
- package/dist/src/smiths/context-pipeline/workspace-document.js +201 -0
- package/dist/src/smiths/context-pipeline/workspace-extraction.js +205 -0
- package/dist/src/smiths/context-pipeline/workspace-migration.js +250 -0
- package/package.json +10 -1
- package/schemas/decision/D29Study.v10.schema.json +65 -0
- package/tools/agents/deploy-agents.mjs +10 -0
- package/tools/agents/providers/claude-post-deploy.mjs +12 -1
- package/tools/agents/providers/context-write.mjs +4 -0
- package/tools/agents/providers/pi.mjs +3 -1
- package/tools/agents/providers/rule-delivery-surface.mjs +332 -0
- package/tools/agents/providers/rule-delivery.mjs +20 -1144
- package/tools/agents/providers/rule-deployment-commit.mjs +144 -0
- package/tools/agents/providers/rule-deployment-prepare.mjs +452 -0
- package/tools/agents/providers/rule-deployment-state.mjs +300 -0
- package/tools/daemon/README.md +511 -0
- package/tools/daemon/adapters/base-adapter.mjs +84 -0
- package/tools/daemon/adapters/webhook-adapter.mjs +107 -0
- package/tools/daemon/agent-supervisor.mjs +299 -0
- package/tools/daemon/automation-engine.mjs +310 -0
- package/tools/daemon/autonomous-engine.mjs +346 -0
- package/tools/daemon/behavior-loader.mjs +316 -0
- package/tools/daemon/behavior.mjs +174 -0
- package/tools/daemon/concierge/intent-router.mjs +401 -0
- package/tools/daemon/concierge/orchestrator.mjs +272 -0
- package/tools/daemon/concierge/response-translator.mjs +462 -0
- package/tools/daemon/config.mjs +377 -0
- package/tools/daemon/cron-scheduler.mjs +178 -0
- package/tools/daemon/daemon-main.mjs +1169 -0
- package/tools/daemon/event-router.mjs +84 -0
- package/tools/daemon/file-watcher.mjs +383 -0
- package/tools/daemon/index.mjs +1181 -0
- package/tools/daemon/init-profile.mjs +124 -0
- package/tools/daemon/ipc-client.mjs +197 -0
- package/tools/daemon/ipc-ops-handlers.mjs +236 -0
- package/tools/daemon/ipc-server.mjs +275 -0
- package/tools/daemon/maintenance-owner.mjs +79 -0
- package/tools/daemon/memory-manager.mjs +386 -0
- package/tools/daemon/message-router.mjs +194 -0
- package/tools/daemon/provider-watcher.mjs +585 -0
- package/tools/daemon/pty-adapter.mjs +420 -0
- package/tools/daemon/repl-chat.mjs +359 -0
- package/tools/daemon/resource-bounds.mjs +88 -0
- package/tools/daemon/sandbox-transport.mjs +295 -0
- package/tools/daemon/scheduled-task-runner.mjs +535 -0
- package/tools/daemon/task-store.mjs +450 -0
- package/tools/daemon/tmux-manager.mjs +324 -0
- package/tools/daemon/update-policy.mjs +517 -0
- package/tools/daemon/web-server.mjs +399 -0
- package/tools/daemon/web-ui/index.html +585 -0
- package/tools/daemon/web-ui/styles.css +156 -0
- package/tools/docker/Dockerfile.daemon +35 -0
- package/tools/docker/container-manager.mjs +291 -0
- package/tools/messaging/adapter-registry.mjs +230 -0
- package/tools/messaging/adapters/base.mjs +326 -0
- package/tools/messaging/adapters/discord.mjs +462 -0
- package/tools/messaging/adapters/slack.mjs +402 -0
- package/tools/messaging/adapters/telegram.mjs +552 -0
- package/tools/messaging/chat-handler.mjs +297 -0
- package/tools/messaging/command-router.mjs +269 -0
- package/tools/messaging/event-bus.mjs +199 -0
- package/tools/messaging/index.mjs +456 -0
- package/tools/messaging/message-formatter.mjs +320 -0
- package/tools/messaging/room-manager.mjs +277 -0
- package/tools/messaging/types.mjs +94 -0
- package/tools/providers/pi-bridge-policy.mjs +4 -0
- package/tools/ralph-external/daemon-supervisor.mjs +394 -0
- package/tools/ralph-external/lib/behavior-registry.mjs +270 -0
- package/tools/ralph-external/lib/worker-invocation-processes.mjs +3 -2
- package/tools/ralph-external/lib/worker-isolation-args.mjs +217 -0
- package/tools/ralph-external/lib/worker-isolation-status.mjs +19 -0
- package/tools/ralph-external/lib/worker-isolation.mjs +11 -237
- package/tools/ralph-external/lib/worker-overflow.mjs +10 -2
- package/tools/ralph-external/lib/worker-unit-cleanup.mjs +72 -0
- package/tools/ralph-external/session-launcher.mjs +7 -7
- 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;
|