@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,118 @@
1
+ import { homedir } from "node:os";
2
+ import { describe, expect, it } from "vitest";
3
+ import { expandHome, findMatchingRule, matchesPattern, normalizePath } from "./rules.ts";
4
+
5
+ describe("expandHome", () => {
6
+ it("expands ~/foo", () => {
7
+ expect(expandHome("~/foo")).toBe(`${homedir()}/foo`);
8
+ });
9
+
10
+ it("expands bare ~", () => {
11
+ expect(expandHome("~")).toBe(homedir());
12
+ });
13
+
14
+ it("leaves non-tilde paths unchanged", () => {
15
+ expect(expandHome("/etc/hosts")).toBe("/etc/hosts");
16
+ expect(expandHome("foo/bar")).toBe("foo/bar");
17
+ });
18
+ });
19
+
20
+ describe("normalizePath", () => {
21
+ it("resolves relative paths against cwd", () => {
22
+ expect(normalizePath("foo.txt", "/tmp")).toBe("/tmp/foo.txt");
23
+ });
24
+
25
+ it("keeps absolute paths", () => {
26
+ expect(normalizePath("/abs/path", "/tmp")).toBe("/abs/path");
27
+ });
28
+
29
+ it("expands ~", () => {
30
+ expect(normalizePath("~/a", "/tmp")).toBe(`${homedir()}/a`);
31
+ });
32
+ });
33
+
34
+ describe("matchesPattern", () => {
35
+ it("substring match on bash command", () => {
36
+ expect(matchesPattern("sudo rm -rf /tmp/x", { pattern: "rm -rf", action: "prompt" })).toBe(true);
37
+ });
38
+
39
+ it("substring does NOT match when absent", () => {
40
+ expect(matchesPattern("ls -la", { pattern: "rm -rf", action: "prompt" })).toBe(false);
41
+ });
42
+
43
+ it("glob ** matches deep paths", () => {
44
+ expect(matchesPattern("/Users/x/.ssh/id_rsa", { pattern: "~/.ssh/**", action: "block" })).toBe(false);
45
+ // Reason: the test path's home isn't the CURRENT user's home. Glob is anchored.
46
+ const real = `${homedir()}/.ssh/id_rsa`;
47
+ expect(matchesPattern(real, { pattern: "~/.ssh/**", action: "block" })).toBe(true);
48
+ });
49
+
50
+ it("glob * does NOT cross /", () => {
51
+ expect(matchesPattern("/a/b/c", { pattern: "/a/*", action: "block" })).toBe(false);
52
+ expect(matchesPattern("/a/b", { pattern: "/a/*", action: "block" })).toBe(true);
53
+ });
54
+
55
+ it("glob ? matches single char", () => {
56
+ expect(matchesPattern("/tmp/a.env", { pattern: "/tmp/?.env", action: "block" })).toBe(true);
57
+ expect(matchesPattern("/tmp/ab.env", { pattern: "/tmp/?.env", action: "block" })).toBe(false);
58
+ });
59
+
60
+ it("character class [abc]", () => {
61
+ expect(matchesPattern("/tmp/a", { pattern: "/tmp/[abc]", action: "block" })).toBe(true);
62
+ expect(matchesPattern("/tmp/z", { pattern: "/tmp/[abc]", action: "block" })).toBe(false);
63
+ });
64
+
65
+ it("glob **/.env matches any depth", () => {
66
+ expect(matchesPattern("/src/app/.env", { pattern: "**/.env", action: "block" })).toBe(true);
67
+ expect(matchesPattern("/.env", { pattern: "**/.env", action: "block" })).toBe(true);
68
+ });
69
+
70
+ it("metacharacters in non-glob pattern are escaped (fall back to substring)", () => {
71
+ // Pattern has no *, ?, or [: substring path used; no regex injection
72
+ expect(matchesPattern("something", { pattern: "some(thing)", action: "block" })).toBe(false);
73
+ expect(matchesPattern("some(thing)", { pattern: "some(thing)", action: "block" })).toBe(true);
74
+ });
75
+ });
76
+
77
+ describe("findMatchingRule: refinements and strictness", () => {
78
+ const rules = [
79
+ { pattern: "> /dev/", action: "block" as const },
80
+ { pattern: "> /dev/null", action: "allow" as const },
81
+ ];
82
+
83
+ it("allow /dev/null overrides block /dev/", () => {
84
+ const r = findMatchingRule("echo hi > /dev/null", rules);
85
+ expect(r?.action).toBe("allow");
86
+ });
87
+
88
+ it("block /dev/sda still blocks when no narrower rule exists", () => {
89
+ const r = findMatchingRule("echo hi > /dev/sda", rules);
90
+ expect(r?.action).toBe("block");
91
+ });
92
+
93
+ it("no match returns null", () => {
94
+ expect(findMatchingRule("ls -la", rules)).toBeNull();
95
+ });
96
+
97
+ it("an unrelated allow never cancels a block or a prompt", () => {
98
+ const all = [...rules, { pattern: "rm -rf /", action: "block" as const }, { pattern: "sudo", action: "prompt" as const }, { pattern: "-u specialist", action: "block" as const }];
99
+ expect(findMatchingRule("sudo rm -rf / > /dev/null", all)?.action).toBe("block");
100
+ expect(findMatchingRule("sudo -n -u specialist -H x > /dev/null", all)?.action).toBe("block");
101
+ expect(findMatchingRule("sudo ls > /dev/null", all)?.action).toBe("prompt");
102
+ });
103
+
104
+ it("a narrow glob exception refines a broad glob", () => {
105
+ const globs = [
106
+ { pattern: "~/.ssh/**", action: "block" as const },
107
+ { pattern: "~/.ssh/known_hosts", action: "allow" as const },
108
+ ];
109
+ expect(findMatchingRule(`${homedir()}/.ssh/known_hosts`, globs)?.action).toBe("allow");
110
+ expect(findMatchingRule(`${homedir()}/.ssh/id_ed25519`, globs)?.action).toBe("block");
111
+ });
112
+
113
+ it("folds case when asked, as on macOS", () => {
114
+ const ssh = [{ pattern: "~/.ssh/**", action: "block" as const }];
115
+ expect(findMatchingRule(`${homedir()}/.SSH/id_ed25519`, ssh, true)?.action).toBe("block");
116
+ expect(findMatchingRule(`${homedir()}/.SSH/id_ed25519`, ssh, false)).toBeNull();
117
+ });
118
+ });
@@ -0,0 +1,101 @@
1
+ import { homedir } from "node:os";
2
+ import { isAbsolute, resolve } from "node:path";
3
+ import type { RuleAction, SecurityRule } from "./types.ts";
4
+
5
+ export function expandHome(pattern: string): string {
6
+ if (pattern === "~") return homedir();
7
+ if (pattern.startsWith("~/")) return `${homedir()}/${pattern.slice(2)}`;
8
+ return pattern;
9
+ }
10
+
11
+ /**
12
+ * Normalize a filesystem path for matching: expand `~`, resolve relative paths
13
+ * against cwd. Non-filesystem strings (bash commands) should NOT go through this.
14
+ */
15
+ export function normalizePath(p: string, cwd: string): string {
16
+ const expanded = expandHome(p);
17
+ return isAbsolute(expanded) ? expanded : resolve(cwd, expanded);
18
+ }
19
+
20
+ /**
21
+ * Convert a glob pattern to a RegExp source. Supports:
22
+ * ? any single non-separator char
23
+ * * any run of non-separator chars
24
+ * ** any run of chars including separators
25
+ * [abc] character class
26
+ * All other regex metacharacters are escaped.
27
+ */
28
+ function globToRegex(glob: string): RegExp {
29
+ let src = "";
30
+ for (let i = 0; i < glob.length; i++) {
31
+ const c = glob[i];
32
+ if (c === "*") {
33
+ if (glob[i + 1] === "*") {
34
+ src += ".*";
35
+ i++;
36
+ } else {
37
+ src += "[^/]*";
38
+ }
39
+ } else if (c === "?") {
40
+ src += "[^/]";
41
+ } else if (c === "[") {
42
+ const end = glob.indexOf("]", i);
43
+ if (end === -1) {
44
+ src += "\\[";
45
+ } else {
46
+ src += glob.slice(i, end + 1);
47
+ i = end;
48
+ }
49
+ } else if (/[.+^${}()|\\]/.test(c)) {
50
+ src += `\\${c}`;
51
+ } else {
52
+ src += c;
53
+ }
54
+ }
55
+ return new RegExp(`^${src}$`);
56
+ }
57
+
58
+ function isGlob(pattern: string): boolean {
59
+ return /[*?[]/.test(pattern);
60
+ }
61
+
62
+ /**
63
+ * Does `text` match `rule.pattern`? For globs, matches as a whole path / whole
64
+ * string. For non-glob patterns, falls back to substring match (friendlier for
65
+ * bash commands and filename fragments).
66
+ */
67
+ export function matchesPattern(text: string, rule: SecurityRule, foldCase = false): boolean {
68
+ const fold = (s: string): string => (foldCase ? s.toLowerCase() : s);
69
+ const expanded = fold(expandHome(rule.pattern));
70
+ const subject = fold(text);
71
+ if (isGlob(rule.pattern)) {
72
+ const re = globToRegex(expanded);
73
+ return re.test(subject);
74
+ }
75
+ return subject.includes(expanded) || subject.includes(fold(rule.pattern));
76
+ }
77
+
78
+ const STRICTNESS: Record<RuleAction, number> = { allow: 0, prompt: 1, block: 2 };
79
+
80
+ /** `narrow` refines `broad` when it is longer and `broad` matches its pattern: `> /dev/null` refines `> /dev/`. */
81
+ function refines(narrow: SecurityRule, broad: SecurityRule, foldCase: boolean): boolean {
82
+ return narrow.pattern.length > broad.pattern.length && matchesPattern(expandHome(narrow.pattern), broad, foldCase);
83
+ }
84
+
85
+ /**
86
+ * A matching rule yields only to a matching rule that refines it, so narrow exceptions still work
87
+ * (`> /dev/` = block, `> /dev/null` = allow). Of the rest the strictest wins: an unrelated `allow`
88
+ * (`> /dev/null` in `sudo rm -rf / > /dev/null`) never cancels a `block` or a `prompt`.
89
+ * macOS paths ignore case, so matching folds case there by default.
90
+ */
91
+ export function findMatchingRule(text: string, rules: readonly SecurityRule[], foldCase = process.platform === "darwin"): SecurityRule | null {
92
+ const matching = rules.filter((rule) => matchesPattern(text, rule, foldCase));
93
+ const standing = matching.filter((rule) => !matching.some((other) => refines(other, rule, foldCase)));
94
+ let best: SecurityRule | null = null;
95
+ for (const rule of standing) {
96
+ if (best === null || STRICTNESS[rule.action] > STRICTNESS[best.action] || (STRICTNESS[rule.action] === STRICTNESS[best.action] && rule.pattern.length > best.pattern.length)) {
97
+ best = rule;
98
+ }
99
+ }
100
+ return best;
101
+ }
@@ -0,0 +1,12 @@
1
+ export type RuleAction = "prompt" | "block" | "allow";
2
+
3
+ export interface SecurityRule {
4
+ pattern: string;
5
+ action: RuleAction;
6
+ }
7
+
8
+ export interface SecurityRules {
9
+ operations: SecurityRule[];
10
+ writes: SecurityRule[];
11
+ reads: SecurityRule[];
12
+ }
@@ -0,0 +1,137 @@
1
+ import { mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
2
+ import { tmpdir } from "node:os";
3
+ import { join } from "node:path";
4
+ import { afterEach, beforeEach, describe, expect, it } from "vitest";
5
+ import { type AgentDirs, discoverAgents, parseAgentFile, parseList, resolveSkills } from "./agents.ts";
6
+
7
+ describe("parseAgentFile", () => {
8
+ const file = `---
9
+ name: arcane
10
+ description: Operates Arcane.
11
+ tools: read, arcane, subagent
12
+ skills: [arcane]
13
+ systemPromptMode: replace
14
+ inheritProjectContext: false
15
+ inheritSkills: false
16
+ maxSubagentDepth: 1
17
+ timeoutMinutes: 30
18
+ ---
19
+ You are the Arcane specialist.
20
+ `;
21
+
22
+ it("namespaces bundled agents and keeps user agents bare", () => {
23
+ const bundled = parseAgentFile(file, "/pkg/agents/arcane.md", "bundled");
24
+ const user = parseAgentFile(file, "/home/.pi/agent/agents/arcane.md", "user");
25
+ expect(bundled?.name).toBe("astro.arcane");
26
+ expect(user?.name).toBe("arcane");
27
+ });
28
+
29
+ it("normalizes every supported field", () => {
30
+ const agent = parseAgentFile(file, "/pkg/agents/arcane.md", "bundled");
31
+ expect(agent).toMatchObject({
32
+ description: "Operates Arcane.",
33
+ tools: ["read", "arcane", "subagent"],
34
+ skills: ["arcane"],
35
+ systemPromptMode: "replace",
36
+ inheritProjectContext: false,
37
+ inheritSkills: false,
38
+ maxSubagentDepth: 1,
39
+ timeoutMinutes: 30,
40
+ systemPrompt: "You are the Arcane specialist.",
41
+ });
42
+ });
43
+
44
+ it("applies defaults and rejects files without name or description", () => {
45
+ const minimal = parseAgentFile("---\nname: scout\ndescription: Recon\n---\nBody", "/a.md", "user");
46
+ expect(minimal).toMatchObject({ tools: undefined, skills: [], systemPromptMode: "replace", inheritProjectContext: false, inheritSkills: false });
47
+ expect(minimal?.maxSubagentDepth).toBeUndefined();
48
+ expect(parseAgentFile("---\nname: reviewer\ndescription: d\ntools: none\n---\nBody", "/r.md", "user")?.tools).toEqual([]);
49
+ expect(parseAgentFile("---\nname: x\n---\nBody", "/b.md", "user")).toBeNull();
50
+ expect(parseAgentFile("---\nname: 'bad name!'\ndescription: d\n---\n", "/c.md", "user")).toBeNull();
51
+ });
52
+
53
+ it("accepts list values as strings or arrays", () => {
54
+ expect(parseList("read, bash")).toEqual(["read", "bash"]);
55
+ expect(parseList(["read", " bash "])).toEqual(["read", "bash"]);
56
+ expect(parseList(42)).toEqual([]);
57
+ });
58
+ });
59
+
60
+ describe("discovery", () => {
61
+ let root: string;
62
+ let dirs: AgentDirs;
63
+
64
+ beforeEach(() => {
65
+ root = mkdtempSync(join(tmpdir(), "astro-agents-"));
66
+ dirs = {
67
+ bundledAgents: join(root, "pkg", "agents"),
68
+ bundledSkills: join(root, "pkg", "skills"),
69
+ packAgents: join(root, "pack", "agents"),
70
+ packSkills: join(root, "pack", "skills"),
71
+ userAgents: join(root, "user", "agents"),
72
+ userSkills: join(root, "user", "skills"),
73
+ sessions: join(root, "sessions"),
74
+ };
75
+ for (const d of Object.values(dirs)) mkdirSync(d, { recursive: true });
76
+ writeFileSync(join(dirs.bundledAgents, "arcane.md"), "---\nname: arcane\ndescription: bundled\nskills: arcane\n---\nB");
77
+ writeFileSync(join(dirs.bundledAgents, "broken.md"), "no frontmatter");
78
+ writeFileSync(join(dirs.userAgents, "scout.md"), "---\nname: scout\ndescription: user\n---\nS");
79
+ writeFileSync(join(dirs.userAgents, "astro.arcane.md"), "---\nname: arcane\ndescription: legacy copy\n---\nL");
80
+ mkdirSync(join(dirs.bundledSkills, "arcane"), { recursive: true });
81
+ writeFileSync(join(dirs.bundledSkills, "arcane", "SKILL.md"), "---\nname: arcane\ndescription: d\n---\n# Arcane skill\nBody");
82
+ mkdirSync(join(dirs.userSkills, "mine"), { recursive: true });
83
+ writeFileSync(join(dirs.userSkills, "mine", "SKILL.md"), "mine body");
84
+ });
85
+
86
+ afterEach(() => rmSync(root, { recursive: true, force: true }));
87
+
88
+ it("loads bundled and user agents, warns on broken files", () => {
89
+ const result = discoverAgents(root, "user", dirs);
90
+ expect(result.agents.map((a) => a.name).sort()).toEqual(["arcane", "astro.arcane", "scout"]);
91
+ expect(result.warnings).toHaveLength(1);
92
+ expect(result.warnings[0]).toContain("broken.md");
93
+ });
94
+
95
+ it("loads project agents only when asked and lets them override", () => {
96
+ const project = join(root, "repo", ".pi", "agents");
97
+ mkdirSync(project, { recursive: true });
98
+ writeFileSync(join(project, "scout.md"), "---\nname: scout\ndescription: project\n---\nP");
99
+ const cwd = join(root, "repo", "src");
100
+ mkdirSync(cwd, { recursive: true });
101
+ expect(discoverAgents(cwd, "user", dirs).agents.find((a) => a.name === "scout")?.description).toBe("user");
102
+ const both = discoverAgents(cwd, "both", dirs);
103
+ expect(both.agents.find((a) => a.name === "scout")?.description).toBe("project");
104
+ expect(both.projectAgentsDir).toBe(project);
105
+ });
106
+
107
+ it("loads pack agents under the astro namespace over bundled ones, and prefers pack skills", () => {
108
+ writeFileSync(join(dirs.packAgents, "arcane.md"), "---\nname: arcane\ndescription: pack\nskills: arcane\n---\nP");
109
+ writeFileSync(join(dirs.packAgents, "dns.md"), "---\nname: dns\ndescription: pack dns\n---\nD");
110
+ mkdirSync(join(dirs.packSkills, "arcane"), { recursive: true });
111
+ writeFileSync(join(dirs.packSkills, "arcane", "SKILL.md"), "pack skill");
112
+ const agents = discoverAgents(root, "user", dirs).agents;
113
+ expect(agents.find((a) => a.name === "astro.arcane")).toMatchObject({ description: "pack", source: "pack" });
114
+ expect(agents.find((a) => a.name === "astro.dns")?.source).toBe("pack");
115
+ expect(resolveSkills(["arcane"], dirs).skills[0].body).toBe("pack skill");
116
+ });
117
+
118
+ it("resolves skills from bundled then user folders and strips frontmatter", () => {
119
+ const { skills, missing } = resolveSkills(["arcane", "mine", "nope"], dirs);
120
+ expect(skills.map((s) => s.name)).toEqual(["arcane", "mine"]);
121
+ expect(skills[0].body).toBe("# Arcane skill\nBody");
122
+ expect(missing).toEqual(["nope"]);
123
+ });
124
+ });
125
+
126
+ describe("bundled agent files", () => {
127
+ it("every agents/*.md parses and declares a specialist-safe front matter", () => {
128
+ const dir = join(import.meta.dirname, "..", "..", "agents");
129
+ const files = readdirSync(dir).filter((f) => f.endsWith(".md"));
130
+ expect(files.length).toBeGreaterThan(0);
131
+ for (const file of files) {
132
+ const agent = parseAgentFile(readFileSync(join(dir, file), "utf-8"), join(dir, file), "bundled");
133
+ expect(agent, file).not.toBeNull();
134
+ expect(agent?.name, file).toBe(`astro.${file.replace(/\.md$/, "")}`);
135
+ }
136
+ });
137
+ });
@@ -0,0 +1,207 @@
1
+ import * as fs from "node:fs";
2
+ import * as path from "node:path";
3
+ import { CONFIG_DIR_NAME, getAgentDir, packageRoot, parseFrontmatter, stripFrontmatter } from "./pi-paths.ts";
4
+
5
+ export type AgentSource = "bundled" | "pack" | "user" | "project";
6
+ export type AgentScope = "user" | "project" | "both";
7
+ export type SystemPromptMode = "replace" | "append";
8
+
9
+ /** Bundled and pack agents register under this namespace, e.g. `astro.arcane`. */
10
+ export const BUNDLED_NAMESPACE = "astro";
11
+
12
+ export interface AgentConfig {
13
+ /** Name callers use: `astro.<name>` for bundled and pack agents, `<name>` otherwise. */
14
+ name: string;
15
+ description: string;
16
+ /** Strict allowlist; undefined means Pi's defaults and an empty list means no tools at all (`tools: none`). */
17
+ tools?: string[];
18
+ skills: string[];
19
+ model?: string;
20
+ thinking?: string;
21
+ systemPromptMode: SystemPromptMode;
22
+ inheritProjectContext: boolean;
23
+ inheritSkills: boolean;
24
+ maxSubagentDepth?: number;
25
+ timeoutMinutes?: number;
26
+ systemPrompt: string;
27
+ source: AgentSource;
28
+ filePath: string;
29
+ }
30
+
31
+ export interface AgentDiscoveryResult {
32
+ agents: AgentConfig[];
33
+ projectAgentsDir: string | null;
34
+ warnings: string[];
35
+ }
36
+
37
+ export interface AgentDirs {
38
+ bundledAgents: string;
39
+ bundledSkills: string;
40
+ /** The installed specialist pack (`~/.pi/agent/pack/`), written only by its installer. */
41
+ packAgents: string;
42
+ packSkills: string;
43
+ userAgents: string;
44
+ userSkills: string;
45
+ /** Root for saved `/run` sessions, one folder per agent. */
46
+ sessions: string;
47
+ }
48
+
49
+ export function defaultDirs(): AgentDirs {
50
+ const root = packageRoot();
51
+ return {
52
+ bundledAgents: path.join(root, "agents"),
53
+ bundledSkills: path.join(root, "skills"),
54
+ packAgents: path.join(getAgentDir(), "pack", "agents"),
55
+ packSkills: path.join(getAgentDir(), "pack", "skills"),
56
+ userAgents: path.join(getAgentDir(), "agents"),
57
+ userSkills: path.join(getAgentDir(), "skills"),
58
+ sessions: path.join(getAgentDir(), "subagent-sessions"),
59
+ };
60
+ }
61
+
62
+ type Frontmatter = {
63
+ name?: unknown;
64
+ description?: unknown;
65
+ tools?: unknown;
66
+ skills?: unknown;
67
+ model?: unknown;
68
+ thinking?: unknown;
69
+ systemPromptMode?: unknown;
70
+ inheritProjectContext?: unknown;
71
+ inheritSkills?: unknown;
72
+ maxSubagentDepth?: unknown;
73
+ timeoutMinutes?: unknown;
74
+ };
75
+
76
+ /** `tools: read, bash` and `tools: [read, bash]` are both in use. */
77
+ export function parseList(value: unknown): string[] {
78
+ const raw = Array.isArray(value) ? value : typeof value === "string" ? value.split(",") : [];
79
+ return raw
80
+ .filter((t): t is string => typeof t === "string")
81
+ .map((t) => t.trim())
82
+ .filter(Boolean);
83
+ }
84
+
85
+ function parseBoolean(value: unknown, fallback: boolean): boolean {
86
+ if (typeof value === "boolean") return value;
87
+ if (value === "true") return true;
88
+ if (value === "false") return false;
89
+ return fallback;
90
+ }
91
+
92
+ function parsePositiveInt(value: unknown): number | undefined {
93
+ const n = typeof value === "number" ? value : typeof value === "string" ? Number(value) : NaN;
94
+ return Number.isInteger(n) && n >= 0 ? n : undefined;
95
+ }
96
+
97
+ export function parseAgentFile(content: string, filePath: string, source: AgentSource): AgentConfig | null {
98
+ const { frontmatter, body } = parseFrontmatter<Frontmatter>(content);
99
+ if (typeof frontmatter.name !== "string" || typeof frontmatter.description !== "string") return null;
100
+ const localName = frontmatter.name.trim();
101
+ if (!/^[A-Za-z0-9][\w.-]*$/.test(localName)) return null;
102
+ const tools = parseList(frontmatter.tools);
103
+ const mode = frontmatter.systemPromptMode === "append" ? "append" : "replace";
104
+ return {
105
+ name: source === "bundled" || source === "pack" ? `${BUNDLED_NAMESPACE}.${localName}` : localName,
106
+ description: frontmatter.description.trim(),
107
+ tools: tools.length === 1 && tools[0] === "none" ? [] : tools.length > 0 ? tools : undefined,
108
+ skills: parseList(frontmatter.skills),
109
+ model: typeof frontmatter.model === "string" ? frontmatter.model : undefined,
110
+ thinking: typeof frontmatter.thinking === "string" ? frontmatter.thinking : undefined,
111
+ systemPromptMode: mode,
112
+ inheritProjectContext: parseBoolean(frontmatter.inheritProjectContext, false),
113
+ inheritSkills: parseBoolean(frontmatter.inheritSkills, false),
114
+ maxSubagentDepth: parsePositiveInt(frontmatter.maxSubagentDepth),
115
+ timeoutMinutes: parsePositiveInt(frontmatter.timeoutMinutes),
116
+ systemPrompt: body.trim(),
117
+ source,
118
+ filePath,
119
+ };
120
+ }
121
+
122
+ function loadAgentsFromDir(dir: string, source: AgentSource, warnings: string[]): AgentConfig[] {
123
+ const agents: AgentConfig[] = [];
124
+ if (!fs.existsSync(dir)) return agents;
125
+ let entries: fs.Dirent[];
126
+ try {
127
+ entries = fs.readdirSync(dir, { withFileTypes: true });
128
+ } catch {
129
+ return agents;
130
+ }
131
+ for (const entry of entries) {
132
+ if (!entry.name.endsWith(".md")) continue;
133
+ if (!entry.isFile() && !entry.isSymbolicLink()) continue;
134
+ const filePath = path.join(dir, entry.name);
135
+ let content: string;
136
+ try {
137
+ content = fs.readFileSync(filePath, "utf-8");
138
+ } catch {
139
+ continue;
140
+ }
141
+ const agent = parseAgentFile(content, filePath, source);
142
+ if (!agent) {
143
+ warnings.push(`${filePath}: missing or invalid name/description frontmatter, skipped`);
144
+ continue;
145
+ }
146
+ agents.push(agent);
147
+ }
148
+ return agents;
149
+ }
150
+
151
+ function findNearestProjectAgentsDir(cwd: string): string | null {
152
+ let current = cwd;
153
+ for (;;) {
154
+ const candidate = path.join(current, CONFIG_DIR_NAME, "agents");
155
+ try {
156
+ if (fs.statSync(candidate).isDirectory()) return candidate;
157
+ } catch {
158
+ /* keep walking */
159
+ }
160
+ const parent = path.dirname(current);
161
+ if (parent === current) return null;
162
+ current = parent;
163
+ }
164
+ }
165
+
166
+ /**
167
+ * Bundled and pack agents always load; a pack agent overrides a bundled one with its name. `scope` controls
168
+ * the others: user agents by default, project agents (`.pi/agents`, repo-controlled) only when asked.
169
+ * A user or project agent with the same runtime name overrides both.
170
+ */
171
+ export function discoverAgents(cwd: string, scope: AgentScope, dirs: AgentDirs = defaultDirs()): AgentDiscoveryResult {
172
+ const warnings: string[] = [];
173
+ const projectAgentsDir = findNearestProjectAgentsDir(cwd);
174
+ const bundled = loadAgentsFromDir(dirs.bundledAgents, "bundled", warnings);
175
+ const pack = loadAgentsFromDir(dirs.packAgents, "pack", warnings);
176
+ const user = scope === "project" ? [] : loadAgentsFromDir(dirs.userAgents, "user", warnings);
177
+ const project = scope === "user" || !projectAgentsDir ? [] : loadAgentsFromDir(projectAgentsDir, "project", warnings);
178
+ const byName = new Map<string, AgentConfig>();
179
+ for (const agent of [...bundled, ...pack, ...user, ...project]) byName.set(agent.name, agent);
180
+ return { agents: [...byName.values()], projectAgentsDir, warnings };
181
+ }
182
+
183
+ export interface ResolvedSkill {
184
+ name: string;
185
+ filePath: string;
186
+ body: string;
187
+ }
188
+
189
+ /** Finds `<name>/SKILL.md` in the installed pack first, then the bundled skills, then the user's. */
190
+ export function resolveSkills(names: string[], dirs: AgentDirs = defaultDirs()): { skills: ResolvedSkill[]; missing: string[] } {
191
+ const skills: ResolvedSkill[] = [];
192
+ const missing: string[] = [];
193
+ for (const name of names) {
194
+ const candidates = [path.join(dirs.packSkills, name, "SKILL.md"), path.join(dirs.bundledSkills, name, "SKILL.md"), path.join(dirs.userSkills, name, "SKILL.md")];
195
+ const filePath = candidates.find((c) => fs.existsSync(c));
196
+ if (!filePath) {
197
+ missing.push(name);
198
+ continue;
199
+ }
200
+ skills.push({ name, filePath, body: stripFrontmatter(fs.readFileSync(filePath, "utf-8")).trim() });
201
+ }
202
+ return { skills, missing };
203
+ }
204
+
205
+ export function formatAgentList(agents: AgentConfig[]): string {
206
+ return agents.map((a) => `${a.name}: ${a.description}`).join("\n");
207
+ }
@@ -0,0 +1,29 @@
1
+ import { existsSync, readdirSync, readFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+ import { parseFrontmatter } from "@earendil-works/pi-coding-agent";
5
+ import { describe, expect, it } from "vitest";
6
+
7
+ const ROOT = fileURLToPath(new URL("../../", import.meta.url));
8
+
9
+ function bundledFiles(): string[] {
10
+ const agents = readdirSync(join(ROOT, "agents"))
11
+ .filter((f) => f.endsWith(".md"))
12
+ .map((f) => join(ROOT, "agents", f));
13
+ if (!existsSync(join(ROOT, "skills"))) return agents;
14
+ const skills = readdirSync(join(ROOT, "skills"), { withFileTypes: true })
15
+ .filter((d) => d.isDirectory())
16
+ .map((d) => join(ROOT, "skills", d.name, "SKILL.md"));
17
+ return [...agents, ...skills];
18
+ }
19
+
20
+ describe("bundled agents and skills", () => {
21
+ // A colon followed by a space inside an unquoted value breaks the YAML, and Pi then skips the file (the foreman skill, 2026-10-23).
22
+ it("parse with Pi's own frontmatter reader and carry a name and a description", () => {
23
+ for (const file of bundledFiles()) {
24
+ const { frontmatter } = parseFrontmatter<{ name?: unknown; description?: unknown }>(readFileSync(file, "utf-8"));
25
+ expect(typeof frontmatter.name, file).toBe("string");
26
+ expect(typeof frontmatter.description, file).toBe("string");
27
+ }
28
+ });
29
+ });