@octopi-agent/engine 0.97.15 → 0.98.4

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.
Files changed (100) hide show
  1. package/dist/config-schema/agent.d.ts +2 -0
  2. package/dist/config-schema/engine.d.ts +4 -0
  3. package/dist/config-schema/governance.d.ts +2 -0
  4. package/dist/config-schema/governance.js +30 -0
  5. package/dist/harness/agent/builder.d.ts +11 -0
  6. package/dist/harness/agent/builder.js +59 -32
  7. package/dist/harness/agent/config-integrity.d.ts +66 -0
  8. package/dist/harness/agent/config-integrity.js +89 -0
  9. package/dist/harness/agent/wire-agent-builder.js +5 -0
  10. package/dist/harness/collaboration/autonomous-subsystem/index.d.ts +2 -2
  11. package/dist/harness/collaboration/autonomous-subsystem/index.js +1 -1
  12. package/dist/harness/collaboration/autonomous-subsystem/loader.js +3 -0
  13. package/dist/harness/collaboration/autonomous-subsystem/sense/engine.js +19 -2
  14. package/dist/harness/collaboration/autonomous-subsystem/think/completion-guard.d.ts +40 -0
  15. package/dist/harness/collaboration/autonomous-subsystem/think/completion-guard.js +59 -0
  16. package/dist/harness/collaboration/autonomous-subsystem/think/index.d.ts +2 -0
  17. package/dist/harness/collaboration/autonomous-subsystem/think/index.js +1 -0
  18. package/dist/harness/collaboration/autonomous-subsystem/think/model-resolver.js +1 -1
  19. package/dist/harness/collaboration/autonomous-subsystem/types.d.ts +9 -0
  20. package/dist/harness/context/capabilities/summary/resolver.d.ts +1 -1
  21. package/dist/harness/context/capabilities/summary/resolver.js +4 -4
  22. package/dist/harness/context/capabilities/summary/types.d.ts +2 -2
  23. package/dist/harness/context/layers.d.ts +2 -4
  24. package/dist/harness/context/layers.js +9 -11
  25. package/dist/harness/context/summarize.d.ts +1 -1
  26. package/dist/harness/context/summarize.js +2 -2
  27. package/dist/harness/context/system-prompt-assembler.d.ts +2 -0
  28. package/dist/harness/context/system-prompt-assembler.js +1 -0
  29. package/dist/harness/extension/execution-environment/effect-policy.d.ts +24 -2
  30. package/dist/harness/extension/execution-environment/effect-policy.js +30 -0
  31. package/dist/harness/extension/execution-environment/ops-audit.d.ts +6 -2
  32. package/dist/harness/extension/execution-environment/ops-audit.js +11 -12
  33. package/dist/harness/extension/execution-environment/undo-log.d.ts +6 -2
  34. package/dist/harness/extension/execution-environment/undo-log.js +31 -10
  35. package/dist/harness/extension/plugin-ecosystem/tools/builtin.js +17 -24
  36. package/dist/harness/extension/plugin-ecosystem/tools/document-tools.js +3 -9
  37. package/dist/harness/extension/plugin-ecosystem/tools/file-edit.js +3 -6
  38. package/dist/harness/extension/plugin-ecosystem/tools/file-ops.js +9 -5
  39. package/dist/harness/extension/plugin-ecosystem/tools/file-search.js +9 -130
  40. package/dist/harness/extension/plugin-ecosystem/tools/git-tools.js +122 -14
  41. package/dist/harness/extension/plugin-ecosystem/tools/package-tools.js +4 -13
  42. package/dist/harness/extension/plugin-ecosystem/tools/platform.d.ts +25 -11
  43. package/dist/harness/extension/plugin-ecosystem/tools/platform.js +168 -62
  44. package/dist/harness/governance/security/default-risk-policy.d.ts +1 -0
  45. package/dist/harness/governance/security/default-risk-policy.js +1 -0
  46. package/dist/harness/governance/security/default-security-guard.js +9 -0
  47. package/dist/harness/governance/security/index.d.ts +1 -0
  48. package/dist/harness/governance/security/index.js +2 -0
  49. package/dist/harness/governance/security/risk-evaluator.js +13 -0
  50. package/dist/harness/governance/security/risk-types.d.ts +12 -0
  51. package/dist/harness/governance/security/shell-parser-fallback.d.ts +29 -0
  52. package/dist/harness/governance/security/shell-parser-fallback.js +410 -0
  53. package/dist/harness/governance/security/shell-parser-shared.d.ts +83 -0
  54. package/dist/harness/governance/security/shell-parser-shared.js +188 -0
  55. package/dist/harness/governance/security/shell-parser-treesitter.d.ts +52 -0
  56. package/dist/harness/governance/security/shell-parser-treesitter.js +370 -0
  57. package/dist/harness/governance/security/shell-parser.d.ts +23 -10
  58. package/dist/harness/governance/security/shell-parser.js +37 -496
  59. package/dist/harness/governance/security/vendor/README.md +24 -0
  60. package/dist/harness/governance/security/vendor/tree-sitter-bash.LICENSE.txt +21 -0
  61. package/dist/harness/governance/security/vendor/tree-sitter-bash.wasm +0 -0
  62. package/dist/harness/memory/index.d.ts +6 -2
  63. package/dist/harness/memory/index.js +4 -1
  64. package/dist/harness/memory/memory-events.d.ts +25 -0
  65. package/dist/harness/memory/memory-events.js +38 -0
  66. package/dist/harness/memory/sqlite/agent-db.js +15 -0
  67. package/dist/harness/memory/sqlite/wisdom-store.d.ts +7 -2
  68. package/dist/harness/memory/sqlite/wisdom-store.js +51 -2
  69. package/dist/harness/memory/steward-policy.d.ts +3 -0
  70. package/dist/harness/memory/steward-policy.js +1 -1
  71. package/dist/harness/memory/types.d.ts +41 -3
  72. package/dist/harness/memory/wisdom-attribution.d.ts +136 -0
  73. package/dist/harness/memory/wisdom-attribution.js +287 -0
  74. package/dist/harness/memory/wisdom-events.d.ts +37 -0
  75. package/dist/harness/memory/wisdom-events.js +61 -0
  76. package/dist/harness/memory/wisdom-formation.d.ts +20 -1
  77. package/dist/harness/memory/wisdom-formation.js +55 -21
  78. package/dist/harness/memory/wisdom.d.ts +7 -2
  79. package/dist/harness/memory/wisdom.js +40 -2
  80. package/dist/harness/run/run-scope.d.ts +4 -0
  81. package/dist/harness/run/runner.d.ts +27 -2
  82. package/dist/harness/run/runner.js +48 -4
  83. package/dist/harness/shared/paths/glob.d.ts +52 -0
  84. package/dist/harness/shared/paths/glob.js +218 -0
  85. package/dist/harness/shared/paths/index.d.ts +84 -0
  86. package/dist/harness/shared/paths/index.js +179 -0
  87. package/dist/subsystems/cognition-steward/conceptualize/config.yaml +4 -2
  88. package/dist/subsystems/cognition-steward/conceptualize/handler.js +12 -20
  89. package/dist/subsystems/memory-steward/backfill/config.yaml +4 -2
  90. package/dist/subsystems/memory-steward/backfill/handler.js +44 -52
  91. package/dist/subsystems/wisdom-steward/attribute/SUBSYSTEM.md +24 -0
  92. package/dist/subsystems/wisdom-steward/attribute/config.yaml +60 -0
  93. package/dist/subsystems/wisdom-steward/attribute/handler.d.ts +23 -0
  94. package/dist/subsystems/wisdom-steward/attribute/handler.js +167 -0
  95. package/dist/subsystems/wisdom-steward/evaluate/handler.js +3 -1
  96. package/dist/subsystems/wisdom-steward/formation/config.yaml +12 -5
  97. package/dist/subsystems/wisdom-steward/formation/handler.js +12 -18
  98. package/dist/subsystems/wisdom-steward/govern/config.yaml +1 -1
  99. package/dist/subsystems/wisdom-steward/govern/handler.js +4 -0
  100. package/package.json +7 -2
@@ -31,7 +31,9 @@ import { createEnvInfoTool } from './env-info.js';
31
31
  import { createProcessListTool } from './process-tools.js';
32
32
  import { createPrivExecTool } from './privileged-tool.js';
33
33
  import { createDocumentProbeTool, createDocumentReadTool } from './document-tools.js';
34
- import { isUnderSessionUndoRoot, defaultPathEnv, isPathUnderRoots, isUnderAttachmentRoot, resolvePlatformShell, resolveReadableToolPath, resolveToolPath, } from './platform.js';
34
+ import { containmentOptions, defaultPathEnv, isPathUnderRoots, isUnderAttachmentRoot, isUnderSessionUndoRoot, resolvePlatformShell, resolveReadableToolPath, resolveToolPath, } from './platform.js';
35
+ import { readFileNoFollow } from '../../../shared/paths/index.js';
36
+ import { matchesDenyPattern } from '../../../shared/paths/glob.js';
35
37
  /**
36
38
  * Shell 工具 — 执行 shell 命令
37
39
  *
@@ -112,10 +114,7 @@ export function createShellTool(options) {
112
114
  notReversedPayload = { reason: 'shell_journal_off' };
113
115
  }
114
116
  const resolvedShell = resolvePlatformShell();
115
- const resolvedCwd = resolveToolPath(cwd, context?.cwd, {
116
- allowRoots: context?.pathRoots,
117
- containment: context?.pathContainment,
118
- });
117
+ const resolvedCwd = resolveToolPath(cwd, context?.cwd, containmentOptions(context));
119
118
  // D2-a: always ProcessSandbox (jail backend when probed, else supervised).
120
119
  const { createProcessSandbox } = await import('../../execution-environment/sandbox.js');
121
120
  const sandbox = await createProcessSandbox({
@@ -324,14 +323,13 @@ export function createFileReadTool(options) {
324
323
  const pathModule = await import('node:path');
325
324
  const rawPath = args.path;
326
325
  const cwd = context?.cwd ?? process.cwd();
327
- const path = resolveReadableToolPath(rawPath, cwd, context?.attachmentRoots, {
328
- allowRoots: context?.pathRoots,
329
- containment: context?.pathContainment,
330
- });
326
+ const path = resolveReadableToolPath(rawPath, cwd, context?.attachmentRoots, containmentOptions(context));
331
327
  const offset = args.offset ?? 1;
332
328
  const limit = args.limit ?? 2000;
333
329
  try {
334
- const content = await readFile(path, 'utf-8');
330
+ const content = context?.refuseFinalSymlink
331
+ ? await readFileNoFollow(path, 'utf8')
332
+ : await readFile(path, 'utf-8');
335
333
  const lines = content.split('\n');
336
334
  const totalLines = lines.length;
337
335
  const start = Math.max(0, offset - 1);
@@ -411,10 +409,7 @@ export function createFileWriteTool() {
411
409
  const { dirname } = await import('node:path');
412
410
  const rawPath = args.path;
413
411
  const cwd = context?.cwd ?? process.cwd();
414
- const path = resolveToolPath(rawPath, cwd, {
415
- allowRoots: context?.pathRoots,
416
- containment: context?.pathContainment,
417
- });
412
+ const path = resolveToolPath(rawPath, cwd, containmentOptions(context));
418
413
  if (isUnderAttachmentRoot(path, context?.attachmentRoots)) {
419
414
  throw new Error('session attachments are read-only; cannot write to attachments root');
420
415
  }
@@ -446,10 +441,10 @@ export function createFileWriteTool() {
446
441
  throw new Error('file_effects_not_configured: file_write requires ToolExecutionContext.fileEffects');
447
442
  }
448
443
  if (append) {
449
- await effects.appendFile(path, content);
444
+ await effects.appendFile(path, content, { refuseFinalSymlink: context?.refuseFinalSymlink === true });
450
445
  }
451
446
  else {
452
- await effects.writeFile(path, content);
447
+ await effects.writeFile(path, content, { refuseFinalSymlink: context?.refuseFinalSymlink === true });
453
448
  }
454
449
  return {
455
450
  path,
@@ -491,10 +486,7 @@ export function createFileDeleteTool() {
491
486
  const { readFile, rm, stat } = await import('node:fs/promises');
492
487
  const rawPath = args.path;
493
488
  const cwd = context?.cwd ?? process.cwd();
494
- const path = resolveToolPath(rawPath, cwd, {
495
- allowRoots: context?.pathRoots,
496
- containment: context?.pathContainment,
497
- });
489
+ const path = resolveToolPath(rawPath, cwd, containmentOptions(context));
498
490
  if (isUnderAttachmentRoot(path, context?.attachmentRoots)) {
499
491
  throw new Error('session attachments are read-only; cannot delete from attachments root');
500
492
  }
@@ -645,10 +637,7 @@ export function createFileListTool(options) {
645
637
  const { join, relative } = await import('node:path');
646
638
  const rawPath = args.path ?? '.';
647
639
  const cwd = context?.cwd ?? process.cwd();
648
- const basePath = resolveReadableToolPath(rawPath, cwd, context?.attachmentRoots, {
649
- allowRoots: context?.pathRoots,
650
- containment: context?.pathContainment,
651
- });
640
+ const basePath = resolveReadableToolPath(rawPath, cwd, context?.attachmentRoots, containmentOptions(context));
652
641
  // 找文件意图(带 pattern)默认递归;显式 recursive:false 仍只列本层
653
642
  const hasPattern = Boolean(args.pattern?.trim());
654
643
  const recursive = args.recursive === undefined && hasPattern
@@ -658,6 +647,7 @@ export function createFileListTool(options) {
658
647
  const maxEntries = Math.min(Math.max(args.maxEntries ?? 500, 1), 2000);
659
648
  const maxDepth = Math.min(Math.max(args.maxDepth ?? 4, 1), 8);
660
649
  const entries = [];
650
+ const denylist = context?.pathDenylist ?? [];
661
651
  let totalCount = 0;
662
652
  let entryCapped = false;
663
653
  let depthCapped = false;
@@ -674,6 +664,9 @@ export function createFileListTool(options) {
674
664
  return;
675
665
  const fullPath = join(dir, item.name);
676
666
  const relativePath = relative(basePath, fullPath);
667
+ // Denied names are not even enumerated: existence and size are data too.
668
+ if (denylist.length > 0 && matchesDenyPattern(relativePath.split('\\').join('/'), denylist))
669
+ continue;
677
670
  if (recursive && item.isDirectory() && SKIP_DIR_NAMES.has(item.name))
678
671
  continue;
679
672
  // pattern 只过滤列出的条目;递归时目录始终下钻(否则 recursive+*.md 进不了子目录)
@@ -3,7 +3,7 @@
3
3
  *
4
4
  * 只消费 DocumentPort;业务/设计知识留在 skill。
5
5
  */
6
- import { resolveReadableToolPath } from './platform.js';
6
+ import { containmentOptions, resolveReadableToolPath, } from './platform.js';
7
7
  /**
8
8
  * document_read — 抽取 PDF/Office 为 Markdown
9
9
  *
@@ -44,10 +44,7 @@ export function createDocumentReadTool(options) {
44
44
  }
45
45
  const rawPath = String(args.path ?? '');
46
46
  const cwd = context?.cwd ?? process.cwd();
47
- const path = resolveReadableToolPath(rawPath, cwd, context?.attachmentRoots, {
48
- allowRoots: context?.pathRoots,
49
- containment: context?.pathContainment,
50
- });
47
+ const path = resolveReadableToolPath(rawPath, cwd, context?.attachmentRoots, containmentOptions(context));
51
48
  try {
52
49
  const result = await port.extract({
53
50
  path,
@@ -135,10 +132,7 @@ export function createDocumentProbeTool(options) {
135
132
  }
136
133
  const rawPath = String(args.path ?? '');
137
134
  const cwd = context?.cwd ?? process.cwd();
138
- const path = resolveReadableToolPath(rawPath, cwd, context?.attachmentRoots, {
139
- allowRoots: context?.pathRoots,
140
- containment: context?.pathContainment,
141
- });
135
+ const path = resolveReadableToolPath(rawPath, cwd, context?.attachmentRoots, containmentOptions(context));
142
136
  try {
143
137
  const probe = await port.probe({ path, name: path });
144
138
  const caps = await port.capabilities();
@@ -10,7 +10,7 @@
10
10
  * - dry-run 预览模式
11
11
  * - 编辑后自动返回周围上下文
12
12
  */
13
- import { isPathUnderRoots, isUnderAttachmentRoot, isUnderSessionUndoRoot, resolveToolPath, } from './platform.js';
13
+ import { containmentOptions, isPathUnderRoots, isUnderAttachmentRoot, isUnderSessionUndoRoot, resolveToolPath, } from './platform.js';
14
14
  import { gateEffect } from '../../execution-environment/effect-policy.js';
15
15
  import { detectEol, oldTextCandidates, toEol } from './eol.js';
16
16
  export function createFileEditTool() {
@@ -51,10 +51,7 @@ export function createFileEditTool() {
51
51
  const { readFile } = await import('node:fs/promises');
52
52
  const rawPath = args.path;
53
53
  const cwd = context.cwd ?? process.cwd();
54
- const path = resolveToolPath(rawPath, cwd, {
55
- allowRoots: context.pathRoots,
56
- containment: context.pathContainment,
57
- });
54
+ const path = resolveToolPath(rawPath, cwd, containmentOptions(context));
58
55
  if (isUnderAttachmentRoot(path, context.attachmentRoots)) {
59
56
  throw new Error('session attachments are read-only; cannot edit attachments root');
60
57
  }
@@ -136,7 +133,7 @@ export function createFileEditTool() {
136
133
  if (!effects) {
137
134
  throw new Error('file_effects_not_configured: file_edit requires ToolExecutionContext.fileEffects');
138
135
  }
139
- await effects.writeFile(path, newContent);
136
+ await effects.writeFile(path, newContent, { refuseFinalSymlink: context?.refuseFinalSymlink === true });
140
137
  }
141
138
  return {
142
139
  path,
@@ -1,11 +1,9 @@
1
- import { isPathUnderRoots, isUnderAttachmentRoot, resolveToolPath, isUnderSessionUndoRoot, } from './platform.js';
1
+ import { containmentOptions, isPathUnderRoots, isUnderAttachmentRoot, isUnderSessionUndoRoot, resolveToolPath, } from './platform.js';
2
2
  import { gateEffect } from '../../execution-environment/effect-policy.js';
3
+ import { isFinalSymlink } from '../../../shared/paths/index.js';
3
4
  function resolveSafePath(rawPath, context, label) {
4
5
  const cwd = context?.cwd ?? process.cwd();
5
- const path = resolveToolPath(rawPath, cwd, {
6
- allowRoots: context?.pathRoots,
7
- containment: context?.pathContainment,
8
- });
6
+ const path = resolveToolPath(rawPath, cwd, containmentOptions(context));
9
7
  if (isUnderAttachmentRoot(path, context?.attachmentRoots)) {
10
8
  throw new Error(`session attachments are read-only; cannot ${label} under attachments root`);
11
9
  }
@@ -256,6 +254,12 @@ export function createFileCopyTool() {
256
254
  await effects.recordCreate(to, after);
257
255
  }
258
256
  // Binary-safe copy (images, Office, etc.)
257
+ // `copyFile` opens the destination with O_TRUNC and would follow a symlink
258
+ // planted at `to`, writing outside the root. It also bypasses
259
+ // `effects.writeFile`, so the final-component guard must be applied here.
260
+ if (context?.refuseFinalSymlink === true && isFinalSymlink(to)) {
261
+ throw new Error(`path_forbidden: "${to}" final component is a symlink (refuseFinalSymlink)`);
262
+ }
259
263
  await copyFile(from, to);
260
264
  return {
261
265
  from,
@@ -21,7 +21,8 @@
21
21
  * - 零结果时返回 diagnostics + hints,便于调用方自纠
22
22
  */
23
23
  import { resolveSupportBinding, } from '../../../context/capabilities/summary/index.js';
24
- import { resolveToolPath } from './platform.js';
24
+ import { containmentOptions, resolveToolPath, } from './platform.js';
25
+ import { globToPathRegex, matchesDenyPattern } from '../../../shared/paths/glob.js';
25
26
  /** 需要忽略的目录 */
26
27
  const IGNORED_DIRS = new Set([
27
28
  'node_modules', '.git', '.svn', '.hg', 'dist', 'build',
@@ -117,10 +118,7 @@ export function createFileSearchTool(options) {
117
118
  const { basename, extname, join, relative } = await import('node:path');
118
119
  const rawRoot = args.path;
119
120
  const rootPath = rawRoot
120
- ? resolveToolPath(rawRoot, context.cwd ?? process.cwd(), {
121
- allowRoots: context.pathRoots,
122
- containment: context.pathContainment,
123
- })
121
+ ? resolveToolPath(rawRoot, context.cwd ?? process.cwd(), containmentOptions(context))
124
122
  : (context.cwd ?? process.cwd());
125
123
  const terms = collectPatternTerms(args);
126
124
  const patternMode = resolvePatternMode(args);
@@ -153,6 +151,12 @@ export function createFileSearchTool(options) {
153
151
  async function considerFile(fullPath, relPath) {
154
152
  if (truncated)
155
153
  return;
154
+ // Denylist applies per file, not just to the `path` argument: this tool
155
+ // walks a tree and returns file *contents*, so a denied name would
156
+ // otherwise be readable here while `file_read` refuses it.
157
+ const denylist = context.pathDenylist ?? [];
158
+ if (denylist.length > 0 && matchesDenyPattern(relPath, denylist))
159
+ return;
156
160
  filesSeen += 1;
157
161
  // glob 过滤:root 相对路径(无 `/` 的模式等价于任意深度 globstar)
158
162
  if (fileFilter && !fileFilter.test(relPath))
@@ -574,131 +578,6 @@ async function searchFileLines(options) {
574
578
  }
575
579
  }
576
580
  // ── glob 编译 ──
577
- /**
578
- * 将路径 glob 编译为正则(匹配 root 相对路径)
579
- *
580
- * 语义对齐 rg/git:
581
- * - `**` 跨目录;`*` / `?` 不跨 `/`
582
- * - 无 `/` 的模式(如 `*.md`)等价于任意深度的 globstar 匹配
583
- * - 支持 `{a,b}` 花括号(可多组)
584
- *
585
- * @param glob - glob 模式
586
- * @returns 整串匹配相对路径的正则(大小写不敏感)
587
- */
588
- function globToPathRegex(glob) {
589
- const trimmed = glob.trim();
590
- if (!trimmed)
591
- throw new Error('glob must be non-empty');
592
- const normalized = trimmed.includes('/') ? trimmed : `**/${trimmed}`;
593
- const source = globToSource(normalized);
594
- return new RegExp(`^${source}$`, 'i');
595
- }
596
- /**
597
- * 将(已规范化)glob 片段编译为正则源
598
- *
599
- * @param glob - 含路径分隔符的 glob
600
- * @returns 正则源片段(无首尾锚点)
601
- */
602
- function globToSource(glob) {
603
- let out = '';
604
- let i = 0;
605
- while (i < glob.length) {
606
- const ch = glob[i];
607
- // `\*` `\?` 等 → 字面量
608
- if (ch === '\\' && i + 1 < glob.length && '*?[]{}\\/!'.includes(glob[i + 1])) {
609
- out += escapeRegex(glob[i + 1]);
610
- i += 2;
611
- continue;
612
- }
613
- if (ch === '*' && glob[i + 1] === '*') {
614
- i += 2;
615
- if (glob[i] === '/') {
616
- i += 1;
617
- // `**/` → 任意深度前缀(含零层)
618
- out += '(?:.*/)?';
619
- }
620
- else {
621
- out += '.*';
622
- }
623
- continue;
624
- }
625
- if (ch === '*') {
626
- i += 1;
627
- out += '[^/]*';
628
- continue;
629
- }
630
- if (ch === '?') {
631
- i += 1;
632
- out += '[^/]';
633
- continue;
634
- }
635
- if (ch === '{') {
636
- const end = findBraceEnd(glob, i);
637
- if (end === -1) {
638
- out += '\\{';
639
- i += 1;
640
- continue;
641
- }
642
- const alts = splitBraceAlts(glob.slice(i + 1, end));
643
- out += `(?:${alts.map((alt) => globToSource(alt)).join('|')})`;
644
- i = end + 1;
645
- continue;
646
- }
647
- if ('.+^$()|[]'.includes(ch)) {
648
- out += `\\${ch}`;
649
- }
650
- else {
651
- out += ch;
652
- }
653
- i += 1;
654
- }
655
- return out;
656
- }
657
- /**
658
- * 找到配对的 `}`(跳过嵌套 `{}`)
659
- *
660
- * @param glob - glob 字符串
661
- * @param openIndex - `{` 下标
662
- * @returns 配对 `}` 下标;无则 -1
663
- */
664
- function findBraceEnd(glob, openIndex) {
665
- let depth = 0;
666
- for (let i = openIndex; i < glob.length; i++) {
667
- if (glob[i] === '{')
668
- depth += 1;
669
- else if (glob[i] === '}') {
670
- depth -= 1;
671
- if (depth === 0)
672
- return i;
673
- }
674
- }
675
- return -1;
676
- }
677
- /**
678
- * 拆分花括号内的顶层逗号备选
679
- *
680
- * @param body - `{}` 内部
681
- * @returns 备选列表
682
- */
683
- function splitBraceAlts(body) {
684
- const alts = [];
685
- let depth = 0;
686
- let current = '';
687
- for (const ch of body) {
688
- if (ch === '{')
689
- depth += 1;
690
- if (ch === '}')
691
- depth -= 1;
692
- if (ch === ',' && depth === 0) {
693
- alts.push(current);
694
- current = '';
695
- continue;
696
- }
697
- current += ch;
698
- }
699
- alts.push(current);
700
- return alts;
701
- }
702
581
  // ── L1 输出收缩(F1-B1:结构化硬顶,零 LLM) ──
703
582
  /**
704
583
  * L1 结构化收缩:把 matches 清单体压进预算,定位符(file+line)永远全保
@@ -1,14 +1,12 @@
1
1
  import { gateEffect } from '../../execution-environment/effect-policy.js';
2
- import { resolveToolPath, isUnderAttachmentRoot, isUnderSessionUndoRoot } from './platform.js';
2
+ import { containmentOptions, isUnderAttachmentRoot, isUnderSessionUndoRoot, resolveToolPath, } from './platform.js';
3
3
  import { detectEol, toEol } from './eol.js';
4
4
  import { assertSafeRef } from './allowlisted-run.js';
5
+ import { matchesDenyPattern } from '../../../shared/paths/glob.js';
5
6
  import { runGit } from './git-runner.js';
6
7
  function resolveCwd(context, raw) {
7
8
  const cwd = raw ?? context?.cwd ?? process.cwd();
8
- const abs = resolveToolPath(cwd, context?.cwd, {
9
- allowRoots: context?.pathRoots,
10
- containment: context?.pathContainment,
11
- });
9
+ const abs = resolveToolPath(cwd, context?.cwd, containmentOptions(context));
12
10
  if (isUnderAttachmentRoot(abs, context?.attachmentRoots)) {
13
11
  throw new Error('session attachments are read-only; cannot run git under attachments root');
14
12
  }
@@ -18,10 +16,7 @@ function resolveCwd(context, raw) {
18
16
  return abs;
19
17
  }
20
18
  function assertPathSafe(raw, context, label) {
21
- const abs = resolveToolPath(raw, context?.cwd, {
22
- allowRoots: context?.pathRoots,
23
- containment: context?.pathContainment,
24
- });
19
+ const abs = resolveToolPath(raw, context?.cwd, containmentOptions(context));
25
20
  if (isUnderAttachmentRoot(abs, context?.attachmentRoots)) {
26
21
  throw new Error(`session attachments are read-only; cannot ${label} under attachments root`);
27
22
  }
@@ -43,6 +38,12 @@ function toGitPathspec(raw, context, label) {
43
38
  if (!isMagic) {
44
39
  return assertPathSafe(raw, context, label);
45
40
  }
41
+ const denylist = context?.pathDenylist ?? [];
42
+ // A glob pathspec is matched by git, not by us, so we cannot prove it excludes
43
+ // denied paths. Fail closed instead of shipping an unverifiable allow.
44
+ if (denylist.length > 0) {
45
+ throw new Error(`pathspec_glob_forbidden: glob pathspec "${raw}" cannot be checked against pathDenylist; pass explicit paths`);
46
+ }
46
47
  if (raw.startsWith('/') ||
47
48
  raw.startsWith('\\\\') ||
48
49
  (process.platform === 'win32' && /^[A-Za-z]:[\\/]/.test(raw))) {
@@ -56,9 +57,116 @@ function toGitPathspec(raw, context, label) {
56
57
  }
57
58
  return raw;
58
59
  }
59
- function toText(result) {
60
+ /**
61
+ * Decode a git-quoted path (`"a\tb"`) into its literal spelling.
62
+ *
63
+ * @param token - path token straight from git output
64
+ * @returns the path git meant, without the a/ or b/ side prefix
65
+ */
66
+ function unquoteGitPath(token) {
67
+ const body = token.startsWith('"') && token.endsWith('"')
68
+ ? token.slice(1, -1).replace(/\\(.)/g, '$1')
69
+ : token;
70
+ return body.replace(/^[ab]\//, '');
71
+ }
72
+ /**
73
+ * Split the arguments of a `diff --git a/<path> b/<path>` header.
74
+ *
75
+ * @param rest - header text after `diff --git `
76
+ * @returns path tokens, still quoted when git quoted them
77
+ */
78
+ function splitDiffHeader(rest) {
79
+ const tokens = [];
80
+ let index = 0;
81
+ while (index < rest.length) {
82
+ if (rest[index] === ' ') {
83
+ index += 1;
84
+ continue;
85
+ }
86
+ let token = '';
87
+ while (index < rest.length && rest[index] !== ' ') {
88
+ if (rest[index] === '"') {
89
+ token += '"';
90
+ index += 1;
91
+ while (index < rest.length) {
92
+ if (rest[index] === '\\' && index + 1 < rest.length) {
93
+ token += rest[index] + rest[index + 1];
94
+ index += 2;
95
+ continue;
96
+ }
97
+ token += rest[index];
98
+ if (rest[index] === '"') {
99
+ index += 1;
100
+ break;
101
+ }
102
+ index += 1;
103
+ }
104
+ continue;
105
+ }
106
+ token += rest[index];
107
+ index += 1;
108
+ }
109
+ tokens.push(token);
110
+ }
111
+ return tokens;
112
+ }
113
+ /**
114
+ * Drop git output that names or contains denied paths.
115
+ *
116
+ * `git_diff` / `git_show` emit file *contents* keyed by section headers, and
117
+ * `git_status` emits bare paths, so path arguments alone are not enough: a
118
+ * deployment that denies `.env*` must not get that content back through VCS.
119
+ * Truncated diffs cannot be verified section by section, so they are refused
120
+ * rather than returned unverified.
121
+ *
122
+ * @param text - raw git stdout
123
+ * @param truncated - whether the runner cut the output
124
+ * @param patterns - denylist globs
125
+ * @param kind - output shape
126
+ * @returns filtered stdout
127
+ */
128
+ function filterGitOutput(text, truncated, patterns, kind) {
129
+ if (patterns.length === 0)
130
+ return text;
131
+ const lines = text.split('\n');
132
+ if (kind === 'status') {
133
+ return lines
134
+ .filter((line) => {
135
+ if (line.startsWith('##') || line.length < 4)
136
+ return true;
137
+ const raw = line.slice(3);
138
+ const target = raw.includes(' -> ') ? raw.slice(raw.lastIndexOf(' -> ') + 4) : raw;
139
+ return !matchesDenyPattern(unquoteGitPath(target.trim()), patterns);
140
+ })
141
+ .join('\n');
142
+ }
143
+ if (truncated) {
144
+ throw new Error('path_forbidden: git output was truncated, so pathDenylist could not be verified; narrow the request');
145
+ }
146
+ let dropping = false;
147
+ const kept = [];
148
+ for (const line of lines) {
149
+ if (line.startsWith('diff --git ')) {
150
+ const paths = splitDiffHeader(line.slice('diff --git '.length)).map(unquoteGitPath);
151
+ dropping = paths.some((path) => matchesDenyPattern(path, patterns));
152
+ }
153
+ else if (/^ .+?\s+\|\s+\d+/.test(line)) {
154
+ // `--stat` rows are single lines, not sections; test the named path.
155
+ const path = unquoteGitPath(line.trim().split(/\s+\|\s+/)[0].trim());
156
+ if (matchesDenyPattern(path, patterns))
157
+ continue;
158
+ }
159
+ if (!dropping)
160
+ kept.push(line);
161
+ }
162
+ return kept.join('\n');
163
+ }
164
+ function toText(result, context, contentKind) {
165
+ const stdout = contentKind
166
+ ? filterGitOutput(result.stdout, result.truncated, context?.pathDenylist ?? [], contentKind)
167
+ : result.stdout;
60
168
  return {
61
- stdout: result.stdout,
169
+ stdout,
62
170
  stderr: result.stderr,
63
171
  exitCode: result.exitCode,
64
172
  durationMs: result.durationMs,
@@ -95,7 +203,7 @@ export function createGitStatusTool() {
95
203
  '--untracked-files=all',
96
204
  ...pathArgs,
97
205
  ]);
98
- return { ...toText(result), cwd };
206
+ return { ...toText(result, context, 'status'), cwd };
99
207
  },
100
208
  };
101
209
  }
@@ -147,7 +255,7 @@ export function createGitDiffTool() {
147
255
  gitArgs.push('--', ...paths.map((p) => toGitPathspec(p, context, 'diff')));
148
256
  }
149
257
  const result = await runGit(context, cwd, gitArgs, { timeoutMs: 120_000 });
150
- return { ...toText(result), cwd, mode };
258
+ return { ...toText(result, context, 'diff'), cwd, mode };
151
259
  },
152
260
  };
153
261
  }
@@ -215,7 +323,7 @@ export function createGitShowTool() {
215
323
  gitArgs.push('--stat');
216
324
  gitArgs.push(rev);
217
325
  const result = await runGit(context, cwd, gitArgs, { timeoutMs: 120_000 });
218
- return { ...toText(result), cwd, revision: rev };
326
+ return { ...toText(result, context, 'diff'), cwd, revision: rev };
219
327
  },
220
328
  };
221
329
  }
@@ -11,15 +11,12 @@
11
11
  import { tmpdir } from 'node:os';
12
12
  import { join } from 'node:path';
13
13
  import { gateEffect } from '../../execution-environment/effect-policy.js';
14
- import { isUnderAttachmentRoot, isUnderSessionUndoRoot, resolveToolPath, findExecutable, } from './platform.js';
14
+ import { containmentOptions, findExecutable, isUnderAttachmentRoot, isUnderSessionUndoRoot, resolveToolPath, } from './platform.js';
15
15
  import { runAllowlistedArgv } from './allowlisted-run.js';
16
16
  import { resolveNodeToolCommand } from './platform.js';
17
17
  function resolveCwd(context, raw) {
18
18
  const cwd = raw ?? context?.cwd ?? process.cwd();
19
- const abs = resolveToolPath(cwd, context?.cwd, {
20
- allowRoots: context?.pathRoots,
21
- containment: context?.pathContainment,
22
- });
19
+ const abs = resolveToolPath(cwd, context?.cwd, containmentOptions(context));
23
20
  if (isUnderAttachmentRoot(abs, context?.attachmentRoots)) {
24
21
  throw new Error('session attachments are read-only; cannot run package tools under attachments root');
25
22
  }
@@ -29,10 +26,7 @@ function resolveCwd(context, raw) {
29
26
  return abs;
30
27
  }
31
28
  function assertPathSafe(raw, context, label) {
32
- const abs = resolveToolPath(raw, context?.cwd, {
33
- allowRoots: context?.pathRoots,
34
- containment: context?.pathContainment,
35
- });
29
+ const abs = resolveToolPath(raw, context?.cwd, containmentOptions(context));
36
30
  if (isUnderAttachmentRoot(abs, context?.attachmentRoots)) {
37
31
  throw new Error(`session attachments are read-only; cannot ${label} under attachments root`);
38
32
  }
@@ -235,10 +229,7 @@ export function createProjectRunTool() {
235
229
  if (!script || !/^[A-Za-z0-9][A-Za-z0-9:._-]*$/.test(script)) {
236
230
  throw new Error(`project_run: invalid script name "${script}"`);
237
231
  }
238
- const pkgPath = resolveToolPath('package.json', cwd, {
239
- allowRoots: context?.pathRoots,
240
- containment: context?.pathContainment,
241
- });
232
+ const pkgPath = resolveToolPath('package.json', cwd, containmentOptions(context));
242
233
  const { pkg } = await readPackageJson(pkgPath);
243
234
  const scripts = (pkg.scripts ?? {});
244
235
  if (typeof scripts[script] !== 'string') {
@@ -4,6 +4,8 @@
4
4
  * 文件/Shell 工具统一走这里,避免在各工具内手写 `startsWith('/')`
5
5
  * 或硬编码 `/bin/bash` 导致 Windows 行为分裂。
6
6
  */
7
+ import { isPathUnderRoots } from '../../../shared/paths/index.js';
8
+ export { isPathUnderRoots };
7
9
  /** 平台 shell 方言 */
8
10
  export type ShellKind = 'bash' | 'powershell' | 'cmd';
9
11
  /** 已解析的平台 shell */
@@ -17,20 +19,34 @@ export interface PlatformShell {
17
19
  label: string;
18
20
  }
19
21
  /**
20
- * 解析工具入参路径:绝对路径原样返回,相对路径相对 cwd
22
+ * Build containment options from a tool context.
21
23
  *
22
- * 使用 `path.isAbsolute`,同时覆盖 POSIX `/foo`、Windows 盘符
23
- * `C:\` / `C:/` 与 UNC `\\server\share`。
24
+ * Every tool used to spell these fields out by hand, which is how a newly added
25
+ * policy field gets silently dropped (the same failure that hid
26
+ * `refuseFinalSymlink` from the tool surface). One constructor, one place to add
27
+ * the next field.
24
28
  *
25
- * @param rawPath - 工具入参路径
26
- * @param cwd - 工作目录;缺省为 `process.cwd()`
27
- * @returns 规范化后的绝对路径
29
+ * @param context - tool execution context
30
+ * @returns options for {@link resolveToolPath}
28
31
  */
32
+ export declare function containmentOptions(context?: {
33
+ pathRoots?: readonly string[];
34
+ pathContainment?: 'strict' | 'soft' | 'none';
35
+ pathDenylist?: readonly string[];
36
+ } | null): ResolveToolPathOptions;
37
+ /** L2 路径约束选项(由 {@link containmentOptions} 从工具上下文构造) */
29
38
  export interface ResolveToolPathOptions {
30
39
  /** L2 允许根;containment 非 none 时必须落在其下 */
31
- allowRoots?: string[];
40
+ allowRoots?: readonly string[];
32
41
  /** L2 级别;省略 = 不限制 */
33
42
  containment?: 'strict' | 'soft' | 'none';
43
+ /**
44
+ * L2 拒绝清单(glob,匹配允许根内相对路径与文件名)。
45
+ *
46
+ * 独立于 containment:声明即拒绝,任何级别都生效。默认空 = 不拒绝任何路径,
47
+ * 因为「agent 读写自己 workspace 里的 `.env`」是合法且常见的用法。
48
+ */
49
+ denyPatterns?: readonly string[];
34
50
  }
35
51
  /**
36
52
  * 解析工具入参路径:绝对路径原样返回,相对路径相对 cwd
@@ -38,13 +54,11 @@ export interface ResolveToolPathOptions {
38
54
  * 使用 path.isAbsolute,同时覆盖 POSIX /foo、Windows 盘符与 UNC。
39
55
  *
40
56
  * @param rawPath - 工具入参路径
41
- * @param cwd - 工作目录;缺省为 process.cwd()
57
+ * @param cwd - 工具 cwd;缺省为 process.cwd()
42
58
  * @param options - L2 路径包含(ToolEffectPolicy)
43
- * @returns 规范化后的绝对路径
59
+ * @returns 规范化后的绝对路径;containment 生效时为符号链接解析后的真实路径
44
60
  */
45
61
  export declare function resolveToolPath(rawPath: string, cwd?: string, options?: ResolveToolPathOptions): string;
46
- /** 路径是否落在任一 root 之下(含 root 本身) */
47
- export declare function isPathUnderRoots(absPath: string, roots: string[]): boolean;
48
62
  /**
49
63
  * 只读附件根内解析(OP-15):相对名优先贴到 attachmentRoots
50
64
  *