@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.
- package/README.md +2 -2
- package/agents/foreman.md +27 -0
- package/cli/astro-install.sh +242 -0
- package/cli/astro.sh +449 -0
- package/cli/astro.test.ts +65 -0
- package/dist/bridge.js +9950 -0
- package/dist/claude.js +7899 -0
- package/dist/extensions/bridge/index.js +9937 -0
- package/dist/extensions/gate/index.js +286 -0
- package/dist/extensions/guard/index.js +364 -0
- package/dist/extensions/subagents/index.js +8458 -0
- package/extensions/bridge/admin.ts +86 -0
- package/extensions/bridge/approvals.ts +147 -0
- package/extensions/bridge/attachments.ts +65 -0
- package/extensions/bridge/chunk.ts +50 -0
- package/extensions/bridge/claude-run.test.ts +62 -0
- package/extensions/bridge/claude-run.ts +301 -0
- package/extensions/bridge/commands.ts +89 -0
- package/extensions/bridge/config.ts +263 -0
- package/extensions/bridge/conversations.ts +144 -0
- package/extensions/bridge/daemon.ts +60 -0
- package/extensions/bridge/discord.test.ts +547 -0
- package/extensions/bridge/gateway.ts +222 -0
- package/extensions/bridge/index.ts +951 -0
- package/extensions/bridge/launcher.ts +36 -0
- package/extensions/bridge/lifecycle.test.ts +78 -0
- package/extensions/bridge/open-work.ts +74 -0
- package/extensions/bridge/plugin.ts +172 -0
- package/extensions/bridge/quote.ts +39 -0
- package/extensions/bridge/reports.ts +65 -0
- package/extensions/bridge/rest.ts +217 -0
- package/extensions/bridge/setup.ts +218 -0
- package/extensions/gate/approvals.test.ts +40 -0
- package/extensions/gate/config.ts +110 -0
- package/extensions/gate/core.ts +114 -0
- package/extensions/gate/index.test.ts +202 -0
- package/extensions/gate/index.ts +114 -0
- package/extensions/gate/risky.ts +14 -0
- package/extensions/gate/types.ts +19 -0
- package/extensions/guard/config.test.ts +107 -0
- package/extensions/guard/config.ts +120 -0
- package/extensions/guard/defaults.ts +40 -0
- package/extensions/guard/index.test.ts +313 -0
- package/extensions/guard/index.ts +183 -0
- package/extensions/guard/rules.test.ts +118 -0
- package/extensions/guard/rules.ts +101 -0
- package/extensions/guard/types.ts +12 -0
- package/extensions/subagents/agents.test.ts +137 -0
- package/extensions/subagents/agents.ts +207 -0
- package/extensions/subagents/bundled.test.ts +29 -0
- package/extensions/subagents/child.test.ts +202 -0
- package/extensions/subagents/child.ts +367 -0
- package/extensions/subagents/index.test.ts +123 -0
- package/extensions/subagents/index.ts +352 -0
- package/extensions/subagents/pi-paths.test.ts +39 -0
- package/extensions/subagents/pi-paths.ts +58 -0
- package/extensions/subagents/render.ts +221 -0
- package/extensions/subagents/sessions.test.ts +32 -0
- package/extensions/subagents/sessions.ts +34 -0
- package/extensions/subagents/ticker.test.ts +40 -0
- package/extensions/subagents/ticker.ts +36 -0
- package/harness/claude/agents.ts +93 -0
- package/harness/claude/claude.test.ts +171 -0
- package/harness/claude/hook.ts +77 -0
- package/harness/claude/main.ts +122 -0
- package/harness/claude/mcp.ts +174 -0
- package/harness/claude/settings.ts +63 -0
- package/package.json +71 -4
- package/release.sha256 +95 -0
- package/release.sha256.sig +6 -0
- package/specialists/AGENTS.md +67 -0
- package/specialists/README.md +81 -0
- package/specialists/entry/specialist-cli.sh +22 -0
- package/specialists/entry/specialist-install.sh +861 -0
- package/specialists/entry/specialist-install.test.ts +305 -0
- package/specialists/lib/argv.ts +19 -0
- package/specialists/lib/audit.ts +20 -0
- package/specialists/lib/config.ts +27 -0
- package/specialists/lib/errors.ts +8 -0
- package/specialists/lib/flush.test.ts +21 -0
- package/specialists/lib/lib.test.ts +87 -0
- package/specialists/lib/lock.test.ts +42 -0
- package/specialists/lib/lock.ts +67 -0
- package/specialists/lib/main.ts +40 -0
- package/specialists/lib/output.ts +11 -0
- package/specialists/lib/paths.ts +22 -0
- package/specialists/lib/pinned.test.ts +55 -0
- package/specialists/lib/pinned.ts +67 -0
- package/specialists/lib/proc.ts +49 -0
- package/specialists/lib/repo.ts +198 -0
- package/specialists/lib/runtime.test.ts +81 -0
- package/specialists/lib/sanitize.ts +43 -0
- package/specialists/lib/secrets.ts +28 -0
- package/specialists/lib/ssh.ts +38 -0
- package/specialists/lib/tunnel.test.ts +44 -0
- package/specialists/lib/tunnel.ts +76 -0
- package/specialists/provision/provision.sh +96 -0
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The part of the specialist gate that every harness shares: the approval
|
|
3
|
+
* request to a chat bridge, the guard's markers, the entry point's argument
|
|
4
|
+
* list, and the texts a failed call returns. No Pi imports, so the Claude Code
|
|
5
|
+
* harness (`harness/claude.ts`) bundles it unchanged.
|
|
6
|
+
*/
|
|
7
|
+
import type { SpecialistEntry, SpecialistsConfig } from "./types.ts";
|
|
8
|
+
|
|
9
|
+
export { isRisky } from "./risky.ts";
|
|
10
|
+
|
|
11
|
+
const DEFAULT_USER = "specialist";
|
|
12
|
+
const FIXED_COMMAND_MARKERS = ["specialist-cli", "arcane-cli"];
|
|
13
|
+
|
|
14
|
+
/** Set by a chat bridge (astro-discord) on the specialist child: where to ask an operator before a risky call. */
|
|
15
|
+
export const APPROVAL_URL_ENV = "ASTRO_APPROVAL_URL";
|
|
16
|
+
export const APPROVAL_TOKEN_ENV = "ASTRO_APPROVAL_TOKEN";
|
|
17
|
+
/** The bridge task a specialist works for; a specialist that another specialist called inherits it. */
|
|
18
|
+
export const APPROVAL_TASK_ENV = "ASTRO_APPROVAL_TASK";
|
|
19
|
+
|
|
20
|
+
export type Decision = "approve" | "deny" | "timeout";
|
|
21
|
+
|
|
22
|
+
export interface ApprovalRequest {
|
|
23
|
+
agent: string;
|
|
24
|
+
service: string;
|
|
25
|
+
args: readonly string[];
|
|
26
|
+
task?: string;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
interface Ticket {
|
|
30
|
+
id?: unknown;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
interface TicketState {
|
|
34
|
+
decision?: unknown;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Asks the bridge for an operator decision: POST creates a ticket, then the
|
|
39
|
+
* ticket is polled until it is decided. Polling keeps every HTTP call short.
|
|
40
|
+
*/
|
|
41
|
+
export async function requestApproval(url: string, token: string, request: ApprovalRequest, signal?: AbortSignal, pollMs = 5000, fetchImpl: typeof fetch = fetch): Promise<Decision> {
|
|
42
|
+
const headers = { Authorization: `Bearer ${token}`, "Content-Type": "application/json" };
|
|
43
|
+
const created = await fetchImpl(`${url}/approvals`, { method: "POST", headers, body: JSON.stringify(request), signal });
|
|
44
|
+
if (!created.ok) throw new Error(`approval endpoint answered ${created.status}`);
|
|
45
|
+
const ticket = (await created.json()) as Ticket;
|
|
46
|
+
if (typeof ticket.id !== "string") throw new Error("approval endpoint returned no ticket id");
|
|
47
|
+
for (;;) {
|
|
48
|
+
await new Promise<void>((resolve, reject) => {
|
|
49
|
+
const timer = setTimeout(resolve, pollMs);
|
|
50
|
+
signal?.addEventListener(
|
|
51
|
+
"abort",
|
|
52
|
+
() => {
|
|
53
|
+
clearTimeout(timer);
|
|
54
|
+
reject(new Error("aborted while waiting for approval"));
|
|
55
|
+
},
|
|
56
|
+
{ once: true },
|
|
57
|
+
);
|
|
58
|
+
});
|
|
59
|
+
const response = await fetchImpl(`${url}/approvals/${ticket.id}`, { headers, signal });
|
|
60
|
+
if (!response.ok) throw new Error(`approval endpoint answered ${response.status}`);
|
|
61
|
+
const state = (await response.json()) as TicketState;
|
|
62
|
+
if (state.decision === "approve" || state.decision === "deny" || state.decision === "timeout") return state.decision;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export interface Guard {
|
|
67
|
+
user: string;
|
|
68
|
+
commandMarkers: string[];
|
|
69
|
+
protectedRoot: string;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export function buildGuard(config: SpecialistsConfig | null): Guard {
|
|
73
|
+
const user = config?.user ?? DEFAULT_USER;
|
|
74
|
+
const markers = new Set(FIXED_COMMAND_MARKERS);
|
|
75
|
+
markers.add(`-u ${user}`);
|
|
76
|
+
markers.add(`su ${user}`);
|
|
77
|
+
for (const entry of config?.specialists ?? []) markers.add(`${entry.service}-run`);
|
|
78
|
+
return { user, commandMarkers: [...markers], protectedRoot: `/Users/${user}` };
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export function blockedCommandMarker(command: string, guard: Guard): string | null {
|
|
82
|
+
for (const marker of guard.commandMarkers) {
|
|
83
|
+
if (command.includes(marker)) return marker;
|
|
84
|
+
}
|
|
85
|
+
return null;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export function isProtectedPath(path: string, guard: Guard): boolean {
|
|
89
|
+
return path === guard.protectedRoot || path.startsWith(`${guard.protectedRoot}/`);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export function entryArgs(config: SpecialistsConfig, entry: SpecialistEntry, args: string[]): string[] {
|
|
93
|
+
return ["-n", "-u", config.user, "-H", config.entry, entry.service, "--caller", entry.agent, "--", ...args];
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
/** Names the specialists to delegate to, for a blocked call's reason. */
|
|
98
|
+
export function delegateHint(config: SpecialistsConfig | null): string {
|
|
99
|
+
const names = (config?.specialists ?? []).map((s) => s.agent);
|
|
100
|
+
return names.length > 0 ? `Delegate to a specialist agent (${names.join(", ")}).` : "Delegate to a specialist agent.";
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
export function deniedText(entry: SpecialistEntry, decision: Exclude<Decision, "approve">, args: readonly string[]): string {
|
|
104
|
+
return `${entry.service}: the operator ${decision === "deny" ? "denied" : "did not answer the approval request for"} \`${args.join(" ")}\`. Report this and stop.`;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
export function stoppedText(entry: SpecialistEntry): string {
|
|
108
|
+
return `${entry.service} specialist was stopped after ${entry.timeoutMs} ms or by an abort; its result is unknown, so check the state before you report anything as done`;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
export function failedText(entry: SpecialistEntry, code: number, stderr: string, stdout: string): string {
|
|
112
|
+
const detail = stderr.trim() || stdout.trim();
|
|
113
|
+
return `${entry.service} specialist exited with code ${code}${detail ? `\n${detail}` : ""}`;
|
|
114
|
+
}
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { tmpdir } from "node:os";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
|
5
|
+
|
|
6
|
+
type Handler = (event: Record<string, unknown>, ctx: unknown) => Promise<unknown>;
|
|
7
|
+
|
|
8
|
+
interface RegisteredTool {
|
|
9
|
+
name: string;
|
|
10
|
+
execute: (id: string, input: { args: string[] }, signal?: AbortSignal) => Promise<{ content: { text: string }[] }>;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
interface CapturedPi {
|
|
14
|
+
handlers: Record<string, Handler>;
|
|
15
|
+
tools: Map<string, RegisteredTool>;
|
|
16
|
+
exec: ReturnType<typeof vi.fn>;
|
|
17
|
+
on: (event: string, handler: Handler) => void;
|
|
18
|
+
registerTool: (tool: RegisteredTool) => void;
|
|
19
|
+
registerCommand: () => void;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function makePi(): CapturedPi {
|
|
23
|
+
const handlers: Record<string, Handler> = {};
|
|
24
|
+
const tools = new Map<string, RegisteredTool>();
|
|
25
|
+
return {
|
|
26
|
+
handlers,
|
|
27
|
+
tools,
|
|
28
|
+
exec: vi.fn().mockResolvedValue({ stdout: '{"ok":true}\n', stderr: "", code: 0, killed: false }),
|
|
29
|
+
on: (event, handler) => {
|
|
30
|
+
handlers[event] = handler;
|
|
31
|
+
},
|
|
32
|
+
registerTool: (tool) => {
|
|
33
|
+
tools.set(tool.name, tool);
|
|
34
|
+
},
|
|
35
|
+
registerCommand: () => {},
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
const config = {
|
|
40
|
+
entry: "/usr/local/bin/specialist-cli",
|
|
41
|
+
user: "specialist",
|
|
42
|
+
specialists: [
|
|
43
|
+
{ agent: "astro.arcane", tool: "arcane", service: "arcane", timeoutMs: 1000 },
|
|
44
|
+
{ agent: "astro.network", tool: "network", service: "network", timeoutMs: 1000 },
|
|
45
|
+
],
|
|
46
|
+
};
|
|
47
|
+
|
|
48
|
+
describe("specialist-gate", () => {
|
|
49
|
+
let root: string;
|
|
50
|
+
const originalDir = process.env.PI_CODING_AGENT_DIR;
|
|
51
|
+
const originalAgent = process.env.ASTRO_SUBAGENT_AGENT;
|
|
52
|
+
|
|
53
|
+
beforeEach(() => {
|
|
54
|
+
root = mkdtempSync(join(tmpdir(), "spg-"));
|
|
55
|
+
process.env.PI_CODING_AGENT_DIR = root;
|
|
56
|
+
delete process.env.ASTRO_SUBAGENT_AGENT;
|
|
57
|
+
vi.resetModules();
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
afterEach(() => {
|
|
61
|
+
rmSync(root, { recursive: true, force: true });
|
|
62
|
+
process.env.PI_CODING_AGENT_DIR = originalDir;
|
|
63
|
+
if (originalAgent === undefined) delete process.env.ASTRO_SUBAGENT_AGENT;
|
|
64
|
+
else process.env.ASTRO_SUBAGENT_AGENT = originalAgent;
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
async function load(cfg?: unknown, agent?: string): Promise<CapturedPi> {
|
|
68
|
+
if (cfg !== undefined) {
|
|
69
|
+
mkdirSync(root, { recursive: true });
|
|
70
|
+
writeFileSync(join(root, "specialists.json"), typeof cfg === "string" ? cfg : JSON.stringify(cfg), "utf-8");
|
|
71
|
+
}
|
|
72
|
+
if (agent) process.env.ASTRO_SUBAGENT_AGENT = agent;
|
|
73
|
+
const mod = await import("./index.ts");
|
|
74
|
+
const pi = makePi();
|
|
75
|
+
mod.default(pi as unknown as Parameters<typeof mod.default>[0]);
|
|
76
|
+
return pi;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
const ctx = { ui: { notify: vi.fn() } };
|
|
80
|
+
|
|
81
|
+
it("registers no tool without a config file", async () => {
|
|
82
|
+
const pi = await load(undefined, "astro.arcane");
|
|
83
|
+
expect(pi.tools.size).toBe(0);
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
it("registers no tool outside a specialist child", async () => {
|
|
87
|
+
const pi = await load(config);
|
|
88
|
+
expect(pi.tools.size).toBe(0);
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
it("registers only the matching specialist's tool in its child", async () => {
|
|
92
|
+
const pi = await load(config, "astro.arcane");
|
|
93
|
+
expect([...pi.tools.keys()]).toEqual(["arcane"]);
|
|
94
|
+
});
|
|
95
|
+
|
|
96
|
+
it("runs the entry point through sudo with args after --", async () => {
|
|
97
|
+
const pi = await load(config, "astro.arcane");
|
|
98
|
+
const tool = pi.tools.get("arcane");
|
|
99
|
+
if (!tool) throw new Error("tool missing");
|
|
100
|
+
const result = await tool.execute("id", { args: ["projects", "list", "--limit", "5"] });
|
|
101
|
+
expect(pi.exec).toHaveBeenCalledWith(
|
|
102
|
+
"sudo",
|
|
103
|
+
["-n", "-u", "specialist", "-H", "/usr/local/bin/specialist-cli", "arcane", "--caller", "astro.arcane", "--", "projects", "list", "--limit", "5"],
|
|
104
|
+
expect.objectContaining({ timeout: 1000 }),
|
|
105
|
+
);
|
|
106
|
+
expect(result.content[0].text).toBe('{"ok":true}');
|
|
107
|
+
});
|
|
108
|
+
|
|
109
|
+
it("throws with stderr when the entry point fails", async () => {
|
|
110
|
+
const pi = await load(config, "astro.arcane");
|
|
111
|
+
pi.exec.mockResolvedValueOnce({ stdout: "", stderr: "unknown subcommand", code: 2, killed: false });
|
|
112
|
+
const tool = pi.tools.get("arcane");
|
|
113
|
+
if (!tool) throw new Error("tool missing");
|
|
114
|
+
await expect(tool.execute("id", { args: ["nope"] })).rejects.toThrow(/code 2[\s\S]*unknown subcommand/);
|
|
115
|
+
});
|
|
116
|
+
|
|
117
|
+
it("blocks bash commands that reach the specialist CLIs", async () => {
|
|
118
|
+
const pi = await load(config);
|
|
119
|
+
for (const command of [
|
|
120
|
+
"arcane-cli projects list",
|
|
121
|
+
"sudo -u specialist ls",
|
|
122
|
+
"/usr/local/bin/specialist-cli arcane -- x",
|
|
123
|
+
"node ~/.specialists/bin/network-run sites",
|
|
124
|
+
]) {
|
|
125
|
+
const decision = await pi.handlers.tool_call({ toolName: "bash", input: { command } }, ctx);
|
|
126
|
+
expect(decision, command).toEqual(expect.objectContaining({ block: true }));
|
|
127
|
+
}
|
|
128
|
+
});
|
|
129
|
+
|
|
130
|
+
it("does not block unrelated bash commands", async () => {
|
|
131
|
+
const pi = await load(config);
|
|
132
|
+
const decision = await pi.handlers.tool_call({ toolName: "bash", input: { command: "git push --dry-run" } }, ctx);
|
|
133
|
+
expect(decision).toBeUndefined();
|
|
134
|
+
});
|
|
135
|
+
|
|
136
|
+
it("blocks reads, writes, and edits under the specialist home", async () => {
|
|
137
|
+
const pi = await load(config);
|
|
138
|
+
for (const toolName of ["read", "write", "edit"]) {
|
|
139
|
+
const decision = await pi.handlers.tool_call(
|
|
140
|
+
{ toolName, input: { path: "/Users/specialist/.specialists/secrets/arcane/ZITADEL_KEY_JSON" } },
|
|
141
|
+
ctx,
|
|
142
|
+
);
|
|
143
|
+
expect(decision, toolName).toEqual(expect.objectContaining({ block: true }));
|
|
144
|
+
}
|
|
145
|
+
const ok = await pi.handlers.tool_call({ toolName: "read", input: { path: "/Users/specialist-notes.md" } }, ctx);
|
|
146
|
+
expect(ok).toBeUndefined();
|
|
147
|
+
});
|
|
148
|
+
|
|
149
|
+
it("keeps the blocks with defaults when the config is invalid", async () => {
|
|
150
|
+
const pi = await load("{not json");
|
|
151
|
+
const decision = await pi.handlers.tool_call({ toolName: "bash", input: { command: "arcane-cli --help" } }, ctx);
|
|
152
|
+
expect(decision).toEqual(expect.objectContaining({ block: true }));
|
|
153
|
+
await pi.handlers.session_start({}, ctx);
|
|
154
|
+
expect(ctx.ui.notify).toHaveBeenCalledWith(expect.stringContaining("invalid JSON"), "warning");
|
|
155
|
+
});
|
|
156
|
+
|
|
157
|
+
it("rejects malformed entries but keeps valid ones", async () => {
|
|
158
|
+
const { validateConfig } = await import("./config.ts");
|
|
159
|
+
const errors: string[] = [];
|
|
160
|
+
const cfg = validateConfig(
|
|
161
|
+
{
|
|
162
|
+
entry: "/usr/local/bin/specialist-cli",
|
|
163
|
+
user: "specialist",
|
|
164
|
+
specialists: [
|
|
165
|
+
{ agent: "astro.arcane", tool: "arcane", service: "arcane", timeoutMs: 10 },
|
|
166
|
+
{ agent: "astro.bad", tool: "Bad Tool", service: "bad", timeoutMs: 10 },
|
|
167
|
+
{ agent: "astro.slow", tool: "slow", service: "slow", timeoutMs: -1 },
|
|
168
|
+
],
|
|
169
|
+
},
|
|
170
|
+
errors,
|
|
171
|
+
);
|
|
172
|
+
expect(cfg?.specialists.map((s) => s.tool)).toEqual(["arcane"]);
|
|
173
|
+
expect(errors).toHaveLength(2);
|
|
174
|
+
expect(validateConfig({ entry: "relative/path", user: "specialist", specialists: [] }, errors)).toBeNull();
|
|
175
|
+
});
|
|
176
|
+
|
|
177
|
+
it("reads a pack's risky patterns and refuses ones that are empty, unanchored, or broken", async () => {
|
|
178
|
+
const { validateConfig } = await import("./config.ts");
|
|
179
|
+
const { isRisky } = await import("./risky.ts");
|
|
180
|
+
const base = { agent: "astro.dns", tool: "dns", service: "dns", timeoutMs: 10 };
|
|
181
|
+
const errors: string[] = [];
|
|
182
|
+
const cfg = validateConfig(
|
|
183
|
+
{
|
|
184
|
+
entry: "/usr/local/bin/specialist-cli",
|
|
185
|
+
user: "specialist",
|
|
186
|
+
specialists: [
|
|
187
|
+
{ ...base, risky: ["^zone-delete\\b"] },
|
|
188
|
+
{ ...base, tool: "a", risky: [] },
|
|
189
|
+
{ ...base, tool: "b", risky: ["zone-delete"] },
|
|
190
|
+
{ ...base, tool: "c", risky: ["^("] },
|
|
191
|
+
],
|
|
192
|
+
},
|
|
193
|
+
errors,
|
|
194
|
+
);
|
|
195
|
+
expect(cfg?.specialists.map((s) => s.tool)).toEqual(["dns"]);
|
|
196
|
+
expect(errors).toHaveLength(3);
|
|
197
|
+
const risky = cfg?.specialists[0].risky ?? [];
|
|
198
|
+
expect(isRisky(["zone-delete", "x"], risky)).toBe(true);
|
|
199
|
+
expect(isRisky(["zones"], risky)).toBe(false);
|
|
200
|
+
expect(isRisky(["zones", "--confirm"], risky)).toBe(true);
|
|
201
|
+
});
|
|
202
|
+
});
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
import type { ExtensionAPI, ExtensionContext, ToolCallEvent } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { Type } from "typebox";
|
|
3
|
+
import { loadConfig } from "./config.ts";
|
|
4
|
+
import { AGENT_ENV } from "../subagents/child.ts";
|
|
5
|
+
import type { SpecialistEntry, SpecialistsConfig } from "./types.ts";
|
|
6
|
+
import { APPROVAL_TASK_ENV, APPROVAL_TOKEN_ENV, APPROVAL_URL_ENV, blockedCommandMarker, buildGuard, delegateHint, deniedText, entryArgs, failedText, type Guard, isProtectedPath, isRisky, requestApproval, stoppedText } from "./core.ts";
|
|
7
|
+
|
|
8
|
+
export { APPROVAL_TASK_ENV, APPROVAL_TOKEN_ENV, APPROVAL_URL_ENV, type ApprovalRequest, blockedCommandMarker, buildGuard, type Decision, entryArgs, type Guard, isProtectedPath, requestApproval } from "./core.ts";
|
|
9
|
+
|
|
10
|
+
/** Set by astro-subagents on every child session it spawns. */
|
|
11
|
+
export const CHILD_AGENT_ENV = AGENT_ENV;
|
|
12
|
+
|
|
13
|
+
function pathsOf(event: ToolCallEvent): string[] {
|
|
14
|
+
const input = event.input as Record<string, unknown>;
|
|
15
|
+
const paths: string[] = [];
|
|
16
|
+
if (typeof input.path === "string") paths.push(input.path);
|
|
17
|
+
const multi = input.multi;
|
|
18
|
+
if (Array.isArray(multi)) {
|
|
19
|
+
for (const item of multi) {
|
|
20
|
+
if (item && typeof item === "object" && typeof (item as { path?: unknown }).path === "string") {
|
|
21
|
+
paths.push((item as { path: string }).path);
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
return paths;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function decide(
|
|
29
|
+
event: ToolCallEvent,
|
|
30
|
+
guard: Guard,
|
|
31
|
+
config: SpecialistsConfig | null,
|
|
32
|
+
): { block: true; reason: string } | undefined {
|
|
33
|
+
if (event.toolName === "bash") {
|
|
34
|
+
const command = (event.input as { command?: string }).command ?? "";
|
|
35
|
+
const marker = blockedCommandMarker(command, guard);
|
|
36
|
+
if (marker) {
|
|
37
|
+
return { block: true, reason: `specialist-gate: "${marker}" is reserved for specialists. ${delegateHint(config)}` };
|
|
38
|
+
}
|
|
39
|
+
return undefined;
|
|
40
|
+
}
|
|
41
|
+
if (event.toolName === "read" || event.toolName === "write" || event.toolName === "edit") {
|
|
42
|
+
for (const p of pathsOf(event)) {
|
|
43
|
+
if (isProtectedPath(p, guard)) {
|
|
44
|
+
return {
|
|
45
|
+
block: true,
|
|
46
|
+
reason: `specialist-gate: ${guard.protectedRoot} holds specialist credentials. ${delegateHint(config)}`,
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
return undefined;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
const params = Type.Object({
|
|
55
|
+
args: Type.Array(Type.String(), {
|
|
56
|
+
description: "Subcommand and arguments for the specialist CLI, one array element per argument.",
|
|
57
|
+
}),
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
function registerSpecialistTool(pi: ExtensionAPI, config: SpecialistsConfig, entry: SpecialistEntry): void {
|
|
61
|
+
pi.registerTool({
|
|
62
|
+
name: entry.tool,
|
|
63
|
+
label: `Specialist: ${entry.service}`,
|
|
64
|
+
description: `Runs the ${entry.service} specialist CLI. Pass the subcommand and its arguments as an array. Output is JSON on success; errors carry the CLI's stderr.`,
|
|
65
|
+
promptGuidelines: [
|
|
66
|
+
`Use \`${entry.tool}\` for every operation in the ${entry.service} area. It is the only path to that service.`,
|
|
67
|
+
`Start with \`${entry.tool}\` and args ["--help"] when unsure which subcommands exist.`,
|
|
68
|
+
],
|
|
69
|
+
parameters: params,
|
|
70
|
+
async execute(_toolCallId, input, signal) {
|
|
71
|
+
const approvalUrl = process.env[APPROVAL_URL_ENV];
|
|
72
|
+
if (approvalUrl && isRisky(input.args, entry.risky ?? [])) {
|
|
73
|
+
const decision = await requestApproval(approvalUrl, process.env[APPROVAL_TOKEN_ENV] ?? "", { agent: entry.agent, service: entry.service, args: input.args, task: process.env[APPROVAL_TASK_ENV] }, signal);
|
|
74
|
+
if (decision !== "approve") throw new Error(deniedText(entry, decision, input.args));
|
|
75
|
+
}
|
|
76
|
+
const result = await pi.exec("sudo", entryArgs(config, entry, input.args), {
|
|
77
|
+
signal,
|
|
78
|
+
timeout: entry.timeoutMs,
|
|
79
|
+
});
|
|
80
|
+
if (result.killed) throw new Error(stoppedText(entry));
|
|
81
|
+
if (result.code !== 0) throw new Error(failedText(entry, result.code, result.stderr, result.stdout));
|
|
82
|
+
return { content: [{ type: "text", text: result.stdout.trim() || "(no output)" }], details: {} };
|
|
83
|
+
},
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export default function specialistGateExtension(pi: ExtensionAPI): void {
|
|
88
|
+
const loaded = loadConfig();
|
|
89
|
+
const guard = buildGuard(loaded.config);
|
|
90
|
+
const childAgent = process.env[CHILD_AGENT_ENV];
|
|
91
|
+
const mine = childAgent ? (loaded.config?.specialists.find((s) => s.agent === childAgent) ?? null) : null;
|
|
92
|
+
|
|
93
|
+
if (loaded.config && mine) registerSpecialistTool(pi, loaded.config, mine);
|
|
94
|
+
|
|
95
|
+
pi.on("tool_call", async (event: ToolCallEvent) => decide(event, guard, loaded.config));
|
|
96
|
+
|
|
97
|
+
pi.on("session_start", async (_event, ctx: ExtensionContext) => {
|
|
98
|
+
for (const error of loaded.errors) ctx.ui.notify(`specialist-gate: ${loaded.configPath}: ${error}`, "warning");
|
|
99
|
+
if (mine) ctx.ui.notify(`specialist-gate: ${mine.agent} has tool \`${mine.tool}\``, "info");
|
|
100
|
+
});
|
|
101
|
+
|
|
102
|
+
pi.registerCommand("specialists", {
|
|
103
|
+
description: "Show specialist-gate status",
|
|
104
|
+
handler: async (_args, ctx) => {
|
|
105
|
+
const lines = [
|
|
106
|
+
`config: ${loaded.configPath}${loaded.config ? "" : " (absent or invalid)"}`,
|
|
107
|
+
`protected: ${guard.protectedRoot}`,
|
|
108
|
+
`blocked bash markers: ${guard.commandMarkers.join(", ")}`,
|
|
109
|
+
`this session: ${mine ? `${mine.agent} → ${mine.tool}` : "no specialist tool"}`,
|
|
110
|
+
];
|
|
111
|
+
ctx.ui.notify(lines.join("\n"), "info");
|
|
112
|
+
},
|
|
113
|
+
});
|
|
114
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Whether a specialist call needs an operator's approval: `--confirm`, or one of the entry's
|
|
3
|
+
* `risky` patterns from specialists.json, which the site's pack writes. Without patterns only
|
|
4
|
+
* `--confirm` is risky. No Pi imports, so a pack can test its patterns against this function.
|
|
5
|
+
*/
|
|
6
|
+
export function isRisky(args: readonly string[], patterns: readonly RegExp[]): boolean {
|
|
7
|
+
// `--help` gets no exemption: a wrapper reads it only as the first argument, so anywhere else it would pass a write unasked.
|
|
8
|
+
if (args.includes("--confirm")) return true;
|
|
9
|
+
// Flags must not hide the command from the patterns, whether they take no value (`--json projects delete x`)
|
|
10
|
+
// or one (`--agent 1 volumes rm x`, `projects --agent 1 down x`); the gate cannot know which, so it tries both.
|
|
11
|
+
const flagsDropped = args.filter((a) => !a.startsWith("-"));
|
|
12
|
+
const valuesDropped = args.filter((a, i) => !a.startsWith("-") && args[i - 1]?.startsWith("-") !== true);
|
|
13
|
+
return [flagsDropped, valuesDropped].some((words) => patterns.some((pattern) => pattern.test(words.join(" "))));
|
|
14
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
export interface SpecialistEntry {
|
|
2
|
+
/** Runtime agent name as pi-subagents reports it, e.g. `astro.arcane`. */
|
|
3
|
+
agent: string;
|
|
4
|
+
/** Tool name registered in that agent's session. */
|
|
5
|
+
tool: string;
|
|
6
|
+
/** Service argument passed to the entry point. */
|
|
7
|
+
service: string;
|
|
8
|
+
timeoutMs: number;
|
|
9
|
+
/** Calls that need the operator's approval, matched against the arguments joined by spaces; a pack sets them. */
|
|
10
|
+
risky?: RegExp[];
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export interface SpecialistsConfig {
|
|
14
|
+
/** Root-owned sudo entry point, e.g. `/usr/local/bin/specialist-cli`. */
|
|
15
|
+
entry: string;
|
|
16
|
+
/** macOS user that owns keys and CLIs. */
|
|
17
|
+
user: string;
|
|
18
|
+
specialists: SpecialistEntry[];
|
|
19
|
+
}
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
import { existsSync, mkdirSync, mkdtempSync, 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, vi } from "vitest";
|
|
5
|
+
|
|
6
|
+
describe("config", () => {
|
|
7
|
+
let root: string;
|
|
8
|
+
const originalDir = process.env.PI_CODING_AGENT_DIR;
|
|
9
|
+
const originalDryRun = process.env.PI_SECURITY_GUARD_DRY_RUN;
|
|
10
|
+
|
|
11
|
+
beforeEach(() => {
|
|
12
|
+
root = mkdtempSync(join(tmpdir(), "sg-cfg-"));
|
|
13
|
+
process.env.PI_CODING_AGENT_DIR = root;
|
|
14
|
+
delete process.env.PI_SECURITY_GUARD_DRY_RUN;
|
|
15
|
+
vi.resetModules();
|
|
16
|
+
});
|
|
17
|
+
|
|
18
|
+
afterEach(() => {
|
|
19
|
+
rmSync(root, { recursive: true, force: true });
|
|
20
|
+
process.env.PI_CODING_AGENT_DIR = originalDir;
|
|
21
|
+
if (originalDryRun === undefined) delete process.env.PI_SECURITY_GUARD_DRY_RUN;
|
|
22
|
+
else process.env.PI_SECURITY_GUARD_DRY_RUN = originalDryRun;
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
it("uses defaults when config file missing", async () => {
|
|
26
|
+
const { loadConfig } = await import("./config.ts");
|
|
27
|
+
const r = loadConfig();
|
|
28
|
+
expect(r.configExists).toBe(false);
|
|
29
|
+
expect(r.rules.operations.length).toBeGreaterThan(0);
|
|
30
|
+
expect(r.errors).toEqual([]);
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
it("loads user JSON rules overriding defaults when non-empty", async () => {
|
|
34
|
+
writeFileSync(
|
|
35
|
+
join(root, "security-guard.json"),
|
|
36
|
+
JSON.stringify({
|
|
37
|
+
operations: [{ pattern: "myop", action: "block" }],
|
|
38
|
+
writes: [{ pattern: "*.secret", action: "prompt" }],
|
|
39
|
+
}),
|
|
40
|
+
"utf-8",
|
|
41
|
+
);
|
|
42
|
+
const { loadConfig } = await import("./config.ts");
|
|
43
|
+
const r = loadConfig();
|
|
44
|
+
expect(r.configExists).toBe(true);
|
|
45
|
+
expect(r.rules.operations).toEqual([{ pattern: "myop", action: "block" }]);
|
|
46
|
+
expect(r.rules.writes).toEqual([{ pattern: "*.secret", action: "prompt" }]);
|
|
47
|
+
// reads missing → defaults used
|
|
48
|
+
expect(r.rules.reads.length).toBeGreaterThan(0);
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
it("invalid JSON falls back to defaults and records error", async () => {
|
|
52
|
+
writeFileSync(join(root, "security-guard.json"), "{not json", "utf-8");
|
|
53
|
+
const { loadConfig } = await import("./config.ts");
|
|
54
|
+
const r = loadConfig();
|
|
55
|
+
expect(r.errors.length).toBeGreaterThan(0);
|
|
56
|
+
expect(r.rules.operations.length).toBeGreaterThan(0);
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
it("malformed rule (bad action) is skipped with error", async () => {
|
|
60
|
+
writeFileSync(
|
|
61
|
+
join(root, "security-guard.json"),
|
|
62
|
+
JSON.stringify({
|
|
63
|
+
operations: [
|
|
64
|
+
{ pattern: "ok", action: "block" },
|
|
65
|
+
{ pattern: "bad", action: "nuke-from-orbit" },
|
|
66
|
+
{ pattern: "", action: "prompt" }, // empty pattern
|
|
67
|
+
"not-an-object",
|
|
68
|
+
],
|
|
69
|
+
}),
|
|
70
|
+
"utf-8",
|
|
71
|
+
);
|
|
72
|
+
const { loadConfig } = await import("./config.ts");
|
|
73
|
+
const r = loadConfig();
|
|
74
|
+
expect(r.rules.operations).toEqual([{ pattern: "ok", action: "block" }]);
|
|
75
|
+
expect(r.errors.length).toBeGreaterThanOrEqual(3);
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
it("non-array section logs error and falls back to default for that section", async () => {
|
|
79
|
+
writeFileSync(
|
|
80
|
+
join(root, "security-guard.json"),
|
|
81
|
+
JSON.stringify({ operations: "not an array" }),
|
|
82
|
+
"utf-8",
|
|
83
|
+
);
|
|
84
|
+
const { loadConfig } = await import("./config.ts");
|
|
85
|
+
const r = loadConfig();
|
|
86
|
+
expect(r.errors.some((e) => e.includes("operations"))).toBe(true);
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
it("ensureExampleConfig creates .example file once", async () => {
|
|
90
|
+
const { ensureExampleConfig } = await import("./config.ts");
|
|
91
|
+
mkdirSync(root, { recursive: true });
|
|
92
|
+
ensureExampleConfig();
|
|
93
|
+
const p = join(root, "security-guard.json.example");
|
|
94
|
+
expect(existsSync(p)).toBe(true);
|
|
95
|
+
const first = readFileSync(p, "utf-8");
|
|
96
|
+
// Running again doesn't overwrite / doesn't throw
|
|
97
|
+
ensureExampleConfig();
|
|
98
|
+
expect(readFileSync(p, "utf-8")).toBe(first);
|
|
99
|
+
});
|
|
100
|
+
|
|
101
|
+
it("isDryRun flips with env var", async () => {
|
|
102
|
+
const { isDryRun } = await import("./config.ts");
|
|
103
|
+
expect(isDryRun()).toBe(false);
|
|
104
|
+
process.env.PI_SECURITY_GUARD_DRY_RUN = "1";
|
|
105
|
+
expect(isDryRun()).toBe(true);
|
|
106
|
+
});
|
|
107
|
+
});
|