@openacp/cli 0.6.10 → 2026.41.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (133) hide show
  1. package/README.md +34 -16
  2. package/dist/cli.d.ts +11 -0
  3. package/dist/cli.js +28362 -449
  4. package/dist/cli.js.map +1 -1
  5. package/dist/data/registry-snapshot.json +1 -1
  6. package/dist/index.d.ts +1930 -467
  7. package/dist/index.js +17331 -102
  8. package/dist/index.js.map +1 -1
  9. package/package.json +13 -7
  10. package/dist/action-detect-P7ZE4NEM.js +0 -16
  11. package/dist/action-detect-P7ZE4NEM.js.map +0 -1
  12. package/dist/adapter-ZOANORGM.js +0 -799
  13. package/dist/adapter-ZOANORGM.js.map +0 -1
  14. package/dist/admin-6SYB6XCZ.js +0 -23
  15. package/dist/admin-6SYB6XCZ.js.map +0 -1
  16. package/dist/agent-catalog-FC3HGDEQ.js +0 -11
  17. package/dist/agent-catalog-FC3HGDEQ.js.map +0 -1
  18. package/dist/agent-dependencies-4OWBMZWZ.js +0 -24
  19. package/dist/agent-dependencies-4OWBMZWZ.js.map +0 -1
  20. package/dist/agent-registry-WT4NXPYG.js +0 -9
  21. package/dist/agent-registry-WT4NXPYG.js.map +0 -1
  22. package/dist/agent-store-VZLFPTZU.js +0 -9
  23. package/dist/agent-store-VZLFPTZU.js.map +0 -1
  24. package/dist/agents-QO7DKARJ.js +0 -15
  25. package/dist/agents-QO7DKARJ.js.map +0 -1
  26. package/dist/api-client-CFQT5U7D.js +0 -14
  27. package/dist/api-client-CFQT5U7D.js.map +0 -1
  28. package/dist/autostart-X33OGMX6.js +0 -23
  29. package/dist/autostart-X33OGMX6.js.map +0 -1
  30. package/dist/chunk-2CJ46J3C.js +0 -154
  31. package/dist/chunk-2CJ46J3C.js.map +0 -1
  32. package/dist/chunk-2HMQOC7N.js +0 -134
  33. package/dist/chunk-2HMQOC7N.js.map +0 -1
  34. package/dist/chunk-33RP6K2O.js +0 -435
  35. package/dist/chunk-33RP6K2O.js.map +0 -1
  36. package/dist/chunk-34M4OS5P.js +0 -83
  37. package/dist/chunk-34M4OS5P.js.map +0 -1
  38. package/dist/chunk-4CTX774K.js +0 -265
  39. package/dist/chunk-4CTX774K.js.map +0 -1
  40. package/dist/chunk-7QJS2XBD.js +0 -92
  41. package/dist/chunk-7QJS2XBD.js.map +0 -1
  42. package/dist/chunk-BNLGTZ34.js +0 -122
  43. package/dist/chunk-BNLGTZ34.js.map +0 -1
  44. package/dist/chunk-CS3KCJ5D.js +0 -4788
  45. package/dist/chunk-CS3KCJ5D.js.map +0 -1
  46. package/dist/chunk-GAK6PIBW.js +0 -224
  47. package/dist/chunk-GAK6PIBW.js.map +0 -1
  48. package/dist/chunk-I7WC6E5S.js +0 -71
  49. package/dist/chunk-I7WC6E5S.js.map +0 -1
  50. package/dist/chunk-J4SJTKIK.js +0 -203
  51. package/dist/chunk-J4SJTKIK.js.map +0 -1
  52. package/dist/chunk-JHYXKVV2.js +0 -183
  53. package/dist/chunk-JHYXKVV2.js.map +0 -1
  54. package/dist/chunk-JKBFUAJK.js +0 -282
  55. package/dist/chunk-JKBFUAJK.js.map +0 -1
  56. package/dist/chunk-KIRH7TUJ.js +0 -219
  57. package/dist/chunk-KIRH7TUJ.js.map +0 -1
  58. package/dist/chunk-LBIKITQT.js +0 -22
  59. package/dist/chunk-LBIKITQT.js.map +0 -1
  60. package/dist/chunk-LCRLAV4G.js +0 -1085
  61. package/dist/chunk-LCRLAV4G.js.map +0 -1
  62. package/dist/chunk-LGP2YGRL.js +0 -4880
  63. package/dist/chunk-LGP2YGRL.js.map +0 -1
  64. package/dist/chunk-MKHUZLII.js +0 -738
  65. package/dist/chunk-MKHUZLII.js.map +0 -1
  66. package/dist/chunk-NAMYZIS5.js +0 -1
  67. package/dist/chunk-NAMYZIS5.js.map +0 -1
  68. package/dist/chunk-NVPG6JCL.js +0 -724
  69. package/dist/chunk-NVPG6JCL.js.map +0 -1
  70. package/dist/chunk-O7CPGUAI.js +0 -298
  71. package/dist/chunk-O7CPGUAI.js.map +0 -1
  72. package/dist/chunk-OWP7RZ62.js +0 -697
  73. package/dist/chunk-OWP7RZ62.js.map +0 -1
  74. package/dist/chunk-S64CB6J3.js +0 -98
  75. package/dist/chunk-S64CB6J3.js.map +0 -1
  76. package/dist/chunk-UKT3G5IA.js +0 -484
  77. package/dist/chunk-UKT3G5IA.js.map +0 -1
  78. package/dist/chunk-V5GZQEIY.js +0 -101
  79. package/dist/chunk-V5GZQEIY.js.map +0 -1
  80. package/dist/chunk-VOIJ6OY4.js +0 -63
  81. package/dist/chunk-VOIJ6OY4.js.map +0 -1
  82. package/dist/chunk-VUNV25KB.js +0 -16
  83. package/dist/chunk-VUNV25KB.js.map +0 -1
  84. package/dist/chunk-W3EYKZNQ.js +0 -45
  85. package/dist/chunk-W3EYKZNQ.js.map +0 -1
  86. package/dist/chunk-WTZDAYZX.js +0 -172
  87. package/dist/chunk-WTZDAYZX.js.map +0 -1
  88. package/dist/chunk-XANPHG7W.js +0 -145
  89. package/dist/chunk-XANPHG7W.js.map +0 -1
  90. package/dist/config-6S355X75.js +0 -15
  91. package/dist/config-6S355X75.js.map +0 -1
  92. package/dist/config-editor-QQTZMWGD.js +0 -13
  93. package/dist/config-editor-QQTZMWGD.js.map +0 -1
  94. package/dist/config-registry-AHYI4MYL.js +0 -18
  95. package/dist/config-registry-AHYI4MYL.js.map +0 -1
  96. package/dist/daemon-4CS6HMB5.js +0 -30
  97. package/dist/daemon-4CS6HMB5.js.map +0 -1
  98. package/dist/discord-OMC52Y54.js +0 -2239
  99. package/dist/discord-OMC52Y54.js.map +0 -1
  100. package/dist/dist-UHQK5CXN.js +0 -21151
  101. package/dist/dist-UHQK5CXN.js.map +0 -1
  102. package/dist/doctor-HZZ5BSHB.js +0 -10
  103. package/dist/doctor-HZZ5BSHB.js.map +0 -1
  104. package/dist/doctor-OLYBO3V3.js +0 -15
  105. package/dist/doctor-OLYBO3V3.js.map +0 -1
  106. package/dist/install-cloudflared-Z7VCGOVG.js +0 -33
  107. package/dist/install-cloudflared-Z7VCGOVG.js.map +0 -1
  108. package/dist/install-jq-HUYSQWKR.js +0 -32
  109. package/dist/install-jq-HUYSQWKR.js.map +0 -1
  110. package/dist/integrate-PNEHRY2I.js +0 -373
  111. package/dist/integrate-PNEHRY2I.js.map +0 -1
  112. package/dist/log-NXABYJTT.js +0 -24
  113. package/dist/log-NXABYJTT.js.map +0 -1
  114. package/dist/main-XOZCLFUK.js +0 -238
  115. package/dist/main-XOZCLFUK.js.map +0 -1
  116. package/dist/menu-YY5MKHEK.js +0 -16
  117. package/dist/menu-YY5MKHEK.js.map +0 -1
  118. package/dist/new-session-FEO4J4VU.js +0 -17
  119. package/dist/new-session-FEO4J4VU.js.map +0 -1
  120. package/dist/post-upgrade-CJG5I7M2.js +0 -80
  121. package/dist/post-upgrade-CJG5I7M2.js.map +0 -1
  122. package/dist/session-IUSI7P5S.js +0 -20
  123. package/dist/session-IUSI7P5S.js.map +0 -1
  124. package/dist/settings-RQPAM4KC.js +0 -14
  125. package/dist/settings-RQPAM4KC.js.map +0 -1
  126. package/dist/setup-XHS4OMPM.js +0 -37
  127. package/dist/setup-XHS4OMPM.js.map +0 -1
  128. package/dist/suggest-7D6B542M.js +0 -38
  129. package/dist/suggest-7D6B542M.js.map +0 -1
  130. package/dist/tunnel-service-CJLUH6SZ.js +0 -1174
  131. package/dist/tunnel-service-CJLUH6SZ.js.map +0 -1
  132. package/dist/version-NQZBM5M7.js +0 -16
  133. package/dist/version-NQZBM5M7.js.map +0 -1
@@ -1,2239 +0,0 @@
1
- import {
2
- buildActionKeyboard,
3
- detectAction,
4
- storeAction
5
- } from "./chunk-I7WC6E5S.js";
6
- import {
7
- handleNew,
8
- handleNewChat,
9
- handleNewSessionButton
10
- } from "./chunk-XANPHG7W.js";
11
- import {
12
- handleDangerous,
13
- handleDangerousButton,
14
- handleRestart,
15
- handleTTS,
16
- handleTTSButton,
17
- handleUpdate,
18
- handleVerbosity
19
- } from "./chunk-KIRH7TUJ.js";
20
- import {
21
- handleCancel,
22
- handleCleanupButton,
23
- handleHandoff,
24
- handleSessions,
25
- handleStatus
26
- } from "./chunk-4CTX774K.js";
27
- import {
28
- buildDeepLink,
29
- createSessionThread,
30
- deleteSessionThread,
31
- ensureForums,
32
- ensureUnarchived,
33
- renameSessionThread
34
- } from "./chunk-BNLGTZ34.js";
35
- import {
36
- handleAgentButton,
37
- handleAgents,
38
- handleInstall
39
- } from "./chunk-J4SJTKIK.js";
40
- import {
41
- handleSettings,
42
- handleSettingsButton
43
- } from "./chunk-O7CPGUAI.js";
44
- import {
45
- handleDoctor,
46
- handleDoctorButton
47
- } from "./chunk-2HMQOC7N.js";
48
- import {
49
- PRODUCT_GUIDE,
50
- dispatchMessage,
51
- evaluateNoise,
52
- extractContentText,
53
- formatTokens,
54
- formatToolSummary,
55
- formatToolTitle,
56
- progressBar,
57
- resolveToolIcon,
58
- splitMessage,
59
- stripCodeFences,
60
- truncateContent
61
- } from "./chunk-OWP7RZ62.js";
62
- import {
63
- ChannelAdapter
64
- } from "./chunk-LBIKITQT.js";
65
- import "./chunk-NVPG6JCL.js";
66
- import "./chunk-JHYXKVV2.js";
67
- import "./chunk-33RP6K2O.js";
68
- import {
69
- log
70
- } from "./chunk-GAK6PIBW.js";
71
- import "./chunk-VUNV25KB.js";
72
-
73
- // src/adapters/discord/adapter.ts
74
- import {
75
- Client,
76
- GatewayIntentBits,
77
- MessageFlags
78
- } from "discord.js";
79
-
80
- // src/adapters/discord/send-queue.ts
81
- var DiscordSendQueue = class {
82
- items = [];
83
- processing = false;
84
- lastExec = 0;
85
- minInterval;
86
- constructor(minInterval = 1e3) {
87
- this.minInterval = minInterval;
88
- }
89
- enqueue(fn, opts) {
90
- const type = opts.type;
91
- const key = opts.key;
92
- return new Promise((resolve, reject) => {
93
- if (type === "text" && key) {
94
- const idx = this.items.findIndex(
95
- (item) => item.type === "text" && item.key === key
96
- );
97
- if (idx !== -1) {
98
- this.items[idx].resolve(void 0);
99
- this.items[idx] = { fn, type, key, resolve, reject };
100
- this.scheduleProcess();
101
- return;
102
- }
103
- }
104
- this.items.push({ fn, type, key, resolve, reject });
105
- this.scheduleProcess();
106
- });
107
- }
108
- onRateLimited() {
109
- log.warn("[DiscordSendQueue] Rate limited \u2014 dropping queued text items");
110
- const remaining = [];
111
- for (const item of this.items) {
112
- if (item.type === "text") {
113
- item.resolve(void 0);
114
- } else {
115
- remaining.push(item);
116
- }
117
- }
118
- this.items = remaining;
119
- }
120
- scheduleProcess() {
121
- if (this.processing) return;
122
- if (this.items.length === 0) return;
123
- const elapsed = Date.now() - this.lastExec;
124
- const delay = Math.max(0, this.minInterval - elapsed);
125
- this.processing = true;
126
- setTimeout(() => void this.processNext(), delay);
127
- }
128
- async processNext() {
129
- const item = this.items.shift();
130
- if (!item) {
131
- this.processing = false;
132
- return;
133
- }
134
- try {
135
- const result = await item.fn();
136
- item.resolve(result);
137
- } catch (err) {
138
- item.reject(err);
139
- } finally {
140
- this.lastExec = Date.now();
141
- this.processing = false;
142
- this.scheduleProcess();
143
- }
144
- }
145
- };
146
-
147
- // src/adapters/discord/formatting.ts
148
- function formatViewerLinks(links, filePath) {
149
- if (!links) return "";
150
- const fileName = filePath ? filePath.split("/").pop() || filePath : "";
151
- let text = "\n";
152
- if (links.file) text += `
153
- [View ${fileName || "file"}](${links.file})`;
154
- if (links.diff)
155
- text += `
156
- [View diff${fileName ? ` \u2014 ${fileName}` : ""}](${links.diff})`;
157
- return text;
158
- }
159
- function formatHighDetails(rawInput, content, maxLen) {
160
- let text = "";
161
- if (rawInput) {
162
- const inputStr = typeof rawInput === "string" ? rawInput : JSON.stringify(rawInput, null, 2);
163
- if (inputStr && inputStr !== "{}") {
164
- text += `
165
- **Input:**
166
- \`\`\`
167
- ${truncateContent(inputStr, maxLen)}
168
- \`\`\``;
169
- }
170
- }
171
- const details = stripCodeFences(extractContentText(content));
172
- if (details) {
173
- text += `
174
- **Output:**
175
- \`\`\`
176
- ${truncateContent(details, maxLen)}
177
- \`\`\``;
178
- }
179
- return text;
180
- }
181
- function formatToolCall(tool, verbosity = "medium") {
182
- const si = resolveToolIcon(tool);
183
- const name = tool.name || "Tool";
184
- const label = verbosity === "low" ? formatToolTitle(name, tool.rawInput, tool.displayTitle) : formatToolSummary(name, tool.rawInput, tool.displaySummary);
185
- let text = `${si} **${label}**`;
186
- text += formatViewerLinks(tool.viewerLinks, tool.viewerFilePath);
187
- if (verbosity === "high") {
188
- text += formatHighDetails(tool.rawInput, tool.content, 500);
189
- }
190
- return text;
191
- }
192
- function formatToolUpdate(update, verbosity = "medium") {
193
- return formatToolCall(update, verbosity);
194
- }
195
- function formatPlan(entries, verbosity = "medium") {
196
- if (verbosity === "medium") {
197
- const done = entries.filter((e) => e.status === "completed").length;
198
- return `\u{1F4CB} **Plan:** ${done}/${entries.length} steps completed`;
199
- }
200
- const statusIcon = {
201
- pending: "\u23F3",
202
- in_progress: "\u{1F504}",
203
- completed: "\u2705"
204
- };
205
- const lines = entries.map(
206
- (e, i) => `${statusIcon[e.status] || "\u2B1C"} ${i + 1}. ${e.content}`
207
- );
208
- return `**Plan:**
209
- ${lines.join("\n")}`;
210
- }
211
- function formatUsage(usage, verbosity = "medium") {
212
- const { tokensUsed, contextSize, cost } = usage;
213
- if (tokensUsed == null) return "\u{1F4CA} Usage data unavailable";
214
- if (verbosity === "medium") {
215
- const costStr = cost != null ? ` \xB7 $${cost.toFixed(2)}` : "";
216
- return `\u{1F4CA} ${formatTokens(tokensUsed)} tokens${costStr}`;
217
- }
218
- if (contextSize == null) return `\u{1F4CA} ${formatTokens(tokensUsed)} tokens`;
219
- const ratio = tokensUsed / contextSize;
220
- const pct = Math.round(ratio * 100);
221
- const bar = progressBar(ratio);
222
- const emoji = pct >= 85 ? "\u26A0\uFE0F" : "\u{1F4CA}";
223
- let text = `${emoji} ${formatTokens(tokensUsed)} / ${formatTokens(contextSize)} tokens
224
- ${bar} ${pct}%`;
225
- if (cost != null) text += `
226
- \u{1F4B0} $${cost.toFixed(2)}`;
227
- return text;
228
- }
229
- function splitMessage2(text, maxLength = 1800) {
230
- return splitMessage(text, maxLength);
231
- }
232
-
233
- // src/adapters/discord/tool-call-tracker.ts
234
- var ToolCallTracker = class {
235
- constructor(sendQueue) {
236
- this.sendQueue = sendQueue;
237
- }
238
- sessions = /* @__PURE__ */ new Map();
239
- async trackNewCall(sessionId, thread, tool, verbosity = "medium") {
240
- if (!this.sessions.has(sessionId)) {
241
- this.sessions.set(sessionId, /* @__PURE__ */ new Map());
242
- }
243
- let resolveReady;
244
- const ready = new Promise((r) => {
245
- resolveReady = r;
246
- });
247
- const state = {
248
- message: void 0,
249
- name: tool.name,
250
- kind: tool.kind,
251
- rawInput: tool.rawInput,
252
- viewerLinks: tool.viewerLinks,
253
- viewerFilePath: tool.viewerFilePath,
254
- ready
255
- };
256
- this.sessions.get(sessionId).set(tool.id, state);
257
- const content = formatToolCall(tool, verbosity);
258
- try {
259
- const msg = await this.sendQueue.enqueue(() => thread.send({ content }), {
260
- type: "other"
261
- });
262
- if (msg) state.message = msg;
263
- } catch (err) {
264
- log.warn(
265
- { err, toolId: tool.id },
266
- "[ToolCallTracker] trackNewCall() send failed"
267
- );
268
- } finally {
269
- resolveReady();
270
- }
271
- }
272
- async updateCall(sessionId, update, verbosity = "medium") {
273
- const toolState = this.sessions.get(sessionId)?.get(update.id);
274
- if (!toolState) return;
275
- if (update.viewerLinks) toolState.viewerLinks = update.viewerLinks;
276
- if (update.viewerFilePath) toolState.viewerFilePath = update.viewerFilePath;
277
- if (update.name) toolState.name = update.name;
278
- if (update.kind) toolState.kind = update.kind;
279
- const isTerminal = update.status === "completed" || update.status === "failed";
280
- if (!isTerminal) return;
281
- await toolState.ready;
282
- if (!toolState.message) return;
283
- log.debug(
284
- {
285
- toolId: update.id,
286
- status: update.status,
287
- hasViewerLinks: !!toolState.viewerLinks,
288
- name: toolState.name,
289
- msgId: toolState.message.id
290
- },
291
- "[ToolCallTracker] Tool completed, preparing edit"
292
- );
293
- const merged = {
294
- ...update,
295
- name: toolState.name,
296
- kind: toolState.kind,
297
- rawInput: toolState.rawInput,
298
- viewerLinks: toolState.viewerLinks,
299
- viewerFilePath: toolState.viewerFilePath
300
- };
301
- const content = formatToolUpdate(merged, verbosity);
302
- try {
303
- await this.sendQueue.enqueue(() => toolState.message.edit({ content }), {
304
- type: "other"
305
- });
306
- } catch (err) {
307
- log.warn(
308
- {
309
- err,
310
- msgId: toolState.message.id,
311
- contentLen: content.length,
312
- hasViewerLinks: !!merged.viewerLinks
313
- },
314
- "[ToolCallTracker] Tool update edit failed"
315
- );
316
- }
317
- }
318
- cleanup(sessionId) {
319
- this.sessions.delete(sessionId);
320
- }
321
- };
322
-
323
- // src/adapters/discord/streaming.ts
324
- var FLUSH_INTERVAL = 5e3;
325
- var MAX_DISPLAY_LENGTH = 1900;
326
- var MessageDraft = class {
327
- constructor(thread, sendQueue, sessionId) {
328
- this.thread = thread;
329
- this.sendQueue = sendQueue;
330
- this.sessionId = sessionId;
331
- }
332
- buffer = "";
333
- message;
334
- flushTimer;
335
- flushPromise = Promise.resolve();
336
- lastSentBuffer = "";
337
- displayTruncated = false;
338
- firstFlushPending = false;
339
- append(text) {
340
- if (!text) return;
341
- this.buffer += text;
342
- this.scheduleFlush();
343
- }
344
- getBuffer() {
345
- return this.buffer;
346
- }
347
- scheduleFlush() {
348
- if (this.flushTimer) return;
349
- this.flushTimer = setTimeout(() => {
350
- this.flushTimer = void 0;
351
- this.flushPromise = this.flushPromise.then(() => this.flush()).catch(() => {
352
- });
353
- }, FLUSH_INTERVAL);
354
- }
355
- async flush() {
356
- if (!this.buffer) return;
357
- if (this.firstFlushPending) return;
358
- const snapshot = this.buffer;
359
- let content = snapshot;
360
- let truncated = false;
361
- if (content.length > MAX_DISPLAY_LENGTH) {
362
- content = snapshot.slice(0, MAX_DISPLAY_LENGTH) + "\u2026";
363
- truncated = true;
364
- }
365
- if (!content) return;
366
- if (!this.message) {
367
- this.firstFlushPending = true;
368
- try {
369
- const result = await this.sendQueue.enqueue(
370
- () => this.thread.send({ content }),
371
- { type: "other" }
372
- );
373
- if (result) {
374
- this.message = result;
375
- if (!truncated) {
376
- this.lastSentBuffer = snapshot;
377
- this.displayTruncated = false;
378
- } else {
379
- this.displayTruncated = true;
380
- }
381
- }
382
- } catch {
383
- } finally {
384
- this.firstFlushPending = false;
385
- }
386
- } else {
387
- if (!truncated && snapshot === this.lastSentBuffer) return;
388
- try {
389
- const result = await this.sendQueue.enqueue(
390
- () => this.message.edit({ content }),
391
- { type: "text", key: this.sessionId }
392
- );
393
- if (result !== void 0) {
394
- if (!truncated) {
395
- this.lastSentBuffer = snapshot;
396
- this.displayTruncated = false;
397
- } else {
398
- this.displayTruncated = true;
399
- }
400
- }
401
- } catch {
402
- }
403
- }
404
- }
405
- async stripPattern(pattern) {
406
- if (!this.message || !this.buffer) return;
407
- const stripped = this.buffer.replace(pattern, "").trim();
408
- if (stripped === this.buffer.trim()) return;
409
- this.buffer = stripped;
410
- this.lastSentBuffer = stripped;
411
- if (!stripped) return;
412
- try {
413
- await this.sendQueue.enqueue(
414
- () => this.message.edit({ content: stripped }),
415
- { type: "other" }
416
- );
417
- } catch {
418
- }
419
- }
420
- async finalize() {
421
- if (this.flushTimer) {
422
- clearTimeout(this.flushTimer);
423
- this.flushTimer = void 0;
424
- }
425
- await this.flushPromise;
426
- if (!this.buffer) return;
427
- if (this.message && this.buffer === this.lastSentBuffer && !this.displayTruncated) {
428
- return;
429
- }
430
- if (this.buffer.length <= MAX_DISPLAY_LENGTH) {
431
- const content = this.buffer;
432
- try {
433
- if (this.message) {
434
- await this.sendQueue.enqueue(
435
- () => this.message.edit({ content }),
436
- { type: "other" }
437
- );
438
- } else {
439
- await this.sendQueue.enqueue(
440
- () => this.thread.send({ content }),
441
- { type: "other" }
442
- );
443
- }
444
- return;
445
- } catch {
446
- }
447
- }
448
- const chunks = splitMessage2(this.buffer, MAX_DISPLAY_LENGTH);
449
- for (let i = 0; i < chunks.length; i++) {
450
- const content = chunks[i];
451
- try {
452
- if (i === 0 && this.message) {
453
- await this.sendQueue.enqueue(
454
- () => this.message.edit({ content }),
455
- { type: "other" }
456
- );
457
- } else {
458
- const msg = await this.sendQueue.enqueue(
459
- () => this.thread.send({ content }),
460
- { type: "other" }
461
- );
462
- if (msg) {
463
- this.message = msg;
464
- }
465
- }
466
- } catch {
467
- }
468
- }
469
- }
470
- };
471
-
472
- // src/adapters/discord/draft-manager.ts
473
- var DraftManager = class {
474
- constructor(sendQueue) {
475
- this.sendQueue = sendQueue;
476
- }
477
- drafts = /* @__PURE__ */ new Map();
478
- textBuffers = /* @__PURE__ */ new Map();
479
- getOrCreate(sessionId, thread) {
480
- let draft = this.drafts.get(sessionId);
481
- if (!draft) {
482
- draft = new MessageDraft(thread, this.sendQueue, sessionId);
483
- this.drafts.set(sessionId, draft);
484
- }
485
- return draft;
486
- }
487
- hasDraft(sessionId) {
488
- return this.drafts.has(sessionId);
489
- }
490
- getDraft(sessionId) {
491
- return this.drafts.get(sessionId);
492
- }
493
- appendText(sessionId, text) {
494
- this.textBuffers.set(sessionId, (this.textBuffers.get(sessionId) ?? "") + text);
495
- }
496
- /**
497
- * Finalize the current draft.
498
- * If isAssistant is true, detects action patterns in the accumulated text and sends
499
- * action buttons as a follow-up message.
500
- */
501
- async finalize(sessionId, thread, isAssistant) {
502
- const draft = this.drafts.get(sessionId);
503
- if (!draft) return;
504
- this.drafts.delete(sessionId);
505
- await draft.finalize();
506
- if (isAssistant && thread) {
507
- const fullText = this.textBuffers.get(sessionId);
508
- this.textBuffers.delete(sessionId);
509
- if (fullText) {
510
- const detected = detectAction(fullText);
511
- if (detected) {
512
- const actionId = storeAction(detected);
513
- const components = [buildActionKeyboard(actionId, detected)];
514
- try {
515
- await this.sendQueue.enqueue(
516
- () => thread.send({ components }),
517
- { type: "other" }
518
- );
519
- } catch {
520
- }
521
- }
522
- }
523
- } else {
524
- this.textBuffers.delete(sessionId);
525
- }
526
- }
527
- cleanup(sessionId) {
528
- this.drafts.delete(sessionId);
529
- this.textBuffers.delete(sessionId);
530
- }
531
- };
532
-
533
- // src/adapters/discord/activity.ts
534
- import { EmbedBuilder } from "discord.js";
535
- var TYPING_REFRESH_MS = 8e3;
536
- var ThinkingIndicator = class {
537
- constructor(channel) {
538
- this.channel = channel;
539
- }
540
- dismissed = false;
541
- refreshTimer;
542
- async show() {
543
- if (this.dismissed) return;
544
- try {
545
- await this.channel.sendTyping();
546
- this.startRefreshTimer();
547
- } catch (err) {
548
- log.warn({ err }, "[ThinkingIndicator] sendTyping() failed");
549
- }
550
- }
551
- dismiss() {
552
- this.dismissed = true;
553
- this.stopRefreshTimer();
554
- }
555
- reset() {
556
- this.dismissed = false;
557
- }
558
- startRefreshTimer() {
559
- this.stopRefreshTimer();
560
- this.refreshTimer = setInterval(() => {
561
- if (this.dismissed) {
562
- this.stopRefreshTimer();
563
- return;
564
- }
565
- this.channel.sendTyping().catch(() => {
566
- });
567
- }, TYPING_REFRESH_MS);
568
- }
569
- stopRefreshTimer() {
570
- if (this.refreshTimer) {
571
- clearInterval(this.refreshTimer);
572
- this.refreshTimer = void 0;
573
- }
574
- }
575
- };
576
- var UsageMessage = class {
577
- constructor(thread, sendQueue) {
578
- this.thread = thread;
579
- this.sendQueue = sendQueue;
580
- }
581
- message;
582
- async send(usage, verbosity = "medium") {
583
- const text = formatUsage(usage, verbosity);
584
- const embed = new EmbedBuilder().setDescription(text);
585
- try {
586
- if (this.message) {
587
- await this.sendQueue.enqueue(
588
- () => this.message.edit({ embeds: [embed] }),
589
- { type: "other" }
590
- );
591
- } else {
592
- const result = await this.sendQueue.enqueue(
593
- () => this.thread.send({ embeds: [embed] }),
594
- { type: "other" }
595
- );
596
- if (result) this.message = result;
597
- }
598
- } catch (err) {
599
- log.warn({ err }, "[UsageMessage] send() failed");
600
- }
601
- }
602
- async delete() {
603
- if (!this.message) return;
604
- const msg = this.message;
605
- this.message = void 0;
606
- try {
607
- await this.sendQueue.enqueue(() => msg.delete(), { type: "other" });
608
- } catch (err) {
609
- log.warn({ err }, "[UsageMessage] delete() failed");
610
- }
611
- }
612
- };
613
- var PLAN_DEBOUNCE_MS = 3500;
614
- var PlanCard = class {
615
- constructor(thread, sendQueue) {
616
- this.thread = thread;
617
- this.sendQueue = sendQueue;
618
- }
619
- message;
620
- flushPromise = Promise.resolve();
621
- latestEntries;
622
- lastSentText;
623
- flushTimer;
624
- verbosity = "medium";
625
- setVerbosity(v) {
626
- this.verbosity = v;
627
- }
628
- update(entries) {
629
- this.latestEntries = entries;
630
- if (this.flushTimer) clearTimeout(this.flushTimer);
631
- this.flushTimer = setTimeout(() => {
632
- this.flushTimer = void 0;
633
- this.flushPromise = this.flushPromise.then(() => this._flush()).catch(() => {
634
- });
635
- }, PLAN_DEBOUNCE_MS);
636
- }
637
- async finalize() {
638
- if (!this.latestEntries) return;
639
- if (this.flushTimer) {
640
- clearTimeout(this.flushTimer);
641
- this.flushTimer = void 0;
642
- }
643
- await this.flushPromise;
644
- this.flushPromise = this.flushPromise.then(() => this._flush()).catch(() => {
645
- });
646
- await this.flushPromise;
647
- }
648
- destroy() {
649
- if (this.flushTimer) {
650
- clearTimeout(this.flushTimer);
651
- this.flushTimer = void 0;
652
- }
653
- }
654
- async _flush() {
655
- if (!this.latestEntries) return;
656
- const text = formatPlan(this.latestEntries, this.verbosity);
657
- if (this.message && text === this.lastSentText) return;
658
- this.lastSentText = text;
659
- const embed = new EmbedBuilder().setDescription(text);
660
- try {
661
- if (this.message) {
662
- await this.sendQueue.enqueue(
663
- () => this.message.edit({ embeds: [embed] }),
664
- { type: "other" }
665
- );
666
- } else {
667
- const result = await this.sendQueue.enqueue(
668
- () => this.thread.send({ embeds: [embed] }),
669
- { type: "other" }
670
- );
671
- if (result) this.message = result;
672
- }
673
- } catch (err) {
674
- log.warn({ err }, "[PlanCard] flush failed");
675
- }
676
- }
677
- };
678
- var ActivityTracker = class {
679
- constructor(thread, sendQueue) {
680
- this.thread = thread;
681
- this.sendQueue = sendQueue;
682
- this.thinking = new ThinkingIndicator(thread);
683
- this.planCard = new PlanCard(thread, sendQueue);
684
- this.usage = new UsageMessage(thread, sendQueue);
685
- }
686
- isFirstEvent = true;
687
- hasPlanCard = false;
688
- thinking;
689
- planCard;
690
- usage;
691
- async onNewPrompt() {
692
- this.isFirstEvent = true;
693
- this.hasPlanCard = false;
694
- this.thinking.dismiss();
695
- this.thinking.reset();
696
- }
697
- async onThought() {
698
- await this._firstEventGuard();
699
- await this.thinking.show();
700
- }
701
- async onTextStart() {
702
- await this._firstEventGuard();
703
- this.thinking.dismiss();
704
- }
705
- async onToolCall() {
706
- await this._firstEventGuard();
707
- this.thinking.dismiss();
708
- this.thinking.reset();
709
- }
710
- async onPlan(entries, verbosity) {
711
- await this._firstEventGuard();
712
- this.thinking.dismiss();
713
- this.hasPlanCard = true;
714
- if (verbosity) this.planCard.setVerbosity(verbosity);
715
- this.planCard.update(entries);
716
- }
717
- async sendUsage(usage, verbosity = "medium") {
718
- await this.usage.send(usage, verbosity);
719
- }
720
- async cleanup() {
721
- this.thinking.dismiss();
722
- this.planCard.destroy();
723
- if (this.hasPlanCard) {
724
- await this.planCard.finalize();
725
- }
726
- }
727
- async _firstEventGuard() {
728
- if (!this.isFirstEvent) return;
729
- this.isFirstEvent = false;
730
- await this.usage.delete();
731
- }
732
- };
733
-
734
- // src/adapters/discord/skill-command-manager.ts
735
- var DISCORD_MSG_LIMIT = 1900;
736
- function buildSkillContent(commands) {
737
- const sorted = [...commands].sort((a, b) => a.name.localeCompare(b.name));
738
- const header = "**Available Skills**\n";
739
- const lines = sorted.map((c) => `\`/${c.name}\``);
740
- let content = header;
741
- for (const line of lines) {
742
- const candidate = content + "\n" + line;
743
- if (candidate.length > DISCORD_MSG_LIMIT) break;
744
- content = candidate;
745
- }
746
- return content;
747
- }
748
- var SkillCommandManager = class {
749
- constructor(sendQueue, sessionManager) {
750
- this.sendQueue = sendQueue;
751
- this.sessionManager = sessionManager;
752
- }
753
- messages = /* @__PURE__ */ new Map();
754
- async send(sessionId, thread, commands) {
755
- if (!this.messages.has(sessionId)) {
756
- const record = this.sessionManager.getSessionRecord(sessionId);
757
- const platform = record?.platform;
758
- if (platform?.skillMsgId) {
759
- try {
760
- const msg = await thread.messages.fetch(platform.skillMsgId);
761
- if (msg) this.messages.set(sessionId, msg);
762
- } catch {
763
- }
764
- }
765
- }
766
- if (commands.length === 0) {
767
- await this.cleanup(sessionId);
768
- return;
769
- }
770
- const content = buildSkillContent(commands);
771
- const existingMsg = this.messages.get(sessionId);
772
- if (existingMsg) {
773
- try {
774
- await existingMsg.edit({ content });
775
- return;
776
- } catch (err) {
777
- const msg = err instanceof Error ? err.message : "";
778
- if (msg.includes("Unknown Message") || msg.includes("10008")) {
779
- this.messages.delete(sessionId);
780
- } else {
781
- return;
782
- }
783
- }
784
- }
785
- try {
786
- const msg = await this.sendQueue.enqueue(
787
- () => thread.send({ content }),
788
- { type: "other" }
789
- );
790
- if (!msg) return;
791
- this.messages.set(sessionId, msg);
792
- const record = this.sessionManager.getSessionRecord(sessionId);
793
- if (record) {
794
- await this.sessionManager.patchRecord(sessionId, {
795
- platform: { ...record.platform, skillMsgId: msg.id }
796
- });
797
- }
798
- try {
799
- await msg.pin();
800
- } catch (err) {
801
- log.warn({ err, sessionId }, "[SkillCommandManager] Failed to pin skill message");
802
- }
803
- } catch (err) {
804
- log.error({ err, sessionId }, "[SkillCommandManager] Failed to send skill commands");
805
- }
806
- }
807
- async cleanup(sessionId) {
808
- const msg = this.messages.get(sessionId);
809
- this.messages.delete(sessionId);
810
- if (msg) {
811
- try {
812
- await msg.edit({ content: "*Session ended*" });
813
- await msg.unpin();
814
- } catch {
815
- }
816
- }
817
- const record = this.sessionManager.getSessionRecord(sessionId);
818
- if (record) {
819
- const platform = record.platform;
820
- if (platform && typeof platform === "object" && "threadId" in platform) {
821
- const { skillMsgId: _removed, ...rest } = platform;
822
- await this.sessionManager.patchRecord(sessionId, { platform: rest });
823
- }
824
- }
825
- }
826
- };
827
-
828
- // src/adapters/discord/permissions.ts
829
- import { ActionRowBuilder, ButtonBuilder, ButtonStyle } from "discord.js";
830
- import { nanoid } from "nanoid";
831
- var PermissionHandler = class {
832
- constructor(guildId, getSession, sendNotification) {
833
- this.guildId = guildId;
834
- this.getSession = getSession;
835
- this.sendNotification = sendNotification;
836
- }
837
- pending = /* @__PURE__ */ new Map();
838
- async sendPermissionRequest(session, request, thread) {
839
- const callbackKey = nanoid(8);
840
- this.pending.set(callbackKey, {
841
- sessionId: session.id,
842
- requestId: request.id,
843
- options: request.options.map((o) => ({ id: o.id, isAllow: o.isAllow })),
844
- guildId: this.guildId,
845
- channelId: thread.id
846
- });
847
- const row = new ActionRowBuilder();
848
- for (const option of request.options) {
849
- const emoji = option.isAllow ? "\u2705" : "\u274C";
850
- row.addComponents(
851
- new ButtonBuilder().setCustomId(`p:${callbackKey}:${option.id}`).setLabel(`${emoji} ${option.label}`).setStyle(option.isAllow ? ButtonStyle.Success : ButtonStyle.Danger)
852
- );
853
- }
854
- let messageId;
855
- try {
856
- const msg = await thread.send({
857
- content: `\u{1F510} **Permission request:**
858
-
859
- ${request.description}`,
860
- components: [row]
861
- });
862
- messageId = msg.id;
863
- const pendingEntry = this.pending.get(callbackKey);
864
- if (pendingEntry) pendingEntry.messageId = messageId;
865
- } catch (err) {
866
- log.warn({ err, sessionId: session.id }, "[PermissionHandler] Failed to send permission request");
867
- return;
868
- }
869
- const deepLink = buildDeepLink(this.guildId, thread.id, messageId);
870
- void this.sendNotification({
871
- sessionId: session.id,
872
- sessionName: session.name,
873
- type: "permission",
874
- summary: request.description,
875
- deepLink
876
- });
877
- }
878
- async handleButtonInteraction(interaction) {
879
- const data = interaction.customId;
880
- if (!data.startsWith("p:")) return false;
881
- const parts = data.split(":");
882
- if (parts.length < 3) return false;
883
- const [, callbackKey, optionId] = parts;
884
- const pending = this.pending.get(callbackKey);
885
- if (!pending) {
886
- try {
887
- await interaction.reply({ content: "\u274C Permission request expired", ephemeral: true });
888
- } catch {
889
- }
890
- return true;
891
- }
892
- const session = this.getSession(pending.sessionId);
893
- const option = pending.options.find((o) => o.id === optionId);
894
- const isAllow = option?.isAllow ?? false;
895
- log.info(
896
- { requestId: pending.requestId, optionId, isAllow },
897
- "[PermissionHandler] Permission responded"
898
- );
899
- if (session?.permissionGate.requestId === pending.requestId) {
900
- session.permissionGate.resolve(optionId);
901
- }
902
- this.pending.delete(callbackKey);
903
- try {
904
- await interaction.reply({ content: "\u2705 Responded", ephemeral: true });
905
- } catch {
906
- }
907
- try {
908
- await interaction.message.edit({ components: [] });
909
- } catch {
910
- }
911
- return true;
912
- }
913
- };
914
-
915
- // src/adapters/discord/commands/index.ts
916
- import { SlashCommandBuilder } from "discord.js";
917
-
918
- // src/adapters/discord/commands/menu.ts
919
- import {
920
- ActionRowBuilder as ActionRowBuilder2,
921
- ButtonBuilder as ButtonBuilder2,
922
- ButtonStyle as ButtonStyle2
923
- } from "discord.js";
924
- function buildMenuKeyboard() {
925
- const row1 = new ActionRowBuilder2().addComponents(
926
- new ButtonBuilder2().setCustomId("m:new").setLabel("\u{1F195} New Session").setStyle(ButtonStyle2.Primary),
927
- new ButtonBuilder2().setCustomId("m:sessions").setLabel("\u{1F4CB} Sessions").setStyle(ButtonStyle2.Secondary),
928
- new ButtonBuilder2().setCustomId("m:status").setLabel("\u{1F4CA} Status").setStyle(ButtonStyle2.Secondary)
929
- );
930
- const row2 = new ActionRowBuilder2().addComponents(
931
- new ButtonBuilder2().setCustomId("m:agents").setLabel("\u{1F916} Agents").setStyle(ButtonStyle2.Secondary),
932
- new ButtonBuilder2().setCustomId("m:settings").setLabel("\u2699\uFE0F Settings").setStyle(ButtonStyle2.Secondary),
933
- new ButtonBuilder2().setCustomId("m:integrate").setLabel("\u{1F517} Integrate").setStyle(ButtonStyle2.Secondary)
934
- );
935
- const row3 = new ActionRowBuilder2().addComponents(
936
- new ButtonBuilder2().setCustomId("m:tts").setLabel("\u{1F50A} TTS").setStyle(ButtonStyle2.Secondary),
937
- new ButtonBuilder2().setCustomId("m:restart").setLabel("\u{1F504} Restart").setStyle(ButtonStyle2.Secondary),
938
- new ButtonBuilder2().setCustomId("m:update").setLabel("\u2B06\uFE0F Update").setStyle(ButtonStyle2.Secondary),
939
- new ButtonBuilder2().setCustomId("m:help").setLabel("\u2753 Help").setStyle(ButtonStyle2.Secondary),
940
- new ButtonBuilder2().setCustomId("m:doctor").setLabel("\u{1FA7A} Doctor").setStyle(ButtonStyle2.Secondary)
941
- );
942
- return [row1, row2, row3];
943
- }
944
- async function handleMenu(interaction, _adapter) {
945
- await interaction.reply({
946
- content: "**OpenACP Menu**\nChoose an action:",
947
- components: buildMenuKeyboard(),
948
- ephemeral: true
949
- });
950
- }
951
- async function handleHelp(interaction, _adapter) {
952
- await interaction.reply({
953
- content: `\u{1F4D6} **OpenACP Help**
954
-
955
- \u{1F680} **Getting Started**
956
- Use \u{1F195} New Session or \`/new\` to start coding with AI.
957
- Each session gets its own forum thread \u2014 chat there to work with the agent.
958
-
959
- \u{1F4A1} **Common Commands**
960
- \`/new [agent] [workspace]\` \u2014 Create new session
961
- \`/newchat\` \u2014 New chat, same agent & workspace
962
- \`/cancel\` \u2014 Cancel current session
963
- \`/status\` \u2014 Show session or system status
964
- \`/sessions\` \u2014 List all sessions
965
- \`/agents\` \u2014 Browse & install agents
966
- \`/install <name>\` \u2014 Install an agent
967
-
968
- \u2699\uFE0F **System**
969
- \`/restart\` \u2014 Restart OpenACP
970
- \`/update\` \u2014 Update to latest version
971
- \`/integrate\` \u2014 Manage agent integrations
972
- \`/settings\` \u2014 View configuration
973
- \`/menu\` \u2014 Show action menu
974
-
975
- \u{1F512} **Session Options**
976
- \`/dangerous\` \u2014 Toggle dangerous mode (auto-approve permissions)
977
- \`/tts\` \u2014 Toggle Text to Speech (on/off/next message)
978
- \`/handoff\` \u2014 Continue session in your terminal
979
- \`/clear\` \u2014 Clear assistant session history
980
-
981
- \u{1FA7A} **Diagnostics**
982
- \`/doctor\` \u2014 Run system diagnostics`,
983
- ephemeral: true
984
- });
985
- }
986
- async function handleClear(interaction, adapter) {
987
- await interaction.deferReply({ ephemeral: true });
988
- if (!adapter.getAssistantSessionId()) {
989
- await interaction.editReply("\u26A0\uFE0F Assistant is not available.");
990
- return;
991
- }
992
- try {
993
- await adapter.respawnAssistant();
994
- await interaction.editReply("\u2705 Assistant history cleared.");
995
- } catch (err) {
996
- const message = err instanceof Error ? err.message : String(err);
997
- await interaction.editReply(`\u274C Failed to clear: \`${message}\``);
998
- }
999
- }
1000
- async function handleMenuButton(interaction, adapter) {
1001
- const { customId } = interaction;
1002
- try {
1003
- await interaction.deferUpdate();
1004
- } catch {
1005
- }
1006
- try {
1007
- switch (customId) {
1008
- case "m:new": {
1009
- const { handleNew: handleNew2 } = await import("./new-session-FEO4J4VU.js");
1010
- await interaction.followUp({ content: "Use `/new` to create a new session.", ephemeral: true });
1011
- break;
1012
- }
1013
- case "m:sessions": {
1014
- const { handleSessions: handleSessions2 } = await import("./session-IUSI7P5S.js");
1015
- await showSessionsList(interaction, adapter);
1016
- break;
1017
- }
1018
- case "m:status": {
1019
- await showGlobalStatus(interaction, adapter);
1020
- break;
1021
- }
1022
- case "m:agents": {
1023
- const { showAgentsList } = await import("./agents-QO7DKARJ.js");
1024
- await showAgentsList(interaction, adapter);
1025
- break;
1026
- }
1027
- case "m:settings": {
1028
- const { showSettingsInfo } = await import("./settings-RQPAM4KC.js");
1029
- await showSettingsInfo(interaction, adapter);
1030
- break;
1031
- }
1032
- case "m:integrate": {
1033
- await interaction.followUp({ content: "Use `/integrate` to manage integrations.", ephemeral: true });
1034
- break;
1035
- }
1036
- case "m:restart": {
1037
- const { handleRestart: handleRestart2 } = await import("./admin-6SYB6XCZ.js");
1038
- if (!adapter.core.requestRestart) {
1039
- await interaction.followUp({ content: "\u26A0\uFE0F Restart not available.", ephemeral: true });
1040
- } else {
1041
- await interaction.followUp({ content: "\u{1F504} Restarting OpenACP...", ephemeral: true });
1042
- await new Promise((r) => setTimeout(r, 500));
1043
- await adapter.core.requestRestart();
1044
- }
1045
- break;
1046
- }
1047
- case "m:update": {
1048
- await interaction.followUp({ content: "\u26A0\uFE0F Update not implemented yet. Run `npm install -g @openacp/cli@latest` in your terminal.", ephemeral: true });
1049
- break;
1050
- }
1051
- case "m:help": {
1052
- await interaction.followUp({ content: "Use `/help` for command reference.", ephemeral: true });
1053
- break;
1054
- }
1055
- case "m:doctor": {
1056
- const { runDoctorInline } = await import("./doctor-OLYBO3V3.js");
1057
- await runDoctorInline(interaction, adapter);
1058
- break;
1059
- }
1060
- case "m:tts": {
1061
- const channelId = interaction.channelId;
1062
- const session = adapter.core.sessionManager.getSessionByThread("discord", channelId);
1063
- if (!session) {
1064
- await interaction.followUp({ content: "\u26A0\uFE0F No active session in this channel. Use `/tts` inside a session thread.", ephemeral: true });
1065
- } else {
1066
- const newMode = session.voiceMode === "on" ? "off" : "on";
1067
- session.setVoiceMode(newMode);
1068
- const msg = newMode === "on" ? "\u{1F50A} Text to Speech enabled for this session." : "\u{1F507} Text to Speech disabled.";
1069
- await interaction.followUp({ content: msg, ephemeral: true });
1070
- }
1071
- break;
1072
- }
1073
- default:
1074
- log.warn({ customId }, "[discord-menu] Unhandled menu button");
1075
- }
1076
- } catch (err) {
1077
- log.error({ err, customId }, "[discord-menu] Menu button handler failed");
1078
- try {
1079
- await interaction.followUp({ content: `\u274C Action failed: ${err instanceof Error ? err.message : String(err)}`, ephemeral: true });
1080
- } catch {
1081
- }
1082
- }
1083
- }
1084
- async function showGlobalStatus(interaction, adapter) {
1085
- const sessions = adapter.core.sessionManager.listSessions("discord");
1086
- const active = sessions.filter((s) => s.status === "active" || s.status === "initializing");
1087
- await interaction.followUp({
1088
- content: `**OpenACP Status**
1089
- Active sessions: ${active.length}
1090
- Total sessions: ${sessions.length}`,
1091
- ephemeral: true
1092
- });
1093
- }
1094
- async function showSessionsList(interaction, adapter) {
1095
- const allRecords = adapter.core.sessionManager.listRecords();
1096
- if (allRecords.length === 0) {
1097
- await interaction.followUp({ content: "No sessions found.", ephemeral: true });
1098
- return;
1099
- }
1100
- const STATUS_EMOJI = {
1101
- active: "\u{1F7E2}",
1102
- initializing: "\u{1F7E1}",
1103
- finished: "\u2705",
1104
- error: "\u274C",
1105
- cancelled: "\u26D4"
1106
- };
1107
- const STATUS_ORDER = {
1108
- active: 0,
1109
- initializing: 1,
1110
- error: 2,
1111
- finished: 3,
1112
- cancelled: 4
1113
- };
1114
- allRecords.sort(
1115
- (a, b) => (STATUS_ORDER[a.status] ?? 5) - (STATUS_ORDER[b.status] ?? 5)
1116
- );
1117
- const lines = allRecords.slice(0, 20).map((r) => {
1118
- const emoji = STATUS_EMOJI[r.status] || "\u26AA";
1119
- const name = r.name?.trim() || `${r.agentName} session`;
1120
- return `${emoji} **${name}** \`[${r.status}]\``;
1121
- });
1122
- const truncated = allRecords.length > 20 ? `
1123
-
1124
- *...and ${allRecords.length - 20} more*` : "";
1125
- await interaction.followUp({
1126
- content: `**Sessions: ${allRecords.length}**
1127
-
1128
- ${lines.join("\n")}${truncated}`,
1129
- ephemeral: true
1130
- });
1131
- }
1132
-
1133
- // src/adapters/discord/commands/integrate.ts
1134
- async function handleIntegrate(interaction, _adapter) {
1135
- await interaction.deferReply({ ephemeral: true });
1136
- await interaction.editReply(
1137
- "\u{1F517} **Integrations**\n\nIntegration management via Discord is not yet implemented.\n\nUse the CLI: `openacp integrate`"
1138
- );
1139
- }
1140
- async function handleIntegrateButton(interaction, _adapter) {
1141
- log.debug({ customId: interaction.customId }, "[discord-integrate] Button stub called");
1142
- try {
1143
- await interaction.reply({
1144
- content: "\u{1F517} Integration management via Discord is not yet implemented. Use the CLI: `openacp integrate`",
1145
- ephemeral: true
1146
- });
1147
- } catch {
1148
- }
1149
- }
1150
-
1151
- // src/adapters/discord/commands/router.ts
1152
- async function handleSlashCommand(interaction, adapter) {
1153
- const { commandName } = interaction;
1154
- try {
1155
- switch (commandName) {
1156
- case "new":
1157
- await handleNew(interaction, adapter);
1158
- break;
1159
- case "newchat":
1160
- await handleNewChat(interaction, adapter);
1161
- break;
1162
- case "cancel":
1163
- await handleCancel(interaction, adapter);
1164
- break;
1165
- case "status":
1166
- await handleStatus(interaction, adapter);
1167
- break;
1168
- case "sessions":
1169
- await handleSessions(interaction, adapter);
1170
- break;
1171
- case "agents":
1172
- await handleAgents(interaction, adapter);
1173
- break;
1174
- case "install":
1175
- await handleInstall(interaction, adapter);
1176
- break;
1177
- case "menu":
1178
- await handleMenu(interaction, adapter);
1179
- break;
1180
- case "help":
1181
- await handleHelp(interaction, adapter);
1182
- break;
1183
- case "dangerous":
1184
- await handleDangerous(interaction, adapter);
1185
- break;
1186
- case "restart":
1187
- await handleRestart(interaction, adapter);
1188
- break;
1189
- case "update":
1190
- await handleUpdate(interaction, adapter);
1191
- break;
1192
- case "integrate":
1193
- await handleIntegrate(interaction, adapter);
1194
- break;
1195
- case "settings":
1196
- await handleSettings(interaction, adapter);
1197
- break;
1198
- case "doctor":
1199
- await handleDoctor(interaction, adapter);
1200
- break;
1201
- case "handoff":
1202
- await handleHandoff(interaction, adapter);
1203
- break;
1204
- case "clear":
1205
- await handleClear(interaction, adapter);
1206
- break;
1207
- case "tts":
1208
- await handleTTS(interaction, adapter);
1209
- break;
1210
- case "verbosity":
1211
- await handleVerbosity(interaction, adapter);
1212
- break;
1213
- default:
1214
- log.warn({ commandName }, "[discord-router] Unknown slash command");
1215
- if (!interaction.replied && !interaction.deferred) {
1216
- await interaction.reply({
1217
- content: `Unknown command: /${commandName}`,
1218
- ephemeral: true
1219
- });
1220
- }
1221
- }
1222
- } catch (err) {
1223
- log.error(
1224
- { err, commandName },
1225
- "[discord-router] Slash command handler failed"
1226
- );
1227
- try {
1228
- const errMsg = `\u274C Command failed: ${err instanceof Error ? err.message : String(err)}`;
1229
- if (interaction.deferred) {
1230
- await interaction.editReply(errMsg);
1231
- } else if (!interaction.replied) {
1232
- await interaction.reply({ content: errMsg, ephemeral: true });
1233
- }
1234
- } catch {
1235
- }
1236
- }
1237
- }
1238
- async function setupButtonCallbacks(interaction, adapter) {
1239
- const { customId } = interaction;
1240
- try {
1241
- if (customId.startsWith("a:dismiss:")) {
1242
- try {
1243
- await interaction.update({ components: [] });
1244
- } catch {
1245
- }
1246
- return;
1247
- }
1248
- if (customId.startsWith("a:")) {
1249
- const { getAction, removeAction } = await import("./action-detect-P7ZE4NEM.js");
1250
- const actionId = customId.slice(2);
1251
- const action = getAction(actionId);
1252
- if (!action) {
1253
- await interaction.reply({
1254
- content: "\u274C Action expired.",
1255
- ephemeral: true
1256
- });
1257
- return;
1258
- }
1259
- removeAction(actionId);
1260
- if (action.type === "new_session") {
1261
- await executeNewSession(
1262
- interaction,
1263
- adapter,
1264
- action.agent,
1265
- action.workspace
1266
- );
1267
- } else if (action.type === "cancel_session") {
1268
- await executeCancelSession(interaction, adapter);
1269
- }
1270
- return;
1271
- }
1272
- if (customId.startsWith("d:")) {
1273
- await handleDangerousButton(interaction, adapter);
1274
- return;
1275
- }
1276
- if (customId.startsWith("v:")) {
1277
- await handleTTSButton(interaction, adapter);
1278
- return;
1279
- }
1280
- if (customId.startsWith("m:new:")) {
1281
- await handleNewSessionButton(interaction, adapter);
1282
- return;
1283
- }
1284
- if (customId === "m:cleanup" || customId.startsWith("m:cleanup:")) {
1285
- await handleCleanupButton(interaction, adapter);
1286
- return;
1287
- }
1288
- if (customId === "m:doctor" || customId.startsWith("m:doctor:")) {
1289
- await handleDoctorButton(interaction, adapter);
1290
- return;
1291
- }
1292
- if (customId.startsWith("ag:")) {
1293
- await handleAgentButton(interaction, adapter);
1294
- return;
1295
- }
1296
- if (customId.startsWith("na:")) {
1297
- const agentKey = customId.slice(3);
1298
- try {
1299
- await interaction.deferReply({ ephemeral: true });
1300
- } catch {
1301
- }
1302
- await executeNewSession(interaction, adapter, agentKey, void 0);
1303
- return;
1304
- }
1305
- if (customId.startsWith("s:")) {
1306
- await handleSettingsButton(interaction, adapter);
1307
- return;
1308
- }
1309
- if (customId.startsWith("i:")) {
1310
- await handleIntegrateButton(interaction, adapter);
1311
- return;
1312
- }
1313
- if (customId.startsWith("m:")) {
1314
- await handleMenuButton(interaction, adapter);
1315
- return;
1316
- }
1317
- log.warn({ customId }, "[discord-router] Unhandled button interaction");
1318
- } catch (err) {
1319
- log.error({ err, customId }, "[discord-router] Button callback failed");
1320
- try {
1321
- const errMsg = `\u274C Action failed: ${err instanceof Error ? err.message : String(err)}`;
1322
- if (!interaction.replied && !interaction.deferred) {
1323
- await interaction.reply({ content: errMsg, ephemeral: true });
1324
- } else {
1325
- await interaction.followUp({ content: errMsg, ephemeral: true });
1326
- }
1327
- } catch {
1328
- }
1329
- }
1330
- }
1331
- async function executeNewSession(interaction, adapter, agentName, workspace) {
1332
- const { executeNewSession: doExecute } = await import("./new-session-FEO4J4VU.js");
1333
- await doExecute(interaction, adapter, agentName, workspace);
1334
- }
1335
- async function executeCancelSession(interaction, adapter) {
1336
- const { executeCancelSession: doCancel } = await import("./session-IUSI7P5S.js");
1337
- await doCancel(interaction, adapter);
1338
- }
1339
-
1340
- // src/adapters/discord/commands/index.ts
1341
- var SLASH_COMMANDS = [
1342
- new SlashCommandBuilder().setName("new").setDescription("Create a new agent session").addStringOption(
1343
- (o) => o.setName("agent").setDescription("Agent to use").setRequired(false)
1344
- ).addStringOption(
1345
- (o) => o.setName("workspace").setDescription("Workspace directory").setRequired(false)
1346
- ),
1347
- new SlashCommandBuilder().setName("newchat").setDescription(
1348
- "New chat in current thread, inheriting agent and workspace"
1349
- ),
1350
- new SlashCommandBuilder().setName("cancel").setDescription("Cancel the current session"),
1351
- new SlashCommandBuilder().setName("status").setDescription("Show session or global status"),
1352
- new SlashCommandBuilder().setName("sessions").setDescription("List all sessions"),
1353
- new SlashCommandBuilder().setName("agents").setDescription("List available agents"),
1354
- new SlashCommandBuilder().setName("install").setDescription("Install an agent by name").addStringOption(
1355
- (o) => o.setName("name").setDescription("Agent name to install").setRequired(true)
1356
- ),
1357
- new SlashCommandBuilder().setName("menu").setDescription("Show the action menu"),
1358
- new SlashCommandBuilder().setName("help").setDescription("Show help"),
1359
- new SlashCommandBuilder().setName("dangerous").setDescription("Toggle dangerous mode for the current session"),
1360
- new SlashCommandBuilder().setName("restart").setDescription("Restart OpenACP"),
1361
- new SlashCommandBuilder().setName("update").setDescription("Update to the latest version"),
1362
- new SlashCommandBuilder().setName("integrate").setDescription("Manage agent integrations"),
1363
- new SlashCommandBuilder().setName("settings").setDescription("Show configuration settings"),
1364
- new SlashCommandBuilder().setName("doctor").setDescription("Run system diagnostics"),
1365
- new SlashCommandBuilder().setName("handoff").setDescription("Generate a terminal resume command for this session"),
1366
- new SlashCommandBuilder().setName("clear").setDescription("Reset the assistant session"),
1367
- new SlashCommandBuilder().setName("tts").setDescription("Toggle Text to Speech for the current session").addStringOption(
1368
- (o) => o.setName("mode").setDescription(
1369
- "on = persistent, off = disable, empty = next message only"
1370
- ).setRequired(false).addChoices({ name: "on", value: "on" }, { name: "off", value: "off" })
1371
- ),
1372
- new SlashCommandBuilder().setName("verbosity").setDescription("Set display verbosity level").addStringOption(
1373
- (o) => o.setName("level").setDescription("Verbosity level").setRequired(true).addChoices(
1374
- { name: "low \u2014 minimal, title only", value: "low" },
1375
- { name: "medium \u2014 balanced (default)", value: "medium" },
1376
- { name: "high \u2014 full detail with content", value: "high" }
1377
- )
1378
- )
1379
- ];
1380
- async function registerSlashCommands(guild) {
1381
- await guild.commands.set(SLASH_COMMANDS.map((cmd) => cmd.toJSON()));
1382
- }
1383
-
1384
- // src/adapters/discord/assistant.ts
1385
- async function spawnAssistant(core, threadId) {
1386
- const config = core.configManager.get();
1387
- log.info({ agent: config.defaultAgent, threadId }, "[discord-assistant] Creating assistant session...");
1388
- const session = await core.createSession({
1389
- channelId: "discord",
1390
- agentName: config.defaultAgent,
1391
- workingDirectory: core.configManager.resolveWorkspace(),
1392
- initialName: "Assistant"
1393
- // Prevent auto-naming from triggering after system prompt
1394
- });
1395
- session.threadId = threadId;
1396
- log.info({ sessionId: session.id, threadId }, "[discord-assistant] Assistant agent spawned");
1397
- const systemPrompt = buildAssistantSystemPrompt(core);
1398
- const ready = session.enqueuePrompt(systemPrompt).then(() => {
1399
- log.info({ sessionId: session.id }, "[discord-assistant] System prompt completed");
1400
- }).catch((err) => {
1401
- log.warn({ err }, "[discord-assistant] System prompt failed");
1402
- });
1403
- return { session, ready };
1404
- }
1405
- function buildWelcomeMessage(core) {
1406
- const allRecords = core.sessionManager.listRecords();
1407
- const activeCount = allRecords.filter(
1408
- (r) => r.status === "active" || r.status === "initializing"
1409
- ).length;
1410
- const errorCount = allRecords.filter((r) => r.status === "error").length;
1411
- const totalCount = allRecords.length;
1412
- const installedEntries = core.agentCatalog.getInstalledEntries();
1413
- const agents = Object.keys(installedEntries);
1414
- const config = core.configManager.get();
1415
- const defaultAgent = config.defaultAgent;
1416
- const agentList = agents.map((a) => `${a}${a === defaultAgent ? " (default)" : ""}`).join(", ");
1417
- if (totalCount === 0) {
1418
- return `\u{1F44B} **OpenACP is ready!**
1419
-
1420
- No sessions yet. Use \`/new\` to start, or ask me anything!
1421
-
1422
- Agents: ${agentList}`;
1423
- }
1424
- if (errorCount > 0) {
1425
- return `\u{1F44B} **OpenACP is ready!**
1426
-
1427
- \u{1F4CA} ${activeCount} active, ${errorCount} errors / ${totalCount} total
1428
- \u26A0\uFE0F ${errorCount} session${errorCount > 1 ? "s have" : " has"} errors \u2014 ask me to check.
1429
-
1430
- Agents: ${agentList}`;
1431
- }
1432
- return `\u{1F44B} **OpenACP is ready!**
1433
-
1434
- \u{1F4CA} ${activeCount} active / ${totalCount} total
1435
- Agents: ${agentList}`;
1436
- }
1437
- function buildAssistantSystemPrompt(core) {
1438
- const config = core.configManager.get();
1439
- const allRecords = core.sessionManager.listRecords();
1440
- const activeCount = allRecords.filter(
1441
- (r) => r.status === "active" || r.status === "initializing"
1442
- ).length;
1443
- const statusCounts = /* @__PURE__ */ new Map();
1444
- for (const r of allRecords) {
1445
- statusCounts.set(r.status, (statusCounts.get(r.status) ?? 0) + 1);
1446
- }
1447
- const topicBreakdown = Array.from(statusCounts.entries()).map(([status, count]) => `${status}: ${count}`).join(", ") || "none";
1448
- const installedEntries = core.agentCatalog.getInstalledEntries();
1449
- const installedAgents = Object.keys(installedEntries);
1450
- const agentNames = installedAgents.length ? installedAgents.join(", ") : Object.keys(config.agents).join(", ");
1451
- const availableItems = core.agentCatalog.getAvailable();
1452
- const availableAgentCount = availableItems.filter((i) => !i.installed).length;
1453
- return `You are the OpenACP Assistant \u2014 a helpful guide for managing AI coding sessions on Discord.
1454
-
1455
- ## Current State
1456
- - Active sessions: ${activeCount} / ${allRecords.length} total
1457
- - Sessions by status: ${topicBreakdown}
1458
- - Installed agents: ${agentNames}
1459
- - Available in ACP Registry: ${availableAgentCount} more agents (use \`/agents\` to browse)
1460
- - Default agent: ${config.defaultAgent}
1461
- - Workspace base directory: ${config.workspace.baseDir}
1462
- - Platform: Discord
1463
-
1464
- ## Discord Context
1465
- - Each session gets its own forum thread in the OpenACP sessions channel
1466
- - Users interact with sessions by chatting in those threads
1467
- - Slash commands: /new, /cancel, /status, /sessions, /agents, /install, /menu, /help, /dangerous, /restart, /update, /integrate, /settings, /doctor, /handoff, /clear
1468
-
1469
- ## Action Playbook
1470
-
1471
- ### Create Session
1472
- - The workspace is the project directory where the agent will work (read, write, execute code). It should be a specific project folder like \`~/code/my-project\` or \`${config.workspace.baseDir}/my-app\`.
1473
- - Ask which agent to use (if multiple are installed). Installed: ${agentNames}
1474
- - Ask which project directory to use as workspace. Suggest \`${config.workspace.baseDir}\` as the base.
1475
- - Create via: \`openacp api new <agent> <workspace>\`
1476
-
1477
- ### Browse & Install Agents
1478
- - Guide users to \`/agents\` command to see all available agents
1479
- - For CLI users: \`openacp agents install <name>\`
1480
- - Some agents need login/setup after install \u2014 guide users to \`openacp agents info <name>\`
1481
- - To run agent CLI for login: \`openacp agents run <name> -- <args>\`
1482
-
1483
- ### Check Status / List Sessions
1484
- - Run \`openacp api status\` for active sessions overview
1485
- - Run \`openacp api topics\` for full list with statuses
1486
-
1487
- ### Cancel Session
1488
- - Run \`openacp api status\` to see what's active
1489
- - If 1 active session \u2192 ask user to confirm \u2192 \`openacp api cancel <id>\`
1490
- - If multiple \u2192 list them, ask user which one to cancel
1491
-
1492
- ### Troubleshoot
1493
- - Run \`openacp api health\` + \`openacp api status\` to diagnose
1494
- - Small issue (stuck session) \u2192 suggest cancel + create new
1495
- - Big issue (system-level) \u2192 suggest restart, ask for confirmation first
1496
-
1497
- ### Cleanup Old Sessions
1498
- - Run \`openacp api topics --status finished,error\` to see what can be cleaned
1499
- - Report the count, ask user to confirm
1500
- - Execute: \`openacp api cleanup --status <statuses>\`
1501
-
1502
- ### Configuration
1503
- - View: \`openacp config\`
1504
- - Update: \`openacp config set <key> <value>\`
1505
-
1506
- ### Restart / Update
1507
- - Always ask for confirmation \u2014 these are disruptive actions
1508
-
1509
- ### Toggle Dangerous Mode
1510
- - Run \`openacp api dangerous <id> on|off\`
1511
- - Explain: dangerous mode auto-approves all permission requests
1512
-
1513
- ## CLI Commands Reference
1514
- \`\`\`bash
1515
- # Session management
1516
- openacp api status # List active sessions
1517
- openacp api session <id> # Session detail
1518
- openacp api new <agent> <workspace> # Create new session
1519
- openacp api send <id> "prompt text" # Send prompt to session
1520
- openacp api cancel <id> # Cancel session
1521
- openacp api dangerous <id> on|off # Toggle dangerous mode
1522
-
1523
- # Topic management
1524
- openacp api topics # List all topics
1525
- openacp api cleanup # Cleanup finished topics
1526
-
1527
- # Agent management
1528
- openacp agents # List installed + available agents
1529
- openacp agents install <name> # Install agent from ACP Registry
1530
- openacp agents uninstall <name> # Remove agent
1531
- openacp agents info <name> # Show details & setup guide
1532
- openacp agents run <name> -- <args> # Run agent CLI (for login, etc.)
1533
-
1534
- # System
1535
- openacp api health # System health
1536
- openacp config # Edit config (interactive)
1537
- openacp config set <key> <value> # Update config value
1538
- openacp api restart # Restart daemon
1539
- \`\`\`
1540
-
1541
- ## Guidelines
1542
- - NEVER show \`openacp api ...\` commands to users. These are internal tools for YOU to run silently.
1543
- - Run \`openacp api ...\` commands yourself for everything you can. Only guide users to Discord slash commands/buttons when needed.
1544
- - When creating sessions: guide user through agent + workspace choice conversationally, then run the command yourself.
1545
- - Destructive actions (cancel active session, restart, cleanup) \u2192 always ask user to confirm first.
1546
- - Respond in the same language the user uses.
1547
- - Format responses for Discord: use **bold**, \`code\`, keep it concise.
1548
- - When you don't know something, check with the relevant \`openacp api\` command first before answering.
1549
-
1550
- ## Product Reference
1551
- ${PRODUCT_GUIDE}`;
1552
- }
1553
-
1554
- // src/adapters/discord/media.ts
1555
- var MAX_DOWNLOAD_SIZE = 100 * 1024 * 1024;
1556
- var DISCORD_UPLOAD_LIMIT = 25 * 1024 * 1024;
1557
- function isAttachmentTooLarge(size) {
1558
- return size > DISCORD_UPLOAD_LIMIT;
1559
- }
1560
- function buildFallbackText(attachments) {
1561
- return attachments.map((att) => {
1562
- const label = att.type === "image" ? "Photo" : att.type === "audio" ? "Audio" : "File";
1563
- return `[${label}: ${att.fileName}]`;
1564
- }).join(" ");
1565
- }
1566
- async function downloadDiscordAttachment(url, fileName) {
1567
- try {
1568
- const response = await fetch(url);
1569
- if (!response.ok) {
1570
- log.warn({ url, status: response.status, fileName }, "[discord-media] Download failed");
1571
- return null;
1572
- }
1573
- const buffer = Buffer.from(await response.arrayBuffer());
1574
- if (buffer.length > MAX_DOWNLOAD_SIZE) {
1575
- log.warn({ fileName, size: buffer.length }, "[discord-media] File exceeds download size cap");
1576
- return null;
1577
- }
1578
- return buffer;
1579
- } catch (err) {
1580
- log.error({ err, url, fileName }, "[discord-media] Download error");
1581
- return null;
1582
- }
1583
- }
1584
-
1585
- // src/adapters/discord/adapter.ts
1586
- var DiscordAdapter = class extends ChannelAdapter {
1587
- client;
1588
- discordConfig;
1589
- sendQueue;
1590
- toolTracker;
1591
- draftManager;
1592
- skillManager;
1593
- permissionHandler;
1594
- sessionTrackers = /* @__PURE__ */ new Map();
1595
- get verbosity() {
1596
- return this.discordConfig.displayVerbosity ?? "medium";
1597
- }
1598
- guild;
1599
- forumChannel;
1600
- notificationChannel;
1601
- assistantSession = null;
1602
- assistantInitializing = false;
1603
- fileService;
1604
- constructor(core, config) {
1605
- super(core, config);
1606
- this.discordConfig = config;
1607
- this.client = new Client({
1608
- intents: [
1609
- GatewayIntentBits.Guilds,
1610
- GatewayIntentBits.GuildMessages,
1611
- GatewayIntentBits.MessageContent
1612
- ]
1613
- });
1614
- this.sendQueue = new DiscordSendQueue();
1615
- this.toolTracker = new ToolCallTracker(this.sendQueue);
1616
- this.draftManager = new DraftManager(this.sendQueue);
1617
- this.fileService = core.fileService;
1618
- this.client.rest.on("rateLimited", (info) => {
1619
- log.warn(
1620
- { route: info.route, timeToReset: info.timeToReset },
1621
- "[DiscordAdapter] Rate limited"
1622
- );
1623
- this.sendQueue.onRateLimited();
1624
- });
1625
- }
1626
- // ─── start ────────────────────────────────────────────────────────────────
1627
- start() {
1628
- return new Promise((resolve, reject) => {
1629
- this.client.once("ready", async () => {
1630
- try {
1631
- log.info(
1632
- { guildId: this.discordConfig.guildId },
1633
- "[DiscordAdapter] Client ready, initializing..."
1634
- );
1635
- const guild = this.client.guilds.cache.get(this.discordConfig.guildId) ?? await this.client.guilds.fetch(this.discordConfig.guildId).catch(() => null);
1636
- if (!guild) {
1637
- throw new Error(`Guild not found: ${this.discordConfig.guildId}`);
1638
- }
1639
- this.guild = guild;
1640
- const saveConfig = (updates) => this.core.configManager.save(
1641
- updates
1642
- );
1643
- const { forumChannel, notificationChannel } = await ensureForums(
1644
- guild,
1645
- {
1646
- forumChannelId: this.discordConfig.forumChannelId,
1647
- notificationChannelId: this.discordConfig.notificationChannelId
1648
- },
1649
- saveConfig
1650
- );
1651
- this.forumChannel = forumChannel;
1652
- this.notificationChannel = notificationChannel;
1653
- this.skillManager = new SkillCommandManager(
1654
- this.sendQueue,
1655
- this.core.sessionManager
1656
- );
1657
- this.permissionHandler = new PermissionHandler(
1658
- guild.id,
1659
- (sessionId) => this.core.sessionManager.getSession(sessionId),
1660
- (notification) => this.sendNotification(notification)
1661
- );
1662
- await registerSlashCommands(guild);
1663
- this.setupInteractionHandler();
1664
- this.setupMessageHandler();
1665
- const welcomeMsg = buildWelcomeMessage(this.core);
1666
- try {
1667
- await this.notificationChannel.send(welcomeMsg);
1668
- } catch (err) {
1669
- log.warn(
1670
- { err },
1671
- "[DiscordAdapter] Failed to send welcome message"
1672
- );
1673
- }
1674
- await this.setupAssistant();
1675
- log.info("[DiscordAdapter] Initialization complete");
1676
- resolve();
1677
- } catch (err) {
1678
- log.error({ err }, "[DiscordAdapter] Initialization failed");
1679
- reject(err);
1680
- }
1681
- });
1682
- this.client.login(this.discordConfig.botToken).catch(reject);
1683
- });
1684
- }
1685
- // ─── stop ─────────────────────────────────────────────────────────────────
1686
- async stop() {
1687
- if (this.assistantSession) {
1688
- try {
1689
- await this.assistantSession.destroy();
1690
- } catch (err) {
1691
- log.warn(
1692
- { err },
1693
- "[DiscordAdapter] Failed to destroy assistant session"
1694
- );
1695
- }
1696
- this.assistantSession = null;
1697
- }
1698
- this.client.destroy();
1699
- log.info("[DiscordAdapter] Stopped");
1700
- }
1701
- // ─── Interaction handler ──────────────────────────────────────────────────
1702
- setupInteractionHandler() {
1703
- this.client.on("interactionCreate", async (interaction) => {
1704
- try {
1705
- if (interaction.isChatInputCommand()) {
1706
- await handleSlashCommand(interaction, this);
1707
- return;
1708
- }
1709
- if (interaction.isButton()) {
1710
- const handled = await this.permissionHandler.handleButtonInteraction(interaction);
1711
- if (!handled) {
1712
- await setupButtonCallbacks(interaction, this);
1713
- }
1714
- }
1715
- } catch (err) {
1716
- log.error({ err }, "[DiscordAdapter] interactionCreate handler error");
1717
- }
1718
- });
1719
- }
1720
- // ─── Message handler ──────────────────────────────────────────────────────
1721
- setupMessageHandler() {
1722
- this.client.on("messageCreate", async (message) => {
1723
- try {
1724
- if (message.author.bot) return;
1725
- if (!message.guild) return;
1726
- if (message.guild.id !== this.guild.id) return;
1727
- if (!message.channel.isThread()) return;
1728
- const threadId = message.channel.id;
1729
- const userId = message.author.id;
1730
- let text = message.content;
1731
- log.debug(
1732
- {
1733
- threadId,
1734
- userId,
1735
- text: text.slice(0, 50),
1736
- attachmentCount: message.attachments.size
1737
- },
1738
- "[DiscordAdapter] messageCreate received"
1739
- );
1740
- if (!text && message.attachments.size === 0) return;
1741
- const sessionId = this.core.sessionManager.getSessionByThread("discord", threadId)?.id ?? "unknown";
1742
- if (message.attachments.size > 0) {
1743
- log.info(
1744
- {
1745
- sessionId,
1746
- attachments: message.attachments.map((a) => ({
1747
- name: a.name,
1748
- size: a.size,
1749
- contentType: a.contentType,
1750
- url: a.url?.slice(0, 80)
1751
- }))
1752
- },
1753
- "[discord-media] Processing incoming attachments"
1754
- );
1755
- }
1756
- const attachments = await this.processIncomingAttachments(
1757
- message,
1758
- sessionId
1759
- );
1760
- if (!text && attachments.length > 0) {
1761
- text = buildFallbackText(attachments);
1762
- }
1763
- if (!text && attachments.length === 0 && message.attachments.size > 0) {
1764
- try {
1765
- await message.reply("Failed to process attachment(s)");
1766
- } catch {
1767
- }
1768
- return;
1769
- }
1770
- if (this.discordConfig.assistantThreadId && threadId === this.discordConfig.assistantThreadId) {
1771
- if (this.assistantSession && text) {
1772
- await this.assistantSession.enqueuePrompt(
1773
- text,
1774
- attachments.length > 0 ? attachments : void 0
1775
- );
1776
- }
1777
- return;
1778
- }
1779
- await this.core.handleMessage({
1780
- channelId: "discord",
1781
- threadId,
1782
- userId,
1783
- text,
1784
- ...attachments.length > 0 ? { attachments } : {}
1785
- });
1786
- } catch (err) {
1787
- log.error({ err }, "[DiscordAdapter] messageCreate handler error");
1788
- }
1789
- });
1790
- }
1791
- // ─── Assistant ────────────────────────────────────────────────────────────
1792
- async setupAssistant() {
1793
- let threadId = this.discordConfig.assistantThreadId;
1794
- if (threadId) {
1795
- try {
1796
- const existing = this.guild.channels.cache.get(threadId) ?? await this.guild.channels.fetch(threadId);
1797
- if (existing && existing.isThread()) {
1798
- await ensureUnarchived(
1799
- existing
1800
- );
1801
- log.info(
1802
- { threadId },
1803
- "[DiscordAdapter] Reusing existing assistant thread"
1804
- );
1805
- } else {
1806
- log.warn(
1807
- { threadId },
1808
- "[DiscordAdapter] Assistant thread not found, recreating..."
1809
- );
1810
- threadId = null;
1811
- }
1812
- } catch {
1813
- log.warn(
1814
- { threadId },
1815
- "[DiscordAdapter] Assistant thread inaccessible, recreating..."
1816
- );
1817
- threadId = null;
1818
- }
1819
- }
1820
- if (!threadId) {
1821
- const thread = await createSessionThread(this.forumChannel, "Assistant");
1822
- threadId = thread.id;
1823
- await this.core.configManager.save({
1824
- channels: { discord: { assistantThreadId: thread.id } }
1825
- });
1826
- log.info({ threadId }, "[DiscordAdapter] Created assistant thread");
1827
- }
1828
- this.assistantInitializing = true;
1829
- try {
1830
- const { session, ready } = await spawnAssistant(this.core, threadId);
1831
- this.assistantSession = session;
1832
- ready.finally(() => {
1833
- this.assistantInitializing = false;
1834
- });
1835
- } catch (err) {
1836
- this.assistantInitializing = false;
1837
- log.error({ err }, "[DiscordAdapter] Failed to spawn assistant");
1838
- }
1839
- }
1840
- async respawnAssistant() {
1841
- if (this.assistantSession) {
1842
- try {
1843
- await this.assistantSession.destroy();
1844
- } catch {
1845
- }
1846
- this.assistantSession = null;
1847
- }
1848
- await this.setupAssistant();
1849
- }
1850
- // ─── Incoming media ──────────────────────────────────────────────────
1851
- async processIncomingAttachments(message, sessionId) {
1852
- if (message.attachments.size === 0) return [];
1853
- const isVoiceMessage = message.flags.has(MessageFlags.IsVoiceMessage);
1854
- const results = await Promise.allSettled(
1855
- message.attachments.map(async (discordAtt) => {
1856
- const buffer = await downloadDiscordAttachment(
1857
- discordAtt.url,
1858
- discordAtt.name ?? "attachment"
1859
- );
1860
- if (!buffer) return null;
1861
- let data = buffer;
1862
- let fileName = discordAtt.name ?? "attachment";
1863
- let mimeType = discordAtt.contentType ?? "application/octet-stream";
1864
- if (isVoiceMessage && mimeType.includes("ogg")) {
1865
- try {
1866
- data = await this.fileService.convertOggToWav(buffer);
1867
- fileName = "voice.wav";
1868
- mimeType = "audio/wav";
1869
- } catch (err) {
1870
- log.warn(
1871
- { err },
1872
- "[discord-media] OGG\u2192WAV conversion failed, saving original"
1873
- );
1874
- }
1875
- }
1876
- return this.fileService.saveFile(sessionId, fileName, data, mimeType);
1877
- })
1878
- );
1879
- const rejected = results.filter((r) => r.status === "rejected");
1880
- if (rejected.length > 0) {
1881
- log.warn(
1882
- { rejected: rejected.map((r) => r.reason) },
1883
- "[discord-media] Some attachments failed"
1884
- );
1885
- }
1886
- const saved = results.filter(
1887
- (r) => r.status === "fulfilled"
1888
- ).map((r) => r.value).filter((att) => att !== null);
1889
- log.info(
1890
- { count: saved.length, files: saved.map((a) => a.fileName) },
1891
- "[discord-media] Attachments processed"
1892
- );
1893
- return saved;
1894
- }
1895
- // ─── Helper: resolve thread ───────────────────────────────────────────────
1896
- async getThread(sessionId) {
1897
- const session = this.core.sessionManager.getSession(sessionId);
1898
- const threadId = session?.threadId;
1899
- if (!threadId) {
1900
- log.warn({ sessionId }, "[DiscordAdapter] No threadId for session");
1901
- return null;
1902
- }
1903
- try {
1904
- const channel = this.guild.channels.cache.get(threadId) ?? await this.guild.channels.fetch(threadId);
1905
- if (channel && channel.isThread()) return channel;
1906
- log.warn(
1907
- { sessionId, threadId },
1908
- "[DiscordAdapter] Channel is not a thread"
1909
- );
1910
- return null;
1911
- } catch (err) {
1912
- log.warn(
1913
- { err, sessionId, threadId },
1914
- "[DiscordAdapter] Failed to fetch thread"
1915
- );
1916
- return null;
1917
- }
1918
- }
1919
- // ─── Helper: get or create activity tracker ──────────────────────────────
1920
- getOrCreateTracker(sessionId, thread) {
1921
- if (!this.sessionTrackers.has(sessionId)) {
1922
- this.sessionTrackers.set(
1923
- sessionId,
1924
- new ActivityTracker(thread, this.sendQueue)
1925
- );
1926
- }
1927
- return this.sessionTrackers.get(sessionId);
1928
- }
1929
- // --- MessageHandlers for dispatchMessage ---
1930
- messageHandlers = {
1931
- onThought: async (ctx, _content) => {
1932
- const tracker = this.getOrCreateTracker(ctx.sessionId, ctx.thread);
1933
- await tracker.onThought();
1934
- },
1935
- onText: async (ctx, content) => {
1936
- const tracker = this.getOrCreateTracker(ctx.sessionId, ctx.thread);
1937
- await tracker.onTextStart();
1938
- const draft = this.draftManager.getOrCreate(ctx.sessionId, ctx.thread);
1939
- draft.append(content.text);
1940
- this.draftManager.appendText(ctx.sessionId, content.text);
1941
- },
1942
- onToolCall: async (ctx, content) => {
1943
- const meta = content.metadata ?? {};
1944
- const toolName = String(meta.name ?? content.text ?? "Tool");
1945
- const toolKind = String(meta.kind ?? "other");
1946
- const noiseAction = evaluateNoise(toolName, toolKind, meta.rawInput);
1947
- if (noiseAction === "hide" && this.verbosity !== "high") return;
1948
- if (noiseAction === "collapse" && this.verbosity === "low") return;
1949
- const tracker = this.getOrCreateTracker(ctx.sessionId, ctx.thread);
1950
- await tracker.onToolCall();
1951
- await this.draftManager.finalize(
1952
- ctx.sessionId,
1953
- ctx.thread,
1954
- ctx.isAssistant
1955
- );
1956
- await this.toolTracker.trackNewCall(
1957
- ctx.sessionId,
1958
- ctx.thread,
1959
- {
1960
- id: String(meta.id ?? ""),
1961
- name: toolName,
1962
- kind: meta.kind,
1963
- status: String(meta.status ?? "running"),
1964
- content: meta.content,
1965
- rawInput: meta.rawInput,
1966
- viewerLinks: meta.viewerLinks,
1967
- viewerFilePath: meta.viewerFilePath,
1968
- displaySummary: meta.displaySummary,
1969
- displayTitle: meta.displayTitle,
1970
- displayKind: meta.displayKind
1971
- },
1972
- this.verbosity
1973
- );
1974
- },
1975
- onToolUpdate: async (ctx, content) => {
1976
- const meta = content.metadata ?? {};
1977
- await this.toolTracker.updateCall(
1978
- ctx.sessionId,
1979
- {
1980
- id: String(meta.id ?? ""),
1981
- name: content.text || String(meta.name ?? ""),
1982
- kind: meta.kind,
1983
- status: String(meta.status ?? "completed"),
1984
- content: meta.content,
1985
- rawInput: meta.rawInput,
1986
- viewerLinks: meta.viewerLinks,
1987
- viewerFilePath: meta.viewerFilePath,
1988
- displaySummary: meta.displaySummary,
1989
- displayTitle: meta.displayTitle,
1990
- displayKind: meta.displayKind
1991
- },
1992
- this.verbosity
1993
- );
1994
- },
1995
- onPlan: async (ctx, content) => {
1996
- const entries = content.metadata?.entries ?? [];
1997
- const tracker = this.getOrCreateTracker(ctx.sessionId, ctx.thread);
1998
- await tracker.onPlan(entries, this.verbosity);
1999
- },
2000
- onUsage: async (ctx, content) => {
2001
- await this.draftManager.finalize(
2002
- ctx.sessionId,
2003
- ctx.thread,
2004
- ctx.isAssistant
2005
- );
2006
- const meta = content.metadata ?? {};
2007
- const tracker = this.getOrCreateTracker(ctx.sessionId, ctx.thread);
2008
- await tracker.sendUsage(
2009
- {
2010
- tokensUsed: meta.tokensUsed,
2011
- contextSize: meta.contextSize,
2012
- cost: meta.cost
2013
- },
2014
- this.verbosity
2015
- );
2016
- try {
2017
- const deepLink = buildDeepLink(this.guild.id, ctx.thread.id);
2018
- await this.sendNotification({
2019
- sessionId: ctx.sessionId,
2020
- type: "completed",
2021
- summary: content.text || "Session completed",
2022
- deepLink
2023
- });
2024
- } catch {
2025
- }
2026
- },
2027
- onSessionEnd: async (ctx, _content) => {
2028
- await this.draftManager.finalize(
2029
- ctx.sessionId,
2030
- ctx.thread,
2031
- ctx.isAssistant
2032
- );
2033
- const tracker = this.getOrCreateTracker(ctx.sessionId, ctx.thread);
2034
- await tracker.cleanup();
2035
- this.toolTracker.cleanup(ctx.sessionId);
2036
- this.sessionTrackers.delete(ctx.sessionId);
2037
- await this.skillManager.cleanup(ctx.sessionId);
2038
- try {
2039
- await this.sendQueue.enqueue(
2040
- () => ctx.thread.send({ content: "\u2705 Done" }),
2041
- { type: "other" }
2042
- );
2043
- } catch {
2044
- }
2045
- },
2046
- onError: async (ctx, content) => {
2047
- await this.draftManager.finalize(
2048
- ctx.sessionId,
2049
- ctx.thread,
2050
- ctx.isAssistant
2051
- );
2052
- const tracker = this.getOrCreateTracker(ctx.sessionId, ctx.thread);
2053
- await tracker.cleanup();
2054
- this.toolTracker.cleanup(ctx.sessionId);
2055
- this.sessionTrackers.delete(ctx.sessionId);
2056
- try {
2057
- await this.sendQueue.enqueue(
2058
- () => ctx.thread.send({ content: `\u274C Error: ${content.text}` }),
2059
- { type: "other" }
2060
- );
2061
- } catch {
2062
- }
2063
- },
2064
- onAttachment: async (ctx, content) => {
2065
- if (!content.attachment) return;
2066
- const { attachment } = content;
2067
- await this.draftManager.finalize(
2068
- ctx.sessionId,
2069
- ctx.thread,
2070
- ctx.isAssistant
2071
- );
2072
- if (isAttachmentTooLarge(attachment.size)) {
2073
- log.warn(
2074
- {
2075
- sessionId: ctx.sessionId,
2076
- fileName: attachment.fileName,
2077
- size: attachment.size
2078
- },
2079
- "[discord-media] File too large (>25MB)"
2080
- );
2081
- try {
2082
- await this.sendQueue.enqueue(
2083
- () => ctx.thread.send({
2084
- content: `\u26A0\uFE0F File too large to send (${Math.round(attachment.size / 1024 / 1024)}MB): ${attachment.fileName}`
2085
- }),
2086
- { type: "other" }
2087
- );
2088
- } catch {
2089
- }
2090
- return;
2091
- }
2092
- try {
2093
- await this.sendQueue.enqueue(
2094
- () => ctx.thread.send({
2095
- files: [
2096
- { attachment: attachment.filePath, name: attachment.fileName }
2097
- ]
2098
- }),
2099
- { type: "other" }
2100
- );
2101
- if (attachment.type === "audio") {
2102
- const draft = this.draftManager.getDraft(ctx.sessionId);
2103
- if (draft) {
2104
- draft.stripPattern(/\[TTS\][\s\S]*?\[\/TTS\]/g).catch(() => {
2105
- });
2106
- }
2107
- }
2108
- } catch (err) {
2109
- log.error(
2110
- { err, sessionId: ctx.sessionId, fileName: attachment.fileName },
2111
- "[discord-media] Failed to send attachment"
2112
- );
2113
- }
2114
- },
2115
- onSystemMessage: async (ctx, content) => {
2116
- try {
2117
- await this.sendQueue.enqueue(
2118
- () => ctx.thread.send({ content: content.text }),
2119
- { type: "other" }
2120
- );
2121
- } catch {
2122
- }
2123
- }
2124
- };
2125
- // ─── sendMessage ──────────────────────────────────────────────────────────
2126
- async sendMessage(sessionId, content) {
2127
- if (this.assistantInitializing && this.assistantSession && sessionId === this.assistantSession.id) {
2128
- return;
2129
- }
2130
- const thread = await this.getThread(sessionId);
2131
- if (!thread) return;
2132
- await ensureUnarchived(thread);
2133
- const isAssistant = this.assistantSession != null && sessionId === this.assistantSession.id;
2134
- const ctx = { sessionId, thread, isAssistant };
2135
- await dispatchMessage(this.messageHandlers, ctx, content, this.verbosity);
2136
- }
2137
- // ─── sendPermissionRequest ────────────────────────────────────────────────
2138
- async sendPermissionRequest(sessionId, request) {
2139
- const session = this.core.sessionManager.getSession(sessionId);
2140
- if (!session) {
2141
- log.warn(
2142
- { sessionId },
2143
- "[DiscordAdapter] sendPermissionRequest: session not found"
2144
- );
2145
- return;
2146
- }
2147
- const thread = await this.getThread(sessionId);
2148
- if (!thread) return;
2149
- await this.permissionHandler.sendPermissionRequest(
2150
- session,
2151
- request,
2152
- thread
2153
- );
2154
- }
2155
- // ─── sendNotification ─────────────────────────────────────────────────────
2156
- async sendNotification(notification) {
2157
- if (!this.notificationChannel) return;
2158
- const typeIcon = {
2159
- completed: "\u2705",
2160
- error: "\u274C",
2161
- permission: "\u{1F510}",
2162
- input_required: "\u{1F4AC}"
2163
- };
2164
- const icon = typeIcon[notification.type] ?? "\u2139\uFE0F";
2165
- const name = notification.sessionName ? ` **${notification.sessionName}**` : "";
2166
- let text = `${icon}${name}: ${notification.summary}`;
2167
- if (notification.deepLink) {
2168
- text += `
2169
- ${notification.deepLink}`;
2170
- }
2171
- try {
2172
- await this.sendQueue.enqueue(
2173
- () => this.notificationChannel.send({ content: text }),
2174
- { type: "other" }
2175
- );
2176
- } catch (err) {
2177
- log.warn({ err }, "[DiscordAdapter] Failed to send notification");
2178
- }
2179
- }
2180
- // ─── createSessionThread ─────────────────────────────────────────────────
2181
- async createSessionThread(sessionId, name) {
2182
- const thread = await createSessionThread(this.forumChannel, name);
2183
- const session = this.core.sessionManager.getSession(sessionId);
2184
- if (session) {
2185
- session.threadId = thread.id;
2186
- }
2187
- const record = this.core.sessionManager.getSessionRecord(sessionId);
2188
- if (record) {
2189
- await this.core.sessionManager.patchRecord(sessionId, {
2190
- platform: { ...record.platform, threadId: thread.id }
2191
- });
2192
- }
2193
- return thread.id;
2194
- }
2195
- // ─── renameSessionThread ──────────────────────────────────────────────────
2196
- async renameSessionThread(sessionId, newName) {
2197
- const session = this.core.sessionManager.getSession(sessionId);
2198
- const threadId = session?.threadId;
2199
- if (!threadId) return;
2200
- await renameSessionThread(this.guild, threadId, newName);
2201
- }
2202
- // ─── deleteSessionThread ──────────────────────────────────────────────────
2203
- async deleteSessionThread(sessionId) {
2204
- const session = this.core.sessionManager.getSession(sessionId);
2205
- const threadId = session?.threadId;
2206
- if (!threadId) return;
2207
- await deleteSessionThread(this.guild, threadId);
2208
- }
2209
- // ─── sendSkillCommands ────────────────────────────────────────────────────
2210
- async sendSkillCommands(sessionId, commands) {
2211
- const thread = await this.getThread(sessionId);
2212
- if (!thread) return;
2213
- await this.skillManager.send(sessionId, thread, commands);
2214
- }
2215
- // ─── cleanupSkillCommands ─────────────────────────────────────────────────
2216
- async cleanupSkillCommands(sessionId) {
2217
- await this.skillManager.cleanup(sessionId);
2218
- }
2219
- // ─── Public helpers (for slash commands) ─────────────────────────────────
2220
- getForumChannel() {
2221
- return this.forumChannel;
2222
- }
2223
- getGuild() {
2224
- return this.guild;
2225
- }
2226
- getGuildId() {
2227
- return this.guild.id;
2228
- }
2229
- getAssistantSessionId() {
2230
- return this.assistantSession?.id ?? null;
2231
- }
2232
- getAssistantThreadId() {
2233
- return this.discordConfig.assistantThreadId;
2234
- }
2235
- };
2236
- export {
2237
- DiscordAdapter
2238
- };
2239
- //# sourceMappingURL=discord-OMC52Y54.js.map