@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,202 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import type { AgentConfig } from "./agents.ts";
3
+ import {
4
+ AGENT_ENV,
5
+ applyEventLine,
6
+ buildChildArgs,
7
+ buildChildEnv,
8
+ childRemaining,
9
+ composeSystemPrompt,
10
+ currentDepth,
11
+ DEPTH_ENV,
12
+ emptyUsage,
13
+ finalOutput,
14
+ isFailed,
15
+ piInvocation,
16
+ REMAINING_ENV,
17
+ resultOutput,
18
+ RunClock,
19
+ type RunResult,
20
+ runAgent,
21
+ } from "./child.ts";
22
+
23
+ const agent: AgentConfig = {
24
+ name: "astro.arcane",
25
+ description: "d",
26
+ tools: ["read", "arcane", "subagent"],
27
+ skills: ["arcane"],
28
+ systemPromptMode: "replace",
29
+ inheritProjectContext: false,
30
+ inheritSkills: false,
31
+ maxSubagentDepth: 1,
32
+ systemPrompt: "You are the Arcane specialist.",
33
+ source: "bundled",
34
+ filePath: "/pkg/agents/arcane.md",
35
+ };
36
+
37
+ describe("child arguments", () => {
38
+ it("builds a print-mode invocation with a strict tool allowlist and replaced prompt", () => {
39
+ const args = buildChildArgs({ agent, task: "list projects", promptFile: "/tmp/p.md", defaults: { model: "openai-codex/gpt-5.5", thinkingLevel: "medium" } });
40
+ expect(args).toEqual([
41
+ "--mode", "json", "-p", "--no-session",
42
+ "--model", "openai-codex/gpt-5.5",
43
+ "--thinking", "medium",
44
+ "--tools", "read,arcane,subagent",
45
+ "--no-context-files",
46
+ "--no-skills",
47
+ "--system-prompt", "/tmp/p.md",
48
+ "--", "Task: list projects",
49
+ ]);
50
+ });
51
+
52
+ it("appends instead of replacing and inherits context when asked", () => {
53
+ const open: AgentConfig = { ...agent, tools: undefined, systemPromptMode: "append", inheritProjectContext: true, inheritSkills: true, model: "anthropic/claude-x", thinking: "high" };
54
+ const args = buildChildArgs({ agent: open, task: "t", promptFile: "/tmp/p.md", defaults: { model: "other", thinkingLevel: "low" } });
55
+ expect(args).toEqual(["--mode", "json", "-p", "--no-session", "--model", "anthropic/claude-x", "--thinking", "high", "--append-system-prompt", "/tmp/p.md", "--", "Task: t"]);
56
+ });
57
+
58
+ it("disables every tool for an agent declared with tools: none", () => {
59
+ const args = buildChildArgs({ agent: { ...agent, tools: [] }, task: "t", promptFile: null, defaults: {} });
60
+ expect(args).toContain("--no-tools");
61
+ expect(args).not.toContain("--tools");
62
+ });
63
+
64
+ it("does not pass the parent's thinking level to an agent that pins its own model", () => {
65
+ const pinned: AgentConfig = { ...agent, model: "m" };
66
+ expect(buildChildArgs({ agent: pinned, task: "t", promptFile: null, defaults: { thinkingLevel: "high" } })).not.toContain("--thinking");
67
+ const saved = buildChildArgs({ agent: pinned, task: "t", promptFile: null, defaults: {}, session: { dir: "/s/x", continue: true } });
68
+ expect(saved.slice(0, 6)).toEqual(["--mode", "json", "-p", "--session-dir", "/s/x", "--continue"]);
69
+ expect(saved).not.toContain("--no-session");
70
+ const exact = buildChildArgs({ agent: pinned, task: "t", promptFile: null, defaults: {}, session: { dir: "/s/x", id: "dns-1", continue: true } });
71
+ expect(exact.slice(3, 7)).toEqual(["--session-dir", "/s/x", "--session-id", "dns-1"]);
72
+ expect(exact).not.toContain("--continue");
73
+ const withFiles = buildChildArgs({ agent: pinned, task: "t", promptFile: null, defaults: {}, files: ["/tmp/a.png", "/tmp/b.png"] });
74
+ expect(withFiles.slice(-4)).toEqual(["--", "@/tmp/a.png", "@/tmp/b.png", "Task: t"]);
75
+ });
76
+
77
+ it("inlines skills after the agent prompt", () => {
78
+ expect(composeSystemPrompt(agent, [{ name: "arcane", filePath: "/s", body: "Skill body" }])).toBe("You are the Arcane specialist.\n\n## Skill: arcane\n\nSkill body");
79
+ });
80
+
81
+ it("marks the child with agent name, depth, and remaining levels", () => {
82
+ const env = buildChildEnv(agent, 0, 1, { PATH: "/usr/bin" });
83
+ expect(env).toEqual({ PATH: "/usr/bin", [AGENT_ENV]: "astro.arcane", [DEPTH_ENV]: "1", [REMAINING_ENV]: "1" });
84
+ });
85
+
86
+ it("computes delegation depth from the environment and tightens per agent", () => {
87
+ expect(currentDepth({})).toEqual({ depth: 0, remaining: 2 });
88
+ expect(currentDepth({ [DEPTH_ENV]: "1", [REMAINING_ENV]: "1" })).toEqual({ depth: 1, remaining: 1 });
89
+ expect(currentDepth({ [DEPTH_ENV]: "x", [REMAINING_ENV]: "-3" })).toEqual({ depth: 0, remaining: 0 });
90
+ expect(childRemaining(2, agent)).toBe(1);
91
+ expect(childRemaining(1, agent)).toBe(0);
92
+ expect(childRemaining(3, { ...agent, maxSubagentDepth: undefined })).toBe(2);
93
+ });
94
+ });
95
+
96
+ describe("pi invocation", () => {
97
+ it("runs the current Node and pi script while both exist", () => {
98
+ expect(piInvocation(["-p"], process.execPath, import.meta.filename)).toEqual({ command: process.execPath, args: [import.meta.filename, "-p"] });
99
+ });
100
+
101
+ it("falls back to pi on PATH after the Node binary vanished", () => {
102
+ expect(piInvocation(["-p"], "/opt/homebrew/Cellar/node/0.0.0_1/bin/node", import.meta.filename)).toEqual({ command: "pi", args: ["-p"] });
103
+ });
104
+ });
105
+
106
+ describe("event parsing", () => {
107
+ it("accumulates assistant messages, usage, model, and stop reason", () => {
108
+ const result: RunResult = { agent: "a", agentSource: "bundled", task: "t", exitCode: -1, messages: [], stderr: "", usage: emptyUsage() };
109
+ const msg = {
110
+ role: "assistant",
111
+ content: [{ type: "toolCall", id: "1", name: "arcane", arguments: { args: ["projects", "list"] } }],
112
+ model: "gpt-5.5",
113
+ usage: { input: 10, output: 5, cacheRead: 0, cacheWrite: 0, totalTokens: 15, cost: { total: 0.01 } },
114
+ stopReason: "toolUse",
115
+ };
116
+ expect(applyEventLine(JSON.stringify({ type: "message_end", message: msg }), result)).toBe(true);
117
+ expect(applyEventLine(JSON.stringify({ type: "message_end", message: { ...msg, content: [{ type: "text", text: "Done." }], stopReason: "stop" } }), result)).toBe(true);
118
+ expect(applyEventLine("not json", result)).toBe(false);
119
+ expect(applyEventLine(JSON.stringify({ type: "other" }), result)).toBe(false);
120
+ expect(result.usage).toMatchObject({ turns: 2, input: 20, output: 10, contextTokens: 15 });
121
+ expect(result.model).toBe("gpt-5.5");
122
+ expect(result.stopReason).toBe("stop");
123
+ expect(finalOutput(result.messages)).toBe("Done.");
124
+ result.exitCode = 0;
125
+ expect(isFailed(result)).toBe(false);
126
+ expect(resultOutput(result)).toBe("Done.");
127
+ });
128
+
129
+ it("joins every text part of the last assistant message", () => {
130
+ const assistant = (content: unknown[]) => ({ role: "assistant", content }) as unknown as RunResult["messages"][number];
131
+ const thinking = { type: "thinking", thinking: "..." };
132
+ const answer = assistant([{ type: "text", text: "Checked the notes." }, thinking, { type: "text", text: '{"verdict":"none","reason":"x"}' }]);
133
+ expect(finalOutput([assistant([{ type: "text", text: "earlier" }]), answer])).toBe('Checked the notes.\n{"verdict":"none","reason":"x"}');
134
+ expect(finalOutput([answer, assistant([thinking])])).toBe('Checked the notes.\n{"verdict":"none","reason":"x"}');
135
+ expect(finalOutput([])).toBe("");
136
+ });
137
+
138
+ it("reports failures with the error message or stderr", () => {
139
+ const failed: RunResult = { agent: "a", agentSource: "user", task: "t", exitCode: 1, messages: [], stderr: "boom\n", usage: emptyUsage() };
140
+ expect(isFailed(failed)).toBe(true);
141
+ expect(resultOutput(failed)).toBe("boom");
142
+ expect(resultOutput({ ...failed, errorMessage: "quota" })).toBe("quota");
143
+ });
144
+ });
145
+
146
+ describe("runAgent", () => {
147
+ const fakePi = (script: string) => (args: string[]) => ({ command: "/bin/sh", args: ["-c", script, "pi", ...args] });
148
+
149
+ it("spawns the child, parses its JSON events, and passes the environment", async () => {
150
+ const script = `printf '%s\\n' "{\\"type\\":\\"message_end\\",\\"message\\":{\\"role\\":\\"assistant\\",\\"content\\":[{\\"type\\":\\"text\\",\\"text\\":\\"agent=$ASTRO_SUBAGENT_AGENT depth=$ASTRO_SUBAGENT_DEPTH remaining=$ASTRO_SUBAGENT_REMAINING tools=$4\\"}],\\"stopReason\\":\\"stop\\"}}"`;
151
+ const updates: string[] = [];
152
+ const result = await runAgent({
153
+ agent: { ...agent, skills: [] },
154
+ skills: [],
155
+ task: "hello",
156
+ cwd: process.cwd(),
157
+ depth: 0,
158
+ remaining: 1,
159
+ defaults: {},
160
+ invocation: fakePi(script),
161
+ onUpdate: (r) => updates.push(finalOutput(r.messages)),
162
+ });
163
+ expect(result.exitCode).toBe(0);
164
+ expect(finalOutput(result.messages)).toBe("agent=astro.arcane depth=1 remaining=1 tools=--no-session");
165
+ expect(updates).toHaveLength(1);
166
+ });
167
+
168
+ it("returns stderr and a non-zero exit code on failure", async () => {
169
+ const result = await runAgent({ agent, skills: [], task: "t", cwd: process.cwd(), depth: 0, remaining: 1, defaults: {}, invocation: fakePi("echo nope >&2; exit 3") });
170
+ expect(result.exitCode).toBe(3);
171
+ expect(resultOutput(result)).toBe("nope");
172
+ });
173
+
174
+ it("aborts through the signal", async () => {
175
+ const controller = new AbortController();
176
+ setTimeout(() => controller.abort(), 100);
177
+ const result = await runAgent({ agent, skills: [], task: "t", cwd: process.cwd(), depth: 0, remaining: 1, defaults: {}, signal: controller.signal, invocation: fakePi("sleep 5") });
178
+ expect(result.stopReason).toBe("aborted");
179
+ expect(isFailed(result)).toBe(true);
180
+ });
181
+
182
+ it("kills the child after timeoutMinutes", async () => {
183
+ const slow: AgentConfig = { ...agent, timeoutMinutes: 0.001 };
184
+ const result = await runAgent({ agent: slow, skills: [], task: "t", cwd: process.cwd(), depth: 0, remaining: 1, defaults: {}, invocation: fakePi("sleep 5") });
185
+ expect(result.errorMessage).toMatch(/timed out/);
186
+ expect(isFailed(result)).toBe(true);
187
+ });
188
+
189
+ it("does not time out while the clock is held, and counts again after release", async () => {
190
+ const slow: AgentConfig = { ...agent, timeoutMinutes: 0.001 };
191
+ const held = new RunClock();
192
+ held.hold();
193
+ const finished = await runAgent({ agent: slow, skills: [], task: "t", cwd: process.cwd(), depth: 0, remaining: 1, defaults: {}, invocation: fakePi("sleep 0.3"), clock: held });
194
+ expect(finished.errorMessage).toBeUndefined();
195
+
196
+ const released = new RunClock();
197
+ released.hold();
198
+ setTimeout(() => released.release(), 100);
199
+ const result = await runAgent({ agent: slow, skills: [], task: "t", cwd: process.cwd(), depth: 0, remaining: 1, defaults: {}, invocation: fakePi("sleep 5"), clock: released });
200
+ expect(result.errorMessage).toMatch(/timed out/);
201
+ });
202
+ });
@@ -0,0 +1,367 @@
1
+ import { spawn } from "node:child_process";
2
+ import * as fs from "node:fs";
3
+ import * as os from "node:os";
4
+ import * as path from "node:path";
5
+ import type { Message } from "@earendil-works/pi-ai";
6
+ import type { AgentConfig, ResolvedSkill } from "./agents.ts";
7
+
8
+ /** Environment the child session receives; `specialist-gate` reads the first one. */
9
+ export const AGENT_ENV = "ASTRO_SUBAGENT_AGENT";
10
+ export const DEPTH_ENV = "ASTRO_SUBAGENT_DEPTH";
11
+ export const REMAINING_ENV = "ASTRO_SUBAGENT_REMAINING";
12
+
13
+ /** Delegation levels allowed below a top-level session unless an agent tightens it. */
14
+ export const DEFAULT_REMAINING = 2;
15
+
16
+ export interface UsageStats {
17
+ input: number;
18
+ output: number;
19
+ cacheRead: number;
20
+ cacheWrite: number;
21
+ cost: number;
22
+ contextTokens: number;
23
+ turns: number;
24
+ }
25
+
26
+ export interface RunResult {
27
+ agent: string;
28
+ agentSource: AgentConfig["source"] | "unknown";
29
+ task: string;
30
+ /** -1 while running. */
31
+ exitCode: number;
32
+ messages: Message[];
33
+ stderr: string;
34
+ usage: UsageStats;
35
+ model?: string;
36
+ stopReason?: string;
37
+ errorMessage?: string;
38
+ step?: number;
39
+ }
40
+
41
+ export function emptyUsage(): UsageStats {
42
+ return { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0, contextTokens: 0, turns: 0 };
43
+ }
44
+
45
+ export interface DispatchDefaults {
46
+ model?: string;
47
+ thinkingLevel?: string;
48
+ }
49
+
50
+ /** Current session's delegation state, read from the environment. */
51
+ export function currentDepth(env: NodeJS.ProcessEnv = process.env): { depth: number; remaining: number } {
52
+ const depth = Number(env[DEPTH_ENV] ?? 0);
53
+ const remainingRaw = env[REMAINING_ENV];
54
+ const remaining = remainingRaw === undefined ? DEFAULT_REMAINING : Number(remainingRaw);
55
+ return {
56
+ depth: Number.isInteger(depth) && depth >= 0 ? depth : 0,
57
+ remaining: Number.isInteger(remaining) && remaining >= 0 ? remaining : 0,
58
+ };
59
+ }
60
+
61
+ /** The child may delegate `remaining - 1` more levels, tightened by its own `maxSubagentDepth`. */
62
+ export function childRemaining(parentRemaining: number, agent: AgentConfig): number {
63
+ const inherited = Math.max(0, parentRemaining - 1);
64
+ return agent.maxSubagentDepth === undefined ? inherited : Math.min(inherited, agent.maxSubagentDepth);
65
+ }
66
+
67
+ export function composeSystemPrompt(agent: AgentConfig, skills: ResolvedSkill[], extra?: string): string {
68
+ const parts = [agent.systemPrompt];
69
+ for (const skill of skills) parts.push(`## Skill: ${skill.name}\n\n${skill.body}`);
70
+ if (extra) parts.push(extra);
71
+ return parts.filter((p) => p.length > 0).join("\n\n");
72
+ }
73
+
74
+ /**
75
+ * Where the child keeps its conversation. Without one the child is ephemeral.
76
+ * `id` opens that exact session (created when missing); otherwise `continue`
77
+ * resumes the most recent session in `dir` started from the same working directory.
78
+ */
79
+ export interface ChildSession {
80
+ dir: string;
81
+ continue?: boolean;
82
+ id?: string;
83
+ }
84
+
85
+ export interface ChildArgsInput {
86
+ agent: AgentConfig;
87
+ task: string;
88
+ promptFile: string | null;
89
+ defaults: DispatchDefaults;
90
+ session?: ChildSession;
91
+ /** Local files passed as `@file` prompt inputs; Pi attaches images by content type. */
92
+ files?: string[];
93
+ }
94
+
95
+ /** Arguments for the child `pi` process: print mode, JSON events, a session file only when asked. */
96
+ export function buildChildArgs({ agent, task, promptFile, defaults, session, files }: ChildArgsInput): string[] {
97
+ const args = ["--mode", "json", "-p"];
98
+ if (session) {
99
+ args.push("--session-dir", session.dir);
100
+ if (session.id) args.push("--session-id", session.id);
101
+ else if (session.continue) args.push("--continue");
102
+ } else args.push("--no-session");
103
+ const model = agent.model ?? defaults.model;
104
+ if (model) args.push("--model", model);
105
+ const thinking = agent.thinking ?? (agent.model ? undefined : defaults.thinkingLevel);
106
+ if (thinking) args.push("--thinking", thinking);
107
+ if (agent.tools?.length === 0) args.push("--no-tools");
108
+ else if (agent.tools) args.push("--tools", agent.tools.join(","));
109
+ if (!agent.inheritProjectContext) args.push("--no-context-files");
110
+ if (!agent.inheritSkills) args.push("--no-skills");
111
+ if (promptFile) args.push(agent.systemPromptMode === "append" ? "--append-system-prompt" : "--system-prompt", promptFile);
112
+ args.push("--", ...(files ?? []).map((file) => `@${file}`), `Task: ${task}`);
113
+ return args;
114
+ }
115
+
116
+ export function buildChildEnv(agent: AgentConfig, depth: number, remaining: number, base: NodeJS.ProcessEnv = process.env): NodeJS.ProcessEnv {
117
+ return { ...base, [AGENT_ENV]: agent.name, [DEPTH_ENV]: String(depth + 1), [REMAINING_ENV]: String(remaining) };
118
+ }
119
+
120
+ export interface Invocation {
121
+ command: string;
122
+ args: string[];
123
+ }
124
+
125
+ /**
126
+ * Runs the same pi that runs this extension; falls back to `pi` on PATH.
127
+ * A long-running host outlives its Homebrew Node keg, so a vanished `execPath` also falls back.
128
+ */
129
+ export function piInvocation(args: string[], execPath: string = process.execPath, script: string | undefined = process.argv[1]): Invocation {
130
+ if (!fs.existsSync(execPath)) return { command: "pi", args };
131
+ if (script && fs.existsSync(script)) return { command: execPath, args: [script, ...args] };
132
+ const execName = path.basename(execPath).toLowerCase();
133
+ if (!/^(node|bun)(\.exe)?$/.test(execName)) return { command: execPath, args };
134
+ return { command: "pi", args };
135
+ }
136
+
137
+ /** Every text part of the last assistant message that has one, joined by newlines. */
138
+ export function finalOutput(messages: Message[]): string {
139
+ for (let i = messages.length - 1; i >= 0; i--) {
140
+ const msg = messages[i];
141
+ if (msg.role !== "assistant") continue;
142
+ const texts = msg.content.flatMap((part) => (part.type === "text" ? [part.text] : []));
143
+ if (texts.length > 0) return texts.join("\n");
144
+ }
145
+ return "";
146
+ }
147
+
148
+ export function isFailed(result: RunResult): boolean {
149
+ return result.exitCode !== 0 || result.stopReason === "error" || result.stopReason === "aborted";
150
+ }
151
+
152
+ export function resultOutput(result: RunResult): string {
153
+ if (isFailed(result)) return result.errorMessage || result.stderr.trim() || finalOutput(result.messages) || "(no output)";
154
+ return finalOutput(result.messages) || "(no output)";
155
+ }
156
+
157
+ interface JsonEvent {
158
+ type?: unknown;
159
+ message?: unknown;
160
+ }
161
+
162
+ /** Feeds one JSON-mode event line into the result; returns true when the result changed. */
163
+ export function applyEventLine(line: string, result: RunResult): boolean {
164
+ if (!line.trim()) return false;
165
+ let event: JsonEvent;
166
+ try {
167
+ event = JSON.parse(line) as JsonEvent;
168
+ } catch {
169
+ return false;
170
+ }
171
+ if ((event.type !== "message_end" && event.type !== "tool_result_end") || typeof event.message !== "object" || event.message === null) {
172
+ return false;
173
+ }
174
+ const msg = event.message as Message;
175
+ result.messages.push(msg);
176
+ if (msg.role === "assistant") {
177
+ result.usage.turns++;
178
+ const usage = msg.usage;
179
+ if (usage) {
180
+ result.usage.input += usage.input || 0;
181
+ result.usage.output += usage.output || 0;
182
+ result.usage.cacheRead += usage.cacheRead || 0;
183
+ result.usage.cacheWrite += usage.cacheWrite || 0;
184
+ result.usage.cost += usage.cost?.total || 0;
185
+ result.usage.contextTokens = usage.totalTokens || 0;
186
+ }
187
+ if (!result.model && msg.model) result.model = msg.model;
188
+ if (msg.stopReason) result.stopReason = msg.stopReason;
189
+ if (msg.errorMessage) result.errorMessage = msg.errorMessage;
190
+ }
191
+ return true;
192
+ }
193
+
194
+ /** A run's time limit that stops counting while an owner decides, for example on an approval request. */
195
+ export class RunClock {
196
+ private holds = 0;
197
+ private leftMs = 0;
198
+ private since = 0;
199
+ private timer: NodeJS.Timeout | null = null;
200
+ private expire: (() => void) | null = null;
201
+
202
+ start(ms: number, expire: () => void): void {
203
+ this.leftMs = ms;
204
+ this.expire = expire;
205
+ if (this.holds === 0) this.arm();
206
+ }
207
+
208
+ hold(): void {
209
+ this.holds++;
210
+ if (this.holds === 1 && this.timer) {
211
+ clearTimeout(this.timer);
212
+ this.timer = null;
213
+ this.leftMs -= Date.now() - this.since;
214
+ }
215
+ }
216
+
217
+ release(): void {
218
+ if (this.holds === 0) return;
219
+ this.holds--;
220
+ if (this.holds === 0 && this.expire) this.arm();
221
+ }
222
+
223
+ stop(): void {
224
+ if (this.timer) clearTimeout(this.timer);
225
+ this.timer = null;
226
+ this.expire = null;
227
+ }
228
+
229
+ private arm(): void {
230
+ const expire = this.expire;
231
+ this.since = Date.now();
232
+ this.timer = setTimeout(() => {
233
+ this.timer = null;
234
+ this.expire = null;
235
+ expire?.();
236
+ }, Math.max(0, this.leftMs));
237
+ }
238
+ }
239
+
240
+ export interface RunOptions {
241
+ agent: AgentConfig;
242
+ skills: ResolvedSkill[];
243
+ task: string;
244
+ cwd: string;
245
+ depth: number;
246
+ remaining: number;
247
+ defaults: DispatchDefaults;
248
+ step?: number;
249
+ signal?: AbortSignal;
250
+ onUpdate?: (result: RunResult) => void;
251
+ invocation?: (args: string[]) => Invocation;
252
+ /** The run's time limit; the caller holds it while an owner decides. */
253
+ clock?: RunClock;
254
+ /** Extra variables for the child process, for example an approval endpoint. */
255
+ env?: Record<string, string>;
256
+ /** Text appended to the system prompt, for example channel rules. */
257
+ extraSystemPrompt?: string;
258
+ /** Saved conversation to continue or start; omitted for a one-off run. */
259
+ session?: ChildSession;
260
+ /** Local files (images) attached to the task. */
261
+ files?: string[];
262
+ }
263
+
264
+ export async function runAgent(options: RunOptions): Promise<RunResult> {
265
+ const { agent, task } = options;
266
+ const result: RunResult = {
267
+ agent: agent.name,
268
+ agentSource: agent.source,
269
+ task,
270
+ exitCode: -1,
271
+ messages: [],
272
+ stderr: "",
273
+ usage: emptyUsage(),
274
+ model: agent.model ?? options.defaults.model,
275
+ step: options.step,
276
+ };
277
+ const prompt = composeSystemPrompt(agent, options.skills, options.extraSystemPrompt);
278
+ let tmpDir: string | null = null;
279
+ let promptFile: string | null = null;
280
+ if (prompt.length > 0) {
281
+ tmpDir = await fs.promises.mkdtemp(path.join(os.tmpdir(), "astro-subagent-"));
282
+ promptFile = path.join(tmpDir, `${agent.name.replace(/[^\w.-]+/g, "_")}.md`);
283
+ await fs.promises.writeFile(promptFile, prompt, { encoding: "utf-8", mode: 0o600 });
284
+ }
285
+ try {
286
+ if (options.session) await fs.promises.mkdir(options.session.dir, { recursive: true, mode: 0o700 });
287
+ const args = buildChildArgs({ agent, task, promptFile, defaults: options.defaults, session: options.session, files: options.files });
288
+ const invocation = (options.invocation ?? piInvocation)(args);
289
+ const env = buildChildEnv(agent, options.depth, options.remaining, { ...process.env, ...options.env });
290
+ let aborted = false;
291
+ const exitCode = await new Promise<number>((resolve) => {
292
+ // Own process group so a kill reaches the child's own tool processes, not only pi itself.
293
+ const proc = spawn(invocation.command, invocation.args, { cwd: options.cwd, env, shell: false, stdio: ["ignore", "pipe", "pipe"], detached: true });
294
+ let buffer = "";
295
+ let settled = false;
296
+ const finish = (code: number) => {
297
+ if (settled) return;
298
+ settled = true;
299
+ if (buffer.trim() && applyEventLine(buffer, result)) options.onUpdate?.(result);
300
+ resolve(code);
301
+ };
302
+ const signalGroup = (sig: NodeJS.Signals) => {
303
+ try {
304
+ if (proc.pid) process.kill(-proc.pid, sig);
305
+ else proc.kill(sig);
306
+ } catch {
307
+ proc.kill(sig);
308
+ }
309
+ };
310
+ const kill = () => {
311
+ aborted = true;
312
+ signalGroup("SIGTERM");
313
+ setTimeout(() => {
314
+ if (!settled) signalGroup("SIGKILL");
315
+ }, 5000).unref();
316
+ };
317
+ const clock = options.clock ?? new RunClock();
318
+ if (agent.timeoutMinutes !== undefined && agent.timeoutMinutes > 0) {
319
+ clock.start(agent.timeoutMinutes * 60_000, () => {
320
+ result.errorMessage = `timed out after ${agent.timeoutMinutes} min`;
321
+ kill();
322
+ });
323
+ }
324
+ proc.stdout.on("data", (data: Buffer) => {
325
+ buffer += data.toString("utf-8");
326
+ const lines = buffer.split("\n");
327
+ buffer = lines.pop() ?? "";
328
+ let changed = false;
329
+ for (const line of lines) changed = applyEventLine(line, result) || changed;
330
+ if (changed) options.onUpdate?.(result);
331
+ });
332
+ proc.stderr.on("data", (data: Buffer) => {
333
+ result.stderr += data.toString("utf-8");
334
+ });
335
+ proc.on("close", (code) => {
336
+ clock.stop();
337
+ finish(code ?? 1);
338
+ });
339
+ // On abort, orphaned grandchildren may keep the pipes open; do not wait for them.
340
+ proc.on("exit", (code) => {
341
+ if (aborted) {
342
+ clock.stop();
343
+ finish(code ?? 1);
344
+ }
345
+ });
346
+ proc.on("error", (err) => {
347
+ clock.stop();
348
+ result.stderr += err.message;
349
+ finish(1);
350
+ });
351
+ if (options.signal) {
352
+ if (options.signal.aborted) kill();
353
+ else options.signal.addEventListener("abort", kill, { once: true });
354
+ }
355
+ });
356
+ result.exitCode = exitCode;
357
+ if (aborted && !result.errorMessage) {
358
+ result.stopReason = "aborted";
359
+ result.errorMessage = "subagent aborted";
360
+ }
361
+ if (aborted && result.exitCode === 0) result.exitCode = 1;
362
+ return result;
363
+ } finally {
364
+ if (promptFile) fs.rmSync(promptFile, { force: true });
365
+ if (tmpDir) fs.rmSync(tmpDir, { recursive: true, force: true });
366
+ }
367
+ }