@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,217 @@
1
+ export const API = "https://discord.com/api/v10";
2
+ /** Channel type of a public thread; Start Thread without Message makes a private one when the type is left out. */
3
+ const PUBLIC_THREAD = 11;
4
+
5
+ export interface MessageComponent {
6
+ type: number;
7
+ /** Set by Discord on every component it returns; kept unchanged when a message is edited. */
8
+ id?: number;
9
+ components?: MessageComponent[];
10
+ /** Text of a Text Display. */
11
+ content?: string;
12
+ /** The button or thumbnail beside a Section's text. */
13
+ accessory?: MessageComponent;
14
+ style?: number;
15
+ label?: string;
16
+ custom_id?: string;
17
+ disabled?: boolean;
18
+ /** A Container's accent bar, RGB. */
19
+ accent_color?: number;
20
+ /** A Separator's visible line and its spacing (1 small, 2 large). */
21
+ divider?: boolean;
22
+ spacing?: number;
23
+ }
24
+
25
+ /** A message body for interaction webhooks: plain `content`, or `components` with the IS_COMPONENTS_V2 flag. */
26
+ export interface WebhookMessage {
27
+ content?: string | null;
28
+ components?: MessageComponent[];
29
+ flags?: number;
30
+ }
31
+
32
+ export interface CreateMessage {
33
+ content: string;
34
+ replyTo?: string;
35
+ components?: MessageComponent[];
36
+ /** One optional text attachment. */
37
+ file?: { name: string; content: string };
38
+ /** Users the message may ping; every other mention stays silent. */
39
+ mentionUsers?: string[];
40
+ }
41
+
42
+ /** No mention pings unless the user is listed. */
43
+ function allowedMentions(users: readonly string[] | undefined): { parse: never[] } | { users: string[] } {
44
+ return users && users.length > 0 ? { users: [...users] } : { parse: [] };
45
+ }
46
+
47
+ export interface DiscordMessage {
48
+ id: string;
49
+ channel_id: string;
50
+ }
51
+
52
+ interface RateLimit {
53
+ retry_after?: number;
54
+ }
55
+
56
+ /** Retries after a 429, each after Discord's `retry_after`, while that wait stays short. */
57
+ const RATE_LIMIT_RETRIES = 3;
58
+ const MAX_RETRY_AFTER_S = 30;
59
+
60
+ /** Seconds a 429 body asks to wait; one second when it names none. */
61
+ function retryAfter(body: string): number {
62
+ try {
63
+ const wait = (JSON.parse(body) as RateLimit).retry_after;
64
+ return typeof wait === "number" && wait >= 0 ? wait : 1;
65
+ } catch {
66
+ return 1;
67
+ }
68
+ }
69
+
70
+ /**
71
+ * Minimal Discord REST client on `fetch`. A 429 is retried up to three times
72
+ * while its `retry_after` stays under 30 seconds; anything else non-2xx throws.
73
+ */
74
+ export class DiscordRest {
75
+ private readonly token: string;
76
+ private readonly fetchImpl: typeof fetch;
77
+ private readonly base: string;
78
+
79
+ constructor(token: string, fetchImpl: typeof fetch = fetch, base = API) {
80
+ this.token = token;
81
+ this.fetchImpl = fetchImpl;
82
+ this.base = base;
83
+ }
84
+
85
+ private async call(method: string, path: string, body?: BodyInit, contentType?: string, attempt = 0): Promise<Response> {
86
+ const headers: Record<string, string> = { Authorization: `Bot ${this.token}`, "User-Agent": "DiscordBot (https://github.com/astrofoundry/astrogate, astro-discord)" };
87
+ if (contentType) headers["Content-Type"] = contentType;
88
+ const response = await this.fetchImpl(`${this.base}${path}`, { method, headers, body });
89
+ if (!response.ok) {
90
+ const text = await response.text();
91
+ if (response.status === 429 && attempt < RATE_LIMIT_RETRIES) {
92
+ const wait = retryAfter(text);
93
+ if (wait < MAX_RETRY_AFTER_S) {
94
+ await new Promise((resolve) => setTimeout(resolve, Math.ceil(wait * 1000)));
95
+ return this.call(method, path, body, contentType, attempt + 1);
96
+ }
97
+ }
98
+ throw new Error(`Discord ${method} ${path} answered ${response.status}: ${text.slice(0, 300)}`);
99
+ }
100
+ return response;
101
+ }
102
+
103
+ async createMessage(channelId: string, message: CreateMessage): Promise<DiscordMessage> {
104
+ const payload: Record<string, unknown> = { content: message.content, allowed_mentions: allowedMentions(message.mentionUsers) };
105
+ if (message.replyTo) payload.message_reference = { message_id: message.replyTo, fail_if_not_exists: false };
106
+ if (message.components) payload.components = message.components;
107
+ if (message.file) {
108
+ const form = new FormData();
109
+ payload.attachments = [{ id: 0, filename: message.file.name }];
110
+ form.append("payload_json", JSON.stringify(payload));
111
+ form.append("files[0]", new Blob([message.file.content], { type: "text/plain" }), message.file.name);
112
+ return (await this.call("POST", `/channels/${channelId}/messages`, form)).json() as Promise<DiscordMessage>;
113
+ }
114
+ return (await this.call("POST", `/channels/${channelId}/messages`, JSON.stringify(payload), "application/json")).json() as Promise<DiscordMessage>;
115
+ }
116
+
117
+ /** A Components V2 message (flag `1 << 15`): text lives in Text Display components, there is no `content`. */
118
+ async createComponentsMessage(channelId: string, components: MessageComponent[], mentionUsers?: string[]): Promise<DiscordMessage> {
119
+ const payload = { flags: 1 << 15, components, allowed_mentions: allowedMentions(mentionUsers) };
120
+ return (await this.call("POST", `/channels/${channelId}/messages`, JSON.stringify(payload), "application/json")).json() as Promise<DiscordMessage>;
121
+ }
122
+
123
+ /** Replaces the components of a Components V2 message; its flag stays set and needs no repeat. */
124
+ async editComponents(channelId: string, messageId: string, components: MessageComponent[]): Promise<void> {
125
+ await this.call("PATCH", `/channels/${channelId}/messages/${messageId}`, JSON.stringify({ components, allowed_mentions: { parse: [] } }), "application/json");
126
+ }
127
+
128
+ async editMessage(channelId: string, messageId: string, content: string, components: MessageComponent[] = []): Promise<void> {
129
+ await this.call("PATCH", `/channels/${channelId}/messages/${messageId}`, JSON.stringify({ content, components, allowed_mentions: { parse: [] } }), "application/json");
130
+ }
131
+
132
+ /** A public thread on a message; its id is the message's id, and a message can carry only one. */
133
+ async startThread(channelId: string, messageId: string, name: string): Promise<{ id: string }> {
134
+ return (await this.call("POST", `/channels/${channelId}/messages/${messageId}/threads`, JSON.stringify({ name: name.slice(0, 100), auto_archive_duration: 10080 }), "application/json")).json() as Promise<{ id: string }>;
135
+ }
136
+
137
+ /** A public thread with no message in the channel under it, such as a week's media picks. */
138
+ async createThread(channelId: string, name: string): Promise<{ id: string }> {
139
+ return (await this.call("POST", `/channels/${channelId}/threads`, JSON.stringify({ name: name.slice(0, 100), auto_archive_duration: 10080, type: PUBLIC_THREAD }), "application/json")).json() as Promise<{ id: string }>;
140
+ }
141
+
142
+ /** Renames a thread the bot started. */
143
+ async renameThread(threadId: string, name: string): Promise<void> {
144
+ await this.call("PATCH", `/channels/${threadId}`, JSON.stringify({ name: name.slice(0, 100) }), "application/json");
145
+ }
146
+
147
+ /** Takes a thread the bot started out of the channel list once its work is done; it stays readable, and any new message reopens it. */
148
+ async archiveThread(threadId: string): Promise<void> {
149
+ await this.call("PATCH", `/channels/${threadId}`, JSON.stringify({ archived: true }), "application/json");
150
+ }
151
+
152
+ /** Shows the "Cortex is typing…" indicator for about ten seconds. */
153
+ async triggerTyping(channelId: string): Promise<void> {
154
+ await this.call("POST", `/channels/${channelId}/typing`);
155
+ }
156
+
157
+ async deleteMessage(channelId: string, messageId: string): Promise<void> {
158
+ await this.call("DELETE", `/channels/${channelId}/messages/${messageId}`);
159
+ }
160
+
161
+ async addReaction(channelId: string, messageId: string, emoji: string): Promise<void> {
162
+ await this.call("PUT", `/channels/${channelId}/messages/${messageId}/reactions/${encodeURIComponent(emoji)}/@me`);
163
+ }
164
+
165
+ async removeOwnReaction(channelId: string, messageId: string, emoji: string): Promise<void> {
166
+ await this.call("DELETE", `/channels/${channelId}/messages/${messageId}/reactions/${encodeURIComponent(emoji)}/@me`);
167
+ }
168
+
169
+ /** Answers a component interaction by editing the message it came from (callback type 7). */
170
+ async updateInteractionMessage(interactionId: string, interactionToken: string, content: string, components: MessageComponent[] = []): Promise<void> {
171
+ await this.call("POST", `/interactions/${interactionId}/${interactionToken}/callback`, JSON.stringify({ type: 7, data: { content, components, allowed_mentions: { parse: [] } } }), "application/json");
172
+ }
173
+
174
+ /** Ephemeral reply to an interaction (callback type 4 with the EPHEMERAL flag). */
175
+ async ephemeralReply(interactionId: string, interactionToken: string, content: string): Promise<void> {
176
+ await this.call("POST", `/interactions/${interactionId}/${interactionToken}/callback`, JSON.stringify({ type: 4, data: { content, flags: 64, allowed_mentions: { parse: [] } } }), "application/json");
177
+ }
178
+
179
+ /** Acknowledges a slash command; Discord shows "thinking" until the original response is edited (callback type 5). */
180
+ async deferReply(interactionId: string, interactionToken: string): Promise<void> {
181
+ await this.call("POST", `/interactions/${interactionId}/${interactionToken}/callback`, JSON.stringify({ type: 5 }), "application/json");
182
+ }
183
+
184
+ /** Acknowledges a component click without a loading state; the message is edited later through the original response (callback type 6). */
185
+ async deferUpdate(interactionId: string, interactionToken: string): Promise<void> {
186
+ await this.call("POST", `/interactions/${interactionId}/${interactionToken}/callback`, JSON.stringify({ type: 6 }), "application/json");
187
+ }
188
+
189
+ /** Edits the original response: the deferred reply of a command, or the message of a clicked component. */
190
+ async editOriginal(applicationId: string, interactionToken: string, message: WebhookMessage): Promise<void> {
191
+ await this.call("PATCH", `/webhooks/${applicationId}/${interactionToken}/messages/@original`, JSON.stringify({ ...message, allowed_mentions: { parse: [] } }), "application/json");
192
+ }
193
+
194
+ /** Another message for the same interaction; with flags 64 only the user who triggered it sees it. */
195
+ async followUp(applicationId: string, interactionToken: string, message: WebhookMessage): Promise<DiscordMessage> {
196
+ return (await this.call("POST", `/webhooks/${applicationId}/${interactionToken}`, JSON.stringify({ ...message, allowed_mentions: { parse: [] } }), "application/json")).json() as Promise<DiscordMessage>;
197
+ }
198
+
199
+ /** Replaces the application's global slash commands with this list. */
200
+ async overwriteGlobalCommands(applicationId: string, commands: readonly unknown[]): Promise<void> {
201
+ await this.call("PUT", `/applications/${applicationId}/commands`, JSON.stringify(commands), "application/json");
202
+ }
203
+
204
+ async gatewayUrl(): Promise<string> {
205
+ const data = (await (await this.call("GET", "/gateway/bot")).json()) as { url?: string };
206
+ if (typeof data.url !== "string") throw new Error("Discord did not return a gateway url");
207
+ return data.url;
208
+ }
209
+
210
+ async currentUser(): Promise<{ id: string; username: string }> {
211
+ return (await this.call("GET", "/users/@me")).json() as Promise<{ id: string; username: string }>;
212
+ }
213
+
214
+ async channel(channelId: string): Promise<{ id: string; name?: string; guild_id?: string; type: number }> {
215
+ return (await this.call("GET", `/channels/${channelId}`)).json() as Promise<{ id: string; name?: string; guild_id?: string; type: number }>;
216
+ }
217
+ }
@@ -0,0 +1,218 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Interactive setup for the Discord bridge. Run on the host that will hold
4
+ * the bot, as the user that runs Pi:
5
+ * node --disable-warning=ExperimentalWarning <package>/extensions/bridge/setup.ts
6
+ * Prompts for the bot token and Discord ids, checks each against the API,
7
+ * writes ~/.config/astro-discord/{token,config.json} (0600), the LaunchAgent,
8
+ * and prints the commands to start it. Imports nothing from Pi on purpose.
9
+ */
10
+ import { execFileSync } from "node:child_process";
11
+ import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
12
+ import { homedir } from "node:os";
13
+ import { join } from "node:path";
14
+ import { createInterface } from "node:readline/promises";
15
+ import { Writable } from "node:stream";
16
+ import { type ChannelSettings, configDir, configPath, tokenPath, validateConfig } from "./config.ts";
17
+ import { daemonScriptText } from "./launcher.ts";
18
+ import { DiscordRest } from "./rest.ts";
19
+
20
+ const LABEL = "com.astrofoundry.astro-discord";
21
+ const SNOWFLAKE = /^\d{17,20}$/;
22
+
23
+ class MutableOutput extends Writable {
24
+ muted = false;
25
+ _write(chunk: Buffer, _encoding: BufferEncoding, callback: () => void): void {
26
+ if (!this.muted) process.stdout.write(chunk);
27
+ callback();
28
+ }
29
+ }
30
+
31
+ async function main(): Promise<void> {
32
+ const output = new MutableOutput();
33
+ const rl = createInterface({ input: process.stdin, output, terminal: true });
34
+ // readline redraws the prompt line on every keystroke, so the question must be its prompt, not a bare stdout write.
35
+ const ask = async (question: string, hidden = false): Promise<string> => {
36
+ output.muted = false;
37
+ const pending = rl.question(question);
38
+ output.muted = hidden;
39
+ const answer = await pending;
40
+ output.muted = false;
41
+ if (hidden) process.stdout.write("\n");
42
+ return answer.trim();
43
+ };
44
+ const askIds = async (question: string, min: number): Promise<string[]> => {
45
+ for (;;) {
46
+ const ids = (await ask(question)).split(/[\s,]+/).filter(Boolean);
47
+ if (ids.length >= min && ids.every((id) => SNOWFLAKE.test(id))) return ids;
48
+ console.log(` need ${min === 0 ? "" : "at least one "}Discord id${min > 1 ? "s" : ""} (17 to 20 digits, comma separated)`);
49
+ }
50
+ };
51
+
52
+ console.log("astro-discord setup. Nothing is written before every value has been checked.\n");
53
+ const existing = existsSync(tokenPath()) ? readFileSync(tokenPath(), "utf-8").trim() : "";
54
+ let token = await ask(existing ? "Bot token (Enter keeps the stored one): " : "Bot token (Developer Portal, Bot, Reset Token): ", true);
55
+ if (token.length === 0 && existing) token = existing;
56
+ const rest = new DiscordRest(token);
57
+ const me = await rest.currentUser();
58
+ console.log(` token ok: bot ${me.username} (${me.id})`);
59
+
60
+ let applicationId: string;
61
+ for (;;) {
62
+ applicationId = await ask("Application ID (General Information): ");
63
+ if (SNOWFLAKE.test(applicationId)) break;
64
+ console.log(" not a Discord id");
65
+ }
66
+
67
+ let guildId: string;
68
+ for (;;) {
69
+ guildId = (await askIds("Server ID (right-click the server, Copy Server ID): ", 1))[0];
70
+ try {
71
+ const guild = (await (await fetch(`https://discord.com/api/v10/guilds/${guildId}`, { headers: { Authorization: `Bot ${token}` } })).json()) as { name?: string; message?: string };
72
+ if (guild.name) {
73
+ console.log(` server ok: ${guild.name}`);
74
+ break;
75
+ }
76
+ console.log(` Discord says: ${guild.message ?? "unknown server"}; is the bot invited there?`);
77
+ } catch (err) {
78
+ console.log(` check failed: ${err instanceof Error ? err.message : String(err)}`);
79
+ }
80
+ }
81
+
82
+ const channels: Record<string, ChannelSettings> = {};
83
+ console.log("Channels. For each: its id, then how the bot listens (always, or only when mentioned), then which specialists live there.");
84
+ for (;;) {
85
+ const raw = await ask(Object.keys(channels).length === 0 ? "Channel ID: " : "Another channel ID (Enter to finish): ");
86
+ if (raw.length === 0) {
87
+ if (Object.keys(channels).length > 0) break;
88
+ console.log(" at least one channel is needed");
89
+ continue;
90
+ }
91
+ if (!SNOWFLAKE.test(raw)) {
92
+ console.log(" not a Discord id");
93
+ continue;
94
+ }
95
+ try {
96
+ const channel = await rest.channel(raw);
97
+ if (channel.guild_id !== guildId) {
98
+ console.log(` channel ${raw} is not in that server`);
99
+ continue;
100
+ }
101
+ console.log(` channel ok: #${channel.name ?? raw}`);
102
+ } catch (err) {
103
+ console.log(` channel ${raw}: ${err instanceof Error ? err.message : String(err)}`);
104
+ continue;
105
+ }
106
+ let trigger: "always" | "mention" = "always";
107
+ for (;;) {
108
+ const answer = (await ask(" trigger, always or mention [always]: ")).toLowerCase();
109
+ if (answer === "" || answer === "always") break;
110
+ if (answer === "mention") {
111
+ trigger = "mention";
112
+ break;
113
+ }
114
+ console.log(" always or mention");
115
+ }
116
+ let specialists: "*" | string[] = "*";
117
+ for (;;) {
118
+ const answer = await ask(" specialists, * for all or comma separated names (dns,edge,...) [*]: ");
119
+ if (answer === "" || answer === "*") break;
120
+ const names = answer.split(/[\s,]+/).filter(Boolean);
121
+ if (names.every((n) => /^[a-z][a-z0-9-]*$/.test(n))) {
122
+ specialists = [...new Set(names)];
123
+ break;
124
+ }
125
+ console.log(" lowercase names only");
126
+ }
127
+ channels[raw] = { trigger, specialists };
128
+ }
129
+ const channelIds = Object.keys(channels);
130
+ let adminChannelId = channelIds[0];
131
+ if (channelIds.length > 1) {
132
+ for (;;) {
133
+ const answer = await ask(`Admin channel for config commands [${channelIds[0]}]: `);
134
+ if (answer.length === 0) break;
135
+ if (channelIds.includes(answer)) {
136
+ adminChannelId = answer;
137
+ break;
138
+ }
139
+ console.log(" must be one of the channels above");
140
+ }
141
+ }
142
+
143
+ const owners = await askIds("Owner user ID(s), may use every specialist and approve risky calls: ", 1);
144
+ for (const id of owners) {
145
+ const user = (await (await fetch(`https://discord.com/api/v10/users/${id}`, { headers: { Authorization: `Bot ${token}` } })).json()) as { username?: string };
146
+ console.log(` owner ${id}: ${user.username ?? "unknown user"}`);
147
+ }
148
+
149
+ const access: Record<string, string[]> = {};
150
+ console.log("Extra users per specialist (Enter on an empty specialist name to finish):");
151
+ for (;;) {
152
+ const name = await ask(" specialist name (dns, edge, ...): ");
153
+ if (name.length === 0) break;
154
+ if (!/^[a-z][a-z0-9-]*$/.test(name)) {
155
+ console.log(" lowercase name only");
156
+ continue;
157
+ }
158
+ access[name] = await askIds(` user id(s) allowed to use ${name}: `, 1);
159
+ }
160
+
161
+ let timeout = 30;
162
+ const timeoutAnswer = await ask("Approval timeout in minutes [30]: ");
163
+ if (timeoutAnswer.length > 0) timeout = Number(timeoutAnswer);
164
+
165
+ const errors: string[] = [];
166
+ const config = validateConfig({ applicationId, guildId, channels, adminChannelId, owners, access, approvalTimeoutMinutes: timeout }, errors);
167
+ if (!config) {
168
+ console.error(`invalid configuration: ${errors.join("; ")}`);
169
+ process.exit(2);
170
+ }
171
+
172
+ mkdirSync(configDir(), { recursive: true, mode: 0o700 });
173
+ chmodSync(configDir(), 0o700);
174
+ writeFileSync(tokenPath(), `${token}\n`, { mode: 0o600 });
175
+ chmodSync(tokenPath(), 0o600);
176
+ writeFileSync(configPath(), `${JSON.stringify(config, null, 2)}\n`, { mode: 0o600 });
177
+ chmodSync(configPath(), 0o600);
178
+
179
+ // The bridge runs as its own process from the installed core; `astro bridge pi` moves it into a headless Pi instead.
180
+ const node = execFileSync("/bin/sh", ["-c", "command -v node"], { encoding: "utf-8", env: { ...process.env, PATH: `/opt/homebrew/bin:${process.env.PATH ?? ""}` } }).trim();
181
+ const daemon = join(process.env.PI_CODING_AGENT_DIR ?? join(homedir(), ".pi", "agent"), "npm", "node_modules", "@astrofoundry", "astrogate", "dist", "bridge.js");
182
+ if (!existsSync(daemon)) throw new Error(`${daemon} is missing: install @astrofoundry/astrogate first`);
183
+ const runScript = join(configDir(), "run.sh");
184
+ const logFile = join(homedir(), "Library", "Logs", "astro-discord.log");
185
+ writeFileSync(
186
+ runScript,
187
+ daemonScriptText(node, daemon),
188
+ { mode: 0o700 },
189
+ );
190
+ const plist = `<?xml version="1.0" encoding="UTF-8"?>
191
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
192
+ <plist version="1.0">
193
+ <dict>
194
+ <key>Label</key><string>${LABEL}</string>
195
+ <key>ProgramArguments</key><array><string>/bin/sh</string><string>${runScript}</string></array>
196
+ <key>RunAtLoad</key><true/>
197
+ <key>KeepAlive</key><true/>
198
+ <key>StandardOutPath</key><string>${logFile}</string>
199
+ <key>StandardErrorPath</key><string>${logFile}</string>
200
+ </dict>
201
+ </plist>
202
+ `;
203
+ const plistPath = join(homedir(), "Library", "LaunchAgents", `${LABEL}.plist`);
204
+ mkdirSync(join(homedir(), "Library", "LaunchAgents"), { recursive: true });
205
+ writeFileSync(plistPath, plist, { mode: 0o644 });
206
+ rl.close();
207
+
208
+ console.log(`\nwrote ${tokenPath()}, ${configPath()}, ${runScript}, ${plistPath}`);
209
+ console.log("Start or restart the bridge:");
210
+ console.log(` launchctl bootout gui/$(id -u)/${LABEL} 2>/dev/null; launchctl bootstrap gui/$(id -u) ${plistPath}`);
211
+ console.log(`Log: tail -f ${logFile}`);
212
+ console.log(`In Discord, in one of the channels: help`);
213
+ }
214
+
215
+ main().catch((err) => {
216
+ console.error(err instanceof Error ? err.message : String(err));
217
+ process.exit(1);
218
+ });
@@ -0,0 +1,40 @@
1
+ import { describe, expect, it, vi } from "vitest";
2
+ import { requestApproval } from "./index.ts";
3
+ import { isRisky } from "./risky.ts";
4
+
5
+ describe("approvals", () => {
6
+ it("marks --confirm and pattern matches as risky, with or without flags around the command", () => {
7
+ const patterns = [/^projects\s+(down|delete)\b/, /^volumes\s+rm\b/];
8
+ expect(isRisky(["vps", "reboot", "--confirm"], [])).toBe(true);
9
+ expect(isRisky(["vps", "reboot", "--confirm", "--help"], [])).toBe(true);
10
+ expect(isRisky(["vps", "status"], [])).toBe(false);
11
+ expect(isRisky(["projects", "delete", "x"], [])).toBe(false);
12
+ expect(isRisky(["--agent", "1", "volumes", "rm", "x"], patterns)).toBe(true);
13
+ expect(isRisky(["projects", "--agent", "1", "down", "media-mira"], patterns)).toBe(true);
14
+ expect(isRisky(["--json", "projects", "delete", "x"], patterns)).toBe(true);
15
+ expect(isRisky(["projects", "delete", "x", "--help"], patterns)).toBe(true);
16
+ expect(isRisky(["--agent", "1", "projects", "list"], patterns)).toBe(false);
17
+ expect(isRisky(["--help"], patterns)).toBe(false);
18
+ });
19
+
20
+ it("creates a ticket and polls until decided", async () => {
21
+ const seen: string[] = [];
22
+ let polls = 0;
23
+ const fetchImpl = vi.fn(async (url: string | URL | Request, init?: RequestInit) => {
24
+ seen.push(`${init?.method ?? "GET"} ${String(url)}`);
25
+ if (init?.method === "POST") {
26
+ expect(JSON.parse(init.body as string)).toEqual({ agent: "astro.edge", service: "edge", args: ["vps", "reboot", "--confirm"] });
27
+ return new Response(JSON.stringify({ id: "t1" }), { status: 201 });
28
+ }
29
+ polls++;
30
+ return new Response(JSON.stringify({ id: "t1", decision: polls < 3 ? null : "deny" }), { status: 200 });
31
+ }) as unknown as typeof fetch;
32
+ const decision = await requestApproval("http://127.0.0.1:1", "tok", { agent: "astro.edge", service: "edge", args: ["vps", "reboot", "--confirm"] }, undefined, 5, fetchImpl);
33
+ expect(decision).toBe("deny");
34
+ expect(seen[0]).toBe("POST http://127.0.0.1:1/approvals");
35
+ expect(seen[1]).toBe("GET http://127.0.0.1:1/approvals/t1");
36
+ expect(polls).toBe(3);
37
+ const failing = vi.fn(async () => new Response("no", { status: 500 })) as unknown as typeof fetch;
38
+ await expect(requestApproval("http://127.0.0.1:1", "tok", { agent: "a", service: "s", args: [] }, undefined, 5, failing)).rejects.toThrow(/500/);
39
+ });
40
+ });
@@ -0,0 +1,110 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import { join } from "node:path";
4
+ import type { SpecialistEntry, SpecialistsConfig } from "./types.ts";
5
+
6
+ export interface ConfigLoadResult {
7
+ config: SpecialistsConfig | null;
8
+ configPath: string;
9
+ errors: string[];
10
+ }
11
+
12
+ export function configPath(): string {
13
+ const dir = process.env.PI_CODING_AGENT_DIR ?? join(homedir(), ".pi", "agent");
14
+ return join(dir, "specialists.json");
15
+ }
16
+
17
+ const NAME = /^[a-z][a-z0-9-]*$/;
18
+
19
+ function validateEntry(raw: unknown, errors: string[], where: string): SpecialistEntry | null {
20
+ if (typeof raw !== "object" || raw === null) {
21
+ errors.push(`${where}: entry is not an object`);
22
+ return null;
23
+ }
24
+ const r = raw as Record<string, unknown>;
25
+ const agent = r.agent;
26
+ const tool = r.tool;
27
+ const service = r.service;
28
+ const timeoutMs = r.timeoutMs;
29
+ if (typeof agent !== "string" || agent.length === 0) {
30
+ errors.push(`${where}: missing 'agent'`);
31
+ return null;
32
+ }
33
+ if (typeof tool !== "string" || !NAME.test(tool)) {
34
+ errors.push(`${where}: 'tool' must match ${NAME}`);
35
+ return null;
36
+ }
37
+ if (typeof service !== "string" || !NAME.test(service)) {
38
+ errors.push(`${where}: 'service' must match ${NAME}`);
39
+ return null;
40
+ }
41
+ if (typeof timeoutMs !== "number" || !Number.isInteger(timeoutMs) || timeoutMs <= 0) {
42
+ errors.push(`${where}: 'timeoutMs' must be a positive integer`);
43
+ return null;
44
+ }
45
+ if (r.risky === undefined) return { agent, tool, service, timeoutMs };
46
+ const risky = riskyPatterns(r.risky, errors, where);
47
+ return risky ? { agent, tool, service, timeoutMs, risky } : null;
48
+ }
49
+
50
+ const MAX_PATTERN = 500;
51
+
52
+ function riskyPatterns(raw: unknown, errors: string[], where: string): RegExp[] | null {
53
+ if (!Array.isArray(raw) || raw.length === 0) {
54
+ errors.push(`${where}: 'risky' must be a non-empty array of patterns`);
55
+ return null;
56
+ }
57
+ const patterns: RegExp[] = [];
58
+ for (const source of raw) {
59
+ if (typeof source !== "string" || source.length === 0 || source.length > MAX_PATTERN || !source.startsWith("^")) {
60
+ errors.push(`${where}: each 'risky' pattern must be a string of 1 to ${MAX_PATTERN} characters that starts with ^`);
61
+ return null;
62
+ }
63
+ try {
64
+ patterns.push(new RegExp(source));
65
+ } catch (err) {
66
+ errors.push(`${where}: 'risky' pattern ${source} does not compile: ${err instanceof Error ? err.message : String(err)}`);
67
+ return null;
68
+ }
69
+ }
70
+ return patterns;
71
+ }
72
+
73
+ export function validateConfig(raw: unknown, errors: string[]): SpecialistsConfig | null {
74
+ if (typeof raw !== "object" || raw === null) {
75
+ errors.push("config root is not an object");
76
+ return null;
77
+ }
78
+ const r = raw as Record<string, unknown>;
79
+ if (typeof r.entry !== "string" || !r.entry.startsWith("/")) {
80
+ errors.push("'entry' must be an absolute path");
81
+ return null;
82
+ }
83
+ if (typeof r.user !== "string" || !NAME.test(r.user)) {
84
+ errors.push(`'user' must match ${NAME}`);
85
+ return null;
86
+ }
87
+ if (!Array.isArray(r.specialists)) {
88
+ errors.push("'specialists' must be an array");
89
+ return null;
90
+ }
91
+ const specialists: SpecialistEntry[] = [];
92
+ r.specialists.forEach((item, i) => {
93
+ const entry = validateEntry(item, errors, `specialists[${i}]`);
94
+ if (entry) specialists.push(entry);
95
+ });
96
+ return { entry: r.entry, user: r.user, specialists };
97
+ }
98
+
99
+ export function loadConfig(): ConfigLoadResult {
100
+ const path = configPath();
101
+ const errors: string[] = [];
102
+ if (!existsSync(path)) return { config: null, configPath: path, errors };
103
+ try {
104
+ const parsed = JSON.parse(readFileSync(path, "utf-8")) as unknown;
105
+ return { config: validateConfig(parsed, errors), configPath: path, errors };
106
+ } catch (err) {
107
+ errors.push(`invalid JSON: ${err instanceof Error ? err.message : String(err)}`);
108
+ return { config: null, configPath: path, errors };
109
+ }
110
+ }