@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,123 @@
1
+ import { mkdirSync, mkdtempSync, readdirSync, 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 type { AgentDirs } from "./agents.ts";
6
+ import { DEPTH_ENV, REMAINING_ENV } from "./child.ts";
7
+ import astroSubagents, { delegationRefusal, parseRunCommand, pruneLegacyCopies, runEntryText } from "./index.ts";
8
+
9
+ type Handler = (event: Record<string, unknown>, ctx: unknown) => Promise<unknown>;
10
+
11
+ interface CapturedPi {
12
+ tools: Map<string, { promptGuidelines?: string[] }>;
13
+ commands: Map<string, { handler: (args: string, ctx: unknown) => Promise<void> | void }>;
14
+ handlers: Record<string, Handler>;
15
+ registerTool: (tool: { name: string; promptGuidelines?: string[] }) => void;
16
+ registerCommand: (name: string, opts: { handler: (args: string, ctx: unknown) => Promise<void> | void }) => void;
17
+ on: (event: string, handler: Handler) => void;
18
+ sendMessage: ReturnType<typeof vi.fn>;
19
+ appendEntry: ReturnType<typeof vi.fn>;
20
+ registerEntryRenderer: ReturnType<typeof vi.fn>;
21
+ }
22
+
23
+ function makePi(): CapturedPi {
24
+ const tools = new Map();
25
+ const commands = new Map();
26
+ const handlers: Record<string, Handler> = {};
27
+ return {
28
+ tools,
29
+ commands,
30
+ handlers,
31
+ registerTool: (tool) => tools.set(tool.name, tool),
32
+ registerCommand: (name, opts) => commands.set(name, opts),
33
+ on: (event, handler) => {
34
+ handlers[event] = handler;
35
+ },
36
+ sendMessage: vi.fn(),
37
+ appendEntry: vi.fn(),
38
+ registerEntryRenderer: vi.fn(),
39
+ };
40
+ }
41
+
42
+ describe("astro-subagents extension", () => {
43
+ let root: string;
44
+ let dirs: AgentDirs;
45
+
46
+ beforeEach(() => {
47
+ root = mkdtempSync(join(tmpdir(), "astro-sub-"));
48
+ dirs = {
49
+ bundledAgents: join(root, "pkg", "agents"),
50
+ bundledSkills: join(root, "pkg", "skills"),
51
+ packAgents: join(root, "pack", "agents"),
52
+ packSkills: join(root, "pack", "skills"),
53
+ userAgents: join(root, "user", "agents"),
54
+ userSkills: join(root, "user", "skills"),
55
+ sessions: join(root, "sessions"),
56
+ };
57
+ for (const d of Object.values(dirs)) mkdirSync(d, { recursive: true });
58
+ writeFileSync(join(dirs.bundledAgents, "arcane.md"), "---\nname: arcane\ndescription: Operates Arcane\n---\nB");
59
+ });
60
+
61
+ afterEach(() => rmSync(root, { recursive: true, force: true }));
62
+
63
+ it("registers the subagent tool with the agent list at the top level", () => {
64
+ const pi = makePi();
65
+ astroSubagents(pi as unknown as Parameters<typeof astroSubagents>[0], { dirs, env: {} });
66
+ expect(pi.tools.has("subagent")).toBe(true);
67
+ expect(pi.tools.get("subagent")?.promptGuidelines?.[1]).toContain("astro.arcane: Operates Arcane");
68
+ expect([...pi.commands.keys()].sort()).toEqual(["agents", "run"]);
69
+ });
70
+
71
+ it("registers no tool when no delegation level remains", async () => {
72
+ const pi = makePi();
73
+ astroSubagents(pi as unknown as Parameters<typeof astroSubagents>[0], { dirs, env: { [DEPTH_ENV]: "2", [REMAINING_ENV]: "0" } });
74
+ expect(pi.tools.has("subagent")).toBe(false);
75
+ const notify = vi.fn();
76
+ await pi.commands.get("run")?.handler("astro.arcane -- x", { ui: { notify }, cwd: root });
77
+ expect(notify).toHaveBeenCalledWith(expect.stringContaining("depth limit"), "warning");
78
+ });
79
+
80
+ it("posts the /run result without a model turn and names the model in the footer", async () => {
81
+ const pi = makePi();
82
+ astroSubagents(pi as unknown as Parameters<typeof astroSubagents>[0], { dirs, env: {} });
83
+ const setStatus = vi.fn();
84
+ const ctx = { ui: { notify: vi.fn(), setStatus }, hasUI: true, cwd: root, model: { provider: "openai-codex", id: "gpt-6-astra" } };
85
+ await pi.commands.get("run")?.handler("astro.nobody -- x", ctx);
86
+ expect(setStatus).toHaveBeenCalledWith("subagent", expect.stringContaining("astro.nobody on openai-codex/gpt-6-astra"));
87
+ expect(pi.appendEntry).toHaveBeenCalledWith("astro-subagents-run", { agent: "astro.nobody", task: "x", continue: false });
88
+ expect(pi.registerEntryRenderer).toHaveBeenCalledWith("astro-subagents-run", expect.any(Function));
89
+ expect(runEntryText({ agent: "astro.dns", task: "zones", continue: true })).toBe("/run astro.dns --continue -- zones");
90
+ expect(pi.sendMessage).toHaveBeenCalledWith(expect.objectContaining({ customType: "astro-subagents", content: expect.stringContaining("Unknown agent") }), { triggerTurn: false });
91
+ });
92
+
93
+ it("removes legacy loader copies on session start", async () => {
94
+ writeFileSync(join(dirs.userAgents, "astro.arcane.md"), "old copy");
95
+ writeFileSync(join(dirs.userAgents, "mine.md"), "---\nname: mine\ndescription: keep\n---\n");
96
+ const pi = makePi();
97
+ astroSubagents(pi as unknown as Parameters<typeof astroSubagents>[0], { dirs, env: {} });
98
+ const notify = vi.fn();
99
+ await pi.handlers.session_start({}, { ui: { notify }, cwd: root });
100
+ expect(readdirSync(dirs.userAgents)).toEqual(["mine.md"]);
101
+ expect(notify).toHaveBeenCalledWith(expect.stringContaining("removed 1 legacy"), "info");
102
+ });
103
+
104
+ it("lets a specialist delegate only to specialists and refuses project agents without a person", () => {
105
+ const specialists = new Set(["astro.arcane", "astro.dns"]);
106
+ expect(delegationRefusal("astro.arcane", specialists, ["astro.dns"], "user", false)).toBeNull();
107
+ expect(delegationRefusal("astro.arcane", specialists, ["astro.google-tech-lead"], "user", false)).toContain("delegates only to specialists");
108
+ expect(delegationRefusal("flourish-architect", specialists, ["flourish-reviewer"], "user", false)).toBeNull();
109
+ expect(delegationRefusal(undefined, specialists, ["astro.google-tech-lead"], "user", true)).toBeNull();
110
+ expect(delegationRefusal(undefined, specialists, ["astro.arcane"], "both", false)).toContain("needs a person");
111
+ expect(delegationRefusal(undefined, specialists, ["astro.arcane"], "both", true)).toBeNull();
112
+ });
113
+
114
+ it("parses /run arguments", () => {
115
+ expect(parseRunCommand("astro.arcane -- list projects")).toEqual({ agent: "astro.arcane", task: "list projects", continue: false });
116
+ expect(parseRunCommand("scout find auth code")).toEqual({ agent: "scout", task: "find auth code", continue: false });
117
+ expect(parseRunCommand("astro.security --continue -- do the next step")).toEqual({ agent: "astro.security", task: "do the next step", continue: true });
118
+ expect(parseRunCommand("astro.security --continue next")).toEqual({ agent: "astro.security", task: "next", continue: true });
119
+ expect(parseRunCommand("scout --continue")).toBeNull();
120
+ expect(parseRunCommand("scout")).toBeNull();
121
+ expect(pruneLegacyCopies(join(root, "missing"))).toEqual([]);
122
+ });
123
+ });
@@ -0,0 +1,352 @@
1
+ import * as fs from "node:fs";
2
+ import * as path from "node:path";
3
+ import type { AgentToolResult } from "@earendil-works/pi-agent-core";
4
+ import { StringEnum } from "@earendil-works/pi-ai";
5
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
6
+ import { Box, Text } from "@earendil-works/pi-tui";
7
+ import { type Static, Type } from "typebox";
8
+ import { type AgentConfig, type AgentDirs, type AgentScope, BUNDLED_NAMESPACE, defaultDirs, discoverAgents, formatAgentList, resolveSkills } from "./agents.ts";
9
+ import { loadConfig as loadSpecialists } from "../gate/config.ts";
10
+ import { AGENT_ENV, type ChildSession, childRemaining, currentDepth, type DispatchDefaults, finalOutput, isFailed, resultOutput, type RunResult, runAgent } from "./child.ts";
11
+ import { pruneSessions, sessionDirFor } from "./sessions.ts";
12
+ import { renderCall, renderResult, type SubagentDetails } from "./render.ts";
13
+ import { startTicker } from "./ticker.ts";
14
+
15
+ const MAX_PARALLEL_TASKS = 8;
16
+ const MAX_CONCURRENCY = 4;
17
+ const PER_TASK_OUTPUT_CAP = 50 * 1024;
18
+
19
+ const TaskItem = Type.Object({
20
+ agent: Type.String({ description: "Agent name, e.g. astro.code-reviewer" }),
21
+ task: Type.String({ description: "Task for the agent. In a chain, {previous} is replaced by the previous step's output." }),
22
+ cwd: Type.Optional(Type.String({ description: "Working directory for the agent" })),
23
+ });
24
+
25
+ const Params = Type.Object({
26
+ agent: Type.Optional(Type.String({ description: "Agent name for a single run" })),
27
+ task: Type.Optional(Type.String({ description: "Task for a single run" })),
28
+ tasks: Type.Optional(Type.Array(TaskItem, { description: "Independent tasks run in parallel" })),
29
+ chain: Type.Optional(Type.Array(TaskItem, { description: "Sequential steps; {previous} carries the prior output" })),
30
+ agentScope: Type.Optional(
31
+ StringEnum(["user", "project", "both"] as const, {
32
+ description: 'Which extra agent folders to use besides the bundled ones. Default "user". "both" adds repo-controlled .pi/agents.',
33
+ }),
34
+ ),
35
+ cwd: Type.Optional(Type.String({ description: "Working directory for a single run" })),
36
+ });
37
+
38
+ function truncate(output: string): string {
39
+ if (Buffer.byteLength(output, "utf8") <= PER_TASK_OUTPUT_CAP) return output;
40
+ let cut = output.slice(0, PER_TASK_OUTPUT_CAP);
41
+ while (Buffer.byteLength(cut, "utf8") > PER_TASK_OUTPUT_CAP) cut = cut.slice(0, -1);
42
+ return `${cut}\n\n[Output truncated; full output in tool details.]`;
43
+ }
44
+
45
+ async function mapLimited<T, R>(items: T[], limit: number, fn: (item: T, index: number) => Promise<R>): Promise<R[]> {
46
+ const results: R[] = new Array<R>(items.length);
47
+ let next = 0;
48
+ await Promise.all(
49
+ Array.from({ length: Math.min(limit, items.length) }, async () => {
50
+ for (;;) {
51
+ const i = next++;
52
+ if (i >= items.length) return;
53
+ results[i] = await fn(items[i], i);
54
+ }
55
+ }),
56
+ );
57
+ return results;
58
+ }
59
+
60
+ /** Bundled agents used to be copied to ~/.pi/agent/agents/astro.*.md by the old loader; remove those copies. */
61
+ export function pruneLegacyCopies(userAgentsDir: string): string[] {
62
+ const removed: string[] = [];
63
+ let entries: string[];
64
+ try {
65
+ entries = fs.readdirSync(userAgentsDir);
66
+ } catch {
67
+ return removed;
68
+ }
69
+ for (const name of entries) {
70
+ if (!name.startsWith(`${BUNDLED_NAMESPACE}.`) || !name.endsWith(".md")) continue;
71
+ const filePath = path.join(userAgentsDir, name);
72
+ try {
73
+ fs.unlinkSync(filePath);
74
+ removed.push(filePath);
75
+ } catch {
76
+ /* leave it */
77
+ }
78
+ }
79
+ return removed;
80
+ }
81
+
82
+ /** Parses `/run <agent> -- <task>` (the `--` is optional when the task has no leading dash). */
83
+ /** `/run <agent> [--continue] [--] <task>`; `--continue` resumes the agent's last saved session from this directory. */
84
+ export function parseRunCommand(input: string): { agent: string; task: string; continue: boolean } | null {
85
+ const trimmed = input.trim();
86
+ const match = /^(\S+)(\s+--continue)?\s+(?:--\s+)?([\s\S]+)$/.exec(trimmed);
87
+ if (!match) return null;
88
+ const task = match[3].trim();
89
+ if (task === "--continue") return null;
90
+ return { agent: match[1], task, continue: match[2] !== undefined };
91
+ }
92
+
93
+ /** Transcript entry for a `/run` invocation; shown to the user, never sent to the model. */
94
+ export interface RunEntry {
95
+ agent: string;
96
+ task: string;
97
+ continue: boolean;
98
+ }
99
+
100
+ export function runEntryText(entry: RunEntry): string {
101
+ return `/run ${entry.agent}${entry.continue ? " --continue" : ""} -- ${entry.task}`;
102
+ }
103
+
104
+ export interface GateOptions {
105
+ dirs?: AgentDirs;
106
+ env?: NodeJS.ProcessEnv;
107
+ /** Agent names of the specialists; read from `specialists.json` when absent. */
108
+ specialistAgents?: ReadonlySet<string>;
109
+ }
110
+
111
+ /**
112
+ * Why a delegation must not run, or null. A specialist hands work only to other specialists, never to an agent
113
+ * with a shell; a session without a person to approve them never loads repository-controlled project agents.
114
+ */
115
+ export function delegationRefusal(parentAgent: string | undefined, specialistAgents: ReadonlySet<string>, requested: readonly string[], scope: AgentScope, hasUI: boolean): string | null {
116
+ if (scope !== "user" && !hasUI) return `agentScope "${scope}" needs a person to approve project agents; use "user"`;
117
+ if (parentAgent === undefined || !specialistAgents.has(parentAgent)) return null;
118
+ const others = requested.filter((name) => !specialistAgents.has(name));
119
+ return others.length > 0 ? `${parentAgent} delegates only to specialists (${[...specialistAgents].join(", ")}), not to ${others.join(", ")}` : null;
120
+ }
121
+
122
+ export default function astroSubagents(pi: ExtensionAPI, options: GateOptions = {}): void {
123
+ const dirs = options.dirs ?? defaultDirs();
124
+ const env = options.env ?? process.env;
125
+ const { depth, remaining } = currentDepth(env);
126
+ const canDelegate = remaining > 0;
127
+ const parentAgent = env[AGENT_ENV];
128
+ const specialistAgents = options.specialistAgents ?? new Set((loadSpecialists().config?.specialists ?? []).map((s) => s.agent));
129
+
130
+ const listAgents = (cwd: string, scope: AgentScope) => discoverAgents(cwd, scope, dirs);
131
+
132
+ async function runOne(
133
+ ctx: ExtensionContext,
134
+ agents: AgentConfig[],
135
+ agentName: string,
136
+ task: string,
137
+ cwd: string | undefined,
138
+ step: number | undefined,
139
+ signal: AbortSignal | undefined,
140
+ onUpdate: ((r: RunResult) => void) | undefined,
141
+ session?: ChildSession,
142
+ ): Promise<RunResult> {
143
+ const agent = agents.find((a) => a.name === agentName);
144
+ if (!agent) {
145
+ return {
146
+ agent: agentName,
147
+ agentSource: "unknown",
148
+ task,
149
+ exitCode: 1,
150
+ messages: [],
151
+ stderr: `Unknown agent "${agentName}". Available: ${agents.map((a) => a.name).join(", ") || "none"}.`,
152
+ usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0, contextTokens: 0, turns: 0 },
153
+ step,
154
+ };
155
+ }
156
+ const { skills, missing } = resolveSkills(agent.skills, dirs);
157
+ if (missing.length > 0) ctx.ui.notify(`${agent.name}: skill(s) not found: ${missing.join(", ")}`, "warning");
158
+ const defaults: DispatchDefaults = {
159
+ model: ctx.model ? `${ctx.model.provider}/${ctx.model.id}` : undefined,
160
+ thinkingLevel: ctx.thinkingLevel,
161
+ };
162
+ return runAgent({
163
+ agent,
164
+ skills,
165
+ task,
166
+ cwd: cwd ?? ctx.cwd,
167
+ depth,
168
+ remaining: childRemaining(remaining, agent),
169
+ defaults,
170
+ step,
171
+ signal,
172
+ onUpdate,
173
+ session,
174
+ });
175
+ }
176
+
177
+ /** Footer label: the agent and the model it will run on. */
178
+ function runLabel(ctx: ExtensionContext, agents: AgentConfig[], agentName: string): string {
179
+ const model = agents.find((a) => a.name === agentName)?.model ?? (ctx.model ? `${ctx.model.provider}/${ctx.model.id}` : undefined);
180
+ return model ? `${agentName} on ${model}` : agentName;
181
+ }
182
+
183
+ if (canDelegate) {
184
+ const initial = listAgents(process.cwd(), "user");
185
+ pi.registerTool({
186
+ name: "subagent",
187
+ label: "Subagent",
188
+ description:
189
+ "Delegate a task to a specialized agent running in its own pi process with an isolated context. Modes: single (agent + task), parallel (tasks), chain (sequential, {previous} carries output).",
190
+ promptGuidelines: [
191
+ "Use subagent for work that a listed agent owns; give it a complete, self-contained task and report its answer.",
192
+ `Available agents:\n${formatAgentList(initial.agents)}`,
193
+ ],
194
+ parameters: Params,
195
+ async execute(_id, params, signal, onUpdate, ctx) {
196
+ const label = params.chain?.length
197
+ ? `chain of ${params.chain.length}`
198
+ : params.tasks?.length
199
+ ? `${params.tasks.length} agents`
200
+ : params.agent
201
+ ? runLabel(ctx, listAgents(ctx.cwd, params.agentScope ?? "user").agents, params.agent)
202
+ : "subagent";
203
+ const stopTicker = startTicker(ctx, label);
204
+ try {
205
+ return await runTool(params, signal, onUpdate, ctx);
206
+ } finally {
207
+ stopTicker();
208
+ }
209
+ },
210
+ renderCall: (args, theme) => renderCall(args, theme),
211
+ renderResult: (result, { expanded }, theme) => renderResult(result as AgentToolResult<SubagentDetails>, expanded, theme),
212
+ });
213
+ }
214
+
215
+ type ToolParams = Static<typeof Params>;
216
+ type ToolResult = AgentToolResult<SubagentDetails> & { isError?: boolean };
217
+
218
+ async function runTool(params: ToolParams, signal: AbortSignal | undefined, onUpdate: ((r: ToolResult) => void) | undefined, ctx: ExtensionContext): Promise<ToolResult> {
219
+ const scope: AgentScope = params.agentScope ?? "user";
220
+ const discovery = listAgents(ctx.cwd, scope);
221
+ const agents = discovery.agents;
222
+ const details = (mode: SubagentDetails["mode"], results: RunResult[]): SubagentDetails => ({ mode, results });
223
+ const modes = Number(Boolean(params.chain?.length)) + Number(Boolean(params.tasks?.length)) + Number(Boolean(params.agent && params.task));
224
+ if (modes !== 1) {
225
+ return {
226
+ content: [{ type: "text", text: `Provide exactly one mode: agent+task, tasks, or chain.\nAvailable agents:\n${formatAgentList(agents)}` }],
227
+ details: details("single", []),
228
+ isError: true,
229
+ };
230
+ }
231
+ const requested = new Set<string>([...(params.chain ?? []).map((s) => s.agent), ...(params.tasks ?? []).map((t) => t.agent), ...(params.agent ? [params.agent] : [])]);
232
+ const refusal = delegationRefusal(parentAgent, specialistAgents, [...requested], scope, ctx.hasUI);
233
+ if (refusal) return { content: [{ type: "text", text: `Refused: ${refusal}.` }], details: details("single", []), isError: true };
234
+ if (scope !== "user" && ctx.hasUI && !ctx.isProjectTrusted()) {
235
+ const projectAgents = [...requested].map((n) => agents.find((a) => a.name === n)).filter((a): a is AgentConfig => a?.source === "project");
236
+ if (projectAgents.length > 0) {
237
+ const ok = await ctx.ui.confirm("Run project-local agents?", `${projectAgents.map((a) => a.name).join(", ")} from ${discovery.projectAgentsDir ?? "?"}. Repo-controlled prompts; continue only for trusted repositories.`);
238
+ if (!ok) return { content: [{ type: "text", text: "Canceled: project-local agents not approved." }], details: details("single", []) };
239
+ }
240
+ }
241
+
242
+ if (params.chain && params.chain.length > 0) {
243
+ const results: RunResult[] = [];
244
+ let previous = "";
245
+ for (let i = 0; i < params.chain.length; i++) {
246
+ const step = params.chain[i];
247
+ const result = await runOne(ctx, agents, step.agent, step.task.replace(/\{previous\}/g, previous), step.cwd, i + 1, signal, (r) =>
248
+ onUpdate?.({ content: [{ type: "text", text: finalOutput(r.messages) || "(running...)" }], details: details("chain", [...results, r]) }),
249
+ );
250
+ results.push(result);
251
+ if (isFailed(result)) {
252
+ return { content: [{ type: "text", text: `Chain stopped at step ${i + 1} (${step.agent}): ${resultOutput(result)}` }], details: details("chain", results), isError: true };
253
+ }
254
+ previous = finalOutput(result.messages);
255
+ }
256
+ return { content: [{ type: "text", text: finalOutput(results[results.length - 1].messages) || "(no output)" }], details: details("chain", results) };
257
+ }
258
+
259
+ if (params.tasks && params.tasks.length > 0) {
260
+ if (params.tasks.length > MAX_PARALLEL_TASKS) {
261
+ return { content: [{ type: "text", text: `Too many parallel tasks (${params.tasks.length}); the limit is ${MAX_PARALLEL_TASKS}.` }], details: details("parallel", []), isError: true };
262
+ }
263
+ const all: RunResult[] = params.tasks.map((t) => ({
264
+ agent: t.agent,
265
+ agentSource: "unknown",
266
+ task: t.task,
267
+ exitCode: -1,
268
+ messages: [],
269
+ stderr: "",
270
+ usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0, contextTokens: 0, turns: 0 },
271
+ }));
272
+ const emit = () => {
273
+ const running = all.filter((r) => r.exitCode === -1).length;
274
+ onUpdate?.({ content: [{ type: "text", text: `Parallel: ${all.length - running}/${all.length} done, ${running} running...` }], details: details("parallel", [...all]) });
275
+ };
276
+ const results = await mapLimited(params.tasks, MAX_CONCURRENCY, async (t, i) => {
277
+ const result = await runOne(ctx, agents, t.agent, t.task, t.cwd, undefined, signal, (r) => {
278
+ all[i] = r;
279
+ emit();
280
+ });
281
+ all[i] = result;
282
+ emit();
283
+ return result;
284
+ });
285
+ const ok = results.filter((r) => !isFailed(r)).length;
286
+ const summaries = results.map((r) => `### [${r.agent}] ${isFailed(r) ? "failed" : "completed"}\n\n${truncate(resultOutput(r))}`);
287
+ return { content: [{ type: "text", text: `Parallel: ${ok}/${results.length} succeeded\n\n${summaries.join("\n\n---\n\n")}` }], details: details("parallel", results) };
288
+ }
289
+
290
+ const result = await runOne(ctx, agents, params.agent as string, params.task as string, params.cwd, undefined, signal, (r) =>
291
+ onUpdate?.({ content: [{ type: "text", text: finalOutput(r.messages) || "(running...)" }], details: details("single", [r]) }),
292
+ );
293
+ if (isFailed(result)) {
294
+ return { content: [{ type: "text", text: `Agent ${result.stopReason ?? "failed"}: ${resultOutput(result)}` }], details: details("single", [result]), isError: true };
295
+ }
296
+ return { content: [{ type: "text", text: finalOutput(result.messages) || "(no output)" }], details: details("single", [result]) };
297
+ }
298
+
299
+ // Slash commands are not echoed in the transcript; show the invocation the way a user message looks.
300
+ pi.registerEntryRenderer<RunEntry>("astro-subagents-run", (entry, _options, theme) => {
301
+ if (!entry.data) return undefined;
302
+ const box = new Box(1, 0, (text) => theme.bg("userMessageBg", text));
303
+ box.addChild(new Text(theme.fg("userMessageText", runEntryText(entry.data)), 0, 0));
304
+ return box;
305
+ });
306
+
307
+ pi.registerCommand("run", {
308
+ description: "Run an agent: /run <agent> [--continue] -- <task>",
309
+ handler: async (args, ctx) => {
310
+ if (!canDelegate) {
311
+ ctx.ui.notify("subagents: this session may not delegate further (depth limit)", "warning");
312
+ return;
313
+ }
314
+ const parsed = parseRunCommand(args);
315
+ if (!parsed) {
316
+ ctx.ui.notify("usage: /run <agent> [--continue] -- <task>", "warning");
317
+ return;
318
+ }
319
+ const agents = listAgents(ctx.cwd, "user").agents;
320
+ pi.appendEntry<RunEntry>("astro-subagents-run", { agent: parsed.agent, task: parsed.task, continue: parsed.continue });
321
+ // Every /run saves its session so a later --continue can pick the conversation up.
322
+ const session: ChildSession = { dir: sessionDirFor(dirs.sessions, parsed.agent), continue: parsed.continue };
323
+ pruneSessions(session.dir);
324
+ const stopTicker = startTicker(ctx, runLabel(ctx, agents, parsed.agent));
325
+ let result: RunResult;
326
+ try {
327
+ result = await runOne(ctx, agents, parsed.agent, parsed.task, undefined, undefined, undefined, undefined, session);
328
+ } finally {
329
+ stopTicker();
330
+ }
331
+ const status = `${isFailed(result) ? "failed" : "done"}${parsed.continue ? ", continued" : ""}`;
332
+ if (isFailed(result)) ctx.ui.notify(`${parsed.agent} failed`, "warning");
333
+ // No turn: the result joins the context for the next prompt without the parent model restating it.
334
+ pi.sendMessage({ customType: "astro-subagents", content: `Result from /run ${parsed.agent} (${status}). Task: ${parsed.task}\n\n${resultOutput(result)}`, display: true }, { triggerTurn: false });
335
+ },
336
+ });
337
+
338
+ pi.registerCommand("agents", {
339
+ description: "List available subagents",
340
+ handler: async (_args, ctx) => {
341
+ const discovery = listAgents(ctx.cwd, "both");
342
+ const lines = [formatAgentList(discovery.agents), ...discovery.warnings.map((w) => `warning: ${w}`), `delegation: depth ${depth}, ${remaining} level(s) left`];
343
+ ctx.ui.notify(lines.join("\n"), "info");
344
+ },
345
+ });
346
+
347
+ pi.on("session_start", async (_event, ctx: ExtensionContext) => {
348
+ const removed = pruneLegacyCopies(dirs.userAgents);
349
+ if (removed.length > 0) ctx.ui.notify(`astro-subagents: removed ${removed.length} legacy agent cop${removed.length === 1 ? "y" : "ies"} from ${dirs.userAgents}`, "info");
350
+ for (const warning of listAgents(ctx.cwd, "user").warnings) ctx.ui.notify(`astro-subagents: ${warning}`, "warning");
351
+ });
352
+ }
@@ -0,0 +1,39 @@
1
+ import { homedir } from "node:os";
2
+ import { join } from "node:path";
3
+ import { afterEach, describe, expect, it } from "vitest";
4
+ import { getAgentDir, packageRoot, parseFrontmatter, stripFrontmatter } from "./pi-paths.ts";
5
+
6
+ const ROOT = join(import.meta.dirname, "..", "..");
7
+
8
+ describe("pi paths", () => {
9
+ const before = process.env.PI_CODING_AGENT_DIR;
10
+ afterEach(() => {
11
+ if (before === undefined) delete process.env.PI_CODING_AGENT_DIR;
12
+ else process.env.PI_CODING_AGENT_DIR = before;
13
+ });
14
+
15
+ it("finds the package from the source tree and from a bundle in dist/", () => {
16
+ expect(packageRoot()).toBe(ROOT);
17
+ expect(packageRoot(join(ROOT, "dist", "bridge.js"))).toBe(ROOT);
18
+ expect(packageRoot(join(ROOT, "extensions", "bridge", "index.ts"))).toBe(ROOT);
19
+ expect(() => packageRoot("/nowhere/at/all.js")).toThrow(/no @astrofoundry\/astrogate package above/);
20
+ });
21
+
22
+ it("follows PI_CODING_AGENT_DIR with a leading ~, else ~/.pi/agent", () => {
23
+ delete process.env.PI_CODING_AGENT_DIR;
24
+ expect(getAgentDir()).toBe(join(homedir(), ".pi", "agent"));
25
+ process.env.PI_CODING_AGENT_DIR = "~/elsewhere";
26
+ expect(getAgentDir()).toBe(join(homedir(), "elsewhere"));
27
+ process.env.PI_CODING_AGENT_DIR = "/abs/dir";
28
+ expect(getAgentDir()).toBe("/abs/dir");
29
+ });
30
+
31
+ it("parses YAML frontmatter and leaves other text whole", () => {
32
+ expect(parseFrontmatter("---\nname: x\ntools: [read, bash]\n---\n\nBody\n")).toEqual({ frontmatter: { name: "x", tools: ["read", "bash"] }, body: "Body" });
33
+ expect(parseFrontmatter("---\r\nname: x\r\n---\r\nBody")).toEqual({ frontmatter: { name: "x" }, body: "Body" });
34
+ expect(parseFrontmatter("No frontmatter\n")).toEqual({ frontmatter: {}, body: "No frontmatter\n" });
35
+ expect(parseFrontmatter("---\nname: x\nnever closed")).toEqual({ frontmatter: {}, body: "---\nname: x\nnever closed" });
36
+ expect(parseFrontmatter("---\n- a\n- b\n---\nBody").frontmatter).toEqual({});
37
+ expect(stripFrontmatter("---\nname: x\n---\nBody")).toBe("Body");
38
+ });
39
+ });
@@ -0,0 +1,58 @@
1
+ /**
2
+ * The parts of Pi's configuration layout that the agent loader needs, without
3
+ * importing Pi at run time, so the Discord bridge can run as plain Node. They
4
+ * follow Pi 1.3's `config.js` and `utils/frontmatter.js`: the agent directory
5
+ * is PI_CODING_AGENT_DIR (with `~` expanded) or `~/.pi/agent`, project files
6
+ * live under `.pi/`, and frontmatter is YAML between `---` lines.
7
+ */
8
+ import { readFileSync } from "node:fs";
9
+ import { homedir } from "node:os";
10
+ import { dirname, join } from "node:path";
11
+ import { fileURLToPath } from "node:url";
12
+ import { parse } from "yaml";
13
+
14
+ export const CONFIG_DIR_NAME = ".pi";
15
+ const PACKAGE_NAME = "@astrofoundry/astrogate";
16
+
17
+ /**
18
+ * The Astrogate core package this code runs from. The same code runs from the source
19
+ * tree (`extensions/...`) and from a bundle in `dist/`, so the root is the first
20
+ * folder above it whose package.json names this package.
21
+ */
22
+ export function packageRoot(from: string = fileURLToPath(import.meta.url)): string {
23
+ let dir = dirname(from);
24
+ for (;;) {
25
+ let name: unknown;
26
+ try {
27
+ name = (JSON.parse(readFileSync(join(dir, "package.json"), "utf-8")) as { name?: unknown }).name;
28
+ } catch {
29
+ name = undefined;
30
+ }
31
+ if (name === PACKAGE_NAME) return dir;
32
+ const parent = dirname(dir);
33
+ if (parent === dir) throw new Error(`no ${PACKAGE_NAME} package above ${from}`);
34
+ dir = parent;
35
+ }
36
+ }
37
+ const AGENT_DIR_ENV = "PI_CODING_AGENT_DIR";
38
+
39
+ export function getAgentDir(): string {
40
+ const dir = process.env[AGENT_DIR_ENV];
41
+ if (!dir) return join(homedir(), CONFIG_DIR_NAME, "agent");
42
+ return dir === "~" ? homedir() : dir.startsWith("~/") ? join(homedir(), dir.slice(2)) : dir;
43
+ }
44
+
45
+ /** YAML frontmatter and the trimmed body of a Markdown file. */
46
+ export function parseFrontmatter<T extends Record<string, unknown>>(content: string): { frontmatter: Partial<T>; body: string } {
47
+ const normalized = content.replace(/^\uFEFF/, "").replace(/\r\n/g, "\n").replace(/\r/g, "\n");
48
+ if (!normalized.startsWith("---")) return { frontmatter: {}, body: normalized };
49
+ const end = normalized.indexOf("\n---", 3);
50
+ if (end === -1) return { frontmatter: {}, body: normalized };
51
+ const parsed: unknown = parse(normalized.slice(4, end));
52
+ const frontmatter = typeof parsed === "object" && parsed !== null && !Array.isArray(parsed) ? (parsed as Partial<T>) : {};
53
+ return { frontmatter, body: normalized.slice(end + 4).trim() };
54
+ }
55
+
56
+ export function stripFrontmatter(content: string): string {
57
+ return parseFrontmatter(content).body;
58
+ }