@ziptie-soft/orca-local-decider 0.0.0 → 1.0.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.
@@ -0,0 +1,503 @@
1
+ import {
2
+ baseName,
3
+ commandWords,
4
+ parseShell,
5
+ substitutions,
6
+ type Segment,
7
+ type ShellParse,
8
+ } from './shell.ts';
9
+ /**
10
+ * Deterministic guard: a short, conservative list of shell commands that are destructive enough
11
+ * to deny without asking a model. It runs before any gateway call and never allows anything; a
12
+ * miss simply falls through to the `command-risk` policy.
13
+ */
14
+ import { resolveSegments } from './subject.ts';
15
+
16
+ export interface GuardHit {
17
+ readonly rule: string;
18
+ readonly reason: string;
19
+ /** The harness should ask rather than deny (Codex cannot ask: it denies). */
20
+ readonly ask?: true;
21
+ }
22
+
23
+ const SYSTEM_DIRS = [
24
+ 'bin',
25
+ 'boot',
26
+ 'dev',
27
+ 'etc',
28
+ 'home',
29
+ 'lib',
30
+ 'lib32',
31
+ 'lib64',
32
+ 'opt',
33
+ 'proc',
34
+ 'root',
35
+ 'sbin',
36
+ 'srv',
37
+ 'sys',
38
+ 'usr',
39
+ 'var',
40
+ 'Applications',
41
+ 'Library',
42
+ 'System',
43
+ 'Users',
44
+ 'private',
45
+ ];
46
+ /** `/`, `/*`, `~`, `$HOME` and top-level system directories, with an optional `/` or `/*`. */
47
+ const DANGEROUS_TARGET = new RegExp(
48
+ `^(?:/|/\\*|(?:~|\\$HOME|\\$\\{HOME\\})(?:/|/\\*)?|/(?:${SYSTEM_DIRS.join('|')})(?:/|/\\*)?)$`,
49
+ );
50
+ /** A `.git` directory or its contents: `.git`, `./.git/`, `repo/.git`, `.git/*`, any case. */
51
+ const GIT_DIR = /(?:^|\/)\.git(?:\/\*?)?$/i;
52
+ const DISK = String.raw`/dev/(?:sd[a-z]|nvme\d|hd[a-z]|vd[a-z]|xvd[a-z]|mmcblk\d|disk\d)`;
53
+ const DISK_DEVICE = new RegExp(`^${DISK}`);
54
+ const DISK_REDIRECT = new RegExp(`^\\d?>>?${DISK}`);
55
+ const SHELLS = new Set(['sh', 'bash', 'zsh', 'dash', 'ksh', 'fish']);
56
+ const POWER = new Set(['shutdown', 'reboot', 'halt', 'poweroff']);
57
+ // Linear forms: a shell word, then (in the same `;&|` segment) `<(` or `$(` and a fetcher.
58
+ const SHELL_WORD = /\b(?:(?:ba|z|da|k)?sh|eval|source)\b|(?:^|\s)\.(?=\s)/;
59
+ const SUBST_FETCH = /(?:<\(|\$\()\s*(?:curl|wget)\b/;
60
+ const LEADING_SUBST_FETCH = /^\s*(?:<\(|\$\()\s*(?:curl|wget)\b/;
61
+
62
+ /** `inScript`: the text is itself a script being run (`eval`, `-c`), so a leading `$(curl …)` runs. */
63
+ function hasShellSubstFetch(text: string, inScript: boolean): boolean {
64
+ for (const part of text.split(/[;&|]/)) {
65
+ const m = SHELL_WORD.exec(part);
66
+ if (m !== null && SUBST_FETCH.test(part.slice(m.index + m[0].length))) {
67
+ return true;
68
+ }
69
+ if (inScript && LEADING_SUBST_FETCH.test(part)) {
70
+ return true;
71
+ }
72
+ }
73
+ return false;
74
+ }
75
+
76
+ const NAME_CHAR = /[\w:]/;
77
+ const NAME_START = /[A-Za-z_:]/;
78
+
79
+ /**
80
+ * `name(){name|name&};name` in whitespace-stripped text, the name being any suffix of the word
81
+ * before `(){`. Scans each `(){` once, forwards and backwards over word characters only, so it is
82
+ * linear (a backreference regex is quadratic on a long word).
83
+ */
84
+ function hasForkBomb(text: string): boolean {
85
+ for (let i = text.indexOf('(){'); i !== -1; i = text.indexOf('(){', i + 1)) {
86
+ let end = i + 3;
87
+ while (end < text.length && NAME_CHAR.test(text[end] ?? '')) {
88
+ end++;
89
+ }
90
+ const name = text.slice(i + 3, end);
91
+ if (
92
+ name !== '' &&
93
+ NAME_START.test(name[0] ?? '') &&
94
+ i >= name.length &&
95
+ text.startsWith(name, i - name.length) &&
96
+ text.startsWith(`|${name}&};${name}`, end)
97
+ ) {
98
+ return true;
99
+ }
100
+ }
101
+ return false;
102
+ }
103
+
104
+ function flags(args: readonly string[]): readonly string[] {
105
+ return args.filter((a) => a.startsWith('-'));
106
+ }
107
+
108
+ function operands(args: readonly string[]): readonly string[] {
109
+ return args.filter((a) => !a.startsWith('-'));
110
+ }
111
+
112
+ function isRecursive(args: readonly string[]): boolean {
113
+ return flags(args).some((f) => f === '--recursive' || /^-[A-Za-z]*[rR]/.test(f));
114
+ }
115
+
116
+ /** `path` with `.`, `..` and repeated slashes collapsed (`//`, `/./`, `/usr/..` → `/`). */
117
+ function canonical(path: string): string {
118
+ const joined = resolveSegments('', path).join('/');
119
+ return path.startsWith('/') ? `/${joined}` : joined;
120
+ }
121
+
122
+ const isDangerous = (t: string): boolean =>
123
+ DANGEROUS_TARGET.test(t) || (t.startsWith('/') && DANGEROUS_TARGET.test(canonical(t)));
124
+ const isGitDir = (t: string): boolean => GIT_DIR.test(t) || GIT_DIR.test(canonical(t));
125
+
126
+ function checkRm(args: readonly string[]): GuardHit | null {
127
+ if (!isRecursive(args)) {
128
+ return null;
129
+ }
130
+ const targets = operands(args);
131
+ if (targets.some(isDangerous)) {
132
+ return {
133
+ rule: 'rm-root',
134
+ reason: 'recursive delete of the filesystem root, home or a system directory',
135
+ };
136
+ }
137
+ if (targets.some(isGitDir)) {
138
+ return { rule: 'rm-git', reason: 'deletes a .git directory (the repository history)' };
139
+ }
140
+ return null;
141
+ }
142
+
143
+ function checkChmod(args: readonly string[]): GuardHit | null {
144
+ const ops = operands(args);
145
+ const worldWritable = ops.some((o) => /^(?:0?777|(?:a|ugo)\+rwx)$/.test(o));
146
+ if (isRecursive(args) && worldWritable && ops.some(isDangerous)) {
147
+ return {
148
+ rule: 'chmod-777-root',
149
+ reason: 'recursive chmod 777 on the root or a system directory',
150
+ };
151
+ }
152
+ return null;
153
+ }
154
+
155
+ function checkDd(args: readonly string[]): GuardHit | null {
156
+ if (args.some((a) => a.startsWith('of=') && DISK_DEVICE.test(a.slice(3)))) {
157
+ return { rule: 'dd-disk', reason: 'dd writes straight to a disk device' };
158
+ }
159
+ return null;
160
+ }
161
+
162
+ const FORCE = /^(?:--force|--force-with-lease(?:=.*)?)$/;
163
+ const SHORT_FLAGS = /^-[A-Za-z]+$/;
164
+ /** `-f`, bundled short flags with `f`, `--force`; the includes keeps the match linear. */
165
+ const isForce = (a: string): boolean => FORCE.test(a) || (SHORT_FLAGS.test(a) && a.includes('f'));
166
+ const PROTECTED_REF = /(?:^|:|\+)(?:refs\/heads\/)?(?:main|master)$/;
167
+
168
+ const DELETE_REF = /^:(?:refs\/heads\/)?(?:main|master)$/;
169
+
170
+ function checkGit(args: readonly string[]): GuardHit | null {
171
+ const push = args.indexOf('push');
172
+ if (push === -1) {
173
+ return null;
174
+ }
175
+ const rest = args.slice(push + 1);
176
+ const forced = rest.some(isForce) || rest.some((a) => /^\+./.test(a));
177
+ if (forced && rest.some((a) => PROTECTED_REF.test(a))) {
178
+ return { rule: 'git-force-push-main', reason: 'force-push to main or master' };
179
+ }
180
+ const deleting = rest.includes('--delete') || rest.includes('-d');
181
+ if (
182
+ (deleting && rest.some((a) => PROTECTED_REF.test(a))) ||
183
+ rest.some((a) => DELETE_REF.test(a))
184
+ ) {
185
+ return { rule: 'git-delete-main', reason: 'deletes the main or master branch on the remote' };
186
+ }
187
+ return null;
188
+ }
189
+
190
+ function checkPower(cmd: string, args: readonly string[]): GuardHit | null {
191
+ const systemctl = cmd === 'systemctl' && args.some((a) => POWER.has(a));
192
+ const init = (cmd === 'init' || cmd === 'telinit') && (args[0] === '0' || args[0] === '6');
193
+ if (POWER.has(cmd) || systemctl || init) {
194
+ return { rule: 'shutdown', reason: 'shuts down or reboots the machine' };
195
+ }
196
+ return null;
197
+ }
198
+
199
+ function checkRedirects(words: readonly string[]): GuardHit | null {
200
+ for (let i = 0; i < words.length; i++) {
201
+ const w = words[i] ?? '';
202
+ const next = words[i + 1] ?? '';
203
+ if (DISK_REDIRECT.test(w) || (/^\d?>>?$/.test(w) && DISK_DEVICE.test(next))) {
204
+ return { rule: 'redirect-disk', reason: 'redirects output onto a disk device' };
205
+ }
206
+ }
207
+ return null;
208
+ }
209
+
210
+ /** `-c`, alone or bundled with other short flags (`-lc`, `-ec`). */
211
+ const INLINE_FLAG = (a: string): boolean => /^-[A-Za-z]+$/.test(a) && a.includes('c');
212
+ const MAX_DEPTH = 4;
213
+ /** Shell commands longer than this (MAX_ARG_STRLEN is 128 KiB) are asked about, never scanned. */
214
+ export const MAX_COMMAND_CHARS = 1024 * 1024;
215
+ export const OVERSIZE_COMMAND: GuardHit = {
216
+ rule: 'oversize-command',
217
+ reason: 'shell command too large to check',
218
+ ask: true,
219
+ };
220
+ const NESTED: GuardHit = {
221
+ rule: 'nested-shell',
222
+ reason: 'shell commands nested too deeply to check',
223
+ ask: true,
224
+ };
225
+
226
+ /** Check a nested script one level deeper; beyond `MAX_DEPTH` it asks instead. */
227
+ function recurse(script: string, depth: number): GuardHit | null {
228
+ return depth >= MAX_DEPTH ? NESTED : guardCommand(script, depth + 1);
229
+ }
230
+
231
+ /** The script of `bash -c "…"`, `bash -lc '…'` (how Codex runs commands), `su -c '…'`, `eval …`. */
232
+ function scriptOf(cmd: string, args: readonly string[]): string | undefined {
233
+ if (cmd === 'eval') {
234
+ return args.join(' ');
235
+ }
236
+ if (!SHELLS.has(cmd) && cmd !== 'su') {
237
+ return undefined;
238
+ }
239
+ const long = args.find((a) => a.startsWith('--command='));
240
+ if (long !== undefined) {
241
+ return long.slice('--command='.length);
242
+ }
243
+ const c = args.findIndex(INLINE_FLAG);
244
+ if (c === -1) {
245
+ return undefined;
246
+ }
247
+ return args[c + 1] === '--' ? args[c + 2] : args[c + 1];
248
+ }
249
+
250
+ function checkScript(cmd: string, args: readonly string[], depth: number): GuardHit | null {
251
+ const script = scriptOf(cmd, args);
252
+ return script === undefined ? null : recurse(script, depth);
253
+ }
254
+
255
+ /** The inline part of an `env -S` flag word (`''` for the bare flag), or undefined. */
256
+ function splitStringHead(w: string): string | undefined {
257
+ if (w === '-S' || w === '--split-string') {
258
+ return '';
259
+ }
260
+ if (w.startsWith('--split-string=')) {
261
+ return w.slice('--split-string='.length);
262
+ }
263
+ return w.startsWith('-S') ? w.slice(2) : undefined;
264
+ }
265
+
266
+ /** The command string of `env -S '…'` / `env -S… ` / `--split-string=…`, or undefined. */
267
+ function envScript(words: readonly string[]): string | undefined {
268
+ const env = words.findIndex((w) => baseName(w) === 'env');
269
+ if (env === -1) {
270
+ return undefined;
271
+ }
272
+ for (let i = env + 1; i < words.length; i++) {
273
+ const w = words[i] ?? '';
274
+ const head = splitStringHead(w);
275
+ if (head !== undefined) {
276
+ return [head, ...words.slice(i + 1)].join(' ');
277
+ }
278
+ if (!w.startsWith('-') && !ASSIGN.test(w)) {
279
+ return undefined;
280
+ }
281
+ }
282
+ return undefined;
283
+ }
284
+ const ASSIGN = /^[A-Za-z_]\w*=/;
285
+
286
+ const EXEC_FLAGS = new Set(['-exec', '-execdir', '-ok', '-okdir']);
287
+ /** Predicates that narrow what `find` selects: a dangerous start with one of them is not a wipe. */
288
+ const NARROWING = new Set([
289
+ '-name',
290
+ '-iname',
291
+ '-path',
292
+ '-ipath',
293
+ '-regex',
294
+ '-iregex',
295
+ '-newer',
296
+ '-mtime',
297
+ '-mmin',
298
+ '-size',
299
+ '-user',
300
+ '-empty',
301
+ ]);
302
+ const FIND_OPTION = /^-(?:[HLP]|O\d)$/;
303
+
304
+ /** The words after `-exec`/`-ok` at `from` up to the closing `;` or `+`, and where to resume. */
305
+ function execWords(args: readonly string[], from: number): { words: string[]; next: number } {
306
+ let end = from;
307
+ while (end < args.length && args[end] !== ';' && args[end] !== '+') {
308
+ end++;
309
+ }
310
+ return { words: args.slice(from, end), next: end + 1 };
311
+ }
312
+
313
+ function checkFindExecs(
314
+ args: readonly string[],
315
+ dangerous: boolean,
316
+ depth: number,
317
+ ): GuardHit | null {
318
+ for (let i = 0; i < args.length; i++) {
319
+ if (!EXEC_FLAGS.has(args[i] ?? '')) {
320
+ continue;
321
+ }
322
+ const { words, next } = execWords(args, i + 1);
323
+ const hit = depth >= MAX_DEPTH ? NESTED : checkWords(words, depth + 1);
324
+ if (hit !== null) {
325
+ return hit;
326
+ }
327
+ if (dangerous && baseName(commandWords(words)[0] ?? '') === 'rm') {
328
+ return {
329
+ rule: 'rm-root',
330
+ reason: 'find deletes files under the root, home or a system directory',
331
+ };
332
+ }
333
+ i = next - 1;
334
+ }
335
+ return null;
336
+ }
337
+
338
+ function checkFind(args: readonly string[], depth: number): GuardHit | null {
339
+ let k = 0;
340
+ while (FIND_OPTION.test(args[k] ?? '')) {
341
+ k++;
342
+ }
343
+ const stop = args.findIndex((a, i) => i >= k && (a.startsWith('-') || a === '(' || a === '!'));
344
+ const starts = args.slice(k, stop === -1 ? args.length : stop);
345
+ const dangerous = starts.some(isDangerous) && !args.some((a) => NARROWING.has(a));
346
+ if (args.includes('-delete') && dangerous) {
347
+ return { rule: 'rm-root', reason: 'find -delete under the root, home or a system directory' };
348
+ }
349
+ if (args.includes('-delete') && starts.some(isGitDir)) {
350
+ return { rule: 'rm-git', reason: 'find -delete inside a .git directory' };
351
+ }
352
+ return checkFindExecs(args, dangerous, depth);
353
+ }
354
+
355
+ function checkWords(words: readonly string[], depth: number): GuardHit | null {
356
+ const env = envScript(words);
357
+ const viaEnv = env === undefined ? null : recurse(env, depth);
358
+ if (viaEnv !== null) {
359
+ return viaEnv;
360
+ }
361
+ const [first = '', ...args] = commandWords(words);
362
+ const cmd = baseName(first);
363
+ if (cmd === 'rm') {
364
+ return checkRm(args);
365
+ }
366
+ if (cmd.startsWith('mkfs')) {
367
+ return { rule: 'mkfs', reason: 'formats a filesystem' };
368
+ }
369
+ const checks: Record<string, (a: readonly string[], depth: number) => GuardHit | null> = {
370
+ chmod: checkChmod,
371
+ dd: checkDd,
372
+ git: checkGit,
373
+ find: checkFind,
374
+ };
375
+ return (
376
+ checks[cmd]?.(args, depth) ??
377
+ checkPower(cmd, args) ??
378
+ checkScript(cmd, args, depth) ??
379
+ checkRedirects(words)
380
+ );
381
+ }
382
+
383
+ function commandOfSegment(segment: Segment | undefined): { cmd: string; args: readonly string[] } {
384
+ const [first = '', ...args] = commandWords(segment?.words ?? []);
385
+ return { cmd: baseName(first), args };
386
+ }
387
+
388
+ function isFetch(segment: Segment | undefined): boolean {
389
+ const { cmd } = commandOfSegment(segment);
390
+ return cmd === 'curl' || cmd === 'wget';
391
+ }
392
+
393
+ const INTERPRETER = /^(?:python[\d.]*|perl|ruby|node)$/;
394
+ const SCRIPT_FLAG = /^-[A-Za-z]*[cemEp]/;
395
+
396
+ /** A shell, or an interpreter that would read its program from stdin (no script or `-c`/`-e`). */
397
+ function readsStdinProgram(segment: Segment | undefined): boolean {
398
+ const { cmd, args } = commandOfSegment(segment);
399
+ if (SHELLS.has(cmd)) {
400
+ return true;
401
+ }
402
+ return (
403
+ INTERPRETER.test(cmd) &&
404
+ operands(args).length === 0 &&
405
+ !flags(args).some((f) => SCRIPT_FLAG.test(f))
406
+ );
407
+ }
408
+
409
+ function isDecode(segment: Segment | undefined): boolean {
410
+ const { cmd, args } = commandOfSegment(segment);
411
+ const decodes = (re: RegExp): boolean => flags(args).some((f) => re.test(f));
412
+ return (
413
+ (cmd === 'base64' && (decodes(/^--decode$/) || decodes(/^-[A-Za-z]*[dD]/))) ||
414
+ (cmd === 'xxd' && decodes(/^-[A-Za-z]*r/))
415
+ );
416
+ }
417
+
418
+ function checkPipeToShell(segments: readonly Segment[]): GuardHit | null {
419
+ for (let i = 1; i < segments.length; i++) {
420
+ const seg = segments[i];
421
+ if (seg?.piped !== true || !readsStdinProgram(seg)) {
422
+ continue;
423
+ }
424
+ if (isFetch(segments[i - 1])) {
425
+ return { rule: 'curl-pipe-shell', reason: 'pipes a downloaded script into a shell' };
426
+ }
427
+ if (SHELLS.has(commandOfSegment(seg).cmd) && isDecode(segments[i - 1])) {
428
+ return { rule: 'decode-pipe-shell', reason: 'pipes decoded data into a shell' };
429
+ }
430
+ }
431
+ return null;
432
+ }
433
+
434
+ const SUBST_FETCH_HIT: GuardHit = {
435
+ rule: 'curl-pipe-shell',
436
+ reason: 'runs a downloaded script in a shell',
437
+ };
438
+
439
+ function checkRaw(parse: ShellParse, inScript: boolean): GuardHit | null {
440
+ if (hasForkBomb(parse.bare.replace(/\s+/g, ''))) {
441
+ return { rule: 'fork-bomb', reason: 'fork bomb' };
442
+ }
443
+ return hasShellSubstFetch(parse.noSingle, inScript) ? SUBST_FETCH_HIT : null;
444
+ }
445
+
446
+ /** Scripts of `$(…)` / backtick substitutions in `text` (they run, so they are guarded). */
447
+ function checkSubstitutions(text: string, depth: number): GuardHit | null {
448
+ const { scripts, tail } = substitutions(text);
449
+ for (const script of scripts) {
450
+ const hit = recurse(script, depth);
451
+ if (hit !== null) {
452
+ return hit;
453
+ }
454
+ }
455
+ // An unterminated `$(` is a syntax error or beyond the scanner: ask, don't rescan the tail.
456
+ return tail === '' ? null : NESTED;
457
+ }
458
+
459
+ /** Unquoted heredoc bodies expand: a fetch or a destructive substitution in one runs. */
460
+ function checkExpanded(segment: Segment, depth: number): GuardHit | null {
461
+ if (segment.expanded === '') {
462
+ return null;
463
+ }
464
+ return hasShellSubstFetch(segment.expanded, true)
465
+ ? SUBST_FETCH_HIT
466
+ : checkSubstitutions(segment.expanded, depth);
467
+ }
468
+
469
+ /** A shell that reads its script from stdin (no `-c`). */
470
+ function feeds(segment: Segment | undefined): boolean {
471
+ const { cmd, args } = commandOfSegment(segment);
472
+ return SHELLS.has(cmd) && args.findIndex(INLINE_FLAG) === -1;
473
+ }
474
+
475
+ /** A heredoc fed to a shell (`bash <<EOF`, `cat <<EOF | sh`) is a script: check its body. */
476
+ function checkHeredoc(segments: readonly Segment[], i: number, depth: number): GuardHit | null {
477
+ const seg = segments[i];
478
+ const next = segments[i + 1];
479
+ if (seg === undefined || seg.heredoc === '') {
480
+ return null;
481
+ }
482
+ return feeds(seg) || (next?.piped === true && feeds(next)) ? recurse(seg.heredoc, depth) : null;
483
+ }
484
+
485
+ /** Return the first deterministic rule a shell command hits, or `null`. */
486
+ export function guardCommand(command: string, depth = 0): GuardHit | null {
487
+ const parse = parseShell(command);
488
+ const raw = checkRaw(parse, depth > 0) ?? checkSubstitutions(parse.noSingle, depth);
489
+ if (raw !== null) {
490
+ return raw;
491
+ }
492
+ const { segments } = parse;
493
+ for (const [i, segment] of segments.entries()) {
494
+ const hit =
495
+ checkWords(segment.words, depth) ??
496
+ checkHeredoc(segments, i, depth) ??
497
+ checkExpanded(segment, depth);
498
+ if (hit !== null) {
499
+ return hit;
500
+ }
501
+ }
502
+ return checkPipeToShell(segments);
503
+ }
@@ -0,0 +1,2 @@
1
+ /** Tool-use and call ids, also the `GET /v1/calls/:id` path segment: a Claude Code `tool_use_id`. */
2
+ export const CALL_ID = /^[\w-]{1,128}$/;
@@ -0,0 +1,71 @@
1
+ /**
2
+ * Caps on the policy input keys a client sends, applied once per client path before the body is
3
+ * serialised. A multi-megabyte `tool_input` must not become a multi-megabyte request: the gateway
4
+ * truncates again for the model, but it should never have to receive the excess. No node imports:
5
+ * the Paseo plugin vendors this file with `truncate.ts` and `canonical.ts`.
6
+ */
7
+ import { canonicalJson } from './canonical.ts';
8
+ import { cutText, type KeepSide } from './truncate.ts';
9
+
10
+ /** Per-key caps in characters. */
11
+ export const INPUT_CAPS: Readonly<Record<string, number>> = {
12
+ project: 1024,
13
+ tool: 512,
14
+ task: 4000,
15
+ history: 8000,
16
+ request: 8000,
17
+ command: 8000,
18
+ prompt: 6000,
19
+ lastMessage: 6000,
20
+ subject: 4096,
21
+ };
22
+
23
+ const DEFAULT_CAP = 6000;
24
+
25
+ /** Keys whose most recent end matters more than the start. */
26
+ const KEEP_TAIL = new Set(['history']);
27
+
28
+ function serialise(value: unknown): string {
29
+ try {
30
+ return typeof value === 'string' ? value : canonicalJson(value);
31
+ } catch {
32
+ return '';
33
+ }
34
+ }
35
+
36
+ function capValue(key: string, value: unknown): unknown {
37
+ const cap = INPUT_CAPS[key] ?? DEFAULT_CAP;
38
+ const text = serialise(value);
39
+ if (text.length <= cap) {
40
+ return value;
41
+ }
42
+ const keep: KeepSide = KEEP_TAIL.has(key) ? 'tail' : 'ends';
43
+ return cutText(text, cap, keep);
44
+ }
45
+
46
+ /**
47
+ * Cap every key of a policy input. Strings over their cap keep both ends (`history` keeps its
48
+ * tail) with the truncation marker; objects are serialised canonically first. A `subject` over
49
+ * its cap is dropped, which disables precedent for that call rather than matching a cut subject.
50
+ * Objects within their cap are kept as they are; numbers and booleans pass through.
51
+ */
52
+ export function capInput(input: Readonly<Record<string, unknown>>): Record<string, unknown> {
53
+ const out: Record<string, unknown> = {};
54
+ for (const [key, value] of Object.entries(input)) {
55
+ if (
56
+ value === undefined ||
57
+ value === null ||
58
+ (typeof value !== 'object' && typeof value !== 'string')
59
+ ) {
60
+ out[key] = value;
61
+ } else if (key === 'subject') {
62
+ const text = serialise(value);
63
+ if (text.length <= (INPUT_CAPS['subject'] ?? DEFAULT_CAP)) {
64
+ out[key] = value;
65
+ }
66
+ } else {
67
+ out[key] = capValue(key, value);
68
+ }
69
+ }
70
+ return out;
71
+ }
@@ -0,0 +1,42 @@
1
+ /**
2
+ * The `permission` policy's input, built the same way for every client (the hook runner, the Claude
3
+ * Code mod and the Paseo plugin). No `node:` imports: the Paseo plugin vendors this file with
4
+ * `input-cap.ts`, `truncate.ts` and `canonical.ts`.
5
+ */
6
+ import { capInput } from './input-cap.ts';
7
+
8
+ /** `name (cwd)`: how the policies refer to the project. */
9
+ export function projectLabel(cwd: string): string {
10
+ // A loop, not `/\/+$/`, which backtracks quadratically on long runs of slashes.
11
+ let end = cwd.length;
12
+ while (end > 0 && cwd.charCodeAt(end - 1) === 0x2f) {
13
+ end -= 1;
14
+ }
15
+ const name = cwd.slice(0, end).split('/').at(-1) ?? '';
16
+ return `${name === '' ? cwd : name} (${cwd})`;
17
+ }
18
+
19
+ export interface PermissionInputParts {
20
+ readonly cwd?: string | undefined;
21
+ readonly tool?: string | undefined;
22
+ readonly request: unknown;
23
+ readonly subject?: string | undefined;
24
+ /** Recent conversation and the task text, already rendered by the client. */
25
+ readonly history?: string | undefined;
26
+ readonly task?: string | undefined;
27
+ }
28
+
29
+ /** Keys the policy's `state.sections` read, capped per key; empty values are left out. */
30
+ export function buildPermissionInput(parts: PermissionInputParts): Record<string, unknown> {
31
+ const input: Record<string, unknown> = {
32
+ project: parts.cwd === undefined ? undefined : projectLabel(parts.cwd),
33
+ history: parts.history,
34
+ task: parts.task,
35
+ tool: parts.tool,
36
+ request: parts.request,
37
+ subject: parts.subject,
38
+ };
39
+ return capInput(
40
+ Object.fromEntries(Object.entries(input).filter(([, v]) => v !== undefined && v !== '')),
41
+ );
42
+ }