@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
@@ -15,6 +15,13 @@ import fs from 'node:fs';
15
15
  import os from 'node:os';
16
16
  import path from 'node:path';
17
17
  import { isLaunchOnlyPrompt, isServerLaunchCommand } from '../launchIntent.js';
18
+ import { sanitizeSubprocessEnv } from './subprocessEnv.js';
19
+ import {
20
+ resolveOsSandboxMode,
21
+ wrapCommandWithOsSandbox,
22
+ type OsSandboxMode,
23
+ type OsSandboxWrapOptions
24
+ } from './osSandbox.js';
18
25
 
19
26
  export interface SysRunArgs {
20
27
  command: string;
@@ -36,7 +43,14 @@ export interface SysRunResult {
36
43
  export interface SysRunContext {
37
44
  signal?: AbortSignal | undefined;
38
45
  skipCache?: boolean | undefined;
39
- parentLoop?: { currentTaskPrompt?: string; userPrompt?: string } | undefined;
46
+ osSandbox?: OsSandboxMode | Partial<OsSandboxWrapOptions> | undefined;
47
+ parentLoop?: {
48
+ currentTaskPrompt?: string;
49
+ userPrompt?: string;
50
+ workspaceRoot?: string;
51
+ config?: { osSandbox?: string };
52
+ sandbox?: { workspacePaths?: string[] };
53
+ } | undefined;
40
54
  }
41
55
 
42
56
  export interface SysRunBgArgs {
@@ -93,7 +107,7 @@ export const SEARCH_COMMAND_PATTERN = /(^|\s|\||&&|;)(grep|egrep|fgrep|diff|test
93
107
  * and language runtimes so ADB, emulator, and build tools function out-of-the-box.
94
108
  */
95
109
  export function getEnhancedEnv(baseEnv?: NodeJS.ProcessEnv): NodeJS.ProcessEnv {
96
- const env: NodeJS.ProcessEnv = { ...(baseEnv || process.env) };
110
+ const env: NodeJS.ProcessEnv = sanitizeSubprocessEnv(baseEnv || process.env);
97
111
 
98
112
  // 1. Discover ANDROID_HOME / ANDROID_SDK_ROOT across standard platform locations
99
113
  if (!env.ANDROID_HOME && !env.ANDROID_SDK_ROOT) {
@@ -101,7 +115,7 @@ export function getEnhancedEnv(baseEnv?: NodeJS.ProcessEnv): NodeJS.ProcessEnv {
101
115
  path.join(os.homedir(), 'Library', 'Android', 'sdk'), // macOS
102
116
  path.join(os.homedir(), 'Android', 'Sdk'), // Linux
103
117
  '/usr/lib/android-sdk', // Linux package
104
- path.join(process.env.LOCALAPPDATA || '', 'Android', 'Sdk') // Windows
118
+ ...(process.env.LOCALAPPDATA ? [path.join(process.env.LOCALAPPDATA, 'Android', 'Sdk')] : []) // Windows
105
119
  ];
106
120
  for (const dir of candidateDirs) {
107
121
  if (dir && fs.existsSync(dir)) {
@@ -235,9 +249,10 @@ export function isFinalCommandSearch(rawCommand: string): boolean {
235
249
  }
236
250
 
237
251
  const pipeParts = lastStmt.split('|');
238
- const finalCmd = pipeParts.at(-1)?.trim().replace(/["'\)\s]+$/, '') || '';
252
+ const rawFinalCmd = pipeParts.at(-1)?.trim().replace(/["'\)\s]+$/, '') || '';
253
+ const finalCmd = rawFinalCmd.replace(/^(?:adb\s+(?:-s\s+\S+\s+)?shell|ssh\s+\S+)\s+/i, '');
239
254
 
240
- return /(?:^|\s)(grep|egrep|fgrep|diff|test|which|where|cmp|pidof|pgrep|find)\b/.test(finalCmd);
255
+ return /^(?:[A-Za-z_][A-Za-z0-9_]*=\S*\s+)*(?:(?:\/(?:usr\/)?bin\/)?(?:grep|egrep|fgrep|diff|test|which|where|cmp|pidof|pgrep|find))(?:\s|$)/.test(finalCmd);
241
256
  }
242
257
 
243
258
  /**
@@ -283,12 +298,38 @@ interface CachedCommandResult {
283
298
  }
284
299
 
285
300
  const COMMAND_CACHE_TTL_MS = 60_000;
301
+ const MAX_CACHE_ENTRIES = 64;
286
302
  const commandCache = new Map<string, CachedCommandResult>();
287
303
 
304
+ function setCachedResult(key: string, entry: CachedCommandResult): void {
305
+ if (commandCache.size >= MAX_CACHE_ENTRIES && !commandCache.has(key)) {
306
+ const oldest = commandCache.keys().next().value;
307
+ if (oldest !== undefined) commandCache.delete(oldest);
308
+ }
309
+ commandCache.set(key, entry);
310
+ }
311
+
288
312
  export function clearSysRunCache(): void {
289
313
  commandCache.clear();
290
314
  }
291
315
 
316
+ function resolveSysCwd(rawCwd: string | undefined, context: SysRunContext): string {
317
+ const expand = (p: string): string => {
318
+ const trimmed = p.trim();
319
+ if (trimmed === '~') return os.homedir();
320
+ if (trimmed.startsWith('~/') || trimmed.startsWith('~\\')) {
321
+ return path.join(os.homedir(), trimmed.slice(2));
322
+ }
323
+ return trimmed;
324
+ };
325
+ const fallbackBase = context?.parentLoop?.workspaceRoot?.trim()
326
+ ? path.resolve(expand(context.parentLoop.workspaceRoot))
327
+ : process.cwd();
328
+ if (!rawCwd || !rawCwd.trim()) return fallbackBase;
329
+ const expanded = expand(rawCwd);
330
+ return path.isAbsolute(expanded) ? path.resolve(expanded) : path.resolve(fallbackBase, expanded);
331
+ }
332
+
292
333
  export const sysRun = {
293
334
  schema: {
294
335
  name: 'sysRun',
@@ -307,7 +348,7 @@ export const sysRun = {
307
348
 
308
349
  async execute(args: SysRunArgs, context: SysRunContext = {}): Promise<SysRunResult> {
309
350
  const rawCommand = (args?.command || '').trim();
310
- const cwd = args?.cwd ? args.cwd.replace(/^~\//, os.homedir() + '/') : process.cwd();
351
+ const cwd = resolveSysCwd(args?.cwd, context);
311
352
  let timeoutMs = 60000;
312
353
  const rawTimeout = (args as unknown as Record<string, unknown>)?.timeout;
313
354
  if (typeof rawTimeout === 'number' && Number.isFinite(rawTimeout) && rawTimeout > 0) {
@@ -323,8 +364,10 @@ export const sysRun = {
323
364
  else timeoutMs = val <= 600 ? Math.round(val * 1000) : Math.round(val);
324
365
  }
325
366
  }
326
- if (timeoutMs < 1000) {
367
+ if (!Number.isFinite(timeoutMs) || timeoutMs < 1000) {
327
368
  timeoutMs = 1000;
369
+ } else if (timeoutMs > 2_147_483_647) {
370
+ timeoutMs = 2_147_483_647;
328
371
  }
329
372
  const signal = context.signal;
330
373
 
@@ -368,11 +411,35 @@ export const sysRun = {
368
411
 
369
412
  let child: ReturnType<typeof spawn>;
370
413
  try {
371
- child = spawn(shell, shellArgs, {
414
+ const resolvedMode = resolveOsSandboxMode(process.env, context.parentLoop?.config?.osSandbox);
415
+ const explicitSandbox = context.osSandbox;
416
+ const wrapOptions: OsSandboxWrapOptions = typeof explicitSandbox === 'string'
417
+ ? {
418
+ mode: explicitSandbox,
419
+ strict: resolvedMode.strict,
420
+ allowNetwork: resolvedMode.allowNetwork,
421
+ cwd,
422
+ workspaceRoots: context.parentLoop?.sandbox?.workspacePaths ?? [cwd]
423
+ }
424
+ : {
425
+ mode: explicitSandbox?.mode ?? resolvedMode.mode,
426
+ strict: explicitSandbox?.strict ?? resolvedMode.strict,
427
+ allowNetwork: explicitSandbox?.allowNetwork ?? resolvedMode.allowNetwork,
428
+ cwd,
429
+ workspaceRoots: explicitSandbox?.workspaceRoots ?? context.parentLoop?.sandbox?.workspacePaths ?? [cwd],
430
+ ...(explicitSandbox?.allowDevCaches !== undefined ? { allowDevCaches: explicitSandbox.allowDevCaches } : {}),
431
+ ...(explicitSandbox?.includeTempDirs !== undefined ? { includeTempDirs: explicitSandbox.includeTempDirs } : {}),
432
+ ...(explicitSandbox?.extraDenyReadPaths ? { extraDenyReadPaths: explicitSandbox.extraDenyReadPaths } : {}),
433
+ ...(explicitSandbox?.homeDir ? { homeDir: explicitSandbox.homeDir } : {}),
434
+ ...(explicitSandbox?.tmpDir ? { tmpDir: explicitSandbox.tmpDir } : {})
435
+ };
436
+
437
+ const wrapped = wrapCommandWithOsSandbox(shell, shellArgs, wrapOptions);
438
+ child = spawn(wrapped.command, wrapped.args, {
372
439
  cwd,
373
440
  signal,
374
441
  env: getEnhancedEnv(),
375
- ...(os.platform() === 'win32' ? { windowsVerbatimArguments: true } : {})
442
+ ...(os.platform() === 'win32' && !wrapped.sandboxed ? { windowsVerbatimArguments: true } : {})
376
443
  });
377
444
  } catch (err: unknown) {
378
445
  const errorMsg = err instanceof Error ? err.message : String(err);
@@ -390,6 +457,15 @@ export const sysRun = {
390
457
  let outputBuffer = '';
391
458
  let isDetached = false;
392
459
 
460
+ const detachChild = (): void => {
461
+ child.stdout?.removeAllListeners('data');
462
+ child.stderr?.removeAllListeners('data');
463
+ child.stdout?.destroy();
464
+ child.stderr?.destroy();
465
+ child.stdin?.destroy();
466
+ child.unref();
467
+ };
468
+
393
469
  const checkServerDetach = (): void => {
394
470
  if (isDetached) return;
395
471
  if (isPersistentServerCommand(rawCommand)) {
@@ -397,7 +473,7 @@ export const sysRun = {
397
473
  isDetached = true;
398
474
  if (timeoutId) clearTimeout(timeoutId);
399
475
  if (serverGraceTimer) clearTimeout(serverGraceTimer);
400
- child.unref();
476
+ detachChild();
401
477
  resolve({
402
478
  success: true,
403
479
  output: cleanSubprocessOutput(outputBuffer),
@@ -440,7 +516,7 @@ export const sysRun = {
440
516
  if (!isDetached && child.exitCode === null) {
441
517
  isDetached = true;
442
518
  if (timeoutId) clearTimeout(timeoutId);
443
- child.unref();
519
+ detachChild();
444
520
  resolve({
445
521
  success: true,
446
522
  output: cleanSubprocessOutput(outputBuffer) || 'Server process started and running in background.',
@@ -451,13 +527,21 @@ export const sysRun = {
451
527
  }, 2500);
452
528
  }
453
529
 
530
+ let settled = false;
531
+ const finish = (result: SysRunResult): void => {
532
+ if (settled) return;
533
+ settled = true;
534
+ if (timeoutId) clearTimeout(timeoutId);
535
+ if (serverGraceTimer) clearTimeout(serverGraceTimer);
536
+ resolve(result);
537
+ };
538
+
454
539
  let timeoutId: NodeJS.Timeout | undefined;
455
540
  if (timeoutMs > 0) {
456
541
  timeoutId = setTimeout(() => {
457
- if (isDetached) return;
458
- if (serverGraceTimer) clearTimeout(serverGraceTimer);
542
+ if (isDetached || settled) return;
459
543
  child.kill('SIGKILL');
460
- resolve({
544
+ finish({
461
545
  success: false,
462
546
  output: cleanSubprocessOutput(outputBuffer),
463
547
  error: `Process timed out after ${timeoutMs}ms`,
@@ -467,10 +551,8 @@ export const sysRun = {
467
551
  }
468
552
 
469
553
  child.on('error', (err: Error) => {
470
- if (isDetached) return;
471
- if (timeoutId) clearTimeout(timeoutId);
472
- if (serverGraceTimer) clearTimeout(serverGraceTimer);
473
- resolve({
554
+ if (isDetached || settled) return;
555
+ finish({
474
556
  success: false,
475
557
  output: cleanSubprocessOutput(outputBuffer),
476
558
  error: err.message,
@@ -479,23 +561,21 @@ export const sysRun = {
479
561
  });
480
562
 
481
563
  child.on('close', (code: number | null) => {
482
- if (isDetached) return;
483
- if (timeoutId) clearTimeout(timeoutId);
484
- if (serverGraceTimer) clearTimeout(serverGraceTimer);
564
+ if (isDetached || settled) return;
485
565
  const cleanOutput = cleanSubprocessOutput(outputBuffer);
486
566
  const exitCode = typeof code === 'number' ? code : 1;
487
567
 
488
568
  if (exitCode === 0) {
489
569
  const res: SysRunResult = { success: true, output: cleanOutput, exitCode: 0 };
490
570
  if (isIdempotent) {
491
- commandCache.set(cacheKey, {
571
+ setCachedResult(cacheKey, {
492
572
  output: cleanOutput,
493
573
  exitCode: 0,
494
574
  success: true,
495
575
  timestamp: Date.now()
496
576
  });
497
577
  }
498
- resolve(res);
578
+ finish(res);
499
579
  } else if (exitCode === 1 && isFinalCommandSearch(rawCommand)) {
500
580
  // Semantic Exit Code Normalization: Search tool found 0 matching lines.
501
581
  const res: SysRunResult = {
@@ -505,7 +585,7 @@ export const sysRun = {
505
585
  note: 'Command executed successfully with 0 search matches.'
506
586
  };
507
587
  if (isIdempotent) {
508
- commandCache.set(cacheKey, {
588
+ setCachedResult(cacheKey, {
509
589
  output: res.output,
510
590
  exitCode: 1,
511
591
  success: true,
@@ -513,16 +593,16 @@ export const sysRun = {
513
593
  timestamp: Date.now()
514
594
  });
515
595
  }
516
- resolve(res);
596
+ finish(res);
517
597
  } else {
518
598
  let errorMsg = `Command exited with code ${exitCode}`;
519
599
  if (cleanOutput.includes('more than one device/emulator')) {
520
600
  errorMsg = 'adb failed: multiple devices/emulators connected. Pass `-s <serial>` (e.g. `adb -s emulator-5554 ...`) or set `export ANDROID_SERIAL=<serial>`.';
521
601
  }
522
602
  if (signal && signal.aborted) {
523
- resolve({ success: false, output: cleanOutput, error: 'Process killed by user.', exitCode: 1 });
603
+ finish({ success: false, output: cleanOutput, error: 'Process killed by user.', exitCode: 1 });
524
604
  } else {
525
- resolve({ success: false, output: cleanOutput, error: errorMsg, exitCode });
605
+ finish({ success: false, output: cleanOutput, error: errorMsg, exitCode });
526
606
  }
527
607
  }
528
608
  });
@@ -546,18 +626,26 @@ export const sysRunBg = {
546
626
  }
547
627
  },
548
628
 
549
- async execute(args: SysRunBgArgs): Promise<SysRunBgResult> {
629
+ async execute(args: SysRunBgArgs, context: SysRunContext = {}): Promise<SysRunBgResult> {
550
630
  try {
551
- const cwd = args.cwd ? args.cwd.replace(/^~\//, os.homedir() + '/') : process.cwd();
631
+ const cwd = resolveSysCwd(args?.cwd, context);
552
632
  const shell = os.platform() === 'win32' ? 'cmd.exe' : '/bin/bash';
553
633
  const shellArgs = os.platform() === 'win32' ? ['/c', args.command] : ['-c', args.command];
634
+ const resolvedMode = resolveOsSandboxMode(process.env, context.parentLoop?.config?.osSandbox);
635
+ const wrapped = wrapCommandWithOsSandbox(shell, shellArgs, {
636
+ mode: resolvedMode.mode,
637
+ strict: resolvedMode.strict,
638
+ allowNetwork: resolvedMode.allowNetwork,
639
+ cwd,
640
+ workspaceRoots: context.parentLoop?.sandbox?.workspacePaths ?? [cwd]
641
+ });
554
642
  return await new Promise<SysRunBgResult>(resolve => {
555
- const child = spawn(shell, shellArgs, {
643
+ const child = spawn(wrapped.command, wrapped.args, {
556
644
  cwd,
557
645
  detached: true,
558
646
  stdio: 'ignore',
559
647
  env: getEnhancedEnv(),
560
- ...(os.platform() === 'win32' ? { windowsVerbatimArguments: true } : {})
648
+ ...(os.platform() === 'win32' && !wrapped.sandboxed ? { windowsVerbatimArguments: true } : {})
561
649
  });
562
650
  child.once('error', error => resolve({ success: false, error: error.message }));
563
651
  child.once('spawn', () => {
@@ -11,8 +11,31 @@ function errorString(error) {
11
11
  return error.message;
12
12
  return typeof error === 'string' ? error : String(error);
13
13
  }
14
+ function safeJsonStringify(value) {
15
+ try {
16
+ return JSON.stringify(value);
17
+ }
18
+ catch {
19
+ const seen = new WeakSet();
20
+ try {
21
+ return JSON.stringify(value, (_key, item) => {
22
+ if (typeof item === 'bigint')
23
+ return item.toString();
24
+ if (item !== null && typeof item === 'object') {
25
+ if (seen.has(item))
26
+ return '[Circular]';
27
+ seen.add(item);
28
+ }
29
+ return item;
30
+ });
31
+ }
32
+ catch {
33
+ return JSON.stringify({ success: false, error: 'Tool returned an unserializable payload.' });
34
+ }
35
+ }
36
+ }
14
37
  export function toolResultMessage(toolCallId, name, payload) {
15
- return { role: 'tool', tool_call_id: toolCallId, name, content: JSON.stringify(payload) };
38
+ return { role: 'tool', tool_call_id: toolCallId, name, content: safeJsonStringify(payload) };
16
39
  }
17
40
  export function mergeHookFeedback(payload, messages, denied = false) {
18
41
  if (!messages || messages.length === 0)
@@ -48,8 +48,28 @@ function errorString(error: unknown): string {
48
48
  return typeof error === 'string' ? error : String(error);
49
49
  }
50
50
 
51
+ function safeJsonStringify(value: unknown): string {
52
+ try {
53
+ return JSON.stringify(value);
54
+ } catch {
55
+ const seen = new WeakSet<object>();
56
+ try {
57
+ return JSON.stringify(value, (_key, item: unknown) => {
58
+ if (typeof item === 'bigint') return item.toString();
59
+ if (item !== null && typeof item === 'object') {
60
+ if (seen.has(item)) return '[Circular]';
61
+ seen.add(item);
62
+ }
63
+ return item;
64
+ });
65
+ } catch {
66
+ return JSON.stringify({ success: false, error: 'Tool returned an unserializable payload.' });
67
+ }
68
+ }
69
+ }
70
+
51
71
  export function toolResultMessage(toolCallId: string, name: string, payload: ToolPayload): ToolResultMessage {
52
- return { role: 'tool', tool_call_id: toolCallId, name, content: JSON.stringify(payload) };
72
+ return { role: 'tool', tool_call_id: toolCallId, name, content: safeJsonStringify(payload) };
53
73
  }
54
74
 
55
75
  export function mergeHookFeedback<T extends ToolPayload>(
@@ -72,18 +72,20 @@ export class ToolOutputStore {
72
72
  if (lines.length === 1) {
73
73
  const budget = Math.max(0, this.config.maxChars - notice.length);
74
74
  const half = Math.floor(budget / 2);
75
- head = text.slice(0, half);
76
- tail = text.slice(-half);
75
+ head = half > 0 ? text.slice(0, half) : '';
76
+ tail = half > 0 ? text.slice(-half) : '';
77
77
  }
78
78
  else {
79
- const rawHead = lines.slice(0, this.config.headLines).join('\n');
80
- const rawTail = lines.slice(-this.config.tailLines).join('\n');
79
+ const headCount = Math.max(0, Math.floor(this.config.headLines));
80
+ const tailCount = Math.max(0, Math.floor(this.config.tailLines));
81
+ const rawHead = headCount > 0 ? lines.slice(0, headCount).join('\n') : '';
82
+ const rawTail = tailCount > 0 ? lines.slice(-tailCount).join('\n') : '';
81
83
  const maxBudget = this.config.maxChars;
82
84
  if (rawHead.length + rawTail.length + notice.length > maxBudget) {
83
85
  const budget = Math.max(0, maxBudget - notice.length);
84
86
  const half = Math.floor(budget / 2);
85
- head = rawHead.slice(0, half);
86
- tail = rawTail.slice(-half);
87
+ head = half > 0 ? rawHead.slice(0, half) : '';
88
+ tail = half > 0 ? rawTail.slice(-half) : '';
87
89
  }
88
90
  else {
89
91
  head = rawHead;
@@ -110,8 +112,10 @@ export class ToolOutputStore {
110
112
  throw new Error('ToolOutputStore: Requested file is outside the output store');
111
113
  }
112
114
  const lines = fs.readFileSync(resolvedPath, 'utf8').split('\n');
113
- const clampedStart = Math.max(1, Math.min(startLine, lines.length));
114
- const clampedEnd = Math.max(clampedStart, Math.min(endLine, lines.length));
115
+ const safeStart = Number.isFinite(startLine) ? Math.floor(startLine) : 1;
116
+ const safeEnd = Number.isFinite(endLine) ? Math.floor(endLine) : lines.length;
117
+ const clampedStart = Math.max(1, Math.min(safeStart, lines.length));
118
+ const clampedEnd = Math.max(clampedStart, Math.min(safeEnd, lines.length));
115
119
  return lines.slice(clampedStart - 1, clampedEnd).join('\n');
116
120
  }
117
121
  pruneOldOutputs(maxAgeMs = 7 * 24 * 60 * 60 * 1000) {
@@ -122,22 +126,34 @@ export class ToolOutputStore {
122
126
  try {
123
127
  const sessions = fs.readdirSync(this.config.storageDir);
124
128
  for (const session of sessions) {
125
- const sessionPath = path.join(this.config.storageDir, session);
126
- const stat = fs.lstatSync(sessionPath);
127
- if (stat.isDirectory()) {
128
- const files = fs.readdirSync(sessionPath);
129
- for (const file of files) {
130
- const filePath = path.join(sessionPath, file);
131
- const fileStat = fs.statSync(filePath);
132
- if (now - fileStat.mtimeMs > maxAgeMs) {
133
- fs.unlinkSync(filePath);
134
- pruned++;
129
+ try {
130
+ const sessionPath = path.join(this.config.storageDir, session);
131
+ const stat = fs.lstatSync(sessionPath);
132
+ if (stat.isDirectory() && !stat.isSymbolicLink()) {
133
+ const files = fs.readdirSync(sessionPath);
134
+ for (const file of files) {
135
+ try {
136
+ const filePath = path.join(sessionPath, file);
137
+ const fileStat = fs.lstatSync(filePath);
138
+ if (!fileStat.isFile())
139
+ continue;
140
+ if (now - fileStat.mtimeMs > maxAgeMs) {
141
+ fs.unlinkSync(filePath);
142
+ pruned++;
143
+ }
144
+ }
145
+ catch {
146
+ // Skip unreadable or transient entries without aborting remaining cleanup
147
+ }
148
+ }
149
+ if (fs.readdirSync(sessionPath).length === 0) {
150
+ fs.rmdirSync(sessionPath);
135
151
  }
136
- }
137
- if (fs.readdirSync(sessionPath).length === 0) {
138
- fs.rmdirSync(sessionPath);
139
152
  }
140
153
  }
154
+ catch {
155
+ // Continue pruning remaining session directories
156
+ }
141
157
  }
142
158
  }
143
159
  catch {
@@ -163,15 +179,38 @@ export function renderSpillDocument(result, meta = {}) {
163
179
  ];
164
180
  const sections = [];
165
181
  const scalars = [];
182
+ const safeStringify = (input, indent) => {
183
+ try {
184
+ return JSON.stringify(input, null, indent);
185
+ }
186
+ catch {
187
+ const seen = new WeakSet();
188
+ try {
189
+ return JSON.stringify(input, (_k, v) => {
190
+ if (typeof v === 'bigint')
191
+ return v.toString();
192
+ if (v !== null && typeof v === 'object') {
193
+ if (seen.has(v))
194
+ return '[Circular]';
195
+ seen.add(v);
196
+ }
197
+ return v;
198
+ }, indent);
199
+ }
200
+ catch {
201
+ return String(input);
202
+ }
203
+ }
204
+ };
166
205
  for (const [key, value] of Object.entries(result)) {
167
206
  if (typeof value === 'string' && value.length > 500) {
168
207
  sections.push(`\n--- field: ${key} (${value.length} chars) ---\n${value}`);
169
208
  }
170
209
  else if (value !== null && typeof value === 'object') {
171
- sections.push(`\n--- field: ${key} (JSON) ---\n${JSON.stringify(value, null, 2)}`);
210
+ sections.push(`\n--- field: ${key} (JSON) ---\n${safeStringify(value, 2)}`);
172
211
  }
173
212
  else {
174
- scalars.push(`${key}: ${JSON.stringify(value)}`);
213
+ scalars.push(`${key}: ${safeStringify(value)}`);
175
214
  }
176
215
  }
177
216
  if (scalars.length > 0)
@@ -92,17 +92,19 @@ export class ToolOutputStore {
92
92
  if (lines.length === 1) {
93
93
  const budget = Math.max(0, this.config.maxChars - notice.length);
94
94
  const half = Math.floor(budget / 2);
95
- head = text.slice(0, half);
96
- tail = text.slice(-half);
95
+ head = half > 0 ? text.slice(0, half) : '';
96
+ tail = half > 0 ? text.slice(-half) : '';
97
97
  } else {
98
- const rawHead = lines.slice(0, this.config.headLines).join('\n');
99
- const rawTail = lines.slice(-this.config.tailLines).join('\n');
98
+ const headCount = Math.max(0, Math.floor(this.config.headLines));
99
+ const tailCount = Math.max(0, Math.floor(this.config.tailLines));
100
+ const rawHead = headCount > 0 ? lines.slice(0, headCount).join('\n') : '';
101
+ const rawTail = tailCount > 0 ? lines.slice(-tailCount).join('\n') : '';
100
102
  const maxBudget = this.config.maxChars;
101
103
  if (rawHead.length + rawTail.length + notice.length > maxBudget) {
102
104
  const budget = Math.max(0, maxBudget - notice.length);
103
105
  const half = Math.floor(budget / 2);
104
- head = rawHead.slice(0, half);
105
- tail = rawTail.slice(-half);
106
+ head = half > 0 ? rawHead.slice(0, half) : '';
107
+ tail = half > 0 ? rawTail.slice(-half) : '';
106
108
  } else {
107
109
  head = rawHead;
108
110
  tail = rawTail;
@@ -130,8 +132,10 @@ export class ToolOutputStore {
130
132
  throw new Error('ToolOutputStore: Requested file is outside the output store');
131
133
  }
132
134
  const lines = fs.readFileSync(resolvedPath, 'utf8').split('\n');
133
- const clampedStart = Math.max(1, Math.min(startLine, lines.length));
134
- const clampedEnd = Math.max(clampedStart, Math.min(endLine, lines.length));
135
+ const safeStart = Number.isFinite(startLine) ? Math.floor(startLine) : 1;
136
+ const safeEnd = Number.isFinite(endLine) ? Math.floor(endLine) : lines.length;
137
+ const clampedStart = Math.max(1, Math.min(safeStart, lines.length));
138
+ const clampedEnd = Math.max(clampedStart, Math.min(safeEnd, lines.length));
135
139
  return lines.slice(clampedStart - 1, clampedEnd).join('\n');
136
140
  }
137
141
 
@@ -142,21 +146,30 @@ export class ToolOutputStore {
142
146
  try {
143
147
  const sessions = fs.readdirSync(this.config.storageDir);
144
148
  for (const session of sessions) {
145
- const sessionPath = path.join(this.config.storageDir, session);
146
- const stat = fs.lstatSync(sessionPath);
147
- if (stat.isDirectory()) {
148
- const files = fs.readdirSync(sessionPath);
149
- for (const file of files) {
150
- const filePath = path.join(sessionPath, file);
151
- const fileStat = fs.statSync(filePath);
152
- if (now - fileStat.mtimeMs > maxAgeMs) {
153
- fs.unlinkSync(filePath);
154
- pruned++;
149
+ try {
150
+ const sessionPath = path.join(this.config.storageDir, session);
151
+ const stat = fs.lstatSync(sessionPath);
152
+ if (stat.isDirectory() && !stat.isSymbolicLink()) {
153
+ const files = fs.readdirSync(sessionPath);
154
+ for (const file of files) {
155
+ try {
156
+ const filePath = path.join(sessionPath, file);
157
+ const fileStat = fs.lstatSync(filePath);
158
+ if (!fileStat.isFile()) continue;
159
+ if (now - fileStat.mtimeMs > maxAgeMs) {
160
+ fs.unlinkSync(filePath);
161
+ pruned++;
162
+ }
163
+ } catch {
164
+ // Skip unreadable or transient entries without aborting remaining cleanup
165
+ }
166
+ }
167
+ if (fs.readdirSync(sessionPath).length === 0) {
168
+ fs.rmdirSync(sessionPath);
155
169
  }
156
170
  }
157
- if (fs.readdirSync(sessionPath).length === 0) {
158
- fs.rmdirSync(sessionPath);
159
- }
171
+ } catch {
172
+ // Continue pruning remaining session directories
160
173
  }
161
174
  }
162
175
  } catch {
@@ -194,13 +207,33 @@ export function renderSpillDocument(
194
207
  const sections: string[] = [];
195
208
  const scalars: string[] = [];
196
209
 
210
+ const safeStringify = (input: unknown, indent?: number): string => {
211
+ try {
212
+ return JSON.stringify(input, null, indent);
213
+ } catch {
214
+ const seen = new WeakSet<object>();
215
+ try {
216
+ return JSON.stringify(input, (_k, v: unknown) => {
217
+ if (typeof v === 'bigint') return v.toString();
218
+ if (v !== null && typeof v === 'object') {
219
+ if (seen.has(v)) return '[Circular]';
220
+ seen.add(v);
221
+ }
222
+ return v;
223
+ }, indent);
224
+ } catch {
225
+ return String(input);
226
+ }
227
+ }
228
+ };
229
+
197
230
  for (const [key, value] of Object.entries(result as Record<string, unknown>)) {
198
231
  if (typeof value === 'string' && value.length > 500) {
199
232
  sections.push(`\n--- field: ${key} (${value.length} chars) ---\n${value}`);
200
233
  } else if (value !== null && typeof value === 'object') {
201
- sections.push(`\n--- field: ${key} (JSON) ---\n${JSON.stringify(value, null, 2)}`);
234
+ sections.push(`\n--- field: ${key} (JSON) ---\n${safeStringify(value, 2)}`);
202
235
  } else {
203
- scalars.push(`${key}: ${JSON.stringify(value)}`);
236
+ scalars.push(`${key}: ${safeStringify(value)}`);
204
237
  }
205
238
  }
206
239