@caupulican/pi-adaptative 0.80.99 → 0.80.102

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 (129) hide show
  1. package/CHANGELOG.md +203 -0
  2. package/dist/core/agent-session.d.ts +72 -0
  3. package/dist/core/agent-session.d.ts.map +1 -1
  4. package/dist/core/agent-session.js +437 -46
  5. package/dist/core/agent-session.js.map +1 -1
  6. package/dist/core/autonomy/envelope-enforcement.d.ts +5 -0
  7. package/dist/core/autonomy/envelope-enforcement.d.ts.map +1 -1
  8. package/dist/core/autonomy/envelope-enforcement.js +28 -4
  9. package/dist/core/autonomy/envelope-enforcement.js.map +1 -1
  10. package/dist/core/autonomy/path-scope.d.ts.map +1 -1
  11. package/dist/core/autonomy/path-scope.js +33 -2
  12. package/dist/core/autonomy/path-scope.js.map +1 -1
  13. package/dist/core/bash-executor.d.ts.map +1 -1
  14. package/dist/core/bash-executor.js +15 -7
  15. package/dist/core/bash-executor.js.map +1 -1
  16. package/dist/core/context/brain-curator.d.ts +10 -0
  17. package/dist/core/context/brain-curator.d.ts.map +1 -1
  18. package/dist/core/context/brain-curator.js +19 -2
  19. package/dist/core/context/brain-curator.js.map +1 -1
  20. package/dist/core/context-gc.d.ts +8 -3
  21. package/dist/core/context-gc.d.ts.map +1 -1
  22. package/dist/core/context-gc.js +5 -0
  23. package/dist/core/context-gc.js.map +1 -1
  24. package/dist/core/delegation/worker-actions.d.ts +0 -10
  25. package/dist/core/delegation/worker-actions.d.ts.map +1 -1
  26. package/dist/core/delegation/worker-actions.js +5 -7
  27. package/dist/core/delegation/worker-actions.js.map +1 -1
  28. package/dist/core/delegation/worker-result.d.ts +6 -0
  29. package/dist/core/delegation/worker-result.d.ts.map +1 -1
  30. package/dist/core/delegation/worker-result.js +10 -4
  31. package/dist/core/delegation/worker-result.js.map +1 -1
  32. package/dist/core/delegation/worker-runner.d.ts +3 -0
  33. package/dist/core/delegation/worker-runner.d.ts.map +1 -1
  34. package/dist/core/delegation/worker-runner.js +6 -1
  35. package/dist/core/delegation/worker-runner.js.map +1 -1
  36. package/dist/core/doctor.d.ts +66 -0
  37. package/dist/core/doctor.d.ts.map +1 -0
  38. package/dist/core/doctor.js +144 -0
  39. package/dist/core/doctor.js.map +1 -0
  40. package/dist/core/learning/learning-audit.d.ts +13 -1
  41. package/dist/core/learning/learning-audit.d.ts.map +1 -1
  42. package/dist/core/learning/learning-audit.js +22 -1
  43. package/dist/core/learning/learning-audit.js.map +1 -1
  44. package/dist/core/learning/learning-gate.d.ts +3 -0
  45. package/dist/core/learning/learning-gate.d.ts.map +1 -1
  46. package/dist/core/learning/learning-gate.js +13 -4
  47. package/dist/core/learning/learning-gate.js.map +1 -1
  48. package/dist/core/models/default-model-suggestions.d.ts +34 -0
  49. package/dist/core/models/default-model-suggestions.d.ts.map +1 -0
  50. package/dist/core/models/default-model-suggestions.js +58 -0
  51. package/dist/core/models/default-model-suggestions.js.map +1 -0
  52. package/dist/core/models/local-registration.d.ts +2 -0
  53. package/dist/core/models/local-registration.d.ts.map +1 -1
  54. package/dist/core/models/local-registration.js +2 -1
  55. package/dist/core/models/local-registration.js.map +1 -1
  56. package/dist/core/models/local-runtime.d.ts +76 -2
  57. package/dist/core/models/local-runtime.d.ts.map +1 -1
  58. package/dist/core/models/local-runtime.js +233 -21
  59. package/dist/core/models/local-runtime.js.map +1 -1
  60. package/dist/core/profile-resource-selection.d.ts +15 -3
  61. package/dist/core/profile-resource-selection.d.ts.map +1 -1
  62. package/dist/core/profile-resource-selection.js +19 -9
  63. package/dist/core/profile-resource-selection.js.map +1 -1
  64. package/dist/core/resource-loader.d.ts +20 -0
  65. package/dist/core/resource-loader.d.ts.map +1 -1
  66. package/dist/core/resource-loader.js +42 -16
  67. package/dist/core/resource-loader.js.map +1 -1
  68. package/dist/core/settings-manager.d.ts +30 -0
  69. package/dist/core/settings-manager.d.ts.map +1 -1
  70. package/dist/core/settings-manager.js +65 -3
  71. package/dist/core/settings-manager.js.map +1 -1
  72. package/dist/core/skills.d.ts +14 -0
  73. package/dist/core/skills.d.ts.map +1 -1
  74. package/dist/core/skills.js +8 -0
  75. package/dist/core/skills.js.map +1 -1
  76. package/dist/core/slash-commands.d.ts.map +1 -1
  77. package/dist/core/slash-commands.js +1 -1
  78. package/dist/core/slash-commands.js.map +1 -1
  79. package/dist/core/tools/fff-search-backend.d.ts +34 -1
  80. package/dist/core/tools/fff-search-backend.d.ts.map +1 -1
  81. package/dist/core/tools/fff-search-backend.js +43 -4
  82. package/dist/core/tools/fff-search-backend.js.map +1 -1
  83. package/dist/core/tools/find.d.ts +16 -0
  84. package/dist/core/tools/find.d.ts.map +1 -1
  85. package/dist/core/tools/find.js +17 -3
  86. package/dist/core/tools/find.js.map +1 -1
  87. package/dist/core/tools/grep.d.ts +20 -0
  88. package/dist/core/tools/grep.d.ts.map +1 -1
  89. package/dist/core/tools/grep.js +15 -3
  90. package/dist/core/tools/grep.js.map +1 -1
  91. package/dist/main.d.ts.map +1 -1
  92. package/dist/main.js +17 -0
  93. package/dist/main.js.map +1 -1
  94. package/dist/modes/interactive/components/fitness-role-selector.d.ts +6 -2
  95. package/dist/modes/interactive/components/fitness-role-selector.d.ts.map +1 -1
  96. package/dist/modes/interactive/components/fitness-role-selector.js +55 -45
  97. package/dist/modes/interactive/components/fitness-role-selector.js.map +1 -1
  98. package/dist/modes/interactive/components/model-suggestion-selector.d.ts +13 -0
  99. package/dist/modes/interactive/components/model-suggestion-selector.d.ts.map +1 -0
  100. package/dist/modes/interactive/components/model-suggestion-selector.js +40 -0
  101. package/dist/modes/interactive/components/model-suggestion-selector.js.map +1 -0
  102. package/dist/modes/interactive/components/profile-resource-editor.d.ts +3 -0
  103. package/dist/modes/interactive/components/profile-resource-editor.d.ts.map +1 -1
  104. package/dist/modes/interactive/components/profile-resource-editor.js +16 -2
  105. package/dist/modes/interactive/components/profile-resource-editor.js.map +1 -1
  106. package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -1
  107. package/dist/modes/interactive/components/settings-selector.js +98 -0
  108. package/dist/modes/interactive/components/settings-selector.js.map +1 -1
  109. package/dist/modes/interactive/interactive-mode.d.ts +8 -1
  110. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  111. package/dist/modes/interactive/interactive-mode.js +57 -10
  112. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  113. package/dist/utils/safe-write-stream.d.ts +8 -0
  114. package/dist/utils/safe-write-stream.d.ts.map +1 -1
  115. package/dist/utils/safe-write-stream.js +32 -0
  116. package/dist/utils/safe-write-stream.js.map +1 -1
  117. package/dist/utils/tools-manager.d.ts +92 -2
  118. package/dist/utils/tools-manager.d.ts.map +1 -1
  119. package/dist/utils/tools-manager.js +172 -32
  120. package/dist/utils/tools-manager.js.map +1 -1
  121. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  122. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  123. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  124. package/examples/extensions/sandbox/package-lock.json +2 -2
  125. package/examples/extensions/sandbox/package.json +1 -1
  126. package/examples/extensions/with-deps/package-lock.json +2 -2
  127. package/examples/extensions/with-deps/package.json +1 -1
  128. package/npm-shrinkwrap.json +12 -36
  129. package/package.json +4 -4
@@ -3,6 +3,11 @@ export declare function extractPathArguments(params: unknown): string[];
3
3
  /**
4
4
  * Deny wins over allow; an empty/absent allow list means "no positive scope restriction"
5
5
  * (only denies apply) — mirroring the resource-profile filter semantics.
6
+ *
7
+ * Both the target and every scope root are resolved through the real filesystem
8
+ * (symlinks expanded in the existing prefix) before comparison: a pre-existing symlink
9
+ * under an allowed root cannot smuggle a write outside the scope, and a shortcut into a
10
+ * denied subtree is still denied. An unresolvable target fails closed.
6
11
  */
7
12
  export declare function isPathWithinEnvelope(envelope: CapabilityEnvelope, rawPath: string, cwd: string): boolean;
8
13
  export interface EnvelopeScopedTool {
@@ -1 +1 @@
1
- {"version":3,"file":"envelope-enforcement.d.ts","sourceRoot":"","sources":["../../../src/core/autonomy/envelope-enforcement.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,gBAAgB,CAAC;AAczD,wBAAgB,oBAAoB,CAAC,MAAM,EAAE,OAAO,GAAG,MAAM,EAAE,CAiB9D;AAUD;;;GAGG;AACH,wBAAgB,oBAAoB,CAAC,QAAQ,EAAE,kBAAkB,EAAE,OAAO,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG,OAAO,CAQxG;AAED,MAAM,WAAW,kBAAkB;IAClC,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,CAAC,GAAG,IAAI,EAAE,OAAO,EAAE,KAAK,OAAO,CAAC;CACzC;AAED;;;GAGG;AACH,wBAAgB,yBAAyB,CAAC,CAAC,SAAS,kBAAkB,EACrE,IAAI,EAAE,CAAC,EACP,QAAQ,EAAE,kBAAkB,EAC5B,GAAG,EAAE,MAAM,GACT,CAAC,CAsBH","sourcesContent":["import { isAbsolute, relative, resolve, sep } from \"node:path\";\nimport type { CapabilityEnvelope } from \"./contracts.ts\";\n\n/**\n * Tool-level envelope enforcement (G2 prerequisite for code-writing workers): the capability\n * envelope's `allowedPaths`/`deniedPaths` were previously VALIDATION-ONLY — recorded on the\n * envelope but never checked when a tool actually ran. This module wraps tools so path-bearing\n * arguments are checked AT EXECUTION TIME, structurally refusing out-of-scope paths the same way\n * a failed script can never look like success: the refusal is an isError result with a stable\n * outcome code, never a silent no-op.\n */\n\nconst PATH_ARGUMENT_KEYS = [\"path\", \"file_path\", \"filePath\", \"cwd\", \"directory\", \"dir\", \"target\"] as const;\nconst PATH_LIST_ARGUMENT_KEYS = [\"paths\", \"files\"] as const;\n\nexport function extractPathArguments(params: unknown): string[] {\n\tif (!params || typeof params !== \"object\") return [];\n\tconst record = params as Record<string, unknown>;\n\tconst found: string[] = [];\n\tfor (const key of PATH_ARGUMENT_KEYS) {\n\t\tconst value = record[key];\n\t\tif (typeof value === \"string\" && value.length > 0) found.push(value);\n\t}\n\tfor (const key of PATH_LIST_ARGUMENT_KEYS) {\n\t\tconst value = record[key];\n\t\tif (Array.isArray(value)) {\n\t\t\tfor (const entry of value) {\n\t\t\t\tif (typeof entry === \"string\" && entry.length > 0) found.push(entry);\n\t\t\t}\n\t\t}\n\t}\n\treturn found;\n}\n\nfunction isWithinRoot(target: string, root: string): boolean {\n\tconst relativePath = relative(root, target);\n\treturn (\n\t\trelativePath === \"\" ||\n\t\t(!relativePath.startsWith(`..${sep}`) && relativePath !== \"..\" && !isAbsolute(relativePath))\n\t);\n}\n\n/**\n * Deny wins over allow; an empty/absent allow list means \"no positive scope restriction\"\n * (only denies apply) — mirroring the resource-profile filter semantics.\n */\nexport function isPathWithinEnvelope(envelope: CapabilityEnvelope, rawPath: string, cwd: string): boolean {\n\tconst target = resolve(cwd, rawPath);\n\tfor (const denied of envelope.deniedPaths ?? []) {\n\t\tif (isWithinRoot(target, resolve(cwd, denied))) return false;\n\t}\n\tconst allowed = envelope.allowedPaths ?? [];\n\tif (allowed.length === 0) return true;\n\treturn allowed.some((root) => isWithinRoot(target, resolve(cwd, root)));\n}\n\nexport interface EnvelopeScopedTool {\n\tname: string;\n\texecute: (...args: unknown[]) => unknown;\n}\n\n/**\n * Wrap a tool so every path-bearing argument is scope-checked when it RUNS. The wrapped tool is\n * shape-identical; params are conventionally the second execute argument (toolCallId, params, …).\n */\nexport function wrapToolWithEnvelopeScope<T extends EnvelopeScopedTool>(\n\ttool: T,\n\tenvelope: CapabilityEnvelope,\n\tcwd: string,\n): T {\n\treturn {\n\t\t...tool,\n\t\texecute: (...args: unknown[]) => {\n\t\t\tconst params = args[1];\n\t\t\tfor (const rawPath of extractPathArguments(params)) {\n\t\t\t\tif (!isPathWithinEnvelope(envelope, rawPath, cwd)) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tcontent: [\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\t\ttext: `envelope_path_denied: \"${rawPath}\" is outside envelope ${envelope.id}'s path scope. The tool was NOT run.`,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t],\n\t\t\t\t\t\tdetails: { outcome: \"envelope_path_denied\", tool: tool.name, path: rawPath, envelopeId: envelope.id },\n\t\t\t\t\t\tisError: true,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn tool.execute(...args);\n\t\t},\n\t};\n}\n"]}
1
+ {"version":3,"file":"envelope-enforcement.d.ts","sourceRoot":"","sources":["../../../src/core/autonomy/envelope-enforcement.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,gBAAgB,CAAC;AAezD,wBAAgB,oBAAoB,CAAC,MAAM,EAAE,OAAO,GAAG,MAAM,EAAE,CAiB9D;AAUD;;;;;;;;GAQG;AACH,wBAAgB,oBAAoB,CAAC,QAAQ,EAAE,kBAAkB,EAAE,OAAO,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG,OAAO,CAuBxG;AAED,MAAM,WAAW,kBAAkB;IAClC,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,CAAC,GAAG,IAAI,EAAE,OAAO,EAAE,KAAK,OAAO,CAAC;CACzC;AAED;;;GAGG;AACH,wBAAgB,yBAAyB,CAAC,CAAC,SAAS,kBAAkB,EACrE,IAAI,EAAE,CAAC,EACP,QAAQ,EAAE,kBAAkB,EAC5B,GAAG,EAAE,MAAM,GACT,CAAC,CAsBH","sourcesContent":["import { isAbsolute, relative, resolve, sep } from \"node:path\";\nimport type { CapabilityEnvelope } from \"./contracts.ts\";\nimport { safeRealpathSync } from \"./path-scope.ts\";\n\n/**\n * Tool-level envelope enforcement (G2 prerequisite for code-writing workers): the capability\n * envelope's `allowedPaths`/`deniedPaths` were previously VALIDATION-ONLY — recorded on the\n * envelope but never checked when a tool actually ran. This module wraps tools so path-bearing\n * arguments are checked AT EXECUTION TIME, structurally refusing out-of-scope paths the same way\n * a failed script can never look like success: the refusal is an isError result with a stable\n * outcome code, never a silent no-op.\n */\n\nconst PATH_ARGUMENT_KEYS = [\"path\", \"file_path\", \"filePath\", \"cwd\", \"directory\", \"dir\", \"target\"] as const;\nconst PATH_LIST_ARGUMENT_KEYS = [\"paths\", \"files\"] as const;\n\nexport function extractPathArguments(params: unknown): string[] {\n\tif (!params || typeof params !== \"object\") return [];\n\tconst record = params as Record<string, unknown>;\n\tconst found: string[] = [];\n\tfor (const key of PATH_ARGUMENT_KEYS) {\n\t\tconst value = record[key];\n\t\tif (typeof value === \"string\" && value.length > 0) found.push(value);\n\t}\n\tfor (const key of PATH_LIST_ARGUMENT_KEYS) {\n\t\tconst value = record[key];\n\t\tif (Array.isArray(value)) {\n\t\t\tfor (const entry of value) {\n\t\t\t\tif (typeof entry === \"string\" && entry.length > 0) found.push(entry);\n\t\t\t}\n\t\t}\n\t}\n\treturn found;\n}\n\nfunction isWithinRoot(target: string, root: string): boolean {\n\tconst relativePath = relative(root, target);\n\treturn (\n\t\trelativePath === \"\" ||\n\t\t(!relativePath.startsWith(`..${sep}`) && relativePath !== \"..\" && !isAbsolute(relativePath))\n\t);\n}\n\n/**\n * Deny wins over allow; an empty/absent allow list means \"no positive scope restriction\"\n * (only denies apply) — mirroring the resource-profile filter semantics.\n *\n * Both the target and every scope root are resolved through the real filesystem\n * (symlinks expanded in the existing prefix) before comparison: a pre-existing symlink\n * under an allowed root cannot smuggle a write outside the scope, and a shortcut into a\n * denied subtree is still denied. An unresolvable target fails closed.\n */\nexport function isPathWithinEnvelope(envelope: CapabilityEnvelope, rawPath: string, cwd: string): boolean {\n\tlet target: string;\n\ttry {\n\t\ttarget = safeRealpathSync(resolve(cwd, rawPath));\n\t} catch {\n\t\treturn false;\n\t}\n\tfor (const denied of envelope.deniedPaths ?? []) {\n\t\ttry {\n\t\t\tif (isWithinRoot(target, safeRealpathSync(resolve(cwd, denied)))) return false;\n\t\t} catch {\n\t\t\t// Mirror checkPathScope: an unresolvable deny root cannot match anything.\n\t\t}\n\t}\n\tconst allowed = envelope.allowedPaths ?? [];\n\tif (allowed.length === 0) return true;\n\treturn allowed.some((root) => {\n\t\ttry {\n\t\t\treturn isWithinRoot(target, safeRealpathSync(resolve(cwd, root)));\n\t\t} catch {\n\t\t\treturn false;\n\t\t}\n\t});\n}\n\nexport interface EnvelopeScopedTool {\n\tname: string;\n\texecute: (...args: unknown[]) => unknown;\n}\n\n/**\n * Wrap a tool so every path-bearing argument is scope-checked when it RUNS. The wrapped tool is\n * shape-identical; params are conventionally the second execute argument (toolCallId, params, …).\n */\nexport function wrapToolWithEnvelopeScope<T extends EnvelopeScopedTool>(\n\ttool: T,\n\tenvelope: CapabilityEnvelope,\n\tcwd: string,\n): T {\n\treturn {\n\t\t...tool,\n\t\texecute: (...args: unknown[]) => {\n\t\t\tconst params = args[1];\n\t\t\tfor (const rawPath of extractPathArguments(params)) {\n\t\t\t\tif (!isPathWithinEnvelope(envelope, rawPath, cwd)) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tcontent: [\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\t\ttext: `envelope_path_denied: \"${rawPath}\" is outside envelope ${envelope.id}'s path scope. The tool was NOT run.`,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t],\n\t\t\t\t\t\tdetails: { outcome: \"envelope_path_denied\", tool: tool.name, path: rawPath, envelopeId: envelope.id },\n\t\t\t\t\t\tisError: true,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn tool.execute(...args);\n\t\t},\n\t};\n}\n"]}
@@ -1,4 +1,5 @@
1
1
  import { isAbsolute, relative, resolve, sep } from "node:path";
2
+ import { safeRealpathSync } from "./path-scope.js";
2
3
  /**
3
4
  * Tool-level envelope enforcement (G2 prerequisite for code-writing workers): the capability
4
5
  * envelope's `allowedPaths`/`deniedPaths` were previously VALIDATION-ONLY — recorded on the
@@ -38,17 +39,40 @@ function isWithinRoot(target, root) {
38
39
  /**
39
40
  * Deny wins over allow; an empty/absent allow list means "no positive scope restriction"
40
41
  * (only denies apply) — mirroring the resource-profile filter semantics.
42
+ *
43
+ * Both the target and every scope root are resolved through the real filesystem
44
+ * (symlinks expanded in the existing prefix) before comparison: a pre-existing symlink
45
+ * under an allowed root cannot smuggle a write outside the scope, and a shortcut into a
46
+ * denied subtree is still denied. An unresolvable target fails closed.
41
47
  */
42
48
  export function isPathWithinEnvelope(envelope, rawPath, cwd) {
43
- const target = resolve(cwd, rawPath);
49
+ let target;
50
+ try {
51
+ target = safeRealpathSync(resolve(cwd, rawPath));
52
+ }
53
+ catch {
54
+ return false;
55
+ }
44
56
  for (const denied of envelope.deniedPaths ?? []) {
45
- if (isWithinRoot(target, resolve(cwd, denied)))
46
- return false;
57
+ try {
58
+ if (isWithinRoot(target, safeRealpathSync(resolve(cwd, denied))))
59
+ return false;
60
+ }
61
+ catch {
62
+ // Mirror checkPathScope: an unresolvable deny root cannot match anything.
63
+ }
47
64
  }
48
65
  const allowed = envelope.allowedPaths ?? [];
49
66
  if (allowed.length === 0)
50
67
  return true;
51
- return allowed.some((root) => isWithinRoot(target, resolve(cwd, root)));
68
+ return allowed.some((root) => {
69
+ try {
70
+ return isWithinRoot(target, safeRealpathSync(resolve(cwd, root)));
71
+ }
72
+ catch {
73
+ return false;
74
+ }
75
+ });
52
76
  }
53
77
  /**
54
78
  * Wrap a tool so every path-bearing argument is scope-checked when it RUNS. The wrapped tool is
@@ -1 +1 @@
1
- {"version":3,"file":"envelope-enforcement.js","sourceRoot":"","sources":["../../../src/core/autonomy/envelope-enforcement.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,OAAO,EAAE,GAAG,EAAE,MAAM,WAAW,CAAC;AAG/D;;;;;;;GAOG;AAEH,MAAM,kBAAkB,GAAG,CAAC,MAAM,EAAE,WAAW,EAAE,UAAU,EAAE,KAAK,EAAE,WAAW,EAAE,KAAK,EA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IAAI,EAAE,OAAO,EAAE,UAAU,EAAE,QAAQ,CAAC,EAAE,EAAE;wBACrG,OAAO,EAAE,IAAI;qBACb,CAAC;gBACH,CAAC;YACF,CAAC;YACD,OAAO,IAAI,CAAC,OAAO,CAAC,GAAG,IAAI,CAAC,CAAC;QAAA,CAC7B;KACD,CAAC;AAAA,CACF","sourcesContent":["import { isAbsolute, relative, resolve, sep } from \"node:path\";\nimport type { CapabilityEnvelope } from \"./contracts.ts\";\n\n/**\n * Tool-level envelope enforcement (G2 prerequisite for code-writing workers): the capability\n * envelope's `allowedPaths`/`deniedPaths` were previously VALIDATION-ONLY — recorded on the\n * envelope but never checked when a tool actually ran. This module wraps tools so path-bearing\n * arguments are checked AT EXECUTION TIME, structurally refusing out-of-scope paths the same way\n * a failed script can never look like success: the refusal is an isError result with a stable\n * outcome code, never a silent no-op.\n */\n\nconst PATH_ARGUMENT_KEYS = [\"path\", \"file_path\", \"filePath\", \"cwd\", \"directory\", \"dir\", \"target\"] as const;\nconst PATH_LIST_ARGUMENT_KEYS = [\"paths\", \"files\"] as const;\n\nexport function extractPathArguments(params: unknown): string[] {\n\tif (!params || typeof params !== \"object\") return [];\n\tconst record = params as Record<string, unknown>;\n\tconst found: string[] = [];\n\tfor (const key of PATH_ARGUMENT_KEYS) {\n\t\tconst value = record[key];\n\t\tif (typeof value === \"string\" && value.length > 0) found.push(value);\n\t}\n\tfor (const key of PATH_LIST_ARGUMENT_KEYS) {\n\t\tconst value = record[key];\n\t\tif (Array.isArray(value)) {\n\t\t\tfor (const entry of value) {\n\t\t\t\tif (typeof entry === \"string\" && entry.length > 0) found.push(entry);\n\t\t\t}\n\t\t}\n\t}\n\treturn found;\n}\n\nfunction isWithinRoot(target: string, root: string): boolean {\n\tconst relativePath = relative(root, target);\n\treturn (\n\t\trelativePath === \"\" ||\n\t\t(!relativePath.startsWith(`..${sep}`) && relativePath !== \"..\" && !isAbsolute(relativePath))\n\t);\n}\n\n/**\n * Deny wins over allow; an empty/absent allow list means \"no positive scope restriction\"\n * (only denies apply) — mirroring the resource-profile filter semantics.\n */\nexport function isPathWithinEnvelope(envelope: CapabilityEnvelope, rawPath: string, cwd: string): boolean {\n\tconst target = resolve(cwd, rawPath);\n\tfor (const denied of envelope.deniedPaths ?? []) {\n\t\tif (isWithinRoot(target, resolve(cwd, denied))) return false;\n\t}\n\tconst allowed = envelope.allowedPaths ?? [];\n\tif (allowed.length === 0) return true;\n\treturn allowed.some((root) => isWithinRoot(target, resolve(cwd, root)));\n}\n\nexport interface EnvelopeScopedTool {\n\tname: string;\n\texecute: (...args: unknown[]) => unknown;\n}\n\n/**\n * Wrap a tool so every path-bearing argument is scope-checked when it RUNS. The wrapped tool is\n * shape-identical; params are conventionally the second execute argument (toolCallId, params, …).\n */\nexport function wrapToolWithEnvelopeScope<T extends EnvelopeScopedTool>(\n\ttool: T,\n\tenvelope: CapabilityEnvelope,\n\tcwd: string,\n): T {\n\treturn {\n\t\t...tool,\n\t\texecute: (...args: unknown[]) => {\n\t\t\tconst params = args[1];\n\t\t\tfor (const rawPath of extractPathArguments(params)) {\n\t\t\t\tif (!isPathWithinEnvelope(envelope, rawPath, cwd)) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tcontent: [\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\t\ttext: `envelope_path_denied: \"${rawPath}\" is outside envelope ${envelope.id}'s path scope. The tool was NOT run.`,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t],\n\t\t\t\t\t\tdetails: { outcome: \"envelope_path_denied\", tool: tool.name, path: rawPath, envelopeId: envelope.id },\n\t\t\t\t\t\tisError: true,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn tool.execute(...args);\n\t\t},\n\t};\n}\n"]}
1
+ {"version":3,"file":"envelope-enforcement.js","sourceRoot":"","sources":["../../../src/core/autonomy/envelope-enforcement.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,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;GAGG;AACH,MAAM,UAAU,yBAAyB,CACxC,IAAO,EACP,QAA4B,EAC5B,GAAW,EACP;IACJ,OAAO;QACN,GAAG,IAAI;QACP,OAAO,EAAE,CAAC,GAAG,IAAe,EAAE,EAAE,CAAC;YAChC,MAAM,MAAM,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC;YACvB,KAAK,MAAM,OAAO,IAAI,oBAAoB,CAAC,MAAM,CAAC,EAAE,CAAC;gBACpD,IAAI,CAAC,oBAAoB,CAAC,QAAQ,EAAE,OAAO,EAAE,GAAG,CAAC,EAAE,CAAC;oBACnD,OAAO;wBACN,OAAO,EAAE;4BACR;gCACC,IAAI,EAAE,MAAM;gCACZ,IAAI,EAAE,0BAA0B,OAAO,yBAAyB,QAAQ,CAAC,EAAE,sCAAsC;6BACjH;yBACD;wBACD,OAAO,EAAE,EAAE,OAAO,EAAE,sBAAsB,EAAE,IAAI,EAAE,IAAI,CAAC,IAAI,EAAE,IAAI,EAAE,OAAO,EAAE,UAAU,EAAE,QAAQ,CAAC,EAAE,EAAE;wBACrG,OAAO,EAAE,IAAI;qBACb,CAAC;gBACH,CAAC;YACF,CAAC;YACD,OAAO,IAAI,CAAC,OAAO,CAAC,GAAG,IAAI,CAAC,CAAC;QAAA,CAC7B;KACD,CAAC;AAAA,CACF","sourcesContent":["import { isAbsolute, relative, resolve, sep } from \"node:path\";\nimport type { CapabilityEnvelope } from \"./contracts.ts\";\nimport { safeRealpathSync } from \"./path-scope.ts\";\n\n/**\n * Tool-level envelope enforcement (G2 prerequisite for code-writing workers): the capability\n * envelope's `allowedPaths`/`deniedPaths` were previously VALIDATION-ONLY — recorded on the\n * envelope but never checked when a tool actually ran. This module wraps tools so path-bearing\n * arguments are checked AT EXECUTION TIME, structurally refusing out-of-scope paths the same way\n * a failed script can never look like success: the refusal is an isError result with a stable\n * outcome code, never a silent no-op.\n */\n\nconst PATH_ARGUMENT_KEYS = [\"path\", \"file_path\", \"filePath\", \"cwd\", \"directory\", \"dir\", \"target\"] as const;\nconst PATH_LIST_ARGUMENT_KEYS = [\"paths\", \"files\"] as const;\n\nexport function extractPathArguments(params: unknown): string[] {\n\tif (!params || typeof params !== \"object\") return [];\n\tconst record = params as Record<string, unknown>;\n\tconst found: string[] = [];\n\tfor (const key of PATH_ARGUMENT_KEYS) {\n\t\tconst value = record[key];\n\t\tif (typeof value === \"string\" && value.length > 0) found.push(value);\n\t}\n\tfor (const key of PATH_LIST_ARGUMENT_KEYS) {\n\t\tconst value = record[key];\n\t\tif (Array.isArray(value)) {\n\t\t\tfor (const entry of value) {\n\t\t\t\tif (typeof entry === \"string\" && entry.length > 0) found.push(entry);\n\t\t\t}\n\t\t}\n\t}\n\treturn found;\n}\n\nfunction isWithinRoot(target: string, root: string): boolean {\n\tconst relativePath = relative(root, target);\n\treturn (\n\t\trelativePath === \"\" ||\n\t\t(!relativePath.startsWith(`..${sep}`) && relativePath !== \"..\" && !isAbsolute(relativePath))\n\t);\n}\n\n/**\n * Deny wins over allow; an empty/absent allow list means \"no positive scope restriction\"\n * (only denies apply) — mirroring the resource-profile filter semantics.\n *\n * Both the target and every scope root are resolved through the real filesystem\n * (symlinks expanded in the existing prefix) before comparison: a pre-existing symlink\n * under an allowed root cannot smuggle a write outside the scope, and a shortcut into a\n * denied subtree is still denied. An unresolvable target fails closed.\n */\nexport function isPathWithinEnvelope(envelope: CapabilityEnvelope, rawPath: string, cwd: string): boolean {\n\tlet target: string;\n\ttry {\n\t\ttarget = safeRealpathSync(resolve(cwd, rawPath));\n\t} catch {\n\t\treturn false;\n\t}\n\tfor (const denied of envelope.deniedPaths ?? []) {\n\t\ttry {\n\t\t\tif (isWithinRoot(target, safeRealpathSync(resolve(cwd, denied)))) return false;\n\t\t} catch {\n\t\t\t// Mirror checkPathScope: an unresolvable deny root cannot match anything.\n\t\t}\n\t}\n\tconst allowed = envelope.allowedPaths ?? [];\n\tif (allowed.length === 0) return true;\n\treturn allowed.some((root) => {\n\t\ttry {\n\t\t\treturn isWithinRoot(target, safeRealpathSync(resolve(cwd, root)));\n\t\t} catch {\n\t\t\treturn false;\n\t\t}\n\t});\n}\n\nexport interface EnvelopeScopedTool {\n\tname: string;\n\texecute: (...args: unknown[]) => unknown;\n}\n\n/**\n * Wrap a tool so every path-bearing argument is scope-checked when it RUNS. The wrapped tool is\n * shape-identical; params are conventionally the second execute argument (toolCallId, params, …).\n */\nexport function wrapToolWithEnvelopeScope<T extends EnvelopeScopedTool>(\n\ttool: T,\n\tenvelope: CapabilityEnvelope,\n\tcwd: string,\n): T {\n\treturn {\n\t\t...tool,\n\t\texecute: (...args: unknown[]) => {\n\t\t\tconst params = args[1];\n\t\t\tfor (const rawPath of extractPathArguments(params)) {\n\t\t\t\tif (!isPathWithinEnvelope(envelope, rawPath, cwd)) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tcontent: [\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\t\ttext: `envelope_path_denied: \"${rawPath}\" is outside envelope ${envelope.id}'s path scope. The tool was NOT run.`,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t],\n\t\t\t\t\t\tdetails: { outcome: \"envelope_path_denied\", tool: tool.name, path: rawPath, envelopeId: envelope.id },\n\t\t\t\t\t\tisError: true,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn tool.execute(...args);\n\t\t},\n\t};\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"path-scope.d.ts","sourceRoot":"","sources":["../../../src/core/autonomy/path-scope.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,SAAS,EAAE,iBAAiB,EAAE,MAAM,gBAAgB,CAAC;AAEnE;;;;GAIG;AACH,wBAAgB,gBAAgB,CAAC,UAAU,EAAE,MAAM,GAAG,MAAM,CAe3D;AAOD,wBAAgB,cAAc,CAAC,KAAK,EAAE,SAAS,EAAE,UAAU,EAAE,MAAM,GAAG,iBAAiB,CAqGtF","sourcesContent":["import fs from \"node:fs\";\nimport path from \"node:path\";\nimport type { PathScope, PathScopeDecision } from \"./contracts.ts\";\n\n/**\n * Resolves the real path of a target. If the target does not exist, it recursively\n * resolves the deepest existing parent directory and then appends the non-existent\n * remainder, ensuring that any symlinks in the existing path prefix are expanded.\n */\nexport function safeRealpathSync(targetPath: string): string {\n\tconst absolutePath = path.resolve(targetPath);\n\n\tif (fs.existsSync(absolutePath)) {\n\t\treturn fs.realpathSync(absolutePath);\n\t}\n\n\tconst parent = path.dirname(absolutePath);\n\t// Base case: if parent is the same as absolutePath, we've hit the root\n\tif (parent === absolutePath) {\n\t\treturn absolutePath;\n\t}\n\n\tconst resolvedParent = safeRealpathSync(parent);\n\treturn path.join(resolvedParent, path.basename(absolutePath));\n}\n\nfunction isPathInside(target: string, root: string): boolean {\n\tconst rootWithSep = root.endsWith(path.sep) ? root : `${root}${path.sep}`;\n\treturn target === root || target.startsWith(rootWithSep);\n}\n\nexport function checkPathScope(scope: PathScope, targetPath: string): PathScopeDecision {\n\tif (!targetPath) {\n\t\treturn {\n\t\t\tkind: \"missing\",\n\t\t\tpath: targetPath,\n\t\t\treasonCode: \"empty_path\",\n\t\t};\n\t}\n\n\tlet resolvedTarget: string;\n\ttry {\n\t\tresolvedTarget = safeRealpathSync(targetPath);\n\t} catch {\n\t\t// If we can't resolve the path at all (e.g. permission error), fail safely\n\t\treturn {\n\t\t\tkind: \"outside\",\n\t\t\tpath: targetPath,\n\t\t\treasonCode: \"unresolvable_target\",\n\t\t};\n\t}\n\n\tlet resolvedRoot: string;\n\ttry {\n\t\tresolvedRoot = safeRealpathSync(scope.root);\n\t} catch {\n\t\treturn {\n\t\t\tkind: \"outside\",\n\t\t\tpath: targetPath,\n\t\t\treasonCode: \"unresolvable_root\",\n\t\t};\n\t}\n\n\t// First, it must be inside the main root\n\tif (!isPathInside(resolvedTarget, resolvedRoot)) {\n\t\treturn {\n\t\t\tkind: \"outside\",\n\t\t\tpath: targetPath,\n\t\t\tresolvedPath: resolvedTarget,\n\t\t\treasonCode: \"outside_root\",\n\t\t};\n\t}\n\n\t// Check deniedPaths (overrides allowedPaths)\n\tif (scope.deniedPaths && scope.deniedPaths.length > 0) {\n\t\tfor (const denied of scope.deniedPaths) {\n\t\t\ttry {\n\t\t\t\tconst resolvedDenied = safeRealpathSync(denied);\n\t\t\t\tif (isPathInside(resolvedTarget, resolvedDenied)) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tkind: \"denied\",\n\t\t\t\t\t\tpath: targetPath,\n\t\t\t\t\t\tresolvedPath: resolvedTarget,\n\t\t\t\t\t\tmatchedRule: denied,\n\t\t\t\t\t\treasonCode: \"matches_denied_path\",\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t} catch {}\n\t\t}\n\t}\n\n\t// Check allowedPaths\n\tif (scope.allowedPaths && scope.allowedPaths.length > 0) {\n\t\tlet isAllowed = false;\n\t\tlet matchedAllowed: string | undefined;\n\n\t\tfor (const allowed of scope.allowedPaths) {\n\t\t\ttry {\n\t\t\t\tconst resolvedAllowed = safeRealpathSync(allowed);\n\t\t\t\tif (isPathInside(resolvedTarget, resolvedAllowed)) {\n\t\t\t\t\tisAllowed = true;\n\t\t\t\t\tmatchedAllowed = allowed;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t} catch {}\n\t\t}\n\n\t\tif (!isAllowed) {\n\t\t\treturn {\n\t\t\t\tkind: \"outside\",\n\t\t\t\tpath: targetPath,\n\t\t\t\tresolvedPath: resolvedTarget,\n\t\t\t\treasonCode: \"outside_allowed_paths\",\n\t\t\t};\n\t\t}\n\n\t\treturn {\n\t\t\tkind: \"inside\",\n\t\t\tpath: targetPath,\n\t\t\tresolvedPath: resolvedTarget,\n\t\t\tmatchedRule: matchedAllowed,\n\t\t\treasonCode: \"inside_allowed_paths\",\n\t\t};\n\t}\n\n\treturn {\n\t\tkind: \"inside\",\n\t\tpath: targetPath,\n\t\tresolvedPath: resolvedTarget,\n\t\tmatchedRule: scope.root,\n\t\treasonCode: \"inside_root\",\n\t};\n}\n"]}
1
+ {"version":3,"file":"path-scope.d.ts","sourceRoot":"","sources":["../../../src/core/autonomy/path-scope.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,SAAS,EAAE,iBAAiB,EAAE,MAAM,gBAAgB,CAAC;AAOnE;;;;GAIG;AACH,wBAAgB,gBAAgB,CAAC,UAAU,EAAE,MAAM,GAAG,MAAM,CAE3D;AAiDD,wBAAgB,cAAc,CAAC,KAAK,EAAE,SAAS,EAAE,UAAU,EAAE,MAAM,GAAG,iBAAiB,CAqGtF","sourcesContent":["import fs from \"node:fs\";\nimport path from \"node:path\";\nimport type { PathScope, PathScopeDecision } from \"./contracts.ts\";\n\n// Bounds the symlink-following recursion in resolveSafely: a chain of dangling links is finite\n// in practice, and a genuine symlink cycle (a -> b -> a) must fail closed with a throw rather\n// than recurse forever.\nconst MAX_SYMLINK_HOPS = 32;\n\n/**\n * Resolves the real path of a target. If the target does not exist, it recursively\n * resolves the deepest existing parent directory and then appends the non-existent\n * remainder, ensuring that any symlinks in the existing path prefix are expanded.\n */\nexport function safeRealpathSync(targetPath: string): string {\n\treturn resolveSafely(path.resolve(targetPath), 0);\n}\n\nfunction resolveSafely(absolutePath: string, hops: number): string {\n\tif (hops > MAX_SYMLINK_HOPS) {\n\t\tthrow new Error(`safeRealpathSync: exceeded ${MAX_SYMLINK_HOPS} symlink hops resolving \"${absolutePath}\"`);\n\t}\n\n\tif (fs.existsSync(absolutePath)) {\n\t\treturn fs.realpathSync(absolutePath);\n\t}\n\n\t// existsSync FOLLOWS symlinks, so it reports false for a DANGLING link (the link exists but\n\t// its target does not) — the same as a path that plain doesn't exist at all. Without this\n\t// lstat check, a dangling leaf would fall straight into the lexical parent-join below, never\n\t// dereferencing the link itself. That would let a dangling symlink placed inside an allowed\n\t// root smuggle writes to wherever it points, since the write itself (e.g. writeFileSync) DOES\n\t// follow the link. lstatSync throws ENOENT for a path that truly doesn't exist anywhere in\n\t// the chain — that case falls through to the parent-recursion branch below, unchanged.\n\tlet lstat: ReturnType<typeof fs.lstatSync> | undefined;\n\ttry {\n\t\tlstat = fs.lstatSync(absolutePath);\n\t} catch {\n\t\tlstat = undefined;\n\t}\n\n\tif (lstat?.isSymbolicLink()) {\n\t\tconst linkTarget = fs.readlinkSync(absolutePath);\n\t\tconst resolvedParent = resolveSafely(path.dirname(absolutePath), hops + 1);\n\t\tconst resolvedTarget = path.isAbsolute(linkTarget)\n\t\t\t? path.resolve(linkTarget)\n\t\t\t: path.resolve(resolvedParent, linkTarget);\n\t\treturn resolveSafely(resolvedTarget, hops + 1);\n\t}\n\n\tconst parent = path.dirname(absolutePath);\n\t// Base case: if parent is the same as absolutePath, we've hit the root\n\tif (parent === absolutePath) {\n\t\treturn absolutePath;\n\t}\n\n\tconst resolvedParent = resolveSafely(parent, hops + 1);\n\treturn path.join(resolvedParent, path.basename(absolutePath));\n}\n\nfunction isPathInside(target: string, root: string): boolean {\n\tconst rootWithSep = root.endsWith(path.sep) ? root : `${root}${path.sep}`;\n\treturn target === root || target.startsWith(rootWithSep);\n}\n\nexport function checkPathScope(scope: PathScope, targetPath: string): PathScopeDecision {\n\tif (!targetPath) {\n\t\treturn {\n\t\t\tkind: \"missing\",\n\t\t\tpath: targetPath,\n\t\t\treasonCode: \"empty_path\",\n\t\t};\n\t}\n\n\tlet resolvedTarget: string;\n\ttry {\n\t\tresolvedTarget = safeRealpathSync(targetPath);\n\t} catch {\n\t\t// If we can't resolve the path at all (e.g. permission error), fail safely\n\t\treturn {\n\t\t\tkind: \"outside\",\n\t\t\tpath: targetPath,\n\t\t\treasonCode: \"unresolvable_target\",\n\t\t};\n\t}\n\n\tlet resolvedRoot: string;\n\ttry {\n\t\tresolvedRoot = safeRealpathSync(scope.root);\n\t} catch {\n\t\treturn {\n\t\t\tkind: \"outside\",\n\t\t\tpath: targetPath,\n\t\t\treasonCode: \"unresolvable_root\",\n\t\t};\n\t}\n\n\t// First, it must be inside the main root\n\tif (!isPathInside(resolvedTarget, resolvedRoot)) {\n\t\treturn {\n\t\t\tkind: \"outside\",\n\t\t\tpath: targetPath,\n\t\t\tresolvedPath: resolvedTarget,\n\t\t\treasonCode: \"outside_root\",\n\t\t};\n\t}\n\n\t// Check deniedPaths (overrides allowedPaths)\n\tif (scope.deniedPaths && scope.deniedPaths.length > 0) {\n\t\tfor (const denied of scope.deniedPaths) {\n\t\t\ttry {\n\t\t\t\tconst resolvedDenied = safeRealpathSync(denied);\n\t\t\t\tif (isPathInside(resolvedTarget, resolvedDenied)) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tkind: \"denied\",\n\t\t\t\t\t\tpath: targetPath,\n\t\t\t\t\t\tresolvedPath: resolvedTarget,\n\t\t\t\t\t\tmatchedRule: denied,\n\t\t\t\t\t\treasonCode: \"matches_denied_path\",\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t} catch {}\n\t\t}\n\t}\n\n\t// Check allowedPaths\n\tif (scope.allowedPaths && scope.allowedPaths.length > 0) {\n\t\tlet isAllowed = false;\n\t\tlet matchedAllowed: string | undefined;\n\n\t\tfor (const allowed of scope.allowedPaths) {\n\t\t\ttry {\n\t\t\t\tconst resolvedAllowed = safeRealpathSync(allowed);\n\t\t\t\tif (isPathInside(resolvedTarget, resolvedAllowed)) {\n\t\t\t\t\tisAllowed = true;\n\t\t\t\t\tmatchedAllowed = allowed;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t} catch {}\n\t\t}\n\n\t\tif (!isAllowed) {\n\t\t\treturn {\n\t\t\t\tkind: \"outside\",\n\t\t\t\tpath: targetPath,\n\t\t\t\tresolvedPath: resolvedTarget,\n\t\t\t\treasonCode: \"outside_allowed_paths\",\n\t\t\t};\n\t\t}\n\n\t\treturn {\n\t\t\tkind: \"inside\",\n\t\t\tpath: targetPath,\n\t\t\tresolvedPath: resolvedTarget,\n\t\t\tmatchedRule: matchedAllowed,\n\t\t\treasonCode: \"inside_allowed_paths\",\n\t\t};\n\t}\n\n\treturn {\n\t\tkind: \"inside\",\n\t\tpath: targetPath,\n\t\tresolvedPath: resolvedTarget,\n\t\tmatchedRule: scope.root,\n\t\treasonCode: \"inside_root\",\n\t};\n}\n"]}
@@ -1,21 +1,52 @@
1
1
  import fs from "node:fs";
2
2
  import path from "node:path";
3
+ // Bounds the symlink-following recursion in resolveSafely: a chain of dangling links is finite
4
+ // in practice, and a genuine symlink cycle (a -> b -> a) must fail closed with a throw rather
5
+ // than recurse forever.
6
+ const MAX_SYMLINK_HOPS = 32;
3
7
  /**
4
8
  * Resolves the real path of a target. If the target does not exist, it recursively
5
9
  * resolves the deepest existing parent directory and then appends the non-existent
6
10
  * remainder, ensuring that any symlinks in the existing path prefix are expanded.
7
11
  */
8
12
  export function safeRealpathSync(targetPath) {
9
- const absolutePath = path.resolve(targetPath);
13
+ return resolveSafely(path.resolve(targetPath), 0);
14
+ }
15
+ function resolveSafely(absolutePath, hops) {
16
+ if (hops > MAX_SYMLINK_HOPS) {
17
+ throw new Error(`safeRealpathSync: exceeded ${MAX_SYMLINK_HOPS} symlink hops resolving "${absolutePath}"`);
18
+ }
10
19
  if (fs.existsSync(absolutePath)) {
11
20
  return fs.realpathSync(absolutePath);
12
21
  }
22
+ // existsSync FOLLOWS symlinks, so it reports false for a DANGLING link (the link exists but
23
+ // its target does not) — the same as a path that plain doesn't exist at all. Without this
24
+ // lstat check, a dangling leaf would fall straight into the lexical parent-join below, never
25
+ // dereferencing the link itself. That would let a dangling symlink placed inside an allowed
26
+ // root smuggle writes to wherever it points, since the write itself (e.g. writeFileSync) DOES
27
+ // follow the link. lstatSync throws ENOENT for a path that truly doesn't exist anywhere in
28
+ // the chain — that case falls through to the parent-recursion branch below, unchanged.
29
+ let lstat;
30
+ try {
31
+ lstat = fs.lstatSync(absolutePath);
32
+ }
33
+ catch {
34
+ lstat = undefined;
35
+ }
36
+ if (lstat?.isSymbolicLink()) {
37
+ const linkTarget = fs.readlinkSync(absolutePath);
38
+ const resolvedParent = resolveSafely(path.dirname(absolutePath), hops + 1);
39
+ const resolvedTarget = path.isAbsolute(linkTarget)
40
+ ? path.resolve(linkTarget)
41
+ : path.resolve(resolvedParent, linkTarget);
42
+ return resolveSafely(resolvedTarget, hops + 1);
43
+ }
13
44
  const parent = path.dirname(absolutePath);
14
45
  // Base case: if parent is the same as absolutePath, we've hit the root
15
46
  if (parent === absolutePath) {
16
47
  return absolutePath;
17
48
  }
18
- const resolvedParent = safeRealpathSync(parent);
49
+ const resolvedParent = resolveSafely(parent, hops + 1);
19
50
  return path.join(resolvedParent, path.basename(absolutePath));
20
51
  }
21
52
  function isPathInside(target, root) {
@@ -1 +1 @@
1
- {"version":3,"file":"path-scope.js","sourceRoot":"","sources":["../../../src/core/autonomy/path-scope.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,SAAS,CAAC;AACzB,OAAO,IAAI,MAAM,WAAW,CAAC;AAG7B;;;;GAIG;AACH,MAAM,UAAU,gBAAgB,CAAC,UAAkB,EAAU;IAC5D,MAAM,YAAY,GAAG,IAAI,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC;IAE9C,IAAI,EAAE,CAAC,UAAU,CAAC,YAAY,CAAC,EAAE,CAAC;QACjC,OAAO,EAAE,CAAC,YAAY,CAAC,YAAY,CAAC,CAAC;IACtC,CAAC;IAED,MAAM,MAAM,GAAG,IAAI,CAAC,OAAO,CAAC,YAAY,CAAC,CAAC;IAC1C,uEAAuE;IACvE,IAAI,MAAM,KAAK,YAAY,EAAE,CAAC;QAC7B,OAAO,YAAY,CAAC;IACrB,CAAC;IAED,MAAM,cAAc,GAAG,gBAAgB,CAAC,MAAM,CAAC,CAAC;IAChD,OAAO,IAAI,CAAC,IAAI,CAAC,cAAc,EAAE,IAAI,CAAC,QAAQ,CAAC,YAAY,CAAC,CAAC,CAAC;AAAA,CAC9D;AAED,SAAS,YAAY,CAAC,MAAc,EAAE,IAAY,EAAW;IAC5D,MAAM,WAAW,GAAG,IAAI,CAAC,QAAQ,CAAC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CAAC;IAED,OAAO;QACN,IAAI,EAAE,QAAQ;QACd,IAAI,EAAE,UAAU;QAChB,YAAY,EAAE,cAAc;QAC5B,WAAW,EAAE,KAAK,CAAC,IAAI;QACvB,UAAU,EAAE,aAAa;KACzB,CAAC;AAAA,CACF","sourcesContent":["import fs from \"node:fs\";\nimport path from \"node:path\";\nimport type { PathScope, PathScopeDecision } from \"./contracts.ts\";\n\n/**\n * Resolves the real path of a target. If the target does not exist, it recursively\n * resolves the deepest existing parent directory and then appends the non-existent\n * remainder, ensuring that any symlinks in the existing path prefix are expanded.\n */\nexport function safeRealpathSync(targetPath: string): string {\n\tconst absolutePath = path.resolve(targetPath);\n\n\tif (fs.existsSync(absolutePath)) {\n\t\treturn fs.realpathSync(absolutePath);\n\t}\n\n\tconst parent = path.dirname(absolutePath);\n\t// Base case: if parent is the same as absolutePath, we've hit the root\n\tif (parent === absolutePath) {\n\t\treturn absolutePath;\n\t}\n\n\tconst resolvedParent = safeRealpathSync(parent);\n\treturn path.join(resolvedParent, path.basename(absolutePath));\n}\n\nfunction isPathInside(target: string, root: string): boolean {\n\tconst rootWithSep = root.endsWith(path.sep) ? root : `${root}${path.sep}`;\n\treturn target === root || target.startsWith(rootWithSep);\n}\n\nexport function checkPathScope(scope: PathScope, targetPath: string): PathScopeDecision {\n\tif (!targetPath) {\n\t\treturn {\n\t\t\tkind: \"missing\",\n\t\t\tpath: targetPath,\n\t\t\treasonCode: \"empty_path\",\n\t\t};\n\t}\n\n\tlet resolvedTarget: string;\n\ttry {\n\t\tresolvedTarget = safeRealpathSync(targetPath);\n\t} catch {\n\t\t// If we can't resolve the path at all (e.g. permission error), fail safely\n\t\treturn {\n\t\t\tkind: \"outside\",\n\t\t\tpath: targetPath,\n\t\t\treasonCode: \"unresolvable_target\",\n\t\t};\n\t}\n\n\tlet resolvedRoot: string;\n\ttry {\n\t\tresolvedRoot = safeRealpathSync(scope.root);\n\t} catch {\n\t\treturn {\n\t\t\tkind: \"outside\",\n\t\t\tpath: targetPath,\n\t\t\treasonCode: \"unresolvable_root\",\n\t\t};\n\t}\n\n\t// First, it must be inside the main root\n\tif (!isPathInside(resolvedTarget, resolvedRoot)) {\n\t\treturn {\n\t\t\tkind: \"outside\",\n\t\t\tpath: targetPath,\n\t\t\tresolvedPath: resolvedTarget,\n\t\t\treasonCode: \"outside_root\",\n\t\t};\n\t}\n\n\t// Check deniedPaths (overrides allowedPaths)\n\tif (scope.deniedPaths && scope.deniedPaths.length > 0) {\n\t\tfor (const denied of scope.deniedPaths) {\n\t\t\ttry {\n\t\t\t\tconst resolvedDenied = safeRealpathSync(denied);\n\t\t\t\tif (isPathInside(resolvedTarget, resolvedDenied)) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tkind: \"denied\",\n\t\t\t\t\t\tpath: targetPath,\n\t\t\t\t\t\tresolvedPath: resolvedTarget,\n\t\t\t\t\t\tmatchedRule: denied,\n\t\t\t\t\t\treasonCode: \"matches_denied_path\",\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t} catch {}\n\t\t}\n\t}\n\n\t// Check allowedPaths\n\tif (scope.allowedPaths && scope.allowedPaths.length > 0) {\n\t\tlet isAllowed = false;\n\t\tlet matchedAllowed: string | undefined;\n\n\t\tfor (const allowed of scope.allowedPaths) {\n\t\t\ttry {\n\t\t\t\tconst resolvedAllowed = safeRealpathSync(allowed);\n\t\t\t\tif (isPathInside(resolvedTarget, resolvedAllowed)) {\n\t\t\t\t\tisAllowed = true;\n\t\t\t\t\tmatchedAllowed = allowed;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t} catch {}\n\t\t}\n\n\t\tif (!isAllowed) {\n\t\t\treturn {\n\t\t\t\tkind: \"outside\",\n\t\t\t\tpath: targetPath,\n\t\t\t\tresolvedPath: resolvedTarget,\n\t\t\t\treasonCode: \"outside_allowed_paths\",\n\t\t\t};\n\t\t}\n\n\t\treturn {\n\t\t\tkind: \"inside\",\n\t\t\tpath: targetPath,\n\t\t\tresolvedPath: resolvedTarget,\n\t\t\tmatchedRule: matchedAllowed,\n\t\t\treasonCode: \"inside_allowed_paths\",\n\t\t};\n\t}\n\n\treturn {\n\t\tkind: \"inside\",\n\t\tpath: targetPath,\n\t\tresolvedPath: resolvedTarget,\n\t\tmatchedRule: scope.root,\n\t\treasonCode: \"inside_root\",\n\t};\n}\n"]}
1
+ {"version":3,"file":"path-scope.js","sourceRoot":"","sources":["../../../src/core/autonomy/path-scope.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,SAAS,CAAC;AACzB,OAAO,IAAI,MAAM,WAAW,CAAC;AAG7B,+FAA+F;AAC/F,8FAA8F;AAC9F,wBAAwB;AACxB,MAAM,gBAAgB,GAAG,EAAE,CAAC;AAE5B;;;;GAIG;AACH,MAAM,UAAU,gBAAgB,CAAC,UAAkB,EAAU;IAC5D,OAAO,aAAa,CAAC,IAAI,CAAC,OAAO,CAAC,UAAU,CAAC,EAAE,CAAC,CAAC,CAAC;AAAA,CAClD;AAED,SAAS,aAAa,CAAC,YAAoB,EAAE,IAAY,EAAU;IAClE,IAAI,IAAI,GAAG,gBAAgB,EAAE,CAAC;QAC7B,MAAM,IAAI,KAAK,CAAC,8BAA8B,gBAAgB,4BAA4B,YAAY,GAAG,CAAC,CAAC;IAC5G,CAAC;IAED,IAAI,EAAE,CAAC,UAAU,CAAC,YAAY,CAAC,EAAE,CAAC;QACjC,OAAO,EAAE,CAAC,YAAY,CAAC,YAAY,CAAC,CAAC;IACtC,CAAC;IAED,4FAA4F;IAC5F,4FAA0F;IAC1F,6FAA6F;IAC7F,4FAA4F;IAC5F,8FAA8F;IAC9F,2FAA2F;IAC3F,yFAAuF;IACvF,IAAI,KAAkD,CAAC;IACvD,IAAI,CAAC;QACJ,KAAK,GAAG,EAAE,CAAC,SAAS,CAAC,YAAY,CAAC,CAAC;IACpC,CAAC;IAAC,MAAM,CAAC;QACR,KAAK,GAAG,SAAS,CAAC;IACnB,CAAC;IAED,IAAI,KAAK,EAAE,cAAc,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AC;gBACH,CAAC;YACF,CAAC;YAAC,MAAM,CAAC,CAAA,CAAC;QACX,CAAC;IACF,CAAC;IAED,qBAAqB;IACrB,IAAI,KAAK,CAAC,YAAY,IAAI,KAAK,CAAC,YAAY,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QACzD,IAAI,SAAS,GAAG,KAAK,CAAC;QACtB,IAAI,cAAkC,CAAC;QAEvC,KAAK,MAAM,OAAO,IAAI,KAAK,CAAC,YAAY,EAAE,CAAC;YAC1C,IAAI,CAAC;gBACJ,MAAM,eAAe,GAAG,gBAAgB,CAAC,OAAO,CAAC,CAAC;gBAClD,IAAI,YAAY,CAAC,cAAc,EAAE,eAAe,CAAC,EAAE,CAAC;oBACnD,SAAS,GAAG,IAAI,CAAC;oBACjB,cAAc,GAAG,OAAO,CAAC;oBACzB,MAAM;gBACP,CAAC;YACF,CAAC;YAAC,MAAM,CAAC,CAAA,CAAC;QACX,CAAC;QAED,IAAI,CAAC,SAAS,EAAE,CAAC;YAChB,OAAO;gBACN,IAAI,EAAE,SAAS;gBACf,IAAI,EAAE,UAAU;gBAChB,YAAY,EAAE,cAAc;gBAC5B,UAAU,EAAE,uBAAuB;aACnC,CAAC;QACH,CAAC;QAED,OAAO;YACN,IAAI,EAAE,QAAQ;YACd,IAAI,EAAE,UAAU;YAChB,YAAY,EAAE,cAAc;YAC5B,WAAW,EAAE,cAAc;YAC3B,UAAU,EAAE,sBAAsB;SAClC,CAAC;IACH,CAAC;IAED,OAAO;QACN,IAAI,EAAE,QAAQ;QACd,IAAI,EAAE,UAAU;QAChB,YAAY,EAAE,cAAc;QAC5B,WAAW,EAAE,KAAK,CAAC,IAAI;QACvB,UAAU,EAAE,aAAa;KACzB,CAAC;AAAA,CACF","sourcesContent":["import fs from \"node:fs\";\nimport path from \"node:path\";\nimport type { PathScope, PathScopeDecision } from \"./contracts.ts\";\n\n// Bounds the symlink-following recursion in resolveSafely: a chain of dangling links is finite\n// in practice, and a genuine symlink cycle (a -> b -> a) must fail closed with a throw rather\n// than recurse forever.\nconst MAX_SYMLINK_HOPS = 32;\n\n/**\n * Resolves the real path of a target. If the target does not exist, it recursively\n * resolves the deepest existing parent directory and then appends the non-existent\n * remainder, ensuring that any symlinks in the existing path prefix are expanded.\n */\nexport function safeRealpathSync(targetPath: string): string {\n\treturn resolveSafely(path.resolve(targetPath), 0);\n}\n\nfunction resolveSafely(absolutePath: string, hops: number): string {\n\tif (hops > MAX_SYMLINK_HOPS) {\n\t\tthrow new Error(`safeRealpathSync: exceeded ${MAX_SYMLINK_HOPS} symlink hops resolving \"${absolutePath}\"`);\n\t}\n\n\tif (fs.existsSync(absolutePath)) {\n\t\treturn fs.realpathSync(absolutePath);\n\t}\n\n\t// existsSync FOLLOWS symlinks, so it reports false for a DANGLING link (the link exists but\n\t// its target does not) — the same as a path that plain doesn't exist at all. Without this\n\t// lstat check, a dangling leaf would fall straight into the lexical parent-join below, never\n\t// dereferencing the link itself. That would let a dangling symlink placed inside an allowed\n\t// root smuggle writes to wherever it points, since the write itself (e.g. writeFileSync) DOES\n\t// follow the link. lstatSync throws ENOENT for a path that truly doesn't exist anywhere in\n\t// the chain — that case falls through to the parent-recursion branch below, unchanged.\n\tlet lstat: ReturnType<typeof fs.lstatSync> | undefined;\n\ttry {\n\t\tlstat = fs.lstatSync(absolutePath);\n\t} catch {\n\t\tlstat = undefined;\n\t}\n\n\tif (lstat?.isSymbolicLink()) {\n\t\tconst linkTarget = fs.readlinkSync(absolutePath);\n\t\tconst resolvedParent = resolveSafely(path.dirname(absolutePath), hops + 1);\n\t\tconst resolvedTarget = path.isAbsolute(linkTarget)\n\t\t\t? path.resolve(linkTarget)\n\t\t\t: path.resolve(resolvedParent, linkTarget);\n\t\treturn resolveSafely(resolvedTarget, hops + 1);\n\t}\n\n\tconst parent = path.dirname(absolutePath);\n\t// Base case: if parent is the same as absolutePath, we've hit the root\n\tif (parent === absolutePath) {\n\t\treturn absolutePath;\n\t}\n\n\tconst resolvedParent = resolveSafely(parent, hops + 1);\n\treturn path.join(resolvedParent, path.basename(absolutePath));\n}\n\nfunction isPathInside(target: string, root: string): boolean {\n\tconst rootWithSep = root.endsWith(path.sep) ? root : `${root}${path.sep}`;\n\treturn target === root || target.startsWith(rootWithSep);\n}\n\nexport function checkPathScope(scope: PathScope, targetPath: string): PathScopeDecision {\n\tif (!targetPath) {\n\t\treturn {\n\t\t\tkind: \"missing\",\n\t\t\tpath: targetPath,\n\t\t\treasonCode: \"empty_path\",\n\t\t};\n\t}\n\n\tlet resolvedTarget: string;\n\ttry {\n\t\tresolvedTarget = safeRealpathSync(targetPath);\n\t} catch {\n\t\t// If we can't resolve the path at all (e.g. permission error), fail safely\n\t\treturn {\n\t\t\tkind: \"outside\",\n\t\t\tpath: targetPath,\n\t\t\treasonCode: \"unresolvable_target\",\n\t\t};\n\t}\n\n\tlet resolvedRoot: string;\n\ttry {\n\t\tresolvedRoot = safeRealpathSync(scope.root);\n\t} catch {\n\t\treturn {\n\t\t\tkind: \"outside\",\n\t\t\tpath: targetPath,\n\t\t\treasonCode: \"unresolvable_root\",\n\t\t};\n\t}\n\n\t// First, it must be inside the main root\n\tif (!isPathInside(resolvedTarget, resolvedRoot)) {\n\t\treturn {\n\t\t\tkind: \"outside\",\n\t\t\tpath: targetPath,\n\t\t\tresolvedPath: resolvedTarget,\n\t\t\treasonCode: \"outside_root\",\n\t\t};\n\t}\n\n\t// Check deniedPaths (overrides allowedPaths)\n\tif (scope.deniedPaths && scope.deniedPaths.length > 0) {\n\t\tfor (const denied of scope.deniedPaths) {\n\t\t\ttry {\n\t\t\t\tconst resolvedDenied = safeRealpathSync(denied);\n\t\t\t\tif (isPathInside(resolvedTarget, resolvedDenied)) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tkind: \"denied\",\n\t\t\t\t\t\tpath: targetPath,\n\t\t\t\t\t\tresolvedPath: resolvedTarget,\n\t\t\t\t\t\tmatchedRule: denied,\n\t\t\t\t\t\treasonCode: \"matches_denied_path\",\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t} catch {}\n\t\t}\n\t}\n\n\t// Check allowedPaths\n\tif (scope.allowedPaths && scope.allowedPaths.length > 0) {\n\t\tlet isAllowed = false;\n\t\tlet matchedAllowed: string | undefined;\n\n\t\tfor (const allowed of scope.allowedPaths) {\n\t\t\ttry {\n\t\t\t\tconst resolvedAllowed = safeRealpathSync(allowed);\n\t\t\t\tif (isPathInside(resolvedTarget, resolvedAllowed)) {\n\t\t\t\t\tisAllowed = true;\n\t\t\t\t\tmatchedAllowed = allowed;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t} catch {}\n\t\t}\n\n\t\tif (!isAllowed) {\n\t\t\treturn {\n\t\t\t\tkind: \"outside\",\n\t\t\t\tpath: targetPath,\n\t\t\t\tresolvedPath: resolvedTarget,\n\t\t\t\treasonCode: \"outside_allowed_paths\",\n\t\t\t};\n\t\t}\n\n\t\treturn {\n\t\t\tkind: \"inside\",\n\t\t\tpath: targetPath,\n\t\t\tresolvedPath: resolvedTarget,\n\t\t\tmatchedRule: matchedAllowed,\n\t\t\treasonCode: \"inside_allowed_paths\",\n\t\t};\n\t}\n\n\treturn {\n\t\tkind: \"inside\",\n\t\tpath: targetPath,\n\t\tresolvedPath: resolvedTarget,\n\t\tmatchedRule: scope.root,\n\t\treasonCode: \"inside_root\",\n\t};\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"bash-executor.d.ts","sourceRoot":"","sources":["../../src/core/bash-executor.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AASH,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AAQtD,MAAM,WAAW,mBAAmB;IACnC,+DAA+D;IAC/D,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,IAAI,CAAC;IAClC,mCAAmC;IACnC,MAAM,CAAC,EAAE,WAAW,CAAC;IACrB,2FAA2F;IAC3F,eAAe,CAAC,EAAE,OAAO,CAAC;CAC1B;AAED,MAAM,WAAW,UAAU;IAC1B,sEAAsE;IACtE,MAAM,EAAE,MAAM,CAAC;IACf,wDAAwD;IACxD,QAAQ,EAAE,MAAM,GAAG,SAAS,CAAC;IAC7B,mDAAmD;IACnD,SAAS,EAAE,OAAO,CAAC;IACnB,uCAAuC;IACvC,SAAS,EAAE,OAAO,CAAC;IACnB,yFAAyF;IACzF,cAAc,CAAC,EAAE,MAAM,CAAC;CACxB;AAMD;;;GAGG;AACH,wBAAsB,yBAAyB,CAC9C,OAAO,EAAE,MAAM,EACf,GAAG,EAAE,MAAM,EACX,UAAU,EAAE,cAAc,EAC1B,OAAO,CAAC,EAAE,mBAAmB,GAC3B,OAAO,CAAC,UAAU,CAAC,CA8IrB","sourcesContent":["/**\n * Bash command execution with streaming support and cancellation.\n *\n * This module provides a unified bash execution implementation used by:\n * - AgentSession.executeBash() for interactive and RPC modes\n * - Direct calls from modes that need bash execution\n */\n\nimport { randomBytes } from \"node:crypto\";\nimport type { WriteStream } from \"node:fs\";\nimport { tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { stripAnsi } from \"../utils/ansi.ts\";\nimport { createSafeWriteStream } from \"../utils/safe-write-stream.ts\";\nimport { sanitizeBinaryOutput } from \"../utils/shell.ts\";\nimport type { BashOperations } from \"./tools/bash.ts\";\nimport { classifyGitCommand, executeFilteredGit } from \"./tools/git-filter.ts\";\nimport { DEFAULT_MAX_BYTES, truncateTail } from \"./tools/truncate.ts\";\n\n// ============================================================================\n// Types\n// ============================================================================\n\nexport interface BashExecutorOptions {\n\t/** Callback for streaming output chunks (already sanitized) */\n\tonChunk?: (chunk: string) => void;\n\t/** AbortSignal for cancellation */\n\tsignal?: AbortSignal;\n\t/** Enable conservative pi-native git output filtering for local default execution paths */\n\tenableGitFilter?: boolean;\n}\n\nexport interface BashResult {\n\t/** Combined stdout + stderr output (sanitized, possibly truncated) */\n\toutput: string;\n\t/** Process exit code (undefined if killed/cancelled) */\n\texitCode: number | undefined;\n\t/** Whether the command was cancelled via signal */\n\tcancelled: boolean;\n\t/** Whether the output was truncated */\n\ttruncated: boolean;\n\t/** Path to temp file containing full output (if output exceeded truncation threshold) */\n\tfullOutputPath?: string;\n}\n\n// ============================================================================\n// Implementation\n// ============================================================================\n\n/**\n * Execute a bash command using custom BashOperations.\n * Used for remote execution (SSH, containers, etc.).\n */\nexport async function executeBashWithOperations(\n\tcommand: string,\n\tcwd: string,\n\toperations: BashOperations,\n\toptions?: BashExecutorOptions,\n): Promise<BashResult> {\n\tif (options?.enableGitFilter) {\n\t\tconst classification = classifyGitCommand(command, process.env);\n\t\tif (classification.eligible && classification.subcommand) {\n\t\t\tconst res = await executeFilteredGit(\n\t\t\t\tcwd,\n\t\t\t\tclassification.subcommand,\n\t\t\t\tclassification.globalOptions || [],\n\t\t\t\tclassification.subcommandArgs || [],\n\t\t\t\t{ signal: options.signal },\n\t\t\t);\n\t\t\tif (res.exitCode !== -100) {\n\t\t\t\tconst rawBytes = res.rawBytes ?? Buffer.from(res.rawOut, \"utf-8\");\n\t\t\t\t// The filter already spills oversized output to a temp file; reuse it\n\t\t\t\t// instead of materializing another full copy here.\n\t\t\t\tlet fullOutputPath = res.fullOutputPath;\n\t\t\t\tif (fullOutputPath === undefined && rawBytes.length > DEFAULT_MAX_BYTES) {\n\t\t\t\t\tconst id = randomBytes(8).toString(\"hex\");\n\t\t\t\t\tfullOutputPath = join(tmpdir(), `pi-bash-${id}.log`);\n\t\t\t\t\tconst tempFileStream = createSafeWriteStream(fullOutputPath);\n\t\t\t\t\ttempFileStream.write(rawBytes);\n\t\t\t\t\ttempFileStream.end();\n\t\t\t\t}\n\t\t\t\toptions.onChunk?.(res.output);\n\t\t\t\treturn {\n\t\t\t\t\toutput: res.output,\n\t\t\t\t\texitCode: res.exitCode,\n\t\t\t\t\tcancelled: options.signal?.aborted ?? false,\n\t\t\t\t\ttruncated: res.fullOutputPath !== undefined || rawBytes.length > DEFAULT_MAX_BYTES,\n\t\t\t\t\tfullOutputPath,\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\t}\n\n\tconst outputChunks: string[] = [];\n\tlet outputBytes = 0;\n\tconst maxOutputBytes = DEFAULT_MAX_BYTES * 2;\n\n\tlet tempFilePath: string | undefined;\n\tlet tempFileStream: WriteStream | undefined;\n\tlet totalBytes = 0;\n\n\tconst ensureTempFile = () => {\n\t\tif (tempFilePath) {\n\t\t\treturn;\n\t\t}\n\t\tconst id = randomBytes(8).toString(\"hex\");\n\t\ttempFilePath = join(tmpdir(), `pi-bash-${id}.log`);\n\t\t// On stream failure (e.g. disk full), drop the artifact instead of\n\t\t// crashing the process; the rolling in-memory output is still returned.\n\t\ttempFileStream = createSafeWriteStream(tempFilePath, () => {\n\t\t\ttempFileStream = undefined;\n\t\t\ttempFilePath = undefined;\n\t\t});\n\t\tfor (const chunk of outputChunks) {\n\t\t\ttempFileStream.write(chunk);\n\t\t}\n\t};\n\n\tconst decoder = new TextDecoder();\n\n\tconst onData = (data: Buffer) => {\n\t\ttotalBytes += data.length;\n\n\t\t// Sanitize: strip ANSI, replace binary garbage, normalize newlines\n\t\tconst text = sanitizeBinaryOutput(stripAnsi(decoder.decode(data, { stream: true }))).replace(/\\r/g, \"\");\n\n\t\t// Start writing to temp file if exceeds threshold\n\t\tif (totalBytes > DEFAULT_MAX_BYTES) {\n\t\t\tensureTempFile();\n\t\t}\n\n\t\t// Guard writableEnded: custom BashOperations may deliver late onData\n\t\t// callbacks after an abort path has already ended the stream.\n\t\tif (tempFileStream && !tempFileStream.writableEnded) {\n\t\t\ttempFileStream.write(text);\n\t\t}\n\n\t\t// Keep rolling buffer\n\t\toutputChunks.push(text);\n\t\toutputBytes += text.length;\n\t\twhile (outputBytes > maxOutputBytes && outputChunks.length > 1) {\n\t\t\tconst removed = outputChunks.shift()!;\n\t\t\toutputBytes -= removed.length;\n\t\t}\n\n\t\t// Stream to callback\n\t\tif (options?.onChunk) {\n\t\t\toptions.onChunk(text);\n\t\t}\n\t};\n\n\ttry {\n\t\tconst result = await operations.exec(command, cwd, {\n\t\t\tonData,\n\t\t\tsignal: options?.signal,\n\t\t});\n\n\t\tconst fullOutput = outputChunks.join(\"\");\n\t\tconst truncationResult = truncateTail(fullOutput);\n\t\tif (truncationResult.truncated) {\n\t\t\tensureTempFile();\n\t\t}\n\t\tif (tempFileStream) {\n\t\t\ttempFileStream.end();\n\t\t}\n\t\tconst cancelled = options?.signal?.aborted ?? false;\n\n\t\treturn {\n\t\t\toutput: truncationResult.truncated ? truncationResult.content : fullOutput,\n\t\t\texitCode: cancelled ? undefined : (result.exitCode ?? undefined),\n\t\t\tcancelled,\n\t\t\ttruncated: truncationResult.truncated,\n\t\t\tfullOutputPath: tempFilePath,\n\t\t};\n\t} catch (err) {\n\t\t// Check if it was an abort\n\t\tif (options?.signal?.aborted) {\n\t\t\tconst fullOutput = outputChunks.join(\"\");\n\t\t\tconst truncationResult = truncateTail(fullOutput);\n\t\t\tif (truncationResult.truncated) {\n\t\t\t\tensureTempFile();\n\t\t\t}\n\t\t\tif (tempFileStream) {\n\t\t\t\ttempFileStream.end();\n\t\t\t}\n\t\t\treturn {\n\t\t\t\toutput: truncationResult.truncated ? truncationResult.content : fullOutput,\n\t\t\t\texitCode: undefined,\n\t\t\t\tcancelled: true,\n\t\t\t\ttruncated: truncationResult.truncated,\n\t\t\t\tfullOutputPath: tempFilePath,\n\t\t\t};\n\t\t}\n\n\t\tif (tempFileStream) {\n\t\t\ttempFileStream.end();\n\t\t}\n\n\t\tthrow err;\n\t}\n}\n"]}
1
+ {"version":3,"file":"bash-executor.d.ts","sourceRoot":"","sources":["../../src/core/bash-executor.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AASH,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AAQtD,MAAM,WAAW,mBAAmB;IACnC,+DAA+D;IAC/D,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,IAAI,CAAC;IAClC,mCAAmC;IACnC,MAAM,CAAC,EAAE,WAAW,CAAC;IACrB,2FAA2F;IAC3F,eAAe,CAAC,EAAE,OAAO,CAAC;CAC1B;AAED,MAAM,WAAW,UAAU;IAC1B,sEAAsE;IACtE,MAAM,EAAE,MAAM,CAAC;IACf,wDAAwD;IACxD,QAAQ,EAAE,MAAM,GAAG,SAAS,CAAC;IAC7B,mDAAmD;IACnD,SAAS,EAAE,OAAO,CAAC;IACnB,uCAAuC;IACvC,SAAS,EAAE,OAAO,CAAC;IACnB,yFAAyF;IACzF,cAAc,CAAC,EAAE,MAAM,CAAC;CACxB;AAMD;;;GAGG;AACH,wBAAsB,yBAAyB,CAC9C,OAAO,EAAE,MAAM,EACf,GAAG,EAAE,MAAM,EACX,UAAU,EAAE,cAAc,EAC1B,OAAO,CAAC,EAAE,mBAAmB,GAC3B,OAAO,CAAC,UAAU,CAAC,CAsJrB","sourcesContent":["/**\n * Bash command execution with streaming support and cancellation.\n *\n * This module provides a unified bash execution implementation used by:\n * - AgentSession.executeBash() for interactive and RPC modes\n * - Direct calls from modes that need bash execution\n */\n\nimport { randomBytes } from \"node:crypto\";\nimport type { WriteStream } from \"node:fs\";\nimport { tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { stripAnsi } from \"../utils/ansi.ts\";\nimport { createSafeWriteStream, endWriteStream } from \"../utils/safe-write-stream.ts\";\nimport { sanitizeBinaryOutput } from \"../utils/shell.ts\";\nimport type { BashOperations } from \"./tools/bash.ts\";\nimport { classifyGitCommand, executeFilteredGit } from \"./tools/git-filter.ts\";\nimport { DEFAULT_MAX_BYTES, truncateTail } from \"./tools/truncate.ts\";\n\n// ============================================================================\n// Types\n// ============================================================================\n\nexport interface BashExecutorOptions {\n\t/** Callback for streaming output chunks (already sanitized) */\n\tonChunk?: (chunk: string) => void;\n\t/** AbortSignal for cancellation */\n\tsignal?: AbortSignal;\n\t/** Enable conservative pi-native git output filtering for local default execution paths */\n\tenableGitFilter?: boolean;\n}\n\nexport interface BashResult {\n\t/** Combined stdout + stderr output (sanitized, possibly truncated) */\n\toutput: string;\n\t/** Process exit code (undefined if killed/cancelled) */\n\texitCode: number | undefined;\n\t/** Whether the command was cancelled via signal */\n\tcancelled: boolean;\n\t/** Whether the output was truncated */\n\ttruncated: boolean;\n\t/** Path to temp file containing full output (if output exceeded truncation threshold) */\n\tfullOutputPath?: string;\n}\n\n// ============================================================================\n// Implementation\n// ============================================================================\n\n/**\n * Execute a bash command using custom BashOperations.\n * Used for remote execution (SSH, containers, etc.).\n */\nexport async function executeBashWithOperations(\n\tcommand: string,\n\tcwd: string,\n\toperations: BashOperations,\n\toptions?: BashExecutorOptions,\n): Promise<BashResult> {\n\tif (options?.enableGitFilter) {\n\t\tconst classification = classifyGitCommand(command, process.env);\n\t\tif (classification.eligible && classification.subcommand) {\n\t\t\tconst res = await executeFilteredGit(\n\t\t\t\tcwd,\n\t\t\t\tclassification.subcommand,\n\t\t\t\tclassification.globalOptions || [],\n\t\t\t\tclassification.subcommandArgs || [],\n\t\t\t\t{ signal: options.signal },\n\t\t\t);\n\t\t\tif (res.exitCode !== -100) {\n\t\t\t\tconst rawBytes = res.rawBytes ?? Buffer.from(res.rawOut, \"utf-8\");\n\t\t\t\t// The filter already spills oversized output to a temp file; reuse it\n\t\t\t\t// instead of materializing another full copy here.\n\t\t\t\tlet fullOutputPath = res.fullOutputPath;\n\t\t\t\tif (fullOutputPath === undefined && rawBytes.length > DEFAULT_MAX_BYTES) {\n\t\t\t\t\tconst id = randomBytes(8).toString(\"hex\");\n\t\t\t\t\tconst spillPath = join(tmpdir(), `pi-bash-${id}.log`);\n\t\t\t\t\tfullOutputPath = spillPath;\n\t\t\t\t\t// On stream failure (e.g. disk full), drop the advertised path instead of\n\t\t\t\t\t// pointing at a partial/missing file.\n\t\t\t\t\tconst tempFileStream = createSafeWriteStream(spillPath, () => {\n\t\t\t\t\t\tfullOutputPath = undefined;\n\t\t\t\t\t});\n\t\t\t\t\ttempFileStream.write(rawBytes);\n\t\t\t\t\t// Await the flush so the returned path points at a COMPLETE file, not one mid-write.\n\t\t\t\t\tawait endWriteStream(tempFileStream);\n\t\t\t\t}\n\t\t\t\toptions.onChunk?.(res.output);\n\t\t\t\treturn {\n\t\t\t\t\toutput: res.output,\n\t\t\t\t\texitCode: res.exitCode,\n\t\t\t\t\tcancelled: options.signal?.aborted ?? false,\n\t\t\t\t\ttruncated: res.fullOutputPath !== undefined || rawBytes.length > DEFAULT_MAX_BYTES,\n\t\t\t\t\tfullOutputPath,\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\t}\n\n\tconst outputChunks: string[] = [];\n\tlet outputBytes = 0;\n\tconst maxOutputBytes = DEFAULT_MAX_BYTES * 2;\n\n\tlet tempFilePath: string | undefined;\n\tlet tempFileStream: WriteStream | undefined;\n\tlet totalBytes = 0;\n\n\tconst ensureTempFile = () => {\n\t\tif (tempFilePath) {\n\t\t\treturn;\n\t\t}\n\t\tconst id = randomBytes(8).toString(\"hex\");\n\t\ttempFilePath = join(tmpdir(), `pi-bash-${id}.log`);\n\t\t// On stream failure (e.g. disk full), drop the artifact instead of\n\t\t// crashing the process; the rolling in-memory output is still returned.\n\t\ttempFileStream = createSafeWriteStream(tempFilePath, () => {\n\t\t\ttempFileStream = undefined;\n\t\t\ttempFilePath = undefined;\n\t\t});\n\t\tfor (const chunk of outputChunks) {\n\t\t\ttempFileStream.write(chunk);\n\t\t}\n\t};\n\n\tconst decoder = new TextDecoder();\n\n\tconst onData = (data: Buffer) => {\n\t\ttotalBytes += data.length;\n\n\t\t// Sanitize: strip ANSI, replace binary garbage, normalize newlines\n\t\tconst text = sanitizeBinaryOutput(stripAnsi(decoder.decode(data, { stream: true }))).replace(/\\r/g, \"\");\n\n\t\t// Start writing to temp file if exceeds threshold\n\t\tif (totalBytes > DEFAULT_MAX_BYTES) {\n\t\t\tensureTempFile();\n\t\t}\n\n\t\t// Guard writableEnded: custom BashOperations may deliver late onData\n\t\t// callbacks after an abort path has already ended the stream.\n\t\tif (tempFileStream && !tempFileStream.writableEnded) {\n\t\t\ttempFileStream.write(text);\n\t\t}\n\n\t\t// Keep rolling buffer\n\t\toutputChunks.push(text);\n\t\toutputBytes += text.length;\n\t\twhile (outputBytes > maxOutputBytes && outputChunks.length > 1) {\n\t\t\tconst removed = outputChunks.shift()!;\n\t\t\toutputBytes -= removed.length;\n\t\t}\n\n\t\t// Stream to callback\n\t\tif (options?.onChunk) {\n\t\t\toptions.onChunk(text);\n\t\t}\n\t};\n\n\ttry {\n\t\tconst result = await operations.exec(command, cwd, {\n\t\t\tonData,\n\t\t\tsignal: options?.signal,\n\t\t});\n\n\t\tconst fullOutput = outputChunks.join(\"\");\n\t\tconst truncationResult = truncateTail(fullOutput);\n\t\tif (truncationResult.truncated) {\n\t\t\tensureTempFile();\n\t\t}\n\t\tif (tempFileStream) {\n\t\t\t// Await the flush so fullOutputPath refers to a fully-written file on return, not one still\n\t\t\t// draining its buffer — otherwise a fast reader can see partial/empty content.\n\t\t\tawait endWriteStream(tempFileStream);\n\t\t}\n\t\tconst cancelled = options?.signal?.aborted ?? false;\n\n\t\treturn {\n\t\t\toutput: truncationResult.truncated ? truncationResult.content : fullOutput,\n\t\t\texitCode: cancelled ? undefined : (result.exitCode ?? undefined),\n\t\t\tcancelled,\n\t\t\ttruncated: truncationResult.truncated,\n\t\t\tfullOutputPath: tempFilePath,\n\t\t};\n\t} catch (err) {\n\t\t// Check if it was an abort\n\t\tif (options?.signal?.aborted) {\n\t\t\tconst fullOutput = outputChunks.join(\"\");\n\t\t\tconst truncationResult = truncateTail(fullOutput);\n\t\t\tif (truncationResult.truncated) {\n\t\t\t\tensureTempFile();\n\t\t\t}\n\t\t\tif (tempFileStream) {\n\t\t\t\tawait endWriteStream(tempFileStream);\n\t\t\t}\n\t\t\treturn {\n\t\t\t\toutput: truncationResult.truncated ? truncationResult.content : fullOutput,\n\t\t\t\texitCode: undefined,\n\t\t\t\tcancelled: true,\n\t\t\t\ttruncated: truncationResult.truncated,\n\t\t\t\tfullOutputPath: tempFilePath,\n\t\t\t};\n\t\t}\n\n\t\tif (tempFileStream) {\n\t\t\tawait endWriteStream(tempFileStream);\n\t\t}\n\n\t\tthrow err;\n\t}\n}\n"]}
@@ -9,7 +9,7 @@ import { randomBytes } from "node:crypto";
9
9
  import { tmpdir } from "node:os";
10
10
  import { join } from "node:path";
11
11
  import { stripAnsi } from "../utils/ansi.js";
12
- import { createSafeWriteStream } from "../utils/safe-write-stream.js";
12
+ import { createSafeWriteStream, endWriteStream } from "../utils/safe-write-stream.js";
13
13
  import { sanitizeBinaryOutput } from "../utils/shell.js";
14
14
  import { classifyGitCommand, executeFilteredGit } from "./tools/git-filter.js";
15
15
  import { DEFAULT_MAX_BYTES, truncateTail } from "./tools/truncate.js";
@@ -32,10 +32,16 @@ export async function executeBashWithOperations(command, cwd, operations, option
32
32
  let fullOutputPath = res.fullOutputPath;
33
33
  if (fullOutputPath === undefined && rawBytes.length > DEFAULT_MAX_BYTES) {
34
34
  const id = randomBytes(8).toString("hex");
35
- fullOutputPath = join(tmpdir(), `pi-bash-${id}.log`);
36
- const tempFileStream = createSafeWriteStream(fullOutputPath);
35
+ const spillPath = join(tmpdir(), `pi-bash-${id}.log`);
36
+ fullOutputPath = spillPath;
37
+ // On stream failure (e.g. disk full), drop the advertised path instead of
38
+ // pointing at a partial/missing file.
39
+ const tempFileStream = createSafeWriteStream(spillPath, () => {
40
+ fullOutputPath = undefined;
41
+ });
37
42
  tempFileStream.write(rawBytes);
38
- tempFileStream.end();
43
+ // Await the flush so the returned path points at a COMPLETE file, not one mid-write.
44
+ await endWriteStream(tempFileStream);
39
45
  }
40
46
  options.onChunk?.(res.output);
41
47
  return {
@@ -107,7 +113,9 @@ export async function executeBashWithOperations(command, cwd, operations, option
107
113
  ensureTempFile();
108
114
  }
109
115
  if (tempFileStream) {
110
- tempFileStream.end();
116
+ // Await the flush so fullOutputPath refers to a fully-written file on return, not one still
117
+ // draining its buffer — otherwise a fast reader can see partial/empty content.
118
+ await endWriteStream(tempFileStream);
111
119
  }
112
120
  const cancelled = options?.signal?.aborted ?? false;
113
121
  return {
@@ -127,7 +135,7 @@ export async function executeBashWithOperations(command, cwd, operations, option
127
135
  ensureTempFile();
128
136
  }
129
137
  if (tempFileStream) {
130
- tempFileStream.end();
138
+ await endWriteStream(tempFileStream);
131
139
  }
132
140
  return {
133
141
  output: truncationResult.truncated ? truncationResult.content : fullOutput,
@@ -138,7 +146,7 @@ export async function executeBashWithOperations(command, cwd, operations, option
138
146
  };
139
147
  }
140
148
  if (tempFileStream) {
141
- tempFileStream.end();
149
+ await endWriteStream(tempFileStream);
142
150
  }
143
151
  throw err;
144
152
  }
@@ -1 +1 @@
1
- {"version":3,"file":"bash-executor.js","sourceRoot":"","sources":["../../src/core/bash-executor.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAE1C,OAAO,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AACjC,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAC7C,OAAO,EAAE,qBAAqB,EAAE,MAAM,+BAA+B,CAAC;AACtE,OAAO,EAAE,oBAAoB,EAAE,MAAM,mBAAmB,CAAC;AAEzD,OAAO,EAAE,kBAAkB,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAC;AAC/E,OAAO,EAAE,iBAAiB,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AA4BtE,+EAA+E;AAC/E,iBAAiB;AACjB,+EAA+E;AAE/E;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,yBAAyB,CAC9C,OAAe,EACf,GAAW,EACX,UAA0B,EAC1B,OAA6B,EACP;IACtB,IAAI,OAAO,EAAE,eAAe,EAAE,CAAC;QAC9B,MAAM,cAAc,GAAG,kBAAkB,CAAC,OAAO,EAAE,OAAO,CAAC,GAAG,CAAC,CAAC;QAChE,IAAI,cAAc,CAAC,Q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AAU;YAC1E,QAAQ,EAAE,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,QAAQ,IAAI,SAAS,CAAC;YAChE,SAAS;YACT,SAAS,EAAE,gBAAgB,CAAC,SAAS;YACrC,cAAc,EAAE,YAAY;SAC5B,CAAC;IACH,CAAC;IAAC,OAAO,GAAG,EAAE,CAAC;QACd,2BAA2B;QAC3B,IAAI,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,CAAC;YAC9B,MAAM,UAAU,GAAG,YAAY,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;YACzC,MAAM,gBAAgB,GAAG,YAAY,CAAC,UAAU,CAAC,CAAC;YAClD,IAAI,gBAAgB,CAAC,SAAS,EAAE,CAAC;gBAChC,cAAc,EAAE,CAAC;YAClB,CAAC;YACD,IAAI,cAAc,EAAE,CAAC;gBACpB,cAAc,CAAC,GAAG,EAAE,CAAC;YACtB,CAAC;YACD,OAAO;gBACN,MAAM,EAAE,gBAAgB,CAAC,SAAS,CAAC,CAAC,CAAC,gBAAgB,CAAC,OAAO,CAAC,CAAC,CAAC,UAAU;gBAC1E,QAAQ,EAAE,SAAS;gBACnB,SAAS,EAAE,IAAI;gBACf,SAAS,EAAE,gBAAgB,CAAC,SAAS;gBACrC,cAAc,EAAE,YAAY;aAC5B,CAAC;QACH,CAAC;QAED,IAAI,cAAc,EAAE,CAAC;YACpB,cAAc,CAAC,GAAG,EAAE,CAAC;QACtB,CAAC;QAED,MAAM,GAAG,CAAC;IACX,CAAC;AAAA,CACD","sourcesContent":["/**\n * Bash command execution with streaming support and cancellation.\n *\n * This module provides a unified bash execution implementation used by:\n * - AgentSession.executeBash() for interactive and RPC modes\n * - Direct calls from modes that need bash execution\n */\n\nimport { randomBytes } from \"node:crypto\";\nimport type { WriteStream } from \"node:fs\";\nimport { tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { stripAnsi } from \"../utils/ansi.ts\";\nimport { createSafeWriteStream } from \"../utils/safe-write-stream.ts\";\nimport { sanitizeBinaryOutput } from \"../utils/shell.ts\";\nimport type { BashOperations } from \"./tools/bash.ts\";\nimport { classifyGitCommand, executeFilteredGit } from \"./tools/git-filter.ts\";\nimport { DEFAULT_MAX_BYTES, truncateTail } from \"./tools/truncate.ts\";\n\n// ============================================================================\n// Types\n// ============================================================================\n\nexport interface BashExecutorOptions {\n\t/** Callback for streaming output chunks (already sanitized) */\n\tonChunk?: (chunk: string) => void;\n\t/** AbortSignal for cancellation */\n\tsignal?: AbortSignal;\n\t/** Enable conservative pi-native git output filtering for local default execution paths */\n\tenableGitFilter?: boolean;\n}\n\nexport interface BashResult {\n\t/** Combined stdout + stderr output (sanitized, possibly truncated) */\n\toutput: string;\n\t/** Process exit code (undefined if killed/cancelled) */\n\texitCode: number | undefined;\n\t/** Whether the command was cancelled via signal */\n\tcancelled: boolean;\n\t/** Whether the output was truncated */\n\ttruncated: boolean;\n\t/** Path to temp file containing full output (if output exceeded truncation threshold) */\n\tfullOutputPath?: string;\n}\n\n// ============================================================================\n// Implementation\n// ============================================================================\n\n/**\n * Execute a bash command using custom BashOperations.\n * Used for remote execution (SSH, containers, etc.).\n */\nexport async function executeBashWithOperations(\n\tcommand: string,\n\tcwd: string,\n\toperations: BashOperations,\n\toptions?: BashExecutorOptions,\n): Promise<BashResult> {\n\tif (options?.enableGitFilter) {\n\t\tconst classification = classifyGitCommand(command, process.env);\n\t\tif (classification.eligible && classification.subcommand) {\n\t\t\tconst res = await executeFilteredGit(\n\t\t\t\tcwd,\n\t\t\t\tclassification.subcommand,\n\t\t\t\tclassification.globalOptions || [],\n\t\t\t\tclassification.subcommandArgs || [],\n\t\t\t\t{ signal: options.signal },\n\t\t\t);\n\t\t\tif (res.exitCode !== -100) {\n\t\t\t\tconst rawBytes = res.rawBytes ?? Buffer.from(res.rawOut, \"utf-8\");\n\t\t\t\t// The filter already spills oversized output to a temp file; reuse it\n\t\t\t\t// instead of materializing another full copy here.\n\t\t\t\tlet fullOutputPath = res.fullOutputPath;\n\t\t\t\tif (fullOutputPath === undefined && rawBytes.length > DEFAULT_MAX_BYTES) {\n\t\t\t\t\tconst id = randomBytes(8).toString(\"hex\");\n\t\t\t\t\tfullOutputPath = join(tmpdir(), `pi-bash-${id}.log`);\n\t\t\t\t\tconst tempFileStream = createSafeWriteStream(fullOutputPath);\n\t\t\t\t\ttempFileStream.write(rawBytes);\n\t\t\t\t\ttempFileStream.end();\n\t\t\t\t}\n\t\t\t\toptions.onChunk?.(res.output);\n\t\t\t\treturn {\n\t\t\t\t\toutput: res.output,\n\t\t\t\t\texitCode: res.exitCode,\n\t\t\t\t\tcancelled: options.signal?.aborted ?? false,\n\t\t\t\t\ttruncated: res.fullOutputPath !== undefined || rawBytes.length > DEFAULT_MAX_BYTES,\n\t\t\t\t\tfullOutputPath,\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\t}\n\n\tconst outputChunks: string[] = [];\n\tlet outputBytes = 0;\n\tconst maxOutputBytes = DEFAULT_MAX_BYTES * 2;\n\n\tlet tempFilePath: string | undefined;\n\tlet tempFileStream: WriteStream | undefined;\n\tlet totalBytes = 0;\n\n\tconst ensureTempFile = () => {\n\t\tif (tempFilePath) {\n\t\t\treturn;\n\t\t}\n\t\tconst id = randomBytes(8).toString(\"hex\");\n\t\ttempFilePath = join(tmpdir(), `pi-bash-${id}.log`);\n\t\t// On stream failure (e.g. disk full), drop the artifact instead of\n\t\t// crashing the process; the rolling in-memory output is still returned.\n\t\ttempFileStream = createSafeWriteStream(tempFilePath, () => {\n\t\t\ttempFileStream = undefined;\n\t\t\ttempFilePath = undefined;\n\t\t});\n\t\tfor (const chunk of outputChunks) {\n\t\t\ttempFileStream.write(chunk);\n\t\t}\n\t};\n\n\tconst decoder = new TextDecoder();\n\n\tconst onData = (data: Buffer) => {\n\t\ttotalBytes += data.length;\n\n\t\t// Sanitize: strip ANSI, replace binary garbage, normalize newlines\n\t\tconst text = sanitizeBinaryOutput(stripAnsi(decoder.decode(data, { stream: true }))).replace(/\\r/g, \"\");\n\n\t\t// Start writing to temp file if exceeds threshold\n\t\tif (totalBytes > DEFAULT_MAX_BYTES) {\n\t\t\tensureTempFile();\n\t\t}\n\n\t\t// Guard writableEnded: custom BashOperations may deliver late onData\n\t\t// callbacks after an abort path has already ended the stream.\n\t\tif (tempFileStream && !tempFileStream.writableEnded) {\n\t\t\ttempFileStream.write(text);\n\t\t}\n\n\t\t// Keep rolling buffer\n\t\toutputChunks.push(text);\n\t\toutputBytes += text.length;\n\t\twhile (outputBytes > maxOutputBytes && outputChunks.length > 1) {\n\t\t\tconst removed = outputChunks.shift()!;\n\t\t\toutputBytes -= removed.length;\n\t\t}\n\n\t\t// Stream to callback\n\t\tif (options?.onChunk) {\n\t\t\toptions.onChunk(text);\n\t\t}\n\t};\n\n\ttry {\n\t\tconst result = await operations.exec(command, cwd, {\n\t\t\tonData,\n\t\t\tsignal: options?.signal,\n\t\t});\n\n\t\tconst fullOutput = outputChunks.join(\"\");\n\t\tconst truncationResult = truncateTail(fullOutput);\n\t\tif (truncationResult.truncated) {\n\t\t\tensureTempFile();\n\t\t}\n\t\tif (tempFileStream) {\n\t\t\ttempFileStream.end();\n\t\t}\n\t\tconst cancelled = options?.signal?.aborted ?? false;\n\n\t\treturn {\n\t\t\toutput: truncationResult.truncated ? truncationResult.content : fullOutput,\n\t\t\texitCode: cancelled ? undefined : (result.exitCode ?? undefined),\n\t\t\tcancelled,\n\t\t\ttruncated: truncationResult.truncated,\n\t\t\tfullOutputPath: tempFilePath,\n\t\t};\n\t} catch (err) {\n\t\t// Check if it was an abort\n\t\tif (options?.signal?.aborted) {\n\t\t\tconst fullOutput = outputChunks.join(\"\");\n\t\t\tconst truncationResult = truncateTail(fullOutput);\n\t\t\tif (truncationResult.truncated) {\n\t\t\t\tensureTempFile();\n\t\t\t}\n\t\t\tif (tempFileStream) {\n\t\t\t\ttempFileStream.end();\n\t\t\t}\n\t\t\treturn {\n\t\t\t\toutput: truncationResult.truncated ? truncationResult.content : fullOutput,\n\t\t\t\texitCode: undefined,\n\t\t\t\tcancelled: true,\n\t\t\t\ttruncated: truncationResult.truncated,\n\t\t\t\tfullOutputPath: tempFilePath,\n\t\t\t};\n\t\t}\n\n\t\tif (tempFileStream) {\n\t\t\ttempFileStream.end();\n\t\t}\n\n\t\tthrow err;\n\t}\n}\n"]}
1
+ {"version":3,"file":"bash-executor.js","sourceRoot":"","sources":["../../src/core/bash-executor.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAE1C,OAAO,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AACjC,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAC7C,OAAO,EAAE,qBAAqB,EAAE,cAAc,EAAE,MAAM,+BAA+B,CAAC;AACtF,OAAO,EAAE,oBAAoB,EAAE,MAAM,mBAAmB,CAAC;AAEzD,OAAO,EAAE,kBAAkB,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAC;AAC/E,OAAO,EAAE,iBAAiB,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AA4BtE,+EAA+E;AAC/E,iBAAiB;AACjB,+EAA+E;AAE/E;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,yBAAyB,CAC9C,OAAe,EACf,GAAW,EACX,UAA0B,EAC1B,OAA6B,EACP;IACtB,IAAI,OAAO,EAAE,eAAe,EAAE,CAAC;QAC9B,MAAM,cAAc,GAAG,kBAAkB,CAAC,OAAO,EAAE,OAAO,CAAC,GAAG,CAAC,CAAC;QAChE,IAAI,cAAc,CAAC,QAAQ,IAAI,cAAc,CAAC,UAAU,EAAE,CAAC;YAC1D,MAAM,GAAG,GAAG,MAAM,kBAAkB,CACnC,GAAG,EACH,cAAc,CAAC,UAAU,EACzB,cAAc,CAAC,aAAa,IAAI,EAAE,EAClC,cA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AAgB,CAAC,OAAO,CAAC,CAAC,CAAC,UAAU;YAC1E,QAAQ,EAAE,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,QAAQ,IAAI,SAAS,CAAC;YAChE,SAAS;YACT,SAAS,EAAE,gBAAgB,CAAC,SAAS;YACrC,cAAc,EAAE,YAAY;SAC5B,CAAC;IACH,CAAC;IAAC,OAAO,GAAG,EAAE,CAAC;QACd,2BAA2B;QAC3B,IAAI,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,CAAC;YAC9B,MAAM,UAAU,GAAG,YAAY,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;YACzC,MAAM,gBAAgB,GAAG,YAAY,CAAC,UAAU,CAAC,CAAC;YAClD,IAAI,gBAAgB,CAAC,SAAS,EAAE,CAAC;gBAChC,cAAc,EAAE,CAAC;YAClB,CAAC;YACD,IAAI,cAAc,EAAE,CAAC;gBACpB,MAAM,cAAc,CAAC,cAAc,CAAC,CAAC;YACtC,CAAC;YACD,OAAO;gBACN,MAAM,EAAE,gBAAgB,CAAC,SAAS,CAAC,CAAC,CAAC,gBAAgB,CAAC,OAAO,CAAC,CAAC,CAAC,UAAU;gBAC1E,QAAQ,EAAE,SAAS;gBACnB,SAAS,EAAE,IAAI;gBACf,SAAS,EAAE,gBAAgB,CAAC,SAAS;gBACrC,cAAc,EAAE,YAAY;aAC5B,CAAC;QACH,CAAC;QAED,IAAI,cAAc,EAAE,CAAC;YACpB,MAAM,cAAc,CAAC,cAAc,CAAC,CAAC;QACtC,CAAC;QAED,MAAM,GAAG,CAAC;IACX,CAAC;AAAA,CACD","sourcesContent":["/**\n * Bash command execution with streaming support and cancellation.\n *\n * This module provides a unified bash execution implementation used by:\n * - AgentSession.executeBash() for interactive and RPC modes\n * - Direct calls from modes that need bash execution\n */\n\nimport { randomBytes } from \"node:crypto\";\nimport type { WriteStream } from \"node:fs\";\nimport { tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { stripAnsi } from \"../utils/ansi.ts\";\nimport { createSafeWriteStream, endWriteStream } from \"../utils/safe-write-stream.ts\";\nimport { sanitizeBinaryOutput } from \"../utils/shell.ts\";\nimport type { BashOperations } from \"./tools/bash.ts\";\nimport { classifyGitCommand, executeFilteredGit } from \"./tools/git-filter.ts\";\nimport { DEFAULT_MAX_BYTES, truncateTail } from \"./tools/truncate.ts\";\n\n// ============================================================================\n// Types\n// ============================================================================\n\nexport interface BashExecutorOptions {\n\t/** Callback for streaming output chunks (already sanitized) */\n\tonChunk?: (chunk: string) => void;\n\t/** AbortSignal for cancellation */\n\tsignal?: AbortSignal;\n\t/** Enable conservative pi-native git output filtering for local default execution paths */\n\tenableGitFilter?: boolean;\n}\n\nexport interface BashResult {\n\t/** Combined stdout + stderr output (sanitized, possibly truncated) */\n\toutput: string;\n\t/** Process exit code (undefined if killed/cancelled) */\n\texitCode: number | undefined;\n\t/** Whether the command was cancelled via signal */\n\tcancelled: boolean;\n\t/** Whether the output was truncated */\n\ttruncated: boolean;\n\t/** Path to temp file containing full output (if output exceeded truncation threshold) */\n\tfullOutputPath?: string;\n}\n\n// ============================================================================\n// Implementation\n// ============================================================================\n\n/**\n * Execute a bash command using custom BashOperations.\n * Used for remote execution (SSH, containers, etc.).\n */\nexport async function executeBashWithOperations(\n\tcommand: string,\n\tcwd: string,\n\toperations: BashOperations,\n\toptions?: BashExecutorOptions,\n): Promise<BashResult> {\n\tif (options?.enableGitFilter) {\n\t\tconst classification = classifyGitCommand(command, process.env);\n\t\tif (classification.eligible && classification.subcommand) {\n\t\t\tconst res = await executeFilteredGit(\n\t\t\t\tcwd,\n\t\t\t\tclassification.subcommand,\n\t\t\t\tclassification.globalOptions || [],\n\t\t\t\tclassification.subcommandArgs || [],\n\t\t\t\t{ signal: options.signal },\n\t\t\t);\n\t\t\tif (res.exitCode !== -100) {\n\t\t\t\tconst rawBytes = res.rawBytes ?? Buffer.from(res.rawOut, \"utf-8\");\n\t\t\t\t// The filter already spills oversized output to a temp file; reuse it\n\t\t\t\t// instead of materializing another full copy here.\n\t\t\t\tlet fullOutputPath = res.fullOutputPath;\n\t\t\t\tif (fullOutputPath === undefined && rawBytes.length > DEFAULT_MAX_BYTES) {\n\t\t\t\t\tconst id = randomBytes(8).toString(\"hex\");\n\t\t\t\t\tconst spillPath = join(tmpdir(), `pi-bash-${id}.log`);\n\t\t\t\t\tfullOutputPath = spillPath;\n\t\t\t\t\t// On stream failure (e.g. disk full), drop the advertised path instead of\n\t\t\t\t\t// pointing at a partial/missing file.\n\t\t\t\t\tconst tempFileStream = createSafeWriteStream(spillPath, () => {\n\t\t\t\t\t\tfullOutputPath = undefined;\n\t\t\t\t\t});\n\t\t\t\t\ttempFileStream.write(rawBytes);\n\t\t\t\t\t// Await the flush so the returned path points at a COMPLETE file, not one mid-write.\n\t\t\t\t\tawait endWriteStream(tempFileStream);\n\t\t\t\t}\n\t\t\t\toptions.onChunk?.(res.output);\n\t\t\t\treturn {\n\t\t\t\t\toutput: res.output,\n\t\t\t\t\texitCode: res.exitCode,\n\t\t\t\t\tcancelled: options.signal?.aborted ?? false,\n\t\t\t\t\ttruncated: res.fullOutputPath !== undefined || rawBytes.length > DEFAULT_MAX_BYTES,\n\t\t\t\t\tfullOutputPath,\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\t}\n\n\tconst outputChunks: string[] = [];\n\tlet outputBytes = 0;\n\tconst maxOutputBytes = DEFAULT_MAX_BYTES * 2;\n\n\tlet tempFilePath: string | undefined;\n\tlet tempFileStream: WriteStream | undefined;\n\tlet totalBytes = 0;\n\n\tconst ensureTempFile = () => {\n\t\tif (tempFilePath) {\n\t\t\treturn;\n\t\t}\n\t\tconst id = randomBytes(8).toString(\"hex\");\n\t\ttempFilePath = join(tmpdir(), `pi-bash-${id}.log`);\n\t\t// On stream failure (e.g. disk full), drop the artifact instead of\n\t\t// crashing the process; the rolling in-memory output is still returned.\n\t\ttempFileStream = createSafeWriteStream(tempFilePath, () => {\n\t\t\ttempFileStream = undefined;\n\t\t\ttempFilePath = undefined;\n\t\t});\n\t\tfor (const chunk of outputChunks) {\n\t\t\ttempFileStream.write(chunk);\n\t\t}\n\t};\n\n\tconst decoder = new TextDecoder();\n\n\tconst onData = (data: Buffer) => {\n\t\ttotalBytes += data.length;\n\n\t\t// Sanitize: strip ANSI, replace binary garbage, normalize newlines\n\t\tconst text = sanitizeBinaryOutput(stripAnsi(decoder.decode(data, { stream: true }))).replace(/\\r/g, \"\");\n\n\t\t// Start writing to temp file if exceeds threshold\n\t\tif (totalBytes > DEFAULT_MAX_BYTES) {\n\t\t\tensureTempFile();\n\t\t}\n\n\t\t// Guard writableEnded: custom BashOperations may deliver late onData\n\t\t// callbacks after an abort path has already ended the stream.\n\t\tif (tempFileStream && !tempFileStream.writableEnded) {\n\t\t\ttempFileStream.write(text);\n\t\t}\n\n\t\t// Keep rolling buffer\n\t\toutputChunks.push(text);\n\t\toutputBytes += text.length;\n\t\twhile (outputBytes > maxOutputBytes && outputChunks.length > 1) {\n\t\t\tconst removed = outputChunks.shift()!;\n\t\t\toutputBytes -= removed.length;\n\t\t}\n\n\t\t// Stream to callback\n\t\tif (options?.onChunk) {\n\t\t\toptions.onChunk(text);\n\t\t}\n\t};\n\n\ttry {\n\t\tconst result = await operations.exec(command, cwd, {\n\t\t\tonData,\n\t\t\tsignal: options?.signal,\n\t\t});\n\n\t\tconst fullOutput = outputChunks.join(\"\");\n\t\tconst truncationResult = truncateTail(fullOutput);\n\t\tif (truncationResult.truncated) {\n\t\t\tensureTempFile();\n\t\t}\n\t\tif (tempFileStream) {\n\t\t\t// Await the flush so fullOutputPath refers to a fully-written file on return, not one still\n\t\t\t// draining its buffer — otherwise a fast reader can see partial/empty content.\n\t\t\tawait endWriteStream(tempFileStream);\n\t\t}\n\t\tconst cancelled = options?.signal?.aborted ?? false;\n\n\t\treturn {\n\t\t\toutput: truncationResult.truncated ? truncationResult.content : fullOutput,\n\t\t\texitCode: cancelled ? undefined : (result.exitCode ?? undefined),\n\t\t\tcancelled,\n\t\t\ttruncated: truncationResult.truncated,\n\t\t\tfullOutputPath: tempFilePath,\n\t\t};\n\t} catch (err) {\n\t\t// Check if it was an abort\n\t\tif (options?.signal?.aborted) {\n\t\t\tconst fullOutput = outputChunks.join(\"\");\n\t\t\tconst truncationResult = truncateTail(fullOutput);\n\t\t\tif (truncationResult.truncated) {\n\t\t\t\tensureTempFile();\n\t\t\t}\n\t\t\tif (tempFileStream) {\n\t\t\t\tawait endWriteStream(tempFileStream);\n\t\t\t}\n\t\t\treturn {\n\t\t\t\toutput: truncationResult.truncated ? truncationResult.content : fullOutput,\n\t\t\t\texitCode: undefined,\n\t\t\t\tcancelled: true,\n\t\t\t\ttruncated: truncationResult.truncated,\n\t\t\t\tfullOutputPath: tempFilePath,\n\t\t\t};\n\t\t}\n\n\t\tif (tempFileStream) {\n\t\t\tawait endWriteStream(tempFileStream);\n\t\t}\n\n\t\tthrow err;\n\t}\n}\n"]}
@@ -46,7 +46,15 @@ export interface CurationResult {
46
46
  key: string;
47
47
  kind: CurationJob["kind"];
48
48
  ok: boolean;
49
+ /** Raw model-parsed digest (stub_digest jobs only): human-readable, NOT fenced. Kept as-is for
50
+ * logging/audit (e.g. the session's brain-curation entry) — never render this into a provider
51
+ * prompt; use `fencedDigest` (via getDigest) for that. */
49
52
  digest?: string;
53
+ /** The same digest fenced in the untrusted-content boundary, wrapped exactly ONCE here at store
54
+ * time (not at every context-gc render), so the fence's nonce is fixed for the life of this
55
+ * result — every render of it is then byte-identical, keeping the provider's prompt-prefix cache
56
+ * warm. This is what getDigest() returns and what context-gc renders verbatim into a packed stub. */
57
+ fencedDigest?: string;
50
58
  relevant?: boolean;
51
59
  confidence?: number;
52
60
  ms: number;
@@ -89,6 +97,8 @@ export declare class BrainCurator {
89
97
  private _digestsServed;
90
98
  private _draining;
91
99
  enqueue(job: CurationJob): void;
100
+ /** Returns the digest already fenced in the untrusted-content boundary — callers must render it
101
+ * verbatim into a provider prompt, never re-wrap it (see CurationResult.fencedDigest for why). */
92
102
  getDigest(key: string): string | undefined;
93
103
  /** Callers report when a digest was rendered into a real (sent) prompt stub. */
94
104
  noteDigestServed(): void;
@@ -1 +1 @@
1
- {"version":3,"file":"brain-curator.d.ts","sourceRoot":"","sources":["../../../src/core/context/brain-curator.ts"],"names":[],"mappings":"AAEA;;;;;;;;;;;GAWG;AAEH,eAAO,MAAM,6BAA6B,QAK9B,CAAC;AAEb,eAAO,MAAM,gCAAgC,QAMjC,CAAC;AAEb,eAAO,MAAM,wCAAwC,QAKzC,CAAC;AAEb,wBAAgB,0BAA0B,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAQ3E;AAED,MAAM,WAAW,eAAe;IAC/B,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,EAAE,MAAM,CAAC;IACpB,QAAQ,EAAE,MAAM,CAAC;IACjB,MAAM,EAAE,MAAM,CAAC;CACf;AAMD;;;;;GAKG;AACH,wBAAsB,yBAAyB,CAAC,IAAI,EAAE;IACrD,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,EAAE,gBAAgB,CAAC;IAC3B,MAAM,CAAC,EAAE,WAAW,CAAC;IACrB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,eAAe,CAAC,EAAE,MAAM,CAAC;CACzB,GAAG,OAAO,CAAC,eAAe,CAAC,CAuC3B;AAED,MAAM,WAAW,WAAW;IAC3B,IAAI,EAAE,aAAa,GAAG,WAAW,CAAC;IAClC,iGAAiG;IACjG,GAAG,EAAE,MAAM,CAAC;IACZ,0FAA0F;IAC1F,OAAO,EAAE,MAAM,CAAC;IAChB,6EAA6E;IAC7E,IAAI,CAAC,EAAE,MAAM,CAAC;CACd;AAED,MAAM,WAAW,cAAc;IAC9B,GAAG,EAAE,MAAM,CAAC;IACZ,IAAI,EAAE,WAAW,CAAC,MAAM,CAAC,CAAC;IAC1B,EAAE,EAAE,OAAO,CAAC;IACZ,MAAM,CAAC,EAAE,MAAM,CAA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GAAG,EAAE,WAAW,GAAG,IAAI,CAS9B;IAED,SAAS,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAGzC;IAED,gFAAgF;IAChF,gBAAgB,IAAI,IAAI,CAEvB;IAED,YAAY,CAAC,GAAG,EAAE,MAAM,GAAG;QAAE,QAAQ,EAAE,OAAO,CAAC;QAAC,UAAU,EAAE,MAAM,CAAA;KAAE,GAAG,SAAS,CAI/E;IAED,OAAO,IAAI,OAAO,CAEjB;IAED,IAAI,UAAU,IAAI,OAAO,CAExB;IAED,SAAS,IAAI,yBAAyB,CAUrC;IAED;;;;;OAKG;IACG,KAAK,CAAC,IAAI,EAAE;QACjB,QAAQ,EAAE,gBAAgB,CAAC;QAC3B,OAAO,EAAE,MAAM,CAAC;QAChB,MAAM,CAAC,EAAE,WAAW,CAAC;QACrB,GAAG,CAAC,EAAE,MAAM,MAAM,CAAC;KACnB,GAAG,OAAO,CAAC,cAAc,EAAE,CAAC,CAiD5B;IAED,OAAO,CAAC,YAAY;CAOpB","sourcesContent":["import { runBoundedCompletion } from \"../autonomy/bounded-completion.ts\";\n\n/**\n * Brain-assisted context curation (see docs/model-router-rework/brain-context-curation-design.md):\n * a SIDECAR curator that consumes reports the context pipeline already produces and feeds back\n * small, typed advisories. It is never a pipeline stage: every consumer must behave byte-for-byte\n * identically when a result is absent (missing digest -> today's stub; missing relevance ->\n * today's enforcement decision). The curator itself is provider-free — the completion executor is\n * injected per drain, so it works against any registered local model and faux providers in tests.\n *\n * Memory bounds are explicit: the queue and result map are both capped, and drops are counted in\n * telemetry rather than silent. Results are keyed for idempotency (digests by the GC record's\n * content hash, relevance by the audit item id), so re-enqueueing the same work is free.\n */\n\nexport const CURATION_DIGEST_SYSTEM_PROMPT = [\n\t\"You digest tool-output chunks for a coding agent's context curator. You never solve the task.\",\n\t\"Given a chunk, respond with STRICT JSON only - no prose:\",\n\t'{\"digest\":\"<one or two sentences, max 200 characters, keeping exact identifiers>\"}',\n\t\"Keep exact file paths, symbol names, error codes, and version strings verbatim.\",\n].join(\"\\n\");\n\nexport const CURATION_RELEVANCE_SYSTEM_PROMPT = [\n\t\"You judge whether a stale tool output is still relevant to the user's current goal.\",\n\t\"You never solve the task. Respond with STRICT JSON only - no prose:\",\n\t'{\"relevant\":true|false,\"confidence\":<0..1>}',\n\t\"relevant=false means the chunk is about something the current goal no longer needs.\",\n\t\"When uncertain, answer relevant=true with low confidence - keeping content is the safe default.\",\n].join(\"\\n\");\n\nexport const CURATION_COMPACTION_DIGEST_SYSTEM_PROMPT = [\n\t\"You pre-digest a chunk of an agent conversation for compaction. You never continue the conversation.\",\n\t\"Extract ONLY durable facts: decisions made, file paths and symbols touched, errors and their causes,\",\n\t\"user requirements, and outcomes. Respond with STRICT JSON only - no prose:\",\n\t'{\"digest\":\"<bullet-style summary, max 700 characters, exact identifiers verbatim>\"}',\n].join(\"\\n\");\n\nexport function parseCompactionChunkDigest(text: string): string | undefined {\n\tconst parsed = extractJsonObject(text);\n\tif (!parsed) return undefined;\n\tconst digest = (parsed as { digest?: unknown }).digest;\n\tif (typeof digest !== \"string\") return undefined;\n\tconst trimmed = digest.trim();\n\tif (trimmed.length === 0 || trimmed.length > 800) return undefined;\n\treturn trimmed;\n}\n\nexport interface PreDigestResult {\n\ttext: string;\n\ttotalChunks: number;\n\tdigested: number;\n\tfailed: number;\n}\n\nconst PRE_DIGEST_CHUNK_CHARS = 24_000;\nconst PRE_DIGEST_KEEP_RECENT_CHARS = 16_000;\nconst PRE_DIGEST_CHUNK_WALL_CLOCK_MS = 25_000;\n\n/**\n * Compaction pre-digest (design surface 3): shrink the conversation text sent to the frontier\n * summarizer by digesting OLD chunks locally, keeping the recent tail verbatim. Chunk digestion\n * is mechanical extraction — the frontier model still writes the summary. Partial assist, never\n * partial loss: any chunk whose digest fails (parse/timeout) passes through verbatim.\n */\nexport async function preDigestConversationText(args: {\n\ttext: string;\n\tcomplete: CurationComplete;\n\tsignal?: AbortSignal;\n\tchunkChars?: number;\n\tkeepRecentChars?: number;\n}): Promise<PreDigestResult> {\n\tconst chunkChars = args.chunkChars ?? PRE_DIGEST_CHUNK_CHARS;\n\tconst keepRecentChars = args.keepRecentChars ?? PRE_DIGEST_KEEP_RECENT_CHARS;\n\tif (args.text.length <= chunkChars + keepRecentChars) {\n\t\treturn { text: args.text, totalChunks: 0, digested: 0, failed: 0 };\n\t}\n\tconst cut = args.text.length - keepRecentChars;\n\tconst prefix = args.text.slice(0, cut);\n\tconst tail = args.text.slice(cut);\n\tconst chunks: string[] = [];\n\tfor (let offset = 0; offset < prefix.length; offset += chunkChars) {\n\t\tchunks.push(prefix.slice(offset, offset + chunkChars));\n\t}\n\tlet digested = 0;\n\tlet failed = 0;\n\tconst parts: string[] = [];\n\tfor (const [index, chunk] of chunks.entries()) {\n\t\tif (args.signal?.aborted) {\n\t\t\tparts.push(chunk);\n\t\t\tfailed++;\n\t\t\tcontinue;\n\t\t}\n\t\tconst bounded = await runBoundedCompletion({\n\t\t\tmaxWallClockMs: PRE_DIGEST_CHUNK_WALL_CLOCK_MS,\n\t\t\tsignal: args.signal,\n\t\t\texecute: (signal) =>\n\t\t\t\targs.complete({ systemPrompt: CURATION_COMPACTION_DIGEST_SYSTEM_PROMPT, userPrompt: chunk, signal }),\n\t\t});\n\t\tconst digest =\n\t\t\tbounded.completion && !bounded.failure ? parseCompactionChunkDigest(bounded.completion.text) : undefined;\n\t\tif (digest !== undefined) {\n\t\t\tdigested++;\n\t\t\tparts.push(`[locally pre-digested chunk ${index + 1}/${chunks.length} (${chunk.length} chars):]\\n${digest}`);\n\t\t} else {\n\t\t\tfailed++;\n\t\t\tparts.push(chunk);\n\t\t}\n\t}\n\treturn { text: `${parts.join(\"\\n\\n\")}${tail}`, totalChunks: chunks.length, digested, failed };\n}\n\nexport interface CurationJob {\n\tkind: \"stub_digest\" | \"relevance\";\n\t/** Idempotency key: digest jobs use the GC record's content hash, relevance jobs the item id. */\n\tkey: string;\n\t/** Bounded chunk the local model must actually be able to process (sliced on enqueue). */\n\tcontent: string;\n\t/** Relevance jobs only: the goal/intent line the chunk is judged against. */\n\tgoal?: string;\n}\n\nexport interface CurationResult {\n\tkey: string;\n\tkind: CurationJob[\"kind\"];\n\tok: boolean;\n\tdigest?: string;\n\trelevant?: boolean;\n\tconfidence?: number;\n\tms: number;\n}\n\nexport interface CurationTelemetrySnapshot {\n\tjobsRun: number;\n\tparseFailures: number;\n\tdroppedJobs: number;\n\t/** Times a computed digest was actually RENDERED into a GC stub on a real turn — the\n\t * pays-for-itself proxy: every serve is packed content the frontier model got a semantic\n\t * handle on without re-running tools. */\n\tdigestsServed: number;\n\t/** Chars processed locally (an honest proxy for frontier tokens NOT spent on this work). */\n\tlocalChars: number;\n\tqueued: number;\n\tresultsHeld: number;\n}\n\nexport type CurationComplete = (input: {\n\tsystemPrompt: string;\n\tuserPrompt: string;\n\tsignal?: AbortSignal;\n}) => Promise<{ text: string; costUsd: number; stopReason: string }>;\n\nconst MAX_QUEUE = 32;\nconst MAX_RESULTS = 200;\nconst MAX_JOB_CONTENT_CHARS = 8_000;\nconst DIGEST_MAX_WALL_CLOCK_MS = 20_000;\nconst RELEVANCE_MAX_WALL_CLOCK_MS = 8_000;\nexport const CURATION_RELEVANCE_MIN_CONFIDENCE = 0.8;\n\nfunction extractJsonObject(text: string): unknown | undefined {\n\tconst trimmed = text.trim();\n\tconst candidates: string[] = [trimmed];\n\tconst fenced = /```(?:json)?\\s*([\\s\\S]*?)```/.exec(trimmed);\n\tif (fenced?.[1]) candidates.push(fenced[1].trim());\n\tconst start = trimmed.indexOf(\"{\");\n\tconst end = trimmed.lastIndexOf(\"}\");\n\tif (start >= 0 && end > start) candidates.push(trimmed.slice(start, end + 1));\n\tfor (const candidate of candidates) {\n\t\ttry {\n\t\t\tconst parsed = JSON.parse(candidate);\n\t\t\tif (parsed && typeof parsed === \"object\" && !Array.isArray(parsed)) return parsed;\n\t\t} catch {\n\t\t\t// try next candidate\n\t\t}\n\t}\n\treturn undefined;\n}\n\nexport function parseCurationDigest(text: string): string | undefined {\n\tconst parsed = extractJsonObject(text);\n\tif (!parsed) return undefined;\n\tconst digest = (parsed as { digest?: unknown }).digest;\n\tif (typeof digest !== \"string\") return undefined;\n\tconst trimmed = digest.trim().replace(/\\s+/g, \" \");\n\tif (trimmed.length === 0 || trimmed.length > 240) return undefined;\n\treturn trimmed;\n}\n\nexport function parseCurationRelevance(text: string): { relevant: boolean; confidence: number } | undefined {\n\tconst parsed = extractJsonObject(text);\n\tif (!parsed) return undefined;\n\tconst record = parsed as { relevant?: unknown; confidence?: unknown };\n\tif (typeof record.relevant !== \"boolean\") return undefined;\n\tconst confidence =\n\t\ttypeof record.confidence === \"number\" && Number.isFinite(record.confidence)\n\t\t\t? Math.max(0, Math.min(1, record.confidence))\n\t\t\t: 0;\n\treturn { relevant: record.relevant, confidence };\n}\n\nexport class BrainCurator {\n\tprivate readonly _queue = new Map<string, CurationJob>();\n\tprivate readonly _results = new Map<string, CurationResult>();\n\tprivate _jobsRun = 0;\n\tprivate _parseFailures = 0;\n\tprivate _droppedJobs = 0;\n\tprivate _localChars = 0;\n\tprivate _digestsServed = 0;\n\tprivate _draining = false;\n\n\tenqueue(job: CurationJob): void {\n\t\tif (this._results.has(job.key) || this._queue.has(job.key)) return;\n\t\tif (this._queue.size >= MAX_QUEUE) {\n\t\t\t// Drop the OLDEST queued job (newer work reflects the current goal better) and count it.\n\t\t\tconst oldest = this._queue.keys().next().value;\n\t\t\tif (oldest !== undefined) this._queue.delete(oldest);\n\t\t\tthis._droppedJobs++;\n\t\t}\n\t\tthis._queue.set(job.key, { ...job, content: job.content.slice(0, MAX_JOB_CONTENT_CHARS) });\n\t}\n\n\tgetDigest(key: string): string | undefined {\n\t\tconst result = this._results.get(key);\n\t\treturn result?.ok && result.kind === \"stub_digest\" ? result.digest : undefined;\n\t}\n\n\t/** Callers report when a digest was rendered into a real (sent) prompt stub. */\n\tnoteDigestServed(): void {\n\t\tthis._digestsServed++;\n\t}\n\n\tgetRelevance(key: string): { relevant: boolean; confidence: number } | undefined {\n\t\tconst result = this._results.get(key);\n\t\tif (!result?.ok || result.kind !== \"relevance\" || result.relevant === undefined) return undefined;\n\t\treturn { relevant: result.relevant, confidence: result.confidence ?? 0 };\n\t}\n\n\thasWork(): boolean {\n\t\treturn this._queue.size > 0;\n\t}\n\n\tget isDraining(): boolean {\n\t\treturn this._draining;\n\t}\n\n\ttelemetry(): CurationTelemetrySnapshot {\n\t\treturn {\n\t\t\tjobsRun: this._jobsRun,\n\t\t\tparseFailures: this._parseFailures,\n\t\t\tdroppedJobs: this._droppedJobs,\n\t\t\tdigestsServed: this._digestsServed,\n\t\t\tlocalChars: this._localChars,\n\t\t\tqueued: this._queue.size,\n\t\t\tresultsHeld: this._results.size,\n\t\t};\n\t}\n\n\t/**\n\t * Run up to `maxJobs` queued jobs through the injected local-model completer. Single-flight:\n\t * a concurrent drain call returns [] immediately rather than double-running jobs. Every call\n\t * is wall-clock bounded; a failed/unparseable job is recorded as a not-ok result (so it is\n\t * not retried forever) and counted in telemetry.\n\t */\n\tasync drain(args: {\n\t\tcomplete: CurationComplete;\n\t\tmaxJobs: number;\n\t\tsignal?: AbortSignal;\n\t\tnow?: () => number;\n\t}): Promise<CurationResult[]> {\n\t\tif (this._draining) return [];\n\t\tthis._draining = true;\n\t\tconst now = args.now ?? Date.now;\n\t\tconst completed: CurationResult[] = [];\n\t\ttry {\n\t\t\tconst jobs = [...this._queue.values()].slice(0, Math.max(0, args.maxJobs));\n\t\t\tfor (const job of jobs) {\n\t\t\t\tif (args.signal?.aborted) break;\n\t\t\t\tthis._queue.delete(job.key);\n\t\t\t\tconst started = now();\n\t\t\t\tconst bounded = await runBoundedCompletion({\n\t\t\t\t\tmaxWallClockMs: job.kind === \"stub_digest\" ? DIGEST_MAX_WALL_CLOCK_MS : RELEVANCE_MAX_WALL_CLOCK_MS,\n\t\t\t\t\tsignal: args.signal,\n\t\t\t\t\texecute: (signal) =>\n\t\t\t\t\t\targs.complete({\n\t\t\t\t\t\t\tsystemPrompt:\n\t\t\t\t\t\t\t\tjob.kind === \"stub_digest\" ? CURATION_DIGEST_SYSTEM_PROMPT : CURATION_RELEVANCE_SYSTEM_PROMPT,\n\t\t\t\t\t\t\tuserPrompt:\n\t\t\t\t\t\t\t\tjob.kind === \"stub_digest\"\n\t\t\t\t\t\t\t\t\t? job.content\n\t\t\t\t\t\t\t\t\t: `Current goal: ${job.goal ?? \"(unknown)\"}\\n\\nStale chunk:\\n${job.content}`,\n\t\t\t\t\t\t\tsignal,\n\t\t\t\t\t\t}),\n\t\t\t\t});\n\t\t\t\tconst ms = now() - started;\n\t\t\t\tthis._jobsRun++;\n\t\t\t\tthis._localChars += job.content.length;\n\t\t\t\tlet result: CurationResult = { key: job.key, kind: job.kind, ok: false, ms };\n\t\t\t\tif (bounded.completion && !bounded.failure) {\n\t\t\t\t\tif (job.kind === \"stub_digest\") {\n\t\t\t\t\t\tconst digest = parseCurationDigest(bounded.completion.text);\n\t\t\t\t\t\tresult = digest !== undefined ? { ...result, ok: true, digest } : result;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tconst relevance = parseCurationRelevance(bounded.completion.text);\n\t\t\t\t\t\tresult =\n\t\t\t\t\t\t\trelevance !== undefined\n\t\t\t\t\t\t\t\t? { ...result, ok: true, relevant: relevance.relevant, confidence: relevance.confidence }\n\t\t\t\t\t\t\t\t: result;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (!result.ok) this._parseFailures++;\n\t\t\t\tthis._storeResult(result);\n\t\t\t\tcompleted.push(result);\n\t\t\t}\n\t\t} finally {\n\t\t\tthis._draining = false;\n\t\t}\n\t\treturn completed;\n\t}\n\n\tprivate _storeResult(result: CurationResult): void {\n\t\tif (this._results.size >= MAX_RESULTS) {\n\t\t\tconst oldest = this._results.keys().next().value;\n\t\t\tif (oldest !== undefined) this._results.delete(oldest);\n\t\t}\n\t\tthis._results.set(result.key, result);\n\t}\n}\n"]}
1
+ {"version":3,"file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AAG,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAGzC;IAED,gFAAgF;IAChF,gBAAgB,IAAI,IAAI,CAEvB;IAED,YAAY,CAAC,GAAG,EAAE,MAAM,GAAG;QAAE,QAAQ,EAAE,OAAO,CAAC;QAAC,UAAU,EAAE,MAAM,CAAA;KAAE,GAAG,SAAS,CAI/E;IAED,OAAO,IAAI,OAAO,CAEjB;IAED,IAAI,UAAU,IAAI,OAAO,CAExB;IAED,SAAS,IAAI,yBAAyB,CAUrC;IAED;;;;;OAKG;IACG,KAAK,CAAC,IAAI,EAAE;QACjB,QAAQ,EAAE,gBAAgB,CAAC;QAC3B,OAAO,EAAE,MAAM,CAAC;QAChB,MAAM,CAAC,EAAE,WAAW,CAAC;QACrB,GAAG,CAAC,EAAE,MAAM,MAAM,CAAC;KACnB,GAAG,OAAO,CAAC,cAAc,EAAE,CAAC,CAoD5B;IAED,OAAO,CAAC,YAAY;CAOpB","sourcesContent":["import { runBoundedCompletion } from \"../autonomy/bounded-completion.ts\";\nimport { wrapUntrustedText } from \"../security/untrusted-boundary.ts\";\n\n/**\n * Brain-assisted context curation (see docs/model-router-rework/brain-context-curation-design.md):\n * a SIDECAR curator that consumes reports the context pipeline already produces and feeds back\n * small, typed advisories. It is never a pipeline stage: every consumer must behave byte-for-byte\n * identically when a result is absent (missing digest -> today's stub; missing relevance ->\n * today's enforcement decision). The curator itself is provider-free — the completion executor is\n * injected per drain, so it works against any registered local model and faux providers in tests.\n *\n * Memory bounds are explicit: the queue and result map are both capped, and drops are counted in\n * telemetry rather than silent. Results are keyed for idempotency (digests by the GC record's\n * content hash, relevance by the audit item id), so re-enqueueing the same work is free.\n */\n\nexport const CURATION_DIGEST_SYSTEM_PROMPT = [\n\t\"You digest tool-output chunks for a coding agent's context curator. You never solve the task.\",\n\t\"Given a chunk, respond with STRICT JSON only - no prose:\",\n\t'{\"digest\":\"<one or two sentences, max 200 characters, keeping exact identifiers>\"}',\n\t\"Keep exact file paths, symbol names, error codes, and version strings verbatim.\",\n].join(\"\\n\");\n\nexport const CURATION_RELEVANCE_SYSTEM_PROMPT = [\n\t\"You judge whether a stale tool output is still relevant to the user's current goal.\",\n\t\"You never solve the task. Respond with STRICT JSON only - no prose:\",\n\t'{\"relevant\":true|false,\"confidence\":<0..1>}',\n\t\"relevant=false means the chunk is about something the current goal no longer needs.\",\n\t\"When uncertain, answer relevant=true with low confidence - keeping content is the safe default.\",\n].join(\"\\n\");\n\nexport const CURATION_COMPACTION_DIGEST_SYSTEM_PROMPT = [\n\t\"You pre-digest a chunk of an agent conversation for compaction. You never continue the conversation.\",\n\t\"Extract ONLY durable facts: decisions made, file paths and symbols touched, errors and their causes,\",\n\t\"user requirements, and outcomes. Respond with STRICT JSON only - no prose:\",\n\t'{\"digest\":\"<bullet-style summary, max 700 characters, exact identifiers verbatim>\"}',\n].join(\"\\n\");\n\nexport function parseCompactionChunkDigest(text: string): string | undefined {\n\tconst parsed = extractJsonObject(text);\n\tif (!parsed) return undefined;\n\tconst digest = (parsed as { digest?: unknown }).digest;\n\tif (typeof digest !== \"string\") return undefined;\n\tconst trimmed = digest.trim();\n\tif (trimmed.length === 0 || trimmed.length > 800) return undefined;\n\treturn trimmed;\n}\n\nexport interface PreDigestResult {\n\ttext: string;\n\ttotalChunks: number;\n\tdigested: number;\n\tfailed: number;\n}\n\nconst PRE_DIGEST_CHUNK_CHARS = 24_000;\nconst PRE_DIGEST_KEEP_RECENT_CHARS = 16_000;\nconst PRE_DIGEST_CHUNK_WALL_CLOCK_MS = 25_000;\n\n/**\n * Compaction pre-digest (design surface 3): shrink the conversation text sent to the frontier\n * summarizer by digesting OLD chunks locally, keeping the recent tail verbatim. Chunk digestion\n * is mechanical extraction — the frontier model still writes the summary. Partial assist, never\n * partial loss: any chunk whose digest fails (parse/timeout) passes through verbatim.\n */\nexport async function preDigestConversationText(args: {\n\ttext: string;\n\tcomplete: CurationComplete;\n\tsignal?: AbortSignal;\n\tchunkChars?: number;\n\tkeepRecentChars?: number;\n}): Promise<PreDigestResult> {\n\tconst chunkChars = args.chunkChars ?? PRE_DIGEST_CHUNK_CHARS;\n\tconst keepRecentChars = args.keepRecentChars ?? PRE_DIGEST_KEEP_RECENT_CHARS;\n\tif (args.text.length <= chunkChars + keepRecentChars) {\n\t\treturn { text: args.text, totalChunks: 0, digested: 0, failed: 0 };\n\t}\n\tconst cut = args.text.length - keepRecentChars;\n\tconst prefix = args.text.slice(0, cut);\n\tconst tail = args.text.slice(cut);\n\tconst chunks: string[] = [];\n\tfor (let offset = 0; offset < prefix.length; offset += chunkChars) {\n\t\tchunks.push(prefix.slice(offset, offset + chunkChars));\n\t}\n\tlet digested = 0;\n\tlet failed = 0;\n\tconst parts: string[] = [];\n\tfor (const [index, chunk] of chunks.entries()) {\n\t\tif (args.signal?.aborted) {\n\t\t\tparts.push(chunk);\n\t\t\tfailed++;\n\t\t\tcontinue;\n\t\t}\n\t\tconst bounded = await runBoundedCompletion({\n\t\t\tmaxWallClockMs: PRE_DIGEST_CHUNK_WALL_CLOCK_MS,\n\t\t\tsignal: args.signal,\n\t\t\texecute: (signal) =>\n\t\t\t\targs.complete({ systemPrompt: CURATION_COMPACTION_DIGEST_SYSTEM_PROMPT, userPrompt: chunk, signal }),\n\t\t});\n\t\tconst digest =\n\t\t\tbounded.completion && !bounded.failure ? parseCompactionChunkDigest(bounded.completion.text) : undefined;\n\t\tif (digest !== undefined) {\n\t\t\tdigested++;\n\t\t\tparts.push(`[locally pre-digested chunk ${index + 1}/${chunks.length} (${chunk.length} chars):]\\n${digest}`);\n\t\t} else {\n\t\t\tfailed++;\n\t\t\tparts.push(chunk);\n\t\t}\n\t}\n\treturn { text: `${parts.join(\"\\n\\n\")}${tail}`, totalChunks: chunks.length, digested, failed };\n}\n\nexport interface CurationJob {\n\tkind: \"stub_digest\" | \"relevance\";\n\t/** Idempotency key: digest jobs use the GC record's content hash, relevance jobs the item id. */\n\tkey: string;\n\t/** Bounded chunk the local model must actually be able to process (sliced on enqueue). */\n\tcontent: string;\n\t/** Relevance jobs only: the goal/intent line the chunk is judged against. */\n\tgoal?: string;\n}\n\nexport interface CurationResult {\n\tkey: string;\n\tkind: CurationJob[\"kind\"];\n\tok: boolean;\n\t/** Raw model-parsed digest (stub_digest jobs only): human-readable, NOT fenced. Kept as-is for\n\t * logging/audit (e.g. the session's brain-curation entry) — never render this into a provider\n\t * prompt; use `fencedDigest` (via getDigest) for that. */\n\tdigest?: string;\n\t/** The same digest fenced in the untrusted-content boundary, wrapped exactly ONCE here at store\n\t * time (not at every context-gc render), so the fence's nonce is fixed for the life of this\n\t * result — every render of it is then byte-identical, keeping the provider's prompt-prefix cache\n\t * warm. This is what getDigest() returns and what context-gc renders verbatim into a packed stub. */\n\tfencedDigest?: string;\n\trelevant?: boolean;\n\tconfidence?: number;\n\tms: number;\n}\n\nexport interface CurationTelemetrySnapshot {\n\tjobsRun: number;\n\tparseFailures: number;\n\tdroppedJobs: number;\n\t/** Times a computed digest was actually RENDERED into a GC stub on a real turn — the\n\t * pays-for-itself proxy: every serve is packed content the frontier model got a semantic\n\t * handle on without re-running tools. */\n\tdigestsServed: number;\n\t/** Chars processed locally (an honest proxy for frontier tokens NOT spent on this work). */\n\tlocalChars: number;\n\tqueued: number;\n\tresultsHeld: number;\n}\n\nexport type CurationComplete = (input: {\n\tsystemPrompt: string;\n\tuserPrompt: string;\n\tsignal?: AbortSignal;\n}) => Promise<{ text: string; costUsd: number; stopReason: string }>;\n\nconst MAX_QUEUE = 32;\nconst MAX_RESULTS = 200;\nconst MAX_JOB_CONTENT_CHARS = 8_000;\nconst DIGEST_MAX_WALL_CLOCK_MS = 20_000;\nconst RELEVANCE_MAX_WALL_CLOCK_MS = 8_000;\nexport const CURATION_RELEVANCE_MIN_CONFIDENCE = 0.8;\n\nfunction extractJsonObject(text: string): unknown | undefined {\n\tconst trimmed = text.trim();\n\tconst candidates: string[] = [trimmed];\n\tconst fenced = /```(?:json)?\\s*([\\s\\S]*?)```/.exec(trimmed);\n\tif (fenced?.[1]) candidates.push(fenced[1].trim());\n\tconst start = trimmed.indexOf(\"{\");\n\tconst end = trimmed.lastIndexOf(\"}\");\n\tif (start >= 0 && end > start) candidates.push(trimmed.slice(start, end + 1));\n\tfor (const candidate of candidates) {\n\t\ttry {\n\t\t\tconst parsed = JSON.parse(candidate);\n\t\t\tif (parsed && typeof parsed === \"object\" && !Array.isArray(parsed)) return parsed;\n\t\t} catch {\n\t\t\t// try next candidate\n\t\t}\n\t}\n\treturn undefined;\n}\n\nexport function parseCurationDigest(text: string): string | undefined {\n\tconst parsed = extractJsonObject(text);\n\tif (!parsed) return undefined;\n\tconst digest = (parsed as { digest?: unknown }).digest;\n\tif (typeof digest !== \"string\") return undefined;\n\tconst trimmed = digest.trim().replace(/\\s+/g, \" \");\n\tif (trimmed.length === 0 || trimmed.length > 240) return undefined;\n\treturn trimmed;\n}\n\n/**\n * Fence a parsed digest in the untrusted-content boundary exactly ONCE, here at store time — the\n * digest is a machine paraphrase of (possibly attacker-influenced) tool output, so it must never\n * reach the provider as bare prose (design: untrusted-content-boundary). Wrapping at store time,\n * not at every context-gc render, fixes the fence's nonce for the life of the stored result: every\n * render of the same stored digest is then byte-identical, so the provider's prompt-prefix cache\n * stays warm — the same pattern transcript-recall already uses for its pages.\n */\nfunction fenceDigestForStorage(digest: string): string {\n\treturn wrapUntrustedText(digest, \"context-gc:auto-digest\");\n}\n\nexport function parseCurationRelevance(text: string): { relevant: boolean; confidence: number } | undefined {\n\tconst parsed = extractJsonObject(text);\n\tif (!parsed) return undefined;\n\tconst record = parsed as { relevant?: unknown; confidence?: unknown };\n\tif (typeof record.relevant !== \"boolean\") return undefined;\n\tconst confidence =\n\t\ttypeof record.confidence === \"number\" && Number.isFinite(record.confidence)\n\t\t\t? Math.max(0, Math.min(1, record.confidence))\n\t\t\t: 0;\n\treturn { relevant: record.relevant, confidence };\n}\n\nexport class BrainCurator {\n\tprivate readonly _queue = new Map<string, CurationJob>();\n\tprivate readonly _results = new Map<string, CurationResult>();\n\tprivate _jobsRun = 0;\n\tprivate _parseFailures = 0;\n\tprivate _droppedJobs = 0;\n\tprivate _localChars = 0;\n\tprivate _digestsServed = 0;\n\tprivate _draining = false;\n\n\tenqueue(job: CurationJob): void {\n\t\tif (this._results.has(job.key) || this._queue.has(job.key)) return;\n\t\tif (this._queue.size >= MAX_QUEUE) {\n\t\t\t// Drop the OLDEST queued job (newer work reflects the current goal better) and count it.\n\t\t\tconst oldest = this._queue.keys().next().value;\n\t\t\tif (oldest !== undefined) this._queue.delete(oldest);\n\t\t\tthis._droppedJobs++;\n\t\t}\n\t\tthis._queue.set(job.key, { ...job, content: job.content.slice(0, MAX_JOB_CONTENT_CHARS) });\n\t}\n\n\t/** Returns the digest already fenced in the untrusted-content boundary — callers must render it\n\t * verbatim into a provider prompt, never re-wrap it (see CurationResult.fencedDigest for why). */\n\tgetDigest(key: string): string | undefined {\n\t\tconst result = this._results.get(key);\n\t\treturn result?.ok && result.kind === \"stub_digest\" ? result.fencedDigest : undefined;\n\t}\n\n\t/** Callers report when a digest was rendered into a real (sent) prompt stub. */\n\tnoteDigestServed(): void {\n\t\tthis._digestsServed++;\n\t}\n\n\tgetRelevance(key: string): { relevant: boolean; confidence: number } | undefined {\n\t\tconst result = this._results.get(key);\n\t\tif (!result?.ok || result.kind !== \"relevance\" || result.relevant === undefined) return undefined;\n\t\treturn { relevant: result.relevant, confidence: result.confidence ?? 0 };\n\t}\n\n\thasWork(): boolean {\n\t\treturn this._queue.size > 0;\n\t}\n\n\tget isDraining(): boolean {\n\t\treturn this._draining;\n\t}\n\n\ttelemetry(): CurationTelemetrySnapshot {\n\t\treturn {\n\t\t\tjobsRun: this._jobsRun,\n\t\t\tparseFailures: this._parseFailures,\n\t\t\tdroppedJobs: this._droppedJobs,\n\t\t\tdigestsServed: this._digestsServed,\n\t\t\tlocalChars: this._localChars,\n\t\t\tqueued: this._queue.size,\n\t\t\tresultsHeld: this._results.size,\n\t\t};\n\t}\n\n\t/**\n\t * Run up to `maxJobs` queued jobs through the injected local-model completer. Single-flight:\n\t * a concurrent drain call returns [] immediately rather than double-running jobs. Every call\n\t * is wall-clock bounded; a failed/unparseable job is recorded as a not-ok result (so it is\n\t * not retried forever) and counted in telemetry.\n\t */\n\tasync drain(args: {\n\t\tcomplete: CurationComplete;\n\t\tmaxJobs: number;\n\t\tsignal?: AbortSignal;\n\t\tnow?: () => number;\n\t}): Promise<CurationResult[]> {\n\t\tif (this._draining) return [];\n\t\tthis._draining = true;\n\t\tconst now = args.now ?? Date.now;\n\t\tconst completed: CurationResult[] = [];\n\t\ttry {\n\t\t\tconst jobs = [...this._queue.values()].slice(0, Math.max(0, args.maxJobs));\n\t\t\tfor (const job of jobs) {\n\t\t\t\tif (args.signal?.aborted) break;\n\t\t\t\tthis._queue.delete(job.key);\n\t\t\t\tconst started = now();\n\t\t\t\tconst bounded = await runBoundedCompletion({\n\t\t\t\t\tmaxWallClockMs: job.kind === \"stub_digest\" ? DIGEST_MAX_WALL_CLOCK_MS : RELEVANCE_MAX_WALL_CLOCK_MS,\n\t\t\t\t\tsignal: args.signal,\n\t\t\t\t\texecute: (signal) =>\n\t\t\t\t\t\targs.complete({\n\t\t\t\t\t\t\tsystemPrompt:\n\t\t\t\t\t\t\t\tjob.kind === \"stub_digest\" ? CURATION_DIGEST_SYSTEM_PROMPT : CURATION_RELEVANCE_SYSTEM_PROMPT,\n\t\t\t\t\t\t\tuserPrompt:\n\t\t\t\t\t\t\t\tjob.kind === \"stub_digest\"\n\t\t\t\t\t\t\t\t\t? job.content\n\t\t\t\t\t\t\t\t\t: `Current goal: ${job.goal ?? \"(unknown)\"}\\n\\nStale chunk:\\n${job.content}`,\n\t\t\t\t\t\t\tsignal,\n\t\t\t\t\t\t}),\n\t\t\t\t});\n\t\t\t\tconst ms = now() - started;\n\t\t\t\tthis._jobsRun++;\n\t\t\t\tthis._localChars += job.content.length;\n\t\t\t\tlet result: CurationResult = { key: job.key, kind: job.kind, ok: false, ms };\n\t\t\t\tif (bounded.completion && !bounded.failure) {\n\t\t\t\t\tif (job.kind === \"stub_digest\") {\n\t\t\t\t\t\tconst digest = parseCurationDigest(bounded.completion.text);\n\t\t\t\t\t\tresult =\n\t\t\t\t\t\t\tdigest !== undefined\n\t\t\t\t\t\t\t\t? { ...result, ok: true, digest, fencedDigest: fenceDigestForStorage(digest) }\n\t\t\t\t\t\t\t\t: result;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tconst relevance = parseCurationRelevance(bounded.completion.text);\n\t\t\t\t\t\tresult =\n\t\t\t\t\t\t\trelevance !== undefined\n\t\t\t\t\t\t\t\t? { ...result, ok: true, relevant: relevance.relevant, confidence: relevance.confidence }\n\t\t\t\t\t\t\t\t: result;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (!result.ok) this._parseFailures++;\n\t\t\t\tthis._storeResult(result);\n\t\t\t\tcompleted.push(result);\n\t\t\t}\n\t\t} finally {\n\t\t\tthis._draining = false;\n\t\t}\n\t\treturn completed;\n\t}\n\n\tprivate _storeResult(result: CurationResult): void {\n\t\tif (this._results.size >= MAX_RESULTS) {\n\t\t\tconst oldest = this._results.keys().next().value;\n\t\t\tif (oldest !== undefined) this._results.delete(oldest);\n\t\t}\n\t\tthis._results.set(result.key, result);\n\t}\n}\n"]}
@@ -1,4 +1,5 @@
1
1
  import { runBoundedCompletion } from "../autonomy/bounded-completion.js";
2
+ import { wrapUntrustedText } from "../security/untrusted-boundary.js";
2
3
  /**
3
4
  * Brain-assisted context curation (see docs/model-router-rework/brain-context-curation-design.md):
4
5
  * a SIDECAR curator that consumes reports the context pipeline already produces and feeds back
@@ -130,6 +131,17 @@ export function parseCurationDigest(text) {
130
131
  return undefined;
131
132
  return trimmed;
132
133
  }
134
+ /**
135
+ * Fence a parsed digest in the untrusted-content boundary exactly ONCE, here at store time — the
136
+ * digest is a machine paraphrase of (possibly attacker-influenced) tool output, so it must never
137
+ * reach the provider as bare prose (design: untrusted-content-boundary). Wrapping at store time,
138
+ * not at every context-gc render, fixes the fence's nonce for the life of the stored result: every
139
+ * render of the same stored digest is then byte-identical, so the provider's prompt-prefix cache
140
+ * stays warm — the same pattern transcript-recall already uses for its pages.
141
+ */
142
+ function fenceDigestForStorage(digest) {
143
+ return wrapUntrustedText(digest, "context-gc:auto-digest");
144
+ }
133
145
  export function parseCurationRelevance(text) {
134
146
  const parsed = extractJsonObject(text);
135
147
  if (!parsed)
@@ -163,9 +175,11 @@ export class BrainCurator {
163
175
  }
164
176
  this._queue.set(job.key, { ...job, content: job.content.slice(0, MAX_JOB_CONTENT_CHARS) });
165
177
  }
178
+ /** Returns the digest already fenced in the untrusted-content boundary — callers must render it
179
+ * verbatim into a provider prompt, never re-wrap it (see CurationResult.fencedDigest for why). */
166
180
  getDigest(key) {
167
181
  const result = this._results.get(key);
168
- return result?.ok && result.kind === "stub_digest" ? result.digest : undefined;
182
+ return result?.ok && result.kind === "stub_digest" ? result.fencedDigest : undefined;
169
183
  }
170
184
  /** Callers report when a digest was rendered into a real (sent) prompt stub. */
171
185
  noteDigestServed() {
@@ -231,7 +245,10 @@ export class BrainCurator {
231
245
  if (bounded.completion && !bounded.failure) {
232
246
  if (job.kind === "stub_digest") {
233
247
  const digest = parseCurationDigest(bounded.completion.text);
234
- result = digest !== undefined ? { ...result, ok: true, digest } : result;
248
+ result =
249
+ digest !== undefined
250
+ ? { ...result, ok: true, digest, fencedDigest: fenceDigestForStorage(digest) }
251
+ : result;
235
252
  }
236
253
  else {
237
254
  const relevance = parseCurationRelevance(bounded.completion.text);