@astrofoundry/astrogate 0.0.0-stage → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (101) hide show
  1. package/README.md +13 -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/cli/astrogate.sh +309 -0
  7. package/cli/astrogate.test.ts +113 -0
  8. package/cli/verify-release.sh +77 -0
  9. package/cli/verify-release.test.ts +140 -0
  10. package/dist/bridge.js +9950 -0
  11. package/dist/claude.js +7899 -0
  12. package/dist/extensions/bridge/index.js +9937 -0
  13. package/dist/extensions/gate/index.js +286 -0
  14. package/dist/extensions/guard/index.js +364 -0
  15. package/dist/extensions/subagents/index.js +8458 -0
  16. package/extensions/bridge/admin.ts +86 -0
  17. package/extensions/bridge/approvals.ts +147 -0
  18. package/extensions/bridge/attachments.ts +65 -0
  19. package/extensions/bridge/chunk.ts +50 -0
  20. package/extensions/bridge/claude-run.test.ts +62 -0
  21. package/extensions/bridge/claude-run.ts +301 -0
  22. package/extensions/bridge/commands.ts +89 -0
  23. package/extensions/bridge/config.ts +263 -0
  24. package/extensions/bridge/conversations.ts +144 -0
  25. package/extensions/bridge/daemon.ts +60 -0
  26. package/extensions/bridge/discord.test.ts +547 -0
  27. package/extensions/bridge/gateway.ts +222 -0
  28. package/extensions/bridge/index.ts +951 -0
  29. package/extensions/bridge/launcher.ts +36 -0
  30. package/extensions/bridge/lifecycle.test.ts +78 -0
  31. package/extensions/bridge/open-work.ts +74 -0
  32. package/extensions/bridge/plugin.ts +172 -0
  33. package/extensions/bridge/quote.ts +39 -0
  34. package/extensions/bridge/reports.ts +65 -0
  35. package/extensions/bridge/rest.ts +217 -0
  36. package/extensions/bridge/setup.ts +218 -0
  37. package/extensions/gate/approvals.test.ts +40 -0
  38. package/extensions/gate/config.ts +110 -0
  39. package/extensions/gate/core.ts +114 -0
  40. package/extensions/gate/index.test.ts +202 -0
  41. package/extensions/gate/index.ts +114 -0
  42. package/extensions/gate/risky.ts +14 -0
  43. package/extensions/gate/types.ts +19 -0
  44. package/extensions/guard/config.test.ts +107 -0
  45. package/extensions/guard/config.ts +120 -0
  46. package/extensions/guard/defaults.ts +40 -0
  47. package/extensions/guard/index.test.ts +313 -0
  48. package/extensions/guard/index.ts +183 -0
  49. package/extensions/guard/rules.test.ts +118 -0
  50. package/extensions/guard/rules.ts +101 -0
  51. package/extensions/guard/types.ts +12 -0
  52. package/extensions/subagents/agents.test.ts +137 -0
  53. package/extensions/subagents/agents.ts +207 -0
  54. package/extensions/subagents/bundled.test.ts +29 -0
  55. package/extensions/subagents/child.test.ts +202 -0
  56. package/extensions/subagents/child.ts +367 -0
  57. package/extensions/subagents/index.test.ts +123 -0
  58. package/extensions/subagents/index.ts +352 -0
  59. package/extensions/subagents/pi-paths.test.ts +39 -0
  60. package/extensions/subagents/pi-paths.ts +58 -0
  61. package/extensions/subagents/render.ts +221 -0
  62. package/extensions/subagents/sessions.test.ts +32 -0
  63. package/extensions/subagents/sessions.ts +34 -0
  64. package/extensions/subagents/ticker.test.ts +40 -0
  65. package/extensions/subagents/ticker.ts +36 -0
  66. package/harness/claude/agents.ts +93 -0
  67. package/harness/claude/claude.test.ts +171 -0
  68. package/harness/claude/hook.ts +77 -0
  69. package/harness/claude/main.ts +122 -0
  70. package/harness/claude/mcp.ts +174 -0
  71. package/harness/claude/settings.ts +63 -0
  72. package/package.json +71 -4
  73. package/release.sha256 +99 -0
  74. package/release.sha256.sig +6 -0
  75. package/specialists/AGENTS.md +67 -0
  76. package/specialists/README.md +81 -0
  77. package/specialists/entry/specialist-cli.sh +22 -0
  78. package/specialists/entry/specialist-install.sh +861 -0
  79. package/specialists/entry/specialist-install.test.ts +305 -0
  80. package/specialists/lib/argv.ts +19 -0
  81. package/specialists/lib/audit.ts +20 -0
  82. package/specialists/lib/config.ts +27 -0
  83. package/specialists/lib/errors.ts +8 -0
  84. package/specialists/lib/flush.test.ts +21 -0
  85. package/specialists/lib/lib.test.ts +87 -0
  86. package/specialists/lib/lock.test.ts +42 -0
  87. package/specialists/lib/lock.ts +67 -0
  88. package/specialists/lib/main.ts +40 -0
  89. package/specialists/lib/output.ts +11 -0
  90. package/specialists/lib/paths.ts +22 -0
  91. package/specialists/lib/pinned.test.ts +55 -0
  92. package/specialists/lib/pinned.ts +67 -0
  93. package/specialists/lib/proc.ts +49 -0
  94. package/specialists/lib/repo.ts +198 -0
  95. package/specialists/lib/runtime.test.ts +81 -0
  96. package/specialists/lib/sanitize.ts +43 -0
  97. package/specialists/lib/secrets.ts +28 -0
  98. package/specialists/lib/ssh.ts +38 -0
  99. package/specialists/lib/tunnel.test.ts +44 -0
  100. package/specialists/lib/tunnel.ts +76 -0
  101. package/specialists/provision/provision.sh +96 -0
@@ -0,0 +1,86 @@
1
+ import { type ChannelSettings, type DiscordConfig, RUNNERS, type Runner, SNOWFLAKE, SPECIALIST } from "./config.ts";
2
+
3
+ export interface AdminResult {
4
+ reply: string;
5
+ /** Present when the command changed the configuration. */
6
+ config?: DiscordConfig;
7
+ }
8
+
9
+ const USAGE = [
10
+ "config show",
11
+ "config channel <#channel> <always|mention> <*|name,name>",
12
+ "config channel <#channel> remove",
13
+ "config access <specialist> add|remove <@user>",
14
+ "config runner <pi|claude>",
15
+ ].join("\n");
16
+
17
+ function idOf(token: string | undefined, kind: "channel" | "user"): string | null {
18
+ if (token === undefined) return null;
19
+ const match = kind === "channel" ? /^<#(\d{17,20})>$/.exec(token) : /^<@!?(\d{17,20})>$/.exec(token);
20
+ const id = match ? match[1] : token;
21
+ return SNOWFLAKE.test(id) ? id : null;
22
+ }
23
+
24
+ export function describeConfig(config: DiscordConfig): string {
25
+ const channels = Object.entries(config.channels).map(([id, c]) => `• <#${id}>: ${c.trigger}, ${c.specialists === "*" ? "every specialist" : c.specialists.join(", ")}${id === config.adminChannelId ? " (admin)" : ""}`);
26
+ const access = Object.entries(config.access)
27
+ .filter(([, ids]) => ids.length > 0)
28
+ .map(([name, ids]) => `• ${name}: ${ids.map((id) => `<@${id}>`).join(", ")}`);
29
+ return [
30
+ "Channels:",
31
+ ...channels,
32
+ `Owners: ${config.owners.map((id) => `<@${id}>`).join(", ")}`,
33
+ access.length > 0 ? "Extra access:" : "Extra access: none",
34
+ ...access,
35
+ `Approval timeout: ${config.approvalTimeoutMinutes} min`,
36
+ `Runner: ${config.runner === "claude" ? "Claude Code" : "Pi"}`,
37
+ config.reports.length > 0 ? `Reports: ${config.reports.map((r) => `${r.report} at ${r.time} ${r.timeZone} in <#${r.channelId}>`).join("; ")}` : "Reports: off",
38
+ ].join("\n");
39
+ }
40
+
41
+ /** Applies one owner `config` command to a copy of the configuration. */
42
+ export function applyAdminCommand(config: DiscordConfig, args: readonly string[], configured: readonly string[]): AdminResult {
43
+ const [verb, ...rest] = args;
44
+ if (verb === undefined || verb === "show") return { reply: describeConfig(config) };
45
+ if (verb === "channel") {
46
+ const channelId = idOf(rest[0], "channel");
47
+ if (!channelId) return { reply: `channel id missing.\n${USAGE}` };
48
+ if (rest[1] === "remove") {
49
+ if (!(channelId in config.channels)) return { reply: `<#${channelId}> is not configured.` };
50
+ if (channelId === config.adminChannelId) return { reply: "The admin channel cannot be removed." };
51
+ const channels = { ...config.channels };
52
+ delete channels[channelId];
53
+ return { reply: `Removed <#${channelId}>.`, config: { ...config, channels } };
54
+ }
55
+ if (rest[1] !== "always" && rest[1] !== "mention") return { reply: `trigger must be always or mention.\n${USAGE}` };
56
+ const names = rest[2] === "*" ? "*" : (rest[2] ?? "").split(",").map((n) => n.trim()).filter(Boolean);
57
+ if (names !== "*") {
58
+ if (names.length === 0) return { reply: `specialists missing.\n${USAGE}` };
59
+ const unknown = names.filter((n) => !SPECIALIST.test(n) || !configured.includes(n));
60
+ if (unknown.length > 0) return { reply: `unknown specialist(s): ${unknown.join(", ")}. Configured: ${configured.join(", ")}.` };
61
+ }
62
+ const settings: ChannelSettings = { trigger: rest[1], specialists: names === "*" ? "*" : [...new Set(names)] };
63
+ const verbNow = channelId in config.channels ? "Updated" : "Added";
64
+ return {
65
+ reply: `${verbNow} <#${channelId}>: ${settings.trigger}, ${settings.specialists === "*" ? "every specialist" : settings.specialists.join(", ")}.`,
66
+ config: { ...config, channels: { ...config.channels, [channelId]: settings } },
67
+ };
68
+ }
69
+ if (verb === "access") {
70
+ const [name, action, who] = rest;
71
+ if (name === undefined || !configured.includes(name)) return { reply: `unknown specialist. Configured: ${configured.join(", ")}.` };
72
+ const userId = idOf(who, "user");
73
+ if ((action !== "add" && action !== "remove") || !userId) return { reply: USAGE };
74
+ const current = config.access[name] ?? [];
75
+ const next = action === "add" ? [...new Set([...current, userId])] : current.filter((id) => id !== userId);
76
+ if (next.length === current.length) return { reply: action === "add" ? `<@${userId}> already has ${name}.` : `<@${userId}> did not have ${name}.` };
77
+ return { reply: `${action === "add" ? "Granted" : "Revoked"} ${name} for <@${userId}>.`, config: { ...config, access: { ...config.access, [name]: next } } };
78
+ }
79
+ if (verb === "runner") {
80
+ const runner = rest[0] as Runner | undefined;
81
+ if (runner === undefined || !RUNNERS.includes(runner) || rest.length !== 1) return { reply: USAGE };
82
+ if (runner === config.runner) return { reply: `The runner is already ${runner === "claude" ? "Claude Code" : "Pi"}.` };
83
+ return { reply: `Specialists now run in ${runner === "claude" ? "Claude Code" : "Pi"}; a conversation started in the other harness starts over.`, config: { ...config, runner } };
84
+ }
85
+ return { reply: USAGE };
86
+ }
@@ -0,0 +1,147 @@
1
+ import { randomBytes, randomUUID } from "node:crypto";
2
+ import { createServer, type Server } from "node:http";
3
+
4
+ export type Decision = "approve" | "deny" | "timeout";
5
+
6
+ /** Longest command an approval message shows inline; Discord refuses messages above 2000 characters. */
7
+ export const APPROVAL_INLINE_CHARS = 1200;
8
+ const APPROVAL_PREVIEW_CHARS = 300;
9
+
10
+ /**
11
+ * How an approval shows the command: whole when it is short, otherwise its start in the message and the whole
12
+ * command as an attached text file, so the owner can still read everything he approves.
13
+ */
14
+ export function approvalCommand(args: readonly string[]): { inline: string; file?: { name: string; content: string } } {
15
+ const whole = args.join(" ");
16
+ if (whole.length <= APPROVAL_INLINE_CHARS) return { inline: whole };
17
+ return { inline: `${whole.slice(0, APPROVAL_PREVIEW_CHARS)}… (${whole.length} characters, the whole command is attached)`, file: { name: "command.txt", content: `${whole}\n` } };
18
+ }
19
+
20
+ export interface Ticket {
21
+ id: string;
22
+ agent: string;
23
+ /** The bridge task that waits for this ticket; it differs from `agent` when one specialist called another. */
24
+ task: string | null;
25
+ service: string;
26
+ args: string[];
27
+ createdAt: number;
28
+ decision: Decision | null;
29
+ decidedBy: string | null;
30
+ }
31
+
32
+ export interface ApprovalEvents {
33
+ /** Called once per new ticket so the bridge can ask the operator. */
34
+ onTicket: (ticket: Ticket) => void;
35
+ /** Called when a ticket ran out of time without a decision. */
36
+ onExpired: (ticket: Ticket) => void;
37
+ /** Called once per ticket when it is decided or runs out of time. */
38
+ onClosed: (ticket: Ticket) => void;
39
+ }
40
+
41
+ /**
42
+ * Loopback HTTP endpoint the specialist gate talks to: `POST /approvals`
43
+ * creates a ticket, `GET /approvals/<id>` reports its decision. Only
44
+ * requests carrying the per-process bearer token are accepted.
45
+ */
46
+ export class ApprovalServer {
47
+ readonly token = randomBytes(24).toString("hex");
48
+ private readonly tickets = new Map<string, Ticket>();
49
+ private server: Server | null = null;
50
+ private port = 0;
51
+
52
+ private readonly events: ApprovalEvents;
53
+ private readonly timeoutMs: number;
54
+
55
+ constructor(events: ApprovalEvents, timeoutMs: number) {
56
+ this.events = events;
57
+ this.timeoutMs = timeoutMs;
58
+ }
59
+
60
+ get url(): string {
61
+ return `http://127.0.0.1:${this.port}`;
62
+ }
63
+
64
+ ticket(id: string): Ticket | undefined {
65
+ return this.tickets.get(id);
66
+ }
67
+
68
+ decide(id: string, decision: Decision, by: string): Ticket | undefined {
69
+ const ticket = this.tickets.get(id);
70
+ if (!ticket || ticket.decision !== null) return undefined;
71
+ ticket.decision = decision;
72
+ ticket.decidedBy = by;
73
+ this.events.onClosed(ticket);
74
+ return ticket;
75
+ }
76
+
77
+ async listen(): Promise<void> {
78
+ const server = createServer((req, res) => {
79
+ const auth = req.headers.authorization ?? "";
80
+ if (auth !== `Bearer ${this.token}`) {
81
+ res.writeHead(401).end();
82
+ return;
83
+ }
84
+ const url = new URL(req.url ?? "/", "http://127.0.0.1");
85
+ if (req.method === "POST" && url.pathname === "/approvals") {
86
+ let body = "";
87
+ req.on("data", (chunk: Buffer) => {
88
+ body += chunk.toString("utf-8");
89
+ if (body.length > 65_536) req.destroy();
90
+ });
91
+ req.on("end", () => {
92
+ let parsed: { agent?: unknown; task?: unknown; service?: unknown; args?: unknown };
93
+ try {
94
+ parsed = JSON.parse(body) as typeof parsed;
95
+ } catch {
96
+ res.writeHead(400).end();
97
+ return;
98
+ }
99
+ if (typeof parsed.agent !== "string" || typeof parsed.service !== "string" || !Array.isArray(parsed.args) || !parsed.args.every((a) => typeof a === "string") || (parsed.task !== undefined && typeof parsed.task !== "string")) {
100
+ res.writeHead(400).end();
101
+ return;
102
+ }
103
+ const ticket: Ticket = { id: randomUUID(), agent: parsed.agent, task: typeof parsed.task === "string" ? parsed.task : null, service: parsed.service, args: parsed.args as string[], createdAt: Date.now(), decision: null, decidedBy: null };
104
+ this.tickets.set(ticket.id, ticket);
105
+ setTimeout(() => {
106
+ if (ticket.decision === null) {
107
+ ticket.decision = "timeout";
108
+ ticket.decidedBy = null;
109
+ this.events.onExpired(ticket);
110
+ this.events.onClosed(ticket);
111
+ }
112
+ setTimeout(() => this.tickets.delete(ticket.id), 60_000).unref();
113
+ }, this.timeoutMs).unref();
114
+ this.events.onTicket(ticket);
115
+ res.writeHead(201, { "Content-Type": "application/json" }).end(JSON.stringify({ id: ticket.id }));
116
+ });
117
+ return;
118
+ }
119
+ const match = /^\/approvals\/([0-9a-f-]{36})$/.exec(url.pathname);
120
+ if (req.method === "GET" && match) {
121
+ const ticket = this.tickets.get(match[1]);
122
+ if (!ticket) {
123
+ res.writeHead(404).end();
124
+ return;
125
+ }
126
+ res.writeHead(200, { "Content-Type": "application/json" }).end(JSON.stringify({ id: ticket.id, decision: ticket.decision }));
127
+ return;
128
+ }
129
+ res.writeHead(404).end();
130
+ });
131
+ await new Promise<void>((resolve, reject) => {
132
+ server.once("error", reject);
133
+ server.listen(0, "127.0.0.1", () => {
134
+ const address = server.address();
135
+ this.port = typeof address === "object" && address ? address.port : 0;
136
+ resolve();
137
+ });
138
+ });
139
+ server.unref();
140
+ this.server = server;
141
+ }
142
+
143
+ close(): void {
144
+ this.server?.close();
145
+ this.server = null;
146
+ }
147
+ }
@@ -0,0 +1,65 @@
1
+ import { createHash } from "node:crypto";
2
+ import { promises as fs } from "node:fs";
3
+ import * as os from "node:os";
4
+ import * as path from "node:path";
5
+ import type { QuotedMessage } from "./quote.ts";
6
+
7
+ /** An image on a Discord message, by its CDN url. */
8
+ export interface ImageAttachment {
9
+ filename: string;
10
+ url: string;
11
+ contentType: string;
12
+ size: number;
13
+ }
14
+
15
+ export const MAX_IMAGES = 4;
16
+ export const MAX_IMAGE_BYTES = 8 * 1024 * 1024;
17
+
18
+ /** Image attachments of the message and of the messages it quotes, oldest quote first, within the count and size limits. */
19
+ export function imageAttachments(messages: readonly QuotedMessage[]): ImageAttachment[] {
20
+ const images: ImageAttachment[] = [];
21
+ for (const message of messages) {
22
+ for (const a of message.attachments ?? []) {
23
+ if (!a.url || !a.content_type?.startsWith("image/") || (a.size ?? 0) > MAX_IMAGE_BYTES) continue;
24
+ images.push({ filename: a.filename, url: a.url, contentType: a.content_type, size: a.size ?? 0 });
25
+ }
26
+ }
27
+ return images.slice(0, MAX_IMAGES);
28
+ }
29
+
30
+ export interface DownloadedImages {
31
+ dir: string;
32
+ files: string[];
33
+ failed: string[];
34
+ }
35
+
36
+ /** Saves the images to a private temp directory, named by an index and a hash so filenames from Discord never reach the file system. */
37
+ export async function downloadImages(images: readonly ImageAttachment[], fetchImpl: typeof fetch = fetch): Promise<DownloadedImages> {
38
+ const dir = await fs.mkdtemp(path.join(os.tmpdir(), "astro-discord-images-"));
39
+ const files: string[] = [];
40
+ const failed: string[] = [];
41
+ for (const [index, image] of images.entries()) {
42
+ try {
43
+ const response = await fetchImpl(image.url);
44
+ if (!response.ok) throw new Error(`HTTP ${response.status}`);
45
+ const bytes = Buffer.from(await response.arrayBuffer());
46
+ if (bytes.length > MAX_IMAGE_BYTES) throw new Error("larger than the limit");
47
+ const name = `${index + 1}-${createHash("sha256").update(image.url).digest("hex").slice(0, 12)}${path.extname(image.filename).toLowerCase().replace(/[^.a-z0-9]/g, "")}`;
48
+ const file = path.join(dir, name);
49
+ await fs.writeFile(file, bytes, { mode: 0o600 });
50
+ files.push(file);
51
+ } catch {
52
+ failed.push(image.filename);
53
+ }
54
+ }
55
+ return { dir, files, failed };
56
+ }
57
+
58
+ /** Task text telling the specialist which images travel with it and which could not be fetched. */
59
+ export function describeImages(task: string, images: readonly ImageAttachment[], failed: readonly string[]): string {
60
+ const lines: string[] = [];
61
+ const fetched = images.filter((i) => !failed.includes(i.filename));
62
+ if (fetched.length > 0) lines.push(`Images attached to the message, included with this task: ${fetched.map((i) => i.filename).join(", ")}.`);
63
+ if (failed.length > 0) lines.push(`Images that could not be fetched: ${failed.join(", ")}.`);
64
+ return lines.length === 0 ? task : `${task}\n\n${lines.join("\n")}`;
65
+ }
@@ -0,0 +1,50 @@
1
+ /** Discord's limit for one message body. */
2
+ export const MESSAGE_LIMIT = 2000;
3
+
4
+ /**
5
+ * Splits text into Discord-sized chunks, preferring paragraph and line
6
+ * boundaries and never leaving a code fence open across a chunk.
7
+ */
8
+ export function chunkMessage(text: string, limit = MESSAGE_LIMIT): string[] {
9
+ const trimmed = text.trim();
10
+ if (trimmed.length === 0) return [];
11
+ const chunks: string[] = [];
12
+ let rest = trimmed;
13
+ let openFence: string | null = null;
14
+ while (rest.length > 0) {
15
+ const closing = 4;
16
+ const budget = limit - closing - (openFence ? openFence.length + 1 : 0);
17
+ let piece: string;
18
+ if (rest.length <= budget) {
19
+ piece = rest;
20
+ rest = "";
21
+ } else {
22
+ let cut = rest.lastIndexOf("\n\n", budget);
23
+ if (cut < budget / 2) cut = rest.lastIndexOf("\n", budget);
24
+ if (cut < budget / 2) cut = rest.lastIndexOf(" ", budget);
25
+ if (cut < budget / 2) cut = budget;
26
+ piece = rest.slice(0, cut);
27
+ rest = rest.slice(cut).replace(/^\s+/, "");
28
+ }
29
+ let body = openFence ? `${openFence}\n${piece}` : piece;
30
+ const fenceAfter = fenceState(body, null);
31
+ if (fenceAfter && rest.length > 0) {
32
+ body = `${body}\n\`\`\``;
33
+ }
34
+ openFence = fenceAfter;
35
+ chunks.push(body);
36
+ }
37
+ return chunks;
38
+ }
39
+
40
+ /** The fence line that is open at the end of `text`, or null when balanced. */
41
+ export function fenceState(text: string, initial: string | null): string | null {
42
+ let open = initial;
43
+ for (const line of text.split("\n")) {
44
+ const match = /^(\s*)(```+|~~~+)(.*)$/.exec(line);
45
+ if (!match) continue;
46
+ if (open === null) open = `${match[2]}${match[3].trim()}`;
47
+ else if (line.trim().startsWith(open.slice(0, 3))) open = null;
48
+ }
49
+ return open;
50
+ }
@@ -0,0 +1,62 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { emptyUsage, type RunResult } from "../subagents/child.ts";
3
+ import { applyClaudeLine, claudeArgs, sessionFile, sessionUuid, toolName } from "./claude-run.ts";
4
+
5
+ function fresh(): RunResult {
6
+ return { agent: "astro-arcane", agentSource: "unknown", task: "t", exitCode: -1, messages: [], stderr: "", usage: emptyUsage() };
7
+ }
8
+
9
+ const line = (event: Record<string, unknown>) => JSON.stringify(event);
10
+
11
+ describe("claude runner", () => {
12
+ it("derives one stable UUID per conversation and finds its session file", () => {
13
+ const a = sessionUuid("arcane-20261201120000-abc123");
14
+ expect(a).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/);
15
+ expect(sessionUuid("arcane-20261201120000-abc123")).toBe(a);
16
+ expect(sessionUuid("arcane-20261201120000-abc124")).not.toBe(a);
17
+ expect(sessionFile("/Users/cortex", a, "/Users/cortex")).toBe(`/Users/cortex/.claude/projects/-Users-cortex/${a}.jsonl`);
18
+ });
19
+
20
+ it("starts a new session or resumes one, with user settings only and the channel rules", () => {
21
+ const base = { service: "arcane", conversationId: "c1", appendSystemPrompt: "rules" };
22
+ const id = sessionUuid("c1");
23
+ expect(claudeArgs({ ...base, resume: false })).toEqual(["-p", "--agent", "astro-arcane", "--output-format", "stream-json", "--verbose", "--setting-sources", "user", "--append-system-prompt", "rules", "--session-id", id]);
24
+ expect(claudeArgs({ ...base, resume: true }).slice(-2)).toEqual(["--resume", id]);
25
+ });
26
+
27
+ it("names a specialist tool after its service", () => {
28
+ expect(toolName("mcp__astro-arcane__run")).toBe("arcane");
29
+ expect(toolName("Read")).toBe("Read");
30
+ });
31
+
32
+ it("turns tool calls, results, and the end of the run into Pi-shaped messages", () => {
33
+ const result = fresh();
34
+ const names = new Map<string, string>();
35
+ expect(applyClaudeLine(line({ type: "system", subtype: "init", model: "claude-opus-5-5" }), result, names)).toBe(false);
36
+ expect(result.model).toBe("claude-opus-5-5");
37
+ expect(applyClaudeLine(line({ type: "assistant", message: { content: [{ type: "thinking", thinking: "x" }, { type: "tool_use", id: "t1", name: "mcp__astro-arcane__run", input: { args: ["stack-update", "media"] } }] } }), result, names)).toBe(true);
38
+ expect(applyClaudeLine(line({ type: "user", message: { content: [{ type: "tool_result", tool_use_id: "t1", content: [{ type: "text", text: '{"status":"updated"}' }] }] } }), result, names)).toBe(true);
39
+ expect(applyClaudeLine(line({ type: "assistant", parent_tool_use_id: "x", message: { content: [{ type: "text", text: "nested" }] } }), result, names)).toBe(false);
40
+ expect(applyClaudeLine(line({ type: "assistant", message: { content: [{ type: "text", text: "Updated media." }] } }), result, names)).toBe(true);
41
+ expect(applyClaudeLine(line({ type: "result", subtype: "success", is_error: false, result: "Updated media.", num_turns: 3, usage: { input_tokens: 10, output_tokens: 5 }, total_cost_usd: 0.01 }), result, names)).toBe(true);
42
+ expect(applyClaudeLine("not json", result, names)).toBe(false);
43
+ expect(result.messages).toMatchObject([
44
+ { role: "assistant", stopReason: "toolUse", content: [{ type: "toolCall", id: "t1", name: "arcane", arguments: { args: ["stack-update", "media"] } }] },
45
+ { role: "toolResult", toolCallId: "t1", toolName: "arcane", isError: false, content: [{ type: "text", text: '{"status":"updated"}' }] },
46
+ { role: "assistant", stopReason: "stop", content: [{ type: "text", text: "Updated media." }] },
47
+ ]);
48
+ expect(result.usage).toMatchObject({ input: 10, output: 5, turns: 3, cost: 0.01 });
49
+ expect(result.stopReason).toBeUndefined();
50
+ });
51
+
52
+ it("marks a failed run with its reason", () => {
53
+ const result = fresh();
54
+ applyClaudeLine(line({ type: "user", message: { content: [{ type: "tool_result", tool_use_id: "t9", is_error: true, content: "denied" }] } }), result, new Map());
55
+ expect(result.messages[0]).toMatchObject({ toolName: "unknown", isError: true, content: [{ text: "denied" }] });
56
+ applyClaudeLine(line({ type: "result", subtype: "success", is_error: true, result: "Failed to authenticate" }), result, new Map());
57
+ expect(result).toMatchObject({ stopReason: "error", errorMessage: "Failed to authenticate" });
58
+ const limit = fresh();
59
+ applyClaudeLine(line({ type: "result", subtype: "error_max_turns" }), limit, new Map());
60
+ expect(limit.errorMessage).toBe("Claude Code ended with error_max_turns");
61
+ });
62
+ });