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