ceulen 0.10.1 → 0.11.0
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/CHANGELOG.md +56 -0
- package/README.md +56 -1
- package/extensions/lib/plan-bridge.ts +18 -0
- package/extensions/lib/registry.ts +14 -0
- package/extensions/modules/a2a/index.ts +4 -2
- package/extensions/modules/attachments/configPanel.ts +91 -0
- package/extensions/modules/attachments/index.ts +274 -0
- package/extensions/modules/attachments/lib/clipboard-files.ts +80 -0
- package/extensions/modules/attachments/lib/pastes.ts +45 -0
- package/extensions/modules/attachments/lib/paths.ts +74 -0
- package/extensions/modules/attachments/lib/registry.ts +70 -0
- package/extensions/modules/attachments/lib/settings.ts +99 -0
- package/extensions/modules/attachments/lib/tray.ts +74 -0
- package/extensions/modules/attachments/test/configPanel.test.ts +122 -0
- package/extensions/modules/attachments/test/index.test.ts +870 -0
- package/extensions/modules/attachments/test/module.test.ts +53 -0
- package/extensions/modules/composer/test/module.test.ts +2 -2
- package/extensions/modules/config/index.ts +3 -0
- package/extensions/modules/config/test/renderTools.test.ts +1 -1
- package/extensions/modules/cron/configPanel.ts +103 -0
- package/extensions/modules/cron/index.ts +638 -0
- package/extensions/modules/cron/lib/jobs.ts +201 -0
- package/extensions/modules/cron/lib/schedule.ts +161 -0
- package/extensions/modules/cron/test/cwd-repro.test.ts +98 -0
- package/extensions/modules/cron/test/index.test.ts +859 -0
- package/extensions/modules/cron/test/schedule.test.ts +93 -0
- package/extensions/modules/munin/index.ts +3 -1
- package/extensions/modules/permission/index.ts +567 -0
- package/extensions/modules/permission/test/permission.test.ts +789 -0
- package/extensions/modules/plan/index.ts +5 -0
- package/extensions/modules/repair/index.ts +134 -3
- package/extensions/modules/repair/test/freshness.test.ts +169 -0
- package/extensions/modules/subagent/index.ts +38 -5
- package/extensions/modules/subagent/lib/runner.ts +348 -12
- package/extensions/modules/subagent/test/worktree.test.ts +230 -0
- package/extensions/modules/usage/index.ts +193 -71
- package/extensions/modules/usage/test/context.test.ts +160 -120
- package/extensions/modules/web/index.ts +3 -1
- package/extensions/modules/web/test/a11y.test.ts +1 -1
- package/package.json +2 -2
- package/skills/cron/SKILL.md +58 -0
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
// Hand-rolled schedule.ts: POSIX semantics the module relies on — validation,
|
|
2
|
+
// name/step/range parsing, the vixie dom/dow OR rule, leap-cycle Feb 29, and
|
|
3
|
+
// never-firing expressions. Fire times cross-checked against crontab(5) and
|
|
4
|
+
// cron-parser answers on the same inputs. Cron fires in LOCAL time — expected
|
|
5
|
+
// values are built with local-time Date constructors, so the suite passes on
|
|
6
|
+
// any machine timezone (a UTC-pinned ISO string breaks on UTC±N hosts).
|
|
7
|
+
import assert from "node:assert/strict";
|
|
8
|
+
import { describe, it } from "node:test";
|
|
9
|
+
import { nextFire, nextFires, parseSchedule, validateSchedule } from "../lib/schedule.ts";
|
|
10
|
+
|
|
11
|
+
const T = (iso: string) => new Date(iso);
|
|
12
|
+
|
|
13
|
+
describe("validateSchedule", () => {
|
|
14
|
+
it("accepts standard expressions incl. names, steps, lists, ranges", () => {
|
|
15
|
+
for (const ok of ["*/5 * * * *", "0 9 * * mon", "0 9 * * mon-fri", "10-30/5 * * * *", "0 0 1,15 * *", "0 0 29 2 *", "0 9 * * 7", "15,45 */2 * jan-mar *", "0 0 * * sun"])
|
|
16
|
+
assert.equal(validateSchedule(ok), null, ok);
|
|
17
|
+
});
|
|
18
|
+
|
|
19
|
+
it("rejects wrong arity, out-of-range values, garbage, misplaced names", () => {
|
|
20
|
+
for (const bad of ["* * *", "not a cron", "61 * * * *", "* 24 * * *", "0 0 32 * *", "0 0 * 13 *", "0 0 * * 8", "0 0 * * foo", "*/0 * * * *", "5-2 * * * *", "0 0 * * 1-foo", "0 0 jan * *", "0 0 * * mon-fri *", "15,45 */2 jan-mar * *"])
|
|
21
|
+
assert.equal(typeof validateSchedule(bad), "string", bad);
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
it("dow 7 is Sunday (folds to 0)", () => {
|
|
25
|
+
assert.deepEqual([...parseSchedule("0 0 * * 7")[4]!], [0]);
|
|
26
|
+
});
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
describe("nextFire / nextFires", () => {
|
|
30
|
+
/** Local-time constructor — cron math is local, so expectations are too. */
|
|
31
|
+
const L = (y: number, mo: number, d: number, h: number, mi: number) => new Date(y, mo - 1, d, h, mi);
|
|
32
|
+
const iso = (d: Date | null) => d?.toISOString();
|
|
33
|
+
|
|
34
|
+
it("strictly after `from`, minute granularity", () => {
|
|
35
|
+
const f = nextFires("*/15 * * * *", 2, T("2026-02-09T10:00:00Z"));
|
|
36
|
+
assert.equal(f[0]!.toISOString(), "2026-02-09T10:15:00.000Z");
|
|
37
|
+
assert.equal(f[1]!.toISOString(), "2026-02-09T10:30:00.000Z");
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
it("names, ranges, step-in-range", () => {
|
|
41
|
+
// cron is LOCAL time: the next mon-fri 09:00 strictly after `from`,
|
|
42
|
+
// computed against the LOCAL calendar so the assertion holds in every TZ
|
|
43
|
+
// (CI runners are UTC; dev machines often are not).
|
|
44
|
+
const from = T("2026-02-09T08:00:00Z");
|
|
45
|
+
const expected = (() => {
|
|
46
|
+
const d = new Date(from);
|
|
47
|
+
d.setSeconds(0, 0);
|
|
48
|
+
do {
|
|
49
|
+
d.setHours(9);
|
|
50
|
+
if (d > from && d.getDay() >= 1 && d.getDay() <= 5) return d;
|
|
51
|
+
d.setDate(d.getDate() + 1);
|
|
52
|
+
d.setHours(0);
|
|
53
|
+
} while (d.getTime() < from.getTime() + 7 * 86_400_000);
|
|
54
|
+
throw new Error("unreachable");
|
|
55
|
+
})();
|
|
56
|
+
assert.equal(iso(nextFires("0 9 * * mon-fri", 1, from)[0]!), iso(expected));
|
|
57
|
+
assert.deepEqual(
|
|
58
|
+
nextFires("10-30/5 * * * *", 4, T("2026-02-09T10:07:00Z")).map((d) => d.getMinutes()),
|
|
59
|
+
[10, 15, 20, 25],
|
|
60
|
+
);
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
it("month boundaries + leap cycle (Feb 29 → 2028, Feb 30 → never)", () => {
|
|
64
|
+
assert.equal(iso(nextFire("0 0 29 2 *", T("2026-02-10T00:00:00Z"))), iso(L(2028, 2, 29, 0, 0)));
|
|
65
|
+
assert.equal(nextFire("0 0 30 2 *", T("2026-02-10T00:00:00Z")), null);
|
|
66
|
+
assert.equal(validateSchedule("0 0 30 2 *"), null, "syntactically valid — just never fires");
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
it("vixie OR rule: dom+dow both restricted → EITHER matches", () => {
|
|
70
|
+
// 13th OR Friday: Feb 13 (Fri, both), then every Fri and every 13th.
|
|
71
|
+
const fires = nextFires("0 0 13 * fri", 6, T("2026-02-09T00:00:00Z"));
|
|
72
|
+
for (const d of fires) assert.ok(d.getDate() === 13 || d.getDay() === 5, d.toISOString());
|
|
73
|
+
assert.equal(iso(fires[0]!), iso(L(2026, 2, 13, 0, 0)), "Feb 13 2026 is a Friday — one fire");
|
|
74
|
+
// Unrestricted dow → plain AND: 1st of every month regardless of weekday.
|
|
75
|
+
const firsts = nextFires("0 0 1 * *", 2, T("2026-02-09T00:00:00Z"));
|
|
76
|
+
assert.deepEqual(firsts.map((d) => d.getDate()), [1, 1]);
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
it("dom/dow OR rule: 1st OR sundays", () => {
|
|
80
|
+
const fires = nextFires("0 0 1 * 0", 8, T("2026-02-09T00:00:00Z"));
|
|
81
|
+
for (const d of fires) assert.ok(d.getDate() === 1 || d.getDay() === 0, d.toISOString());
|
|
82
|
+
});
|
|
83
|
+
|
|
84
|
+
it("invalid expression → null / empty (callers validate first)", () => {
|
|
85
|
+
assert.equal(nextFire("garbage", T("2026-01-01T00:00:00Z")), null);
|
|
86
|
+
assert.deepEqual(nextFires("garbage", 3, T("2026-01-01T00:00:00Z")), []);
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
it("second-resolution `from` truncates, never emits a same-minute fire", () => {
|
|
90
|
+
const f = nextFire("* * * * *", T("2026-02-09T10:00:30Z"));
|
|
91
|
+
assert.equal(f!.toISOString(), "2026-02-09T10:01:00.000Z");
|
|
92
|
+
});
|
|
93
|
+
});
|
|
@@ -571,7 +571,9 @@ export default function muninExtension(pi: ExtensionAPI) {
|
|
|
571
571
|
// package.json `pi.skills` manifest — so the kill-switch gates it too:
|
|
572
572
|
// disabled module ⇒ factory never runs ⇒ no munin skill registered.
|
|
573
573
|
pi.on("resources_discover", () => ({
|
|
574
|
-
|
|
574
|
+
// skillsRoot() is already a native absolute path (fileURLToPath) — no
|
|
575
|
+
// realpath needed; a throw here would kill the whole module load.
|
|
576
|
+
skillPaths: [path.join(skillsRoot(), "munin")],
|
|
575
577
|
}));
|
|
576
578
|
|
|
577
579
|
// Per-tool kill-switch (ceulen.disabledTools): listed tools register
|
|
@@ -0,0 +1,567 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* permission — granular, persistent allow/ask/deny rules per tool.
|
|
3
|
+
*
|
|
4
|
+
* Ported from @bacnh85/pi-permission 0.2.10 (plain JS → TS; zero behavior
|
|
5
|
+
* deltas except the plan-mode deferral below). An opt-in companion to Pi's
|
|
6
|
+
* container-first philosophy: config-driven rules in the `permission` section
|
|
7
|
+
* of .pi/settings.json (trust-gated project) or the agent-dir settings.json —
|
|
8
|
+
* the first file carrying the section wins. No rules configured → the module
|
|
9
|
+
* has NO opinion (inert).
|
|
10
|
+
*
|
|
11
|
+
* Actions: "allow" (silent), "ask" (prompt via ctx.ui), "deny" (block).
|
|
12
|
+
* Patterns: `*` (zero+ chars), `?` (one char), else literal. Last match wins.
|
|
13
|
+
* external_directory is a deny-only boundary gate for path tools.
|
|
14
|
+
* Flags: --yolo / --auto auto-approve "ask" (explicit deny still enforced).
|
|
15
|
+
* Doom-loop guard: the 3rd identical consecutive call is blocked.
|
|
16
|
+
*
|
|
17
|
+
* ceulen delta: while plan mode is active the handler returns undefined (no
|
|
18
|
+
* opinion) — plan mode owns tool gating then; without this, both hooks
|
|
19
|
+
* prompt on the same call. See extensions/lib/plan-bridge.ts.
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
import { readFileSync, mkdirSync, writeFileSync, renameSync } from "node:fs";
|
|
23
|
+
import * as nodePath from "node:path";
|
|
24
|
+
import os from "node:os";
|
|
25
|
+
import type { ExtensionAPI, ExtensionContext, ToolCallEvent } from "@earendil-works/pi-coding-agent";
|
|
26
|
+
import { isPlanActive } from "../../lib/plan-bridge.ts";
|
|
27
|
+
|
|
28
|
+
/** A rule object: pattern → action. Whole-tool string rules are kept too. */
|
|
29
|
+
type RuleMap = Record<string, string>;
|
|
30
|
+
/** The `permission` settings section: tool name → rules (or whole-tool verb).
|
|
31
|
+
* `external_directory` is deny-only and always a rule object (validated at
|
|
32
|
+
* runtime by warnInvalidRules). */
|
|
33
|
+
export interface PermissionRules {
|
|
34
|
+
[tool: string]: string | RuleMap;
|
|
35
|
+
}
|
|
36
|
+
/** The narrowed external_directory entry. */
|
|
37
|
+
export type ExternalDirectoryRules = RuleMap;
|
|
38
|
+
|
|
39
|
+
const ACTIONS = new Set(["allow", "ask", "deny"]);
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Convert an OpenCode-style wildcard pattern to a RegExp.
|
|
43
|
+
* `*` → zero+ chars, `?` → exactly one char, everything else literal.
|
|
44
|
+
* Patterns match against the WHOLE subject string (anchored).
|
|
45
|
+
* Exported for unit testing.
|
|
46
|
+
*/
|
|
47
|
+
export function wildcardToRegex(pattern: string): RegExp {
|
|
48
|
+
// Escape regex specials, collapse runs of `*` (OpenCode: `*` matches zero or
|
|
49
|
+
// more of ANY char including `/`, so `**` == `*`), convert `?` to any-one.
|
|
50
|
+
let re = "";
|
|
51
|
+
let prevStar = false;
|
|
52
|
+
for (const ch of String(pattern)) {
|
|
53
|
+
if (ch === "*") {
|
|
54
|
+
if (prevStar) continue; // collapse **, ***, ... → single .*
|
|
55
|
+
re += ".*";
|
|
56
|
+
prevStar = true;
|
|
57
|
+
continue;
|
|
58
|
+
}
|
|
59
|
+
prevStar = false;
|
|
60
|
+
if (ch === "?") re += ".";
|
|
61
|
+
else if ("\\^$.|+()[]{}:".includes(ch)) re += "\\" + ch;
|
|
62
|
+
else re += ch;
|
|
63
|
+
}
|
|
64
|
+
// "s" flag: `*` must cross newlines like it crosses `/` — without it,
|
|
65
|
+
// multiline commands (heredocs, multi-line scripts) matched NO rule and
|
|
66
|
+
// bypassed every ask/deny.
|
|
67
|
+
return new RegExp("^" + re + "$", "s");
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Resolve a single rule object { pattern: action } to an action for a subject.
|
|
72
|
+
* Rules evaluated in insertion order, LAST matching rule wins (OpenCode semantics).
|
|
73
|
+
* Returns the action or null (no rule matched).
|
|
74
|
+
* If `home` is provided, `~` and `$HOME` are expanded in BOTH pattern and subject
|
|
75
|
+
* so a pattern like `~/projects/**` matches an absolute path like `/home/u/...`.
|
|
76
|
+
* Exported for unit testing.
|
|
77
|
+
*/
|
|
78
|
+
export function resolveRule(rules: RuleMap, subject: string, home?: string): string | null {
|
|
79
|
+
if (!rules || typeof rules !== "object") return null;
|
|
80
|
+
let action: string | null = null;
|
|
81
|
+
const subj = home ? expandHome(subject, home) : subject;
|
|
82
|
+
for (const [pattern, val] of Object.entries(rules)) {
|
|
83
|
+
const pat = home ? expandHome(pattern, home) : pattern;
|
|
84
|
+
if (wildcardToRegex(pat).test(subj)) action = val;
|
|
85
|
+
}
|
|
86
|
+
return action;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* Expand leading ~ or $HOME in a path pattern. An empty home returns the
|
|
91
|
+
* pattern unchanged — expanding would turn `~/x` into `/x` via join.
|
|
92
|
+
* Exported for unit testing.
|
|
93
|
+
*/
|
|
94
|
+
export function expandHome(pattern: string, home?: string): string {
|
|
95
|
+
if (!home) return pattern;
|
|
96
|
+
if (pattern === "~") return home;
|
|
97
|
+
if (pattern.startsWith("~/")) return nodePath.join(home, pattern.slice(2));
|
|
98
|
+
if (pattern.startsWith("$HOME/")) return nodePath.join(home, pattern.slice(6));
|
|
99
|
+
return pattern;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** Read one settings.json key directly from disk: cwd/.pi (when `project`) →
|
|
103
|
+
* PI_CODING_AGENT_DIR|~/.pi/agent → ~/.pi/agents, first file containing the
|
|
104
|
+
* key wins. The project scope is gated on `project`: settings.json inside an
|
|
105
|
+
* untrusted checkout must not disable the user's ask/deny guardrails. Only
|
|
106
|
+
* plain objects count; wrong shapes warn and fall through to the next scope.
|
|
107
|
+
* Exported for unit testing. */
|
|
108
|
+
export function readSettingsKey(cwd: string | undefined, key: string, { project = true } = {}): Record<string, unknown> | undefined {
|
|
109
|
+
const home = os.homedir();
|
|
110
|
+
const dirs = [
|
|
111
|
+
...(project ? [nodePath.join(cwd || process.cwd(), ".pi")] : []),
|
|
112
|
+
process.env.PI_CODING_AGENT_DIR || nodePath.join(home, ".pi", "agent"),
|
|
113
|
+
nodePath.join(home, ".pi", "agents"),
|
|
114
|
+
];
|
|
115
|
+
for (const dir of dirs) {
|
|
116
|
+
try {
|
|
117
|
+
const parsed = JSON.parse(readFileSync(nodePath.join(dir, "settings.json"), "utf8")) as Record<string, unknown>;
|
|
118
|
+
const v = parsed?.[key];
|
|
119
|
+
if (v && typeof v === "object" && !Array.isArray(v)) return v as Record<string, unknown>;
|
|
120
|
+
if (v !== undefined) {
|
|
121
|
+
// Parsed but wrong shape: warn and CONTINUE to the next settings location,
|
|
122
|
+
// so a bad project-level key can't shadow a valid global one.
|
|
123
|
+
console.warn(
|
|
124
|
+
`${key}: ${nodePath.join(dir, "settings.json")} has a non-object "${key}" value — ignoring (trying next settings location)`,
|
|
125
|
+
);
|
|
126
|
+
}
|
|
127
|
+
} catch {
|
|
128
|
+
// missing/unreadable settings.json is fine — try next location
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
return undefined;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* Normalize a tool's "subject" — the string patterns are matched against.
|
|
136
|
+
* bash → the command; read/write/edit/grep/find/ls → the raw path as the
|
|
137
|
+
* model passed it (patterns are written relative, e.g. `src/*.ts`, so we do
|
|
138
|
+
* NOT resolve to absolute here — external_directory handles absolute matching
|
|
139
|
+
* separately).
|
|
140
|
+
*/
|
|
141
|
+
function toolSubject(toolName: string, input: Record<string, unknown> | undefined): string {
|
|
142
|
+
if (toolName === "bash") return String(input?.command || "");
|
|
143
|
+
if (["grep", "find", "ls", "read", "write", "edit"].includes(toolName)) {
|
|
144
|
+
return String(input?.path || "");
|
|
145
|
+
}
|
|
146
|
+
return "";
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/**
|
|
150
|
+
* Normalized match subjects for path tools. Rules are matched against the
|
|
151
|
+
* traversal-normalized relative form AND the absolute form — never the raw
|
|
152
|
+
* string: raw matching let `src/../../x` satisfy `src/*` (`*` crosses `/`,
|
|
153
|
+
* `..` was never resolved) and let absolute `/proj/private/k` slip past a
|
|
154
|
+
* relative `private/*` deny. Falls back to the raw string if resolution
|
|
155
|
+
* throws (exotic inputs must not crash the gate).
|
|
156
|
+
*/
|
|
157
|
+
export function normalizedSubjects(
|
|
158
|
+
raw: string | undefined,
|
|
159
|
+
cwd: string | undefined,
|
|
160
|
+
home?: string,
|
|
161
|
+
ppath?: typeof nodePath.posix | typeof nodePath.win32,
|
|
162
|
+
): { rel: string; abs: string } {
|
|
163
|
+
const s = String(raw || "");
|
|
164
|
+
if (!s.trim()) return { rel: "", abs: "" }; // subject-less call stays subject-less
|
|
165
|
+
try {
|
|
166
|
+
// Drive-letter input/cwd (C:\… or C:/…) resolves under path.win32 even on
|
|
167
|
+
// a posix host — WSL-boundary rules and cross-platform configs stay sane.
|
|
168
|
+
const P = ppath || (/^[A-Za-z]:[/\\]/.test(s) || /^[A-Za-z]:[/\\]/.test(cwd || "") ? nodePath.win32 : nodePath);
|
|
169
|
+
const root = P.resolve(cwd || process.cwd());
|
|
170
|
+
const abs = P.resolve(root, expandHome(s, home));
|
|
171
|
+
const rel = P.relative(root, abs) || ".";
|
|
172
|
+
return { rel, abs };
|
|
173
|
+
} catch {
|
|
174
|
+
return { rel: s, abs: s };
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
// Per-pattern subject selection: relative patterns match the normalized
|
|
179
|
+
// relative subject, absolute/~/patterns match the absolute form (keeps a
|
|
180
|
+
// scoped allow from being overridden by its own `*` fallback matching the
|
|
181
|
+
// other subject form). Insertion order + last-match-wins preserved.
|
|
182
|
+
function resolvePathAction(toolRules: RuleMap, rel: string, abs: string, home?: string): string | null {
|
|
183
|
+
let action: string | null = null;
|
|
184
|
+
for (const [pattern, val] of Object.entries(toolRules)) {
|
|
185
|
+
const pat = home ? expandHome(pattern, home) : pattern;
|
|
186
|
+
// Absolute = posix `/…` OR win32 drive-letter `C:\…`/`C:/…` (nodePath is
|
|
187
|
+
// platform-correct in production; the drive-letter test covers rules
|
|
188
|
+
// written for a Windows cwd from any host).
|
|
189
|
+
const subject = pat.startsWith("/") || /^[A-Za-z]:[/\\]/.test(pat) ? abs : rel;
|
|
190
|
+
if (wildcardToRegex(pat).test(subject)) action = val;
|
|
191
|
+
}
|
|
192
|
+
return action;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
function resolve(p: string | undefined, cwd: string, ppath: typeof nodePath.posix | typeof nodePath.win32 = nodePath as unknown as typeof nodePath.posix): string {
|
|
196
|
+
if (!p) return "";
|
|
197
|
+
// node:path resolve normalizes `..` — the old hand-rolled join left it in
|
|
198
|
+
// place ("../x" → "/proj/../x"), so the isExternal prefix check classified
|
|
199
|
+
// traversal paths as internal and they bypassed the deny gate.
|
|
200
|
+
return ppath.resolve(cwd || ppath.sep, p);
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/**
|
|
204
|
+
* Check whether `path` falls outside `cwd` (the external-directory boundary).
|
|
205
|
+
* A path exactly equal to cwd (e.g. reading the project root itself) is NOT
|
|
206
|
+
* external — only strictly-outside paths are.
|
|
207
|
+
*
|
|
208
|
+
* Containment uses path.relative, NOT a `root + "/"` prefix check: win32
|
|
209
|
+
* pathResolve yields backslash separators, so the prefix check classified
|
|
210
|
+
* every path as external and external_directory deny blocked all path tools
|
|
211
|
+
* (upstream regression 0.2.5). Exported for unit testing; `ppath` lets tests
|
|
212
|
+
* inject `path.win32` to exercise the exact code path production Windows takes.
|
|
213
|
+
*/
|
|
214
|
+
export function isExternal(path: string | undefined, cwd: string | undefined, ppath?: typeof nodePath.posix | typeof nodePath.win32): boolean {
|
|
215
|
+
if (!path || !cwd) return false;
|
|
216
|
+
const P = ppath || (nodePath as unknown as typeof nodePath.posix);
|
|
217
|
+
const abs = resolve(path, cwd, P);
|
|
218
|
+
const root = resolve(cwd, "", P);
|
|
219
|
+
if (abs === root) return false;
|
|
220
|
+
const rel = P.relative(root, abs);
|
|
221
|
+
// Canonical containment idiom: `..env` (a legal workspace filename) also
|
|
222
|
+
// starts with ".." but is INSIDE the root — only the exact parent rel or a
|
|
223
|
+
// true `..`+separator prefix escapes it.
|
|
224
|
+
return rel === ".." || rel.startsWith(".." + P.sep) || P.isAbsolute(rel);
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
// Tools that take a path and can trigger the external_directory boundary.
|
|
228
|
+
const PATH_TOOLS = new Set(["read", "write", "edit", "grep", "find", "ls"]);
|
|
229
|
+
|
|
230
|
+
// Tools to surface in the UI when "ask" fires. Control characters are
|
|
231
|
+
// flattened and long commands/paths clipped so untrusted command text can't
|
|
232
|
+
// reshape the dialog.
|
|
233
|
+
function describe(toolName: string, input: Record<string, unknown> | undefined): string {
|
|
234
|
+
const clip = (s: unknown): string => {
|
|
235
|
+
const c = String(s).replace(/[\x00-\x1f\x7f]/g, " ").replace(/\s+/g, " ").trim();
|
|
236
|
+
return c.length > 120 ? c.slice(0, 120) + "…" : c;
|
|
237
|
+
};
|
|
238
|
+
if (toolName === "bash") return `\`bash\`: ${clip(input?.command || "")}`;
|
|
239
|
+
if (input?.path) return `\`${toolName}\`: ${clip(input.path)}`;
|
|
240
|
+
return `\`${toolName}\``;
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
// Session-scoped allowlist for "Allow for this session" promotions. Module
|
|
244
|
+
// state — settings are re-read from disk on every tool_call, so promotions
|
|
245
|
+
// cannot live on the (ephemeral) rules object.
|
|
246
|
+
const sessionAllows = new Map<string, Set<string>>(); // toolName → Set<subject>
|
|
247
|
+
|
|
248
|
+
function promoteToSessionAllow(toolName: string, subject: string): void {
|
|
249
|
+
if (!sessionAllows.has(toolName)) sessionAllows.set(toolName, new Set());
|
|
250
|
+
sessionAllows.get(toolName)!.add(subject);
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
function sessionAllowed(toolName: string, subject: string): boolean {
|
|
254
|
+
return sessionAllows.get(toolName)?.has(subject) === true;
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/**
|
|
258
|
+
* Persist an "allow" rule for this exact (tool, subject) into the settings.json
|
|
259
|
+
* that already carries the permission config (same resolution order as
|
|
260
|
+
* readSettingsKey); if none exists, create <cwd>/.pi/settings.json.
|
|
261
|
+
* Returns { file } on success or { error } on failure.
|
|
262
|
+
* Exported for unit testing (dirs overrides the search list).
|
|
263
|
+
*/
|
|
264
|
+
export function persistAllowlistRule(
|
|
265
|
+
toolName: string,
|
|
266
|
+
subject: string,
|
|
267
|
+
ctx: { cwd?: string } | undefined,
|
|
268
|
+
dirs?: string[],
|
|
269
|
+
): { file?: string; error?: string } {
|
|
270
|
+
try {
|
|
271
|
+
// A subject bearing wildcards (e.g. `git add *`) would be stored as a
|
|
272
|
+
// glob pattern far broader than what the user approved — refuse.
|
|
273
|
+
if (/[\x2a\x3f]/.test(String(subject))) {
|
|
274
|
+
return { error: `subject contains wildcard characters (* or ?): ${String(subject)} — add the rule manually` };
|
|
275
|
+
}
|
|
276
|
+
const home = os.homedir();
|
|
277
|
+
const search = dirs ?? [
|
|
278
|
+
nodePath.join(ctx?.cwd || process.cwd(), ".pi"),
|
|
279
|
+
process.env.PI_CODING_AGENT_DIR || nodePath.join(home, ".pi", "agent"),
|
|
280
|
+
nodePath.join(home, ".pi", "agents"),
|
|
281
|
+
];
|
|
282
|
+
let target = search[0]!;
|
|
283
|
+
for (const dir of search) {
|
|
284
|
+
try {
|
|
285
|
+
const existing = JSON.parse(readFileSync(nodePath.join(dir, "settings.json"), "utf8")) as Record<string, unknown>;
|
|
286
|
+
const perm = existing?.permission;
|
|
287
|
+
if (perm && typeof perm === "object" && !Array.isArray(perm)) {
|
|
288
|
+
target = dir;
|
|
289
|
+
break;
|
|
290
|
+
}
|
|
291
|
+
} catch { /* no/invalid settings.json here — keep looking */ }
|
|
292
|
+
}
|
|
293
|
+
mkdirSync(target, { recursive: true });
|
|
294
|
+
const file = nodePath.join(target, "settings.json");
|
|
295
|
+
let parsed: Record<string, unknown> = {};
|
|
296
|
+
try {
|
|
297
|
+
parsed = JSON.parse(readFileSync(file, "utf8")) as Record<string, unknown>;
|
|
298
|
+
} catch (e) {
|
|
299
|
+
if ((e as NodeJS.ErrnoException)?.code !== "ENOENT") {
|
|
300
|
+
// An existing-but-unparseable settings.json must never be overwritten.
|
|
301
|
+
return { error: `settings.json at ${file} is not valid JSON; not overwriting` };
|
|
302
|
+
}
|
|
303
|
+
parsed = {};
|
|
304
|
+
}
|
|
305
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) parsed = {};
|
|
306
|
+
const prev = parsed.permission;
|
|
307
|
+
const perm: Record<string, unknown> = prev && typeof prev === "object" && !Array.isArray(prev) ? (prev as Record<string, unknown>) : {};
|
|
308
|
+
const prevRules = perm[toolName];
|
|
309
|
+
const toolRules: RuleMap = prevRules && typeof prevRules === "object" && !Array.isArray(prevRules) ? { ...(prevRules as RuleMap) } : {};
|
|
310
|
+
if (typeof prevRules === "string") toolRules["*"] = prevRules; // whole-tool rule kept as `*` (inserted first, specific allow still wins)
|
|
311
|
+
// Re-append the subject LAST so the explicit allow wins (last-match-wins),
|
|
312
|
+
// even when the same key already existed earlier in insertion order.
|
|
313
|
+
delete toolRules[String(subject)];
|
|
314
|
+
toolRules[String(subject)] = "allow";
|
|
315
|
+
perm[toolName] = toolRules;
|
|
316
|
+
parsed.permission = perm;
|
|
317
|
+
// Atomic write: temp file + rename so a crash can't truncate settings.json.
|
|
318
|
+
const tmp = `${file}.tmp-${process.pid}`;
|
|
319
|
+
writeFileSync(tmp, JSON.stringify(parsed, null, 2) + "\n");
|
|
320
|
+
renameSync(tmp, file);
|
|
321
|
+
return { file };
|
|
322
|
+
} catch (e) {
|
|
323
|
+
return { error: String((e as Error)?.message || e) };
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
/**
|
|
328
|
+
* One-time-per-session warning for permission rules that parse but can never
|
|
329
|
+
* match: a string-valued `external_directory` (resolveRule only handles rule
|
|
330
|
+
* objects) or an unknown action verb (treated as no-opinion — the rule
|
|
331
|
+
* silently no-ops). Best-effort via ctx.ui.notify; fires at most once.
|
|
332
|
+
*/
|
|
333
|
+
let warnedInvalidRules = false;
|
|
334
|
+
export function resetInvalidRulesWarning(): void {
|
|
335
|
+
warnedInvalidRules = false;
|
|
336
|
+
}
|
|
337
|
+
function warnInvalidRules(rules: PermissionRules, ctx: ExtensionContext | undefined): void {
|
|
338
|
+
if (warnedInvalidRules) return;
|
|
339
|
+
const problems: string[] = [];
|
|
340
|
+
if (typeof rules.external_directory === "string") {
|
|
341
|
+
problems.push('external_directory must be a rule object ({"pattern":"action"}), not a string');
|
|
342
|
+
}
|
|
343
|
+
for (const [tool, r] of Object.entries(rules)) {
|
|
344
|
+
const vals: string[] =
|
|
345
|
+
r && typeof r === "object" && !Array.isArray(r)
|
|
346
|
+
? (tool === "external_directory" ? [] : (Object.values(r) as string[]))
|
|
347
|
+
: [r as string];
|
|
348
|
+
for (const v of vals) {
|
|
349
|
+
if (!ACTIONS.has(v)) {
|
|
350
|
+
problems.push(`unknown action ${JSON.stringify(v)} in "${tool}" rules`);
|
|
351
|
+
break;
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
if (problems.length === 0) return;
|
|
356
|
+
warnedInvalidRules = true;
|
|
357
|
+
try {
|
|
358
|
+
ctx?.ui?.notify(`Invalid permission rules ignored: ${problems.join("; ")}`, "warning");
|
|
359
|
+
} catch { /* best-effort */ }
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
interface ResolvedCall {
|
|
363
|
+
block: true;
|
|
364
|
+
reason: string;
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
/** Test seam: lets a test drive the win32 code paths (drive-letter subjects,
|
|
368
|
+
* backslash containment) on a posix host — production passes nothing and
|
|
369
|
+
* node:path picks the platform module. */
|
|
370
|
+
interface PathCtx {
|
|
371
|
+
home?: string;
|
|
372
|
+
ppath?: typeof nodePath.posix | typeof nodePath.win32;
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
export default function permissionModule(pi: ExtensionAPI): void {
|
|
376
|
+
// yolo mode auto-approves "ask" without prompting; explicit deny still holds.
|
|
377
|
+
pi.registerFlag("yolo", {
|
|
378
|
+
description: "Auto-approve all permission prompts (deny rules still enforced)",
|
|
379
|
+
type: "boolean",
|
|
380
|
+
});
|
|
381
|
+
pi.registerFlag("auto", {
|
|
382
|
+
description: "Alias for --yolo (auto-approve permission prompts)",
|
|
383
|
+
type: "boolean",
|
|
384
|
+
});
|
|
385
|
+
|
|
386
|
+
// CLI flags are immutable after parse; capture once at load so event
|
|
387
|
+
// handlers never touch the captured pi API (stale after session
|
|
388
|
+
// replacement/reload — getFlag throws there).
|
|
389
|
+
let yolo = false;
|
|
390
|
+
let auto = false;
|
|
391
|
+
try {
|
|
392
|
+
yolo = Boolean(pi.getFlag("yolo"));
|
|
393
|
+
auto = Boolean(pi.getFlag("auto"));
|
|
394
|
+
} catch {
|
|
395
|
+
yolo = false;
|
|
396
|
+
auto = false;
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
// doom-loop state: ring of recent (tool, inputKey) signatures
|
|
400
|
+
const recent: string[] = [];
|
|
401
|
+
const DOOM_THRESHOLD = 3;
|
|
402
|
+
|
|
403
|
+
// Rule resolution for a tool call: undefined = allow, { block, reason } =
|
|
404
|
+
// deny. Doom-loop counting lives in the handler wrapper below.
|
|
405
|
+
async function resolveCall(rules: PermissionRules, event: ToolCallEvent, ctx: ExtensionContext): Promise<ResolvedCall | undefined> {
|
|
406
|
+
const { toolName, input } = event;
|
|
407
|
+
const home = (ctx as { home?: string }).home || process.env.HOME || "";
|
|
408
|
+
const inp = input as Record<string, unknown> | undefined;
|
|
409
|
+
|
|
410
|
+
// ── Rule resolution ────────────────────────────────────────────────
|
|
411
|
+
// external_directory is a deny-only boundary gate: a path outside cwd is
|
|
412
|
+
// blocked only if the matched external rule is "deny". Allow/null lets the
|
|
413
|
+
// path through to normal tool rules (OpenCode semantics: a directory allowed
|
|
414
|
+
// here inherits workspace defaults, it is not blanket-trusted).
|
|
415
|
+
if (PATH_TOOLS.has(toolName) && rules.external_directory && typeof rules.external_directory === "object") {
|
|
416
|
+
// Expand ~ BEFORE the boundary check: on the raw path, `~/ext/file`
|
|
417
|
+
// resolves relative to cwd (e.g. /proj/~/ext/file) → classified internal
|
|
418
|
+
// → the deny gate never fired, while the path tool expands ~ to an
|
|
419
|
+
// external file. resolveRule already expanded; the gate must too.
|
|
420
|
+
// Empty home → expandHome is identity → behavior unchanged.
|
|
421
|
+
const subj = expandHome(String(inp?.path || ""), home);
|
|
422
|
+
if (isExternal(subj, ctx.cwd, (ctx as PathCtx).ppath) && resolveRule(rules.external_directory, subj, home) === "deny") {
|
|
423
|
+
return { block: true, reason: "denied by permission rule (external_directory)" };
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
let action: string | null = null;
|
|
428
|
+
let matchedRule = "(default)";
|
|
429
|
+
|
|
430
|
+
// 1. tool-specific rules (expand ~ for path patterns so rules can reference $HOME)
|
|
431
|
+
if (rules[toolName] !== undefined) {
|
|
432
|
+
const toolRules = rules[toolName];
|
|
433
|
+
if (typeof toolRules === "string") {
|
|
434
|
+
action = toolRules;
|
|
435
|
+
matchedRule = toolName + " (whole)";
|
|
436
|
+
} else {
|
|
437
|
+
if (PATH_TOOLS.has(toolName)) {
|
|
438
|
+
const { rel, abs } = normalizedSubjects(String(inp?.path || ""), ctx.cwd, home, (ctx as PathCtx).ppath);
|
|
439
|
+
action = resolvePathAction(toolRules, rel, abs, home);
|
|
440
|
+
} else {
|
|
441
|
+
action = resolveRule(toolRules, toolSubject(toolName, inp), home);
|
|
442
|
+
}
|
|
443
|
+
matchedRule = toolName;
|
|
444
|
+
}
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
// 2. global "*" default
|
|
448
|
+
if (action === null && rules["*"] !== undefined) {
|
|
449
|
+
action = String(rules["*"]);
|
|
450
|
+
matchedRule = "*";
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
// Validate action is a known verb; unknown values (e.g. an object placed at
|
|
454
|
+
// "*") are treated as no-opinion so a misconfig can't accidentally block.
|
|
455
|
+
if (action !== null && !ACTIONS.has(action)) {
|
|
456
|
+
action = null;
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
// No rule matched → allow (no opinion).
|
|
460
|
+
if (action === null || action === "allow") return undefined;
|
|
461
|
+
if (action === "deny") {
|
|
462
|
+
return { block: true, reason: `denied by permission rule (${matchedRule})` };
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
// Session promotions key on the NORMALIZED RELATIVE subject for path
|
|
466
|
+
// tools (what "Add to permanent allowlist" wrote for a relative rule) —
|
|
467
|
+
// win32 cwd tests drive path.win32 via the ctx shim.
|
|
468
|
+
const sessionSubject = PATH_TOOLS.has(toolName)
|
|
469
|
+
? normalizedSubjects(String(inp?.path || ""), ctx.cwd, home, (ctx as PathCtx).ppath).rel
|
|
470
|
+
: toolSubject(toolName, inp);
|
|
471
|
+
if (sessionAllowed(toolName, sessionSubject)) return undefined;
|
|
472
|
+
|
|
473
|
+
// ── "ask" ───────────────────────────────────────────────────────
|
|
474
|
+
if (yolo || auto) return undefined; // auto-approve (--yolo or --auto)
|
|
475
|
+
|
|
476
|
+
if (!ctx.hasUI) {
|
|
477
|
+
// Non-interactive: can't ask → block by default (fail closed).
|
|
478
|
+
return { block: true, reason: `requires approval (no UI): ${matchedRule}` };
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
try {
|
|
482
|
+
const subject = sessionSubject;
|
|
483
|
+
// Subject-less tools (no command/path to key on) get no remember options.
|
|
484
|
+
const options = subject
|
|
485
|
+
? ["Allow once", "Allow for this session", "Add to permanent allowlist", "Deny"]
|
|
486
|
+
: ["Allow once", "Deny"];
|
|
487
|
+
const choice = await ctx.ui.select(
|
|
488
|
+
`Permission required (${matchedRule}):\n\n ${describe(toolName, inp)}`,
|
|
489
|
+
options,
|
|
490
|
+
);
|
|
491
|
+
if (choice === "Allow for this session") {
|
|
492
|
+
promoteToSessionAllow(toolName, subject);
|
|
493
|
+
return undefined;
|
|
494
|
+
}
|
|
495
|
+
if (choice === "Add to permanent allowlist") {
|
|
496
|
+
// Trust gate mirrors the read path: in an untrusted project the rule
|
|
497
|
+
// must land in global scope — writing cwd/.pi/settings.json would be
|
|
498
|
+
// a silent no-op (that file is not read there) and modifies a
|
|
499
|
+
// repo-controlled file.
|
|
500
|
+
const trusted = ctx?.isProjectTrusted?.() === true;
|
|
501
|
+
const written = trusted
|
|
502
|
+
? persistAllowlistRule(toolName, subject, ctx)
|
|
503
|
+
: persistAllowlistRule(toolName, subject, ctx, [
|
|
504
|
+
process.env.PI_CODING_AGENT_DIR || nodePath.join(os.homedir(), ".pi", "agent"),
|
|
505
|
+
nodePath.join(os.homedir(), ".pi", "agents"),
|
|
506
|
+
]);
|
|
507
|
+
if (written.error) {
|
|
508
|
+
return { block: true, reason: `could not persist allowlist rule: ${written.error}` };
|
|
509
|
+
}
|
|
510
|
+
promoteToSessionAllow(toolName, subject); // cover the rest of this session too
|
|
511
|
+
try {
|
|
512
|
+
ctx.ui.notify(`Permission rule added to ${written.file}: ${describe(toolName, inp)} → allow`, "info");
|
|
513
|
+
} catch { /* best-effort */ }
|
|
514
|
+
return undefined;
|
|
515
|
+
}
|
|
516
|
+
if (choice !== "Allow once") {
|
|
517
|
+
// "Deny" or dismissed dialog (Esc) — fail closed.
|
|
518
|
+
return { block: true, reason: `denied by user (${matchedRule})` };
|
|
519
|
+
}
|
|
520
|
+
return undefined; // Allow once
|
|
521
|
+
} catch {
|
|
522
|
+
return { block: true, reason: `approval prompt failed (${matchedRule})` };
|
|
523
|
+
}
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
pi.on("tool_call", async (event, ctx) => {
|
|
527
|
+
// Plan mode owns tool gating while it is active (its confirm tiers cover
|
|
528
|
+
// the same calls) — a second prompt would be double prompting.
|
|
529
|
+
if (isPlanActive()) return undefined;
|
|
530
|
+
|
|
531
|
+
// Settings.json first (production), then the legacy getSetting stub (tests).
|
|
532
|
+
// Project scope is trust-gated: settings.json in an untrusted checkout must
|
|
533
|
+
// not shadow the user's global rules.
|
|
534
|
+
const rules =
|
|
535
|
+
(readSettingsKey(ctx?.cwd, "permission", {
|
|
536
|
+
project: ctx?.isProjectTrusted?.() === true,
|
|
537
|
+
}) as PermissionRules | undefined) ??
|
|
538
|
+
((pi as unknown as { getSetting?: (k: string) => PermissionRules | undefined }).getSetting?.("permission") ?? undefined);
|
|
539
|
+
if (!rules) return undefined; // not configured → no opinion
|
|
540
|
+
warnInvalidRules(rules, ctx);
|
|
541
|
+
|
|
542
|
+
// ── Doom-loop guard ────────────────────────────────────────────────
|
|
543
|
+
// Block the Nth identical consecutive call. Cheap insurance vs model loops.
|
|
544
|
+
// Only allowed/ask outcomes count toward the ring: repeated DENIED calls
|
|
545
|
+
// must keep reporting the real deny reason, not a doom-loop mask.
|
|
546
|
+
const { toolName } = event;
|
|
547
|
+
const sig = JSON.stringify({ toolName, input: event.input });
|
|
548
|
+
const lastN = recent.slice(-(DOOM_THRESHOLD - 1));
|
|
549
|
+
if (lastN.length === DOOM_THRESHOLD - 1 && lastN.every((s) => s === sig)) {
|
|
550
|
+
try {
|
|
551
|
+
ctx.ui.notify(`Doom-loop blocked: \`${toolName}\` repeated ${DOOM_THRESHOLD}×`, "warning");
|
|
552
|
+
} catch { /* best-effort */ }
|
|
553
|
+
return { block: true, reason: `doom-loop: ${toolName} repeated ${DOOM_THRESHOLD} times` };
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
const result = await resolveCall(rules, event, ctx);
|
|
557
|
+
if (!result?.block) {
|
|
558
|
+
recent.push(sig);
|
|
559
|
+
if (recent.length > DOOM_THRESHOLD) recent.shift();
|
|
560
|
+
}
|
|
561
|
+
return result;
|
|
562
|
+
});
|
|
563
|
+
|
|
564
|
+
// Reset doom-loop + session-allow memory on new session so a prior session's
|
|
565
|
+
// calls don't poison the new one when pi reuses the extension process.
|
|
566
|
+
pi.on("session_start", () => { recent.length = 0; sessionAllows.clear(); resetInvalidRulesWarning(); });
|
|
567
|
+
}
|