@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
@@ -0,0 +1,513 @@
1
+ /**
2
+ * Causyne Agent — OS-Level Process Sandboxing Wrapper (Sector 2B)
3
+ *
4
+ * Provides kernel-enforced filesystem & network isolation around shell tool
5
+ * subprocesses when enabled via `CAUSYNE_OS_SANDBOX` or `config.osSandbox`:
6
+ * - macOS (`darwin`): Apple Seatbelt (`/usr/bin/sandbox-exec -p <SBPL>`)
7
+ * - Linux (`linux`): Bubblewrap (`bwrap`) mount/network namespaces
8
+ * - Windows / nested containers: honest capability reporting (`backend: 'none'`)
9
+ * with fail-closed enforcement when `strict` mode is explicitly requested.
10
+ *
11
+ * Complements application-level `Sandbox` classification and `sanitizeSubprocessEnv`
12
+ * without ever stripping or degrading peer ACP capabilities.
13
+ */
14
+ import { spawnSync } from 'node:child_process';
15
+ import fs from 'node:fs';
16
+ import os from 'node:os';
17
+ import path from 'node:path';
18
+ const SEATBELT_BIN = '/usr/bin/sandbox-exec';
19
+ const CREDENTIAL_SUBPATHS = [
20
+ '.ssh',
21
+ '.aws',
22
+ '.gnupg',
23
+ '.kube',
24
+ '.causyne',
25
+ '.netrc',
26
+ '.git-credentials',
27
+ '.pypirc',
28
+ 'Library/Keychains'
29
+ ];
30
+ const SHELL_PERSISTENCE_FILES = [
31
+ '.bashrc',
32
+ '.bash_profile',
33
+ '.bash_login',
34
+ '.profile',
35
+ '.zshrc',
36
+ '.zprofile',
37
+ '.zshenv',
38
+ '.zlogin',
39
+ '.config/fish/config.fish'
40
+ ];
41
+ const DEV_CACHE_SUBPATHS = [
42
+ '.npm',
43
+ '.cache',
44
+ '.cargo',
45
+ '.rustup',
46
+ '.gradle',
47
+ '.m2',
48
+ 'go/pkg',
49
+ 'Library/Caches'
50
+ ];
51
+ let cachedProbe = null;
52
+ /**
53
+ * Escapes a filesystem path for safe embedding in an Apple Seatbelt SBPL string.
54
+ * Rejects control characters and NUL bytes to prevent S-expression injection.
55
+ */
56
+ export function escapeSeatbeltPath(rawPath) {
57
+ if (typeof rawPath !== 'string' || rawPath.length === 0)
58
+ return null;
59
+ for (let i = 0; i < rawPath.length; i++) {
60
+ const code = rawPath.charCodeAt(i);
61
+ if (code < 0x20 || code === 0x7f)
62
+ return null;
63
+ }
64
+ return rawPath.replace(/\\/g, '\\\\').replace(/"/g, '\\"');
65
+ }
66
+ function resolveCanonicalPaths(rawPath) {
67
+ const resolved = path.resolve(rawPath);
68
+ const out = new Set();
69
+ try {
70
+ const real = fs.realpathSync.native(resolved);
71
+ out.add(real);
72
+ }
73
+ catch {
74
+ // Walk up to nearest existing ancestor so symlinked prefixes (e.g. /var -> /private/var) resolve
75
+ let current = resolved;
76
+ const tail = [];
77
+ for (let depth = 0; depth < 64; depth++) {
78
+ const parent = path.dirname(current);
79
+ if (parent === current)
80
+ break;
81
+ tail.unshift(path.basename(current));
82
+ current = parent;
83
+ try {
84
+ const realAncestor = fs.realpathSync.native(current);
85
+ out.add(path.resolve(realAncestor, ...tail));
86
+ break;
87
+ }
88
+ catch {
89
+ continue;
90
+ }
91
+ }
92
+ }
93
+ out.add(resolved);
94
+ return [...out];
95
+ }
96
+ function isSameOrChildPath(candidate, parent) {
97
+ const rel = path.relative(parent, candidate);
98
+ return rel === '' || (rel !== '..' && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel));
99
+ }
100
+ function workspaceOverlapsPath(workspacePaths, targetPath) {
101
+ const targetVariants = resolveCanonicalPaths(targetPath);
102
+ for (const ws of workspacePaths) {
103
+ const wsVariants = resolveCanonicalPaths(ws);
104
+ for (const wv of wsVariants) {
105
+ for (const tv of targetVariants) {
106
+ if (isSameOrChildPath(wv, tv))
107
+ return true;
108
+ }
109
+ }
110
+ }
111
+ return false;
112
+ }
113
+ /**
114
+ * Parses `CAUSYNE_OS_SANDBOX` / `config.osSandbox` into an explicit OS sandbox mode.
115
+ * Defaults to `'off'` unless explicitly enabled so standard workflows never break unexpectedly.
116
+ */
117
+ export function resolveOsSandboxMode(env = process.env, configMode) {
118
+ const raw = (typeof env.CAUSYNE_OS_SANDBOX === 'string' && env.CAUSYNE_OS_SANDBOX.trim())
119
+ ? env.CAUSYNE_OS_SANDBOX.trim()
120
+ : (typeof configMode === 'string' ? configMode.trim() : '');
121
+ const lower = raw.toLowerCase();
122
+ const networkEnv = typeof env.CAUSYNE_OS_SANDBOX_NETWORK === 'string'
123
+ ? env.CAUSYNE_OS_SANDBOX_NETWORK.trim().toLowerCase()
124
+ : '';
125
+ const allowNetwork = !(networkEnv === '0' || networkEnv === 'false' || networkEnv === 'off' || networkEnv === 'deny');
126
+ if (!lower || lower === 'off' || lower === '0' || lower === 'false' || lower === 'disabled') {
127
+ return { mode: 'off', strict: false, allowNetwork };
128
+ }
129
+ if (lower === 'read-only' || lower === 'readonly' || lower === 'ro') {
130
+ return { mode: 'read-only', strict: false, allowNetwork };
131
+ }
132
+ if (lower === 'read-only-strict') {
133
+ return { mode: 'read-only', strict: true, allowNetwork };
134
+ }
135
+ if (lower === 'strict') {
136
+ return { mode: 'workspace-write', strict: true, allowNetwork };
137
+ }
138
+ if (lower === 'workspace-write' || lower === 'on' || lower === '1' || lower === 'true' || lower === 'auto') {
139
+ return { mode: 'workspace-write', strict: false, allowNetwork };
140
+ }
141
+ return { mode: 'off', strict: false, allowNetwork };
142
+ }
143
+ function findExecutableInPath(binaryName, env = process.env) {
144
+ const pathVal = env.PATH || '';
145
+ for (const dir of pathVal.split(path.delimiter)) {
146
+ if (!dir)
147
+ continue;
148
+ const candidate = path.join(dir, binaryName);
149
+ try {
150
+ fs.accessSync(candidate, fs.constants.X_OK);
151
+ if (fs.statSync(candidate).isFile())
152
+ return candidate;
153
+ }
154
+ catch {
155
+ continue;
156
+ }
157
+ }
158
+ return null;
159
+ }
160
+ /**
161
+ * Probes whether an OS-level kernel sandbox backend is installed and functional
162
+ * (not blocked by a nested container or restricted user namespace).
163
+ */
164
+ export function probeOsSandbox(options) {
165
+ const platform = options?.platform ?? process.platform;
166
+ if (!options?.bypassCache && cachedProbe && cachedProbe.platform === platform) {
167
+ return cachedProbe.result;
168
+ }
169
+ let result;
170
+ if (platform === 'darwin') {
171
+ if (!fs.existsSync(SEATBELT_BIN)) {
172
+ result = {
173
+ backend: 'none',
174
+ platform,
175
+ available: false,
176
+ binaryPath: null,
177
+ reason: 'macOS sandbox-exec binary not found.'
178
+ };
179
+ }
180
+ else {
181
+ const check = spawnSync(SEATBELT_BIN, ['-p', '(version 1)(allow default)', '/usr/bin/true'], {
182
+ stdio: 'ignore',
183
+ timeout: 3000
184
+ });
185
+ if (check.status === 0) {
186
+ result = {
187
+ backend: 'seatbelt',
188
+ platform,
189
+ available: true,
190
+ binaryPath: SEATBELT_BIN,
191
+ reason: 'macOS Seatbelt (sandbox-exec) active and verified.'
192
+ };
193
+ }
194
+ else {
195
+ result = {
196
+ backend: 'none',
197
+ platform,
198
+ available: false,
199
+ binaryPath: SEATBELT_BIN,
200
+ reason: 'macOS Seatbelt cannot apply in this environment (likely nested sandbox).'
201
+ };
202
+ }
203
+ }
204
+ }
205
+ else if (platform === 'linux') {
206
+ const bwrapPath = findExecutableInPath('bwrap');
207
+ if (!bwrapPath) {
208
+ result = {
209
+ backend: 'none',
210
+ platform,
211
+ available: false,
212
+ binaryPath: null,
213
+ reason: 'Linux bubblewrap (bwrap) is not installed.'
214
+ };
215
+ }
216
+ else {
217
+ const check = spawnSync(bwrapPath, ['--ro-bind', '/', '/', '--dev', '/dev', '--proc', '/proc', '/bin/true'], {
218
+ stdio: 'ignore',
219
+ timeout: 3000
220
+ });
221
+ if (check.status === 0) {
222
+ result = {
223
+ backend: 'bubblewrap',
224
+ platform,
225
+ available: true,
226
+ binaryPath: bwrapPath,
227
+ reason: 'Linux bubblewrap (bwrap) namespaces active and verified.'
228
+ };
229
+ }
230
+ else {
231
+ result = {
232
+ backend: 'none',
233
+ platform,
234
+ available: false,
235
+ binaryPath: bwrapPath,
236
+ reason: 'Linux bubblewrap (bwrap) unavailable (user namespaces disabled in container).'
237
+ };
238
+ }
239
+ }
240
+ }
241
+ else {
242
+ result = {
243
+ backend: 'none',
244
+ platform,
245
+ available: false,
246
+ binaryPath: null,
247
+ reason: `Kernel subprocess sandboxing is not implemented for platform "${platform}"; application sandbox and env isolation remain active.`
248
+ };
249
+ }
250
+ if (!options?.bypassCache) {
251
+ cachedProbe = { platform, result };
252
+ }
253
+ return result;
254
+ }
255
+ /**
256
+ * Generates an Apple Seatbelt SBPL profile for macOS `sandbox-exec`.
257
+ * Uses Seatbelt's last-match-wins semantics:
258
+ * 1. Allow default reads/exec of system libraries & toolchains.
259
+ * 2. Optionally deny remote outbound IP connections (`allowNetwork === false`).
260
+ * 3. Deny all `file-write*`, then allow only safe device nodes, workspace roots,
261
+ * temp dirs, and standard dev caches (in `workspace-write` mode).
262
+ * 4. Explicitly deny `file-write*` on shell startup profiles and credential vaults.
263
+ * 5. Explicitly deny `file-read*` on credential vaults (unless the user explicitly
264
+ * selected that directory as their workspace).
265
+ */
266
+ export function buildSeatbeltProfile(options) {
267
+ const mode = options.mode ?? 'workspace-write';
268
+ const homeDir = options.homeDir ?? os.homedir();
269
+ const tmpDir = options.tmpDir ?? os.tmpdir();
270
+ const configuredWorkspaces = (options.workspaceRoots ?? [])
271
+ .filter((entry) => typeof entry === 'string' && entry.trim().length > 0);
272
+ const workspaces = configuredWorkspaces.length > 0 ? configuredWorkspaces : [options.cwd];
273
+ const lines = [
274
+ '(version 1)',
275
+ '(allow default)'
276
+ ];
277
+ if (options.allowNetwork === false) {
278
+ lines.push('(deny network-outbound (remote ip))');
279
+ }
280
+ lines.push('(deny file-write*)');
281
+ // Always allow writing to standard harmless device sinks
282
+ const safeDeviceLiterals = [
283
+ '/dev/null',
284
+ '/dev/zero',
285
+ '/dev/tty',
286
+ '/dev/ptmx',
287
+ '/dev/dtracehelper',
288
+ '/dev/stdout',
289
+ '/dev/stderr'
290
+ ];
291
+ lines.push(`(allow file-write* ${safeDeviceLiterals.map(p => `(literal "${p}")`).join(' ')})`);
292
+ if (mode === 'workspace-write') {
293
+ const writableSubpaths = new Set();
294
+ const addWritable = (rawPath) => {
295
+ for (const variant of resolveCanonicalPaths(rawPath)) {
296
+ const escaped = escapeSeatbeltPath(variant);
297
+ if (escaped)
298
+ writableSubpaths.add(escaped);
299
+ }
300
+ };
301
+ for (const ws of workspaces) {
302
+ addWritable(ws);
303
+ }
304
+ if (options.includeTempDirs !== false) {
305
+ for (const t of ['/tmp', '/private/tmp', '/private/var/tmp', '/private/var/folders', tmpDir]) {
306
+ if (t)
307
+ addWritable(t);
308
+ }
309
+ }
310
+ if (options.allowDevCaches !== false && homeDir) {
311
+ for (const rel of DEV_CACHE_SUBPATHS) {
312
+ addWritable(path.join(homeDir, rel));
313
+ }
314
+ }
315
+ if (writableSubpaths.size > 0) {
316
+ const clauses = [...writableSubpaths].map(p => `(subpath "${p}")`).join(' ');
317
+ lines.push(`(allow file-write* ${clauses})`);
318
+ }
319
+ }
320
+ // Last-match-wins: shell startup persistence targets remain strictly unwritable
321
+ if (homeDir) {
322
+ const denyWriteLiterals = new Set();
323
+ for (const rel of SHELL_PERSISTENCE_FILES) {
324
+ const full = path.join(homeDir, rel);
325
+ for (const variant of resolveCanonicalPaths(full)) {
326
+ const escaped = escapeSeatbeltPath(variant);
327
+ if (escaped)
328
+ denyWriteLiterals.add(escaped);
329
+ }
330
+ }
331
+ if (denyWriteLiterals.size > 0) {
332
+ lines.push(`(deny file-write* ${[...denyWriteLiterals].map(p => `(literal "${p}")`).join(' ')})`);
333
+ }
334
+ }
335
+ // Last-match-wins: credential vaults denied for both read and write unless explicitly chosen as workspace
336
+ const denyCredSubpaths = new Set();
337
+ if (homeDir) {
338
+ for (const rel of CREDENTIAL_SUBPATHS) {
339
+ const full = path.join(homeDir, rel);
340
+ if (workspaceOverlapsPath(workspaces, full))
341
+ continue;
342
+ for (const variant of resolveCanonicalPaths(full)) {
343
+ const escaped = escapeSeatbeltPath(variant);
344
+ if (escaped)
345
+ denyCredSubpaths.add(escaped);
346
+ }
347
+ }
348
+ }
349
+ if (Array.isArray(options.extraDenyReadPaths)) {
350
+ for (const extra of options.extraDenyReadPaths) {
351
+ for (const variant of resolveCanonicalPaths(extra)) {
352
+ const escaped = escapeSeatbeltPath(variant);
353
+ if (escaped)
354
+ denyCredSubpaths.add(escaped);
355
+ }
356
+ }
357
+ }
358
+ if (denyCredSubpaths.size > 0) {
359
+ const clauses = [...denyCredSubpaths].map(p => `(subpath "${p}")`).join(' ');
360
+ lines.push(`(deny file-read* ${clauses})`);
361
+ lines.push(`(deny file-write* ${clauses})`);
362
+ }
363
+ return `${lines.join('\n')}\n`;
364
+ }
365
+ /**
366
+ * Generates shell-free argv for Linux `bwrap` (bubblewrap) isolation.
367
+ */
368
+ export function buildBubblewrapArgs(shell, shellArgs, options) {
369
+ const mode = options.mode ?? 'workspace-write';
370
+ const homeDir = options.homeDir ?? os.homedir();
371
+ const configuredWorkspaces = (options.workspaceRoots ?? [])
372
+ .filter((entry) => typeof entry === 'string' && entry.trim().length > 0);
373
+ const workspaces = configuredWorkspaces.length > 0 ? configuredWorkspaces : [options.cwd];
374
+ const args = [
375
+ '--die-with-parent',
376
+ '--ro-bind', '/', '/',
377
+ '--dev', '/dev',
378
+ '--proc', '/proc'
379
+ ];
380
+ if (options.includeTempDirs !== false) {
381
+ args.push('--tmpfs', '/tmp');
382
+ }
383
+ if (options.allowNetwork === false) {
384
+ args.push('--unshare-net');
385
+ }
386
+ if (mode === 'workspace-write') {
387
+ const bound = new Set();
388
+ const bindIfExists = (rawPath) => {
389
+ const resolved = path.resolve(rawPath);
390
+ if (bound.has(resolved))
391
+ return;
392
+ if (!fs.existsSync(resolved))
393
+ return;
394
+ bound.add(resolved);
395
+ args.push('--bind', resolved, resolved);
396
+ };
397
+ for (const ws of workspaces) {
398
+ bindIfExists(ws);
399
+ }
400
+ if (options.allowDevCaches !== false && homeDir) {
401
+ for (const rel of DEV_CACHE_SUBPATHS) {
402
+ bindIfExists(path.join(homeDir, rel));
403
+ }
404
+ }
405
+ }
406
+ else if (mode === 'read-only' && options.includeTempDirs !== false) {
407
+ const roBound = new Set();
408
+ const roBindTmpPath = (rawPath) => {
409
+ const resolved = path.resolve(rawPath);
410
+ if (roBound.has(resolved))
411
+ return;
412
+ if (!isSameOrChildPath(resolved, '/tmp'))
413
+ return;
414
+ if (!fs.existsSync(resolved))
415
+ return;
416
+ roBound.add(resolved);
417
+ args.push('--ro-bind', resolved, resolved);
418
+ };
419
+ for (const ws of workspaces) {
420
+ roBindTmpPath(ws);
421
+ }
422
+ roBindTmpPath(options.cwd);
423
+ }
424
+ // Mask existing credential vaults (directories & files) and extra deny paths unless inside selected workspace
425
+ const masked = new Set();
426
+ const maskTarget = (rawPath) => {
427
+ for (const variant of resolveCanonicalPaths(rawPath)) {
428
+ if (masked.has(variant))
429
+ continue;
430
+ try {
431
+ const stat = fs.statSync(variant);
432
+ if (stat.isDirectory()) {
433
+ masked.add(variant);
434
+ args.push('--tmpfs', variant);
435
+ }
436
+ else if (stat.isFile()) {
437
+ masked.add(variant);
438
+ args.push('--ro-bind', '/dev/null', variant);
439
+ }
440
+ }
441
+ catch {
442
+ continue;
443
+ }
444
+ }
445
+ };
446
+ if (homeDir) {
447
+ for (const rel of CREDENTIAL_SUBPATHS) {
448
+ const full = path.join(homeDir, rel);
449
+ if (workspaceOverlapsPath(workspaces, full))
450
+ continue;
451
+ maskTarget(full);
452
+ }
453
+ }
454
+ if (Array.isArray(options.extraDenyReadPaths)) {
455
+ for (const extra of options.extraDenyReadPaths) {
456
+ if (typeof extra === 'string' && extra.trim()) {
457
+ maskTarget(extra);
458
+ }
459
+ }
460
+ }
461
+ args.push('--chdir', path.resolve(options.cwd), '--', shell, ...shellArgs);
462
+ return args;
463
+ }
464
+ /**
465
+ * Wraps a `(shell, shellArgs)` invocation in an OS kernel sandbox when enabled.
466
+ */
467
+ export function wrapCommandWithOsSandbox(shell, shellArgs, options) {
468
+ const mode = options.mode ?? 'off';
469
+ if (mode === 'off') {
470
+ return {
471
+ command: shell,
472
+ args: [...shellArgs],
473
+ sandboxed: false,
474
+ backend: 'none',
475
+ mode: 'off'
476
+ };
477
+ }
478
+ const platform = options.platform ?? process.platform;
479
+ const backend = options.backendOverride
480
+ ?? (probeOsSandbox({ platform }).available ? probeOsSandbox({ platform }).backend : 'none');
481
+ if (backend === 'seatbelt') {
482
+ const profile = buildSeatbeltProfile({ ...options, mode });
483
+ return {
484
+ command: options.binaryPathOverride || SEATBELT_BIN,
485
+ args: ['-p', profile, '--', shell, ...shellArgs],
486
+ sandboxed: true,
487
+ backend: 'seatbelt',
488
+ mode,
489
+ profile
490
+ };
491
+ }
492
+ if (backend === 'bubblewrap') {
493
+ const bin = options.binaryPathOverride || probeOsSandbox({ platform }).binaryPath || 'bwrap';
494
+ return {
495
+ command: bin,
496
+ args: buildBubblewrapArgs(shell, shellArgs, { ...options, mode }),
497
+ sandboxed: true,
498
+ backend: 'bubblewrap',
499
+ mode
500
+ };
501
+ }
502
+ if (options.strict) {
503
+ const probe = probeOsSandbox({ platform });
504
+ throw new Error(`Strict OS sandbox requested (${mode}) but no kernel sandbox backend is available: ${probe.reason}`);
505
+ }
506
+ return {
507
+ command: shell,
508
+ args: [...shellArgs],
509
+ sandboxed: false,
510
+ backend: 'none',
511
+ mode
512
+ };
513
+ }