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