pi-keeper 0.1.0 → 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/CHANGELOG.md +78 -0
- package/extensions/ask-mailbox.ts +22 -4
- package/extensions/ask-server.ts +15 -6
- package/extensions/child-cwd.ts +4 -2
- package/extensions/config.ts +24 -12
- package/extensions/index.ts +254 -68
- package/extensions/modes.ts +59 -7
- package/extensions/options.ts +9 -0
- package/extensions/preview.ts +5 -3
- package/extensions/project-rules.ts +81 -12
- package/extensions/remote-relay.ts +10 -5
- package/extensions/rulebook.ts +61 -1
- package/extensions/rules-view.ts +35 -16
- package/extensions/rules.ts +189 -22
- package/extensions/session-grant-store.ts +18 -0
- package/extensions/session-grants.ts +9 -3
- package/extensions/settings-panel.ts +80 -22
- package/extensions/telemetry.ts +99 -2
- package/extensions/ui-relay.ts +6 -1
- package/extensions/utils.ts +1108 -105
- package/package.json +5 -2
- package/prompt-templates/new-rule.md +30 -0
package/extensions/modes.ts
CHANGED
|
@@ -766,10 +766,19 @@ export const SAFE_ENV_VARS = new Set(["LANG", "LANGUAGE", "NO_COLOR", "TERM", "F
|
|
|
766
766
|
export const SAFE_ENV_PREFIXES = ["LC_"];
|
|
767
767
|
|
|
768
768
|
/** Wrappers stripped before matching (they run their argument). */
|
|
769
|
-
export const WRAPPERS = new Set(["timeout", "time", "nice", "nohup", "stdbuf", "command", "builtin", "noglob", "xargs"]);
|
|
769
|
+
export const WRAPPERS = new Set(["!", "timeout", "time", "nice", "nohup", "stdbuf", "command", "builtin", "noglob", "xargs"]);
|
|
770
770
|
|
|
771
771
|
/** Shells whose `-c <script>` argument is analyzed recursively. */
|
|
772
|
-
export const SHELLS = new Set(["sh", "bash", "zsh", "dash", "ksh", "fish"]);
|
|
772
|
+
export const SHELLS = new Set(["sh", "bash", "zsh", "dash", "ksh", "fish", "ash", "csh", "tcsh", "mksh", "rbash", "pwsh", "nu"]);
|
|
773
|
+
|
|
774
|
+
/**
|
|
775
|
+
* Shell reserved words. Never a rememberable root, and a unit whose first word is one is
|
|
776
|
+
* never covered by a remembered prefix: `do python3 x.py` is not `do`.
|
|
777
|
+
*/
|
|
778
|
+
// `time` and `!` are not here: they are WRAPPERS, stripped before a rule is matched (`time npm test` is `npm test`)
|
|
779
|
+
export const SHELL_RESERVED_WORDS = new Set(["{", "}", "[[", "]]", "case", "coproc", "do", "done", "elif", "else", "esac", "fi", "for", "function", "if", "in", "select", "then", "until", "while"]);
|
|
780
|
+
/** Words a remembered or project rule may never start with: the reserved words plus the `!` and `time` wrappers. */
|
|
781
|
+
export const NEVER_RULE_ROOTS = new Set([...SHELL_RESERVED_WORDS, "!", "time"]);
|
|
773
782
|
|
|
774
783
|
/**
|
|
775
784
|
* Commands that run arbitrary code: "Yes, and always allow" is never offered for
|
|
@@ -823,6 +832,25 @@ export const INTERPRETERS = new Set([
|
|
|
823
832
|
"ssh",
|
|
824
833
|
"watch",
|
|
825
834
|
"parallel",
|
|
835
|
+
// other language runtimes, REPLs, database and terminal multiplexers
|
|
836
|
+
"tsx",
|
|
837
|
+
"ts-node",
|
|
838
|
+
"uvx",
|
|
839
|
+
"pipx",
|
|
840
|
+
"bundle",
|
|
841
|
+
"powershell",
|
|
842
|
+
"xonsh",
|
|
843
|
+
"ipython",
|
|
844
|
+
"groovy",
|
|
845
|
+
"swift",
|
|
846
|
+
"osascript",
|
|
847
|
+
"dotnet",
|
|
848
|
+
"java",
|
|
849
|
+
"rake",
|
|
850
|
+
"sqlite3",
|
|
851
|
+
"psql",
|
|
852
|
+
"tmux",
|
|
853
|
+
"screen",
|
|
826
854
|
]);
|
|
827
855
|
|
|
828
856
|
/**
|
|
@@ -1048,10 +1076,28 @@ export const COMMAND_ARITY: Record<string, number> = {
|
|
|
1048
1076
|
};
|
|
1049
1077
|
|
|
1050
1078
|
/** Privilege escalation — denied in every mode. */
|
|
1051
|
-
export const PRIVILEGE_COMMANDS = new Set(["sudo", "sudoedit", "su", "doas", "pkexec", "run0"]);
|
|
1079
|
+
export const PRIVILEGE_COMMANDS = new Set(["sudo", "sudoedit", "su", "runuser", "doas", "pkexec", "run0"]);
|
|
1052
1080
|
|
|
1053
1081
|
/** Commands that execute another command given in their args. */
|
|
1054
|
-
export const COMMAND_RUNNERS = new Set(["xargs", "find", "fd", "parallel", "watch", "setsid", "nohup", "exec", "eval", "script", "flock", "chroot", "unbuffer", "env", "nice", "timeout", "stdbuf", "time", "command"]);
|
|
1082
|
+
export const COMMAND_RUNNERS = new Set(["xargs", "find", "fd", "parallel", "watch", "setsid", "nohup", "exec", "eval", "script", "flock", "chroot", "unbuffer", "env", "nice", "timeout", "stdbuf", "time", "command", "ionice", "chronic", "taskset", "chrt", "strace", "unshare", "nsenter", "systemd-run"]);
|
|
1083
|
+
|
|
1084
|
+
/**
|
|
1085
|
+
* Runners and launchers whose options take a separate value (`ionice -c 2 cmd`,
|
|
1086
|
+
* `ssh -p 22 host cmd`, `busybox sh -c …`): the value words are skipped, and the
|
|
1087
|
+
* command starts at any other word. A runner that takes no value option has `[]`.
|
|
1088
|
+
*/
|
|
1089
|
+
export const RUNNER_VALUE_OPTIONS: Record<string, string[]> = {
|
|
1090
|
+
ionice: ["-c", "-n", "-p", "-P", "-u", "--class", "--classdata", "--pid", "--pgid", "--uid"],
|
|
1091
|
+
taskset: ["-c", "--cpu-list"],
|
|
1092
|
+
chrt: ["-T", "-P", "-D", "--sched-runtime", "--sched-period", "--sched-deadline"],
|
|
1093
|
+
strace: ["-a", "-b", "-e", "-E", "-I", "-o", "-O", "-p", "-P", "-s", "-S", "-u", "-X"],
|
|
1094
|
+
unshare: ["-R", "--root", "-w", "--wd", "-S", "--setuid", "-G", "--setgid", "--map-user", "--map-group"],
|
|
1095
|
+
nsenter: ["-t", "--target", "-S", "--setuid", "-G", "--setgid", "-w", "--wd"],
|
|
1096
|
+
"systemd-run": ["--unit", "-p", "--property", "--uid", "--gid", "--description", "--slice", "--working-directory", "--service-type", "--on-calendar", "--on-active", "--on-boot", "--timer-property"],
|
|
1097
|
+
ssh: ["-b", "-c", "-D", "-E", "-e", "-F", "-I", "-i", "-J", "-L", "-l", "-m", "-O", "-o", "-p", "-Q", "-R", "-S", "-W", "-w"],
|
|
1098
|
+
chronic: [],
|
|
1099
|
+
busybox: [],
|
|
1100
|
+
};
|
|
1055
1101
|
|
|
1056
1102
|
/** Flags that disarm a safety guard; dangerous on any command. */
|
|
1057
1103
|
export const SAFETY_OFF_FLAGS = new Set(["--no-verify", "--insecure", "--dangerously-skip-permissions", "--yolo", "--no-sandbox"]);
|
|
@@ -1104,14 +1150,20 @@ export const DANGEROUS_COMMANDS: Record<string, (args: string[]) => boolean> = {
|
|
|
1104
1150
|
/** Roots matched by prefix (mkfs, mkfs.ext4, ...). */
|
|
1105
1151
|
export const DANGEROUS_ROOT_PREFIXES = ["mkfs"];
|
|
1106
1152
|
|
|
1153
|
+
/**
|
|
1154
|
+
* Wrappers a download-and-run pipe may start with, each with its options or
|
|
1155
|
+
* NAME=value words (`env -i`, `nice -n 5`, `timeout 5`, `busybox`), then an optional path.
|
|
1156
|
+
*/
|
|
1157
|
+
const RUN_WRAPPERS = String.raw`(?:(?:\S*\/)?(?:env|exec|command|nice|nohup|setsid|stdbuf|ionice|chronic|busybox|time|timeout\s+\S+|xargs)(?:\s+(?:-\S+|[A-Za-z_]\w*=\S*|\d+))*\s+)*`;
|
|
1158
|
+
|
|
1107
1159
|
/**
|
|
1108
1160
|
* Raw-string patterns for forms the unit analysis can't see (download and
|
|
1109
1161
|
* run, substitution as an rm target).
|
|
1110
1162
|
*/
|
|
1111
1163
|
export const DANGEROUS_RAW_PATTERNS: RegExp[] = [
|
|
1112
|
-
// curl/wget piped into a shell or interpreter
|
|
1113
|
-
|
|
1114
|
-
|
|
1164
|
+
// curl/wget piped into a shell or interpreter, through wrappers with their options and assignments (`env -i`, `nice -n 5`) and a path
|
|
1165
|
+
new RegExp(String.raw`\b(curl|wget)\b[^;&\n]*\|\s*(sudo\s+)?${RUN_WRAPPERS}(?:\S*\/)?(?:ba|z|da|k|a)?sh\b`),
|
|
1166
|
+
new RegExp(String.raw`\b(curl|wget)\b[^;&\n]*\|\s*(sudo\s+)?${RUN_WRAPPERS}(?:\S*\/)?(python3?(\.\d+)?|perl|ruby|node|php|deno|bun)\b`),
|
|
1115
1167
|
// bash <(curl ...) / sh -c "$(curl ...)"
|
|
1116
1168
|
/<\(\s*(curl|wget)\b/,
|
|
1117
1169
|
/\$\(\s*(curl|wget)\b/,
|
package/extensions/options.ts
CHANGED
|
@@ -29,6 +29,12 @@ export function projectReadGrantLabel(dirs: readonly string[]): string {
|
|
|
29
29
|
export function fetchGrantLabel(hosts: readonly string[]): string {
|
|
30
30
|
return `Yes, and allow fetching from ${hosts.map((h) => sanitizeForTerminal(h)).join(", ")} this session`;
|
|
31
31
|
}
|
|
32
|
+
/** "Yes, and allow git in <repo>/ this session": a cd into another git repository, for the repo roots it runs git in (see gitGrantRoots). */
|
|
33
|
+
export function gitGrantLabel(roots: readonly string[]): string {
|
|
34
|
+
const shown = roots.slice(0, 2).map((d) => sanitizeForTerminal(d.endsWith("/") ? d : `${d}/`));
|
|
35
|
+
const more = roots.length > 2 ? ` (+${roots.length - 2} more)` : "";
|
|
36
|
+
return `Yes, and allow git in ${shown.join(", ")}${more} this session`;
|
|
37
|
+
}
|
|
32
38
|
/** "Yes, and always allow fetching from <host> in this project": saved as Fetch(<host>). */
|
|
33
39
|
export function projectFetchGrantLabel(hosts: readonly string[]): string {
|
|
34
40
|
return `Yes, and always allow fetching from ${hosts.map((h) => sanitizeForTerminal(h)).join(", ")} in this project`;
|
|
@@ -65,6 +71,8 @@ export interface DialogOptionsInput {
|
|
|
65
71
|
fetchGrantLabel?: string;
|
|
66
72
|
/** "Yes, and always allow fetching from <host> in this project" label; undefined unless project options are on. */
|
|
67
73
|
projectFetchGrantLabel?: string;
|
|
74
|
+
/** "Yes, and allow git in <repo>/ this session" label; undefined when no repo grant would remove the ask. */
|
|
75
|
+
gitGrantLabel?: string;
|
|
68
76
|
/** The ask comes from a subagent child: no switching to auto mode (children can't switch). */
|
|
69
77
|
child?: boolean; /** Offer REJECT_WITH_FEEDBACK (default true). False when the answer cannot carry text back, as for a background child. */
|
|
70
78
|
feedback?: boolean;
|
|
@@ -94,6 +102,7 @@ export function dialogOptions(input: DialogOptionsInput): DialogOptions {
|
|
|
94
102
|
if (input.projectReadGrantLabel !== undefined) primary.push(input.projectReadGrantLabel);
|
|
95
103
|
if (input.fetchGrantLabel !== undefined) primary.push(input.fetchGrantLabel);
|
|
96
104
|
if (input.projectFetchGrantLabel !== undefined) primary.push(input.projectFetchGrantLabel);
|
|
105
|
+
if (input.gitGrantLabel !== undefined) primary.push(input.gitGrantLabel);
|
|
97
106
|
if (canAllowEdits) primary.push(input.sharedEdits === true ? ALLOW_EDITS_SHARED : ALLOW_EDITS);
|
|
98
107
|
primary.push(REJECT);
|
|
99
108
|
|
package/extensions/preview.ts
CHANGED
|
@@ -71,11 +71,13 @@ async function rawPreviewFor(call: ToolCall, cwd: string): Promise<Preview | und
|
|
|
71
71
|
* Make model-controlled text safe to print inside the dialog: C0/C1
|
|
72
72
|
* control characters (ESC, CR, backspace, ...) become visible symbols, so
|
|
73
73
|
* escape sequences can't move the cursor, erase lines or draw fake
|
|
74
|
-
* options; bidi overrides (Trojan Source)
|
|
75
|
-
*
|
|
74
|
+
* options; bidi overrides (Trojan Source) and invisible format characters
|
|
75
|
+
* (zero-width space and joiners, line/paragraph separators, word joiner,
|
|
76
|
+
* BOM) become U+FFFD, so they show as a marker instead of hiding text.
|
|
77
|
+
* Newlines and tabs are kept.
|
|
76
78
|
*/
|
|
77
79
|
export function sanitizeForTerminal(text: string): string {
|
|
78
|
-
return text.replace(/[\x00-\x08\x0b-\x1f\x7f-\x9f
|
|
80
|
+
return text.replace(/[\x00-\x08\x0b-\x1f\x7f-\x9f--\u200b-\u200d\u2028\u2029\u2060\ufeff]/g, (ch) => {
|
|
79
81
|
const code = ch.charCodeAt(0);
|
|
80
82
|
if (code < 0x20) return String.fromCharCode(0x2400 + code); // ␛, ␍, ...
|
|
81
83
|
if (code === 0x7f) return "␡"; // ␡
|
|
@@ -16,9 +16,9 @@
|
|
|
16
16
|
|
|
17
17
|
import { createHash, randomBytes } from "node:crypto";
|
|
18
18
|
import { existsSync, mkdirSync, readFileSync, renameSync, statSync, unlinkSync, writeFileSync, appendFileSync } from "node:fs";
|
|
19
|
-
import { dirname, isAbsolute, join, normalize, resolve } from "node:path";
|
|
19
|
+
import { basename, dirname, isAbsolute, join, normalize, resolve, sep } from "node:path";
|
|
20
20
|
import { homedir } from "node:os";
|
|
21
|
-
import { canonicalize, commandUnits, isRememberableExact, isRememberablePrefix } from "./utils.ts";
|
|
21
|
+
import { canonicalize, commandUnits, hasRemoval, isPrivilegedCommand, isRememberableExact, isRememberablePrefix } from "./utils.ts";
|
|
22
22
|
import { countWork } from "./perf.ts";
|
|
23
23
|
|
|
24
24
|
export const NAMESPACE = "pi-keeper";
|
|
@@ -51,6 +51,14 @@ export interface ParsedFetchHost {
|
|
|
51
51
|
host: string;
|
|
52
52
|
}
|
|
53
53
|
|
|
54
|
+
/** `BashExact(<command text>)` in the allow list: that whole command, character for character, runs without asking. */
|
|
55
|
+
export interface ParsedVerbatim {
|
|
56
|
+
/** The entry as written, trimmed. */
|
|
57
|
+
text: string;
|
|
58
|
+
/** The command text (trimmed), compared as verbatimKey (rules.ts). */
|
|
59
|
+
command: string;
|
|
60
|
+
}
|
|
61
|
+
|
|
54
62
|
export interface ParsedRules {
|
|
55
63
|
allow: ParsedRule[];
|
|
56
64
|
ask: ParsedRule[];
|
|
@@ -59,6 +67,8 @@ export interface ParsedRules {
|
|
|
59
67
|
readDirs: ParsedReadDir[];
|
|
60
68
|
/** Allow-list `Fetch(<host>)` entries. */
|
|
61
69
|
fetchHosts: ParsedFetchHost[];
|
|
70
|
+
/** Allow-list `BashExact(<command text>)` entries. */
|
|
71
|
+
allowVerbatim: ParsedVerbatim[];
|
|
62
72
|
/** Malformed entries and structure problems, one line each. */
|
|
63
73
|
warnings: string[];
|
|
64
74
|
}
|
|
@@ -66,7 +76,8 @@ export interface ParsedRules {
|
|
|
66
76
|
/** Rules in effect for decisions (see rules.ts). */
|
|
67
77
|
export interface ProjectPermissions {
|
|
68
78
|
/** Trusted allow rules only: prefixes plus exact commands. */
|
|
69
|
-
|
|
79
|
+
/** `verbatim`: trusted BashExact command texts (absent in hand-built permissions: read as none). */
|
|
80
|
+
allow: { prefixes: string[][]; exact: string[][]; verbatim?: string[] };
|
|
70
81
|
ask: ParsedRule[];
|
|
71
82
|
deny: ParsedRule[];
|
|
72
83
|
/** Trusted `Read(<dir>/**)` directories (outside reads that run without asking; secrets still ask). */
|
|
@@ -77,7 +88,7 @@ export interface ProjectPermissions {
|
|
|
77
88
|
broken?: string;
|
|
78
89
|
}
|
|
79
90
|
|
|
80
|
-
export const NO_PROJECT_RULES: ProjectPermissions = { allow: { prefixes: [], exact: [] }, ask: [], deny: [], readDirs: [], fetchHosts: [] };
|
|
91
|
+
export const NO_PROJECT_RULES: ProjectPermissions = { allow: { prefixes: [], exact: [], verbatim: [] }, ask: [], deny: [], readDirs: [], fetchHosts: [] };
|
|
81
92
|
|
|
82
93
|
/**
|
|
83
94
|
* Parse a `Read(<dir>/**)` entry: undefined when it isn't one, an error when
|
|
@@ -131,6 +142,27 @@ export function fetchRuleFor(host: string): string {
|
|
|
131
142
|
return `Fetch(${host})`;
|
|
132
143
|
}
|
|
133
144
|
|
|
145
|
+
/**
|
|
146
|
+
* Parse a `BashExact(<command text>)` entry: undefined when it isn't one, an
|
|
147
|
+
* error when the body is empty or holds a control character other than tab
|
|
148
|
+
* and newline. The body runs to the last `)`, so it may contain parentheses.
|
|
149
|
+
*/
|
|
150
|
+
export function parseVerbatim(entry: string): ParsedVerbatim | { error: string } | undefined {
|
|
151
|
+
const m = /^BashExact\(([\s\S]*)\)$/.exec(entry.trim());
|
|
152
|
+
if (m === null) return undefined;
|
|
153
|
+
const command = m[1].trim();
|
|
154
|
+
if (command === "") return { error: "names no command" };
|
|
155
|
+
if (/[\x00-\x08\x0b-\x1f\x7f-\x9f]/.test(command)) return { error: "contains control characters" };
|
|
156
|
+
// the same limits as an exact token rule: nothing that removes or escalates, anywhere in the text
|
|
157
|
+
if (hasRemoval(command) || isPrivilegedCommand(command)) return { error: "can't be allowed (removal or privilege command)" };
|
|
158
|
+
return { text: entry.trim(), command };
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** The allow entry for one exact command text (the text is trimmed, as verbatimKey does). */
|
|
162
|
+
export function verbatimRuleFor(command: string): string {
|
|
163
|
+
return `BashExact(${command.trim()})`;
|
|
164
|
+
}
|
|
165
|
+
|
|
134
166
|
// ---------------------------------------------------------------------------
|
|
135
167
|
// Parsing
|
|
136
168
|
// ---------------------------------------------------------------------------
|
|
@@ -139,7 +171,8 @@ export function fetchRuleFor(host: string): string {
|
|
|
139
171
|
export function parseRule(entry: string, list: RuleList): ParsedRule | { error: string } {
|
|
140
172
|
const m = /^Bash\(([\s\S]*)\)$/.exec(entry.trim());
|
|
141
173
|
if (m === null) return { error: "not of the form Bash(<command>) or Bash(<command> *)" };
|
|
142
|
-
|
|
174
|
+
// Claude Code's `Bash(rm:*)` is the same prefix rule as `Bash(rm *)`
|
|
175
|
+
let body = m[1].trim().replace(/:\*$/, " *");
|
|
143
176
|
let exact = true;
|
|
144
177
|
if (body.endsWith(" *")) {
|
|
145
178
|
exact = false;
|
|
@@ -169,7 +202,7 @@ export function parsePattern(text: string, list: RuleList): ParsedRule | { error
|
|
|
169
202
|
|
|
170
203
|
/** Parse the file's JSON. Malformed entries are skipped and reported. */
|
|
171
204
|
export function parseRules(json: unknown): ParsedRules {
|
|
172
|
-
const out: ParsedRules = { allow: [], ask: [], deny: [], readDirs: [], fetchHosts: [], warnings: [] };
|
|
205
|
+
const out: ParsedRules = { allow: [], ask: [], deny: [], readDirs: [], fetchHosts: [], allowVerbatim: [], warnings: [] };
|
|
173
206
|
const isObject = (v: unknown): v is Record<string, unknown> => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
174
207
|
if (!isObject(json)) return out;
|
|
175
208
|
const ns = json[NAMESPACE];
|
|
@@ -202,6 +235,13 @@ export function parseRules(json: unknown): ParsedRules {
|
|
|
202
235
|
else out.fetchHosts.push(fetchHost);
|
|
203
236
|
continue;
|
|
204
237
|
}
|
|
238
|
+
const verbatim = typeof entry === "string" ? parseVerbatim(entry) : undefined;
|
|
239
|
+
if (verbatim !== undefined) {
|
|
240
|
+
if (list !== "allow") out.warnings.push(`${list}: ignored \`${label}\` (BashExact(...) entries belong in allow)`);
|
|
241
|
+
else if ("error" in verbatim) out.warnings.push(`${list}: ignored \`${label}\` (${verbatim.error})`);
|
|
242
|
+
else out.allowVerbatim.push(verbatim);
|
|
243
|
+
continue;
|
|
244
|
+
}
|
|
205
245
|
const parsed = typeof entry === "string" ? parseRule(entry, list) : { error: "not a string" };
|
|
206
246
|
if ("error" in parsed) out.warnings.push(`${list}: ignored \`${label}\` (${parsed.error})`);
|
|
207
247
|
else out[list].push(parsed);
|
|
@@ -222,8 +262,10 @@ export function parseRules(json: unknown): ParsedRules {
|
|
|
222
262
|
*/
|
|
223
263
|
function unitMatches(rule: ParsedRule, unit: readonly string[]): boolean {
|
|
224
264
|
const [root, ...wanted] = rule.tokens;
|
|
225
|
-
|
|
226
|
-
|
|
265
|
+
// a bare name in the rule also matches the command named by path (`/usr/bin/make`, `./make`)
|
|
266
|
+
const named = (t: string): boolean => t === root || (!root.includes("/") && basename(t) === root);
|
|
267
|
+
if (rule.exact) return unit.length === rule.tokens.length && unit.every((t, k) => (k === 0 ? named(t) : t === rule.tokens[k]));
|
|
268
|
+
if (!named(unit[0])) return false;
|
|
227
269
|
let u = 1;
|
|
228
270
|
for (const token of wanted) {
|
|
229
271
|
while (u < unit.length && unit[u] !== token && (unit[u].startsWith("-") || unit[u - 1].startsWith("-"))) u++;
|
|
@@ -244,7 +286,7 @@ export function findMatchingRule(rules: readonly ParsedRule[], command: string):
|
|
|
244
286
|
export function compilePermissions(rules: ParsedRules, allowActive: boolean, broken?: string): ProjectPermissions {
|
|
245
287
|
const allow = allowActive ? rules.allow : [];
|
|
246
288
|
return {
|
|
247
|
-
allow: { prefixes: allow.filter((r) => !r.exact).map((r) => r.tokens), exact: allow.filter((r) => r.exact).map((r) => r.tokens) },
|
|
289
|
+
allow: { prefixes: allow.filter((r) => !r.exact).map((r) => r.tokens), exact: allow.filter((r) => r.exact).map((r) => r.tokens), verbatim: allowActive ? rules.allowVerbatim.map((r) => r.command) : [] },
|
|
248
290
|
ask: rules.ask,
|
|
249
291
|
deny: rules.deny,
|
|
250
292
|
readDirs: allowActive ? rules.readDirs.map((r) => r.dir) : [],
|
|
@@ -273,6 +315,11 @@ export function rulesPath(cwd: string): string {
|
|
|
273
315
|
return join(findProjectRoot(cwd), RULES_FILE);
|
|
274
316
|
}
|
|
275
317
|
|
|
318
|
+
/** True when `path` lies strictly inside `dir` (both resolved; a path prefix alone is not enough). */
|
|
319
|
+
export function isInsideDir(path: string, dir: string): boolean {
|
|
320
|
+
return resolve(path).startsWith(`${resolve(dir)}${sep}`);
|
|
321
|
+
}
|
|
322
|
+
|
|
276
323
|
export function sha256(text: string): string {
|
|
277
324
|
return createHash("sha256").update(text).digest("hex");
|
|
278
325
|
}
|
|
@@ -303,8 +350,30 @@ function readTrustStore(agentDir: string): Record<string, string> {
|
|
|
303
350
|
}
|
|
304
351
|
}
|
|
305
352
|
|
|
306
|
-
/**
|
|
353
|
+
/** Throws when the trust store exists but is not a JSON object: recording over it would drop every other approval. */
|
|
354
|
+
function assertTrustStoreUsable(agentDir: string): void {
|
|
355
|
+
const path = trustStorePath(agentDir);
|
|
356
|
+
let text: string;
|
|
357
|
+
try {
|
|
358
|
+
text = readFileSync(path, "utf8");
|
|
359
|
+
} catch (error) {
|
|
360
|
+
if ((error as NodeJS.ErrnoException).code === "ENOENT") return;
|
|
361
|
+
throw new Error(`${path} cannot be read; fix or delete it`);
|
|
362
|
+
}
|
|
363
|
+
// an empty file holds no approval to lose
|
|
364
|
+
if (text.trim() === "") return;
|
|
365
|
+
let data: unknown;
|
|
366
|
+
try {
|
|
367
|
+
data = JSON.parse(text);
|
|
368
|
+
} catch {
|
|
369
|
+
data = undefined;
|
|
370
|
+
}
|
|
371
|
+
if (typeof data !== "object" || data === null || Array.isArray(data)) throw new Error(`${path} is not valid JSON; fix or delete it`);
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
/** Record `hash` as reviewed for `file`. Throws (and writes nothing) when the trust store is malformed. */
|
|
307
375
|
export function recordTrust(agentDir: string, file: string, hash: string): void {
|
|
376
|
+
assertTrustStoreUsable(agentDir);
|
|
308
377
|
const store = readTrustStore(agentDir);
|
|
309
378
|
store[resolve(file)] = hash;
|
|
310
379
|
atomicWrite(trustStorePath(agentDir), `${JSON.stringify(store, null, 2)}\n`);
|
|
@@ -351,7 +420,7 @@ export interface LoadedRules {
|
|
|
351
420
|
broken?: string;
|
|
352
421
|
}
|
|
353
422
|
|
|
354
|
-
const NO_RULES: ParsedRules = { allow: [], ask: [], deny: [], readDirs: [], fetchHosts: [], warnings: [] };
|
|
423
|
+
const NO_RULES: ParsedRules = { allow: [], ask: [], deny: [], readDirs: [], fetchHosts: [], allowVerbatim: [], warnings: [] };
|
|
355
424
|
|
|
356
425
|
/** Read, parse and trust-check the project's rules file. Never throws. */
|
|
357
426
|
export function loadProjectRules(cwd: string, agentDir: string): LoadedRules {
|
|
@@ -436,7 +505,7 @@ export function saveRules(cwd: string, agentDir: string, list: RuleList, entries
|
|
|
436
505
|
const root = findProjectRoot(cwd);
|
|
437
506
|
const file = join(root, RULES_FILE);
|
|
438
507
|
for (const entry of entries) {
|
|
439
|
-
const special = list === "allow" ? (parseReadDir(entry) ?? parseFetchHost(entry)) : undefined;
|
|
508
|
+
const special = list === "allow" ? (parseReadDir(entry) ?? parseFetchHost(entry) ?? parseVerbatim(entry)) : undefined;
|
|
440
509
|
const parsed = special ?? parseRule(entry, list);
|
|
441
510
|
if ("error" in parsed) throw new Error(`${entry}: ${parsed.error}`);
|
|
442
511
|
}
|
|
@@ -21,7 +21,7 @@
|
|
|
21
21
|
*/
|
|
22
22
|
|
|
23
23
|
import { heartbeatFresh } from "./ask-heartbeat.ts";
|
|
24
|
-
import { askDirFor, cleanup,
|
|
24
|
+
import { askDirFor, cleanup, newAskId, newNonce, readReply, RequestTooLargeError, writeCancel, writeRequest, type AskRequest, type ChildMode, type ReplyDecision, type ReplyReason } from "./ask-mailbox.ts";
|
|
25
25
|
import { backgroundAsksEnabled, type KeeperConfig } from "./config.ts";
|
|
26
26
|
import { PARENT_SESSION_ENV, readParentGrants, readParentPid } from "./session-grants.ts";
|
|
27
27
|
|
|
@@ -29,7 +29,8 @@ import { PARENT_SESSION_ENV, readParentGrants, readParentPid } from "./session-g
|
|
|
29
29
|
export const REPLY_POLL_MS = 250;
|
|
30
30
|
|
|
31
31
|
/** Why an ask was denied: what the parent said, or what the child saw. */
|
|
32
|
-
|
|
32
|
+
/** "request-size": the request is too big for the parent to read, so it is denied at once. */
|
|
33
|
+
export type RelayReason = ReplyReason | "parent-gone" | "error" | "request-size";
|
|
33
34
|
|
|
34
35
|
export interface RelayResult {
|
|
35
36
|
decision: ReplyDecision;
|
|
@@ -93,9 +94,13 @@ export async function askParent(call: AskRequest["call"], options: AskParentOpti
|
|
|
93
94
|
if (aborted()) return { decision: "cancelled" };
|
|
94
95
|
const nonce = newNonce();
|
|
95
96
|
const request: AskRequest = { v: 1, id, nonce, childPid: process.pid, childLabel: sanitizeLabel(options.label, `subagent ${process.pid}`), childMode: options.childMode, cwd: options.cwd, call };
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
97
|
+
try {
|
|
98
|
+
writeRequest(dir, request);
|
|
99
|
+
} catch (error) {
|
|
100
|
+
// the parent would drop this file unread: no point waiting for an answer that cannot come
|
|
101
|
+
if (error instanceof RequestTooLargeError) return { decision: "deny", reason: "request-size" };
|
|
102
|
+
throw error;
|
|
103
|
+
}
|
|
99
104
|
const deadline = Date.now() + options.timeoutMs;
|
|
100
105
|
const pollMs = options.pollMs ?? REPLY_POLL_MS;
|
|
101
106
|
for (;;) {
|
package/extensions/rulebook.ts
CHANGED
|
@@ -21,7 +21,7 @@
|
|
|
21
21
|
* accepts one flat `key: value` per line and one condition per rule.
|
|
22
22
|
*/
|
|
23
23
|
|
|
24
|
-
import { readFileSync, readdirSync } from "node:fs";
|
|
24
|
+
import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs";
|
|
25
25
|
import { basename, join, resolve } from "node:path";
|
|
26
26
|
import { RULE_WARNING } from "./modes.ts";
|
|
27
27
|
import { findProjectRoot, sha256 } from "./project-rules.ts";
|
|
@@ -152,6 +152,9 @@ export function compileCondition(source: string): RegExp | undefined {
|
|
|
152
152
|
}
|
|
153
153
|
}
|
|
154
154
|
|
|
155
|
+
/** Text no rule should match; a condition that does fires on every answer. */
|
|
156
|
+
const NEUTRAL_TEXTS = ["", " ", "qqq vvv."];
|
|
157
|
+
|
|
155
158
|
/**
|
|
156
159
|
* One rule file to a rule, or the reason it cannot be one. Pure: the caller
|
|
157
160
|
* decides what to do with `{ problem }` (index.ts reports it once and skips).
|
|
@@ -159,12 +162,18 @@ export function compileCondition(source: string): RegExp | undefined {
|
|
|
159
162
|
export function parseRuleFile(file: string, kind: "user" | "project", text: string): RulebookRule | RulebookProblem {
|
|
160
163
|
const name = basename(file).replace(RULE_FILE, "");
|
|
161
164
|
const { fields, body } = splitFrontmatter(text);
|
|
165
|
+
if (!text.replace(/^\uFEFF/, "").startsWith("---")) {
|
|
166
|
+
const literal = text.includes("\\n") && !text.includes("\n---");
|
|
167
|
+
return { file, problem: `no frontmatter: the file must start with a --- line, then description: and condition: lines, then ---${literal ? " (the file contains a literal \\n, not line breaks)" : ""}` };
|
|
168
|
+
}
|
|
162
169
|
const description = fields.description ?? "";
|
|
163
170
|
const condition = fields.condition ?? "";
|
|
164
171
|
if (description === "") return { file, problem: "no `description:` in the frontmatter" };
|
|
165
172
|
if (condition === "") return { file, problem: "no `condition:` in the frontmatter (the regex that makes it fire)" };
|
|
166
173
|
const pattern = compileCondition(condition);
|
|
167
174
|
if (pattern === undefined) return { file, problem: `the condition does not compile as a regex: ${condition}` };
|
|
175
|
+
// a pattern that matches text no rule is about (`(a|b)*` is optional, so it matches everywhere) would fire on every answer
|
|
176
|
+
if (NEUTRAL_TEXTS.some((sample) => pattern.test(sample))) return { file, problem: `the condition matches ordinary text, so it would fire on every answer: ${condition}` };
|
|
168
177
|
if (body === "") return { file, problem: "the body is empty, so there is no correction to send" };
|
|
169
178
|
return { name, kind, file, description, condition, pattern, body, hash: sha256(text) };
|
|
170
179
|
}
|
|
@@ -300,3 +309,54 @@ export function firedFromBranch(branch: readonly { type?: string; customType?: s
|
|
|
300
309
|
|
|
301
310
|
/** The user's rulebook directory for this agent dir (index.ts and docs/guide.md name it). */
|
|
302
311
|
export const userRuleDir = (agentDir: string): string => resolve(join(agentDir, "pi-keeper", USER_RULE_DIR));
|
|
312
|
+
|
|
313
|
+
/** The example `ensureUserRuleDir` writes into an empty rules directory. */
|
|
314
|
+
export const EXAMPLE_RULE_FILE = "example-rule.md";
|
|
315
|
+
/** The example's condition: a marker no answer contains, so the example never fires. */
|
|
316
|
+
export const EXAMPLE_RULE_CONDITION = "\\bEXAMPLE_RULE_PLACEHOLDER_NEVER_MATCHES\\b";
|
|
317
|
+
export const EXAMPLE_RULE = `---
|
|
318
|
+
description: Example only, never fires. Copy it to write your own rule.
|
|
319
|
+
condition: ${EXAMPLE_RULE_CONDITION}
|
|
320
|
+
---
|
|
321
|
+
This is a dummy rule. Its condition matches a placeholder word, so it never fires.
|
|
322
|
+
Delete it or edit it.
|
|
323
|
+
|
|
324
|
+
How to write a rule:
|
|
325
|
+
|
|
326
|
+
1. Make one .md file per rule in this folder (for all your projects), or in
|
|
327
|
+
<project>/.pi/rules/ (for one project; pi-keeper asks you to review it once).
|
|
328
|
+
2. The frontmatter has two lines:
|
|
329
|
+
description: one line on what must not happen (shown by /rules and on the card)
|
|
330
|
+
condition: a JavaScript regex matched against the end of the model's answer.
|
|
331
|
+
A leading (?i) makes it case-insensitive. For example: (?i)\\bshould work\\b
|
|
332
|
+
3. This text, below the frontmatter, is the correction the model receives when the
|
|
333
|
+
condition matches. Say what to do instead.
|
|
334
|
+
4. A rule fires once per session. Rules are re-read every turn: no restart needed.
|
|
335
|
+
|
|
336
|
+
Shortcut: type /new-rule <what must not happen> and the model writes the file for you.
|
|
337
|
+
`;
|
|
338
|
+
|
|
339
|
+
/** Written next to the example so it is offered once: deleting the example must not bring it back. Not a `.md` file, so never read as a rule. */
|
|
340
|
+
export const EXAMPLE_MARKER_FILE = ".example-seeded";
|
|
341
|
+
|
|
342
|
+
/**
|
|
343
|
+
* Create the user's rules directory and offer the example once, so the format is
|
|
344
|
+
* visible. Runs at session start and on `/rules`, so an install that is updated
|
|
345
|
+
* gets the folder and the example without doing anything. The example is written
|
|
346
|
+
* only when the folder holds no rule file and has not been offered before.
|
|
347
|
+
* Never throws (a read-only home just means no directory). Returns the directory.
|
|
348
|
+
*/
|
|
349
|
+
export function ensureUserRuleDir(agentDir: string): string {
|
|
350
|
+
const dir = userRuleDir(agentDir);
|
|
351
|
+
try {
|
|
352
|
+
mkdirSync(dir, { recursive: true });
|
|
353
|
+
const marker = join(dir, EXAMPLE_MARKER_FILE);
|
|
354
|
+
if (!existsSync(marker)) {
|
|
355
|
+
if (ruleFilesIn(dir).length === 0) writeFileSync(join(dir, EXAMPLE_RULE_FILE), EXAMPLE_RULE, { flag: "wx" });
|
|
356
|
+
writeFileSync(marker, "The example rule was offered once; delete it freely.\n", { flag: "wx" });
|
|
357
|
+
}
|
|
358
|
+
} catch {
|
|
359
|
+
// best effort: /rules still lists what it can read
|
|
360
|
+
}
|
|
361
|
+
return dir;
|
|
362
|
+
}
|
package/extensions/rules-view.ts
CHANGED
|
@@ -13,9 +13,10 @@
|
|
|
13
13
|
*/
|
|
14
14
|
|
|
15
15
|
import type { ExtensionContext, Theme } from "@earendil-works/pi-coding-agent";
|
|
16
|
-
import { Key, matchesKey, truncateToWidth, wrapTextWithAnsi, type Component } from "@earendil-works/pi-tui";
|
|
16
|
+
import { Key, matchesKey, truncateToWidth, visibleWidth, wrapTextWithAnsi, type Component } from "@earendil-works/pi-tui";
|
|
17
17
|
import { withDialogLock } from "./dialog-lock.ts";
|
|
18
18
|
import type { RulebookRule } from "./rulebook.ts";
|
|
19
|
+
import { sanitizeForTerminal } from "./preview.ts";
|
|
19
20
|
|
|
20
21
|
/** The part of pi's theme this view uses; a fake object is enough to test it. */
|
|
21
22
|
export interface RulesTheme {
|
|
@@ -53,6 +54,24 @@ const SEP = " · ";
|
|
|
53
54
|
const fireText = (fired: boolean): string => (fired ? "1 fire" : "not fired");
|
|
54
55
|
const baseName = (file: string): string => file.split("/").pop() ?? file;
|
|
55
56
|
|
|
57
|
+
/**
|
|
58
|
+
* Wrap one logical line to `width`. pi-tui throws when a rendered line is wider
|
|
59
|
+
* than the terminal, and a rule's description, regex, file path or problem text
|
|
60
|
+
* is user-written and can be any length; nothing here may emit a long line.
|
|
61
|
+
* Continuation lines get `indent`. A single token longer than the width (a regex
|
|
62
|
+
* has no spaces) is broken by the wrapper; the final clamp is a safety net.
|
|
63
|
+
*/
|
|
64
|
+
export function wrapLine(text: string, width: number, indent = ""): string[] {
|
|
65
|
+
const room = Math.max(1, width - visibleWidth(indent));
|
|
66
|
+
const parts = wrapTextWithAnsi(text, Math.max(1, width));
|
|
67
|
+
const lines: string[] = [];
|
|
68
|
+
for (const [index, part] of parts.entries()) {
|
|
69
|
+
if (index === 0) lines.push(part);
|
|
70
|
+
else lines.push(...wrapTextWithAnsi(part, room).map((piece) => `${indent}${piece}`));
|
|
71
|
+
}
|
|
72
|
+
return (lines.length === 0 ? [""] : lines).map((line) => (visibleWidth(line) > width ? truncateToWidth(line, width) : line));
|
|
73
|
+
}
|
|
74
|
+
|
|
56
75
|
/** The coloured list, one line per row. `selected` is skipped when it points at a non-rule row. */
|
|
57
76
|
export function renderRulesList(theme: RulesTheme, rows: readonly RulesRow[], selected: number, width: number): string[] {
|
|
58
77
|
const sep = theme.fg("dim", SEP);
|
|
@@ -60,34 +79,34 @@ export function renderRulesList(theme: RulesTheme, rows: readonly RulesRow[], se
|
|
|
60
79
|
for (const [index, row] of rows.entries()) {
|
|
61
80
|
const cursor = index === selected ? theme.fg("accent", "> ") : " ";
|
|
62
81
|
if (row.kind === "untrusted") {
|
|
63
|
-
out.push(
|
|
82
|
+
out.push(...wrapLine(`${cursor}${theme.fg("warning", baseName(sanitizeForTerminal(row.file)))}${sep}${theme.fg("warning", "needs review")}${sep}${theme.fg("text", "a project rule file; asked on the next prompt")}`, width, " "));
|
|
64
83
|
continue;
|
|
65
84
|
}
|
|
66
85
|
if (row.kind === "problem") {
|
|
67
|
-
out.push(
|
|
86
|
+
out.push(...wrapLine(`${cursor}${theme.fg("error", baseName(sanitizeForTerminal(row.file)))}${sep}${theme.fg("error", "skipped")}${sep}${theme.fg("text", sanitizeForTerminal(row.problem))}`, width, " "));
|
|
68
87
|
continue;
|
|
69
88
|
}
|
|
70
|
-
const name = theme.bold(theme.fg(index === selected ? "accent" : "mdLink", row.rule.name));
|
|
89
|
+
const name = theme.bold(theme.fg(index === selected ? "accent" : "mdLink", sanitizeForTerminal(row.rule.name)));
|
|
71
90
|
const source = row.rule.kind === "user" ? theme.fg("success", "user") : theme.fg("warning", "project");
|
|
72
91
|
const fires = row.fired ? theme.fg("success", fireText(true)) : theme.fg("muted", fireText(false));
|
|
73
|
-
out.push(
|
|
92
|
+
out.push(...wrapLine(`${cursor}${name}${sep}${source}${sep}${fires}${sep}${theme.fg("text", sanitizeForTerminal(row.rule.description))}`, width, " "));
|
|
74
93
|
}
|
|
75
94
|
return out;
|
|
76
95
|
}
|
|
77
96
|
|
|
78
97
|
/** One rule in full: where it lives, what makes it fire, and what it says. */
|
|
79
98
|
export function renderRuleDetail(theme: RulesTheme, rule: RulebookRule, fired: boolean, width: number): string[] {
|
|
80
|
-
const lines = [
|
|
81
|
-
`${theme.bold(theme.fg("accent", rule.name))}${theme.fg("dim", SEP)}${rule.kind === "user" ? theme.fg("success", "user") : theme.fg("warning", "project")}${theme.fg("dim", SEP)}${fired ? theme.fg("success", fireText(true)) : theme.fg("muted", fireText(false))}`,
|
|
82
|
-
theme.fg("text", rule.description),
|
|
99
|
+
const lines: string[] = [
|
|
100
|
+
...wrapLine(`${theme.bold(theme.fg("accent", sanitizeForTerminal(rule.name)))}${theme.fg("dim", SEP)}${rule.kind === "user" ? theme.fg("success", "user") : theme.fg("warning", "project")}${theme.fg("dim", SEP)}${fired ? theme.fg("success", fireText(true)) : theme.fg("muted", fireText(false))}`, width),
|
|
101
|
+
...wrapLine(theme.fg("text", sanitizeForTerminal(rule.description)), width),
|
|
83
102
|
"",
|
|
84
|
-
theme.fg("dim", "condition
|
|
85
|
-
theme.fg("mdCode", rule.condition),
|
|
86
|
-
theme.fg("dim", "file
|
|
87
|
-
theme.fg("dim", rule.file),
|
|
103
|
+
...wrapLine(theme.fg("dim", "condition"), width),
|
|
104
|
+
...wrapLine(theme.fg("mdCode", sanitizeForTerminal(rule.condition)), width, " "),
|
|
105
|
+
...wrapLine(theme.fg("dim", "file"), width),
|
|
106
|
+
...wrapLine(theme.fg("dim", sanitizeForTerminal(rule.file)), width, " "),
|
|
88
107
|
"",
|
|
89
108
|
];
|
|
90
|
-
for (const line of rule.body.split("\n")) lines.push(...(line === "" ? [""] :
|
|
109
|
+
for (const line of sanitizeForTerminal(rule.body).split("\n")) lines.push(...(line === "" ? [""] : wrapLine(theme.fg("text", line), width)));
|
|
91
110
|
return lines;
|
|
92
111
|
}
|
|
93
112
|
|
|
@@ -95,12 +114,12 @@ export function renderRuleDetail(theme: RulesTheme, rule: RulebookRule, fired: b
|
|
|
95
114
|
function listScreen(theme: RulesTheme, rows: readonly RulesRow[], selected: number, width: number): string[] {
|
|
96
115
|
const header = `${theme.bold(theme.fg("text", "Rulebook rules"))}${theme.fg("dim", " · behaviour rules that fire on the model's answer; permission rules are /permissions")}`;
|
|
97
116
|
const body = rows.length === 0
|
|
98
|
-
? [theme.fg("text", "No rulebook rules yet."), theme.fg("dim", "
|
|
117
|
+
? [theme.fg("text", "No rulebook rules yet."), theme.fg("dim", "Put one .md file per rule in ~/.pi/agent/pi-keeper/rules/ (all projects) or <project>/.pi/rules/ (one project).")]
|
|
99
118
|
: renderRulesList(theme, rows, selected, width);
|
|
100
119
|
const footer = rows.length === 0
|
|
101
120
|
? theme.fg("dim", " Esc close")
|
|
102
121
|
: theme.fg("dim", " ↑↓ select · Enter shows the rule · Esc close");
|
|
103
|
-
return [
|
|
122
|
+
return [...wrapLine(header, width), "", ...body.flatMap((line) => wrapLine(line, width, " ")), "", ...wrapLine(footer, width)];
|
|
104
123
|
}
|
|
105
124
|
|
|
106
125
|
/** The plain-text form for a session without a TUI: same facts, no colours. */
|
|
@@ -137,7 +156,7 @@ export async function rulesPanel(ctx: ExtensionContext, input: RulesViewInput):
|
|
|
137
156
|
render(width: number): string[] {
|
|
138
157
|
if (detail !== undefined) {
|
|
139
158
|
const fired = input.fired.has(detail.name);
|
|
140
|
-
return [...renderRuleDetail(theme, detail, fired, width), "", theme.fg("dim", " Esc back · Esc again closes")];
|
|
159
|
+
return [...renderRuleDetail(theme, detail, fired, width), "", ...wrapLine(theme.fg("dim", " Esc back · Esc again closes"), width)];
|
|
141
160
|
}
|
|
142
161
|
return listScreen(theme, rows, selected, width);
|
|
143
162
|
},
|