@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,547 @@
1
+ import { chmodSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
2
+ import { tmpdir } from "node:os";
3
+ import { join } from "node:path";
4
+ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
5
+ import { APPROVAL_INLINE_CHARS, ApprovalServer, approvalCommand, type Ticket } from "./approvals.ts";
6
+ import { chunkMessage, fenceState } from "./chunk.ts";
7
+ import { applyAdminCommand, describeConfig } from "./admin.ts";
8
+ import { helpText, needsPrefixText, needsYou, parseCommand } from "./commands.ts";
9
+ import { allowedSpecialists, canUse, channelSpecialists, loadClaudeToken, loadConfig, loadToken, validateConfig } from "./config.ts";
10
+ import { GatewayClient, INTENTS, initialState, reduce } from "./gateway.ts";
11
+ import type { RunResult } from "../subagents/child.ts";
12
+ import { failureReply, ticketTask } from "./index.ts";
13
+ import { DiscordRest } from "./rest.ts";
14
+ import { CONVERSATION_IDLE_MS, CONVERSATION_MAX_AGE_MS, askingSpecialist, forgetStale, loadState, newConversationId, recordAnswer, replySpecialist, resolveConversation, saveState, startConversation } from "./conversations.ts";
15
+ import { quoteText, withQuotes } from "./quote.ts";
16
+ import { MAX_IMAGE_BYTES, describeImages, downloadImages, imageAttachments } from "./attachments.ts";
17
+
18
+ const ID = "123456789012345678";
19
+ const OTHER = "223456789012345678";
20
+ const THIRD = "323456789012345678";
21
+ const valid = { applicationId: ID, guildId: ID, channels: { [ID]: { trigger: "always", specialists: "*" }, [OTHER]: { trigger: "mention", specialists: ["arcane"] } }, adminChannelId: ID, owners: [ID], access: { dns: [OTHER] }, approvalTimeoutMinutes: 30, reports: [] };
22
+
23
+ describe("config", () => {
24
+ it("validates ids and shapes", () => {
25
+ const errors: string[] = [];
26
+ expect(validateConfig(valid, errors)).toEqual({ ...valid, runner: "pi" });
27
+ expect(errors).toEqual([]);
28
+ expect(validateConfig({ ...valid, runner: "claude" }, [])).toMatchObject({ runner: "claude" });
29
+ const runner: string[] = [];
30
+ expect(validateConfig({ ...valid, runner: "codex" }, runner)).toBeNull();
31
+ expect(runner.join(" ")).toMatch(/runner must be one of pi, claude/);
32
+ expect(validateConfig({ ...valid, guildId: "abc" }, errors)).toBeNull();
33
+ expect(validateConfig({ ...valid, channels: {} }, [])).toBeNull();
34
+ expect(validateConfig({ ...valid, channels: { [ID]: { trigger: "sometimes", specialists: "*" } } }, [])).toBeNull();
35
+ expect(validateConfig({ ...valid, adminChannelId: THIRD }, [])).toBeNull();
36
+ expect(channelSpecialists({ trigger: "always", specialists: "*" }, ["dns", "edge"])).toEqual(["dns", "edge"]);
37
+ expect(channelSpecialists({ trigger: "always", specialists: ["edge", "nope"] }, ["dns", "edge"])).toEqual(["edge"]);
38
+ expect(validateConfig({ ...valid, access: { "Bad Name": [ID] } }, [])).toBeNull();
39
+ expect(validateConfig({ ...valid, approvalTimeoutMinutes: 0 }, [])).toBeNull();
40
+ expect(validateConfig({ ...valid, access: undefined }, [])).toMatchObject({ access: {} });
41
+ });
42
+
43
+ it("grants owners everything and others their listed specialists", () => {
44
+ const config = validateConfig(valid, [])!;
45
+ expect(canUse(config, ID, "proxmox")).toBe(true);
46
+ expect(canUse(config, OTHER, "dns")).toBe(true);
47
+ expect(canUse(config, OTHER, "proxmox")).toBe(false);
48
+ expect(canUse(config, THIRD, "dns")).toBe(false);
49
+ expect(allowedSpecialists(config, OTHER, ["dns", "edge"])).toEqual(["dns"]);
50
+ expect(allowedSpecialists(config, ID, ["dns", "edge"])).toEqual(["dns", "edge"]);
51
+ });
52
+
53
+ describe("files", () => {
54
+ let dir: string;
55
+ beforeEach(() => {
56
+ dir = mkdtempSync(join(tmpdir(), "astro-discord-"));
57
+ process.env.ASTRO_DISCORD_DIR = dir;
58
+ });
59
+ afterEach(() => {
60
+ delete process.env.ASTRO_DISCORD_DIR;
61
+ rmSync(dir, { recursive: true, force: true });
62
+ });
63
+
64
+ it("loads config and refuses a readable token", () => {
65
+ writeFileSync(join(dir, "config.json"), JSON.stringify(valid));
66
+ expect(loadConfig().config).toEqual({ ...valid, runner: "pi" });
67
+ writeFileSync(join(dir, "token"), `${"x".repeat(60)}\n`, { mode: 0o644 });
68
+ expect(() => loadToken()).toThrow(/0600/);
69
+ chmodSync(join(dir, "token"), 0o600);
70
+ expect(loadToken()).toBe("x".repeat(60));
71
+ writeFileSync(join(dir, "claude-token"), "sk-ant-oat01-abcdefghijklmnopqrstuvwxyz\n", { mode: 0o644 });
72
+ expect(() => loadClaudeToken()).toThrow(/0600/);
73
+ chmodSync(join(dir, "claude-token"), 0o600);
74
+ expect(loadClaudeToken()).toBe("sk-ant-oat01-abcdefghijklmnopqrstuvwxyz");
75
+ writeFileSync(join(dir, "claude-token"), "abcdefghijklmnopqrstuvwxyz#state12345", { mode: 0o600 });
76
+ expect(() => loadClaudeToken()).toThrow(/sign-in code/);
77
+ writeFileSync(join(dir, "config.json"), "{");
78
+ expect(loadConfig().config).toBeNull();
79
+ });
80
+ });
81
+ });
82
+
83
+ describe("approval command", () => {
84
+ it("shows a short command whole and a long one as a preview with the whole command attached", () => {
85
+ expect(approvalCommand(["restart", "--confirm"])).toEqual({ inline: "restart --confirm" });
86
+ const body = JSON.stringify({ alias: "Hallway lights", actions: "x".repeat(3000) });
87
+ const long = approvalCommand(["rest", "post", "/api/config/automation/config/1734267132664", body]);
88
+ const whole = `rest post /api/config/automation/config/1734267132664 ${body}`;
89
+ expect(long.inline.length).toBeLessThan(APPROVAL_INLINE_CHARS);
90
+ expect(long.inline.startsWith("rest post /api/config/automation/config/1734267132664")).toBe(true);
91
+ expect(long.inline).toContain(`(${whole.length} characters, the whole command is attached)`);
92
+ expect(long.file).toEqual({ name: "command.txt", content: `${whole}\n` });
93
+ // The message around the command stays far below Discord's 2000-character limit.
94
+ expect(`🔒 **home** wants to run \`${long.inline}\` for <@123456789012345678>. <@123456789012345678>: approve or deny within 30 min.`.length).toBeLessThan(2000);
95
+ });
96
+ });
97
+
98
+ describe("chunk", () => {
99
+ it("splits on paragraphs and keeps fences balanced", () => {
100
+ const text = `${"a".repeat(1500)}\n\n${"b".repeat(1500)}`;
101
+ const chunks = chunkMessage(text);
102
+ expect(chunks).toHaveLength(2);
103
+ expect(chunks[0]).toBe("a".repeat(1500));
104
+ const fenced = "intro\n```json\n" + "x\n".repeat(1500) + "```\nafter";
105
+ const parts = chunkMessage(fenced);
106
+ expect(parts.length).toBeGreaterThan(1);
107
+ for (const part of parts) {
108
+ expect(part.length).toBeLessThanOrEqual(2000);
109
+ expect(fenceState(part, null)).toBeNull();
110
+ }
111
+ expect(parts[1].startsWith("```json\n")).toBe(true);
112
+ expect(chunkMessage(" ")).toEqual([]);
113
+ });
114
+ });
115
+
116
+ describe("commands", () => {
117
+ it("tags the requester only when the reply's first line asks the owner for something", () => {
118
+ expect(needsYou("**Needs you:** the go for the queue drain.\n1. Pull the image.")).toBe(true);
119
+ expect(needsYou("Needs you: a decision on the backup.")).toBe(true);
120
+ expect(needsYou("All three services run.\n**Needs you:** nothing")).toBe(false);
121
+ });
122
+
123
+ const many = { botUserId: ID, specialists: ["dns", "edge"], trigger: "always" as const, repliedToBot: false };
124
+ const one = { ...many, specialists: ["arcane"] };
125
+ it("parses prefixed tasks, mentions, help, status, and config", () => {
126
+ expect(parseCommand("dns list the zones", many)).toEqual({ kind: "run", specialist: "dns", task: "list the zones", fresh: false });
127
+ expect(parseCommand(`<@${ID}> edge probe the front door`, many)).toEqual({ kind: "run", specialist: "edge", task: "probe the front door", fresh: false });
128
+ expect(parseCommand("!astro.dns zones", many)).toEqual({ kind: "run", specialist: "dns", task: "zones", fresh: false });
129
+ expect(parseCommand("help", many)).toEqual({ kind: "help" });
130
+ expect(parseCommand("Status", many)).toEqual({ kind: "status" });
131
+ expect(parseCommand("config channel <#1> mention dns", many)).toEqual({ kind: "config", args: ["channel", "<#1>", "mention", "dns"] });
132
+ expect(parseCommand("dns", many)).toEqual({ kind: "help" });
133
+ expect(parseCommand("dns new list the zones", many)).toEqual({ kind: "run", specialist: "dns", task: "list the zones", fresh: true });
134
+ expect(parseCommand("New what changed?", one)).toEqual({ kind: "run", specialist: "arcane", task: "what changed?", fresh: true });
135
+ expect(parseCommand("newer images?", one)).toEqual({ kind: "run", specialist: "arcane", task: "newer images?", fresh: false });
136
+ expect(parseCommand("dns new", many)).toEqual({ kind: "help" });
137
+ expect(parseCommand("hello everyone", many)).toEqual({ kind: "none" });
138
+ expect(parseCommand("", many)).toEqual({ kind: "none" });
139
+ });
140
+
141
+ it("sends a reply to a message that names a specialist there, without a prefix", () => {
142
+ const reply = { ...many, repliedToBot: true, repliedSpecialist: "edge" };
143
+ expect(parseCommand("Do it", reply)).toEqual({ kind: "run", specialist: "edge", task: "Do it", fresh: false });
144
+ expect(parseCommand("dns list the zones", reply)).toEqual({ kind: "run", specialist: "dns", task: "list the zones", fresh: false });
145
+ expect(parseCommand("Do it", { ...reply, repliedSpecialist: "proxmox" })).toEqual({ kind: "needs-prefix", specialists: ["dns", "edge"] });
146
+ expect(parseCommand("Do it", { ...reply, repliedSpecialist: null })).toEqual({ kind: "needs-prefix", specialists: ["dns", "edge"] });
147
+ });
148
+
149
+ it("sends the next message to the specialist that asked the user, even without a reply", () => {
150
+ expect(parseCommand("Yes", { ...many, askingSpecialist: "edge" })).toEqual({ kind: "run", specialist: "edge", task: "Yes", fresh: false });
151
+ expect(parseCommand("Yes", { ...many, repliedToBot: true, repliedSpecialist: "dns", askingSpecialist: "edge" })).toEqual({ kind: "run", specialist: "dns", task: "Yes", fresh: false });
152
+ expect(parseCommand("dns list the zones", { ...many, askingSpecialist: "edge" })).toEqual({ kind: "run", specialist: "dns", task: "list the zones", fresh: false });
153
+ expect(parseCommand("Yes", { ...many, askingSpecialist: "proxmox" })).toEqual({ kind: "none" });
154
+ expect(parseCommand("Yes", { ...many, trigger: "mention", askingSpecialist: "edge" })).toEqual({ kind: "none" });
155
+ });
156
+
157
+ it("needs no prefix with one specialist and asks for one when addressed with several", () => {
158
+ expect(parseCommand("list the projects", one)).toEqual({ kind: "run", specialist: "arcane", task: "list the projects", fresh: false });
159
+ expect(parseCommand("arcane list the projects", one)).toEqual({ kind: "run", specialist: "arcane", task: "list the projects", fresh: false });
160
+ expect(parseCommand(`<@${ID}> list the zones`, many)).toEqual({ kind: "needs-prefix", specialists: ["dns", "edge"] });
161
+ expect(parseCommand("list the zones", { ...many, repliedToBot: true })).toEqual({ kind: "needs-prefix", specialists: ["dns", "edge"] });
162
+ expect(parseCommand(`<@${ID}>`, many)).toEqual({ kind: "help" });
163
+ });
164
+
165
+ it("sends a message that names no specialist to the default agent", () => {
166
+ const admin = { ...many, defaultAgent: "foreman" };
167
+ expect(parseCommand("update the media stack", admin)).toEqual({ kind: "run", specialist: "foreman", task: "update the media stack", fresh: false });
168
+ expect(parseCommand("new why is Jellyfin slow?", admin)).toEqual({ kind: "run", specialist: "foreman", task: "why is Jellyfin slow?", fresh: true });
169
+ expect(parseCommand("foreman check the backups", admin)).toEqual({ kind: "run", specialist: "foreman", task: "check the backups", fresh: false });
170
+ expect(parseCommand("dns list the zones", admin)).toEqual({ kind: "run", specialist: "dns", task: "list the zones", fresh: false });
171
+ expect(parseCommand("Yes", { ...admin, askingSpecialist: "edge" })).toEqual({ kind: "run", specialist: "edge", task: "Yes", fresh: false });
172
+ expect(parseCommand("Do it", { ...admin, repliedToBot: true, repliedSpecialist: "foreman", askingSpecialist: "edge" })).toEqual({ kind: "run", specialist: "foreman", task: "Do it", fresh: false });
173
+ expect(parseCommand("help", admin)).toEqual({ kind: "help" });
174
+ expect(parseCommand("anything", { ...admin, trigger: "mention" })).toEqual({ kind: "none" });
175
+ expect(parseCommand("hello everyone", many)).toEqual({ kind: "none" });
176
+ });
177
+
178
+ it("stays silent in mention channels unless addressed", () => {
179
+ const mention = { ...many, trigger: "mention" as const };
180
+ expect(parseCommand("dns list the zones", mention)).toEqual({ kind: "none" });
181
+ expect(parseCommand(`<@${ID}> dns list the zones`, mention)).toEqual({ kind: "run", specialist: "dns", task: "list the zones", fresh: false });
182
+ expect(parseCommand("dns list the zones", { ...mention, repliedToBot: true })).toEqual({ kind: "run", specialist: "dns", task: "list the zones", fresh: false });
183
+ expect(parseCommand("anything", { ...one, trigger: "mention" })).toEqual({ kind: "none" });
184
+ expect(parseCommand(`<@${ID}> anything`, { ...one, trigger: "mention" })).toEqual({ kind: "run", specialist: "arcane", task: "anything", fresh: false });
185
+ });
186
+
187
+ it("writes help and prefix texts", () => {
188
+ expect(helpText([], [], false, "always", false)).toMatch(/No specialist/);
189
+ expect(helpText([], ["dns"], false, "always", false)).toMatch(/may not/);
190
+ expect(helpText(["arcane"], ["arcane"], false, "mention", false)).toMatch(/addresses me here goes to `arcane`/);
191
+ expect(helpText(["dns"], ["dns", "edge"], true, "always", false)).toMatch(/`dns`/);
192
+ expect(helpText(["dns"], ["dns"], true, "always", false)).not.toMatch(/config show/);
193
+ expect(helpText(["dns"], ["dns"], true, "always", true)).toMatch(/`config show`/);
194
+ expect(needsPrefixText(["dns", "edge"])).toMatch(/`dns`, `edge`/);
195
+ });
196
+ });
197
+
198
+ describe("admin commands", () => {
199
+ const config = validateConfig(valid, [])!;
200
+ const configured = ["dns", "edge", "arcane"];
201
+ it("switches the runner between Pi and Claude Code", () => {
202
+ expect(describeConfig(config)).toContain("Runner: Pi");
203
+ const claude = applyAdminCommand(config, ["runner", "claude"], configured);
204
+ expect(claude.config?.runner).toBe("claude");
205
+ expect(claude.reply).toMatch(/now run in Claude Code/);
206
+ expect(applyAdminCommand(claude.config!, ["runner", "claude"], configured)).toEqual({ reply: "The runner is already Claude Code." });
207
+ expect(applyAdminCommand(config, ["runner", "codex"], configured).config).toBeUndefined();
208
+ expect(applyAdminCommand(config, ["runner"], configured).config).toBeUndefined();
209
+ });
210
+
211
+ it("shows, adds, updates, removes channels and grants access", () => {
212
+ expect(applyAdminCommand(config, ["show"], configured).reply).toContain(`<#${ID}>: always, every specialist (admin)`);
213
+ expect(describeConfig(config)).toContain(`dns: <@${OTHER}>`);
214
+ const added = applyAdminCommand(config, ["channel", `<#${THIRD}>`, "mention", "dns,edge"], configured);
215
+ expect(added.config?.channels[THIRD]).toEqual({ trigger: "mention", specialists: ["dns", "edge"] });
216
+ expect(added.reply).toMatch(/^Added/);
217
+ const updated = applyAdminCommand(added.config!, ["channel", THIRD, "always", "*"], configured);
218
+ expect(updated.config?.channels[THIRD]).toEqual({ trigger: "always", specialists: "*" });
219
+ expect(updated.reply).toMatch(/^Updated/);
220
+ expect(applyAdminCommand(config, ["channel", `<#${THIRD}>`, "mention", "nope"], configured).reply).toMatch(/unknown specialist/);
221
+ expect(applyAdminCommand(config, ["channel", `<#${ID}>`, "remove"], configured)).toEqual({ reply: "The admin channel cannot be removed." });
222
+ expect(applyAdminCommand(updated.config!, ["channel", `<#${THIRD}>`, "remove"], configured).config?.channels[THIRD]).toBeUndefined();
223
+ const granted = applyAdminCommand(config, ["access", "edge", "add", `<@${THIRD}>`], configured);
224
+ expect(granted.config?.access.edge).toEqual([THIRD]);
225
+ expect(applyAdminCommand(granted.config!, ["access", "edge", "add", THIRD], configured).config).toBeUndefined();
226
+ expect(applyAdminCommand(granted.config!, ["access", "edge", "remove", THIRD], configured).config?.access.edge).toEqual([]);
227
+ expect(applyAdminCommand(config, ["access", "nope", "add", THIRD], configured).reply).toMatch(/unknown specialist/);
228
+ expect(applyAdminCommand(config, ["bogus"], configured).reply).toMatch(/config show/);
229
+ });
230
+ });
231
+
232
+ describe("gateway reducer", () => {
233
+ it("identifies after hello, resumes with a session, heartbeats, and reconnects", () => {
234
+ const state = initialState();
235
+ const handlers = { dispatch: vi.fn(), log: vi.fn() };
236
+ expect(reduce(state, { op: 10, d: { heartbeat_interval: 1000 } }, handlers)).toEqual({ kind: "identify" });
237
+ expect(state.heartbeatMs).toBe(1000);
238
+ expect(reduce(state, { op: 0, t: "READY", s: 1, d: { session_id: "s1", resume_gateway_url: "wss://r" } }, handlers)).toEqual({ kind: "none" });
239
+ expect(state).toMatchObject({ sessionId: "s1", resumeUrl: "wss://r", seq: 1 });
240
+ expect(handlers.dispatch).toHaveBeenCalledWith("READY", expect.objectContaining({ session_id: "s1" }));
241
+ expect(reduce(state, { op: 0, t: "MESSAGE_CREATE", s: 2, d: { id: "m" } }, handlers)).toEqual({ kind: "none" });
242
+ expect(handlers.dispatch).toHaveBeenLastCalledWith("MESSAGE_CREATE", { id: "m" });
243
+ expect(reduce(state, { op: 1 }, handlers)).toEqual({ kind: "heartbeat-now" });
244
+ state.awaitingAck = true;
245
+ expect(reduce(state, { op: 11 }, handlers)).toEqual({ kind: "none" });
246
+ expect(state.awaitingAck).toBe(false);
247
+ expect(reduce(state, { op: 7 }, handlers)).toEqual({ kind: "reconnect", resume: true });
248
+ expect(reduce(state, { op: 9, d: false }, handlers)).toEqual({ kind: "reconnect", resume: false });
249
+ expect(reduce(state, { op: 10, d: { heartbeat_interval: 1000 } }, handlers)).toEqual({ kind: "resume" });
250
+ expect(INTENTS).toBe(33281);
251
+ });
252
+ });
253
+
254
+ class FakeSocket {
255
+ readyState = 1;
256
+ sent: { op: number; d?: unknown }[] = [];
257
+ closedWith: number | null = null;
258
+ private readonly listeners = new Map<string, ((event: unknown) => void)[]>();
259
+ addEventListener(type: string, fn: (event: unknown) => void): void {
260
+ this.listeners.set(type, [...(this.listeners.get(type) ?? []), fn]);
261
+ }
262
+ send(data: string): void {
263
+ this.sent.push(JSON.parse(data) as { op: number; d?: unknown });
264
+ }
265
+ close(code: number): void {
266
+ this.closedWith = code;
267
+ }
268
+ emit(payload: object): void {
269
+ for (const fn of this.listeners.get("message") ?? []) fn({ data: JSON.stringify(payload) });
270
+ }
271
+ emitClose(code: number): void {
272
+ this.readyState = 3;
273
+ for (const fn of this.listeners.get("close") ?? []) fn({ code, reason: "" });
274
+ }
275
+ }
276
+
277
+ describe("gateway client", () => {
278
+ beforeEach(() => vi.useFakeTimers());
279
+ afterEach(() => vi.useRealTimers());
280
+
281
+ function client() {
282
+ const sockets: FakeSocket[] = [];
283
+ const log = vi.fn();
284
+ const gateway = new GatewayClient({
285
+ token: "t",
286
+ gatewayUrl: "wss://gateway",
287
+ handlers: { dispatch: vi.fn(), log },
288
+ socketFactory: () => {
289
+ const socket = new FakeSocket();
290
+ sockets.push(socket);
291
+ return socket as unknown as WebSocket;
292
+ },
293
+ });
294
+ return { gateway, sockets, log };
295
+ }
296
+
297
+ it("opens exactly one new connection after a reconnect request, and the replaced socket's close changes nothing", () => {
298
+ const { gateway, sockets, log } = client();
299
+ gateway.start();
300
+ sockets[0].emit({ op: 10, d: { heartbeat_interval: 1000 } });
301
+ sockets[0].emit({ op: 0, t: "READY", s: 1, d: { session_id: "s1", resume_gateway_url: "wss://resume" } });
302
+ sockets[0].emit({ op: 7 });
303
+ expect(sockets[0].closedWith).toBe(4000);
304
+ sockets[0].emitClose(4000);
305
+ vi.advanceTimersByTime(5_000);
306
+ expect(sockets).toHaveLength(2);
307
+
308
+ sockets[1].emit({ op: 10, d: { heartbeat_interval: 1000 } });
309
+ expect(sockets[1].sent.at(-1)).toMatchObject({ op: 6, d: { session_id: "s1", seq: 1 } });
310
+ sockets[0].emitClose(1000);
311
+ sockets[0].emit({ op: 7 });
312
+ vi.advanceTimersByTime(1_000);
313
+ expect(sockets).toHaveLength(2);
314
+ expect(sockets[1].sent.at(-1)).toEqual({ op: 1, d: 1 });
315
+ expect(log).not.toHaveBeenCalledWith("gateway closed (1000); reconnecting");
316
+ gateway.stop();
317
+ });
318
+
319
+ it("reconnects and resumes once when the server closes the current socket", () => {
320
+ const { gateway, sockets } = client();
321
+ gateway.start();
322
+ sockets[0].emit({ op: 10, d: { heartbeat_interval: 1000 } });
323
+ sockets[0].emit({ op: 0, t: "READY", s: 3, d: { session_id: "s1", resume_gateway_url: "wss://resume" } });
324
+ sockets[0].emitClose(1000);
325
+ vi.advanceTimersByTime(5_000);
326
+ expect(sockets).toHaveLength(2);
327
+ sockets[1].emit({ op: 10, d: { heartbeat_interval: 1000 } });
328
+ expect(sockets[1].sent.at(-1)).toMatchObject({ op: 6, d: { session_id: "s1", seq: 3 } });
329
+ gateway.stop();
330
+ });
331
+ });
332
+
333
+ describe("rest", () => {
334
+ it("sends JSON messages, multipart attachments, and retries once after 429", async () => {
335
+ const calls: { url: string; init: RequestInit }[] = [];
336
+ let first = true;
337
+ const fetchImpl = vi.fn(async (url: string | URL | Request, init?: RequestInit) => {
338
+ calls.push({ url: String(url), init: init ?? {} });
339
+ if (first) {
340
+ first = false;
341
+ return new Response(JSON.stringify({ retry_after: 0.01 }), { status: 429 });
342
+ }
343
+ return new Response(JSON.stringify({ id: "m1", channel_id: "c1" }), { status: 200 });
344
+ }) as unknown as typeof fetch;
345
+ const rest = new DiscordRest("tok", fetchImpl);
346
+ const message = await rest.createMessage("c1", { content: "hi", replyTo: "m0" });
347
+ expect(message.id).toBe("m1");
348
+ expect(calls).toHaveLength(2);
349
+ expect(calls[1].url).toBe("https://discord.com/api/v10/channels/c1/messages");
350
+ expect((calls[1].init.headers as Record<string, string>).Authorization).toBe("Bot tok");
351
+ expect(JSON.parse(calls[1].init.body as string)).toMatchObject({ content: "hi", message_reference: { message_id: "m0" }, allowed_mentions: { parse: [] } });
352
+ await rest.createMessage("c1", { content: "long", file: { name: "a.md", content: "body" } });
353
+ expect(calls[2].init.body).toBeInstanceOf(FormData);
354
+ await rest.addReaction("c1", "m1", "⏳");
355
+ expect(calls[3].url).toBe(`https://discord.com/api/v10/channels/c1/messages/m1/reactions/${encodeURIComponent("⏳")}/@me`);
356
+ expect(calls[3].init.method).toBe("PUT");
357
+ });
358
+
359
+ it("retries a 429 up to three times while retry_after stays under 30 seconds", async () => {
360
+ const limited = (statuses: { status: number; retryAfter?: number }[]) => {
361
+ let calls = 0;
362
+ const fetchImpl = vi.fn(async () => {
363
+ const next = statuses[calls++] ?? { status: 200 };
364
+ return next.status === 200 ? new Response(JSON.stringify({ id: "m1", channel_id: "c1" }), { status: 200 }) : new Response(JSON.stringify({ retry_after: next.retryAfter }), { status: next.status });
365
+ }) as unknown as typeof fetch;
366
+ return { rest: new DiscordRest("tok", fetchImpl), calls: () => calls };
367
+ };
368
+ const busy = { status: 429, retryAfter: 0.001 };
369
+ const three = limited([busy, busy, busy]);
370
+ expect((await three.rest.createMessage("c1", { content: "hi" })).id).toBe("m1");
371
+ expect(three.calls()).toBe(4);
372
+ const four = limited([busy, busy, busy, busy]);
373
+ await expect(four.rest.createMessage("c1", { content: "hi" })).rejects.toThrow(/answered 429/);
374
+ expect(four.calls()).toBe(4);
375
+ const long = limited([{ status: 429, retryAfter: 30 }]);
376
+ await expect(long.rest.createMessage("c1", { content: "hi" })).rejects.toThrow(/answered 429: \{"retry_after":30\}/);
377
+ expect(long.calls()).toBe(1);
378
+ });
379
+
380
+ it("pings only the listed users and opens a thread on a message", async () => {
381
+ const calls: { url: string; init: RequestInit }[] = [];
382
+ const fetchImpl = vi.fn(async (url: string | URL | Request, init?: RequestInit) => {
383
+ calls.push({ url: String(url), init: init ?? {} });
384
+ return new Response(JSON.stringify({ id: "m1", channel_id: "c1" }), { status: 200 });
385
+ }) as unknown as typeof fetch;
386
+ const rest = new DiscordRest("tok", fetchImpl);
387
+ await rest.createMessage("c1", { content: "<@1> alert", mentionUsers: ["178096425509453824"] });
388
+ expect(JSON.parse(calls[0].init.body as string).allowed_mentions).toEqual({ users: ["178096425509453824"] });
389
+ await rest.createComponentsMessage("c1", [{ type: 10, content: "x" }], ["178096425509453824"]);
390
+ expect(JSON.parse(calls[1].init.body as string)).toMatchObject({ flags: 1 << 15, allowed_mentions: { users: ["178096425509453824"] } });
391
+ await rest.createComponentsMessage("c1", [{ type: 10, content: "x" }]);
392
+ expect(JSON.parse(calls[2].init.body as string).allowed_mentions).toEqual({ parse: [] });
393
+ await rest.startThread("c1", "m9", "Rule 100021 on arcane");
394
+ expect(calls[3].url).toBe("https://discord.com/api/v10/channels/c1/messages/m9/threads");
395
+ expect(JSON.parse(calls[3].init.body as string)).toEqual({ name: "Rule 100021 on arcane", auto_archive_duration: 10080 });
396
+ await rest.archiveThread("m9");
397
+ expect(calls[4].url).toBe("https://discord.com/api/v10/channels/m9");
398
+ expect(calls[4].init.method).toBe("PATCH");
399
+ expect(JSON.parse(calls[4].init.body as string)).toEqual({ archived: true });
400
+ await rest.createThread("c1", "2026-11-06: Weekly media picks");
401
+ expect(calls[5].url).toBe("https://discord.com/api/v10/channels/c1/threads");
402
+ expect(JSON.parse(calls[5].init.body as string)).toEqual({ name: "2026-11-06: Weekly media picks", auto_archive_duration: 10080, type: 11 });
403
+ });
404
+ });
405
+
406
+ describe("failure reply", () => {
407
+ it("names the reason and keeps stderr as an attachment", () => {
408
+ const base: RunResult = { agent: "astro.dns", agentSource: "bundled", task: "t", exitCode: 1, messages: [], stderr: "", usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0, contextTokens: 0, turns: 0 } };
409
+ expect(failureReply({ ...base, errorMessage: "timed out after 30 min" })).toEqual({ text: "timed out after 30 min" });
410
+ expect(failureReply({ ...base, stderr: "noise\n" })).toEqual({ text: "the specialist process exited with code 1", attachment: "noise" });
411
+ expect(failureReply({ ...base, stopReason: "aborted" as RunResult["stopReason"] }).text).toBe("the run was stopped");
412
+ const withWords = failureReply({ ...base, messages: [{ role: "assistant", content: [{ type: "text", text: "I asked for approval." }] } as never] });
413
+ expect(withWords.text).toContain("Last words of the specialist:\nI asked for approval.");
414
+ });
415
+ });
416
+
417
+ describe("approval server", () => {
418
+ it("creates tickets, reports decisions, expires, and rejects bad tokens", async () => {
419
+ const tickets: Ticket[] = [];
420
+ const expired: Ticket[] = [];
421
+ const closed: string[] = [];
422
+ const server = new ApprovalServer({ onTicket: (t) => tickets.push(t), onExpired: (t) => expired.push(t), onClosed: (t) => closed.push(t.id) }, 300);
423
+ await server.listen();
424
+ const headers = { Authorization: `Bearer ${server.token}`, "Content-Type": "application/json" };
425
+ expect((await fetch(`${server.url}/approvals`, { method: "POST", headers: { ...headers, Authorization: "Bearer nope" }, body: "{}" })).status).toBe(401);
426
+ expect((await fetch(`${server.url}/approvals`, { method: "POST", headers, body: JSON.stringify({ agent: "astro.dns" }) })).status).toBe(400);
427
+ const created = await fetch(`${server.url}/approvals`, { method: "POST", headers, body: JSON.stringify({ agent: "astro.dns", service: "dns", args: ["technitium", "primary", "zone-delete", "x"] }) });
428
+ expect(created.status).toBe(201);
429
+ const { id } = (await created.json()) as { id: string };
430
+ expect(tickets[0]).toMatchObject({ id, service: "dns", decision: null });
431
+ expect((await (await fetch(`${server.url}/approvals/${id}`, { headers })).json()) as object).toEqual({ id, decision: null });
432
+ expect(server.decide(id, "approve", ID)?.decidedBy).toBe(ID);
433
+ expect(server.decide(id, "deny", ID)).toBeUndefined();
434
+ expect((await (await fetch(`${server.url}/approvals/${id}`, { headers })).json()) as object).toEqual({ id, decision: "approve" });
435
+ const second = (await (await fetch(`${server.url}/approvals`, { method: "POST", headers, body: JSON.stringify({ agent: "astro.edge", service: "edge", args: ["vps", "reboot", "--confirm"] }) })).json()) as { id: string };
436
+ await new Promise((resolve) => setTimeout(resolve, 400));
437
+ expect(server.ticket(second.id)?.decision).toBe("timeout");
438
+ expect(expired.map((t) => t.id)).toEqual([second.id]);
439
+ expect(closed).toEqual([id, second.id]);
440
+ server.close();
441
+ });
442
+
443
+ it("keeps the bridge task of a specialist that another specialist called", async () => {
444
+ const tickets: Ticket[] = [];
445
+ const server = new ApprovalServer({ onTicket: (t) => tickets.push(t), onExpired: () => undefined, onClosed: () => undefined }, 60_000);
446
+ await server.listen();
447
+ const headers = { Authorization: `Bearer ${server.token}`, "Content-Type": "application/json" };
448
+ const post = (body: object) => fetch(`${server.url}/approvals`, { method: "POST", headers, body: JSON.stringify(body) });
449
+ expect((await post({ agent: "astro.backup", task: 1, service: "backup", args: [] })).status).toBe(400);
450
+ expect((await post({ agent: "astro.backup", task: "arcane", service: "backup", args: ["restic-restore", "b1d602e2"] })).status).toBe(201);
451
+ expect((await post({ agent: "astro.dns", service: "dns", args: ["x"] })).status).toBe(201);
452
+ expect(tickets.map(ticketTask)).toEqual(["arcane", "dns"]);
453
+ server.close();
454
+ });
455
+ });
456
+
457
+ describe("conversations", () => {
458
+ const now = 1_800_000_000_000;
459
+ it("continues on a reply or within the idle window, otherwise starts fresh", () => {
460
+ let state = startConversation({ conversations: {} }, "1:dns", "dns-a", now);
461
+ state = recordAnswer(state, "1:dns", ["m1"], now);
462
+ const input = { channelId: "1", specialist: "dns", fresh: false, now: now + 60_000 };
463
+ expect(resolveConversation(state, input, () => "dns-b")).toEqual({ key: "1:dns", id: "dns-a", resumed: true });
464
+ expect(resolveConversation(state, { ...input, now: now + CONVERSATION_IDLE_MS + 1 }, () => "dns-b")).toEqual({ key: "1:dns", id: "dns-b", resumed: false });
465
+ expect(resolveConversation(state, { ...input, now: now + CONVERSATION_IDLE_MS + 1, repliedTo: "m1" }, () => "dns-b")).toEqual({ key: "1:dns", id: "dns-a", resumed: true });
466
+ expect(resolveConversation(state, { ...input, fresh: true }, () => "dns-b")).toEqual({ key: "1:dns", id: "dns-b", resumed: false });
467
+ expect(resolveConversation(state, { ...input, channelId: "2" }, () => "dns-b").resumed).toBe(false);
468
+ expect(recordAnswer(state, "missing", ["x"], now)).toBe(state);
469
+ expect(forgetStale(state, now + CONVERSATION_MAX_AGE_MS + 1).conversations).toEqual({});
470
+ expect(forgetStale(state, now + 1).conversations["1:dns"]).toBeDefined();
471
+ });
472
+
473
+ it("finds the specialist of a replied-to answer and the one that asked a user", () => {
474
+ let state = startConversation(startConversation({ conversations: {} }, "1:dns", "dns-a", now), "1:proxmox", "proxmox-a", now);
475
+ state = recordAnswer(state, "1:dns", ["m1"], now, "u1");
476
+ state = recordAnswer(state, "1:proxmox", ["m2"], now + 1000, "u1");
477
+ expect(replySpecialist(state, "1", "m2")).toBe("proxmox");
478
+ expect(replySpecialist(state, "2", "m2")).toBeNull();
479
+ expect(askingSpecialist(state, "1", "u1", now + 2000)).toBe("proxmox");
480
+ expect(askingSpecialist(state, "1", "u2", now + 2000)).toBeNull();
481
+ expect(askingSpecialist(state, "1", "u1", now + 1000 + CONVERSATION_IDLE_MS)).toBeNull();
482
+ state = recordAnswer(state, "1:proxmox", ["m3"], now + 3000);
483
+ expect(state.conversations["1:proxmox"]?.asked).toBeUndefined();
484
+ expect(askingSpecialist(state, "1", "u1", now + 4000)).toBe("dns");
485
+ });
486
+
487
+ it("builds Pi-compatible ids and round-trips the state file", () => {
488
+ const id = newConversationId("security", Date.UTC(2026, 8, 16, 20, 55, 0), () => "abc123");
489
+ expect(id).toBe("security-20260916205500-abc123");
490
+ expect(id).toMatch(/^[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?$/);
491
+ const dir = mkdtempSync(join(tmpdir(), "astro-conv-"));
492
+ process.env.ASTRO_DISCORD_DIR = dir;
493
+ try {
494
+ expect(loadState()).toEqual({ conversations: {} });
495
+ const state = recordAnswer(startConversation({ conversations: {} }, "1:dns", id, now), "1:dns", ["m1"], now);
496
+ saveState(state);
497
+ expect(loadState()).toEqual(state);
498
+ writeFileSync(join(dir, "conversations.json"), JSON.stringify({ conversations: { bad: { id: 1 }, ok: { id: "x", lastAt: 1, messageIds: [] } } }));
499
+ expect(Object.keys(loadState().conversations)).toEqual(["ok"]);
500
+ } finally {
501
+ delete process.env.ASTRO_DISCORD_DIR;
502
+ rmSync(dir, { recursive: true, force: true });
503
+ }
504
+ });
505
+ });
506
+
507
+ describe("quotes", () => {
508
+ it("flattens content, embeds, and attachments and appends them to the task", () => {
509
+ const alert = { content: "", embeds: [{ title: "Wazuh alert, level 12", description: "System running out of memory.", fields: [{ name: "agent", value: "arcane" }], footer: { text: "rule 5108" } }], attachments: [{ filename: "log.txt" }] };
510
+ expect(quoteText(alert)).toBe("Wazuh alert, level 12\nSystem running out of memory.\nagent: arcane\nrule 5108\nAttachments: log.txt");
511
+ expect(quoteText({ content: "x".repeat(5000) })).toHaveLength(4001);
512
+ expect(withQuotes("check this", [])).toBe("check this");
513
+ expect(withQuotes("check this", [{ label: "Forwarded message", message: { content: "" } }])).toBe("check this");
514
+ expect(withQuotes("check this", [{ label: "Forwarded message", message: alert }])).toMatch(/^check this\n\nForwarded message:\nWazuh alert/);
515
+ });
516
+ });
517
+
518
+ describe("image attachments", () => {
519
+ const png = { filename: "alert.png", url: "https://cdn.example/alert.png", content_type: "image/png", size: 1000 };
520
+ const image = { filename: png.filename, url: png.url, contentType: png.content_type, size: png.size };
521
+ it("keeps images within the limits, in message order", () => {
522
+ const big = { ...png, filename: "big.png", size: MAX_IMAGE_BYTES + 1 };
523
+ const text = { filename: "log.txt", url: "https://cdn.example/log.txt", content_type: "text/plain", size: 10 };
524
+ const many = Array.from({ length: 6 }, (_, i) => ({ ...png, filename: `${i}.png` }));
525
+ expect(imageAttachments([{ attachments: [text, big, png] }, { attachments: [{ ...png, filename: "quoted.jpg" }] }]).map((i) => i.filename)).toEqual(["alert.png", "quoted.jpg"]);
526
+ expect(imageAttachments([{ attachments: many }])).toHaveLength(4);
527
+ expect(imageAttachments([{}])).toEqual([]);
528
+ });
529
+
530
+ it("downloads to a private temp dir and reports failures", async () => {
531
+ const fetchImpl = vi.fn(async (url: string | URL | Request) => {
532
+ const u = String(url);
533
+ if (u.endsWith("missing.png")) return new Response("nope", { status: 404 });
534
+ return new Response(new Uint8Array([137, 80, 78, 71]), { status: 200 });
535
+ }) as unknown as typeof fetch;
536
+ const result = await downloadImages([image, { ...image, filename: "missing.png", url: "https://cdn.example/missing.png" }], fetchImpl);
537
+ try {
538
+ expect(result.files).toHaveLength(1);
539
+ expect(result.files[0]).toMatch(/\/1-[0-9a-f]{12}\.png$/);
540
+ expect(result.failed).toEqual(["missing.png"]);
541
+ expect(describeImages("check this", [image, { ...image, filename: "missing.png" }], result.failed)).toBe("check this\n\nImages attached to the message, included with this task: alert.png.\nImages that could not be fetched: missing.png.");
542
+ expect(describeImages("check this", [], [])).toBe("check this");
543
+ } finally {
544
+ rmSync(result.dir, { recursive: true, force: true });
545
+ }
546
+ });
547
+ });