@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,301 @@
1
+ /**
2
+ * Runs one specialist task through Claude Code (`claude -p --agent
3
+ * astro-<service>`) and turns its stream-json events into the same RunResult
4
+ * the Pi runner returns, so the bridge and its plugin read both alike: a
5
+ * specialist tool call becomes a `toolCall` named after the service, its answer
6
+ * a `toolResult`. Risky calls wait in the gate hook for the bridge's owners.
7
+ */
8
+ import { spawn } from "node:child_process";
9
+ import { createHash } from "node:crypto";
10
+ import { existsSync } from "node:fs";
11
+ import { homedir } from "node:os";
12
+ import { join } from "node:path";
13
+ import type { AssistantMessage, JsonObject, TextContent, ToolCall, ToolResultMessage } from "@earendil-works/pi-ai";
14
+ import { emptyUsage, RunClock, type RunResult } from "../subagents/child.ts";
15
+
16
+ const TOOL = /^mcp__astro-([a-z][a-z0-9-]{0,30})__run$/;
17
+ const MAX_STDERR = 200_000;
18
+
19
+ export interface ClaudeRunOptions {
20
+ service: string;
21
+ task: string;
22
+ /** The conversation's id; Claude Code's session id derives from it. */
23
+ conversationId: string;
24
+ /** True when the conversation already has a session to continue. */
25
+ resume: boolean;
26
+ appendSystemPrompt: string;
27
+ env: Record<string, string>;
28
+ timeoutMs: number;
29
+ clock: RunClock;
30
+ signal: AbortSignal;
31
+ cwd: string;
32
+ command: string;
33
+ onUpdate?: (result: RunResult) => void;
34
+ }
35
+
36
+ /** A stable UUID for a conversation id, because Claude Code names sessions by UUID. */
37
+ export function sessionUuid(conversationId: string): string {
38
+ const hex = createHash("sha256").update(`astro-discord:${conversationId}`).digest("hex");
39
+ const variant = ((parseInt(hex[16], 16) & 0x3) | 0x8).toString(16);
40
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-4${hex.slice(13, 16)}-${variant}${hex.slice(17, 20)}-${hex.slice(20, 32)}`;
41
+ }
42
+
43
+ /** Where Claude Code keeps a session started in `cwd`: the path with every other character than a letter or digit as "-". */
44
+ export function sessionFile(cwd: string, session: string, home = homedir()): string {
45
+ return join(home, ".claude", "projects", cwd.replace(/[^a-zA-Z0-9]/g, "-"), `${session}.jsonl`);
46
+ }
47
+
48
+ /** The task goes on stdin, so it never shows in the process list. */
49
+ export function claudeArgs(options: Pick<ClaudeRunOptions, "service" | "conversationId" | "resume" | "appendSystemPrompt">): string[] {
50
+ const session = sessionUuid(options.conversationId);
51
+ return [
52
+ "-p",
53
+ "--agent",
54
+ `astro-${options.service}`,
55
+ "--output-format",
56
+ "stream-json",
57
+ "--verbose",
58
+ // User settings only: the gate hook lives there, and no project file in the working directory joins in.
59
+ "--setting-sources",
60
+ "user",
61
+ "--append-system-prompt",
62
+ options.appendSystemPrompt,
63
+ ...(options.resume ? ["--resume", session] : ["--session-id", session]),
64
+ ];
65
+ }
66
+
67
+ /** The name the plugin and the logs know a tool by: the service for a specialist tool, else Claude Code's own name. */
68
+ export function toolName(name: string): string {
69
+ return TOOL.exec(name)?.[1] ?? name;
70
+ }
71
+
72
+ interface ClaudeContent {
73
+ type?: unknown;
74
+ text?: unknown;
75
+ id?: unknown;
76
+ name?: unknown;
77
+ input?: unknown;
78
+ tool_use_id?: unknown;
79
+ content?: unknown;
80
+ is_error?: unknown;
81
+ }
82
+
83
+ interface ClaudeEvent {
84
+ type?: unknown;
85
+ subtype?: unknown;
86
+ model?: unknown;
87
+ parent_tool_use_id?: unknown;
88
+ message?: { content?: unknown };
89
+ is_error?: unknown;
90
+ result?: unknown;
91
+ num_turns?: unknown;
92
+ usage?: { input_tokens?: unknown; output_tokens?: unknown; cache_read_input_tokens?: unknown; cache_creation_input_tokens?: unknown };
93
+ total_cost_usd?: unknown;
94
+ }
95
+
96
+ function number(value: unknown): number {
97
+ return typeof value === "number" && Number.isFinite(value) ? value : 0;
98
+ }
99
+
100
+ function contentText(content: unknown): string {
101
+ if (typeof content === "string") return content;
102
+ if (!Array.isArray(content)) return "";
103
+ return (content as ClaudeContent[]).map((c) => (c.type === "text" && typeof c.text === "string" ? c.text : "")).join("");
104
+ }
105
+
106
+ function assistant(content: AssistantMessage["content"], model: string): AssistantMessage {
107
+ return {
108
+ role: "assistant",
109
+ content,
110
+ api: "anthropic-messages",
111
+ provider: "anthropic",
112
+ model,
113
+ usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } },
114
+ stopReason: content.some((c) => c.type === "toolCall") ? "toolUse" : "stop",
115
+ timestamp: Date.now(),
116
+ };
117
+ }
118
+
119
+ /** Feeds one stream-json line into the result; returns true when the result changed. Events of a nested subagent are skipped. */
120
+ export function applyClaudeLine(line: string, result: RunResult, names: Map<string, string>): boolean {
121
+ if (!line.trim()) return false;
122
+ let event: ClaudeEvent;
123
+ try {
124
+ event = JSON.parse(line) as ClaudeEvent;
125
+ } catch {
126
+ return false;
127
+ }
128
+ if (typeof event.parent_tool_use_id === "string") return false;
129
+ if (event.type === "system" && event.subtype === "init" && typeof event.model === "string") {
130
+ result.model = event.model;
131
+ return false;
132
+ }
133
+ const items = Array.isArray(event.message?.content) ? (event.message.content as ClaudeContent[]) : [];
134
+ if (event.type === "assistant") {
135
+ const content: AssistantMessage["content"] = [];
136
+ for (const item of items) {
137
+ if (item.type === "text" && typeof item.text === "string") content.push({ type: "text", text: item.text } satisfies TextContent);
138
+ else if (item.type === "tool_use" && typeof item.id === "string" && typeof item.name === "string") {
139
+ const name = toolName(item.name);
140
+ names.set(item.id, name);
141
+ const args = typeof item.input === "object" && item.input !== null && !Array.isArray(item.input) ? (item.input as JsonObject) : {};
142
+ content.push({ type: "toolCall", id: item.id, name, arguments: args } satisfies ToolCall);
143
+ }
144
+ }
145
+ if (content.length === 0) return false;
146
+ result.messages.push(assistant(content, result.model ?? "claude"));
147
+ return true;
148
+ }
149
+ if (event.type === "user") {
150
+ let changed = false;
151
+ for (const item of items) {
152
+ if (item.type !== "tool_result" || typeof item.tool_use_id !== "string") continue;
153
+ const message: ToolResultMessage = {
154
+ role: "toolResult",
155
+ toolCallId: item.tool_use_id,
156
+ toolName: names.get(item.tool_use_id) ?? "unknown",
157
+ content: [{ type: "text", text: contentText(item.content) }],
158
+ isError: item.is_error === true,
159
+ timestamp: Date.now(),
160
+ };
161
+ result.messages.push(message);
162
+ changed = true;
163
+ }
164
+ return changed;
165
+ }
166
+ if (event.type === "result") {
167
+ const failed = event.is_error === true || (typeof event.subtype === "string" && event.subtype !== "success");
168
+ if (failed) {
169
+ result.stopReason = "error";
170
+ result.errorMessage = typeof event.result === "string" && event.result.trim() ? event.result.trim() : `Claude Code ended with ${String(event.subtype ?? "an error")}`;
171
+ }
172
+ result.usage = {
173
+ ...result.usage,
174
+ input: number(event.usage?.input_tokens),
175
+ output: number(event.usage?.output_tokens),
176
+ cacheRead: number(event.usage?.cache_read_input_tokens),
177
+ cacheWrite: number(event.usage?.cache_creation_input_tokens),
178
+ cost: number(event.total_cost_usd),
179
+ turns: number(event.num_turns),
180
+ };
181
+ return true;
182
+ }
183
+ return false;
184
+ }
185
+
186
+ /** Runs the task; resolves when Claude Code exits, after a stop, or when the clock runs out. */
187
+ export function runClaude(options: ClaudeRunOptions): Promise<RunResult> {
188
+ const result: RunResult = { agent: `astro-${options.service}`, agentSource: "unknown", task: options.task, exitCode: -1, messages: [], stderr: "", usage: emptyUsage() };
189
+ const names = new Map<string, string>();
190
+ return new Promise((resolve) => {
191
+ // Own process group, so a stop reaches the MCP server and the hooks Claude Code started.
192
+ // A conversation the Pi runner started has no Claude Code session to continue.
193
+ const resume = options.resume && existsSync(sessionFile(options.cwd, sessionUuid(options.conversationId)));
194
+ const proc = spawn(options.command, claudeArgs({ ...options, resume }), { cwd: options.cwd, env: { ...process.env, ...options.env }, stdio: ["pipe", "pipe", "pipe"], detached: true });
195
+ let buffer = "";
196
+ let settled = false;
197
+ let aborted = false;
198
+ const finish = (code: number) => {
199
+ if (settled) return;
200
+ settled = true;
201
+ options.clock.stop();
202
+ if (buffer.trim() && applyClaudeLine(buffer, result, names)) options.onUpdate?.(result);
203
+ result.exitCode = aborted && code === 0 ? 1 : code;
204
+ if (aborted && !result.errorMessage) {
205
+ result.stopReason = "aborted";
206
+ result.errorMessage = "the run was stopped";
207
+ }
208
+ resolve(result);
209
+ };
210
+ const signalGroup = (sig: NodeJS.Signals) => {
211
+ try {
212
+ if (proc.pid) process.kill(-proc.pid, sig);
213
+ else proc.kill(sig);
214
+ } catch {
215
+ proc.kill(sig);
216
+ }
217
+ };
218
+ const kill = () => {
219
+ aborted = true;
220
+ signalGroup("SIGTERM");
221
+ setTimeout(() => {
222
+ if (!settled) signalGroup("SIGKILL");
223
+ }, 5000).unref();
224
+ };
225
+ options.clock.start(options.timeoutMs, () => {
226
+ result.errorMessage = `timed out after ${Math.round(options.timeoutMs / 60_000)} min`;
227
+ kill();
228
+ });
229
+ proc.stdout.on("data", (data: Buffer) => {
230
+ buffer += data.toString("utf-8");
231
+ const lines = buffer.split("\n");
232
+ buffer = lines.pop() ?? "";
233
+ let changed = false;
234
+ for (const line of lines) changed = applyClaudeLine(line, result, names) || changed;
235
+ if (changed) options.onUpdate?.(result);
236
+ });
237
+ proc.stderr.on("data", (data: Buffer) => {
238
+ if (result.stderr.length < MAX_STDERR) result.stderr += data.toString("utf-8");
239
+ });
240
+ proc.on("close", (code) => finish(code ?? 1));
241
+ proc.on("exit", (code) => {
242
+ if (aborted) finish(code ?? 1);
243
+ });
244
+ proc.on("error", (err) => {
245
+ result.stderr += err.message;
246
+ finish(1);
247
+ });
248
+ if (options.signal.aborted) kill();
249
+ else options.signal.addEventListener("abort", kill, { once: true });
250
+ proc.stdin.end(options.task);
251
+ });
252
+ }
253
+
254
+ export interface ClaudeOneShotOptions {
255
+ systemPrompt: string;
256
+ task: string;
257
+ model: string;
258
+ env: Record<string, string>;
259
+ timeoutMs: number;
260
+ cwd: string;
261
+ command: string;
262
+ }
263
+
264
+ interface ClaudeJsonResult {
265
+ is_error?: unknown;
266
+ subtype?: unknown;
267
+ result?: unknown;
268
+ }
269
+
270
+ /** One answer from Claude Code with no tools and no saved session, such as a release-notes review. */
271
+ export function runClaudeOneShot(options: ClaudeOneShotOptions): Promise<{ failed: boolean; output: string }> {
272
+ const args = ["-p", "--tools", "", "--system-prompt", options.systemPrompt, "--model", options.model, "--output-format", "json", "--setting-sources", "user", "--no-session-persistence"];
273
+ return new Promise((resolve) => {
274
+ const proc = spawn(options.command, args, { cwd: options.cwd, env: { ...process.env, ...options.env }, stdio: ["pipe", "pipe", "pipe"] });
275
+ let stdout = "";
276
+ let stderr = "";
277
+ const timer = setTimeout(() => proc.kill("SIGTERM"), options.timeoutMs);
278
+ proc.stdout.on("data", (data: Buffer) => {
279
+ stdout += data.toString("utf-8");
280
+ });
281
+ proc.stderr.on("data", (data: Buffer) => {
282
+ if (stderr.length < MAX_STDERR) stderr += data.toString("utf-8");
283
+ });
284
+ proc.on("error", (err) => {
285
+ clearTimeout(timer);
286
+ resolve({ failed: true, output: err.message });
287
+ });
288
+ proc.on("close", (code) => {
289
+ clearTimeout(timer);
290
+ try {
291
+ const parsed = JSON.parse(stdout) as ClaudeJsonResult;
292
+ const text = typeof parsed.result === "string" ? parsed.result : "";
293
+ const failed = code !== 0 || parsed.is_error === true || parsed.subtype !== "success";
294
+ resolve({ failed, output: text || stderr.trim() || `Claude Code exited with ${code ?? "a signal"}` });
295
+ } catch {
296
+ resolve({ failed: true, output: stderr.trim() || stdout.trim().slice(0, 500) || `Claude Code exited with ${code ?? "a signal"}` });
297
+ }
298
+ });
299
+ proc.stdin.end(options.task);
300
+ });
301
+ }
@@ -0,0 +1,89 @@
1
+ import type { Trigger } from "./config.ts";
2
+
3
+ export type Command =
4
+ | { kind: "run"; specialist: string; task: string; fresh: boolean }
5
+ | { kind: "help" }
6
+ | { kind: "status" }
7
+ | { kind: "config"; args: string[] }
8
+ | { kind: "needs-prefix"; specialists: string[] }
9
+ | { kind: "none" };
10
+
11
+ export interface CommandContext {
12
+ botUserId: string;
13
+ /** Specialists present in this channel that the host has configured. */
14
+ specialists: readonly string[];
15
+ trigger: Trigger;
16
+ /** True when the message replies to one of the bot's messages. */
17
+ repliedToBot: boolean;
18
+ /** The specialist the replied-to bot message names, such as a morning-run problem's, or whose answer it is. */
19
+ repliedSpecialist?: string | null;
20
+ /** The specialist whose recent answer in this channel asked this user for something (`Needs you:`). */
21
+ askingSpecialist?: string | null;
22
+ /** The agent that takes a message naming no specialist, such as the foreman for an owner in the admin channel. */
23
+ defaultAgent?: string | null;
24
+ }
25
+
26
+ /**
27
+ * Interprets one channel message. `mention` channels react only when addressed
28
+ * (bot mention or a reply to the bot). A channel with one specialist needs no
29
+ * prefix; with several, a message without a prefix goes to the default agent,
30
+ * or, when addressed and there is none, gets a request for a prefix.
31
+ */
32
+ export function parseCommand(content: string, context: CommandContext): Command {
33
+ const mention = new RegExp(`^<@!?${context.botUserId}>\\s*`);
34
+ const addressed = mention.test(content.trim()) || context.repliedToBot;
35
+ const text = content.trim().replace(mention, "").replace(/^[!/]/, "").trim();
36
+ if (context.trigger === "mention" && !addressed) return { kind: "none" };
37
+ if (text.length === 0) return addressed ? { kind: "help" } : { kind: "none" };
38
+ const [first, ...rest] = text.split(/\s+/);
39
+ const word = first.toLowerCase();
40
+ if (word === "help") return { kind: "help" };
41
+ if (word === "status") return { kind: "status" };
42
+ if (word === "config") return { kind: "config", args: rest };
43
+ const known = context.defaultAgent ? [...context.specialists, context.defaultAgent] : context.specialists;
44
+ const named = word.replace(/^astro\./, "");
45
+ if (known.includes(named)) return runCommand(named, text.slice(first.length).trim());
46
+ if (context.repliedSpecialist && known.includes(context.repliedSpecialist)) return runCommand(context.repliedSpecialist, text);
47
+ if (context.askingSpecialist && known.includes(context.askingSpecialist)) return runCommand(context.askingSpecialist, text);
48
+ if (context.defaultAgent) return runCommand(context.defaultAgent, text);
49
+ if (context.specialists.length === 1) return runCommand(context.specialists[0], text);
50
+ if (addressed) return { kind: "needs-prefix", specialists: [...context.specialists] };
51
+ return { kind: "none" };
52
+ }
53
+
54
+ /** A task; a leading `new` asks for a fresh conversation instead of continuing the recent one. */
55
+ function runCommand(specialist: string, text: string): Command {
56
+ const fresh = /^new(\s|$)/i.test(text);
57
+ const task = fresh ? text.replace(/^new\s*/i, "").trim() : text;
58
+ return task.length > 0 ? { kind: "run", specialist, task, fresh } : { kind: "help" };
59
+ }
60
+
61
+ /** Prompt paragraph appended for tasks that arrive from a chat channel. */
62
+ export const CHANNEL_RULES = `## Channel rules
63
+
64
+ This task arrived from a Discord channel and your answer is posted there. Answer in plain text, facts first, no headings, with the fewest words that keep the meaning; this is mandatory, and 1500 characters is the ceiling. Write only what the owner needs to act or to know the outcome: the result, what you need from them, and the next step. Leave out what you read, checks that found nothing, what did not change, and comments on your own reasoning. Use short, plain sentences. When the task is ambiguous (which guest, which record, which host), do not act: ask one precise question and stop. Risky calls may wait for an operator's approval; if the tool reports a denial or a missing answer, report it and stop. When you need something from the owner (a go, a decision, an action, or a blocker you cannot remove), your first line starts with **Needs you:** and says what you need in one sentence; the bridge then tags them.`;
65
+
66
+ /** A reply whose first line asks the owner for something; the bridge tags the requester on it. */
67
+ export function needsYou(output: string): boolean {
68
+ return /^\s*\**Needs you:/i.test(output);
69
+ }
70
+
71
+ /** `extra`: the site plugin's lines for these specialists, such as its slash commands. */
72
+ export function helpText(allowed: readonly string[], present: readonly string[], isOwner: boolean, trigger: Trigger, canConfig: boolean, extra: readonly string[] = []): string {
73
+ if (allowed.length === 0) return present.length === 0 ? "No specialist is present in this channel." : "You may not use the specialists present in this channel.";
74
+ const how = present.length === 1 ? `Every message${trigger === "mention" ? " that addresses me" : ""} here goes to \`${present[0]}\`.` : `Send \`<specialist> <task>\`${trigger === "mention" ? " after mentioning me" : ""}. Specialists you may use here:`;
75
+ const lines = [how];
76
+ if (present.length > 1) lines.push(...allowed.map((name) => `• \`${name}\``));
77
+ lines.push("Reactions: ⏳ running, 🔒 waiting for an owner's approval, ✅ done, ❌ failed.");
78
+ lines.push("A reply to my answer, or another task for the same specialist within 30 minutes, continues that conversation; start the task with `new` for a fresh one. Within 30 minutes of a question to you, your next message goes to the specialist that asked.");
79
+ lines.push(...extra);
80
+ const commands = ["`help` this message", "`status` running tasks"];
81
+ if (canConfig) commands.push("`config show`", "`config channel <#channel> <always|mention> <*|name,name>`", "`config access <specialist> add|remove <@user>`", "`config runner <pi|claude>`");
82
+ lines.push(`Commands: ${commands.join(", ")}.`);
83
+ if (isOwner) lines.push("Owners approve risky calls with the buttons the bot posts and may use every specialist.");
84
+ return lines.join("\n");
85
+ }
86
+
87
+ export function needsPrefixText(specialists: readonly string[]): string {
88
+ return `Several specialists live here; start your message with one of: ${specialists.map((s) => `\`${s}\``).join(", ")}.`;
89
+ }
@@ -0,0 +1,263 @@
1
+ import { readFileSync, renameSync, statSync, writeFileSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import { join } from "node:path";
4
+
5
+ /** Set to "1" on the headless Pi host that should connect to Discord. */
6
+ export const ACTIVATION_ENV = "ASTRO_DISCORD";
7
+
8
+ export type Trigger = "always" | "mention";
9
+ export type Runner = "pi" | "claude";
10
+ export const RUNNERS: readonly Runner[] = ["pi", "claude"];
11
+
12
+ export interface ChannelSettings {
13
+ /** `always`: every message that names a specialist (or any message when one specialist is present); `mention`: only when addressed. */
14
+ trigger: Trigger;
15
+ /** Specialists available in this channel: every configured one, or a list of short names. */
16
+ specialists: "*" | string[];
17
+ /** Each addressed message opens a thread named by the specialist; later messages there need no mention. */
18
+ threads?: true;
19
+ /** Anyone who can post here may use this channel's specialists; approvals still need an owner. */
20
+ everyone?: true;
21
+ }
22
+
23
+ export interface DiscordConfig {
24
+ applicationId: string;
25
+ guildId: string;
26
+ /** Channels the bot reads, by id; messages elsewhere are ignored. Threads inherit their parent's entry. */
27
+ channels: Record<string, ChannelSettings>;
28
+ /** The one channel where owners may run `config` commands. */
29
+ adminChannelId: string;
30
+ /** Users who may use every specialist and decide approvals. */
31
+ owners: string[];
32
+ /** Extra users per specialist name (without the astro. prefix). */
33
+ access: Record<string, string[]>;
34
+ approvalTimeoutMinutes: number;
35
+ /** Reports posted on a schedule, at most one per report name; empty when none is configured. */
36
+ reports: ReportSchedule[];
37
+ /** Which harness runs the specialists: Pi (the default) or Claude Code with the pack's `astro-<service>` subagents. */
38
+ runner: Runner;
39
+ }
40
+
41
+ /** A report name; the site plugin defines which reports exist. */
42
+ export const REPORT_NAME = /^[a-z][a-z0-9-]{0,40}$/;
43
+
44
+ /** One entry of `reports` in config.json: which report, where, and when. */
45
+ export interface ReportSchedule {
46
+ report: string;
47
+ channelId: string;
48
+ /** Local wall-clock time, `HH:MM`, in `timeZone`. */
49
+ time: string;
50
+ /** IANA zone such as `Europe/Madrid`; daylight-saving changes follow from it. */
51
+ timeZone: string;
52
+ }
53
+
54
+ export const SNOWFLAKE = /^\d{17,20}$/;
55
+ export const SPECIALIST = /^[a-z][a-z0-9-]*$/;
56
+
57
+ export function configDir(): string {
58
+ return process.env.ASTRO_DISCORD_DIR ?? join(homedir(), ".config", "astro-discord");
59
+ }
60
+
61
+ /** Where the LaunchAgent writes the bridge's output on Cortex (`setup.ts`), named in messages that point to a reason. */
62
+ export const BRIDGE_LOG = "`~/Library/Logs/astro-discord.log` on Cortex";
63
+
64
+ export function configPath(): string {
65
+ return join(configDir(), "config.json");
66
+ }
67
+
68
+ export function tokenPath(): string {
69
+ return join(configDir(), "token");
70
+ }
71
+
72
+ /** The long-lived Claude Code token (`claude setup-token`) the Claude runner passes as CLAUDE_CODE_OAUTH_TOKEN. */
73
+ export function claudeTokenPath(): string {
74
+ return join(configDir(), "claude-token");
75
+ }
76
+
77
+ function snowflakes(value: unknown, where: string, errors: string[]): string[] {
78
+ if (!Array.isArray(value) || value.length === 0) {
79
+ errors.push(`${where} must be a non-empty array of Discord ids`);
80
+ return [];
81
+ }
82
+ const out: string[] = [];
83
+ for (const item of value) {
84
+ if (typeof item !== "string" || !SNOWFLAKE.test(item)) errors.push(`${where}: ${String(item)} is not a Discord id`);
85
+ else out.push(item);
86
+ }
87
+ return out;
88
+ }
89
+
90
+ export function validateConfig(raw: unknown, errors: string[]): DiscordConfig | null {
91
+ if (typeof raw !== "object" || raw === null) {
92
+ errors.push("config root is not an object");
93
+ return null;
94
+ }
95
+ const r = raw as Record<string, unknown>;
96
+ for (const key of ["applicationId", "guildId"]) {
97
+ if (typeof r[key] !== "string" || !SNOWFLAKE.test(r[key] as string)) errors.push(`${key} must be a Discord id`);
98
+ }
99
+ const channels: Record<string, ChannelSettings> = {};
100
+ if (typeof r.channels !== "object" || r.channels === null || Array.isArray(r.channels) || Object.keys(r.channels).length === 0) {
101
+ errors.push("channels must be a non-empty object of channel id to settings");
102
+ } else {
103
+ for (const [id, raw] of Object.entries(r.channels as Record<string, unknown>)) {
104
+ if (!SNOWFLAKE.test(id)) errors.push(`channels: ${id} is not a Discord id`);
105
+ const settings = validateChannel(raw, `channels.${id}`, errors);
106
+ if (settings) channels[id] = settings;
107
+ }
108
+ }
109
+ if (typeof r.adminChannelId !== "string" || !SNOWFLAKE.test(r.adminChannelId)) errors.push("adminChannelId must be a Discord id");
110
+ else if (!(r.adminChannelId in channels) && errors.length === 0) errors.push("adminChannelId must be one of the configured channels");
111
+ const owners = snowflakes(r.owners, "owners", errors);
112
+ const access: Record<string, string[]> = {};
113
+ if (r.access !== undefined) {
114
+ if (typeof r.access !== "object" || r.access === null || Array.isArray(r.access)) errors.push("access must be an object of specialist name to id array");
115
+ else {
116
+ for (const [name, ids] of Object.entries(r.access as Record<string, unknown>)) {
117
+ if (!SPECIALIST.test(name)) errors.push(`access: ${name} is not a specialist name`);
118
+ access[name] = Array.isArray(ids) && ids.length === 0 ? [] : snowflakes(ids, `access.${name}`, errors);
119
+ }
120
+ }
121
+ }
122
+ const timeout = r.approvalTimeoutMinutes;
123
+ if (typeof timeout !== "number" || !Number.isInteger(timeout) || timeout < 1 || timeout > 240) errors.push("approvalTimeoutMinutes must be an integer from 1 to 240");
124
+ if (r.dailyReport !== undefined) errors.push('dailyReport was replaced by reports: [{ "report": "arcane", "channelId", "time", "timeZone" }]');
125
+ const reports = r.reports === undefined ? [] : validateReports(r.reports, errors);
126
+ if (r.runner !== undefined && !RUNNERS.includes(r.runner as Runner)) errors.push(`runner must be one of ${RUNNERS.join(", ")}`);
127
+ if (errors.length > 0) return null;
128
+ return {
129
+ applicationId: r.applicationId as string,
130
+ guildId: r.guildId as string,
131
+ channels,
132
+ adminChannelId: r.adminChannelId as string,
133
+ owners,
134
+ access,
135
+ approvalTimeoutMinutes: timeout as number,
136
+ reports,
137
+ runner: (r.runner as Runner | undefined) ?? "pi",
138
+ };
139
+ }
140
+
141
+ function validTimeZone(value: unknown): value is string {
142
+ if (typeof value !== "string") return false;
143
+ try {
144
+ new Intl.DateTimeFormat("en", { timeZone: value });
145
+ return true;
146
+ } catch {
147
+ return false;
148
+ }
149
+ }
150
+
151
+ /** `reports` from config.json: a list with at most one entry per report. */
152
+ export function validateReports(raw: unknown, errors: string[]): ReportSchedule[] {
153
+ if (!Array.isArray(raw)) {
154
+ errors.push("reports must be a list of { report, channelId, time, timeZone }");
155
+ return [];
156
+ }
157
+ const out: ReportSchedule[] = [];
158
+ raw.forEach((entry: unknown, i) => {
159
+ const where = `reports[${i}]`;
160
+ const r = entry as Record<string, unknown> | null;
161
+ if (typeof r !== "object" || r === null) {
162
+ errors.push(`${where} must be an object`);
163
+ return;
164
+ }
165
+ const before = errors.length;
166
+ if (typeof r.report !== "string" || !REPORT_NAME.test(r.report)) errors.push(`${where}.report must be a report name such as daily`);
167
+ else if (out.some((s) => s.report === r.report)) errors.push(`${where}: ${String(r.report)} is listed twice`);
168
+ if (typeof r.channelId !== "string" || !SNOWFLAKE.test(r.channelId)) errors.push(`${where}.channelId must be a Discord id`);
169
+ if (typeof r.time !== "string" || !/^([01]\d|2[0-3]):[0-5]\d$/.test(r.time)) errors.push(`${where}.time must be HH:MM`);
170
+ if (!validTimeZone(r.timeZone)) errors.push(`${where}.timeZone must be an IANA time zone such as Europe/Madrid`);
171
+ if (errors.length === before) out.push({ report: r.report as string, channelId: r.channelId as string, time: r.time as string, timeZone: r.timeZone as string });
172
+ });
173
+ return out;
174
+ }
175
+
176
+ /** The schedule of one report, or undefined when it is not configured. */
177
+ export function reportSchedule(config: DiscordConfig, name: string): ReportSchedule | undefined {
178
+ return config.reports.find((r) => r.report === name);
179
+ }
180
+
181
+ export function validateChannel(raw: unknown, where: string, errors: string[]): ChannelSettings | null {
182
+ if (typeof raw !== "object" || raw === null) {
183
+ errors.push(`${where} must be an object`);
184
+ return null;
185
+ }
186
+ const r = raw as Record<string, unknown>;
187
+ if (r.trigger !== "always" && r.trigger !== "mention") errors.push(`${where}.trigger must be always or mention`);
188
+ let specialists: "*" | string[] = "*";
189
+ if (r.specialists !== "*") {
190
+ if (!Array.isArray(r.specialists) || r.specialists.length === 0 || !r.specialists.every((n) => typeof n === "string" && SPECIALIST.test(n))) {
191
+ errors.push(`${where}.specialists must be "*" or a non-empty list of specialist names`);
192
+ } else specialists = [...new Set(r.specialists as string[])];
193
+ }
194
+ for (const flag of ["threads", "everyone"] as const) {
195
+ if (r[flag] !== undefined && r[flag] !== true) errors.push(`${where}.${flag} must be true when present`);
196
+ }
197
+ if (errors.length > 0) return null;
198
+ return {
199
+ trigger: r.trigger as Trigger,
200
+ specialists,
201
+ ...(r.threads === true ? { threads: true as const } : {}),
202
+ ...(r.everyone === true ? { everyone: true as const } : {}),
203
+ };
204
+ }
205
+
206
+ /** Writes the configuration back atomically with owner-only permissions. */
207
+ export function saveConfig(config: DiscordConfig): void {
208
+ const path = configPath();
209
+ const tmp = `${path}.tmp`;
210
+ writeFileSync(tmp, `${JSON.stringify(config, null, 2)}\n`, { mode: 0o600 });
211
+ renameSync(tmp, path);
212
+ }
213
+
214
+ /** Specialists present in a channel, intersected with the ones configured on this host. */
215
+ export function channelSpecialists(settings: ChannelSettings, configured: readonly string[]): string[] {
216
+ return settings.specialists === "*" ? [...configured] : settings.specialists.filter((name) => configured.includes(name));
217
+ }
218
+
219
+ export function loadConfig(): { config: DiscordConfig | null; errors: string[] } {
220
+ const errors: string[] = [];
221
+ let parsed: unknown;
222
+ try {
223
+ parsed = JSON.parse(readFileSync(configPath(), "utf-8"));
224
+ } catch (err) {
225
+ return { config: null, errors: [`cannot read ${configPath()}: ${err instanceof Error ? err.message : String(err)}`] };
226
+ }
227
+ return { config: validateConfig(parsed, errors), errors };
228
+ }
229
+
230
+ /** The bot token; the file must be readable by its owner only. */
231
+ export function loadToken(): string {
232
+ const path = tokenPath();
233
+ const mode = statSync(path).mode;
234
+ if ((mode & 0o077) !== 0) throw new Error(`${path} must be mode 0600`);
235
+ const token = readFileSync(path, "utf-8").trim();
236
+ if (token.length < 50) throw new Error(`${path} does not look like a bot token`);
237
+ return token;
238
+ }
239
+
240
+ /** The Claude Code token; the file must be readable by its owner only. */
241
+ export function loadClaudeToken(): string {
242
+ const path = claudeTokenPath();
243
+ const mode = statSync(path).mode;
244
+ if ((mode & 0o077) !== 0) throw new Error(`${path} must be mode 0600`);
245
+ const token = readFileSync(path, "utf-8").trim();
246
+ if (token.includes("#")) throw new Error(`${path} holds the sign-in code from the browser; it needs the token \`claude setup-token\` prints after that code`);
247
+ if (token.length < 20 || /\s/.test(token)) throw new Error(`${path} does not look like a Claude Code token`);
248
+ return token;
249
+ }
250
+
251
+ export function isOwner(config: DiscordConfig, userId: string): boolean {
252
+ return config.owners.includes(userId);
253
+ }
254
+
255
+ /** Owners may use every specialist; others only those listed for them under `access`. */
256
+ export function canUse(config: DiscordConfig, userId: string, specialist: string): boolean {
257
+ return isOwner(config, userId) || (config.access[specialist] ?? []).includes(userId);
258
+ }
259
+
260
+ /** Specialists a user may address among those present, from the runtime list of `astro.*` agents. */
261
+ export function allowedSpecialists(config: DiscordConfig, userId: string, available: readonly string[]): string[] {
262
+ return available.filter((name) => canUse(config, userId, name));
263
+ }