@clothespin/pi-pippi 0.0.0-stage → 0.1.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 +13 -0
- package/README.md +415 -2
- package/approvals.ts +552 -0
- package/ble.ts +1062 -0
- package/bluez.ts +962 -0
- package/bridge.ts +1759 -0
- package/claims.ts +453 -0
- package/index.ts +827 -0
- package/package.json +53 -4
- package/protocol.ts +593 -0
- package/simulate.ts +249 -0
- package/state.ts +91 -0
- package/transport.ts +183 -0
- package/usage.ts +959 -0
package/approvals.ts
ADDED
|
@@ -0,0 +1,552 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Approval policy: which pi tool calls are worth interrupting a human for.
|
|
3
|
+
*
|
|
4
|
+
* Three modes (config.approvals):
|
|
5
|
+
* off - never block; the pet only reflects state
|
|
6
|
+
* dangerous - block calls matching the patterns below (default)
|
|
7
|
+
* all - block every tool call the bridge knows about
|
|
8
|
+
*
|
|
9
|
+
* "dangerous" is deliberately a deny-list rather than a sandbox: pi still owns
|
|
10
|
+
* its own safety story. This exists so the device buttons mean something, and
|
|
11
|
+
* so a walk-away session has a choke point.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import { lstatSync, realpathSync } from "node:fs";
|
|
15
|
+
import { tmpdir } from "node:os";
|
|
16
|
+
import { basename, isAbsolute, relative, resolve, sep } from "node:path";
|
|
17
|
+
|
|
18
|
+
export type ApprovalPolicy = "off" | "dangerous" | "all";
|
|
19
|
+
|
|
20
|
+
export interface GateDecision {
|
|
21
|
+
gate: boolean;
|
|
22
|
+
/** Short label shown as the device prompt tool (e.g. "Bash", "Write"). */
|
|
23
|
+
tool: string;
|
|
24
|
+
/** One-line preview of the call (device budget: 43 bytes). */
|
|
25
|
+
hint: string;
|
|
26
|
+
/** Why this call was gated; surfaced in the block reason. */
|
|
27
|
+
risk?: string;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** Shell patterns worth a human. Kept as regexes with a reason each. */
|
|
31
|
+
export const DANGEROUS_BASH: Array<{
|
|
32
|
+
pattern: RegExp;
|
|
33
|
+
risk: string;
|
|
34
|
+
/**
|
|
35
|
+
* Look again at the actual arguments before believing the pattern. A pattern
|
|
36
|
+
* that matches too broadly ("any recursive delete") is only acceptable if the
|
|
37
|
+
* exemption is narrower than the match, so this answers "may this specific
|
|
38
|
+
* call proceed?" and must never widen what the pattern would have allowed.
|
|
39
|
+
*/
|
|
40
|
+
exempt?: (command: string, root: string) => boolean;
|
|
41
|
+
}> = [
|
|
42
|
+
{
|
|
43
|
+
pattern: /\brm\s+(-[a-z]*[rf][a-z]*\b|--recursive\b)/i,
|
|
44
|
+
risk: "recursive delete",
|
|
45
|
+
exempt: deletesOnlyScratch,
|
|
46
|
+
},
|
|
47
|
+
{ pattern: /\bsudo\b/i, risk: "privilege escalation" },
|
|
48
|
+
{ pattern: /\b(doas|pkexec)\b/i, risk: "privilege escalation" },
|
|
49
|
+
{ pattern: /\bdd\b[^|]*\bof=\/dev\//i, risk: "raw device write" },
|
|
50
|
+
{ pattern: /\bmkfs(\.\w+)?\b/i, risk: "format filesystem" },
|
|
51
|
+
{ pattern: /\b(shutdown|reboot|poweroff|halt)\b/i, risk: "power state change" },
|
|
52
|
+
{ pattern: /\bkill\s+(-9\s+)?-?1\b/i, risk: "kill init" },
|
|
53
|
+
{ pattern: /:\(\)\s*\{.*\|.*\};\s*:/, risk: "fork bomb" },
|
|
54
|
+
{ pattern: /\b(curl|wget|fetch)\b[^|]*\|\s*(sudo\s+)?(ba|z|k|)sh\b/i, risk: "remote code execution" },
|
|
55
|
+
{ pattern: /\bgit\s+push\b[^;|]*(-f\b|--force\b|--force-with-lease\b)/i, risk: "force push" },
|
|
56
|
+
{ pattern: /\bgit\s+(reset|clean|checkout)\b[^;|]*(-[fdh]\b|--hard\b)/i, risk: "discard working tree" },
|
|
57
|
+
{ pattern: /\bchmod\b[^;|]*(-R\b|777)/i, risk: "broad permission change" },
|
|
58
|
+
{ pattern: /\bchown\b[^;|]*-R\b/i, risk: "recursive ownership change" },
|
|
59
|
+
{ pattern: /(^|[\s;&(])\.env\b[^;|]*\b(rm|mv|cat|>|>>)/i, risk: "secret file access" },
|
|
60
|
+
{ pattern: /(?:^|\s)\/(?:etc|usr|bin|sbin|System|Library)\b/i, risk: "system path write" },
|
|
61
|
+
{ pattern: /\b(DROP|DELETE|TRUNCATE)\s+(TABLE|DATABASE)\b/i, risk: "destructive SQL" },
|
|
62
|
+
{ pattern: /\b(kubectl|terraform|helm)\b[^;|]*\b(apply|delete|destroy|rollback)\b/i, risk: "infra change" },
|
|
63
|
+
{ pattern: /\baws\b[^;|]*\b(delete|remove|terminate)\b/i, risk: "cloud destroy" },
|
|
64
|
+
{ pattern: /\bcrontab\b\s+-[r]/i, risk: "cron removal" },
|
|
65
|
+
{ pattern: /\blaunchctl\b\s+(unload|remove|bootout)/i, risk: "service removal" },
|
|
66
|
+
];
|
|
67
|
+
|
|
68
|
+
/** Files whose contents should never be overwritten without asking. */
|
|
69
|
+
export const SENSITIVE_PATHS: RegExp[] = [
|
|
70
|
+
/(^|\/)\.env(\.|$)/i,
|
|
71
|
+
/(^|\/)\.ssh(\/|$)/,
|
|
72
|
+
/(^|\/)\.aws(\/|$)/,
|
|
73
|
+
/(^|\/)\.gnupg(\/|$)/,
|
|
74
|
+
/(^|\/)\.npmrc$/i,
|
|
75
|
+
/(^|\/)\.netrc$/i,
|
|
76
|
+
/(^|\/)id_(rsa|ed25519|ecdsa)(\.pub)?$/,
|
|
77
|
+
/(^|\/)credentials(\.json)?$/i,
|
|
78
|
+
/(^|\/)\.gitconfig$/,
|
|
79
|
+
/(^|\/)\.bashrc$|(^|\/)\.zshrc$|(^|\/)\.profile$/,
|
|
80
|
+
];
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Directories whose contents are throwaways: writing there is not "outside the
|
|
84
|
+
* workspace" and does not deserve an interrupt. os.tmpdir() is in the list
|
|
85
|
+
* beside the literal POSIX ones because macOS puts $TMPDIR under /var/folders
|
|
86
|
+
* and Windows puts it somewhere else entirely, and the device-side prompt is
|
|
87
|
+
* supposed to mean the same thing on every host.
|
|
88
|
+
*/
|
|
89
|
+
function scratchRoots(): string[] {
|
|
90
|
+
const roots = new Set<string>();
|
|
91
|
+
for (const dir of ["/tmp", "/var/tmp", tmpdir()]) {
|
|
92
|
+
if (!dir) continue;
|
|
93
|
+
roots.add(resolve(dir));
|
|
94
|
+
// macOS spells /tmp as /private/tmp the moment anything resolves it, and
|
|
95
|
+
// callers hand us whichever spelling they started from.
|
|
96
|
+
try {
|
|
97
|
+
roots.add(resolve(realpathSync(dir)));
|
|
98
|
+
} catch {
|
|
99
|
+
// Not on this host: the plain spelling still stands.
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
return [...roots];
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
const SCRATCH_DIRS = scratchRoots();
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* Is `abs` at or under `root`? Both must already be absolute and normalized
|
|
109
|
+
* (resolve() does that). A prefix test is not the same thing: `startsWith(root)`
|
|
110
|
+
* calls /work/pi-pippi-evil/x a descendant of /work/pi-pippi,
|
|
111
|
+
* and relative() has no such sibling confusion because it answers structurally.
|
|
112
|
+
*
|
|
113
|
+
* We never resolve the *target* against the filesystem. Only the roots get
|
|
114
|
+
* realpath'd, because a symlink inside the workspace pointing outward would
|
|
115
|
+
* otherwise launder a write to anywhere, and the target usually does not exist
|
|
116
|
+
* yet anyway.
|
|
117
|
+
*/
|
|
118
|
+
function inside(root: string, abs: string): boolean {
|
|
119
|
+
const rel = relative(root, abs);
|
|
120
|
+
if (rel === "" || rel === ".") return true;
|
|
121
|
+
if (isAbsolute(rel)) return false; // different drive or UNC root
|
|
122
|
+
// "..foo" is a sibling-free filename, not a traversal: compare against ".."
|
|
123
|
+
// and ".."+separator, not against the two-character prefix.
|
|
124
|
+
return rel !== ".." && !rel.startsWith(`..${sep}`);
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* A path that means "somewhere under a home directory": `~`, `~/x`, or a
|
|
129
|
+
* `~user/x` expansion. Deliberately not any string starting with a tilde, so a
|
|
130
|
+
* file actually named `~scratch.txt` in the workspace is just a file.
|
|
131
|
+
*/
|
|
132
|
+
const HOME_REF = /^~($|[\\/]|[^\\/]+[\\/])/;
|
|
133
|
+
|
|
134
|
+
function strictlyInside(root: string, abs: string): boolean {
|
|
135
|
+
return inside(root, abs) && root !== abs;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* May `rm -r…` be waved through? Only when every operand of every recursive rm
|
|
140
|
+
* in the command is a *child* of a scratch directory (never `/tmp` itself),
|
|
141
|
+
* owned by the user running the bridge, and not a symlink pointing out of
|
|
142
|
+
* scratch.
|
|
143
|
+
*
|
|
144
|
+
* The ownership test is what makes "it is in /tmp" mean something: /tmp is
|
|
145
|
+
* world-writable, so a directory there is not necessarily yours, and on a shared
|
|
146
|
+
* machine "scratch" is somebody else's data. `/tmp` itself is excluded because
|
|
147
|
+
* wiping it takes everyone else's scratch with it, however the top-level
|
|
148
|
+
* directory happens to be owned.
|
|
149
|
+
*
|
|
150
|
+
* Anything we cannot resolve stays gated, which is why the failure mode of every
|
|
151
|
+
* check here is `false`: an unquoted glob, a `$VAR` we would have to expand the
|
|
152
|
+
* way the shell does, a path that is a symlink to somewhere else, a platform
|
|
153
|
+
* without POSIX uids. `rm -rf` is the most valuable prompt on the device; it is
|
|
154
|
+
* allowed to be over-eager, not wrong.
|
|
155
|
+
*/
|
|
156
|
+
function deletesOnlyScratch(command: string, root: string): boolean {
|
|
157
|
+
const segments = splitSegments(command);
|
|
158
|
+
if (!segments) return false; // unterminated quote: we do not know the argv
|
|
159
|
+
let sawGatedRm = false;
|
|
160
|
+
for (const segment of segments) {
|
|
161
|
+
const argv = tokenize(segment);
|
|
162
|
+
// `FOO=bar rm -rf /tmp/x` still runs rm.
|
|
163
|
+
while (argv.length && /^[A-Za-z_][A-Za-z0-9_]*=/.test(argv[0])) argv.shift();
|
|
164
|
+
if (!argv.length || basename(argv[0]) !== "rm") continue; // `xargs rm`, `command rm`: still gated
|
|
165
|
+
|
|
166
|
+
const flags: string[] = [];
|
|
167
|
+
const operands: string[] = [];
|
|
168
|
+
let endOfFlags = false;
|
|
169
|
+
for (const arg of argv.slice(1)) {
|
|
170
|
+
if (!endOfFlags && arg === "--") endOfFlags = true;
|
|
171
|
+
else if (!endOfFlags && arg.startsWith("-") && arg !== "-") flags.push(arg);
|
|
172
|
+
else operands.push(arg);
|
|
173
|
+
}
|
|
174
|
+
const recursive = flags.some((f) => /-[a-zA-Z]*[rR]/.test(f) || f === "--recursive");
|
|
175
|
+
// The pattern fires on -f as readily as -r, so a force-delete of one scratch
|
|
176
|
+
// file is waved through on the same terms as a recursive one: refusing it
|
|
177
|
+
// while allowing `rm -rf` of the directory above it would be theatre. A rm
|
|
178
|
+
// with neither flag is not this pattern's business anywhere else either, so
|
|
179
|
+
// it decides nothing here -- `rm /tmp/a && rm -rf /tmp/b` is one delete and
|
|
180
|
+
// one no-op, not two things to fear.
|
|
181
|
+
if (!recursive && !flags.some((f) => /-[a-zA-Z]*[fF]/.test(f) || f === "--force")) continue;
|
|
182
|
+
sawGatedRm = true;
|
|
183
|
+
if (!operands.length) return false;
|
|
184
|
+
for (const operand of operands) if (!isOwnedScratchChild(operand, root)) return false;
|
|
185
|
+
}
|
|
186
|
+
return sawGatedRm;
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/**
|
|
190
|
+
* Shell control operators, but only the ones that are not inside quotes.
|
|
191
|
+
*
|
|
192
|
+
* The naive regex split is unsound and this is the command that proves it:
|
|
193
|
+
* `rm -rf "/tmp/x|/.."` splits into `rm -rf "/tmp/x` and `/.."`, so the parser
|
|
194
|
+
* checks an operand that is a *prefix* of the real one -- `/tmp/x`, a scratch
|
|
195
|
+
* child, exempt -- while the shell deletes `/tmp`, which the rule says is never
|
|
196
|
+
* exempt. Reading a truncated operand as if it were the whole path is the bug;
|
|
197
|
+
* refusing to read the command at all is not. So splitting tracks quote state,
|
|
198
|
+
* and an unbalanced quote makes the whole command ungovernable: we keep the
|
|
199
|
+
* prompt rather than guess at an argv we never parsed.
|
|
200
|
+
*/
|
|
201
|
+
export function splitSegments(command: string): string[] | undefined {
|
|
202
|
+
const segments: string[] = [];
|
|
203
|
+
let current = "";
|
|
204
|
+
let quote: "'" | '"' | "" = "";
|
|
205
|
+
for (let i = 0; i < command.length; i++) {
|
|
206
|
+
const ch = command[i] as string;
|
|
207
|
+
if (quote) {
|
|
208
|
+
// Backslash is inert inside single quotes, live inside double ones.
|
|
209
|
+
if (ch === "\\" && quote === '"' && i + 1 < command.length) {
|
|
210
|
+
current += ch + command[i + 1];
|
|
211
|
+
i++;
|
|
212
|
+
} else if (ch === quote) {
|
|
213
|
+
// Keep it. This function only finds boundaries; dropping the closing quote
|
|
214
|
+
// would leave tokenize() reading an unbalanced string, and `rm -rf "/tmp/a"
|
|
215
|
+
// "/.."` becomes one operand `/tmp/a "/..` -- a scratch child, exempt --
|
|
216
|
+
// with the traversal operand swallowed instead of poisoning the verdict.
|
|
217
|
+
current += ch;
|
|
218
|
+
quote = "";
|
|
219
|
+
} else current += ch;
|
|
220
|
+
continue;
|
|
221
|
+
}
|
|
222
|
+
if (ch === "\\" && i + 1 < command.length) {
|
|
223
|
+
current += ch + command[i + 1];
|
|
224
|
+
i++;
|
|
225
|
+
continue;
|
|
226
|
+
}
|
|
227
|
+
if (ch === "'" || ch === '"') {
|
|
228
|
+
quote = ch;
|
|
229
|
+
current += ch;
|
|
230
|
+
continue;
|
|
231
|
+
}
|
|
232
|
+
const pair = command.slice(i, i + 2);
|
|
233
|
+
if (pair === "&&" || pair === "||") {
|
|
234
|
+
segments.push(current);
|
|
235
|
+
current = "";
|
|
236
|
+
i++;
|
|
237
|
+
continue;
|
|
238
|
+
}
|
|
239
|
+
if (ch === ";" || ch === "\n" || ch === "|") {
|
|
240
|
+
segments.push(current);
|
|
241
|
+
current = "";
|
|
242
|
+
continue;
|
|
243
|
+
}
|
|
244
|
+
current += ch;
|
|
245
|
+
}
|
|
246
|
+
if (quote) return undefined; // unterminated quote: no trustworthy argv
|
|
247
|
+
segments.push(current);
|
|
248
|
+
return segments;
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
/** Glob, expansion or escape we would have to resolve the way a shell does. */
|
|
252
|
+
const SHELL_EXPANSION = /[$*?{}[\]`\\]/;
|
|
253
|
+
|
|
254
|
+
/** Split one command into words, honouring quotes and backslash escapes. */
|
|
255
|
+
function tokenize(line: string): string[] {
|
|
256
|
+
const out: string[] = [];
|
|
257
|
+
let current = "";
|
|
258
|
+
let quote: "'" | '"' | "" = "";
|
|
259
|
+
let started = false;
|
|
260
|
+
for (let i = 0; i < line.length; i++) {
|
|
261
|
+
const ch = line[i] as string;
|
|
262
|
+
if (quote) {
|
|
263
|
+
const next = line[i + 1];
|
|
264
|
+
if (ch === "\\" && quote === '"' && next !== undefined) {
|
|
265
|
+
current += next;
|
|
266
|
+
i++;
|
|
267
|
+
} else if (ch === quote) quote = "";
|
|
268
|
+
else current += ch;
|
|
269
|
+
continue;
|
|
270
|
+
}
|
|
271
|
+
const next = line[i + 1];
|
|
272
|
+
if (ch === "\\" && next !== undefined) {
|
|
273
|
+
current += next;
|
|
274
|
+
started = true;
|
|
275
|
+
i++;
|
|
276
|
+
} else if (ch === "'" || ch === '"') {
|
|
277
|
+
quote = ch;
|
|
278
|
+
started = true;
|
|
279
|
+
} else if (/\s/.test(ch)) {
|
|
280
|
+
if (started) out.push(current);
|
|
281
|
+
current = "";
|
|
282
|
+
started = false;
|
|
283
|
+
} else {
|
|
284
|
+
current += ch;
|
|
285
|
+
started = true;
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
if (started) out.push(current);
|
|
289
|
+
return out;
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
/**
|
|
293
|
+
* Location half of the scratch rule, with no I/O in it: a scratch *child*, never
|
|
294
|
+
* a scratch root. Asserted directly because on Linux every scratch root is
|
|
295
|
+
* root-owned, so the ownership test in isOwnedScratchChild happens to reject
|
|
296
|
+
* `rm -rf /tmp` and this rule looks redundant here. It is not redundant on
|
|
297
|
+
* macOS, where $TMPDIR is /var/folders/.../T and belongs to the user; there,
|
|
298
|
+
* this is the rule that stops a wipe of the whole temp tree.
|
|
299
|
+
*/
|
|
300
|
+
export function isScratchLocation(raw: string, root: string): boolean {
|
|
301
|
+
if (raw === "" || HOME_REF.test(raw) || SHELL_EXPANSION.test(raw)) return false;
|
|
302
|
+
const abs = resolve(root, raw);
|
|
303
|
+
return SCRATCH_DIRS.some((d) => strictlyInside(d, abs));
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
function isOwnedScratchChild(operand: string, root: string): boolean {
|
|
307
|
+
if (!isScratchLocation(operand, root)) return false;
|
|
308
|
+
const abs = resolve(root, operand);
|
|
309
|
+
|
|
310
|
+
// No POSIX ownership to check on this platform, so "yours" is unverifiable.
|
|
311
|
+
const uid = process.getuid?.();
|
|
312
|
+
if (uid === undefined) return false;
|
|
313
|
+
|
|
314
|
+
// ENOENT is the only failure allowed to mean "fine": a recursive delete of a
|
|
315
|
+
// path that is not there destroys nothing. Everything else fails closed -- a
|
|
316
|
+
// throwing gate breaks the tool call with something the device cannot render,
|
|
317
|
+
// and an over-eager prompt is the cheaper mistake. This is also what kept the
|
|
318
|
+
// first version of this function from working at all: `abs` was undefined,
|
|
319
|
+
// lstatSync threw, and a bare `catch { return true }` answered "go ahead" for
|
|
320
|
+
// every scratch path on the machine.
|
|
321
|
+
let owner: number;
|
|
322
|
+
try {
|
|
323
|
+
owner = lstatSync(abs).uid;
|
|
324
|
+
} catch (err) {
|
|
325
|
+
return (err as NodeJS.ErrnoException).code === "ENOENT";
|
|
326
|
+
}
|
|
327
|
+
if (owner !== uid) return false;
|
|
328
|
+
|
|
329
|
+
// Symlinks are the hole in "it is under /tmp": `rm -rf /tmp/link/` with a
|
|
330
|
+
// trailing slash traverses into whatever link points at. Checking only the
|
|
331
|
+
// operand is enough -- rm does not follow symlinks it meets while descending.
|
|
332
|
+
try {
|
|
333
|
+
const real = realpathSync(abs);
|
|
334
|
+
return SCRATCH_DIRS.some((d) => strictlyInside(d, real));
|
|
335
|
+
} catch {
|
|
336
|
+
return false; // dangling or unreadable: gated
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
/** The file a call targets, however that tool happens to spell the field. */
|
|
341
|
+
function targetOf(input: Record<string, unknown>): string | undefined {
|
|
342
|
+
return asString(input.path) ?? asString(input.file) ?? asString(input.filePath) ?? asString(input.filename);
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
/** Tools worth considering at all; the rest run freely. */
|
|
346
|
+
const GATEABLE = new Set([
|
|
347
|
+
"bash",
|
|
348
|
+
"write",
|
|
349
|
+
"edit",
|
|
350
|
+
"edit_file",
|
|
351
|
+
"apply_patch",
|
|
352
|
+
"str_replace_editor",
|
|
353
|
+
// Two more ways to run a shell that the first version of this list did not know
|
|
354
|
+
// about. `process` is a shell (`command`), and `codemode` is JavaScript that can
|
|
355
|
+
// call the shell, so its source is scanned as text. Without them the gate was
|
|
356
|
+
// bypassable by reaching for the other tool: `process start` with
|
|
357
|
+
// `command: "sudo ..."` ran with no approval at all.
|
|
358
|
+
"process",
|
|
359
|
+
"codemode",
|
|
360
|
+
]);
|
|
361
|
+
|
|
362
|
+
/**
|
|
363
|
+
* Tools whose danger lives in a string, not in a path: the shell itself and the
|
|
364
|
+
* two fields that can carry one. Scanned by the same `DANGEROUS_BASH` patterns, so
|
|
365
|
+
* a call that would be allowed through `bash` is allowed here -- the list is the
|
|
366
|
+
* policy, and this only says which fields get read.
|
|
367
|
+
*/
|
|
368
|
+
const SHELL_BODIED: Record<string, string[]> = {
|
|
369
|
+
bash: ["command", "cmd"],
|
|
370
|
+
process: ["command"],
|
|
371
|
+
// A codemode script is not a shell command, so patterns match inside it as text:
|
|
372
|
+
// `tools.bash({ command: "sudo ..." })` contains the risk in plain sight. Reading
|
|
373
|
+
// it loosely over-gates on a script that merely mentions `sudo` in a comment, which
|
|
374
|
+
// is the acceptable direction for a deny-list whose alternative is silence.
|
|
375
|
+
codemode: ["code"],
|
|
376
|
+
};
|
|
377
|
+
|
|
378
|
+
const TOOL_LABELS: Record<string, string> = {
|
|
379
|
+
bash: "Bash",
|
|
380
|
+
write: "Write",
|
|
381
|
+
edit: "Edit",
|
|
382
|
+
edit_file: "Edit",
|
|
383
|
+
apply_patch: "Patch",
|
|
384
|
+
str_replace_editor: "Edit",
|
|
385
|
+
process: "Process",
|
|
386
|
+
codemode: "Codemode",
|
|
387
|
+
};
|
|
388
|
+
|
|
389
|
+
function asString(value: unknown): string | undefined {
|
|
390
|
+
return typeof value === "string" ? value : undefined;
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
/**
|
|
394
|
+
* Paths a patch body touches. apply_patch is not a pi tool -- it is here for
|
|
395
|
+
* hosts and MCP servers that bring their own -- so the two dialects in the wild
|
|
396
|
+
* are matched, and the field holding the body is found by shape rather than by
|
|
397
|
+
* name because that is the only thing we can rely on across hosts.
|
|
398
|
+
*
|
|
399
|
+
* Empty for write/edit calls, which name their file directly: a .diff file being
|
|
400
|
+
* written is not a patch being applied, and reading paths out of its contents
|
|
401
|
+
* would prompt for the paths it merely mentions.
|
|
402
|
+
*/
|
|
403
|
+
function patchTargets(input: Record<string, unknown>): string[] {
|
|
404
|
+
const out: string[] = [];
|
|
405
|
+
for (const value of Object.values(input)) {
|
|
406
|
+
if (typeof value !== "string" || !PATCH_BODY.test(value)) continue;
|
|
407
|
+
for (const line of value.split("\n")) {
|
|
408
|
+
// *** Add File: p / *** Update File: p / *** Delete File: p
|
|
409
|
+
const star = /^\*\*\*\s+(?:Add|Update|Delete)\s+File:?\s*(.+?)\s*$/.exec(line);
|
|
410
|
+
if (star?.[1]) {
|
|
411
|
+
out.push(unquote(star[1]));
|
|
412
|
+
continue;
|
|
413
|
+
}
|
|
414
|
+
// diff --git a/x b/x (the a/ path; a rename's destination is on the +++ line)
|
|
415
|
+
const git = /^diff --git a\/(.*?) b\/.*$/.exec(line);
|
|
416
|
+
if (git?.[1]) {
|
|
417
|
+
out.push(git[1]);
|
|
418
|
+
continue;
|
|
419
|
+
}
|
|
420
|
+
// --- a/p / +++ b/p, with the optional tab-separated timestamp git emits.
|
|
421
|
+
// "a/" and "b/" are stripped as a prefix, which misreads a real directory
|
|
422
|
+
// named a/ -- but the unstripped form differs only by a leading component,
|
|
423
|
+
// so both answers land on the same side of every boundary we care about.
|
|
424
|
+
const uni = /^(?:---|\+\+\+) (?!\/dev\/null)(?:[ab]\/)?(.+?)(?:\t.*)?$/.exec(line);
|
|
425
|
+
if (uni?.[1]) out.push(uni[1]);
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
return out;
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
/** A string that is a patch rather than prose: one of the headers above. */
|
|
432
|
+
const PATCH_BODY = /^(?:\*\*\* (?:Add|Update|Delete) File|diff --git |--- a\/|\+\+\+ b\/|@@ -\d+)/m;
|
|
433
|
+
|
|
434
|
+
function unquote(p: string): string {
|
|
435
|
+
const q = p[0];
|
|
436
|
+
return (q === '"' || q === "'") && p.endsWith(q) && p.length > 1 ? p.slice(1, -1) : p;
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
/**
|
|
440
|
+
* Why this path deserves an interrupt, or undefined to let it through. One copy
|
|
441
|
+
* of the rule for single-target tools and patch bodies alike, so the two can
|
|
442
|
+
* never drift apart: a patch that could write where `write` could not would make
|
|
443
|
+
* the gate a joke.
|
|
444
|
+
*/
|
|
445
|
+
function pathRisk(raw: string, root: string): string | undefined {
|
|
446
|
+
for (const pattern of SENSITIVE_PATHS) {
|
|
447
|
+
if (pattern.test(raw)) return "sensitive path";
|
|
448
|
+
}
|
|
449
|
+
// "~" is left unexpanded on purpose: expanding it means trusting the host
|
|
450
|
+
// environment, and $HOME is outside both the workspace and the scratch roots,
|
|
451
|
+
// so the answer is "gate" either way.
|
|
452
|
+
if (HOME_REF.test(raw)) return "outside workspace";
|
|
453
|
+
const abs = resolve(root, raw);
|
|
454
|
+
if (inside(root, abs) || SCRATCH_DIRS.some((d) => inside(d, abs))) return undefined;
|
|
455
|
+
return "outside workspace";
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
/** One-line preview of a tool call, sized for the device's hint field. */
|
|
459
|
+
export function previewInput(toolName: string, input: Record<string, unknown>): string {
|
|
460
|
+
const command = asString(input.command) ?? asString(input.cmd);
|
|
461
|
+
if (command) return command;
|
|
462
|
+
const target = targetOf(input);
|
|
463
|
+
if (target) {
|
|
464
|
+
const extra = asString(input.content) ?? asString(input.oldText) ?? asString(input.text);
|
|
465
|
+
return extra ? `${target} — ${extra.slice(0, 60)}` : target;
|
|
466
|
+
}
|
|
467
|
+
// A patch: name the files it touches, since "Patch" plus 80 bytes of JSON body
|
|
468
|
+
// is not something a device prompt can be answered usefully from.
|
|
469
|
+
const targets = patchTargets(input);
|
|
470
|
+
if (targets.length) {
|
|
471
|
+
const shown = targets.slice(0, 2).join(", ");
|
|
472
|
+
return targets.length > 2 ? `${shown} +${targets.length - 2} more` : shown;
|
|
473
|
+
}
|
|
474
|
+
// A codemode script is a wall of JavaScript and the device has room for about forty
|
|
475
|
+
// characters. Lead with the line that carries the risk when there is one -- that is
|
|
476
|
+
// the line the human is being asked about -- and otherwise with the first line that
|
|
477
|
+
// does something.
|
|
478
|
+
const code = asString(input.code);
|
|
479
|
+
if (code) {
|
|
480
|
+
const lines = code
|
|
481
|
+
.split("\n")
|
|
482
|
+
.map((line) => line.trim())
|
|
483
|
+
.filter((line) => line.length > 0);
|
|
484
|
+
const risky = lines.find((line) => DANGEROUS_BASH.some(({ pattern }) => pattern.test(line)));
|
|
485
|
+
const busy = lines.find((line) => !/^(?:\/\/|import\b|export\b)/.test(line));
|
|
486
|
+
const lead = risky ?? busy ?? lines[0];
|
|
487
|
+
if (lead) return lead.slice(0, 78);
|
|
488
|
+
}
|
|
489
|
+
const json = JSON.stringify(input);
|
|
490
|
+
return json === "{}" ? toolName : json.slice(0, 80);
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
export function classifyToolCall(
|
|
494
|
+
policy: ApprovalPolicy,
|
|
495
|
+
toolName: string,
|
|
496
|
+
input: Record<string, unknown>,
|
|
497
|
+
options: { cwd?: string } = {},
|
|
498
|
+
): GateDecision {
|
|
499
|
+
const tool = TOOL_LABELS[toolName] ?? toolName;
|
|
500
|
+
const hint = previewInput(toolName, input);
|
|
501
|
+
if (policy === "off" || !GATEABLE.has(toolName)) return { gate: false, tool, hint };
|
|
502
|
+
|
|
503
|
+
if (policy === "all") return { gate: true, tool, hint, risk: "approvals=all" };
|
|
504
|
+
|
|
505
|
+
// The shell and its two stand-ins: nothing here is dangerous by name, only by
|
|
506
|
+
// what was passed. An ordinary `bash`, `process start` or `codemode` call matches
|
|
507
|
+
// no pattern and runs without interrupting anybody.
|
|
508
|
+
const fields = SHELL_BODIED[toolName];
|
|
509
|
+
if (fields) {
|
|
510
|
+
const command = fields.map((f) => asString(input[f])).filter((v): v is string => !!v).join("\n");
|
|
511
|
+
const root = resolve(options.cwd ?? process.cwd());
|
|
512
|
+
for (const { pattern, risk, exempt } of DANGEROUS_BASH) {
|
|
513
|
+
if (!pattern.test(command)) continue;
|
|
514
|
+
// An exemption may only ever un-gate, so a pattern whose matcher says
|
|
515
|
+
// "dangerous" and whose exemption says "actually, fine" is answered by the
|
|
516
|
+
// exemption -- and only when there is one to ask.
|
|
517
|
+
if (exempt?.(command, root)) continue;
|
|
518
|
+
return { gate: true, tool, hint, risk };
|
|
519
|
+
}
|
|
520
|
+
return { gate: false, tool, hint };
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
// ctx.cwd is whatever the session was started in and may be relative, so
|
|
524
|
+
// normalize it before treating it as a boundary; a relative root makes
|
|
525
|
+
// relative() answer against process.cwd() instead.
|
|
526
|
+
const root = resolve(options.cwd ?? process.cwd());
|
|
527
|
+
|
|
528
|
+
// write / edit: one named file.
|
|
529
|
+
const target = targetOf(input);
|
|
530
|
+
if (target !== undefined) {
|
|
531
|
+
const risk = pathRisk(target, root);
|
|
532
|
+
return risk ? { gate: true, tool, hint, risk } : { gate: false, tool, hint };
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
// No named file: the targets live in the patch body. An unparseable body stays
|
|
536
|
+
// ungated, as it was -- this gate is a deny-list, and inventing a target we
|
|
537
|
+
// cannot read would train nobody to trust it. A host that wants belt and
|
|
538
|
+
// braces sets approvals=all, which gates every call before any of this runs.
|
|
539
|
+
for (const path of patchTargets(input)) {
|
|
540
|
+
const risk = pathRisk(path, root);
|
|
541
|
+
if (risk) return { gate: true, tool, hint, risk };
|
|
542
|
+
}
|
|
543
|
+
return { gate: false, tool, hint };
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
export function parsePolicy(value: string | undefined): ApprovalPolicy | undefined {
|
|
547
|
+
const normalised = value?.trim().toLowerCase();
|
|
548
|
+
if (normalised === "off" || normalised === "none") return "off";
|
|
549
|
+
if (normalised === "dangerous" || normalised === "risky") return "dangerous";
|
|
550
|
+
if (normalised === "all" || normalised === "every") return "all";
|
|
551
|
+
return undefined;
|
|
552
|
+
}
|