@causyne/agent 1.20.120 → 1.20.122

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 (276) hide show
  1. package/README.md +3 -3
  2. package/package.json +1 -1
  3. package/src/acp/agentCatalog.js +81 -26
  4. package/src/acp/agentCatalog.ts +73 -29
  5. package/src/acp/client.js +210 -53
  6. package/src/acp/client.ts +202 -52
  7. package/src/acp/peerProfiles.js +55 -22
  8. package/src/acp/peerProfiles.ts +51 -22
  9. package/src/acp/protocol.js +37 -8
  10. package/src/acp/protocol.ts +30 -8
  11. package/src/acp/server.js +123 -25
  12. package/src/acp/server.ts +124 -24
  13. package/src/agent/errorClassifier.js +117 -0
  14. package/src/agent/errorClassifier.ts +165 -0
  15. package/src/agent/promptIntent.js +200 -0
  16. package/src/agent/promptIntent.ts +203 -0
  17. package/src/agent/toolArgValidator.js +97 -0
  18. package/src/agent/toolArgValidator.ts +112 -0
  19. package/src/agentLoop.js +33 -344
  20. package/src/agentLoop.ts +51 -352
  21. package/src/approvalGrants.js +19 -7
  22. package/src/approvalGrants.ts +20 -7
  23. package/src/approvalPolicy.js +48 -15
  24. package/src/approvalPolicy.ts +46 -15
  25. package/src/autoUpdate.js +116 -10
  26. package/src/autoUpdate.ts +149 -10
  27. package/src/browser/causyneBrowser.js +3 -2
  28. package/src/browser/causyneBrowser.ts +3 -2
  29. package/src/browser/searchProviders.js +1 -1
  30. package/src/browser/searchProviders.ts +1 -1
  31. package/src/cliMode.js +16 -2
  32. package/src/commands.js +10 -9
  33. package/src/config.js +288 -272
  34. package/src/config.ts +342 -0
  35. package/src/configVault.js +271 -0
  36. package/src/configVault.ts +273 -0
  37. package/src/continuum/compactor.js +2 -1
  38. package/src/continuum/compactor.ts +2 -1
  39. package/src/continuum/sanitizer.js +10 -3
  40. package/src/continuum/sanitizer.ts +9 -3
  41. package/src/continuum/ui/continuumPickerView.js +3 -2
  42. package/src/continuum/ui/continuumPickerView.ts +3 -2
  43. package/src/core/contextCompactor.js +70 -11
  44. package/src/core/contextCompactor.ts +83 -11
  45. package/src/cortex/vectorDb.js +26 -15
  46. package/src/cortex/vectorDb.ts +26 -16
  47. package/src/creative/liveBridge.js +7 -5
  48. package/src/creative/liveBridge.ts +7 -5
  49. package/src/creative/studioScripts.js +16 -5
  50. package/src/creative/studioScripts.ts +14 -5
  51. package/src/decisionPolicy.js +16 -4
  52. package/src/decisionPolicy.ts +14 -4
  53. package/src/documentEngine/antiSlopAuditor.js +10 -5
  54. package/src/documentEngine/antiSlopAuditor.ts +11 -5
  55. package/src/documentEngine/documentForge.js +47 -15
  56. package/src/documentEngine/documentForge.ts +43 -14
  57. package/src/dynamicCatalogue.js +42 -73
  58. package/src/dynamicCatalogue.ts +74 -60
  59. package/src/engines/design.js +2 -1
  60. package/src/engines/design.ts +2 -1
  61. package/src/engines/film.js +4 -4
  62. package/src/engines/film.ts +2 -2
  63. package/src/engines/light.js +2 -1
  64. package/src/engines/light.ts +2 -1
  65. package/src/engines/registry.js +1 -1
  66. package/src/engines/registry.ts +1 -1
  67. package/src/engines/reverseHarness.js +4 -3
  68. package/src/engines/reverseHarness.ts +4 -3
  69. package/src/entrypoint.js +77 -4
  70. package/src/headlessCli.js +305 -0
  71. package/src/headlessCli.ts +381 -0
  72. package/src/historyPruner.js +3 -2
  73. package/src/historyPruner.ts +3 -2
  74. package/src/hooks.js +3 -0
  75. package/src/hooks.ts +3 -0
  76. package/src/implementationPlan.js +21 -11
  77. package/src/implementationPlan.ts +21 -11
  78. package/src/infra/atomicWriter.js +4 -1
  79. package/src/infra/atomicWriter.ts +4 -1
  80. package/src/launchIntent.js +1 -1
  81. package/src/launchIntent.ts +1 -1
  82. package/src/mcp/mcpClient.js +38 -11
  83. package/src/mcp/mcpClient.ts +44 -11
  84. package/src/mcp/mcpRegistry.js +2 -5
  85. package/src/mcp/mcpRegistry.ts +2 -5
  86. package/src/mcp/mcpSecurity.js +189 -0
  87. package/src/mcp/mcpSecurity.ts +190 -0
  88. package/src/memory/scopedFacts.js +1 -1
  89. package/src/memory/scopedFacts.ts +1 -1
  90. package/src/memory/symbolFolder.js +1 -1
  91. package/src/memory/symbolFolder.ts +1 -1
  92. package/src/modelRouter.js +1 -1
  93. package/src/modelRouter.ts +1 -1
  94. package/src/observer/evidence.js +10 -4
  95. package/src/observer/evidence.ts +10 -4
  96. package/src/osKeychain.js +263 -0
  97. package/src/osKeychain.ts +287 -0
  98. package/src/perception.js +3 -2
  99. package/src/perception.ts +3 -2
  100. package/src/planCache.js +2 -2
  101. package/src/planCache.ts +2 -2
  102. package/src/pluginsFactory/pluginsFactory.js +19 -11
  103. package/src/pluginsFactory/pluginsFactory.ts +18 -11
  104. package/src/promptMentions.js +2 -2
  105. package/src/promptMentions.ts +2 -2
  106. package/src/providers/acp.js +1 -1
  107. package/src/providers/acp.ts +1 -1
  108. package/src/providers/anthropic.js +328 -385
  109. package/src/providers/anthropic.ts +386 -0
  110. package/src/providers/antigravity.js +10 -4
  111. package/src/providers/antigravity.ts +10 -4
  112. package/src/providers/base.js +221 -319
  113. package/src/providers/base.ts +340 -0
  114. package/src/providers/byokHttp.js +397 -0
  115. package/src/providers/byokHttp.ts +497 -0
  116. package/src/providers/byokStream.js +748 -0
  117. package/src/providers/byokStream.ts +863 -0
  118. package/src/providers/dashscope-byok.js +98 -81
  119. package/src/providers/dashscope-byok.ts +114 -0
  120. package/src/providers/deepseek.js +74 -64
  121. package/src/providers/deepseek.ts +99 -0
  122. package/src/providers/factory.js +35 -28
  123. package/src/providers/factory.ts +40 -0
  124. package/src/providers/gemini.js +229 -253
  125. package/src/providers/gemini.ts +261 -0
  126. package/src/providers/loopGuard.js +9 -5
  127. package/src/providers/loopGuard.ts +10 -5
  128. package/src/providers/moonshot.js +71 -64
  129. package/src/providers/moonshot.ts +93 -0
  130. package/src/providers/muse.js +82 -152
  131. package/src/providers/muse.ts +122 -0
  132. package/src/providers/ollama.js +116 -93
  133. package/src/providers/ollama.ts +135 -0
  134. package/src/providers/openai-compatible.js +114 -65
  135. package/src/providers/openai-compatible.ts +139 -0
  136. package/src/providers/openai.js +22 -15
  137. package/src/providers/openai.ts +30 -0
  138. package/src/providers/openrouter.js +194 -98
  139. package/src/providers/openrouter.ts +202 -97
  140. package/src/providers/pi.js +6 -0
  141. package/src/providers/pi.ts +6 -0
  142. package/src/providers/qwen-byok.js +97 -71
  143. package/src/providers/qwen-byok.ts +113 -0
  144. package/src/providers/toolContracts.js +40 -14
  145. package/src/providers/toolContracts.ts +35 -14
  146. package/src/providers/wireNormalizer.js +78 -11
  147. package/src/providers/wireNormalizer.ts +68 -12
  148. package/src/providers/xai.js +74 -64
  149. package/src/providers/xai.ts +97 -0
  150. package/src/reliability/assetEvidence.js +4 -2
  151. package/src/reliability/assetEvidence.ts +4 -2
  152. package/src/sandbox.js +486 -530
  153. package/src/sandbox.ts +552 -0
  154. package/src/sandboxPolicy.js +1287 -0
  155. package/src/sandboxPolicy.ts +1381 -0
  156. package/src/sessionJournal.js +55 -3
  157. package/src/sessionJournal.ts +58 -3
  158. package/src/skills/skillResourceSafety.js +19 -8
  159. package/src/skills/skillResourceSafety.ts +16 -7
  160. package/src/skillsManager.js +3 -3
  161. package/src/skillsManager.ts +3 -3
  162. package/src/smartToolsUse.js +28 -4
  163. package/src/smartToolsUse.ts +29 -7
  164. package/src/stallGuard.js +45 -22
  165. package/src/stallGuard.ts +46 -22
  166. package/src/subagentJournal.js +6 -4
  167. package/src/subagentJournal.ts +6 -4
  168. package/src/textDiff.js +6 -1
  169. package/src/textDiff.ts +6 -1
  170. package/src/timeMachine.js +7 -1
  171. package/src/timeMachine.ts +7 -1
  172. package/src/tokenTracker.js +43 -28
  173. package/src/tokenTracker.ts +44 -30
  174. package/src/toolPacks.js +3 -1
  175. package/src/toolPacks.ts +3 -1
  176. package/src/tools/archive.js +245 -35
  177. package/src/tools/archive.ts +244 -35
  178. package/src/tools/computerUse.js +7 -3
  179. package/src/tools/computerUse.ts +7 -3
  180. package/src/tools/creativeApps.js +13 -8
  181. package/src/tools/creativeApps.ts +22 -9
  182. package/src/tools/deferredMcpSearch.js +26 -14
  183. package/src/tools/deferredMcpSearch.ts +26 -14
  184. package/src/tools/desktopOpen.js +69 -10
  185. package/src/tools/desktopOpen.ts +70 -11
  186. package/src/tools/documentForge.js +167 -82
  187. package/src/tools/documentForge.ts +169 -84
  188. package/src/tools/fsEdit.js +101 -30
  189. package/src/tools/fsEdit.ts +105 -32
  190. package/src/tools/fsFind.js +8 -5
  191. package/src/tools/fsFind.ts +7 -4
  192. package/src/tools/fsRead.js +119 -13
  193. package/src/tools/fsRead.ts +124 -13
  194. package/src/tools/fsWrite.js +17 -5
  195. package/src/tools/fsWrite.ts +17 -7
  196. package/src/tools/generateMediaViaApi.js +82 -19
  197. package/src/tools/generateMediaViaApi.ts +80 -19
  198. package/src/tools/memoryRecall.js +62 -11
  199. package/src/tools/memoryRecall.ts +70 -13
  200. package/src/tools/memoryWrite.js +27 -14
  201. package/src/tools/memoryWrite.ts +30 -14
  202. package/src/tools/multiEdit.js +100 -30
  203. package/src/tools/multiEdit.ts +104 -32
  204. package/src/tools/nativeEngine.js +33 -18
  205. package/src/tools/nativeEngine.ts +31 -18
  206. package/src/tools/openSourceToolProvisioner.js +49 -14
  207. package/src/tools/openSourceToolProvisioner.ts +54 -15
  208. package/src/tools/osSandbox.js +513 -0
  209. package/src/tools/osSandbox.ts +588 -0
  210. package/src/tools/payloadSanitizer.js +40 -8
  211. package/src/tools/payloadSanitizer.ts +39 -8
  212. package/src/tools/peerAgent.js +96 -34
  213. package/src/tools/peerAgent.ts +114 -37
  214. package/src/tools/persistentShell.js +8 -3
  215. package/src/tools/pluginsFactory.js +38 -6
  216. package/src/tools/pluginsFactory.ts +42 -6
  217. package/src/tools/readNativeSkill.js +10 -8
  218. package/src/tools/readNativeSkill.ts +10 -8
  219. package/src/tools/requestDecision.js +10 -3
  220. package/src/tools/requestDecision.ts +10 -3
  221. package/src/tools/resolveAutomator.js +91 -17
  222. package/src/tools/resolveAutomator.ts +102 -17
  223. package/src/tools/reverseEngineering.js +168 -41
  224. package/src/tools/reverseEngineering.ts +161 -41
  225. package/src/tools/subprocessEnv.js +197 -0
  226. package/src/tools/subprocessEnv.ts +212 -0
  227. package/src/tools/sysRun.js +108 -35
  228. package/src/tools/sysRun.ts +119 -31
  229. package/src/tools/toolDispatch.js +24 -1
  230. package/src/tools/toolDispatch.ts +21 -1
  231. package/src/tools/toolOutputStore.js +62 -23
  232. package/src/tools/toolOutputStore.ts +56 -23
  233. package/src/tools/toolScanner.js +13 -10
  234. package/src/tools/toolScanner.ts +13 -10
  235. package/src/tools/toolSelfRepair.js +94 -28
  236. package/src/tools/toolSelfRepair.ts +96 -28
  237. package/src/tools/uiForge.js +71 -6
  238. package/src/tools/uiForge.ts +74 -6
  239. package/src/tools/viewImage.js +62 -17
  240. package/src/tools/viewImage.ts +57 -12
  241. package/src/tools/visionInspector.js +15 -3
  242. package/src/tools/visionInspector.ts +15 -3
  243. package/src/tools/walkerSafety.js +2 -0
  244. package/src/tools/walkerSafety.ts +1 -0
  245. package/src/tools/webFetch.js +105 -10
  246. package/src/tools/webFetch.ts +105 -11
  247. package/src/tui/banner.js +3 -2
  248. package/src/tui/banner.ts +3 -2
  249. package/src/tui/consoleGuard.js +12 -4
  250. package/src/tui/consoleGuard.ts +9 -4
  251. package/src/tui/messageInteraction.js +2 -3
  252. package/src/tui/messageInteraction.ts +2 -3
  253. package/src/tui/modelPicker.js +1 -0
  254. package/src/tui/modelPicker.ts +1 -0
  255. package/src/tui/overlay.js +3 -1
  256. package/src/tui/overlay.ts +3 -1
  257. package/src/tui/sessionPicker.js +3 -2
  258. package/src/tui/sessionPicker.ts +3 -2
  259. package/src/tui/sessionPickerView.js +7 -1
  260. package/src/tui/sessionPickerView.ts +6 -1
  261. package/src/tui/toolOutputNormalizer.js +2 -3
  262. package/src/tui/toolOutputNormalizer.ts +4 -3
  263. package/src/tui/viewport.js +4 -4
  264. package/src/tui/viewport.ts +5 -5
  265. package/src/tui/workspaceIdentity.js +2 -1
  266. package/src/tui/workspaceIdentity.ts +2 -1
  267. package/src/uncertainty.js +8 -3
  268. package/src/uncertainty.ts +8 -3
  269. package/src/utils/paths.js +8 -5
  270. package/src/utils/paths.ts +9 -7
  271. package/src/vfeTracker.js +9 -3
  272. package/src/vfeTracker.ts +9 -3
  273. package/src/config.d.ts +0 -2
  274. package/src/providers/base.d.ts +0 -94
  275. package/src/providers/factory.d.ts +0 -1
  276. package/src/sandbox.d.ts +0 -1
package/src/sandbox.js CHANGED
@@ -1,559 +1,515 @@
1
- import path from 'path';
2
- import os from 'os';
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import os from 'node:os';
3
4
  import { isIP } from 'node:net';
4
5
  import { loadConfig } from './config.js';
5
6
  import { isDevEmulator } from './devMode.js';
6
7
  import { validateBrowserActSandbox } from './browser/causyneBrowser.js';
7
- import { isPhysicalPathAllowed } from './agent/workspaceBoundary.js';
8
-
9
-
10
- function maskQuotedSpans(text) {
11
- return text
12
- .replace(/"(?:[^"\\]|\\.)*"/g, '""')
13
- .replace(/'(?:[^'\\]|\\.)*'/g, "''")
14
- .replace(/`(?:[^`\\]|\\.)*`/g, '``');
15
- }
16
-
17
- /**
18
- * Split a command line into the individual commands the shell will run.
19
- *
20
- * Prefix matching only ever inspected the FIRST word of the whole line, so any
21
- * leading token disguised everything after it: `cd ~/Documents && rm -f x` was
22
- * classified from `cd` and auto-executed with no approval. Each segment must be
23
- * judged on its own.
24
- */
25
- function splitShellSegments(text) {
26
- return text
27
- .split(/&&|\|\||[;\n|&]/)
28
- .map((segment) => segment.trim())
29
- .filter((segment) => segment.length > 0);
30
- }
31
-
32
- /**
33
- * Read-only invocations of tools whose NAME is dangerous but whose subcommand
34
- * is not. Keyed by the leading word; the pattern must match the whole segment.
35
- *
36
- * WHY THIS EXISTS. `brew` is in DANGEROUS_PREFIXES because `brew install` runs
37
- * arbitrary install scripts. The prefix rule cannot tell that from
38
- * `brew --version`, so asking Blender's version escalated a chain to
39
- * DANGEROUS and put a red approval modal in front of the user. That is not a
40
- * cosmetic problem: a gate that cries wolf on `--version` is a gate people
41
- * learn to approve without reading, and then it is not a gate at all.
42
- *
43
- * THE RULE FOR ADDING TO THIS TABLE: the subcommand must be incapable of
44
- * changing anything — no install, no remove, no start/stop, no write. When in
45
- * doubt, leave it out; a false alarm is cheap and a missed one is not.
46
- *
47
- * `sudo` and `su` are deliberately absent and must stay absent: `sudo brew
48
- * --version` is a privilege escalation whatever follows it.
49
- */
8
+ import { isPhysicalPathAllowed, physicalPath } from './agent/workspaceBoundary.js';
9
+ import { isBlockedWorkspaceRoot, isExtendedCredentialPath, isSensitiveWriteTarget, analyzeShellCommand, isExtremeRemovalSegment, isFetchAndExecPipeline } from './sandboxPolicy.js';
50
10
  const READ_ONLY_INVOCATIONS = {
51
- brew: /^brew\s+(--version|-v|list|info|search|config|outdated|deps|home|--prefix|--cellar)\b/,
52
- apt: /^apt\s+(--version|list|show|search|policy)\b/,
53
- 'apt-get': /^apt-get\s+(--version|-v)\b/,
54
- yum: /^yum\s+(--version|list|info|search)\b/,
55
- dnf: /^dnf\s+(--version|list|info|search)\b/,
56
- systemctl: /^systemctl\s+(status|show|cat|is-active|is-enabled|is-failed|list-units|list-unit-files|--version)\b/,
57
- service: /^service\s+[\w.@-]+\s+status\b/,
58
- crontab: /^crontab\s+-l\b/,
59
- // `kill -l` lists signal names; `kill -0 PID` only probes whether a process
60
- // exists. Neither delivers a terminating signal.
61
- kill: /^kill\s+(-l|-0)\b/,
62
- git: /^git\s+reset\s+(--\s*)?$/
11
+ brew: /^brew\s+(--version|-v|list|info|search|config|outdated|deps|home|--prefix|--cellar)\b/,
12
+ apt: /^apt\s+(--version|list|show|search|policy)\b/,
13
+ 'apt-get': /^apt-get\s+(--version|-v)\b/,
14
+ yum: /^yum\s+(--version|list|info|search)\b/,
15
+ dnf: /^dnf\s+(--version|list|info|search)\b/,
16
+ systemctl: /^systemctl\s+(status|show|cat|is-active|is-enabled|is-failed|list-units|list-unit-files|--version)\b/,
17
+ service: /^service\s+[\w.@-]+\s+status\b/,
18
+ crontab: /^crontab\s+-l\b/,
19
+ kill: /^kill\s+(-l|-0)\b/,
20
+ git: /^git\s+reset\s+(--\s*)?$/
63
21
  };
64
-
65
- /**
66
- * True when a segment is a read-only use of an otherwise dangerous command.
67
- *
68
- * @param {string} segment One shell segment, already quote-masked.
69
- * @returns {boolean}
70
- */
22
+ function hasLinearPipeToShell(lowerText) {
23
+ const pipeIdx = lowerText.indexOf('|');
24
+ if (pipeIdx === -1)
25
+ return false;
26
+ const beforePipe = lowerText.slice(0, pipeIdx);
27
+ if (!/\b(?:curl|wget)\s/.test(beforePipe))
28
+ return false;
29
+ const afterPipe = lowerText.slice(pipeIdx + 1).trimStart();
30
+ return /^(?:sh|bash)(?:\s|$)/.test(afterPipe);
31
+ }
32
+ function hasRansomwareKeyword(lowerText) {
33
+ if (lowerText.includes('ransomware'))
34
+ return true;
35
+ const encIdx = lowerText.indexOf('encrypt');
36
+ return encIdx !== -1 && lowerText.indexOf('ransom', encIdx + 7) !== -1;
37
+ }
38
+ function hasDangerousFindAction(unit) {
39
+ const findMatch = /\bfind\b/.exec(unit);
40
+ if (!findMatch)
41
+ return false;
42
+ const tail = unit.slice(findMatch.index + findMatch[0].length);
43
+ return /\s-(?:exec|execdir|delete)\b/.test(tail);
44
+ }
71
45
  function isReadOnlyInvocation(segment) {
72
- const text = String(segment || '').trim();
73
- const leadingWord = text.split(/\s+/)[0];
74
- const pattern = READ_ONLY_INVOCATIONS[leadingWord];
75
- return Boolean(pattern && pattern.test(text));
46
+ const text = String(segment || '').trim();
47
+ const leadingWord = text.split(/\s+/)[0] || '';
48
+ if (!leadingWord || !Object.hasOwn(READ_ONLY_INVOCATIONS, leadingWord))
49
+ return false;
50
+ const pattern = READ_ONLY_INVOCATIONS[leadingWord];
51
+ return Boolean(pattern && pattern.test(text));
76
52
  }
77
-
78
- /**
79
- * Does this command line hand a string to something that will execute it?
80
- *
81
- * Quote masking is right for `echo "rm -rf /"` and wrong for
82
- * `bash -c "rm -rf ~"` — in the second the quoted text IS the payload. When an
83
- * interpreter is present we judge the raw line instead, so masking can never
84
- * downgrade a real destructive command.
85
- */
86
- // Includes the scripting interpreters (perl/ruby/awk/python/node/…) so that a
87
- // `python3 -c "import os; os.system('rm -rf ~')"` or `perl -e '...'` is judged on
88
- // the RAW line: the destructive payload lives in the quoted argument, and without
89
- // these an attacker could hide any command inside an interpreter string and have
90
- // it read as merely 'moderate' (auto-run in Mode C). Matching only forces the raw
91
- // line to be scanned — a benign `python3 script.py` still classifies as before.
92
53
  const INTERPRETER_INVOCATION = /(^|\s)(sh|bash|zsh|ksh|dash|fish|eval|xargs|ssh|sudo|env|nohup|command|perl|ruby|awk|gawk|mawk|tclsh|php|lua|luajit|python3|python|pwsh|powershell|node|deno|bun|rscript)(\s|$)/i;
93
-
94
- /**
95
- * Files where a single appended line changes what the machine does next, or who
96
- * can log into it. Written out plainly and unencoded — this is Vision section 10
97
- * defence code and must stay auditable.
98
- */
99
- /**
100
- * Credential stores and key material.
101
- *
102
- * A user may deliberately select a workspace that contains credential material.
103
- * These paths are not silently trusted just because they sit below that root:
104
- * touching one is classified 'extreme' for supervised-mode approval and audit.
105
- * Mode C still applies the selected-workspace boundary and hard safety blocks.
106
- */
107
54
  const CREDENTIAL_PATHS = [
108
- /(^|\/)\.ssh(\/|$)/,
109
- /(^|\/)\.aws(\/|$)/,
110
- /(^|\/)\.gnupg(\/|$)/,
111
- /(^|\/)\.docker\/config\.json$/,
112
- /(^|\/)\.netrc$/,
113
- /(^|\/)\.npmrc$/,
114
- /(^|\/)\.kube(\/|$)/,
115
- /(^|\/)Library\/Keychains(\/|$)/i,
116
- // Causyne's own vault: config.json holds the encrypted provider key and
117
- // .vault_key is the key that decrypts it.
118
- /(^|\/)\.causyne(\/|$)/
55
+ /(^|\/)\.ssh(\/|$)/,
56
+ /(^|\/)\.aws(\/|$)/,
57
+ /(^|\/)\.gnupg(\/|$)/,
58
+ /(^|\/)\.docker\/config\.json$/,
59
+ /(^|\/)\.netrc$/,
60
+ /(^|\/)\.npmrc$/,
61
+ /(^|\/)\.kube(\/|$)/,
62
+ /(^|\/)Library\/Keychains(\/|$)/i,
63
+ /(^|\/)\.causyne(\/|$)/,
64
+ /(^|\/)\.envrc$/i,
65
+ /(^|\/)\.git-credentials$/i,
66
+ /(^|\/)\.pypirc$/i,
67
+ /(^|\/)\.pgpass$/i,
68
+ /(^|\/)\.my\.cnf$/i
119
69
  ];
120
-
121
70
  export function isCredentialPath(targetPath) {
122
- if (typeof targetPath !== 'string' || targetPath.length === 0) return false;
123
- const normalized = targetPath.replace(/\\/g, '/');
124
- return CREDENTIAL_PATHS.some(pattern => pattern.test(normalized));
71
+ if (typeof targetPath !== 'string' || targetPath.length === 0 || targetPath.includes('\0'))
72
+ return false;
73
+ const normalized = targetPath.replace(/\\/g, '/');
74
+ return CREDENTIAL_PATHS.some(pattern => pattern.test(normalized)) || isExtendedCredentialPath(normalized);
125
75
  }
126
-
127
76
  const SENSITIVE_WRITE_TARGETS = [
128
- // Shell startup files: an appended line runs on the user's next shell.
129
- /(^|\/)\.(bashrc|bash_profile|bash_login|profile|zshrc|zprofile|zshenv|zlogin)$/,
130
- /(^|\/)\.config\/fish\/config\.fish$/,
131
- // Remote session routing profiles and authentication credentials.
132
- /(^|\/)\.ssh\//,
133
- // Scheduled execution.
134
- /(^|\/)(crontab|cron\.d)(\/|$)/,
135
- /\/etc\//,
136
- // Causyne's own state: config.json holds the encrypted API key and .vault_key
137
- // is the key that decrypts it.
138
- /(^|\/)\.causyne\//
77
+ /(^|\/)\.(bashrc|bash_profile|bash_login|profile|zshrc|zprofile|zshenv|zlogin)$/,
78
+ /(^|\/)\.config\/fish\/config\.fish$/,
79
+ /(^|\/)\.ssh\//,
80
+ /(^|\/)\.aws\//,
81
+ /(^|\/)\.kube\//,
82
+ /(^|\/)\.gnupg\//,
83
+ /(^|\/)\.docker\/config\.json$/,
84
+ /(^|\/)\.(npmrc|netrc|git-credentials|pypirc|envrc)$/,
85
+ /(^|\/)\.git\/(hooks(\/|$)|config$)/,
86
+ /(^|\/)(crontab|cron\.d)(\/|$)/,
87
+ /\/etc\//,
88
+ /(^|\/)\.causyne\//
139
89
  ];
140
-
141
- /**
142
- * Extract the file targets a command line redirects into.
143
- *
144
- * Context-aware per rule ZM-09: `2>&1` and `>&2` are descriptor duplications,
145
- * not files, and must not be reported as write targets — a guard that fires on
146
- * those would be disabled within a day.
147
- */
148
90
  function redirectionTargets(maskedCommand) {
149
- const targets = [];
150
- const pattern = /(?:^|[^0-9&>])>>?\s*([^\s;|&<>]+)/g;
151
- let match;
152
- while ((match = pattern.exec(maskedCommand)) !== null) {
153
- const target = match[1];
154
- if (!target || target.startsWith('&')) continue;
155
- targets.push(target);
156
- }
157
- return targets;
91
+ const targets = [];
92
+ const pattern = /(?:^|[^0-9&>])>>?\s*([^\s;|&<>]+)/g;
93
+ let match;
94
+ while ((match = pattern.exec(maskedCommand)) !== null) {
95
+ const target = match[1];
96
+ if (!target || target.startsWith('&'))
97
+ continue;
98
+ targets.push(target);
99
+ }
100
+ return targets;
158
101
  }
159
-
160
102
  function redirectsIntoSensitiveTarget(maskedCommand) {
161
- for (const target of redirectionTargets(maskedCommand)) {
162
- const normalizedTarget = target.replace(/^~/, '/home/user');
163
- for (const pattern of SENSITIVE_WRITE_TARGETS) {
164
- if (pattern.test(normalizedTarget)) return true;
103
+ for (const target of redirectionTargets(maskedCommand)) {
104
+ if (isSensitiveWriteTarget(target))
105
+ return true;
106
+ const normalizedTarget = target.replace(/^~/, '/home/user');
107
+ for (const pattern of SENSITIVE_WRITE_TARGETS) {
108
+ if (pattern.test(normalizedTarget))
109
+ return true;
110
+ }
165
111
  }
166
- }
167
- return false;
112
+ return false;
168
113
  }
169
-
170
114
  export class Sandbox {
171
- constructor({ workspaceRoot = process.cwd() } = {}) {
172
- this.config = loadConfig();
173
-
174
- // The launch directory is the workspace. A previous default advertised
175
- // Desktop, Documents, Downloads, ~/Causyne and the whole home directory as
176
- // equally valid roots. That made the model drift into the agent's own source
177
- // even when the user launched it from another project, while also making the
178
- // sandbox effectively home-wide. Explicit runtime grants can still use
179
- // updateWorkspacePaths(), but stale config never overrides the folder the
180
- // user selected for this invocation.
181
- this.workspacePaths = [path.resolve(workspaceRoot)];
182
-
183
- // Developer emulator mode (hardened, secret-gated — see devMode.js) grants
184
- // full local access for agent development on a Fast-tier emulator. It cannot
185
- // be triggered by a bare env flag in the published package.
186
- const devMode = isDevEmulator(this.config);
187
- this.grantAllAccess = devMode ? true : (this.config.grantAllAccess || false);
188
- this.allowedTools = devMode ? ['*'] : (this.config.allowedTools || ['*']);
189
- this.deniedTools = new Set(
190
- (devMode ? [] : (this.config.deniedTools || []))
191
- .map((name) => String(name).replace(/\./g, '_'))
192
- );
193
- }
194
-
195
-
196
- updateWorkspacePaths(newPaths) {
197
- if (Array.isArray(newPaths) && newPaths.length > 0) {
198
- // Validate: reject any system-critical paths
199
- const BLOCKED_ROOTS = ['/etc', '/usr', '/bin', '/sbin', '/System', '/var', '/private', '/Library'];
200
- const safePaths = newPaths.filter(p => {
201
- const resolved = path.resolve(p);
202
- return !BLOCKED_ROOTS.some(blocked => resolved.startsWith(blocked));
203
- });
204
-
205
- if (safePaths.length > 0) {
206
- this.workspacePaths = safePaths;
207
- return { success: true, paths: this.workspacePaths };
208
- }
209
- }
210
- return { success: false, reason: 'Invalid or blocked paths provided' };
211
- }
212
-
213
- // V5: Add a single workspace path
214
- addWorkspacePath(newPath) {
215
- const resolved = path.resolve(newPath);
216
- if (!this.workspacePaths.includes(resolved)) {
217
- this.workspacePaths.push(resolved);
218
- }
219
- return this.workspacePaths;
220
- }
221
-
222
- validate(toolName, args) {
223
- // 1. Tool availability check
224
- const canonicalToolName = String(toolName || '').replace(/\./g, '_');
225
- if (this.deniedTools.has(canonicalToolName)) {
226
- return { allowed: false, reason: `Tool ${toolName} is denied by local policy`, risk: 'forbidden' };
227
- }
228
- if (!this.allowedTools.includes('*') && !this.allowedTools.includes(toolName)) {
229
- return { allowed: false, reason: `Tool ${toolName} not allowed on current tier`, risk: 'forbidden' };
230
- }
231
-
232
- // 2. Path scoping.
233
- // Tools do not agree on what to call their path argument: MultiEdit uses
234
- // file_path, the Blender/Godot automators use filepath and directory, the
235
- // media tools use outputPath. Checking only `path` let all of those write
236
- // outside the workspace unchallenged.
237
- // fs_read_skill parameters (`skill_id`, `file_path`) identify bundled or
238
- // user-skill resources bounded strictly by skillResourceSafety.ts rather
239
- // than workspace filesystem paths.
240
- const safeArgs = args && typeof args === 'object' ? args : {};
241
- const pathsToCheck = [];
242
- if (canonicalToolName !== 'fs_read_skill') {
243
- const PATH_ARGUMENTS = [
244
- 'path', 'searchPath', 'cwd', 'source', 'destination',
245
- 'file_path', 'filePath', 'filepath', 'directory',
246
- 'targetFile', 'outputFile', 'outputPath'
247
- ];
248
- for (const field of PATH_ARGUMENTS) {
249
- if (safeArgs[field]) pathsToCheck.push(safeArgs[field]);
250
- }
251
- if (Array.isArray(safeArgs.target_directories)) {
252
- for (const dir of safeArgs.target_directories) {
253
- if (typeof dir === 'string' && dir.trim()) pathsToCheck.push(dir);
254
- }
255
- }
256
- }
257
-
258
- for (const p of pathsToCheck) {
259
- if (typeof p === 'string' && !this.isPathAllowed(p)) {
260
- return { allowed: false, reason: `Path outside allowed workspace: ${p}`, risk: 'dangerous' };
261
- }
262
- }
263
-
264
- // L4: classify credential material in an explicitly selected workspace as
265
- // extreme. The approval policy interprets that signal by autonomy mode.
266
- for (const p of pathsToCheck) {
267
- if (typeof p === 'string' && isCredentialPath(p)) {
268
- return { allowed: true, risk: 'extreme', reason: `Touches credential material: ${p}` };
269
- }
270
- }
271
-
272
- // 3. Command classification (for terminal tools).
273
- // terminal_persistent_shell runs arbitrary commands exactly like sysRun does
274
- // and must go through the same classifier — it previously bypassed it.
275
- if (toolName === 'sysRun' || toolName === 'sysRunBg' || toolName === 'terminal_persistent_shell') {
276
- const command = args.command || args.input;
277
- if (command) {
278
- const risk = this.classifyCommandRisk(command);
279
- if (risk === 'forbidden') {
280
- return { allowed: false, reason: 'Command is permanently blocked for safety', risk: 'forbidden' };
281
- }
282
- return { allowed: true, risk };
283
- }
284
- return { allowed: true, risk: 'moderate' };
285
- }
286
-
287
- if (toolName === 'gitOp') {
288
- const command = String(args.command || '');
289
- const risk = this.classifyCommandRisk(`git ${command}`);
290
- if (risk === 'forbidden') {
291
- return { allowed: false, reason: 'Command is permanently blocked for safety', risk: 'forbidden' };
292
- }
293
- return { allowed: true, risk: /\bbranch\s+-D\b/.test(command) ? 'dangerous' : risk };
294
- }
295
-
296
- // 4. SSRF protection (for web fetch)
297
- if (toolName === 'web_fetch' && args.url) {
298
- if (this.isInternalUrl(args.url)) {
299
- return { allowed: false, reason: 'Cannot access internal/local network URLs (SSRF Protection)', risk: 'forbidden' };
300
- }
301
- if (args.outputFile) {
302
- return { allowed: true, risk: 'extreme', reason: 'Downloads network content to disk' };
303
- }
115
+ config;
116
+ workspacePaths;
117
+ grantAllAccess;
118
+ allowedTools;
119
+ deniedTools;
120
+ constructor(options) {
121
+ const safeOptions = options && typeof options === 'object' ? options : {};
122
+ const candidateRoot = typeof safeOptions.workspaceRoot === 'string' && safeOptions.workspaceRoot.trim()
123
+ ? safeOptions.workspaceRoot.trim()
124
+ : process.cwd();
125
+ this.config = loadConfig();
126
+ this.workspacePaths = isBlockedWorkspaceRoot(candidateRoot) ? [] : [path.resolve(candidateRoot)];
127
+ const devMode = isDevEmulator(this.config);
128
+ this.grantAllAccess = devMode ? true : (this.config.grantAllAccess || false);
129
+ const rawAllowed = devMode ? ['*'] : (Array.isArray(this.config.allowedTools) ? this.config.allowedTools : ['*']);
130
+ this.allowedTools = rawAllowed.map((name) => String(name).replace(/\./g, '_'));
131
+ this.deniedTools = new Set((devMode ? [] : (this.config.deniedTools || []))
132
+ .map((name) => String(name).replace(/\./g, '_')));
304
133
  }
305
-
306
- if (toolName === 'browser_act') {
307
- return validateBrowserActSandbox(
308
- args,
309
- this.workspacePaths[0],
310
- url => this.isInternalUrl(url, { allowLoopback: true }),
311
- targetPath => this.isPathAllowed(targetPath)
312
- );
313
- }
314
-
315
- if (toolName === 'creative_apps') {
316
- const isReadOnly =
317
- args.action === 'status' ||
318
- args.action === 'verify_bridge' ||
319
- (args.action === 'live_bridge' && args.liveOperation === 'inspect_active');
320
- return { allowed: true, risk: isReadOnly ? 'safe' : 'dangerous' };
321
- }
322
-
323
- if (toolName === 'native_engine') {
324
- if (args.action === 'install') {
325
- return { allowed: true, risk: 'extreme', reason: 'Downloads and installs a native engine binary' };
326
- }
327
- const readOnly = ['status', 'catalog', 'describe', 'inspect', 'probe'];
328
- return { allowed: true, risk: readOnly.includes(args.action) ? 'safe' : 'dangerous' };
329
- }
330
-
331
- if (toolName === 'game_asset_fetch' && args.action === 'download_asset') {
332
- if (!args.url || this.isInternalUrl(args.url)) {
333
- return { allowed: false, reason: 'Cannot download from an internal or invalid URL', risk: 'forbidden' };
334
- }
335
- return { allowed: true, risk: 'extreme', reason: 'Downloads a third-party asset to disk' };
336
- }
337
-
338
- // Keep downloads classified as extreme for supervised modes and auditing.
339
- // Mode C approval is decided separately by the TypeScript approval policy.
340
- if (toolName === 'manage_local_dependencies') {
341
- // grant_capability installs third-party packages into the user's home
342
- // directory. Classification remains visible even when Mode C proceeds.
343
- const heavyActions = ['pipInst', 'grant_capability', 'grant_mcp_server'];
344
- if (heavyActions.includes(args.action)) {
345
- return { allowed: true, risk: 'extreme' };
346
- }
347
- return { allowed: true, risk: 'moderate' };
348
- }
349
-
350
- // Plugins are code extensions. Keep their risk classification visible to
351
- // supervised modes and audit logs; Mode C still uses workspace and hard
352
- // policy checks before execution.
353
- if (toolName === 'plugin_manager') {
354
- return ['create', 'enable'].includes(args.action)
355
- ? { allowed: true, risk: 'extreme', reason: 'Creates or trusts executable plugin code' }
356
- : { allowed: true, risk: 'safe' };
357
- }
358
- if (toolName.startsWith('plugin__')) {
359
- return { allowed: true, risk: 'extreme', reason: 'Executes an enabled local plugin' };
360
- }
361
-
362
- // Tools that overwrite or delete are inherently dangerous.
363
- // These comparisons used the dotted schema names (`fs.delete`, `proc.term`,
364
- // `fs.write`) while validate() is always called with the canonical wire name
365
- // (`fs_delete`, ...), so none of them ever matched: the Human-in-the-Loop
366
- // approval gate for destructive operations had never once fired.
367
- if (toolName === 'fs_delete') {
368
- // If wiping an entire directory tree, flag as extreme
369
- if (args.path && !args.path.includes('.')) {
370
- return { allowed: true, risk: 'extreme' };
371
- }
372
- return { allowed: true, risk: 'dangerous' };
373
- }
374
- if (toolName === 'proc_term') {
375
- return { allowed: true, risk: 'dangerous' };
376
- }
377
- // Desktop interaction reaches applications the user is signed into.
378
- // Keep the extreme risk signal for supervised modes and auditing; Mode C
379
- // follows the owner's autonomous approval policy after hard checks.
380
- if (toolName === 'desktop_act' || toolName === 'computer_use') {
381
- return { allowed: true, risk: 'extreme' };
382
- }
383
- if (toolName === 'ui_forge' || toolName === 'document_forge') {
384
- return { allowed: true, risk: 'safe' };
385
- }
386
- if (toolName === 'fs_write' || toolName === 'fs_move' || toolName === 'fs_edit' || toolName === 'MultiEdit') {
387
- return { allowed: true, risk: 'moderate' };
388
- }
389
-
390
- return { allowed: true, risk: 'safe' };
391
- }
392
-
393
- isPathAllowed(targetPath) {
394
- if (typeof targetPath !== 'string' || targetPath.length === 0) return false;
395
- const expand = (value) => {
396
- if (value === '~') return os.homedir();
397
- if (value.startsWith('~/') || value.startsWith('~\\')) {
398
- return path.join(os.homedir(), value.slice(2));
399
- }
400
- return value;
401
- };
402
- const workspaces = Array.isArray(this.workspacePaths)
403
- ? this.workspacePaths.filter(item => typeof item === 'string').map(expand) : [];
404
- const baseDir = workspaces[0] ? path.resolve(workspaces[0]) : process.cwd();
405
- const expandedTarget = expand(targetPath);
406
- const resolvedTarget = path.isAbsolute(expandedTarget)
407
- ? expandedTarget
408
- : path.resolve(baseDir, expandedTarget);
409
- // Resolve physical ancestors, including symlinks, before checking the scope.
410
- // Missing destination files remain possible inside a valid workspace.
411
- return isPhysicalPathAllowed(resolvedTarget, workspaces, this.grantAllAccess === true);
412
- }
413
-
414
- isInternalUrl(urlString, { allowLoopback = false } = {}) {
415
- try {
416
- const url = new URL(urlString);
417
- if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password) return true;
418
- const host = url.hostname.toLowerCase().replace(/^\[|\]$/g, '').replace(/\.$/, '');
419
- const isLoopback = host === 'localhost' || host.endsWith('.localhost') || /^127\.\d+\.\d+\.\d+$/.test(host) || host === '::1';
420
- if (allowLoopback && isLoopback) return false;
421
- if (host === 'localhost' || host.endsWith('.localhost') || host.endsWith('.local') || host.endsWith('.internal')) return true;
422
-
423
- // Block localhost, private IPs, cloud metadata
424
- const blockedRegex = /^(localhost|0\.\d+\.\d+\.\d+|127\.\d+\.\d+\.\d+|10\.\d+\.\d+\.\d+|100\.(6[4-9]|[7-9]\d|1[01]\d|12[0-7])\.\d+\.\d+|172\.(1[6-9]|2\d|3[01])\.\d+\.\d+|169\.254\.\d+\.\d+|192\.168\.\d+\.\d+|192\.0\.(0|2)\.\d+|192\.88\.99\.\d+|198\.(18|19)\.\d+\.\d+|198\.51\.100\.\d+|203\.0\.113\.\d+|(22[4-9]|23\d|24\d|25[0-5])\.\d+\.\d+\.\d+)$/;
425
- if (blockedRegex.test(host)) return true;
426
- if (host === 'metadata.google.internal') return true;
427
- if (isIP(host) === 6) {
428
- const normalized = host.split('%')[0];
429
- if (normalized === '::' || normalized === '::1' || /^(fc|fd|fe8|fe9|fea|feb|fec|fed|fee|fef|ff|2001:db8:|64:ff9b:)/.test(normalized)) return true;
430
- if (normalized.startsWith('::ffff:')) return true;
431
- }
432
-
433
- return false;
434
- } catch(e) {
435
- return true; // If URL is unparseable, block it to be safe
134
+ updateWorkspacePaths(newPaths) {
135
+ if (Array.isArray(newPaths) && newPaths.length > 0) {
136
+ const seen = new Set();
137
+ const safePaths = [];
138
+ for (const p of newPaths) {
139
+ if (typeof p !== 'string' || p.includes('\0') || !p.trim() || isBlockedWorkspaceRoot(p))
140
+ continue;
141
+ const resolved = path.resolve(p.trim());
142
+ if (!seen.has(resolved)) {
143
+ seen.add(resolved);
144
+ safePaths.push(resolved);
145
+ }
146
+ }
147
+ if (safePaths.length > 0) {
148
+ this.workspacePaths = safePaths;
149
+ return { success: true, paths: this.workspacePaths };
150
+ }
151
+ }
152
+ return { success: false, reason: 'Invalid or blocked paths provided' };
436
153
  }
437
- }
438
-
439
- classifyCommandRisk(command) {
440
- if (!command) return 'safe';
441
- const normalized = command.trim().toLowerCase();
442
-
443
- // FORBIDDEN — absolute blocklist (Technical + Ethical Safety Net Layer 3)
444
- const FORBIDDEN_PATTERNS = [
445
- /:\(\)\s*\{\s*:\|:&\s*\};/,
446
- /curl\s+.*\|\s*(sh|bash)/,
447
- /wget\s+.*\|\s*(sh|bash)/,
448
- // Process substitution — `bash <(curl …)` / `sh <(wget …)` fetch-and-run,
449
- // the pipe-to-shell trick's twin that the `| sh` patterns above miss.
450
- /<\(\s*(curl|wget)\b/,
451
- />\s*\/dev\/sda/,
452
- // Ethical Safety Gate: Offensive security attack tools & ransomware patterns
453
- /nmap\s+-s[STUVFN]/i,
454
- /sqlmap/i,
455
- /metasploit|msfconsole|msfvenom/i,
456
- /hydra\s+/i,
457
- /john\s+/i,
458
- /hashcat/i,
459
- /aircrack|airmon|aireplay/i,
460
- /ettercap|arpspoof|bettercap/i,
461
- /nikto/i,
462
- /xmrig|cpuminer|minerd/i,
463
- /ransomware|encrypt.*ransom/i
464
- ];
465
-
466
- // FORBIDDEN is matched against the WHOLE line, never against segments:
467
- // several of these patterns deliberately span shell separators (the fork
468
- // bomb contains ; and |, the pipe-to-shell patterns contain |), so
469
- // splitting first would stop them matching at all.
470
- for (const pattern of FORBIDDEN_PATTERNS) {
471
- if (pattern.test(normalized)) return 'forbidden';
154
+ addWorkspacePath(newPath) {
155
+ if (typeof newPath !== 'string' || newPath.includes('\0') || !newPath.trim() || isBlockedWorkspaceRoot(newPath)) {
156
+ return this.workspacePaths;
157
+ }
158
+ const resolved = path.resolve(newPath.trim());
159
+ if (!this.workspacePaths.includes(resolved)) {
160
+ this.workspacePaths.push(resolved);
161
+ }
162
+ return this.workspacePaths;
472
163
  }
473
-
474
- // Everything below judges what the shell will actually execute.
475
- const masked = maskQuotedSpans(normalized);
476
-
477
-
478
- // L3 (local-path audit): classify the redirection target, not just the verb.
479
- // Tool argument validation enforces boundaries on named arguments, but
480
- // shell redirection targets appended via operators (>> or >) require independent
481
- // audit. Writing into sensitive paths (such as user startup profiles, remote
482
- // authentication directories, or agent configuration stores) must always escalate
483
- // to extreme classification regardless of which command performs the redirection.
484
- if (redirectsIntoSensitiveTarget(masked)) return 'extreme';
485
- const executesQuotedText = INTERPRETER_INVOCATION.test(masked);
486
- const destructiveScanTarget = executesQuotedText ? normalized : masked;
487
-
488
-
489
- const EXTREME_PATTERNS = [
490
- /rm\s+(-rf|-fr)\s+[\/~]/,
491
- /rm\s+(-rf|-fr)\s+\*/,
492
- /mkfs/,
493
- /dd\s+if=/,
494
- /shutdown|reboot|init\s+[06]/,
495
- /passwd|useradd|userdel/,
496
- /iptables|ufw\s+delete/,
497
- /format\s+[a-z]:/i,
498
- /diskpart/i
499
- ];
500
-
501
- for (const pattern of EXTREME_PATTERNS) {
502
- if (pattern.test(destructiveScanTarget)) return 'extreme';
164
+ validate(toolName, args) {
165
+ const canonicalToolName = String(toolName || '').replace(/\./g, '_');
166
+ if (this.deniedTools.has(canonicalToolName)) {
167
+ return { allowed: false, reason: `Tool ${toolName} is denied by local policy`, risk: 'forbidden' };
168
+ }
169
+ if (!this.allowedTools.includes('*') && !this.allowedTools.includes(canonicalToolName)) {
170
+ return { allowed: false, reason: `Tool ${toolName} not allowed on current tier`, risk: 'forbidden' };
171
+ }
172
+ const safeArgs = args && typeof args === 'object' ? args : {};
173
+ const pathsToCheck = [];
174
+ if (canonicalToolName !== 'fs_read_skill') {
175
+ const PATH_ARGUMENTS = [
176
+ 'path', 'searchPath', 'cwd', 'workdir', 'dir', 'source', 'destination',
177
+ 'file_path', 'filePath', 'filepath', 'directory', 'inputPath', 'targetPath',
178
+ 'targetFile', 'outputFile', 'outputPath', 'outFile', 'outputDir', 'previewFile'
179
+ ];
180
+ for (const field of PATH_ARGUMENTS) {
181
+ if (safeArgs[field])
182
+ pathsToCheck.push(safeArgs[field]);
183
+ }
184
+ if (Array.isArray(safeArgs.target_directories)) {
185
+ for (const dir of safeArgs.target_directories) {
186
+ if (typeof dir === 'string' && dir.trim())
187
+ pathsToCheck.push(dir);
188
+ }
189
+ }
190
+ if (Array.isArray(safeArgs.files)) {
191
+ for (const entry of safeArgs.files) {
192
+ if (typeof entry === 'string' && entry.trim())
193
+ pathsToCheck.push(entry);
194
+ }
195
+ }
196
+ }
197
+ for (const p of pathsToCheck) {
198
+ if (typeof p === 'string' && !this.isPathAllowed(p)) {
199
+ return { allowed: false, reason: `Path outside allowed workspace: ${p}`, risk: 'dangerous' };
200
+ }
201
+ }
202
+ const baseWorkspace = this.workspacePaths[0] || process.cwd();
203
+ let credentialPathHit = null;
204
+ for (const p of pathsToCheck) {
205
+ if (typeof p !== 'string')
206
+ continue;
207
+ if (isCredentialPath(p)) {
208
+ credentialPathHit = p;
209
+ break;
210
+ }
211
+ const expanded = p === '~'
212
+ ? os.homedir()
213
+ : (p.startsWith('~/') || p.startsWith('~\\') ? path.join(os.homedir(), p.slice(2)) : p);
214
+ const resolvedCandidate = path.isAbsolute(expanded) ? expanded : path.resolve(baseWorkspace, expanded);
215
+ const real = physicalPath(resolvedCandidate);
216
+ if (real && isCredentialPath(real)) {
217
+ credentialPathHit = p;
218
+ break;
219
+ }
220
+ }
221
+ const withCredentialEscalation = (verdict) => {
222
+ if (!verdict.allowed || !credentialPathHit)
223
+ return verdict;
224
+ return {
225
+ allowed: true,
226
+ risk: 'extreme',
227
+ reason: verdict.reason
228
+ ? `${verdict.reason} (touches credential material: ${credentialPathHit})`
229
+ : `Touches credential material: ${credentialPathHit}`
230
+ };
231
+ };
232
+ if (canonicalToolName === 'sysRun' || canonicalToolName === 'sysRunBg' || canonicalToolName === 'terminal_persistent_shell') {
233
+ const command = safeArgs.command || safeArgs.input || safeArgs.cmd;
234
+ if (command) {
235
+ const risk = this.classifyCommandRisk(command);
236
+ if (risk === 'forbidden') {
237
+ return { allowed: false, reason: 'Command is permanently blocked for safety', risk: 'forbidden' };
238
+ }
239
+ return withCredentialEscalation({ allowed: true, risk });
240
+ }
241
+ return withCredentialEscalation({ allowed: true, risk: 'moderate' });
242
+ }
243
+ if (canonicalToolName === 'gitOp') {
244
+ const command = String(safeArgs.command ?? safeArgs.action ?? '');
245
+ const risk = this.classifyCommandRisk(`git ${command}`);
246
+ if (risk === 'forbidden') {
247
+ return { allowed: false, reason: 'Command is permanently blocked for safety', risk: 'forbidden' };
248
+ }
249
+ const destructiveGit = /\b(?:branch\s+-D|clean\s+-[a-zA-Z]*f|reset\s+--hard|push\s+(?:--force|-f)\b)/.test(command);
250
+ return withCredentialEscalation({
251
+ allowed: true,
252
+ risk: risk === 'extreme' ? 'extreme' : (destructiveGit ? 'dangerous' : risk)
253
+ });
254
+ }
255
+ if (canonicalToolName === 'web_fetch' && safeArgs.url) {
256
+ if (this.isInternalUrl(safeArgs.url)) {
257
+ return { allowed: false, reason: 'Cannot access internal/local network URLs (SSRF Protection)', risk: 'forbidden' };
258
+ }
259
+ if (safeArgs.outputFile) {
260
+ return withCredentialEscalation({ allowed: true, risk: 'extreme', reason: 'Downloads network content to disk' });
261
+ }
262
+ }
263
+ if (canonicalToolName === 'browser_act') {
264
+ return withCredentialEscalation(validateBrowserActSandbox(safeArgs, this.workspacePaths[0] || process.cwd(), url => this.isInternalUrl(url, { allowLoopback: true }), targetPath => this.isPathAllowed(targetPath)));
265
+ }
266
+ if (canonicalToolName === 'creative_apps') {
267
+ const isReadOnly = safeArgs.action === 'status' ||
268
+ safeArgs.action === 'verify_bridge' ||
269
+ (safeArgs.action === 'live_bridge' && safeArgs.liveOperation === 'inspect_active');
270
+ return withCredentialEscalation({ allowed: true, risk: isReadOnly ? 'safe' : 'dangerous' });
271
+ }
272
+ if (canonicalToolName === 'native_engine') {
273
+ if (safeArgs.action === 'install') {
274
+ return withCredentialEscalation({ allowed: true, risk: 'extreme', reason: 'Downloads and installs a native engine binary' });
275
+ }
276
+ const readOnly = ['status', 'catalog', 'describe', 'inspect', 'probe'];
277
+ return withCredentialEscalation({ allowed: true, risk: readOnly.includes(String(safeArgs.action ?? '')) ? 'safe' : 'dangerous' });
278
+ }
279
+ if (canonicalToolName === 'game_asset_fetch' && safeArgs.action === 'download_asset') {
280
+ if (!safeArgs.url || this.isInternalUrl(safeArgs.url)) {
281
+ return { allowed: false, reason: 'Cannot download from an internal or invalid URL', risk: 'forbidden' };
282
+ }
283
+ return withCredentialEscalation({ allowed: true, risk: 'extreme', reason: 'Downloads a third-party asset to disk' });
284
+ }
285
+ if (canonicalToolName === 'manage_local_dependencies') {
286
+ const heavyActions = ['pipInst', 'grant_capability', 'grant_mcp_server'];
287
+ if (heavyActions.includes(String(safeArgs.action ?? ''))) {
288
+ return withCredentialEscalation({ allowed: true, risk: 'extreme' });
289
+ }
290
+ return withCredentialEscalation({ allowed: true, risk: 'moderate' });
291
+ }
292
+ if (canonicalToolName === 'plugin_manager') {
293
+ return withCredentialEscalation(['create', 'enable'].includes(String(safeArgs.action ?? ''))
294
+ ? { allowed: true, risk: 'extreme', reason: 'Creates or trusts executable plugin code' }
295
+ : { allowed: true, risk: 'safe' });
296
+ }
297
+ if (canonicalToolName.startsWith('plugin__')) {
298
+ return withCredentialEscalation({ allowed: true, risk: 'extreme', reason: 'Executes an enabled local plugin' });
299
+ }
300
+ if (canonicalToolName === 'fs_delete') {
301
+ if (typeof safeArgs.path === 'string' && safeArgs.path.trim()) {
302
+ const baseDir = this.workspacePaths[0] || process.cwd();
303
+ const candidate = path.isAbsolute(safeArgs.path)
304
+ ? safeArgs.path
305
+ : path.resolve(baseDir, safeArgs.path);
306
+ try {
307
+ if (fs.lstatSync(candidate).isDirectory()) {
308
+ return withCredentialEscalation({ allowed: true, risk: 'extreme' });
309
+ }
310
+ }
311
+ catch {
312
+ if (!path.basename(safeArgs.path).includes('.')) {
313
+ return withCredentialEscalation({ allowed: true, risk: 'extreme' });
314
+ }
315
+ }
316
+ }
317
+ return withCredentialEscalation({ allowed: true, risk: 'dangerous' });
318
+ }
319
+ if (canonicalToolName === 'proc_term') {
320
+ return withCredentialEscalation({ allowed: true, risk: 'dangerous' });
321
+ }
322
+ if (canonicalToolName === 'desktop_act' || canonicalToolName === 'computer_use') {
323
+ return withCredentialEscalation({ allowed: true, risk: 'extreme' });
324
+ }
325
+ if (canonicalToolName === 'ui_forge' || canonicalToolName === 'document_forge') {
326
+ return withCredentialEscalation({ allowed: true, risk: 'safe' });
327
+ }
328
+ if (canonicalToolName === 'fs_write' || canonicalToolName === 'fs_move' || canonicalToolName === 'fs_edit' || canonicalToolName === 'MultiEdit') {
329
+ return withCredentialEscalation({ allowed: true, risk: 'moderate' });
330
+ }
331
+ return withCredentialEscalation({ allowed: true, risk: 'safe' });
503
332
  }
504
-
505
- // DANGEROUS — requires approval in Mode B, auto-executes in Mode C
506
- const DANGEROUS_PREFIXES = [
507
- 'rm ', 'sudo ', 'su ', 'chmod ', 'chown ',
508
- 'apt ', 'apt-get ', 'brew ', 'yum ', 'dnf ',
509
- 'git reset', 'git push --force', 'git push -f', 'git rebase',
510
- 'kill ', 'pkill ', 'killall ',
511
- 'ssh ', 'scp ', 'rsync ',
512
- 'mv ', 'crontab ', 'systemctl ', 'service '
513
- ];
514
-
515
- // Prefix rules are per-segment: `cd x && rm -f y` must be judged on `rm`,
516
- // not on `cd`. Highest risk across all segments wins.
517
- const segments = splitShellSegments(masked);
518
-
519
- for (const segment of segments) {
520
- for (const prefix of DANGEROUS_PREFIXES) {
521
- if (segment.startsWith(prefix) && !isReadOnlyInvocation(segment)) return 'dangerous';
522
- }
333
+ isPathAllowed(targetPath) {
334
+ if (typeof targetPath !== 'string' || targetPath.trim().length === 0 || targetPath.includes('\0'))
335
+ return false;
336
+ const expand = (value) => {
337
+ if (value === '~')
338
+ return os.homedir();
339
+ if (value.startsWith('~/') || value.startsWith('~\\')) {
340
+ return path.join(os.homedir(), value.slice(2));
341
+ }
342
+ return value;
343
+ };
344
+ const workspaces = Array.isArray(this.workspacePaths)
345
+ ? this.workspacePaths.filter(item => typeof item === 'string').map(expand) : [];
346
+ const baseDir = workspaces[0] ? path.resolve(workspaces[0]) : process.cwd();
347
+ const expandedTarget = expand(targetPath);
348
+ const resolvedTarget = path.isAbsolute(expandedTarget)
349
+ ? expandedTarget
350
+ : path.resolve(baseDir, expandedTarget);
351
+ return isPhysicalPathAllowed(resolvedTarget, workspaces, this.grantAllAccess === true);
523
352
  }
524
-
525
- // DANGEROUS — pattern form, for commands whose risk is in a flag rather than
526
- // the leading word. `find … -exec/-delete` runs an arbitrary command against
527
- // (or removes) every match, so it is at least as risky as a bare `rm`.
528
- const DANGEROUS_PATTERNS = [
529
- /\bfind\b[\s\S]*\s-(exec|execdir|delete)\b/,
530
- ];
531
- for (const pattern of DANGEROUS_PATTERNS) {
532
- if (pattern.test(destructiveScanTarget)) return 'dangerous';
353
+ isInternalUrl(urlString, { allowLoopback = false } = {}) {
354
+ if (typeof urlString !== 'string' || !urlString.trim() || /[\r\n\0]/.test(urlString)) {
355
+ return true;
356
+ }
357
+ try {
358
+ const url = new URL(urlString.trim());
359
+ if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password)
360
+ return true;
361
+ const rawHost = url.hostname.toLowerCase().replace(/^\[|\]$/g, '').replace(/\.$/, '');
362
+ const host = rawHost.split('%')[0] || '';
363
+ if (!host)
364
+ return true;
365
+ const ipv6OnlyZerosAndOne = host.includes(':') && /^(?:0+:){0,7}0*1$/.test(host);
366
+ const ipv6AllZeros = host.includes(':') && /^(?:0*:)+0*$/.test(host);
367
+ const isLoopback = host === 'localhost'
368
+ || host.endsWith('.localhost')
369
+ || /^127\.\d+\.\d+\.\d+$/.test(host)
370
+ || host === '::1'
371
+ || ipv6OnlyZerosAndOne;
372
+ if (allowLoopback && isLoopback)
373
+ return false;
374
+ if (host === 'localhost' || host.endsWith('.localhost') || host.endsWith('.local') || host.endsWith('.internal'))
375
+ return true;
376
+ const blockedRegex = /^(localhost|0\.\d+\.\d+\.\d+|127\.\d+\.\d+\.\d+|10\.\d+\.\d+\.\d+|100\.(6[4-9]|[7-9]\d|1[01]\d|12[0-7])\.\d+\.\d+|172\.(1[6-9]|2\d|3[01])\.\d+\.\d+|169\.254\.\d+\.\d+|192\.168\.\d+\.\d+|192\.0\.(0|2)\.\d+|192\.88\.99\.\d+|198\.(18|19)\.\d+\.\d+|198\.51\.100\.\d+|203\.0\.113\.\d+|(22[4-9]|23\d|24\d|25[0-5])\.\d+\.\d+\.\d+)$/;
377
+ if (blockedRegex.test(host))
378
+ return true;
379
+ if (host === 'metadata.google.internal')
380
+ return true;
381
+ if (isIP(host) === 6) {
382
+ if (host === '::' || host === '::1' || ipv6AllZeros || ipv6OnlyZerosAndOne)
383
+ return true;
384
+ if (/^(fc|fd|fe8|fe9|fea|feb|fec|fed|fee|fef|ff|2001:db8:|64:ff9b:|100::)/.test(host))
385
+ return true;
386
+ if (host.startsWith('::ffff:') || host.startsWith('0:0:0:0:0:ffff:'))
387
+ return true;
388
+ }
389
+ return false;
390
+ }
391
+ catch {
392
+ return true;
393
+ }
533
394
  }
534
-
535
- // MODERATE — auto-execute + notify in Mode B
536
- const MODERATE_PREFIXES = [
537
- 'npm i', 'npm run', 'npx ', 'yarn ', 'pnpm ',
538
- 'pip install', 'pip uninstall', 'pip3 ',
539
- 'python', 'python3', 'node ', 'deno ', 'bun ',
540
- 'perl ', 'ruby ', 'awk ', 'gawk ', 'php ', 'lua ', 'tclsh ', 'rscript ',
541
- 'pwsh ', 'powershell ',
542
- 'git add', 'git commit', 'git push', 'git pull', 'git checkout',
543
- 'git merge', 'git branch', 'git tag',
544
- 'mkdir', 'touch', 'cp ',
545
- 'cargo ', 'go ', 'make', 'cmake', 'gcc', 'g++',
546
- 'docker ', 'docker-compose ', 'podman ',
547
- 'code ', 'open ', 'xdg-open ',
548
- 'curl ', 'wget '
549
- ];
550
-
551
- for (const segment of segments) {
552
- for (const prefix of MODERATE_PREFIXES) {
553
- if (segment.startsWith(prefix)) return 'moderate';
554
- }
395
+ classifyCommandRisk(command) {
396
+ if (!command || typeof command !== 'string')
397
+ return 'safe';
398
+ if (command.length > 200_000)
399
+ return 'extreme';
400
+ const normalized = command.trim().toLowerCase();
401
+ const FORBIDDEN_PATTERNS = [
402
+ /:\(\)\s*\{\s*:\|:&\s*\};/,
403
+ /<\(\s*(curl|wget)\b/,
404
+ />\s*\/dev\/sda/,
405
+ /nmap\s+-s[STUVFN]/i,
406
+ /sqlmap/i,
407
+ /metasploit|msfconsole|msfvenom/i,
408
+ /hydra\s+/i,
409
+ /john\s+/i,
410
+ /hashcat/i,
411
+ /aircrack|airmon|aireplay/i,
412
+ /ettercap|arpspoof|bettercap/i,
413
+ /nikto/i,
414
+ /xmrig|cpuminer|minerd/i
415
+ ];
416
+ const analyzed = analyzeShellCommand(command);
417
+ if (hasLinearPipeToShell(normalized) || hasRansomwareKeyword(normalized))
418
+ return 'forbidden';
419
+ for (const rawUnit of analyzed.allRawUnits) {
420
+ const lowerUnit = rawUnit.toLowerCase();
421
+ if (hasLinearPipeToShell(lowerUnit) || hasRansomwareKeyword(lowerUnit))
422
+ return 'forbidden';
423
+ }
424
+ for (const pattern of FORBIDDEN_PATTERNS) {
425
+ if (pattern.test(normalized))
426
+ return 'forbidden';
427
+ for (const rawUnit of analyzed.allRawUnits) {
428
+ if (pattern.test(rawUnit.toLowerCase()))
429
+ return 'forbidden';
430
+ }
431
+ }
432
+ if (isFetchAndExecPipeline(analyzed.normalizedPipelines))
433
+ return 'forbidden';
434
+ const masked = analyzed.maskedTopLevel;
435
+ if (redirectsIntoSensitiveTarget(masked) ||
436
+ analyzed.writeTargets.some(target => isSensitiveWriteTarget(target))) {
437
+ return 'extreme';
438
+ }
439
+ const executesQuotedText = analyzed.allMaskedUnits.some(unit => INTERPRETER_INVOCATION.test(unit));
440
+ const scanUnits = executesQuotedText
441
+ ? analyzed.allRawUnits.map(u => u.toLowerCase())
442
+ : analyzed.allMaskedUnits;
443
+ const EXTREME_PATTERNS = [
444
+ /rm\s+(-rf|-fr)\s+[\/~]/,
445
+ /rm\s+(-rf|-fr)\s+\*/,
446
+ /mkfs/,
447
+ /dd\s+if=/,
448
+ /shutdown|reboot|init\s+[06]/,
449
+ /passwd|useradd|userdel/,
450
+ /iptables|ufw\s+delete/,
451
+ /format\s+[a-z]:/i,
452
+ /diskpart/i
453
+ ];
454
+ for (const unit of scanUnits) {
455
+ for (const pattern of EXTREME_PATTERNS) {
456
+ if (pattern.test(unit))
457
+ return 'extreme';
458
+ }
459
+ }
460
+ for (const seg of analyzed.normalizedSegments) {
461
+ if (isExtremeRemovalSegment(seg))
462
+ return 'extreme';
463
+ }
464
+ for (const seg of analyzed.unwrappedRawSegments) {
465
+ if (isExtremeRemovalSegment(seg))
466
+ return 'extreme';
467
+ }
468
+ const DANGEROUS_PREFIXES = [
469
+ 'rm ', 'sudo ', 'su ', 'doas ', 'pkexec ', 'chmod ', 'chown ',
470
+ 'apt ', 'apt-get ', 'brew ', 'yum ', 'dnf ',
471
+ 'git reset', 'git push --force', 'git push -f', 'git rebase',
472
+ 'kill ', 'pkill ', 'killall ',
473
+ 'ssh ', 'scp ', 'rsync ',
474
+ 'mv ', 'crontab ', 'systemctl ', 'service '
475
+ ];
476
+ for (const seg of analyzed.normalizedSegments) {
477
+ if (seg.isReadOnlyLookup)
478
+ continue;
479
+ if (seg.executable === 'su')
480
+ return 'dangerous';
481
+ for (const prefix of DANGEROUS_PREFIXES) {
482
+ if (seg.normalized.startsWith(prefix) && !isReadOnlyInvocation(seg.normalized)) {
483
+ return 'dangerous';
484
+ }
485
+ }
486
+ }
487
+ for (const unit of scanUnits) {
488
+ if (hasDangerousFindAction(unit))
489
+ return 'dangerous';
490
+ }
491
+ const MODERATE_PREFIXES = [
492
+ 'npm i', 'npm run', 'npx ', 'yarn ', 'pnpm ',
493
+ 'pip install', 'pip uninstall', 'pip3 ',
494
+ 'python', 'python3', 'node ', 'deno ', 'bun ',
495
+ 'perl ', 'ruby ', 'awk ', 'gawk ', 'php ', 'lua ', 'tclsh ', 'rscript ',
496
+ 'pwsh ', 'powershell ',
497
+ 'git add', 'git commit', 'git push', 'git pull', 'git checkout',
498
+ 'git merge', 'git branch', 'git tag',
499
+ 'mkdir', 'touch', 'cp ',
500
+ 'cargo ', 'go ', 'make', 'cmake', 'gcc', 'g++',
501
+ 'docker ', 'docker-compose ', 'podman ',
502
+ 'code ', 'open ', 'xdg-open ',
503
+ 'curl ', 'wget '
504
+ ];
505
+ for (const seg of analyzed.normalizedSegments) {
506
+ if (seg.isReadOnlyLookup)
507
+ continue;
508
+ for (const prefix of MODERATE_PREFIXES) {
509
+ if (seg.normalized.startsWith(prefix))
510
+ return 'moderate';
511
+ }
512
+ }
513
+ return 'safe';
555
514
  }
556
-
557
- return 'safe';
558
- }
559
515
  }