@astrofoundry/astrogate 0.0.0-stage → 0.1.1

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 (97) hide show
  1. package/README.md +2 -2
  2. package/agents/foreman.md +27 -0
  3. package/cli/astro-install.sh +242 -0
  4. package/cli/astro.sh +449 -0
  5. package/cli/astro.test.ts +65 -0
  6. package/dist/bridge.js +9950 -0
  7. package/dist/claude.js +7899 -0
  8. package/dist/extensions/bridge/index.js +9937 -0
  9. package/dist/extensions/gate/index.js +286 -0
  10. package/dist/extensions/guard/index.js +364 -0
  11. package/dist/extensions/subagents/index.js +8458 -0
  12. package/extensions/bridge/admin.ts +86 -0
  13. package/extensions/bridge/approvals.ts +147 -0
  14. package/extensions/bridge/attachments.ts +65 -0
  15. package/extensions/bridge/chunk.ts +50 -0
  16. package/extensions/bridge/claude-run.test.ts +62 -0
  17. package/extensions/bridge/claude-run.ts +301 -0
  18. package/extensions/bridge/commands.ts +89 -0
  19. package/extensions/bridge/config.ts +263 -0
  20. package/extensions/bridge/conversations.ts +144 -0
  21. package/extensions/bridge/daemon.ts +60 -0
  22. package/extensions/bridge/discord.test.ts +547 -0
  23. package/extensions/bridge/gateway.ts +222 -0
  24. package/extensions/bridge/index.ts +951 -0
  25. package/extensions/bridge/launcher.ts +36 -0
  26. package/extensions/bridge/lifecycle.test.ts +78 -0
  27. package/extensions/bridge/open-work.ts +74 -0
  28. package/extensions/bridge/plugin.ts +172 -0
  29. package/extensions/bridge/quote.ts +39 -0
  30. package/extensions/bridge/reports.ts +65 -0
  31. package/extensions/bridge/rest.ts +217 -0
  32. package/extensions/bridge/setup.ts +218 -0
  33. package/extensions/gate/approvals.test.ts +40 -0
  34. package/extensions/gate/config.ts +110 -0
  35. package/extensions/gate/core.ts +114 -0
  36. package/extensions/gate/index.test.ts +202 -0
  37. package/extensions/gate/index.ts +114 -0
  38. package/extensions/gate/risky.ts +14 -0
  39. package/extensions/gate/types.ts +19 -0
  40. package/extensions/guard/config.test.ts +107 -0
  41. package/extensions/guard/config.ts +120 -0
  42. package/extensions/guard/defaults.ts +40 -0
  43. package/extensions/guard/index.test.ts +313 -0
  44. package/extensions/guard/index.ts +183 -0
  45. package/extensions/guard/rules.test.ts +118 -0
  46. package/extensions/guard/rules.ts +101 -0
  47. package/extensions/guard/types.ts +12 -0
  48. package/extensions/subagents/agents.test.ts +137 -0
  49. package/extensions/subagents/agents.ts +207 -0
  50. package/extensions/subagents/bundled.test.ts +29 -0
  51. package/extensions/subagents/child.test.ts +202 -0
  52. package/extensions/subagents/child.ts +367 -0
  53. package/extensions/subagents/index.test.ts +123 -0
  54. package/extensions/subagents/index.ts +352 -0
  55. package/extensions/subagents/pi-paths.test.ts +39 -0
  56. package/extensions/subagents/pi-paths.ts +58 -0
  57. package/extensions/subagents/render.ts +221 -0
  58. package/extensions/subagents/sessions.test.ts +32 -0
  59. package/extensions/subagents/sessions.ts +34 -0
  60. package/extensions/subagents/ticker.test.ts +40 -0
  61. package/extensions/subagents/ticker.ts +36 -0
  62. package/harness/claude/agents.ts +93 -0
  63. package/harness/claude/claude.test.ts +171 -0
  64. package/harness/claude/hook.ts +77 -0
  65. package/harness/claude/main.ts +122 -0
  66. package/harness/claude/mcp.ts +174 -0
  67. package/harness/claude/settings.ts +63 -0
  68. package/package.json +71 -4
  69. package/release.sha256 +95 -0
  70. package/release.sha256.sig +6 -0
  71. package/specialists/AGENTS.md +67 -0
  72. package/specialists/README.md +81 -0
  73. package/specialists/entry/specialist-cli.sh +22 -0
  74. package/specialists/entry/specialist-install.sh +861 -0
  75. package/specialists/entry/specialist-install.test.ts +305 -0
  76. package/specialists/lib/argv.ts +19 -0
  77. package/specialists/lib/audit.ts +20 -0
  78. package/specialists/lib/config.ts +27 -0
  79. package/specialists/lib/errors.ts +8 -0
  80. package/specialists/lib/flush.test.ts +21 -0
  81. package/specialists/lib/lib.test.ts +87 -0
  82. package/specialists/lib/lock.test.ts +42 -0
  83. package/specialists/lib/lock.ts +67 -0
  84. package/specialists/lib/main.ts +40 -0
  85. package/specialists/lib/output.ts +11 -0
  86. package/specialists/lib/paths.ts +22 -0
  87. package/specialists/lib/pinned.test.ts +55 -0
  88. package/specialists/lib/pinned.ts +67 -0
  89. package/specialists/lib/proc.ts +49 -0
  90. package/specialists/lib/repo.ts +198 -0
  91. package/specialists/lib/runtime.test.ts +81 -0
  92. package/specialists/lib/sanitize.ts +43 -0
  93. package/specialists/lib/secrets.ts +28 -0
  94. package/specialists/lib/ssh.ts +38 -0
  95. package/specialists/lib/tunnel.test.ts +44 -0
  96. package/specialists/lib/tunnel.ts +76 -0
  97. package/specialists/provision/provision.sh +96 -0
@@ -0,0 +1,951 @@
1
+ import { execFile } from "node:child_process";
2
+ import { existsSync, promises as fs, readFileSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { pathToFileURL } from "node:url";
5
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
6
+ import { getAgentDir, packageRoot } from "../subagents/pi-paths.ts";
7
+ import { loadConfig as loadSpecialists } from "../gate/config.ts";
8
+ import { APPROVAL_TASK_ENV, APPROVAL_TOKEN_ENV, APPROVAL_URL_ENV } from "../gate/core.ts";
9
+ import { type AgentConfig, defaultDirs, discoverAgents, resolveSkills } from "../subagents/agents.ts";
10
+ import { AGENT_ENV, type ChildSession, type DispatchDefaults, type Invocation, RunClock, type RunResult, childRemaining, currentDepth, finalOutput, isFailed, resultOutput, runAgent } from "../subagents/child.ts";
11
+ import { pruneSessions, sessionDirFor } from "../subagents/sessions.ts";
12
+ import { ApprovalServer, approvalCommand, type Ticket } from "./approvals.ts";
13
+ import { chunkMessage } from "./chunk.ts";
14
+ import { applyAdminCommand } from "./admin.ts";
15
+ import { CHANNEL_RULES, helpText, needsPrefixText, needsYou, parseCommand } from "./commands.ts";
16
+ import { ACTIVATION_ENV, type ChannelSettings, type DiscordConfig, allowedSpecialists, canUse, channelSpecialists, isOwner, loadClaudeToken, loadConfig, loadToken, saveConfig } from "./config.ts";
17
+ import { runClaude, runClaudeOneShot } from "./claude-run.ts";
18
+ import { type ConversationState, type ResolvedConversation, askingSpecialist, forgetStale, loadState, newConversationId, recordAnswer, replySpecialist, resolveConversation, saveState, sessionsRoot, startConversation } from "./conversations.ts";
19
+ import { describeImages, type DownloadedImages, downloadImages, type ImageAttachment, imageAttachments } from "./attachments.ts";
20
+ import { GatewayClient } from "./gateway.ts";
21
+ import { cancelledApprovalText, interruptedTaskText, readOpenWork, type OpenWork, type StopReason, writeOpenWork } from "./open-work.ts";
22
+ import { type Activity, type BridgeApi, type BridgePlugin, type Exec, type Interaction, type InvestigationRequest, type OneShotResult, PLUGIN_API_VERSION, type PluginFactory, type ThreadStyle, type TrackedWork } from "./plugin.ts";
23
+ import { isDue, readReportState } from "./reports.ts";
24
+ import { type Quote, type QuotedMessage, withQuotes } from "./quote.ts";
25
+ import { DiscordRest, type MessageComponent } from "./rest.ts";
26
+
27
+ const REACTION = { running: "⏳", waiting: "🔒", done: "✅", failed: "❌" } as const;
28
+ /** Answers longer than this go as a file attachment with a short summary. */
29
+ const ATTACHMENT_THRESHOLD = 6000;
30
+ /** Upper bound for one specialist run started from chat; the wrappers' own timeouts are shorter. */
31
+ const TASK_TIMEOUT_MINUTES = 30;
32
+ /** The pack agent that takes the owner's requests in the admin channel (`astro.foreman`). */
33
+ const FOREMAN = "foreman";
34
+
35
+ interface ToolCallPart {
36
+ type?: string;
37
+ name?: string;
38
+ arguments?: unknown;
39
+ }
40
+
41
+ /** One log line per new message: tool calls with their arguments, tool results, and assistant text lengths. */
42
+ function describeProgress(result: RunResult, seen: number): { lines: string[]; seen: number } {
43
+ const lines: string[] = [];
44
+ for (const message of result.messages.slice(seen)) {
45
+ if (message.role === "assistant") {
46
+ for (const part of message.content as ToolCallPart[]) {
47
+ if (part.type === "toolCall") lines.push(`tool ${part.name ?? "?"} ${JSON.stringify(part.arguments ?? {}).slice(0, 300)}`);
48
+ else if (part.type === "text") lines.push(`assistant text ${((part as { text?: string }).text ?? "").length} chars`);
49
+ }
50
+ } else if (message.role === "toolResult") {
51
+ const { toolName, isError } = message as { toolName?: string; isError?: boolean };
52
+ lines.push(`result ${toolName ?? "?"}${isError ? " (error)" : ""}`);
53
+ }
54
+ }
55
+ return { lines, seen: result.messages.length };
56
+ }
57
+
58
+ /** Reply for a failed run: the reason in one line, the specialist's last words if any, raw stderr only as an attachment. */
59
+ export function failureReply(result: RunResult): { text: string; attachment?: string } {
60
+ const reason = result.errorMessage?.trim() || (result.stopReason === "aborted" ? "the run was stopped" : `the specialist process exited with code ${result.exitCode}`);
61
+ const lastWords = finalOutput(result.messages).trim();
62
+ const text = lastWords.length > 0 ? `${reason}\n\nLast words of the specialist:\n${lastWords}` : reason;
63
+ const stderr = result.stderr.trim();
64
+ return stderr.length > 0 ? { text, attachment: stderr } : { text };
65
+ }
66
+
67
+ interface IncomingMessage {
68
+ id: string;
69
+ channel_id: string;
70
+ guild_id?: string;
71
+ content?: string;
72
+ author?: { id: string; bot?: boolean };
73
+ attachments?: QuotedMessage["attachments"];
74
+ /** The message this one replies to; Discord resolves it on every reply event. */
75
+ referenced_message?: QuotedMessage | null;
76
+ /** Copies of forwarded messages, without their authors. */
77
+ message_snapshots?: { message: QuotedMessage }[];
78
+ }
79
+
80
+ /** The release Pi has installed: the package this bridge runs from, read from disk so an update shows at once. */
81
+ const PACKAGE_JSON = join(packageRoot(), "package.json");
82
+
83
+ /** A thread-per-request channel without a site plugin: the request names the thread, and answers stay as they are. */
84
+ const PLAIN_THREADS: ThreadStyle = {
85
+ name: (request) => request.replace(/<@[!&]?\d+>/g, " ").replace(/\s+/g, " ").trim().slice(0, 100) || "request",
86
+ context: (threadId) => `Session: t${threadId}.`,
87
+ shape: (output) => ({ title: null, text: output, buttons: null }),
88
+ buttonTasks: {},
89
+ };
90
+
91
+ interface ActiveTask {
92
+ specialist: string;
93
+ channelId: string;
94
+ messageId: string;
95
+ userId: string;
96
+ startedAt: number;
97
+ conversation: ResolvedConversation;
98
+ images: ImageAttachment[];
99
+ abort?: AbortController;
100
+ /** The run's time limit, held while an approval request waits for an owner. */
101
+ clock?: RunClock;
102
+ placeholder?: string;
103
+ /** A task in a thread-per-request channel: the answer may rename the thread and carry buttons. */
104
+ threaded?: true;
105
+ }
106
+
107
+ /** How long a shutdown may spend editing Discord messages; launchd kills the job 20 s after the stop signal. */
108
+ const SHUTDOWN_BUDGET_MS = 8000;
109
+
110
+ function log(line: string): void {
111
+ process.stderr.write(`[astro-discord ${new Date().toISOString()}] ${line}\n`);
112
+ }
113
+
114
+ function errorText(err: unknown): string {
115
+ return err instanceof Error ? err.message : String(err);
116
+ }
117
+
118
+ function approvalButtons(ticketId: string, disabled = false, labels: { approve: string; deny: string } = { approve: "Approve", deny: "Deny" }): MessageComponent[] {
119
+ return [
120
+ {
121
+ type: 1,
122
+ components: [
123
+ { type: 2, style: 3, label: labels.approve, custom_id: `apr:${ticketId}:approve`, disabled },
124
+ { type: 2, style: 4, label: labels.deny, custom_id: `apr:${ticketId}:deny`, disabled },
125
+ ],
126
+ },
127
+ ];
128
+ }
129
+
130
+ function code(text: string): string {
131
+ return `\`${text.replace(/`/g, "'")}\``;
132
+ }
133
+
134
+ /** The site plugin of the installed pack. */
135
+ export function pluginPath(): string {
136
+ return join(getAgentDir(), "pack", "bridge", "index.js");
137
+ }
138
+
139
+ /** The model the installed pack sets for Claude Code (`harness.claude.model` in its pack.json), or null. */
140
+ function packClaudeModel(): string | null {
141
+ try {
142
+ const pack = JSON.parse(readFileSync(join(getAgentDir(), "pack", "pack.json"), "utf-8")) as { harness?: { claude?: { model?: unknown } } };
143
+ const model = pack.harness?.claude?.model;
144
+ return typeof model === "string" ? model : null;
145
+ } catch {
146
+ return null;
147
+ }
148
+ }
149
+
150
+ /** Loads the site plugin of the installed pack; the bridge runs without one when it is missing or broken. */
151
+ async function loadPlugin(api: BridgeApi): Promise<BridgePlugin | undefined> {
152
+ const path = pluginPath();
153
+ if (!existsSync(path)) {
154
+ log(`no site plugin at ${path}`);
155
+ return undefined;
156
+ }
157
+ try {
158
+ const loaded = (await import(pathToFileURL(path).href)) as { default?: unknown };
159
+ if (typeof loaded.default !== "function") throw new Error("its default export is not a function");
160
+ const plugin = await (loaded.default as PluginFactory)(api);
161
+ if (plugin.apiVersion !== PLUGIN_API_VERSION) throw new Error(`it speaks plugin API ${plugin.apiVersion}, this bridge ${PLUGIN_API_VERSION}`);
162
+ return plugin;
163
+ } catch (err) {
164
+ log(`site plugin ${path} not loaded: ${errorText(err)}`);
165
+ return undefined;
166
+ }
167
+ }
168
+
169
+ /** What differs between the bridge's two hosts. */
170
+ export interface BridgeHost {
171
+ /** Model and thinking level for Pi runs of agents that name none; a bridge outside Pi leaves them to Pi's settings. */
172
+ defaults: DispatchDefaults;
173
+ /** How to start Pi for a task. Inside Pi the default starts the same Pi; the daemon must name `pi`, because its own script is the bridge. */
174
+ invocation?: (args: string[]) => Invocation;
175
+ }
176
+
177
+ /** Bridge state for one host connected to Discord; it runs as its own process (`daemon.ts`) or inside a headless Pi (`astroDiscord`). */
178
+ export class Bridge {
179
+ private readonly rest: DiscordRest;
180
+ private readonly approvals: ApprovalServer;
181
+ private readonly queues = new Map<string, Promise<void>>();
182
+ private readonly active = new Map<string, ActiveTask>();
183
+ private readonly clockHolds = new Map<string, RunClock>();
184
+ private readonly approvalMessages = new Map<string, { channelId: string; messageId: string; userMessage: ActiveTask }>();
185
+ /** Work a plugin started that counts as open, by the plugin's key. */
186
+ private readonly tracked = new Map<string, TrackedWork>();
187
+ private gateway: GatewayClient | undefined;
188
+ private stopping = false;
189
+ private readonly reportsRunning = new Set<string>();
190
+ private reportTimer: NodeJS.Timeout | undefined;
191
+ private readonly since = new Date().toISOString();
192
+ private config: DiscordConfig;
193
+ private conversations: ConversationState;
194
+ private botUserId = "";
195
+ /** Thread id to parent channel id; null marks a plain channel. */
196
+ private readonly parents = new Map<string, string | null>();
197
+ private readonly host: BridgeHost;
198
+ private readonly token: string;
199
+ private plugin: BridgePlugin | undefined;
200
+
201
+ constructor(host: BridgeHost, config: DiscordConfig, token: string) {
202
+ this.host = host;
203
+ this.token = token;
204
+ this.config = config;
205
+ this.conversations = loadState();
206
+ this.rest = new DiscordRest(token);
207
+ this.approvals = new ApprovalServer(
208
+ {
209
+ onTicket: (t) => {
210
+ this.holdClock(t);
211
+ void this.askApproval(t).catch((err) => this.approvalFailed(t, err));
212
+ },
213
+ onClosed: (t) => this.releaseClock(t),
214
+ onExpired: (t) => void this.expireApproval(t).catch((err) => log(`approval ${t.id} expiry: ${errorText(err)}`)),
215
+ },
216
+ config.approvalTimeoutMinutes * 60_000,
217
+ );
218
+ }
219
+
220
+ /** What a site plugin may use; everything with state stays in this process. */
221
+ private api(): BridgeApi {
222
+ return {
223
+ apiVersion: PLUGIN_API_VERSION,
224
+ rest: this.rest,
225
+ corePackageJson: PACKAGE_JSON,
226
+ log,
227
+ config: () => this.config,
228
+ reloadConfig: () => {
229
+ this.refreshConfig();
230
+ return this.config;
231
+ },
232
+ stopping: () => this.stopping,
233
+ specialists: () => this.specialists().names,
234
+ hasAgent: (name) => this.specialists().agents.some((a) => a.name === name),
235
+ settingsFor: (channelId) => this.settingsFor(channelId),
236
+ runEntry: (service, caller, args, timeoutMs) => this.runEntry(service, caller, args, timeoutMs),
237
+ exec: this.execTool,
238
+ oneShot: (agentName, task) => this.oneShot(agentName, task),
239
+ investigate: (specialist, request) => this.investigateIn(specialist, request),
240
+ track: (key, work) => {
241
+ this.tracked.set(key, work);
242
+ this.saveOpenWork();
243
+ },
244
+ untrack: (key) => {
245
+ if (this.stopping) return;
246
+ this.tracked.delete(key);
247
+ this.saveOpenWork();
248
+ },
249
+ tracked: (key) => this.tracked.get(key),
250
+ activity: () => this.activity(),
251
+ archiveThread: (threadId) => this.archiveThread(threadId),
252
+ };
253
+ }
254
+
255
+ /** Specialists configured for this host, as short names. */
256
+ private specialists(): { names: string[]; agents: AgentConfig[] } {
257
+ const gate = loadSpecialists().config;
258
+ const agents = discoverAgents(process.cwd(), "user", defaultDirs()).agents;
259
+ const names = (gate?.specialists ?? []).map((s) => s.agent.replace(/^astro\./, "")).filter((short) => agents.some((a) => a.name === `astro.${short}`));
260
+ return { names, agents };
261
+ }
262
+
263
+ private refreshConfig(): void {
264
+ const loaded = loadConfig();
265
+ if (loaded.config) this.config = loaded.config;
266
+ else log(`config not reloaded: ${loaded.errors.join("; ")}`);
267
+ }
268
+
269
+ private threads(): ThreadStyle {
270
+ return this.plugin?.threads ?? PLAIN_THREADS;
271
+ }
272
+
273
+ private openWork(): OpenWork {
274
+ return {
275
+ since: this.since,
276
+ tasks: [
277
+ ...[...this.active.values()].map((t) => ({ specialist: t.specialist, channelId: t.channelId, messageId: t.messageId, ...(t.placeholder ? { placeholderId: t.placeholder } : {}) })),
278
+ ...[...this.tracked.values()].map((w) => ({ specialist: w.kind, channelId: w.channelId })),
279
+ ],
280
+ approvals: [...this.approvalMessages.entries()].map(([ticketId, a]) => ({ ticketId, channelId: a.channelId, messageId: a.messageId, userChannelId: a.userMessage.channelId, userMessageId: a.userMessage.messageId })),
281
+ };
282
+ }
283
+
284
+ /** Records what is open in Discord, so a restart can wait for it and the next process can close it after a crash. */
285
+ private saveOpenWork(): void {
286
+ try {
287
+ writeOpenWork(this.openWork());
288
+ } catch (err) {
289
+ log(`open work not saved: ${errorText(err)}`);
290
+ }
291
+ }
292
+
293
+ /** Tells Discord that open approvals were cancelled and running tasks interrupted, so no button is left dead without a word. */
294
+ private async closeOpen(work: OpenWork, reason: StopReason): Promise<void> {
295
+ const edits: Promise<unknown>[] = [];
296
+ for (const a of work.approvals) {
297
+ edits.push(this.rest.editMessage(a.channelId, a.messageId, cancelledApprovalText(reason), approvalButtons(a.ticketId, true)).catch(() => undefined));
298
+ edits.push(this.rest.removeOwnReaction(a.userChannelId, a.userMessageId, REACTION.waiting).catch(() => undefined));
299
+ }
300
+ for (const t of work.tasks) {
301
+ const text = interruptedTaskText(t.specialist, reason);
302
+ edits.push((t.placeholderId ? this.rest.editMessage(t.channelId, t.placeholderId, text) : this.rest.createMessage(t.channelId, { content: text, ...(t.messageId ? { replyTo: t.messageId } : {}) })).catch(() => undefined));
303
+ const messageId = t.messageId;
304
+ if (!messageId) continue;
305
+ edits.push(
306
+ this.rest
307
+ .removeOwnReaction(t.channelId, messageId, REACTION.running)
308
+ .then(() => this.rest.addReaction(t.channelId, messageId, REACTION.failed))
309
+ .catch(() => undefined),
310
+ );
311
+ }
312
+ await Promise.race([Promise.all(edits), new Promise((resolve) => setTimeout(resolve, SHUTDOWN_BUDGET_MS).unref())]);
313
+ }
314
+
315
+ /** Called from Pi's session_shutdown, which Pi awaits on SIGTERM before it exits. */
316
+ async shutdown(): Promise<void> {
317
+ if (this.stopping) return;
318
+ this.stopping = true;
319
+ clearInterval(this.reportTimer);
320
+ this.gateway?.stop();
321
+ const work = this.openWork();
322
+ for (const task of this.active.values()) task.abort?.abort();
323
+ if (work.tasks.length > 0 || work.approvals.length > 0) log(`shutdown: cancelling ${work.approvals.length} approval(s), interrupting ${work.tasks.length} task(s)`);
324
+ // Plugin work is answered by the plugin, through its interaction or its channel, instead of a generic message.
325
+ const answers = [...this.tracked.values()].map((w) => w.onShutdown?.().catch(() => undefined));
326
+ await Promise.all([this.closeOpen({ ...work, tasks: work.tasks.filter((t) => t.messageId !== undefined) }, "restart"), ...answers]);
327
+ this.approvals.close();
328
+ writeOpenWork({ since: this.since, tasks: [], approvals: [] });
329
+ }
330
+
331
+ async start(): Promise<void> {
332
+ const me = await this.rest.currentUser();
333
+ this.botUserId = me.id;
334
+ const leftover = readOpenWork();
335
+ if (leftover) {
336
+ log(`closing what the previous process left open: ${leftover.approvals.length} approval(s), ${leftover.tasks.length} task(s)`);
337
+ await this.closeOpen(leftover, "crash");
338
+ writeOpenWork({ since: this.since, tasks: [], approvals: [] });
339
+ }
340
+ this.plugin = await loadPlugin(this.api());
341
+ await this.approvals.listen();
342
+ const gateway = new GatewayClient({
343
+ token: this.token,
344
+ gatewayUrl: await this.rest.gatewayUrl(),
345
+ handlers: {
346
+ dispatch: (event, data) => void this.dispatch(event, data),
347
+ log,
348
+ },
349
+ });
350
+ gateway.start();
351
+ this.gateway = gateway;
352
+ void this.registerCommands();
353
+ await this.plugin?.start?.().catch((err) => log(`plugin start: ${errorText(err)}`));
354
+ const unknown = this.config.reports.filter((r) => !this.plugin?.reports?.[r.report]).map((r) => r.report);
355
+ if (unknown.length > 0) log(`reports without a plugin to post them: ${unknown.join(", ")}`);
356
+ // Checked every minute: each report decides whether today's is due, and the plugin runs its own checks.
357
+ this.reportTimer = setInterval(() => {
358
+ void this.maybeReports();
359
+ this.tickPlugin();
360
+ }, 60_000);
361
+ this.reportTimer.unref();
362
+ void this.maybeReports();
363
+ this.tickPlugin();
364
+ const plugin = this.plugin ? `; plugin ${this.plugin.name}` : "; no site plugin";
365
+ const { names, agents } = this.specialists();
366
+ log(`connected as ${me.username} (${me.id}); channels ${Object.keys(this.config.channels).join(", ")}; specialists ${names.join(", ")}; ${agents.length} agents; runner ${this.config.runner}${plugin}`);
367
+ }
368
+
369
+ private tickPlugin(): void {
370
+ try {
371
+ this.plugin?.tick?.();
372
+ } catch (err) {
373
+ log(`plugin tick: ${errorText(err)}`);
374
+ }
375
+ }
376
+
377
+ /** Registers the plugin's slash commands as the application's global list. */
378
+ private async registerCommands(): Promise<void> {
379
+ const commands = this.plugin?.commands?.() ?? [];
380
+ if (commands.length === 0) return;
381
+ try {
382
+ await this.rest.overwriteGlobalCommands(this.config.applicationId, commands);
383
+ log(`registered ${commands.length} slash command(s)`);
384
+ } catch (err) {
385
+ log(`slash command registration failed: ${errorText(err)}`);
386
+ }
387
+ }
388
+
389
+ private async dispatch(event: string, data: unknown): Promise<void> {
390
+ try {
391
+ if (event === "MESSAGE_CREATE") await this.onMessage(data as IncomingMessage);
392
+ else if (event === "INTERACTION_CREATE") await this.onInteraction(data as Interaction);
393
+ } catch (err) {
394
+ log(`${event} failed: ${errorText(err)}`);
395
+ }
396
+ }
397
+
398
+ /** Settings for a channel or, for a thread, of its parent channel; null when neither is configured. */
399
+ private async settingsFor(channelId: string): Promise<{ id: string; settings: ChannelSettings } | null> {
400
+ const direct = this.config.channels[channelId];
401
+ if (direct) return { id: channelId, settings: direct };
402
+ if (!this.parents.has(channelId)) {
403
+ try {
404
+ const channel = (await this.rest.channel(channelId)) as { parent_id?: string | null };
405
+ this.parents.set(channelId, channel.parent_id ?? null);
406
+ } catch {
407
+ // Not cached: a failed lookup asks again on the next message.
408
+ return null;
409
+ }
410
+ }
411
+ const parent = this.parents.get(channelId);
412
+ const inherited = parent ? this.config.channels[parent] : undefined;
413
+ return parent && inherited ? { id: parent, settings: inherited } : null;
414
+ }
415
+
416
+ private async onMessage(message: IncomingMessage): Promise<void> {
417
+ if (!message.author || message.author.bot) return;
418
+ this.refreshConfig();
419
+ const channel = await this.settingsFor(message.channel_id);
420
+ if (!channel) return;
421
+ const { names, agents } = this.specialists();
422
+ const present = channelSpecialists(channel.settings, names);
423
+ const userId = message.author.id;
424
+ const owner = isOwner(this.config, userId);
425
+ const inThread = channel.id !== message.channel_id;
426
+ const threaded = channel.settings.threads === true;
427
+ // An owner's message in the admin channel that names no specialist goes to the foreman, which delegates to the specialists.
428
+ const foreman = owner && channel.id === this.config.adminChannelId && agents.some((a) => a.name === `astro.${FOREMAN}`) ? FOREMAN : null;
429
+ const command = parseCommand(message.content ?? "", {
430
+ botUserId: this.botUserId,
431
+ specialists: present,
432
+ // In a request's thread the work continues without a mention.
433
+ trigger: threaded && inThread ? "always" : channel.settings.trigger,
434
+ repliedToBot: message.referenced_message?.author?.id === this.botUserId,
435
+ repliedSpecialist:
436
+ message.referenced_message?.author?.id === this.botUserId
437
+ ? (this.plugin?.replySpecialist?.(message.referenced_message.content ?? "") ?? replySpecialist(this.conversations, message.channel_id, message.referenced_message.id ?? ""))
438
+ : null,
439
+ askingSpecialist: askingSpecialist(this.conversations, message.channel_id, userId, Date.now()),
440
+ defaultAgent: foreman,
441
+ });
442
+ if (command.kind === "none") return;
443
+ const allowed = channel.settings.everyone ? present : allowedSpecialists(this.config, userId, present);
444
+ if (command.kind === "config") {
445
+ if (!owner || channel.id !== this.config.adminChannelId) return;
446
+ const result = applyAdminCommand(this.config, command.args, names);
447
+ if (result.config) {
448
+ saveConfig(result.config);
449
+ this.config = result.config;
450
+ log(`config changed by ${userId}: ${command.args.join(" ")}`);
451
+ }
452
+ await this.rest.createMessage(message.channel_id, { content: result.reply, replyTo: message.id });
453
+ return;
454
+ }
455
+ if (allowed.length === 0) return;
456
+ if (command.kind === "help") {
457
+ const extra = [...(foreman ? [`A message that names no specialist goes to \`${foreman}\`, which asks the specialists for you.`] : []), ...(this.plugin?.helpLines?.(allowed) ?? [])];
458
+ await this.rest.createMessage(message.channel_id, { content: helpText(allowed, present, owner, channel.settings.trigger, owner && channel.id === this.config.adminChannelId, extra), replyTo: message.id });
459
+ return;
460
+ }
461
+ if (command.kind === "status") {
462
+ const lines = [...this.active.values()].map((t) => `• ${t.specialist} for <@${t.userId}>, running ${Math.round((Date.now() - t.startedAt) / 1000)} s`);
463
+ await this.rest.createMessage(message.channel_id, { content: lines.length > 0 ? lines.join("\n") : "Nothing is running.", replyTo: message.id });
464
+ return;
465
+ }
466
+ if (command.kind === "needs-prefix") {
467
+ await this.rest.createMessage(message.channel_id, { content: needsPrefixText(allowed), replyTo: message.id });
468
+ return;
469
+ }
470
+ if (!channel.settings.everyone && !canUse(this.config, userId, command.specialist)) return;
471
+ const agent = agents.find((a) => a.name === `astro.${command.specialist}`);
472
+ if (!agent) return;
473
+ const now = Date.now();
474
+ let taskChannel = message.channel_id;
475
+ let taskMessage = message.id;
476
+ if (threaded && !inThread) {
477
+ try {
478
+ const thread = await this.rest.startThread(message.channel_id, message.id, this.threads().name(command.task, now));
479
+ const starter = await this.rest.createMessage(thread.id, { content: `🔎 **${command.specialist}** took the request. Answer its questions here; no mention needed.` });
480
+ taskChannel = thread.id;
481
+ taskMessage = starter.id;
482
+ } catch (err) {
483
+ log(`${command.specialist}: thread for ${message.id} failed: ${errorText(err)}`);
484
+ await this.rest.createMessage(message.channel_id, { content: "❌ Could not open a thread for this request; try again.", replyTo: message.id }).catch(() => undefined);
485
+ return;
486
+ }
487
+ }
488
+ this.conversations = forgetStale(this.conversations, now);
489
+ const conversation = resolveConversation(
490
+ this.conversations,
491
+ { channelId: taskChannel, specialist: command.specialist, repliedTo: message.referenced_message?.id, fresh: command.fresh || (threaded && !inThread), now },
492
+ () => newConversationId(command.specialist, now),
493
+ );
494
+ if (!conversation.resumed) this.conversations = startConversation(this.conversations, conversation.key, conversation.id, now);
495
+ saveState(this.conversations);
496
+ const known = conversation.resumed ? (this.conversations.conversations[conversation.key]?.messageIds ?? []) : [];
497
+ const quotes = this.quotesFor(message, (id) => known.includes(id));
498
+ const images = imageAttachments([message, ...quotes.map((q) => q.message)]);
499
+ const task: ActiveTask = { specialist: command.specialist, channelId: taskChannel, messageId: taskMessage, userId, startedAt: now, conversation, images, ...(threaded ? { threaded: true as const } : {}) };
500
+ const quoted = withQuotes(command.task, quotes);
501
+ const taskText = threaded ? `${this.threads().context(taskChannel, now, !inThread)}\n\n${quoted}` : quoted;
502
+ this.enqueue(command.specialist, () => this.runTask(agent, taskText, task));
503
+ }
504
+
505
+ /** Runs a task after every earlier task of that specialist. */
506
+ private enqueue(specialist: string, run: () => Promise<boolean>): Promise<boolean> {
507
+ let failed = true;
508
+ const previous = this.queues.get(specialist) ?? Promise.resolve();
509
+ const next = previous
510
+ .then(async () => {
511
+ failed = await run();
512
+ })
513
+ .catch((err) => log(`${specialist} run failed: ${errorText(err)}`));
514
+ this.queues.set(specialist, next);
515
+ return next.then(() => failed);
516
+ }
517
+
518
+ /** Every configured report that is due today and not already running; a report another one includes posts only through it. */
519
+ private async maybeReports(): Promise<void> {
520
+ if (this.stopping) return;
521
+ this.refreshConfig();
522
+ const reports = this.plugin?.reports ?? {};
523
+ const configured = new Set(this.config.reports.map((r) => r.report));
524
+ const included = new Set(
525
+ Object.entries(reports)
526
+ .filter(([name]) => configured.has(name))
527
+ .flatMap(([, definition]) => definition.includes ?? []),
528
+ );
529
+ for (const schedule of this.config.reports) {
530
+ const definition = reports[schedule.report];
531
+ if (!definition || this.reportsRunning.has(schedule.report) || included.has(schedule.report)) continue;
532
+ const { due, date } = isDue(schedule, readReportState(definition.stateFile), new Date(), definition.weekday);
533
+ if (!due) continue;
534
+ this.reportsRunning.add(schedule.report);
535
+ void definition
536
+ .run(schedule, date)
537
+ .catch((err) => log(`${schedule.report} report ${date}: ${errorText(err)}`))
538
+ .finally(() => this.reportsRunning.delete(schedule.report));
539
+ }
540
+ }
541
+
542
+ /** Runs a program with an argument list as this user, never through a shell; resolves even on failure. */
543
+ private readonly execTool: Exec = (file, args, options) =>
544
+ new Promise((resolve) => {
545
+ execFile(file, args, { timeout: options.timeoutMs, maxBuffer: 50 * 1024 * 1024, env: { ...process.env, ...options.env } }, (err, stdout, stderr) => {
546
+ const code = err ? (typeof (err as { code?: unknown }).code === "number" ? (err as { code: number }).code : 1) : 0;
547
+ resolve({ code, stdout: String(stdout), stderr: String(stderr) || (err ? err.message : "") });
548
+ });
549
+ });
550
+
551
+ /** One run of a tool-less agent; the task carries everything it may read. */
552
+ private async oneShot(agentName: string, task: string): Promise<OneShotResult> {
553
+ const agent = this.specialists().agents.find((a) => a.name === agentName);
554
+ if (!agent) return { failed: true, output: `${agentName} is not installed` };
555
+ if (this.config.runner === "claude") {
556
+ const model = packClaudeModel();
557
+ if (!model) return { failed: true, output: "the installed pack sets no Claude Code model (harness.claude.model)" };
558
+ let token: string;
559
+ try {
560
+ token = loadClaudeToken();
561
+ } catch (err) {
562
+ return { failed: true, output: errorText(err) };
563
+ }
564
+ return runClaudeOneShot({ systemPrompt: agent.systemPrompt, task, model, env: { [ACTIVATION_ENV]: "0", CLAUDE_CODE_OAUTH_TOKEN: token }, timeoutMs: (agent.timeoutMinutes ?? 5) * 60_000, cwd: process.cwd(), command: "claude" });
565
+ }
566
+ const { depth } = currentDepth();
567
+ const result = await runAgent({
568
+ agent,
569
+ skills: [],
570
+ task,
571
+ cwd: process.cwd(),
572
+ depth,
573
+ remaining: 0,
574
+ defaults: this.host.defaults,
575
+ invocation: this.host.invocation,
576
+ env: { [ACTIVATION_ENV]: "0" },
577
+ });
578
+ return isFailed(result) ? { failed: true, output: resultOutput(result) } : { failed: false, output: finalOutput(result.messages) };
579
+ }
580
+
581
+ /** A thread whose work is done leaves the channel list; a failure only costs the 7-day automatic archive. */
582
+ private async archiveThread(threadId: string): Promise<void> {
583
+ await this.rest.archiveThread(threadId).catch((err) => log(`discord: archiving thread ${threadId} failed: ${errorText(err)}`));
584
+ }
585
+
586
+ private activity(): Activity {
587
+ const running = [
588
+ ...[...this.active.values()].map((t) => `${t.specialist} task for <@${t.userId}>`),
589
+ ...(this.approvalMessages.size > 0 ? [`${this.approvalMessages.size} approval request(s)`] : []),
590
+ ...[...this.tracked.values()].map((w) => w.label),
591
+ ...[...this.reportsRunning].map((name) => `the ${name} report`),
592
+ ];
593
+ return { idle: running.length === 0, running };
594
+ }
595
+
596
+ /** Runs one specialist wrapper through the sudo entry point, without a model; rejects with the wrapper's stderr. */
597
+ private runEntry(service: string, caller: string, args: string[], timeoutMs: number): Promise<string> {
598
+ const gate = loadSpecialists().config;
599
+ if (!gate) return Promise.reject(new Error("specialists.json is missing"));
600
+ return new Promise<string>((resolve, reject) =>
601
+ execFile("/usr/bin/sudo", ["-n", "-u", gate.user, "-H", gate.entry, service, "--caller", caller, "--", ...args], { timeout: timeoutMs, maxBuffer: 20 * 1024 * 1024 }, (err, out, errOut) =>
602
+ err ? reject(new Error(errOut.trim() || err.message)) : resolve(out),
603
+ ),
604
+ );
605
+ }
606
+
607
+ /** An answer button in a thread-per-request channel: the same specialist gets the button's request in its thread, as if written there. */
608
+ private async onThreadButton(interaction: Interaction, request: string): Promise<void> {
609
+ const threadId = interaction.channel_id;
610
+ const message = interaction.message;
611
+ const userId = interaction.member?.user?.id ?? interaction.user?.id ?? "";
612
+ if (!threadId || !message || this.stopping) return;
613
+ const channel = await this.settingsFor(threadId);
614
+ const { names, agents } = this.specialists();
615
+ const specialist = channel?.settings.threads && channel.id !== threadId ? channelSpecialists(channel.settings, names)[0] : undefined;
616
+ const agent = specialist ? agents.find((a) => a.name === `astro.${specialist}`) : undefined;
617
+ if (!channel || !specialist || !agent || (!channel.settings.everyone && !canUse(this.config, userId, specialist))) {
618
+ await this.rest.ephemeralReply(interaction.id, interaction.token, "This button does not work here.");
619
+ return;
620
+ }
621
+ await this.rest.deferUpdate(interaction.id, interaction.token);
622
+ // One click per reply: the buttons go, and the next reply brings its own.
623
+ await this.rest.editMessage(threadId, message.id, message.content ?? "", []).catch(() => undefined);
624
+ const now = Date.now();
625
+ const conversation = resolveConversation(this.conversations, { channelId: threadId, specialist, fresh: false, now }, () => newConversationId(specialist, now));
626
+ if (!conversation.resumed) this.conversations = startConversation(this.conversations, conversation.key, conversation.id, now);
627
+ saveState(this.conversations);
628
+ const task: ActiveTask = { specialist, channelId: threadId, messageId: message.id, userId, startedAt: now, conversation, images: [], threaded: true };
629
+ const taskText = `${this.threads().context(threadId, now, false)}\n\n${request}`;
630
+ this.enqueue(specialist, () => this.runTask(agent, taskText, task));
631
+ }
632
+
633
+ /** Replied-to and forwarded messages to show the specialist; a bot message only when the resumed conversation does not already hold it. */
634
+ private quotesFor(message: IncomingMessage, inContext: (id: string) => boolean): Quote[] {
635
+ const quotes: Quote[] = [];
636
+ const replied = message.referenced_message;
637
+ if (replied) {
638
+ const mine = replied.author?.id === this.botUserId;
639
+ if (!mine) quotes.push({ label: `Replied-to message from ${replied.author?.username ?? replied.author?.id ?? "an unknown author"}`, message: replied });
640
+ else if (!(replied.id && inContext(replied.id))) quotes.push({ label: "My earlier message, which this message replies to", message: replied });
641
+ }
642
+ for (const snapshot of message.message_snapshots ?? []) quotes.push({ label: "Forwarded message", message: snapshot.message });
643
+ return quotes;
644
+ }
645
+
646
+ /**
647
+ * A plugin's task in a thread, such as an investigation of an alert. It
648
+ * waits behind any other task of that specialist and starts a fresh
649
+ * conversation that the owner can continue by writing in the thread.
650
+ */
651
+ private async investigateIn(specialist: string, request: InvestigationRequest): Promise<boolean> {
652
+ const agent = this.specialists().agents.find((a) => a.name === `astro.${specialist}`);
653
+ if (!agent) {
654
+ await this.rest.createMessage(request.threadId, { content: `❌ astro.${specialist} is not configured on this host.` }).catch(() => undefined);
655
+ return false;
656
+ }
657
+ const now = Date.now();
658
+ const conversation = resolveConversation(this.conversations, { channelId: request.threadId, specialist, fresh: true, now }, () => newConversationId(specialist, now));
659
+ this.conversations = startConversation(this.conversations, conversation.key, conversation.id, now);
660
+ saveState(this.conversations);
661
+ const task: ActiveTask = { specialist, channelId: request.threadId, messageId: request.starterId, userId: request.userId, startedAt: now, conversation, images: [] };
662
+ return !(await this.enqueue(specialist, () => this.runTask(agent, request.task, task)));
663
+ }
664
+
665
+ /** Runs one specialist task and answers in Discord; resolves true when the run failed or was cut off. */
666
+ private async runTask(agent: AgentConfig, taskText: string, task: ActiveTask): Promise<boolean> {
667
+ task.startedAt = Date.now();
668
+ task.abort = new AbortController();
669
+ this.active.set(task.specialist, task);
670
+ this.saveOpenWork();
671
+ let placeholder: string | undefined;
672
+ let typing: NodeJS.Timeout | undefined;
673
+ let images: DownloadedImages | undefined;
674
+ let failed = true;
675
+ let output: string;
676
+ let attachment: string | undefined;
677
+ let seen = 0;
678
+ let messages: RunResult["messages"] = [];
679
+ task.clock = new RunClock();
680
+ // Everything after the registration sits in the try, so the finally always clears the task, busy.json, and the typing refresh.
681
+ try {
682
+ await this.rest.addReaction(task.channelId, task.messageId, REACTION.running).catch(() => undefined);
683
+ placeholder = await this.rest
684
+ .createMessage(task.channelId, { content: `${REACTION.running} **${task.specialist}** is working on your task, please wait…`, replyTo: task.messageId })
685
+ .then((m) => m.id)
686
+ .catch(() => undefined);
687
+ task.placeholder = placeholder;
688
+ this.saveOpenWork();
689
+ // Discord clears the typing indicator after about ten seconds; refresh it while the task runs.
690
+ await this.rest.triggerTyping(task.channelId).catch(() => undefined);
691
+ typing = setInterval(() => void this.rest.triggerTyping(task.channelId).catch(() => undefined), 8000);
692
+ typing.unref();
693
+ log(`run astro.${task.specialist} for ${task.userId} (${task.conversation.resumed ? "continuing" : "new conversation"} ${task.conversation.id}): ${taskText.slice(0, 200)}`);
694
+ const session: ChildSession = { dir: sessionDirFor(sessionsRoot(), task.specialist), id: task.conversation.id };
695
+ pruneSessions(session.dir);
696
+ images = task.images.length > 0 ? await downloadImages(task.images) : undefined;
697
+ if (images && images.failed.length > 0) log(`astro.${task.specialist}: could not fetch ${images.failed.join(", ")}`);
698
+ const prompt = images ? describeImages(taskText, task.images, images.failed) : taskText;
699
+ const dirs = defaultDirs();
700
+ const { skills, missing } = resolveSkills(agent.skills, dirs);
701
+ if (missing.length > 0) log(`${agent.name}: skill(s) not found: ${missing.join(", ")}`);
702
+ const defaults = this.host.defaults;
703
+ const { depth, remaining } = currentDepth();
704
+ const approvalEnv = { [APPROVAL_URL_ENV]: this.approvals.url, [APPROVAL_TOKEN_ENV]: this.approvals.token, [APPROVAL_TASK_ENV]: task.specialist, ASTRO_CHANNEL: "discord" };
705
+ const onUpdate = (partial: RunResult) => {
706
+ const progress = describeProgress(partial, seen);
707
+ seen = progress.seen;
708
+ for (const line of progress.lines) log(`astro.${task.specialist}: ${line}`);
709
+ };
710
+ const result =
711
+ this.config.runner === "claude"
712
+ ? await runClaude({
713
+ service: task.specialist,
714
+ task: prompt,
715
+ conversationId: task.conversation.id,
716
+ resume: task.conversation.resumed,
717
+ appendSystemPrompt: CHANNEL_RULES,
718
+ // The child must not become a second Discord bridge.
719
+ env: { [ACTIVATION_ENV]: "0", ...approvalEnv, CLAUDE_CODE_OAUTH_TOKEN: loadClaudeToken() },
720
+ timeoutMs: (agent.timeoutMinutes ?? TASK_TIMEOUT_MINUTES) * 60_000,
721
+ clock: task.clock,
722
+ signal: task.abort.signal,
723
+ cwd: process.cwd(),
724
+ command: "claude",
725
+ onUpdate,
726
+ })
727
+ : await runAgent({
728
+ agent: { ...agent, timeoutMinutes: agent.timeoutMinutes ?? TASK_TIMEOUT_MINUTES },
729
+ skills,
730
+ task: prompt,
731
+ files: images?.files,
732
+ cwd: process.cwd(),
733
+ clock: task.clock,
734
+ depth,
735
+ remaining: childRemaining(remaining, agent),
736
+ defaults,
737
+ invocation: this.host.invocation,
738
+ // The child must not become a second Discord bridge.
739
+ env: { [ACTIVATION_ENV]: "0", ...approvalEnv },
740
+ extraSystemPrompt: CHANNEL_RULES,
741
+ session,
742
+ signal: task.abort.signal,
743
+ onUpdate,
744
+ });
745
+ failed = isFailed(result);
746
+ messages = result.messages;
747
+ if (failed) {
748
+ const reply = failureReply(result);
749
+ output = reply.text;
750
+ attachment = reply.attachment;
751
+ } else {
752
+ output = finalOutput(result.messages) || "(no output)";
753
+ }
754
+ log(`astro.${task.specialist} ${failed ? "failed" : "done"} in ${Math.round((Date.now() - task.startedAt) / 1000)} s, ${result.usage.turns} turns, ${result.usage.input + result.usage.output} tokens`);
755
+ } catch (err) {
756
+ output = errorText(err);
757
+ } finally {
758
+ clearInterval(typing);
759
+ if (!this.stopping) {
760
+ this.active.delete(task.specialist);
761
+ this.saveOpenWork();
762
+ }
763
+ if (images) await fs.rm(images.dir, { recursive: true, force: true }).catch(() => undefined);
764
+ }
765
+ // During shutdown the interrupted message was already written; an aborted run has nothing else to say.
766
+ if (this.stopping) return true;
767
+ let buttons: MessageComponent[] | null = null;
768
+ if (task.threaded && !failed) {
769
+ const texts = messages.flatMap((m) => (m.role === "assistant" ? m.content.flatMap((part) => (part.type === "text" ? [part.text] : [])) : []));
770
+ const shaped = this.threads().shape(output, texts);
771
+ if (shaped.title) await this.rest.renameThread(task.channelId, shaped.title).catch((err) => log(`${task.specialist}: renaming thread ${task.channelId} failed: ${errorText(err)}`));
772
+ output = shaped.text || "(no output)";
773
+ buttons = shaped.buttons;
774
+ }
775
+ await this.rest.removeOwnReaction(task.channelId, task.messageId, REACTION.running).catch(() => undefined);
776
+ await this.rest.addReaction(task.channelId, task.messageId, failed ? REACTION.failed : REACTION.done).catch(() => undefined);
777
+ // In a request's thread the requester is tagged on every reply, elsewhere when the reply needs them; an edited message never notifies, so it is posted new.
778
+ const notify = task.threaded || (!failed && needsYou(output)) ? task.userId : undefined;
779
+ const reply = `${notify ? `<@${notify}> ` : ""}${failed ? "❌" : "✅"} **${task.specialist}**\n${output}`;
780
+ const answers = await this.deliver(task, placeholder, reply, attachment, notify);
781
+ const last = answers[answers.length - 1];
782
+ if (buttons && last && attachment === undefined && reply.length <= ATTACHMENT_THRESHOLD) {
783
+ const chunks = chunkMessage(reply);
784
+ await this.rest.editMessage(task.channelId, last, chunks[chunks.length - 1] ?? reply, buttons).catch((err) => log(`${task.specialist}: answer buttons failed: ${errorText(err)}`));
785
+ }
786
+ this.conversations = recordAnswer(this.conversations, task.conversation.key, answers, Date.now(), !failed && needsYou(output) ? task.userId : undefined);
787
+ saveState(this.conversations);
788
+ await this.plugin?.afterTask?.({ specialist: task.specialist, channelId: task.channelId, messages, answerIds: answers, failed }).catch((err) => log(`plugin after ${task.specialist} task: ${errorText(err)}`));
789
+ return failed;
790
+ }
791
+
792
+ /** Turns the "working" placeholder into the answer: edit it in place when it fits, otherwise replace it with chunks or an attachment. Returns the answer message ids. */
793
+ private async deliver(task: ActiveTask, placeholder: string | undefined, text: string, attachment?: string, notify?: string): Promise<string[]> {
794
+ const mentionUsers = notify ? [notify] : undefined;
795
+ const oversized = attachment !== undefined || text.length > ATTACHMENT_THRESHOLD;
796
+ if (oversized) {
797
+ if (placeholder) await this.rest.deleteMessage(task.channelId, placeholder).catch(() => undefined);
798
+ const file = attachment !== undefined ? { name: `astro-${task.specialist}-stderr-${Date.now()}.txt`, content: attachment } : { name: `astro-${task.specialist}-${Date.now()}.md`, content: text };
799
+ const content = attachment !== undefined ? text.slice(0, 1900) : `${text.slice(0, 1200).trim()}\n… full answer attached (${text.length} characters).`;
800
+ const posted = await this.rest.createMessage(task.channelId, { content, replyTo: task.messageId, file, mentionUsers });
801
+ return [posted.id];
802
+ }
803
+ const chunks = chunkMessage(text);
804
+ if (chunks.length === 0) chunks.push(text);
805
+ const ids: string[] = [];
806
+ if (placeholder && notify) await this.rest.deleteMessage(task.channelId, placeholder).catch(() => undefined);
807
+ if (placeholder && !notify) {
808
+ await this.rest.editMessage(task.channelId, placeholder, chunks[0]).catch(() => undefined);
809
+ ids.push(placeholder);
810
+ } else ids.push((await this.rest.createMessage(task.channelId, { content: chunks[0], replyTo: task.messageId, mentionUsers })).id);
811
+ for (let i = 1; i < chunks.length; i++) {
812
+ ids.push((await this.rest.createMessage(task.channelId, { content: chunks[i] })).id);
813
+ }
814
+ return ids;
815
+ }
816
+
817
+ /** An approval request stops the run's clock, so an owner's 30 minutes do not use up the run's own limit. */
818
+ private holdClock(ticket: Ticket): void {
819
+ const clock = this.active.get(ticketTask(ticket))?.clock;
820
+ if (!clock) return;
821
+ clock.hold();
822
+ this.clockHolds.set(ticket.id, clock);
823
+ }
824
+
825
+ private releaseClock(ticket: Ticket): void {
826
+ this.clockHolds.get(ticket.id)?.release();
827
+ this.clockHolds.delete(ticket.id);
828
+ }
829
+
830
+ private async askApproval(ticket: Ticket): Promise<void> {
831
+ const short = ticket.agent.replace(/^astro\./, "");
832
+ const task = this.active.get(ticketTask(ticket));
833
+ if (!task) {
834
+ log(`approval ${ticket.id} for ${ticket.agent} has no active task; denying`);
835
+ this.approvals.decide(ticket.id, "deny", "bridge");
836
+ return;
837
+ }
838
+ await this.rest.addReaction(task.channelId, task.messageId, REACTION.waiting).catch(() => undefined);
839
+ const owners = this.config.owners.map((id) => `<@${id}>`).join(" ");
840
+ const channel = (await this.settingsFor(task.channelId))?.settings ?? null;
841
+ const view = this.plugin?.approvalView?.(ticket.args, channel, owners) ?? null;
842
+ const command = approvalCommand(ticket.args);
843
+ const content = view
844
+ ? `${view.content} Within ${this.config.approvalTimeoutMinutes} min.`
845
+ : `🔒 **${short}**${task.specialist === short ? "" : ` (called by **${task.specialist}**)`} wants to run ${code(command.inline)} for <@${task.userId}>. ${owners}: approve or deny within ${this.config.approvalTimeoutMinutes} min.`;
846
+ const posted = await this.rest.createMessage(task.channelId, {
847
+ content,
848
+ ...(command.file && !view ? { file: command.file } : {}),
849
+ replyTo: task.messageId,
850
+ components: approvalButtons(ticket.id, false, view?.labels),
851
+ mentionUsers: this.config.owners,
852
+ });
853
+ this.approvalMessages.set(ticket.id, { channelId: posted.channel_id, messageId: posted.id, userMessage: task });
854
+ this.saveOpenWork();
855
+ }
856
+
857
+ /** A ticket that could not be shown is denied, so the specialist stops waiting; the bridge keeps running. */
858
+ private approvalFailed(ticket: Ticket, err: unknown): void {
859
+ log(`approval ${ticket.id} for ${ticket.agent} could not be posted; denying: ${errorText(err)}`);
860
+ this.approvals.decide(ticket.id, "deny", "bridge");
861
+ const task = this.active.get(ticketTask(ticket));
862
+ if (task) void this.rest.createMessage(task.channelId, { content: "⚠️ The approval request could not be posted, so the change was not run. Ask again.", replyTo: task.messageId }).catch(() => undefined);
863
+ }
864
+
865
+ private async expireApproval(ticket: Ticket): Promise<void> {
866
+ const posted = this.approvalMessages.get(ticket.id);
867
+ if (!posted) return;
868
+ this.approvalMessages.delete(ticket.id);
869
+ this.saveOpenWork();
870
+ await this.rest.editMessage(posted.channelId, posted.messageId, `⌛ No decision within ${this.config.approvalTimeoutMinutes} min; ${code(approvalCommand(ticket.args).inline)} was not run.`).catch(() => undefined);
871
+ await this.rest.removeOwnReaction(posted.userMessage.channelId, posted.userMessage.messageId, REACTION.waiting).catch(() => undefined);
872
+ }
873
+
874
+ private async onInteraction(interaction: Interaction): Promise<void> {
875
+ const customId = interaction.type === 3 ? (interaction.data?.custom_id ?? "") : "";
876
+ const approval = /^apr:([0-9a-f-]{36}):(approve|deny)$/.exec(customId);
877
+ if (approval) {
878
+ await this.onApprovalButton(interaction, approval[1], approval[2] as "approve" | "deny");
879
+ return;
880
+ }
881
+ const request = customId ? this.threads().buttonTasks[customId] : undefined;
882
+ if (request !== undefined) {
883
+ await this.onThreadButton(interaction, request);
884
+ return;
885
+ }
886
+ if (interaction.type !== 2 && interaction.type !== 3) return;
887
+ const handled = (await this.plugin?.onInteraction?.(interaction)) ?? false;
888
+ if (!handled && interaction.type === 3) await this.rest.ephemeralReply(interaction.id, interaction.token, "This button is no longer active.").catch(() => undefined);
889
+ }
890
+
891
+ private async onApprovalButton(interaction: Interaction, ticketId: string, decision: "approve" | "deny"): Promise<void> {
892
+ const userId = interaction.member?.user?.id ?? interaction.user?.id ?? "";
893
+ this.refreshConfig();
894
+ if (!isOwner(this.config, userId)) {
895
+ await this.rest.ephemeralReply(interaction.id, interaction.token, "Only owners decide approvals.");
896
+ return;
897
+ }
898
+ const ticket = this.approvals.decide(ticketId, decision, userId);
899
+ if (!ticket) {
900
+ await this.rest.ephemeralReply(interaction.id, interaction.token, "This request was already decided or has expired.");
901
+ return;
902
+ }
903
+ const posted = this.approvalMessages.get(ticket.id);
904
+ this.approvalMessages.delete(ticket.id);
905
+ this.saveOpenWork();
906
+ const approved = decision === "approve";
907
+ const standard = `${approved ? `✅ Approved by <@${userId}>` : `⛔ Denied by <@${userId}>`}: ${code(approvalCommand(ticket.args).inline)}`;
908
+ await this.rest.updateInteractionMessage(interaction.id, interaction.token, this.plugin?.approvalVerdict?.(ticket.args, approved, userId) ?? standard);
909
+ if (posted) await this.rest.removeOwnReaction(posted.userMessage.channelId, posted.userMessage.messageId, REACTION.waiting).catch(() => undefined);
910
+ log(`approval ${ticket.id} ${decision} by ${userId}: ${ticket.args.join(" ")}`);
911
+ }
912
+ }
913
+
914
+ /** The bridge task a ticket belongs to: the specialist the owner asked, also when that specialist called another one. */
915
+ export function ticketTask(ticket: Pick<Ticket, "agent" | "task">): string {
916
+ return ticket.task ?? ticket.agent.replace(/^astro\./, "");
917
+ }
918
+
919
+ /**
920
+ * Discord bridge to the specialists. Inert unless ASTRO_DISCORD=1, which only
921
+ * the headless LaunchAgent host sets; interactive sessions never connect.
922
+ */
923
+ export default function astroDiscord(pi: ExtensionAPI): void {
924
+ if (process.env[ACTIVATION_ENV] !== "1" || process.env[AGENT_ENV]) return;
925
+ let bridge: Bridge | undefined;
926
+ pi.on("session_shutdown", async () => {
927
+ await bridge?.shutdown();
928
+ });
929
+ pi.on("session_start", async (_event, ctx: ExtensionContext) => {
930
+ const loaded = loadConfig();
931
+ if (!loaded.config) {
932
+ for (const error of loaded.errors) log(`config error: ${error}`);
933
+ return;
934
+ }
935
+ let token: string;
936
+ try {
937
+ token = loadToken();
938
+ } catch (err) {
939
+ log(`token error: ${errorText(err)}`);
940
+ return;
941
+ }
942
+ try {
943
+ bridge = new Bridge({ defaults: { model: ctx.model ? `${ctx.model.provider}/${ctx.model.id}` : undefined, thinkingLevel: ctx.thinkingLevel } }, loaded.config, token);
944
+ await bridge.start();
945
+ } catch (err) {
946
+ log(`start failed: ${errorText(err)}`);
947
+ // Pi stays alive on its FIFO stdin, so only an exit lets launchd's KeepAlive start the bridge again (at boot the network may not be up yet).
948
+ process.exit(1);
949
+ }
950
+ });
951
+ }