talentos 1.2.0 → 1.4.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.
@@ -1,4 +1,4 @@
1
- import { ROOM_TOOLS } from "../codex-policy.js";
1
+ import { ROOM_LOCAL_TOOLS, ROOM_TOOLS } from "../codex-policy.js";
2
2
  import { canonical, isInside, protectedPaths, protectedReason, reachesProtected, } from "./paths.js";
3
3
  import { parseShell } from "./shell.js";
4
4
  const NON_ALNUM = /[^A-Za-z\d]+/u;
@@ -7,6 +7,7 @@ const GREP_R = /^-\w*[rR]|^--recursive|^--dereference-recursive/u;
7
7
  const LS_R = /^-\w*R|^--recursive/u;
8
8
  const PATTERN_FLAG = /^-\w*e|^--regexp|^-\w*f|^--file/u;
9
9
  const GLOB_CHARS = /[*?[{]/u;
10
+ const PATH_IN_FLAG = /[/~]/u;
10
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.";
11
12
  const BLOCKED = "Blocked: this touches credentials or the settings that protect this session. Do not retry or work around it.";
12
13
  const allow = (mutates = false) => ({ allow: true, mutates });
@@ -155,7 +156,12 @@ function nameWords(name) {
155
156
  }
156
157
  export function classifyMcpTool(server, tool) {
157
158
  if (server === "talentos_room") {
158
- return ROOM_TOOLS.includes(tool) ? allow() : deny(0);
159
+ // run_command reaches our local proxy, which classifies the command itself
160
+ // (the parity of Claude's Bash). Letting the MCP call through here, rather
161
+ // than classifying the command twice, keeps one gate and one ask.
162
+ return ROOM_TOOLS.includes(tool) || ROOM_LOCAL_TOOLS.includes(tool)
163
+ ? allow()
164
+ : deny(0);
159
165
  }
160
166
  // The owner's personal-key TalentOS server carries owner authority; a room
161
167
  // job never gets it (it is also removed from the tool list at launch).
@@ -210,8 +216,11 @@ const SECRET_PROGRAMS = new Set([
210
216
  "ssh-keygen",
211
217
  ]);
212
218
  const READ_ONLY = {
219
+ awk: { paths: "after-pattern", valid: awkIsPrint },
213
220
  basename: { paths: "none" },
214
221
  cat: { paths: "all" },
222
+ column: { paths: "all" },
223
+ comm: { paths: "all" },
215
224
  cut: { paths: "all" },
216
225
  date: { badFlags: /^-s|^--set/u, paths: "none" },
217
226
  df: { paths: "all" },
@@ -224,6 +233,7 @@ const READ_ONLY = {
224
233
  echo: { paths: "none" },
225
234
  false: { paths: "none" },
226
235
  file: { badFlags: /^-C|^-m|^--magic/u, paths: "all" },
236
+ fold: { paths: "all" },
227
237
  find: {
228
238
  badFlags: /^-(exec|execdir|ok|okdir|delete|fprint0?|fprintf|fls)$/u,
229
239
  paths: "find",
@@ -234,10 +244,18 @@ const READ_ONLY = {
234
244
  recursive: (a) => a.some((x) => GREP_R.test(x)),
235
245
  },
236
246
  head: { paths: "all" },
247
+ hexdump: { paths: "all" },
248
+ hostname: { paths: "none" },
249
+ id: { paths: "none" },
250
+ jq: { paths: "after-pattern", valid: jqIsRead },
237
251
  ls: {
238
252
  paths: "all",
239
253
  recursive: (a) => a.some((x) => LS_R.test(x)),
240
254
  },
255
+ md5sum: { paths: "all" },
256
+ nl: { paths: "all" },
257
+ od: { paths: "all" },
258
+ paste: { paths: "all" },
241
259
  printf: { paths: "none" },
242
260
  pwd: { paths: "none" },
243
261
  readlink: { paths: "all" },
@@ -247,21 +265,95 @@ const READ_ONLY = {
247
265
  paths: "after-pattern",
248
266
  recursive: () => true,
249
267
  },
268
+ rev: { paths: "all" },
269
+ sed: { paths: "after-pattern", valid: sedIsPrint },
270
+ sha1sum: { paths: "all" },
271
+ sha256sum: { paths: "all" },
272
+ shasum: { paths: "all" },
273
+ sleep: { paths: "none" },
250
274
  sort: { badFlags: /^-o|^--output|^--compress-program/u, paths: "all" },
251
275
  stat: { paths: "all" },
276
+ tac: { paths: "all" },
252
277
  tail: { badFlags: /^-\w*f|^--follow/u, paths: "all" },
278
+ test: { paths: "all" },
253
279
  tr: { paths: "none" },
254
280
  tree: { badFlags: /^-o$/u, paths: "all", recursive: () => true },
255
281
  true: { paths: "none" },
282
+ uname: { paths: "none" },
256
283
  uniq: { paths: "all" },
257
284
  wc: { paths: "all" },
258
285
  which: { paths: "none" },
286
+ whoami: { paths: "none" },
287
+ xxd: { paths: "all" },
259
288
  };
289
+ // sed, awk and jq can run code or write files, so only plain "print what matches"
290
+ // scripts pass; anything else is an ordinary ask. The script is the first
291
+ // positional word; the rest are files.
292
+ const SED_FLAGS = new Set(["-E", "-n", "-r", "-s", "--quiet", "--silent"]);
293
+ const SED_SCRIPT = /^(?:\d+|\$)(?:,(?:\d+|\$))?p$|^\/[^/]+\/p$|^s([^\\\n])(?:(?!\1)[^\\]|\\.)*\1(?:(?!\1)[^\\]|\\.)*\1[gIip]*$/u;
294
+ const AWK_SCRIPT = /^\{\s*print(?:\s+\$(?:\d+|NF))?(?:\s*,\s*\$(?:\d+|NF))*\s*\}$/u;
295
+ const AWK_FLAG = /^-F[^\w\s'"\\]$|^-F\\t$/u;
296
+ const JQ_FLAGS = new Set([
297
+ "-C",
298
+ "-M",
299
+ "-S",
300
+ "-a",
301
+ "-c",
302
+ "-e",
303
+ "-j",
304
+ "-n",
305
+ "-r",
306
+ "-s",
307
+ "--compact-output",
308
+ "--exit-status",
309
+ "--join-output",
310
+ "--null-input",
311
+ "--raw-output",
312
+ "--slurp",
313
+ "--sort-keys",
314
+ ]);
315
+ // env/$ENV print secrets; input* and import read other files; debug/stderr leak.
316
+ const JQ_BAD_WORD = /\b(?:ENV|env|import|include|input|inputs|input_filename|debug|stderr|halt_error)\b/u;
317
+ function firstPositional(args) {
318
+ return args.find((word) => !isFlag(word));
319
+ }
320
+ function sedIsPrint(args) {
321
+ const script = firstPositional(args);
322
+ return (args.filter(isFlag).every((flag) => SED_FLAGS.has(flag.text)) &&
323
+ script !== undefined &&
324
+ !script.glob &&
325
+ SED_SCRIPT.test(script.text));
326
+ }
327
+ function awkIsPrint(args) {
328
+ const script = firstPositional(args);
329
+ return (args.filter(isFlag).every((flag) => AWK_FLAG.test(flag.text)) &&
330
+ script !== undefined &&
331
+ AWK_SCRIPT.test(script.text));
332
+ }
333
+ function jqIsRead(args) {
334
+ const script = firstPositional(args);
335
+ return (args.filter(isFlag).every((flag) => JQ_FLAGS.has(flag.text)) &&
336
+ script !== undefined &&
337
+ !JQ_BAD_WORD.test(script.text));
338
+ }
260
339
  const RUNNER_SCRIPTS = new Set(["build", "check", "lint", "test", "typecheck"]);
261
340
  const SAFE_ARG = /^--?[A-Za-z][\w-]*(=[\w./:@-]+)?$|^--$/u;
262
341
  function isFlag(word) {
263
342
  return word.text.startsWith("-") && word.text !== "-";
264
343
  }
344
+ // A flag can carry a path: `--files0-from=/x`, `--file=/x`, `-f/x`. Each one is
345
+ // read like a positional path, so a protected file cannot hide in a flag value.
346
+ function flagPathWords(args) {
347
+ const words = [];
348
+ for (const word of args.filter(isFlag)) {
349
+ const equals = word.text.indexOf("=");
350
+ const start = equals > 0 ? equals + 1 : word.text.slice(2).search(PATH_IN_FLAG) + 2;
351
+ if (start > (equals > 0 ? 0 : 1) && start < word.text.length) {
352
+ words.push({ glob: word.glob, text: word.text.slice(start) });
353
+ }
354
+ }
355
+ return words;
356
+ }
265
357
  function pathCheck(word, ctx, recursive) {
266
358
  if (word.glob) {
267
359
  // A glob can only be judged by its literal directory; keep it inside cwd.
@@ -286,6 +378,15 @@ function classifyReadOnly(spec, args, ctx) {
286
378
  if (spec.badFlags && flags.some((flag) => spec.badFlags?.test(flag))) {
287
379
  return deny(2);
288
380
  }
381
+ if (spec.valid && !spec.valid(args)) {
382
+ return deny(2);
383
+ }
384
+ for (const word of flagPathWords(args)) {
385
+ const refused = pathCheck(word, ctx, false);
386
+ if (refused) {
387
+ return refused;
388
+ }
389
+ }
289
390
  const recursive = spec.recursive?.(flags) ?? false;
290
391
  let targets = [];
291
392
  if (spec.paths === "all") {
@@ -364,39 +465,125 @@ function classifyRunner(args, ctx) {
364
465
  const GIT_READ = new Set([
365
466
  "blame",
366
467
  "branch",
468
+ "cat-file",
367
469
  "describe",
368
470
  "diff",
471
+ "diff-tree",
472
+ "for-each-ref",
473
+ "grep",
369
474
  "log",
370
475
  "ls-files",
476
+ "ls-tree",
477
+ "merge-base",
478
+ "name-rev",
479
+ "reflog",
480
+ "remote",
481
+ "rev-list",
371
482
  "rev-parse",
372
483
  "shortlog",
373
484
  "show",
485
+ "show-ref",
486
+ "stash",
374
487
  "status",
488
+ "tag",
489
+ "worktree",
375
490
  ]);
376
- const GIT_BAD_FLAG = /^(--output|-c$|-C$|--exec-path|--upload-pack|--git-dir|--work-tree|--no-index|--ext-diff|--textconv|--open-files-in-pager|-O)/u;
491
+ 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;
377
492
  const GIT_LIST_FLAG = /^(-a|-r|-v|-vv|--all|--remotes|--list|--show-current)$/u;
493
+ // Global options that cannot run anything. -c, --config-env, --exec-path and
494
+ // aliases can, so they stay asks; GIT_* env assignments never parse.
495
+ const GIT_GLOBAL_OK = new Set([
496
+ "--literal-pathspecs",
497
+ "--no-optional-locks",
498
+ "--no-pager",
499
+ "-P",
500
+ ]);
501
+ const GIT_DIR_FLAG = /^--(?:git-dir|work-tree)=(.+)$/u;
502
+ // `git [globals] <sub> ...`: only the globals above are understood.
503
+ function splitGit(args) {
504
+ const dirs = [];
505
+ let index = 0;
506
+ while (index < args.length && isFlag(args[index])) {
507
+ const word = args[index];
508
+ const next = args[index + 1];
509
+ const attached = GIT_DIR_FLAG.exec(word.text);
510
+ if (GIT_GLOBAL_OK.has(word.text)) {
511
+ index += 1;
512
+ }
513
+ else if (attached?.[1]) {
514
+ dirs.push({ chdir: false, word: { glob: word.glob, text: attached[1] } });
515
+ index += 1;
516
+ }
517
+ else if (["-C", "--git-dir", "--work-tree"].includes(word.text) &&
518
+ next &&
519
+ !isFlag(next)) {
520
+ dirs.push({ chdir: word.text === "-C", word: next });
521
+ index += 2;
522
+ }
523
+ else {
524
+ return { dirs, ok: false, rest: [] };
525
+ }
526
+ }
527
+ return { dirs, ok: true, rest: args.slice(index + 1), sub: args[index] };
528
+ }
529
+ // Subcommands that also write take a read-only form: check it.
530
+ function gitSubIsRead(sub, rest) {
531
+ const flags = rest.filter(isFlag).map((word) => word.text);
532
+ const positional = rest.filter((word) => !isFlag(word)).map((w) => w.text);
533
+ switch (sub) {
534
+ case "branch":
535
+ // `git branch NAME` creates a branch; only the listing forms pass.
536
+ return (positional.length === 0 && flags.every((f) => GIT_LIST_FLAG.test(f)));
537
+ case "tag":
538
+ return flags.some((f) => f === "-l" || f === "--list");
539
+ case "remote":
540
+ return (flags.every((f) => f === "-v" || f === "--verbose") &&
541
+ (positional.length === 0 || positional[0] === "get-url"));
542
+ case "stash":
543
+ return positional[0] === "list" || positional[0] === "show";
544
+ case "worktree":
545
+ return positional[0] === "list";
546
+ case "reflog":
547
+ return positional.length === 0 || positional[0] === "show";
548
+ default:
549
+ return true;
550
+ }
551
+ }
378
552
  function classifyGit(args, ctx) {
379
- const [sub, ...rest] = args;
380
- if (!(sub && GIT_READ.has(sub.text))) {
553
+ const git = splitGit(args);
554
+ const { sub, rest } = git;
555
+ if (!(git.ok && sub && GIT_READ.has(sub.text))) {
381
556
  return deny(2);
382
557
  }
383
558
  const flags = rest.filter(isFlag);
384
- const positional = rest.filter((word) => !isFlag(word));
385
- if (flags.some((flag) => GIT_BAD_FLAG.test(flag.text))) {
386
- return deny(2);
387
- }
388
- // `git branch NAME` creates a branch; only the listing forms pass.
389
- if (sub.text === "branch" &&
390
- (positional.length > 0 ||
391
- flags.some((flag) => !GIT_LIST_FLAG.test(flag.text)))) {
559
+ if (flags.some((flag) => GIT_BAD_FLAG.test(flag.text)) ||
560
+ !gitSubIsRead(sub.text, rest)) {
392
561
  return deny(2);
393
562
  }
394
- for (const word of positional) {
563
+ for (const word of flagPathWords(rest)) {
395
564
  const refused = pathCheck(word, ctx, false);
396
565
  if (refused) {
397
566
  return refused;
398
567
  }
399
568
  }
569
+ // `-C dir` and friends read that path: the same check as `cat dir/x`. Later
570
+ // paths resolve against the directory `-C` moved into.
571
+ let local = ctx;
572
+ for (const { chdir, word } of git.dirs) {
573
+ const refused = pathCheck(word, local, false);
574
+ if (refused) {
575
+ return refused;
576
+ }
577
+ if (chdir) {
578
+ local = { ...local, cwd: canonical(word.text, local.cwd, local.home) };
579
+ }
580
+ }
581
+ for (const word of rest.filter((word) => !isFlag(word))) {
582
+ const refused = pathCheck(word, local, false);
583
+ if (refused) {
584
+ return refused;
585
+ }
586
+ }
400
587
  return allow();
401
588
  }
402
589
  // What an always-allow rule can name: local repository work the owner expects
@@ -451,12 +638,19 @@ function shellAsk(command, ctx) {
451
638
  return { kind: "shell:script", tier: 1 };
452
639
  }
453
640
  if (program === "git") {
454
- const sub = args[0]?.text ?? "";
455
- const badFlag = args.some((word) => isFlag(word) && GIT_BAD_FLAG.test(word.text));
456
- if (!GIT_TIER2.has(sub) || badFlag) {
641
+ const git = splitGit(args);
642
+ const sub = git.ok ? (git.sub?.text ?? "") : "";
643
+ const badFlag = git.rest.some((word) => isFlag(word) && GIT_BAD_FLAG.test(word.text));
644
+ // A change to another repository is not the workspace's own work.
645
+ const elsewhere = git.dirs.some(({ word }) => word.glob ||
646
+ !ctx.writeRoots.some((root) => isInside(canonical(word.text, ctx.cwd, ctx.home), root)));
647
+ if (!(git.ok && GIT_TIER2.has(sub)) || badFlag || elsewhere) {
457
648
  return { kind: `git:${sub || "?"}`, tier: 1 };
458
649
  }
459
- return { kind: `git:${sub}`, tier: sub === "push" ? gitPushTier(args) : 2 };
650
+ return {
651
+ kind: `git:${sub}`,
652
+ tier: sub === "push" ? gitPushTier([git.sub, ...git.rest]) : 2,
653
+ };
460
654
  }
461
655
  if (FILE_UTILS.has(program)) {
462
656
  const inside = args
@@ -486,6 +680,40 @@ function shellAsk(command, ctx) {
486
680
  }
487
681
  return { kind: `shell:${program}`, tier: 1 };
488
682
  }
683
+ const VERSION_PROGRAMS = new Set([
684
+ "bun",
685
+ "cargo",
686
+ "claude",
687
+ "deno",
688
+ "git",
689
+ "node",
690
+ "npm",
691
+ "pip",
692
+ "pip3",
693
+ "pnpm",
694
+ "python",
695
+ "python3",
696
+ "rustc",
697
+ "yarn",
698
+ ]);
699
+ // `node --version`, `go version`: asking a tool who it is runs nothing else.
700
+ function isVersionQuery(program, args) {
701
+ if (args.length !== 1) {
702
+ return false;
703
+ }
704
+ const only = args[0]?.text;
705
+ return ((VERSION_PROGRAMS.has(program) &&
706
+ (only === "--version" || only === "-v" || only === "-V")) ||
707
+ (program === "go" && only === "version"));
708
+ }
709
+ // Another repository's attributes, config and submodule map pick the programs
710
+ // git runs for a diff, a filter or a fetch. Outside this job's workspace they
711
+ // are never written (R13); inside it they are the owner's own repo.
712
+ const GIT_CONTROL_FILE = /(?:^|\/)(?:\.gitattributes|\.gitmodules|\.git\/config|\.git\/info\/attributes)$/iu;
713
+ function gitControlFile(real, ctx) {
714
+ return (GIT_CONTROL_FILE.test(real) &&
715
+ !ctx.writeRoots.some((root) => isInside(real, root)));
716
+ }
489
717
  function classifySimple(command, ctx) {
490
718
  const [programWord, ...args] = command.argv;
491
719
  if (!programWord) {
@@ -499,6 +727,14 @@ function classifySimple(command, ctx) {
499
727
  if (SECRET_PROGRAMS.has(program)) {
500
728
  verdict = deny(0);
501
729
  }
730
+ else if (isVersionQuery(program, args)) {
731
+ verdict = allow();
732
+ }
733
+ else if (FILE_UTILS.has(program) &&
734
+ args.some((word) => !(isFlag(word) || word.glob) &&
735
+ gitControlFile(canonical(word.text, ctx.cwd, ctx.home), ctx))) {
736
+ verdict = deny(0);
737
+ }
502
738
  else {
503
739
  const spec = READ_ONLY[program];
504
740
  if (program === "git") {
@@ -526,7 +762,8 @@ function classifySimple(command, ctx) {
526
762
  continue;
527
763
  }
528
764
  const real = canonical(redirect.target.text, ctx.cwd, ctx.home);
529
- if (protectedReason(real, "write", ctx.home, ctx.guard)) {
765
+ if (protectedReason(real, "write", ctx.home, ctx.guard) ||
766
+ gitControlFile(real, ctx)) {
530
767
  return deny(0);
531
768
  }
532
769
  if (redirect.target.glob ||
@@ -537,6 +774,25 @@ function classifySimple(command, ctx) {
537
774
  }
538
775
  return allow(mutates);
539
776
  }
777
+ function changeDirectory(command, ctx) {
778
+ const [program, target, ...extra] = command.argv;
779
+ if (program?.text !== "cd" ||
780
+ extra.length > 0 ||
781
+ command.redirects.length > 0 ||
782
+ !target ||
783
+ target.glob ||
784
+ target.text === "-" ||
785
+ isFlag(target)) {
786
+ return;
787
+ }
788
+ const refused = pathCheck(target, ctx, false);
789
+ if (refused) {
790
+ return refused.allow || refused.tier !== 0 ? undefined : refused;
791
+ }
792
+ return {
793
+ moved: { ...ctx, cwd: canonical(target.text, ctx.cwd, ctx.home) },
794
+ };
795
+ }
540
796
  export function classifyShell(source, ctx) {
541
797
  const parsed = parseShell(source);
542
798
  const summary = redactSummary(source);
@@ -546,8 +802,19 @@ export function classifyShell(source, ctx) {
546
802
  let mutates = false;
547
803
  let worst;
548
804
  const asked = [];
805
+ let here = ctx;
549
806
  for (const command of parsed.commands) {
550
- const verdict = classifySimple(command, ctx);
807
+ // `cd dir && ...`: later paths resolve from there. A target the reader
808
+ // cannot judge falls through to the ordinary ask for `cd`.
809
+ const moved = changeDirectory(command, here);
810
+ if (moved) {
811
+ if (!("moved" in moved)) {
812
+ return moved;
813
+ }
814
+ here = moved.moved;
815
+ continue;
816
+ }
817
+ const verdict = classifySimple(command, here);
551
818
  if (verdict.allow) {
552
819
  mutates ||= verdict.mutates;
553
820
  continue;
@@ -555,7 +822,7 @@ export function classifyShell(source, ctx) {
555
822
  if (verdict.tier === 0) {
556
823
  return verdict;
557
824
  }
558
- asked.push(shellAsk(command, ctx));
825
+ asked.push(shellAsk(command, here));
559
826
  if (!worst || (!worst.allow && verdict.tier < worst.tier)) {
560
827
  worst = verdict;
561
828
  }
@@ -575,6 +842,35 @@ export function classifyShell(source, ctx) {
575
842
  function text(value) {
576
843
  return typeof value === "string" && value.length > 0 ? value : undefined;
577
844
  }
845
+ const APPLY_PATCH_PATH = /^\*\*\*\s+(?:Add File|Update File|Delete File|Move to):\s*(.+?)\s*$/gmu;
846
+ /** Every file path an apply_patch touches: add, update, delete and move-to. */
847
+ export function applyPatchPaths(command) {
848
+ if (!command) {
849
+ return [];
850
+ }
851
+ const paths = [];
852
+ for (const match of command.matchAll(APPLY_PATCH_PATH)) {
853
+ if (match[1]) {
854
+ paths.push(match[1]);
855
+ }
856
+ }
857
+ return paths;
858
+ }
859
+ /** The write rule shared by Edit tools and apply_patch: inside a write root, or ask. */
860
+ function classifyWrite(tool, real, ctx) {
861
+ if (protectedReason(real, "write", ctx.home, ctx.guard) ||
862
+ gitControlFile(real, ctx)) {
863
+ return deny(0);
864
+ }
865
+ return ctx.writeRoots.some((root) => isInside(real, root))
866
+ ? allow(true)
867
+ : askDeny("That file is outside this job's workspace. Needs the owner's approval.", {
868
+ detail: `${tool} ${real}`,
869
+ kind: "write-outside-workspace",
870
+ summary: redactSummary(`${tool} ${real}`),
871
+ tier: 1,
872
+ });
873
+ }
578
874
  export function classifyCall(call, context) {
579
875
  const guard = context.guard ?? protectedPaths(context.home);
580
876
  const ctx = { ...context, guard, cwd: call.cwd };
@@ -594,18 +890,34 @@ export function classifyCall(call, context) {
594
890
  if (!target) {
595
891
  return deny(1);
596
892
  }
597
- const real = canonical(target, call.cwd, context.home);
598
- if (protectedReason(real, "write", context.home, guard)) {
599
- return deny(0);
893
+ return classifyWrite(tool, canonical(target, call.cwd, context.home), ctx);
894
+ }
895
+ // Codex's freeform file-edit tool: the whole patch is in `command`, so every
896
+ // path it adds, updates, moves to or deletes is checked like an Edit, and one
897
+ // path outside the workspace or into a protected file refuses the patch.
898
+ if (tool === "apply_patch") {
899
+ const paths = applyPatchPaths(text(input.command));
900
+ if (paths.length === 0) {
901
+ return deny(1);
600
902
  }
601
- return context.writeRoots.some((root) => isInside(real, root))
602
- ? allow(true)
603
- : askDeny("That file is outside this job's workspace. Needs the owner's approval.", {
604
- detail: `${tool} ${real}`,
605
- kind: "write-outside-workspace",
606
- summary: redactSummary(`${tool} ${real}`),
607
- tier: 1,
608
- });
903
+ let verdict = allow(true);
904
+ for (const path of paths) {
905
+ const refused = classifyWrite("apply_patch", canonical(path, call.cwd, context.home), ctx);
906
+ if (!refused.allow) {
907
+ if (refused.tier === 0) {
908
+ return refused;
909
+ }
910
+ verdict = refused;
911
+ }
912
+ }
913
+ return verdict;
914
+ }
915
+ // Codex reads a local image to look at it; judged like any other read.
916
+ if (tool === "view_image") {
917
+ const path = text(input.path) ?? text(input.file_path);
918
+ return path
919
+ ? (pathCheck({ glob: false, text: path }, ctx, false) ?? allow())
920
+ : deny(1);
609
921
  }
610
922
  if (PLAIN_TOOLS.has(tool)) {
611
923
  const raw = text(input.file_path) ?? text(input.notebook_path) ?? text(input.path);
@@ -130,22 +130,25 @@ export async function runScenario(binary, scenario, hookEntry) {
130
130
  // A stand-in owner behind the real supervisor bridge: the ask is pending for
131
131
  // `answerAfterMs`, then the server "says" the scenario's answer.
132
132
  const startedAt = Date.now();
133
- const owner = scenario.answer
134
- ? await new ApprovalBridge({
135
- gateway: {
136
- request: () => Promise.resolve({ status: "pending" }),
137
- status: (keys) => Promise.resolve(keys.map((actionKey) => ({
138
- actionKey,
139
- status: Date.now() - startedAt < (scenario.answerAfterMs ?? 0)
140
- ? "pending"
141
- : scenario.answer,
142
- }))),
143
- },
144
- statusEveryMs: 50,
145
- }).start()
146
- : undefined;
133
+ // Every scenario runs behind the real supervisor: the hook reports calls
134
+ // that reach the owner's setup (a subagent, an MCP tool) through it before
135
+ // the call runs, and refuses the call if it cannot. A scenario with no
136
+ // `answer` has an owner who declines at once.
137
+ const owner = await new ApprovalBridge({
138
+ gateway: {
139
+ touch: async () => undefined,
140
+ request: () => Promise.resolve({ status: scenario.answer ? "pending" : "denied" }),
141
+ status: (keys) => Promise.resolve(keys.map((actionKey) => ({
142
+ actionKey,
143
+ status: Date.now() - startedAt < (scenario.answerAfterMs ?? 0)
144
+ ? "pending"
145
+ : (scenario.answer ?? "denied"),
146
+ }))),
147
+ },
148
+ statusEveryMs: 50,
149
+ }).start();
147
150
  await writeFile(join(jobDir, "context.json"), JSON.stringify({
148
- ...(owner ? { askSocket: owner.socketPath } : {}),
151
+ askSocket: owner.socketPath,
149
152
  home,
150
153
  writeRoots: [realpathSync.native(work)],
151
154
  }));
@@ -0,0 +1,106 @@
1
+ import { discoverProjects } from "./discover.js";
2
+ import { checkRepo, readProjects, registerRoot, removeProject, } from "./projects.js";
3
+ const DISCOVERY_TTL_MS = 5 * 60_000;
4
+ export class ProjectRequests {
5
+ discoveries = new Map();
6
+ running;
7
+ again = false;
8
+ input;
9
+ constructor(input) {
10
+ this.input = input;
11
+ }
12
+ /** Coalesced: a burst of wakes runs at most one pass plus one follow-up. */
13
+ poke() {
14
+ if (this.running) {
15
+ this.again = true;
16
+ return this.running;
17
+ }
18
+ this.running = (async () => {
19
+ try {
20
+ do {
21
+ this.again = false;
22
+ await this.pass();
23
+ } while (this.again);
24
+ }
25
+ finally {
26
+ this.running = undefined;
27
+ }
28
+ })();
29
+ return this.running;
30
+ }
31
+ async pass() {
32
+ const now = Date.now();
33
+ for (const [id, entry] of this.discoveries) {
34
+ if (now - entry.at > DISCOVERY_TTL_MS) {
35
+ this.discoveries.delete(id);
36
+ }
37
+ }
38
+ const requests = (await this.input.post("/agent-gateway/projects/requests", {})) ?? [];
39
+ for (const request of requests) {
40
+ await this.handle(request).catch(() => undefined);
41
+ }
42
+ }
43
+ async handle(request) {
44
+ const { directory, home } = this.input;
45
+ if (request.kind === "remove") {
46
+ if (request.projectId) {
47
+ await removeProject(directory, request.projectId);
48
+ }
49
+ await this.close(request.requestId);
50
+ return;
51
+ }
52
+ if (request.status === "requested") {
53
+ const env = await this.input.env();
54
+ const discovery = await discoverProjects({
55
+ claudeConfigDir: env.CLAUDE_CONFIG_DIR,
56
+ codexHome: env.CODEX_HOME,
57
+ home,
58
+ registered: (await readProjects(directory)).map((project) => project.root),
59
+ });
60
+ this.discoveries.set(request.requestId, {
61
+ at: Date.now(),
62
+ names: new Map(discovery.candidates.map((candidate) => [
63
+ candidate.candidateId,
64
+ candidate.hint
65
+ ? `${candidate.name} (${candidate.hint})`
66
+ : candidate.name,
67
+ ])),
68
+ roots: discovery.roots,
69
+ });
70
+ await this.input.post("/agent-gateway/projects/offer", {
71
+ candidates: discovery.candidates,
72
+ requestId: request.requestId,
73
+ });
74
+ return;
75
+ }
76
+ if (request.status !== "chosen") {
77
+ return;
78
+ }
79
+ const offered = this.discoveries.get(request.requestId);
80
+ for (const candidateId of request.picks ?? []) {
81
+ const root = offered?.roots.get(candidateId);
82
+ if (!root) {
83
+ // Not an id this process offered for this request: never a path.
84
+ continue;
85
+ }
86
+ try {
87
+ // Re-checked now: the folder must still be the one that was offered.
88
+ const now = await checkRepo(root.root, home);
89
+ if (now.root === root.root &&
90
+ now.dev === root.dev &&
91
+ now.ino === root.ino) {
92
+ await registerRoot(directory, now, offered?.names.get(candidateId));
93
+ }
94
+ }
95
+ catch {
96
+ // A folder that moved or failed its checks is skipped.
97
+ }
98
+ }
99
+ this.discoveries.delete(request.requestId);
100
+ await this.close(request.requestId);
101
+ }
102
+ async close(requestId) {
103
+ await this.input.mirror().catch(() => undefined);
104
+ await this.input.post("/agent-gateway/projects/done", { requestId });
105
+ }
106
+ }