@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,286 @@
1
+ import { createRequire as __astroCreateRequire } from "node:module";
2
+ const require = __astroCreateRequire(import.meta.url);
3
+
4
+ // extensions/gate/index.ts
5
+ import { Type } from "typebox";
6
+
7
+ // extensions/gate/config.ts
8
+ import { existsSync, readFileSync } from "node:fs";
9
+ import { homedir } from "node:os";
10
+ import { join } from "node:path";
11
+ function configPath() {
12
+ const dir = process.env.PI_CODING_AGENT_DIR ?? join(homedir(), ".pi", "agent");
13
+ return join(dir, "specialists.json");
14
+ }
15
+ var NAME = /^[a-z][a-z0-9-]*$/;
16
+ function validateEntry(raw, errors, where) {
17
+ if (typeof raw !== "object" || raw === null) {
18
+ errors.push(`${where}: entry is not an object`);
19
+ return null;
20
+ }
21
+ const r = raw;
22
+ const agent = r.agent;
23
+ const tool = r.tool;
24
+ const service = r.service;
25
+ const timeoutMs = r.timeoutMs;
26
+ if (typeof agent !== "string" || agent.length === 0) {
27
+ errors.push(`${where}: missing 'agent'`);
28
+ return null;
29
+ }
30
+ if (typeof tool !== "string" || !NAME.test(tool)) {
31
+ errors.push(`${where}: 'tool' must match ${NAME}`);
32
+ return null;
33
+ }
34
+ if (typeof service !== "string" || !NAME.test(service)) {
35
+ errors.push(`${where}: 'service' must match ${NAME}`);
36
+ return null;
37
+ }
38
+ if (typeof timeoutMs !== "number" || !Number.isInteger(timeoutMs) || timeoutMs <= 0) {
39
+ errors.push(`${where}: 'timeoutMs' must be a positive integer`);
40
+ return null;
41
+ }
42
+ if (r.risky === void 0) return { agent, tool, service, timeoutMs };
43
+ const risky = riskyPatterns(r.risky, errors, where);
44
+ return risky ? { agent, tool, service, timeoutMs, risky } : null;
45
+ }
46
+ var MAX_PATTERN = 500;
47
+ function riskyPatterns(raw, errors, where) {
48
+ if (!Array.isArray(raw) || raw.length === 0) {
49
+ errors.push(`${where}: 'risky' must be a non-empty array of patterns`);
50
+ return null;
51
+ }
52
+ const patterns = [];
53
+ for (const source of raw) {
54
+ if (typeof source !== "string" || source.length === 0 || source.length > MAX_PATTERN || !source.startsWith("^")) {
55
+ errors.push(`${where}: each 'risky' pattern must be a string of 1 to ${MAX_PATTERN} characters that starts with ^`);
56
+ return null;
57
+ }
58
+ try {
59
+ patterns.push(new RegExp(source));
60
+ } catch (err) {
61
+ errors.push(`${where}: 'risky' pattern ${source} does not compile: ${err instanceof Error ? err.message : String(err)}`);
62
+ return null;
63
+ }
64
+ }
65
+ return patterns;
66
+ }
67
+ function validateConfig(raw, errors) {
68
+ if (typeof raw !== "object" || raw === null) {
69
+ errors.push("config root is not an object");
70
+ return null;
71
+ }
72
+ const r = raw;
73
+ if (typeof r.entry !== "string" || !r.entry.startsWith("/")) {
74
+ errors.push("'entry' must be an absolute path");
75
+ return null;
76
+ }
77
+ if (typeof r.user !== "string" || !NAME.test(r.user)) {
78
+ errors.push(`'user' must match ${NAME}`);
79
+ return null;
80
+ }
81
+ if (!Array.isArray(r.specialists)) {
82
+ errors.push("'specialists' must be an array");
83
+ return null;
84
+ }
85
+ const specialists = [];
86
+ r.specialists.forEach((item, i) => {
87
+ const entry = validateEntry(item, errors, `specialists[${i}]`);
88
+ if (entry) specialists.push(entry);
89
+ });
90
+ return { entry: r.entry, user: r.user, specialists };
91
+ }
92
+ function loadConfig() {
93
+ const path = configPath();
94
+ const errors = [];
95
+ if (!existsSync(path)) return { config: null, configPath: path, errors };
96
+ try {
97
+ const parsed = JSON.parse(readFileSync(path, "utf-8"));
98
+ return { config: validateConfig(parsed, errors), configPath: path, errors };
99
+ } catch (err) {
100
+ errors.push(`invalid JSON: ${err instanceof Error ? err.message : String(err)}`);
101
+ return { config: null, configPath: path, errors };
102
+ }
103
+ }
104
+
105
+ // extensions/subagents/child.ts
106
+ var AGENT_ENV = "ASTRO_SUBAGENT_AGENT";
107
+
108
+ // extensions/gate/risky.ts
109
+ function isRisky(args, patterns) {
110
+ if (args.includes("--confirm")) return true;
111
+ const flagsDropped = args.filter((a) => !a.startsWith("-"));
112
+ const valuesDropped = args.filter((a, i) => !a.startsWith("-") && args[i - 1]?.startsWith("-") !== true);
113
+ return [flagsDropped, valuesDropped].some((words) => patterns.some((pattern) => pattern.test(words.join(" "))));
114
+ }
115
+
116
+ // extensions/gate/core.ts
117
+ var DEFAULT_USER = "specialist";
118
+ var FIXED_COMMAND_MARKERS = ["specialist-cli", "arcane-cli"];
119
+ var APPROVAL_URL_ENV = "ASTRO_APPROVAL_URL";
120
+ var APPROVAL_TOKEN_ENV = "ASTRO_APPROVAL_TOKEN";
121
+ var APPROVAL_TASK_ENV = "ASTRO_APPROVAL_TASK";
122
+ async function requestApproval(url, token, request, signal, pollMs = 5e3, fetchImpl = fetch) {
123
+ const headers = { Authorization: `Bearer ${token}`, "Content-Type": "application/json" };
124
+ const created = await fetchImpl(`${url}/approvals`, { method: "POST", headers, body: JSON.stringify(request), signal });
125
+ if (!created.ok) throw new Error(`approval endpoint answered ${created.status}`);
126
+ const ticket = await created.json();
127
+ if (typeof ticket.id !== "string") throw new Error("approval endpoint returned no ticket id");
128
+ for (; ; ) {
129
+ await new Promise((resolve, reject) => {
130
+ const timer = setTimeout(resolve, pollMs);
131
+ signal?.addEventListener(
132
+ "abort",
133
+ () => {
134
+ clearTimeout(timer);
135
+ reject(new Error("aborted while waiting for approval"));
136
+ },
137
+ { once: true }
138
+ );
139
+ });
140
+ const response = await fetchImpl(`${url}/approvals/${ticket.id}`, { headers, signal });
141
+ if (!response.ok) throw new Error(`approval endpoint answered ${response.status}`);
142
+ const state = await response.json();
143
+ if (state.decision === "approve" || state.decision === "deny" || state.decision === "timeout") return state.decision;
144
+ }
145
+ }
146
+ function buildGuard(config) {
147
+ const user = config?.user ?? DEFAULT_USER;
148
+ const markers = new Set(FIXED_COMMAND_MARKERS);
149
+ markers.add(`-u ${user}`);
150
+ markers.add(`su ${user}`);
151
+ for (const entry of config?.specialists ?? []) markers.add(`${entry.service}-run`);
152
+ return { user, commandMarkers: [...markers], protectedRoot: `/Users/${user}` };
153
+ }
154
+ function blockedCommandMarker(command, guard) {
155
+ for (const marker of guard.commandMarkers) {
156
+ if (command.includes(marker)) return marker;
157
+ }
158
+ return null;
159
+ }
160
+ function isProtectedPath(path, guard) {
161
+ return path === guard.protectedRoot || path.startsWith(`${guard.protectedRoot}/`);
162
+ }
163
+ function entryArgs(config, entry, args) {
164
+ return ["-n", "-u", config.user, "-H", config.entry, entry.service, "--caller", entry.agent, "--", ...args];
165
+ }
166
+ function delegateHint(config) {
167
+ const names = (config?.specialists ?? []).map((s) => s.agent);
168
+ return names.length > 0 ? `Delegate to a specialist agent (${names.join(", ")}).` : "Delegate to a specialist agent.";
169
+ }
170
+ function deniedText(entry, decision, args) {
171
+ return `${entry.service}: the operator ${decision === "deny" ? "denied" : "did not answer the approval request for"} \`${args.join(" ")}\`. Report this and stop.`;
172
+ }
173
+ function stoppedText(entry) {
174
+ 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`;
175
+ }
176
+ function failedText(entry, code, stderr, stdout) {
177
+ const detail = stderr.trim() || stdout.trim();
178
+ return `${entry.service} specialist exited with code ${code}${detail ? `
179
+ ${detail}` : ""}`;
180
+ }
181
+
182
+ // extensions/gate/index.ts
183
+ var CHILD_AGENT_ENV = AGENT_ENV;
184
+ function pathsOf(event) {
185
+ const input = event.input;
186
+ const paths = [];
187
+ if (typeof input.path === "string") paths.push(input.path);
188
+ const multi = input.multi;
189
+ if (Array.isArray(multi)) {
190
+ for (const item of multi) {
191
+ if (item && typeof item === "object" && typeof item.path === "string") {
192
+ paths.push(item.path);
193
+ }
194
+ }
195
+ }
196
+ return paths;
197
+ }
198
+ function decide(event, guard, config) {
199
+ if (event.toolName === "bash") {
200
+ const command = event.input.command ?? "";
201
+ const marker = blockedCommandMarker(command, guard);
202
+ if (marker) {
203
+ return { block: true, reason: `specialist-gate: "${marker}" is reserved for specialists. ${delegateHint(config)}` };
204
+ }
205
+ return void 0;
206
+ }
207
+ if (event.toolName === "read" || event.toolName === "write" || event.toolName === "edit") {
208
+ for (const p of pathsOf(event)) {
209
+ if (isProtectedPath(p, guard)) {
210
+ return {
211
+ block: true,
212
+ reason: `specialist-gate: ${guard.protectedRoot} holds specialist credentials. ${delegateHint(config)}`
213
+ };
214
+ }
215
+ }
216
+ }
217
+ return void 0;
218
+ }
219
+ var params = Type.Object({
220
+ args: Type.Array(Type.String(), {
221
+ description: "Subcommand and arguments for the specialist CLI, one array element per argument."
222
+ })
223
+ });
224
+ function registerSpecialistTool(pi, config, entry) {
225
+ pi.registerTool({
226
+ name: entry.tool,
227
+ label: `Specialist: ${entry.service}`,
228
+ 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.`,
229
+ promptGuidelines: [
230
+ `Use \`${entry.tool}\` for every operation in the ${entry.service} area. It is the only path to that service.`,
231
+ `Start with \`${entry.tool}\` and args ["--help"] when unsure which subcommands exist.`
232
+ ],
233
+ parameters: params,
234
+ async execute(_toolCallId, input, signal) {
235
+ const approvalUrl = process.env[APPROVAL_URL_ENV];
236
+ if (approvalUrl && isRisky(input.args, entry.risky ?? [])) {
237
+ 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);
238
+ if (decision !== "approve") throw new Error(deniedText(entry, decision, input.args));
239
+ }
240
+ const result = await pi.exec("sudo", entryArgs(config, entry, input.args), {
241
+ signal,
242
+ timeout: entry.timeoutMs
243
+ });
244
+ if (result.killed) throw new Error(stoppedText(entry));
245
+ if (result.code !== 0) throw new Error(failedText(entry, result.code, result.stderr, result.stdout));
246
+ return { content: [{ type: "text", text: result.stdout.trim() || "(no output)" }], details: {} };
247
+ }
248
+ });
249
+ }
250
+ function specialistGateExtension(pi) {
251
+ const loaded = loadConfig();
252
+ const guard = buildGuard(loaded.config);
253
+ const childAgent = process.env[CHILD_AGENT_ENV];
254
+ const mine = childAgent ? loaded.config?.specialists.find((s) => s.agent === childAgent) ?? null : null;
255
+ if (loaded.config && mine) registerSpecialistTool(pi, loaded.config, mine);
256
+ pi.on("tool_call", async (event) => decide(event, guard, loaded.config));
257
+ pi.on("session_start", async (_event, ctx) => {
258
+ for (const error of loaded.errors) ctx.ui.notify(`specialist-gate: ${loaded.configPath}: ${error}`, "warning");
259
+ if (mine) ctx.ui.notify(`specialist-gate: ${mine.agent} has tool \`${mine.tool}\``, "info");
260
+ });
261
+ pi.registerCommand("specialists", {
262
+ description: "Show specialist-gate status",
263
+ handler: async (_args, ctx) => {
264
+ const lines = [
265
+ `config: ${loaded.configPath}${loaded.config ? "" : " (absent or invalid)"}`,
266
+ `protected: ${guard.protectedRoot}`,
267
+ `blocked bash markers: ${guard.commandMarkers.join(", ")}`,
268
+ `this session: ${mine ? `${mine.agent} \u2192 ${mine.tool}` : "no specialist tool"}`
269
+ ];
270
+ ctx.ui.notify(lines.join("\n"), "info");
271
+ }
272
+ });
273
+ }
274
+ export {
275
+ APPROVAL_TASK_ENV,
276
+ APPROVAL_TOKEN_ENV,
277
+ APPROVAL_URL_ENV,
278
+ CHILD_AGENT_ENV,
279
+ blockedCommandMarker,
280
+ buildGuard,
281
+ decide,
282
+ specialistGateExtension as default,
283
+ entryArgs,
284
+ isProtectedPath,
285
+ requestApproval
286
+ };
@@ -0,0 +1,364 @@
1
+ import { createRequire as __astroCreateRequire } from "node:module";
2
+ const require = __astroCreateRequire(import.meta.url);
3
+
4
+ // extensions/guard/config.ts
5
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
6
+ import { homedir } from "node:os";
7
+ import { dirname, join } from "node:path";
8
+
9
+ // extensions/guard/defaults.ts
10
+ var DEFAULT_RULES = {
11
+ operations: [
12
+ { pattern: "rm -rf /", action: "block" },
13
+ { pattern: ":(){ :|:&", action: "block" },
14
+ // fork bomb fragment
15
+ { pattern: "mkfs", action: "block" },
16
+ { pattern: "dd if=", action: "block" },
17
+ { pattern: "> /dev/sd", action: "block" },
18
+ { pattern: "> /dev/null", action: "allow" },
19
+ { pattern: "> /dev/", action: "block" },
20
+ { pattern: "rm -rf", action: "prompt" },
21
+ { pattern: "sudo", action: "prompt" },
22
+ { pattern: "chmod -R 777", action: "prompt" }
23
+ ],
24
+ writes: [
25
+ { pattern: "**/.env", action: "block" },
26
+ { pattern: "**/.env.*", action: "block" },
27
+ { pattern: "~/.ssh/**", action: "block" },
28
+ { pattern: "~/.aws/**", action: "block" },
29
+ { pattern: "~/.gnupg/**", action: "block" },
30
+ { pattern: "/etc/**", action: "prompt" },
31
+ { pattern: "~/.bash_history", action: "prompt" },
32
+ { pattern: "~/.zsh_history", action: "prompt" }
33
+ ],
34
+ reads: [
35
+ { pattern: "~/.ssh/**", action: "block" },
36
+ { pattern: "~/.aws/credentials", action: "block" },
37
+ { pattern: "~/.aws/**", action: "prompt" },
38
+ { pattern: "~/.gnupg/**", action: "block" },
39
+ { pattern: "**/.env", action: "prompt" },
40
+ { pattern: "**/.env.*", action: "prompt" },
41
+ { pattern: "~/.pi/agent/auth.json", action: "block" },
42
+ { pattern: "~/.config/astro-discord/token", action: "block" }
43
+ ]
44
+ };
45
+
46
+ // extensions/guard/config.ts
47
+ function configPath() {
48
+ const dir = process.env.PI_CODING_AGENT_DIR ?? join(homedir(), ".pi", "agent");
49
+ return join(dir, "security-guard.json");
50
+ }
51
+ function examplePath() {
52
+ return `${configPath()}.example`;
53
+ }
54
+ var VALID_ACTIONS = ["prompt", "block", "allow"];
55
+ function validateRule(raw, errors, where) {
56
+ if (typeof raw !== "object" || raw === null) {
57
+ errors.push(`${where}: rule is not an object`);
58
+ return null;
59
+ }
60
+ const r = raw;
61
+ if (typeof r.pattern !== "string" || r.pattern.length === 0) {
62
+ errors.push(`${where}: missing or empty 'pattern' string`);
63
+ return null;
64
+ }
65
+ if (typeof r.action !== "string" || !VALID_ACTIONS.includes(r.action)) {
66
+ errors.push(`${where}: action must be one of ${VALID_ACTIONS.join(", ")}`);
67
+ return null;
68
+ }
69
+ return { pattern: r.pattern, action: r.action };
70
+ }
71
+ function validateRules(raw, errors) {
72
+ const out = { operations: [], writes: [], reads: [] };
73
+ if (typeof raw !== "object" || raw === null) {
74
+ errors.push("config root is not an object");
75
+ return out;
76
+ }
77
+ const r = raw;
78
+ for (const section of ["operations", "writes", "reads"]) {
79
+ const list = r[section];
80
+ if (list === void 0) continue;
81
+ if (!Array.isArray(list)) {
82
+ errors.push(`${section}: expected array, got ${typeof list}`);
83
+ continue;
84
+ }
85
+ for (let i = 0; i < list.length; i++) {
86
+ const rule = validateRule(list[i], errors, `${section}[${i}]`);
87
+ if (rule) out[section].push(rule);
88
+ }
89
+ }
90
+ return out;
91
+ }
92
+ function loadConfig() {
93
+ const path = configPath();
94
+ const errors = [];
95
+ if (!existsSync(path)) {
96
+ return { rules: DEFAULT_RULES, configPath: path, configExists: false, errors };
97
+ }
98
+ try {
99
+ const parsed = JSON.parse(readFileSync(path, "utf-8"));
100
+ const rules = validateRules(parsed, errors);
101
+ const merged = {
102
+ operations: rules.operations.length > 0 ? rules.operations : DEFAULT_RULES.operations,
103
+ writes: rules.writes.length > 0 ? rules.writes : DEFAULT_RULES.writes,
104
+ reads: rules.reads.length > 0 ? rules.reads : DEFAULT_RULES.reads
105
+ };
106
+ return { rules: merged, configPath: path, configExists: true, errors };
107
+ } catch (err) {
108
+ errors.push(`invalid JSON: ${err instanceof Error ? err.message : String(err)}`);
109
+ return { rules: DEFAULT_RULES, configPath: path, configExists: true, errors };
110
+ }
111
+ }
112
+ var EXAMPLE_CONTENT = `{
113
+ "_comment": "Copy this file to security-guard.json to activate. Patterns support globs: * matches one path segment, ** matches any number, ? matches one char. ~/ expands to your home directory. A rule yields only to a longer rule it matches (an allow for '> /dev/null' refines a block for '> /dev/'); otherwise the strictest matching rule wins.",
114
+ "operations": [
115
+ { "pattern": "rm -rf /", "action": "block" },
116
+ { "pattern": "mkfs", "action": "block" },
117
+ { "pattern": "dd if=", "action": "block" },
118
+ { "pattern": "> /dev/", "action": "block" },
119
+ { "pattern": "> /dev/null", "action": "allow" },
120
+ { "pattern": "rm -rf", "action": "prompt" },
121
+ { "pattern": "sudo", "action": "prompt" }
122
+ ],
123
+ "writes": [
124
+ { "pattern": "**/.env", "action": "block" },
125
+ { "pattern": "**/.env.*", "action": "block" },
126
+ { "pattern": "~/.ssh/**", "action": "block" },
127
+ { "pattern": "~/.aws/**", "action": "block" },
128
+ { "pattern": "/etc/**", "action": "prompt" }
129
+ ],
130
+ "reads": [
131
+ { "pattern": "~/.ssh/**", "action": "block" },
132
+ { "pattern": "~/.aws/credentials", "action": "block" },
133
+ { "pattern": "**/.env", "action": "prompt" }
134
+ ]
135
+ }
136
+ `;
137
+ function ensureExampleConfig() {
138
+ const path = examplePath();
139
+ if (existsSync(path)) return;
140
+ mkdirSync(dirname(path), { recursive: true });
141
+ writeFileSync(path, EXAMPLE_CONTENT, "utf-8");
142
+ }
143
+ function isDryRun() {
144
+ return process.env.PI_SECURITY_GUARD_DRY_RUN === "1";
145
+ }
146
+
147
+ // extensions/guard/rules.ts
148
+ import { homedir as homedir2 } from "node:os";
149
+ import { isAbsolute, resolve } from "node:path";
150
+ function expandHome(pattern) {
151
+ if (pattern === "~") return homedir2();
152
+ if (pattern.startsWith("~/")) return `${homedir2()}/${pattern.slice(2)}`;
153
+ return pattern;
154
+ }
155
+ function normalizePath(p, cwd) {
156
+ const expanded = expandHome(p);
157
+ return isAbsolute(expanded) ? expanded : resolve(cwd, expanded);
158
+ }
159
+ function globToRegex(glob) {
160
+ let src = "";
161
+ for (let i = 0; i < glob.length; i++) {
162
+ const c = glob[i];
163
+ if (c === "*") {
164
+ if (glob[i + 1] === "*") {
165
+ src += ".*";
166
+ i++;
167
+ } else {
168
+ src += "[^/]*";
169
+ }
170
+ } else if (c === "?") {
171
+ src += "[^/]";
172
+ } else if (c === "[") {
173
+ const end = glob.indexOf("]", i);
174
+ if (end === -1) {
175
+ src += "\\[";
176
+ } else {
177
+ src += glob.slice(i, end + 1);
178
+ i = end;
179
+ }
180
+ } else if (/[.+^${}()|\\]/.test(c)) {
181
+ src += `\\${c}`;
182
+ } else {
183
+ src += c;
184
+ }
185
+ }
186
+ return new RegExp(`^${src}$`);
187
+ }
188
+ function isGlob(pattern) {
189
+ return /[*?[]/.test(pattern);
190
+ }
191
+ function matchesPattern(text, rule, foldCase = false) {
192
+ const fold = (s) => foldCase ? s.toLowerCase() : s;
193
+ const expanded = fold(expandHome(rule.pattern));
194
+ const subject = fold(text);
195
+ if (isGlob(rule.pattern)) {
196
+ const re = globToRegex(expanded);
197
+ return re.test(subject);
198
+ }
199
+ return subject.includes(expanded) || subject.includes(fold(rule.pattern));
200
+ }
201
+ var STRICTNESS = { allow: 0, prompt: 1, block: 2 };
202
+ function refines(narrow, broad, foldCase) {
203
+ return narrow.pattern.length > broad.pattern.length && matchesPattern(expandHome(narrow.pattern), broad, foldCase);
204
+ }
205
+ function findMatchingRule(text, rules, foldCase = process.platform === "darwin") {
206
+ const matching = rules.filter((rule) => matchesPattern(text, rule, foldCase));
207
+ const standing = matching.filter((rule) => !matching.some((other) => refines(other, rule, foldCase)));
208
+ let best = null;
209
+ for (const rule of standing) {
210
+ if (best === null || STRICTNESS[rule.action] > STRICTNESS[best.action] || STRICTNESS[rule.action] === STRICTNESS[best.action] && rule.pattern.length > best.pattern.length) {
211
+ best = rule;
212
+ }
213
+ }
214
+ return best;
215
+ }
216
+
217
+ // extensions/guard/index.ts
218
+ async function evaluate(label, target, rules, ctx) {
219
+ const rule = findMatchingRule(target, rules);
220
+ if (!rule || rule.action === "allow") return { block: false };
221
+ const dryRun = isDryRun();
222
+ const prefix = dryRun ? "[security-guard DRY-RUN] " : "";
223
+ if (rule.action === "block") {
224
+ ctx.ui.notify(
225
+ `${prefix}Blocked ${label}: matched pattern "${rule.pattern}"`,
226
+ "warning"
227
+ );
228
+ if (dryRun) return { block: false };
229
+ return {
230
+ block: true,
231
+ reason: `Blocked by security-guard: pattern "${rule.pattern}"`
232
+ };
233
+ }
234
+ if (!ctx.hasUI) {
235
+ if (dryRun) return { block: false };
236
+ return {
237
+ block: true,
238
+ reason: "security-guard: confirmation required but no UI available"
239
+ };
240
+ }
241
+ const confirmed = await ctx.ui.confirm(
242
+ `Security check: ${label}`,
243
+ `Matched pattern "${rule.pattern}"
244
+
245
+ Target: ${target}
246
+
247
+ Allow this operation?`
248
+ );
249
+ if (confirmed) return { block: false };
250
+ ctx.ui.notify(`${prefix}Denied ${label}`, "warning");
251
+ if (dryRun) return { block: false };
252
+ return { block: true, reason: "Denied by user via security-guard" };
253
+ }
254
+ function extractEditPaths(input) {
255
+ const paths = [];
256
+ if (typeof input.path === "string") paths.push(input.path);
257
+ const multi = input.multi;
258
+ if (Array.isArray(multi)) {
259
+ for (const item of multi) {
260
+ if (item && typeof item === "object" && typeof item.path === "string") {
261
+ paths.push(item.path);
262
+ }
263
+ }
264
+ }
265
+ const patch = input.patch;
266
+ if (typeof patch === "string") {
267
+ const re = /^\*\*\* (?:Add File|Update File|Delete File):\s+(.+)$/gm;
268
+ let m;
269
+ while ((m = re.exec(patch)) !== null) {
270
+ paths.push(m[1].trim());
271
+ }
272
+ }
273
+ return paths;
274
+ }
275
+ async function handleToolCall(event, ctx, rules) {
276
+ switch (event.toolName) {
277
+ case "bash": {
278
+ const command = event.input.command ?? "";
279
+ const decision = await evaluate("bash command", command, rules.operations, ctx);
280
+ if (decision.block) return { block: true, reason: decision.reason };
281
+ return void 0;
282
+ }
283
+ case "write": {
284
+ const target = normalizePath(String(event.input.path ?? ""), ctx.cwd);
285
+ const decision = await evaluate(`write to ${target}`, target, rules.writes, ctx);
286
+ if (decision.block) return { block: true, reason: decision.reason };
287
+ return void 0;
288
+ }
289
+ case "edit": {
290
+ const paths = extractEditPaths(event.input);
291
+ for (const raw of paths) {
292
+ const target = normalizePath(raw, ctx.cwd);
293
+ const decision = await evaluate(`edit of ${target}`, target, rules.writes, ctx);
294
+ if (decision.block) return { block: true, reason: decision.reason };
295
+ }
296
+ return void 0;
297
+ }
298
+ case "read": {
299
+ const target = normalizePath(String(event.input.path ?? ""), ctx.cwd);
300
+ const decision = await evaluate(`read of ${target}`, target, rules.reads, ctx);
301
+ if (decision.block) return { block: true, reason: decision.reason };
302
+ return void 0;
303
+ }
304
+ case "grep":
305
+ case "find":
306
+ case "ls": {
307
+ const target = normalizePath(String(event.input.path ?? "."), ctx.cwd);
308
+ const subject = findMatchingRule(target, rules.reads) ? target : `${target.replace(/\/$/, "")}/`;
309
+ const decision = await evaluate(`${event.toolName} in ${target}`, subject, rules.reads, ctx);
310
+ if (decision.block) return { block: true, reason: decision.reason };
311
+ return void 0;
312
+ }
313
+ default:
314
+ return void 0;
315
+ }
316
+ }
317
+ function securityGuardExtension(pi) {
318
+ ensureExampleConfig();
319
+ let loaded = loadConfig();
320
+ pi.registerCommand("security-guard", {
321
+ description: "Security guard status / reload / test. Usage: /security-guard [status|reload|test <bash|write|read> <input>]",
322
+ handler: async (args, ctx) => {
323
+ const parts = args.trim().split(/\s+/).filter(Boolean);
324
+ const sub = parts[0] ?? "status";
325
+ if (sub === "reload") {
326
+ loaded = loadConfig();
327
+ const n = loaded.rules.operations.length + loaded.rules.writes.length + loaded.rules.reads.length;
328
+ ctx.ui.notify(
329
+ `security-guard reloaded: ${n} rules${loaded.errors.length > 0 ? `; ${loaded.errors.length} errors` : ""}`,
330
+ loaded.errors.length > 0 ? "warning" : "info"
331
+ );
332
+ return;
333
+ }
334
+ if (sub === "test") {
335
+ const kind = parts[1];
336
+ const input = parts.slice(2).join(" ");
337
+ if (!kind || !input || !["bash", "write", "read"].includes(kind)) {
338
+ ctx.ui.notify("usage: /security-guard test <bash|write|read> <input>", "warning");
339
+ return;
340
+ }
341
+ const rules2 = kind === "bash" ? loaded.rules.operations : kind === "write" ? loaded.rules.writes : loaded.rules.reads;
342
+ const target = kind === "bash" ? input : normalizePath(input, ctx.cwd);
343
+ const rule = findMatchingRule(target, rules2);
344
+ ctx.ui.notify(
345
+ rule ? `match: pattern "${rule.pattern}" -> ${rule.action}` : `no match (would be allowed)`,
346
+ "info"
347
+ );
348
+ return;
349
+ }
350
+ const { rules, configPath: configPath2, configExists, errors } = loaded;
351
+ const lines = [
352
+ `config: ${configPath2}${configExists ? "" : " (not found; using defaults)"}`,
353
+ `operations=${rules.operations.length} writes=${rules.writes.length} reads=${rules.reads.length}`,
354
+ isDryRun() ? "dry-run: ON (PI_SECURITY_GUARD_DRY_RUN=1)" : "dry-run: off"
355
+ ];
356
+ if (errors.length > 0) lines.push(`errors: ${errors.join("; ")}`);
357
+ ctx.ui.notify(lines.join(" | "), "info");
358
+ }
359
+ });
360
+ pi.on("tool_call", async (event, ctx) => handleToolCall(event, ctx, loaded.rules));
361
+ }
362
+ export {
363
+ securityGuardExtension as default
364
+ };