talentos 1.1.6 → 1.3.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,916 @@
1
+ import { ROOM_TOOLS } from "../codex-policy.js";
2
+ import { canonical, isInside, protectedPaths, protectedReason, reachesProtected, } from "./paths.js";
3
+ import { parseShell } from "./shell.js";
4
+ const NON_ALNUM = /[^A-Za-z\d]+/u;
5
+ const GREP_R_DIFF = /^-\w*r|^--recursive/u;
6
+ const GREP_R = /^-\w*[rR]|^--recursive|^--dereference-recursive/u;
7
+ const LS_R = /^-\w*R|^--recursive/u;
8
+ const PATTERN_FLAG = /^-\w*e|^--regexp|^-\w*f|^--file/u;
9
+ const GLOB_CHARS = /[*?[{]/u;
10
+ const PATH_IN_FLAG = /[/~]/u;
11
+ const ASK = "This needs the owner's approval, which isn't available yet. Tell the owner in your reply what you wanted to do and why. Do not retry or work around it.";
12
+ const BLOCKED = "Blocked: this touches credentials or the settings that protect this session. Do not retry or work around it.";
13
+ const allow = (mutates = false) => ({ allow: true, mutates });
14
+ const deny = (tier, reason) => ({
15
+ allow: false,
16
+ reason: reason ?? (tier === 0 ? BLOCKED : ASK),
17
+ tier,
18
+ });
19
+ const PLAIN_TOOLS = new Set([
20
+ "Agent",
21
+ "AskUserQuestion",
22
+ "BashOutput",
23
+ "ExitPlanMode",
24
+ "Glob",
25
+ "Grep",
26
+ "KillShell",
27
+ "LS",
28
+ "NotebookRead",
29
+ "Read",
30
+ "Skill",
31
+ "TaskCreate",
32
+ "TaskGet",
33
+ "TaskList",
34
+ "TaskStop",
35
+ "TaskUpdate",
36
+ "TodoWrite",
37
+ "ToolSearch",
38
+ "WebSearch",
39
+ ]);
40
+ const EDIT_TOOLS = new Set(["Edit", "MultiEdit", "NotebookEdit", "Write"]);
41
+ const READ_VERBS = new Set([
42
+ "count",
43
+ "describe",
44
+ "find",
45
+ "get",
46
+ "list",
47
+ "lookup",
48
+ "read",
49
+ "retrieve",
50
+ "search",
51
+ "show",
52
+ "view",
53
+ ]);
54
+ // Any of these anywhere in an MCP tool name makes it a write, whatever it starts
55
+ // with. Outward verbs also match their inflections (sends, sending, deleted, ...).
56
+ const OUTWARD_VERBS = [
57
+ "add",
58
+ "approve",
59
+ "archive",
60
+ "assign",
61
+ "cancel",
62
+ "close",
63
+ "comment",
64
+ "create",
65
+ "delete",
66
+ "deploy",
67
+ "destroy",
68
+ "edit",
69
+ "execute",
70
+ "forward",
71
+ "insert",
72
+ "invite",
73
+ "merge",
74
+ "move",
75
+ "post",
76
+ "publish",
77
+ "push",
78
+ "remove",
79
+ "rename",
80
+ "reply",
81
+ "revoke",
82
+ "run",
83
+ "send",
84
+ "set",
85
+ "share",
86
+ "submit",
87
+ "trash",
88
+ "trigger",
89
+ "update",
90
+ "upload",
91
+ "write",
92
+ ];
93
+ const OTHER_WRITE_WORDS = [
94
+ "accept",
95
+ "append",
96
+ "apply",
97
+ "clear",
98
+ "commit",
99
+ "confirm",
100
+ "disable",
101
+ "download",
102
+ "draft",
103
+ "enable",
104
+ "export",
105
+ "fire",
106
+ "import",
107
+ "invoke",
108
+ "kill",
109
+ "label",
110
+ "mark",
111
+ "notify",
112
+ "pin",
113
+ "ping",
114
+ "reject",
115
+ "reset",
116
+ "restore",
117
+ "schedule",
118
+ "sms",
119
+ "star",
120
+ "start",
121
+ "stop",
122
+ "sync",
123
+ "text",
124
+ "toggle",
125
+ "unpin",
126
+ "unsubscribe",
127
+ ];
128
+ const CONSONANT_VOWEL_CONSONANT = /[^aeiou][aeiou][^aeiouwy]$/u;
129
+ function inflections(verb) {
130
+ const stem = verb.endsWith("e") ? verb.slice(0, -1) : verb;
131
+ const doubled = CONSONANT_VOWEL_CONSONANT.test(verb)
132
+ ? `${verb}${verb.slice(-1)}`
133
+ : verb;
134
+ return [
135
+ verb,
136
+ `${verb}s`,
137
+ `${verb}es`,
138
+ `${verb}d`,
139
+ `${verb}ed`,
140
+ `${stem}ing`,
141
+ `${doubled}ing`,
142
+ `${doubled}ed`,
143
+ ];
144
+ }
145
+ const WRITE_WORDS = new Set([
146
+ ...OUTWARD_VERBS.flatMap(inflections),
147
+ ...OTHER_WRITE_WORDS,
148
+ ]);
149
+ /** Splits `search_emails`, `search-emails` and `searchEmails` into lower-case words. */
150
+ function nameWords(name) {
151
+ return name
152
+ .replace(/([a-z\d])([A-Z])/gu, "$1 $2")
153
+ .split(NON_ALNUM)
154
+ .filter(Boolean)
155
+ .map((word) => word.toLowerCase());
156
+ }
157
+ export function classifyMcpTool(server, tool) {
158
+ if (server === "talentos_room") {
159
+ return ROOM_TOOLS.includes(tool) ? allow() : deny(0);
160
+ }
161
+ // The owner's personal-key TalentOS server carries owner authority; a room
162
+ // job never gets it (it is also removed from the tool list at launch).
163
+ if (server === "talentos" || server.startsWith("talentos_")) {
164
+ return deny(0);
165
+ }
166
+ const words = nameWords(tool);
167
+ const [first] = words;
168
+ if (first !== undefined &&
169
+ READ_VERBS.has(first) &&
170
+ !words.some((word) => WRITE_WORDS.has(word))) {
171
+ return allow();
172
+ }
173
+ // Outward or unknown MCP tool: the owner may allow it once, or always for this
174
+ // exact tool. The name is the only identity the hook has.
175
+ return askDeny(ASK, {
176
+ detail: tool,
177
+ kind: `tool:mcp__${server}__${tool}`.slice(0, 80),
178
+ summary: `${server}: ${tool}`.slice(0, 200),
179
+ tier: 2,
180
+ });
181
+ }
182
+ const SECRET_WORDS = /(bearer\s+)\S+|((?:token|key|secret|password|passwd|auth)[=:]\s*)\S+/giu;
183
+ const LONG_BLOB = /\b[A-Za-z\d+/_-]{32,}\b/gu;
184
+ /** Owner-only summaries still never carry what looks like a credential. */
185
+ export function redactSummary(value) {
186
+ return value
187
+ .replace(SECRET_WORDS, (_m, bearer, named) => `${bearer ?? named}…`)
188
+ .replace(LONG_BLOB, "…")
189
+ .replace(/\s+/gu, " ")
190
+ .trim()
191
+ .slice(0, 200);
192
+ }
193
+ const askDeny = (reason, ask) => ({
194
+ allow: false,
195
+ ask,
196
+ reason,
197
+ tier: ask.tier,
198
+ });
199
+ // ---- shell ----------------------------------------------------------------
200
+ const SECRET_PROGRAMS = new Set([
201
+ "env",
202
+ "export",
203
+ "gpg",
204
+ "history",
205
+ "op",
206
+ "pass",
207
+ "printenv",
208
+ "security",
209
+ "set",
210
+ "ssh-add",
211
+ "ssh-keygen",
212
+ ]);
213
+ const READ_ONLY = {
214
+ awk: { paths: "after-pattern", valid: awkIsPrint },
215
+ basename: { paths: "none" },
216
+ cat: { paths: "all" },
217
+ column: { paths: "all" },
218
+ comm: { paths: "all" },
219
+ cut: { paths: "all" },
220
+ date: { badFlags: /^-s|^--set/u, paths: "none" },
221
+ df: { paths: "all" },
222
+ diff: {
223
+ paths: "all",
224
+ recursive: (a) => a.some((x) => GREP_R_DIFF.test(x)),
225
+ },
226
+ dirname: { paths: "none" },
227
+ du: { paths: "all", recursive: () => true },
228
+ echo: { paths: "none" },
229
+ false: { paths: "none" },
230
+ file: { badFlags: /^-C|^-m|^--magic/u, paths: "all" },
231
+ fold: { paths: "all" },
232
+ find: {
233
+ badFlags: /^-(exec|execdir|ok|okdir|delete|fprint0?|fprintf|fls)$/u,
234
+ paths: "find",
235
+ recursive: () => true,
236
+ },
237
+ grep: {
238
+ paths: "after-pattern",
239
+ recursive: (a) => a.some((x) => GREP_R.test(x)),
240
+ },
241
+ head: { paths: "all" },
242
+ hexdump: { paths: "all" },
243
+ hostname: { paths: "none" },
244
+ id: { paths: "none" },
245
+ jq: { paths: "after-pattern", valid: jqIsRead },
246
+ ls: {
247
+ paths: "all",
248
+ recursive: (a) => a.some((x) => LS_R.test(x)),
249
+ },
250
+ md5sum: { paths: "all" },
251
+ nl: { paths: "all" },
252
+ od: { paths: "all" },
253
+ paste: { paths: "all" },
254
+ printf: { paths: "none" },
255
+ pwd: { paths: "none" },
256
+ readlink: { paths: "all" },
257
+ realpath: { paths: "all" },
258
+ rg: {
259
+ badFlags: /^--pre|^-z$|^--search-zip|^--hostname-bin/u,
260
+ paths: "after-pattern",
261
+ recursive: () => true,
262
+ },
263
+ rev: { paths: "all" },
264
+ sed: { paths: "after-pattern", valid: sedIsPrint },
265
+ sha1sum: { paths: "all" },
266
+ sha256sum: { paths: "all" },
267
+ shasum: { paths: "all" },
268
+ sleep: { paths: "none" },
269
+ sort: { badFlags: /^-o|^--output|^--compress-program/u, paths: "all" },
270
+ stat: { paths: "all" },
271
+ tac: { paths: "all" },
272
+ tail: { badFlags: /^-\w*f|^--follow/u, paths: "all" },
273
+ test: { paths: "all" },
274
+ tr: { paths: "none" },
275
+ tree: { badFlags: /^-o$/u, paths: "all", recursive: () => true },
276
+ true: { paths: "none" },
277
+ uname: { paths: "none" },
278
+ uniq: { paths: "all" },
279
+ wc: { paths: "all" },
280
+ which: { paths: "none" },
281
+ whoami: { paths: "none" },
282
+ xxd: { paths: "all" },
283
+ };
284
+ // sed, awk and jq can run code or write files, so only plain "print what matches"
285
+ // scripts pass; anything else is an ordinary ask. The script is the first
286
+ // positional word; the rest are files.
287
+ const SED_FLAGS = new Set(["-E", "-n", "-r", "-s", "--quiet", "--silent"]);
288
+ const SED_SCRIPT = /^(?:\d+|\$)(?:,(?:\d+|\$))?p$|^\/[^/]+\/p$|^s([^\\\n])(?:(?!\1)[^\\]|\\.)*\1(?:(?!\1)[^\\]|\\.)*\1[gIip]*$/u;
289
+ const AWK_SCRIPT = /^\{\s*print(?:\s+\$(?:\d+|NF))?(?:\s*,\s*\$(?:\d+|NF))*\s*\}$/u;
290
+ const AWK_FLAG = /^-F[^\w\s'"\\]$|^-F\\t$/u;
291
+ const JQ_FLAGS = new Set([
292
+ "-C",
293
+ "-M",
294
+ "-S",
295
+ "-a",
296
+ "-c",
297
+ "-e",
298
+ "-j",
299
+ "-n",
300
+ "-r",
301
+ "-s",
302
+ "--compact-output",
303
+ "--exit-status",
304
+ "--join-output",
305
+ "--null-input",
306
+ "--raw-output",
307
+ "--slurp",
308
+ "--sort-keys",
309
+ ]);
310
+ // env/$ENV print secrets; input* and import read other files; debug/stderr leak.
311
+ const JQ_BAD_WORD = /\b(?:ENV|env|import|include|input|inputs|input_filename|debug|stderr|halt_error)\b/u;
312
+ function firstPositional(args) {
313
+ return args.find((word) => !isFlag(word));
314
+ }
315
+ function sedIsPrint(args) {
316
+ const script = firstPositional(args);
317
+ return (args.filter(isFlag).every((flag) => SED_FLAGS.has(flag.text)) &&
318
+ script !== undefined &&
319
+ !script.glob &&
320
+ SED_SCRIPT.test(script.text));
321
+ }
322
+ function awkIsPrint(args) {
323
+ const script = firstPositional(args);
324
+ return (args.filter(isFlag).every((flag) => AWK_FLAG.test(flag.text)) &&
325
+ script !== undefined &&
326
+ AWK_SCRIPT.test(script.text));
327
+ }
328
+ function jqIsRead(args) {
329
+ const script = firstPositional(args);
330
+ return (args.filter(isFlag).every((flag) => JQ_FLAGS.has(flag.text)) &&
331
+ script !== undefined &&
332
+ !JQ_BAD_WORD.test(script.text));
333
+ }
334
+ const RUNNER_SCRIPTS = new Set(["build", "check", "lint", "test", "typecheck"]);
335
+ const SAFE_ARG = /^--?[A-Za-z][\w-]*(=[\w./:@-]+)?$|^--$/u;
336
+ function isFlag(word) {
337
+ return word.text.startsWith("-") && word.text !== "-";
338
+ }
339
+ // A flag can carry a path: `--files0-from=/x`, `--file=/x`, `-f/x`. Each one is
340
+ // read like a positional path, so a protected file cannot hide in a flag value.
341
+ function flagPathWords(args) {
342
+ const words = [];
343
+ for (const word of args.filter(isFlag)) {
344
+ const equals = word.text.indexOf("=");
345
+ const start = equals > 0 ? equals + 1 : word.text.slice(2).search(PATH_IN_FLAG) + 2;
346
+ if (start > (equals > 0 ? 0 : 1) && start < word.text.length) {
347
+ words.push({ glob: word.glob, text: word.text.slice(start) });
348
+ }
349
+ }
350
+ return words;
351
+ }
352
+ function pathCheck(word, ctx, recursive) {
353
+ if (word.glob) {
354
+ // A glob can only be judged by its literal directory; keep it inside cwd.
355
+ if (word.text.startsWith("/") ||
356
+ word.text.startsWith("~") ||
357
+ word.text.split("/").includes("..")) {
358
+ return deny(1, "This command uses a pattern the hook cannot check. Ask the owner.");
359
+ }
360
+ return;
361
+ }
362
+ const real = canonical(word.text, ctx.cwd, ctx.home);
363
+ if (protectedReason(real, "read", ctx.home, ctx.guard)) {
364
+ return deny(0);
365
+ }
366
+ if (recursive && reachesProtected(real, ctx.home, ctx.guard)) {
367
+ return deny(0);
368
+ }
369
+ return;
370
+ }
371
+ function classifyReadOnly(spec, args, ctx) {
372
+ const flags = args.filter(isFlag).map((word) => word.text);
373
+ if (spec.badFlags && flags.some((flag) => spec.badFlags?.test(flag))) {
374
+ return deny(2);
375
+ }
376
+ if (spec.valid && !spec.valid(args)) {
377
+ return deny(2);
378
+ }
379
+ for (const word of flagPathWords(args)) {
380
+ const refused = pathCheck(word, ctx, false);
381
+ if (refused) {
382
+ return refused;
383
+ }
384
+ }
385
+ const recursive = spec.recursive?.(flags) ?? false;
386
+ let targets = [];
387
+ if (spec.paths === "all") {
388
+ targets = args.filter((word) => !isFlag(word));
389
+ }
390
+ else if (spec.paths === "after-pattern") {
391
+ const positional = args.filter((word) => !isFlag(word));
392
+ const patternGiven = flags.some((flag) => PATTERN_FLAG.test(flag));
393
+ targets = patternGiven ? positional : positional.slice(1);
394
+ }
395
+ else if (spec.paths === "find") {
396
+ const leading = [];
397
+ for (const word of args) {
398
+ if (isFlag(word) || word.text === "(" || word.text === "!") {
399
+ break;
400
+ }
401
+ leading.push(word);
402
+ }
403
+ targets = leading;
404
+ }
405
+ if (recursive && targets.length === 0) {
406
+ targets = [{ glob: false, text: "." }];
407
+ }
408
+ for (const target of targets) {
409
+ const refused = pathCheck(target, ctx, recursive);
410
+ if (refused) {
411
+ return refused;
412
+ }
413
+ }
414
+ // `echo $x > file` style writes are handled as redirects by the caller.
415
+ return allow();
416
+ }
417
+ function classifyRunner(args, ctx) {
418
+ const [first, second, third] = args.map((word) => word.text);
419
+ let rest;
420
+ if (first !== undefined &&
421
+ ["npm", "pnpm", "yarn"].includes(first) &&
422
+ ((second !== undefined && RUNNER_SCRIPTS.has(second)) ||
423
+ (second === "run" && third !== undefined && RUNNER_SCRIPTS.has(third)))) {
424
+ rest = args.slice(second === "run" ? 3 : 2);
425
+ }
426
+ else if (first === "pytest") {
427
+ rest = args.slice(1);
428
+ }
429
+ else if (first !== undefined &&
430
+ ["go", "cargo"].includes(first) &&
431
+ second === "test") {
432
+ rest = args.slice(2);
433
+ }
434
+ else {
435
+ return;
436
+ }
437
+ // Runners execute repository code. That is the owner's own repo until the
438
+ // model has changed it; after an edit, a run asks (R5).
439
+ if (ctx.dirty) {
440
+ return deny(2, "You changed files in this job, so running tests or builds needs the owner's approval, which isn't available yet. Tell the owner what you changed and how to run it.");
441
+ }
442
+ for (const word of rest) {
443
+ if (isFlag(word) || word.text === "--") {
444
+ if (!SAFE_ARG.test(word.text)) {
445
+ return deny(2);
446
+ }
447
+ continue;
448
+ }
449
+ const real = canonical(word.text, ctx.cwd, ctx.home);
450
+ if (word.glob ||
451
+ protectedReason(real, "read", ctx.home, ctx.guard) ||
452
+ !ctx.writeRoots.some((root) => isInside(real, root))) {
453
+ return deny(2);
454
+ }
455
+ }
456
+ return allow();
457
+ }
458
+ // Read-only git. Flags that run programs, write files or read outside the
459
+ // repository are refused; anything that changes a ref or the network is not here.
460
+ const GIT_READ = new Set([
461
+ "blame",
462
+ "branch",
463
+ "cat-file",
464
+ "describe",
465
+ "diff",
466
+ "diff-tree",
467
+ "for-each-ref",
468
+ "grep",
469
+ "log",
470
+ "ls-files",
471
+ "ls-tree",
472
+ "merge-base",
473
+ "name-rev",
474
+ "reflog",
475
+ "remote",
476
+ "rev-list",
477
+ "rev-parse",
478
+ "shortlog",
479
+ "show",
480
+ "show-ref",
481
+ "stash",
482
+ "status",
483
+ "tag",
484
+ "worktree",
485
+ ]);
486
+ const GIT_BAD_FLAG = /^(--output|-c$|-C$|--config-env|--exec-path|--upload-pack|--git-dir|--work-tree|--no-index|--ext-diff|--textconv|--filters|--open-files-in-pager|-O)/u;
487
+ const GIT_LIST_FLAG = /^(-a|-r|-v|-vv|--all|--remotes|--list|--show-current)$/u;
488
+ // Global options that cannot run anything. -c, --config-env, --exec-path and
489
+ // aliases can, so they stay asks; GIT_* env assignments never parse.
490
+ const GIT_GLOBAL_OK = new Set([
491
+ "--literal-pathspecs",
492
+ "--no-optional-locks",
493
+ "--no-pager",
494
+ "-P",
495
+ ]);
496
+ const GIT_DIR_FLAG = /^--(?:git-dir|work-tree)=(.+)$/u;
497
+ // `git [globals] <sub> ...`: only the globals above are understood.
498
+ function splitGit(args) {
499
+ const dirs = [];
500
+ let index = 0;
501
+ while (index < args.length && isFlag(args[index])) {
502
+ const word = args[index];
503
+ const next = args[index + 1];
504
+ const attached = GIT_DIR_FLAG.exec(word.text);
505
+ if (GIT_GLOBAL_OK.has(word.text)) {
506
+ index += 1;
507
+ }
508
+ else if (attached?.[1]) {
509
+ dirs.push({ chdir: false, word: { glob: word.glob, text: attached[1] } });
510
+ index += 1;
511
+ }
512
+ else if (["-C", "--git-dir", "--work-tree"].includes(word.text) &&
513
+ next &&
514
+ !isFlag(next)) {
515
+ dirs.push({ chdir: word.text === "-C", word: next });
516
+ index += 2;
517
+ }
518
+ else {
519
+ return { dirs, ok: false, rest: [] };
520
+ }
521
+ }
522
+ return { dirs, ok: true, rest: args.slice(index + 1), sub: args[index] };
523
+ }
524
+ // Subcommands that also write take a read-only form: check it.
525
+ function gitSubIsRead(sub, rest) {
526
+ const flags = rest.filter(isFlag).map((word) => word.text);
527
+ const positional = rest.filter((word) => !isFlag(word)).map((w) => w.text);
528
+ switch (sub) {
529
+ case "branch":
530
+ // `git branch NAME` creates a branch; only the listing forms pass.
531
+ return (positional.length === 0 && flags.every((f) => GIT_LIST_FLAG.test(f)));
532
+ case "tag":
533
+ return flags.some((f) => f === "-l" || f === "--list");
534
+ case "remote":
535
+ return (flags.every((f) => f === "-v" || f === "--verbose") &&
536
+ (positional.length === 0 || positional[0] === "get-url"));
537
+ case "stash":
538
+ return positional[0] === "list" || positional[0] === "show";
539
+ case "worktree":
540
+ return positional[0] === "list";
541
+ case "reflog":
542
+ return positional.length === 0 || positional[0] === "show";
543
+ default:
544
+ return true;
545
+ }
546
+ }
547
+ function classifyGit(args, ctx) {
548
+ const git = splitGit(args);
549
+ const { sub, rest } = git;
550
+ if (!(git.ok && sub && GIT_READ.has(sub.text))) {
551
+ return deny(2);
552
+ }
553
+ const flags = rest.filter(isFlag);
554
+ if (flags.some((flag) => GIT_BAD_FLAG.test(flag.text)) ||
555
+ !gitSubIsRead(sub.text, rest)) {
556
+ return deny(2);
557
+ }
558
+ for (const word of flagPathWords(rest)) {
559
+ const refused = pathCheck(word, ctx, false);
560
+ if (refused) {
561
+ return refused;
562
+ }
563
+ }
564
+ // `-C dir` and friends read that path: the same check as `cat dir/x`. Later
565
+ // paths resolve against the directory `-C` moved into.
566
+ let local = ctx;
567
+ for (const { chdir, word } of git.dirs) {
568
+ const refused = pathCheck(word, local, false);
569
+ if (refused) {
570
+ return refused;
571
+ }
572
+ if (chdir) {
573
+ local = { ...local, cwd: canonical(word.text, local.cwd, local.home) };
574
+ }
575
+ }
576
+ for (const word of rest.filter((word) => !isFlag(word))) {
577
+ const refused = pathCheck(word, local, false);
578
+ if (refused) {
579
+ return refused;
580
+ }
581
+ }
582
+ return allow();
583
+ }
584
+ // What an always-allow rule can name: local repository work the owner expects
585
+ // from a coding agent. Network, interpreters, installs and anything else ask
586
+ // every time (tier 1).
587
+ const GIT_TIER2 = new Set([
588
+ "add",
589
+ "checkout",
590
+ "clone",
591
+ "commit",
592
+ "fetch",
593
+ "pull",
594
+ "push",
595
+ "restore",
596
+ "stash",
597
+ "switch",
598
+ ]);
599
+ const PROTECTED_BRANCH = /^(?:main|master|trunk|develop|dev|release|production|prod|stable)$|^release[/-]/u;
600
+ const PUSH_RISKY_FLAG = /^(-f$|--force|--delete$|-d$|--mirror|--all$|--prune)/u;
601
+ const HEADS_PREFIX = /^refs\/heads\//u;
602
+ const FILE_UTILS = new Set(["cp", "mkdir", "mv", "touch"]);
603
+ function gitPushTier(args) {
604
+ const rest = args.slice(1);
605
+ const flags = rest.filter(isFlag).map((word) => word.text);
606
+ if (flags.some((flag) => PUSH_RISKY_FLAG.test(flag))) {
607
+ return 1;
608
+ }
609
+ const positional = rest
610
+ .filter((word) => !isFlag(word))
611
+ .map((word) => word.text);
612
+ const refspec = positional[1];
613
+ if (!refspec || refspec.startsWith("+") || refspec.startsWith(":")) {
614
+ return 1;
615
+ }
616
+ const target = refspec.includes(":")
617
+ ? (refspec.split(":")[1] ?? "")
618
+ : refspec;
619
+ const branch = target.replace(HEADS_PREFIX, "");
620
+ return branch.startsWith("talentos/") && !PROTECTED_BRANCH.test(branch)
621
+ ? 2
622
+ : 1;
623
+ }
624
+ function shellAsk(command, ctx) {
625
+ const [programWord, ...args] = command.argv;
626
+ const program = programWord?.text ?? "?";
627
+ if (command.redirects.some((redirect) => redirect.mode === "write" &&
628
+ redirect.target.text !== "/dev/null" &&
629
+ !ctx.writeRoots.some((root) => isInside(canonical(redirect.target.text, ctx.cwd, ctx.home), root)))) {
630
+ return { kind: "shell:redirect-outside", tier: 1 };
631
+ }
632
+ if (program.includes("/")) {
633
+ return { kind: "shell:script", tier: 1 };
634
+ }
635
+ if (program === "git") {
636
+ const git = splitGit(args);
637
+ const sub = git.ok ? (git.sub?.text ?? "") : "";
638
+ const badFlag = git.rest.some((word) => isFlag(word) && GIT_BAD_FLAG.test(word.text));
639
+ // A change to another repository is not the workspace's own work.
640
+ const elsewhere = git.dirs.some(({ word }) => word.glob ||
641
+ !ctx.writeRoots.some((root) => isInside(canonical(word.text, ctx.cwd, ctx.home), root)));
642
+ if (!(git.ok && GIT_TIER2.has(sub)) || badFlag || elsewhere) {
643
+ return { kind: `git:${sub || "?"}`, tier: 1 };
644
+ }
645
+ return {
646
+ kind: `git:${sub}`,
647
+ tier: sub === "push" ? gitPushTier([git.sub, ...git.rest]) : 2,
648
+ };
649
+ }
650
+ if (FILE_UTILS.has(program)) {
651
+ const inside = args
652
+ .filter((word) => !isFlag(word))
653
+ .every((word) => !word.glob &&
654
+ ctx.writeRoots.some((root) => isInside(canonical(word.text, ctx.cwd, ctx.home), root)) &&
655
+ !protectedReason(canonical(word.text, ctx.cwd, ctx.home), "write", ctx.home, ctx.guard));
656
+ return { kind: `shell:${program}`, tier: inside ? 2 : 1 };
657
+ }
658
+ const [first, second, third] = command.argv.map((word) => word.text);
659
+ if (ctx.dirty &&
660
+ ["npm", "pnpm", "yarn"].includes(first ?? "") &&
661
+ (RUNNER_SCRIPTS.has(second ?? "") ||
662
+ (second === "run" && RUNNER_SCRIPTS.has(third ?? "")))) {
663
+ return {
664
+ kind: `run:${first} ${second === "run" ? third : second}`,
665
+ tier: 1,
666
+ };
667
+ }
668
+ if (ctx.dirty &&
669
+ (first === "pytest" ||
670
+ (["go", "cargo"].includes(first ?? "") && second === "test"))) {
671
+ return {
672
+ kind: `run:${first}${first === "pytest" ? "" : " test"}`,
673
+ tier: 1,
674
+ };
675
+ }
676
+ return { kind: `shell:${program}`, tier: 1 };
677
+ }
678
+ const VERSION_PROGRAMS = new Set([
679
+ "bun",
680
+ "cargo",
681
+ "claude",
682
+ "deno",
683
+ "git",
684
+ "node",
685
+ "npm",
686
+ "pip",
687
+ "pip3",
688
+ "pnpm",
689
+ "python",
690
+ "python3",
691
+ "rustc",
692
+ "yarn",
693
+ ]);
694
+ // `node --version`, `go version`: asking a tool who it is runs nothing else.
695
+ function isVersionQuery(program, args) {
696
+ if (args.length !== 1) {
697
+ return false;
698
+ }
699
+ const only = args[0]?.text;
700
+ return ((VERSION_PROGRAMS.has(program) &&
701
+ (only === "--version" || only === "-v" || only === "-V")) ||
702
+ (program === "go" && only === "version"));
703
+ }
704
+ // Another repository's attributes, config and submodule map pick the programs
705
+ // git runs for a diff, a filter or a fetch. Outside this job's workspace they
706
+ // are never written (R13); inside it they are the owner's own repo.
707
+ const GIT_CONTROL_FILE = /(?:^|\/)(?:\.gitattributes|\.gitmodules|\.git\/config|\.git\/info\/attributes)$/iu;
708
+ function gitControlFile(real, ctx) {
709
+ return (GIT_CONTROL_FILE.test(real) &&
710
+ !ctx.writeRoots.some((root) => isInside(real, root)));
711
+ }
712
+ function classifySimple(command, ctx) {
713
+ const [programWord, ...args] = command.argv;
714
+ if (!programWord) {
715
+ return deny(1);
716
+ }
717
+ const program = programWord.text;
718
+ if (program.includes("/") || programWord.glob) {
719
+ return deny(2);
720
+ }
721
+ let verdict;
722
+ if (SECRET_PROGRAMS.has(program)) {
723
+ verdict = deny(0);
724
+ }
725
+ else if (isVersionQuery(program, args)) {
726
+ verdict = allow();
727
+ }
728
+ else if (FILE_UTILS.has(program) &&
729
+ args.some((word) => !(isFlag(word) || word.glob) &&
730
+ gitControlFile(canonical(word.text, ctx.cwd, ctx.home), ctx))) {
731
+ verdict = deny(0);
732
+ }
733
+ else {
734
+ const spec = READ_ONLY[program];
735
+ if (program === "git") {
736
+ verdict = classifyGit(args, ctx);
737
+ }
738
+ else {
739
+ verdict = spec
740
+ ? classifyReadOnly(spec, args, ctx)
741
+ : (classifyRunner(command.argv, ctx) ?? deny(2));
742
+ }
743
+ }
744
+ if (!verdict.allow) {
745
+ return verdict;
746
+ }
747
+ let mutates = false;
748
+ for (const redirect of command.redirects) {
749
+ if (redirect.mode === "read") {
750
+ const refused = pathCheck(redirect.target, ctx, false);
751
+ if (refused) {
752
+ return refused;
753
+ }
754
+ continue;
755
+ }
756
+ if (redirect.target.text === "/dev/null") {
757
+ continue;
758
+ }
759
+ const real = canonical(redirect.target.text, ctx.cwd, ctx.home);
760
+ if (protectedReason(real, "write", ctx.home, ctx.guard) ||
761
+ gitControlFile(real, ctx)) {
762
+ return deny(0);
763
+ }
764
+ if (redirect.target.glob ||
765
+ !ctx.writeRoots.some((root) => isInside(real, root))) {
766
+ return deny(2);
767
+ }
768
+ mutates = true;
769
+ }
770
+ return allow(mutates);
771
+ }
772
+ function changeDirectory(command, ctx) {
773
+ const [program, target, ...extra] = command.argv;
774
+ if (program?.text !== "cd" ||
775
+ extra.length > 0 ||
776
+ command.redirects.length > 0 ||
777
+ !target ||
778
+ target.glob ||
779
+ target.text === "-" ||
780
+ isFlag(target)) {
781
+ return;
782
+ }
783
+ const refused = pathCheck(target, ctx, false);
784
+ if (refused) {
785
+ return refused.allow || refused.tier !== 0 ? undefined : refused;
786
+ }
787
+ return {
788
+ moved: { ...ctx, cwd: canonical(target.text, ctx.cwd, ctx.home) },
789
+ };
790
+ }
791
+ export function classifyShell(source, ctx) {
792
+ const parsed = parseShell(source);
793
+ const summary = redactSummary(source);
794
+ if (!parsed.ok) {
795
+ return askDeny("The hook could not read this command safely. Use a simpler command, or ask the owner.", { detail: source, kind: "shell:unparseable", summary, tier: 1 });
796
+ }
797
+ let mutates = false;
798
+ let worst;
799
+ const asked = [];
800
+ let here = ctx;
801
+ for (const command of parsed.commands) {
802
+ // `cd dir && ...`: later paths resolve from there. A target the reader
803
+ // cannot judge falls through to the ordinary ask for `cd`.
804
+ const moved = changeDirectory(command, here);
805
+ if (moved) {
806
+ if (!("moved" in moved)) {
807
+ return moved;
808
+ }
809
+ here = moved.moved;
810
+ continue;
811
+ }
812
+ const verdict = classifySimple(command, here);
813
+ if (verdict.allow) {
814
+ mutates ||= verdict.mutates;
815
+ continue;
816
+ }
817
+ if (verdict.tier === 0) {
818
+ return verdict;
819
+ }
820
+ asked.push(shellAsk(command, here));
821
+ if (!worst || (!worst.allow && verdict.tier < worst.tier)) {
822
+ worst = verdict;
823
+ }
824
+ }
825
+ if (!worst || worst.allow) {
826
+ return allow(mutates);
827
+ }
828
+ // One ask covers the whole command. Its tier is the strictest part's, and its
829
+ // kind names every part, so a rule for one program never covers a chain.
830
+ const kinds = [...new Set(asked.map((entry) => entry.kind))].sort();
831
+ const joined = kinds.join(" + ");
832
+ const kind = joined.length <= 80 ? joined : `${kinds[0]} +${kinds.length - 1}`;
833
+ const tier = Math.min(...asked.map((entry) => entry.tier));
834
+ return { ...worst, ask: { detail: source, kind, summary, tier }, tier };
835
+ }
836
+ // ---- tools ----------------------------------------------------------------
837
+ function text(value) {
838
+ return typeof value === "string" && value.length > 0 ? value : undefined;
839
+ }
840
+ export function classifyCall(call, context) {
841
+ const guard = context.guard ?? protectedPaths(context.home);
842
+ const ctx = { ...context, guard, cwd: call.cwd };
843
+ const { tool, toolInput: input } = call;
844
+ if (tool.startsWith("mcp__")) {
845
+ const [, server, ...rest] = tool.split("__");
846
+ return server && rest.length > 0
847
+ ? classifyMcpTool(server, rest.join("__"))
848
+ : deny(2);
849
+ }
850
+ if (tool === "Bash") {
851
+ const command = text(input.command);
852
+ return command ? classifyShell(command, ctx) : deny(1);
853
+ }
854
+ if (EDIT_TOOLS.has(tool)) {
855
+ const target = text(input.file_path) ?? text(input.notebook_path);
856
+ if (!target) {
857
+ return deny(1);
858
+ }
859
+ const real = canonical(target, call.cwd, context.home);
860
+ if (protectedReason(real, "write", context.home, guard) ||
861
+ gitControlFile(real, context)) {
862
+ return deny(0);
863
+ }
864
+ return context.writeRoots.some((root) => isInside(real, root))
865
+ ? allow(true)
866
+ : askDeny("That file is outside this job's workspace. Needs the owner's approval.", {
867
+ detail: `${tool} ${real}`,
868
+ kind: "write-outside-workspace",
869
+ summary: redactSummary(`${tool} ${real}`),
870
+ tier: 1,
871
+ });
872
+ }
873
+ if (PLAIN_TOOLS.has(tool)) {
874
+ const raw = text(input.file_path) ?? text(input.notebook_path) ?? text(input.path);
875
+ const recursive = tool === "Grep" || tool === "Glob" || tool === "LS";
876
+ const patternPath = tool === "Glob" ? text(input.pattern) : undefined;
877
+ for (const candidate of [
878
+ raw ?? (recursive ? "." : undefined),
879
+ patternPath,
880
+ ]) {
881
+ if (candidate === undefined) {
882
+ continue;
883
+ }
884
+ // A glob pattern is judged by its literal directory prefix.
885
+ const literal = candidate.split(GLOB_CHARS)[0] ?? candidate;
886
+ const refused = pathCheck({ glob: false, text: literal === "" ? "." : literal }, ctx, recursive);
887
+ if (refused) {
888
+ return refused;
889
+ }
890
+ }
891
+ return allow();
892
+ }
893
+ // WebFetch (a GET carries data; rules are per domain), scheduling, messaging,
894
+ // worktree switches and every tool this list does not know: ask.
895
+ if (tool === "WebFetch") {
896
+ let host;
897
+ try {
898
+ host = new URL(text(input.url) ?? "").hostname.toLowerCase();
899
+ }
900
+ catch {
901
+ host = undefined;
902
+ }
903
+ return askDeny(ASK, {
904
+ detail: text(input.url) ?? "",
905
+ kind: host ? `web:${host}`.slice(0, 80) : "web:?",
906
+ summary: redactSummary(text(input.url) ?? ""),
907
+ tier: host ? 2 : 1,
908
+ });
909
+ }
910
+ return askDeny(ASK, {
911
+ detail: JSON.stringify(input).slice(0, 4000),
912
+ kind: `tool:${tool}`.slice(0, 80),
913
+ summary: redactSummary(`${tool} ${JSON.stringify(input)}`),
914
+ tier: 1,
915
+ });
916
+ }