@causyne/agent 1.20.121 → 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 (256) 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 +6 -2
  14. package/src/agent/errorClassifier.ts +6 -2
  15. package/src/agentLoop.js +11 -5
  16. package/src/agentLoop.ts +11 -5
  17. package/src/approvalGrants.js +19 -7
  18. package/src/approvalGrants.ts +20 -7
  19. package/src/approvalPolicy.js +48 -15
  20. package/src/approvalPolicy.ts +46 -15
  21. package/src/autoUpdate.js +5 -2
  22. package/src/autoUpdate.ts +5 -2
  23. package/src/browser/causyneBrowser.js +3 -2
  24. package/src/browser/causyneBrowser.ts +3 -2
  25. package/src/browser/searchProviders.js +1 -1
  26. package/src/browser/searchProviders.ts +1 -1
  27. package/src/config.js +287 -250
  28. package/src/config.ts +342 -0
  29. package/src/configVault.js +84 -17
  30. package/src/configVault.ts +77 -17
  31. package/src/continuum/compactor.js +2 -1
  32. package/src/continuum/compactor.ts +2 -1
  33. package/src/continuum/sanitizer.js +10 -3
  34. package/src/continuum/sanitizer.ts +9 -3
  35. package/src/continuum/ui/continuumPickerView.js +3 -2
  36. package/src/continuum/ui/continuumPickerView.ts +3 -2
  37. package/src/cortex/vectorDb.js +26 -15
  38. package/src/cortex/vectorDb.ts +26 -16
  39. package/src/creative/liveBridge.js +7 -5
  40. package/src/creative/liveBridge.ts +7 -5
  41. package/src/creative/studioScripts.js +16 -5
  42. package/src/creative/studioScripts.ts +14 -5
  43. package/src/decisionPolicy.js +16 -4
  44. package/src/decisionPolicy.ts +14 -4
  45. package/src/documentEngine/antiSlopAuditor.js +10 -5
  46. package/src/documentEngine/antiSlopAuditor.ts +11 -5
  47. package/src/documentEngine/documentForge.js +47 -15
  48. package/src/documentEngine/documentForge.ts +43 -14
  49. package/src/engines/design.js +2 -1
  50. package/src/engines/design.ts +2 -1
  51. package/src/engines/film.js +4 -4
  52. package/src/engines/film.ts +2 -2
  53. package/src/engines/light.js +2 -1
  54. package/src/engines/light.ts +2 -1
  55. package/src/engines/registry.js +1 -1
  56. package/src/engines/registry.ts +1 -1
  57. package/src/engines/reverseHarness.js +4 -3
  58. package/src/engines/reverseHarness.ts +4 -3
  59. package/src/headlessCli.js +2 -1
  60. package/src/headlessCli.ts +2 -1
  61. package/src/historyPruner.js +3 -2
  62. package/src/historyPruner.ts +3 -2
  63. package/src/hooks.js +3 -0
  64. package/src/hooks.ts +3 -0
  65. package/src/implementationPlan.js +21 -11
  66. package/src/implementationPlan.ts +21 -11
  67. package/src/infra/atomicWriter.js +4 -1
  68. package/src/infra/atomicWriter.ts +4 -1
  69. package/src/launchIntent.js +1 -1
  70. package/src/launchIntent.ts +1 -1
  71. package/src/memory/scopedFacts.js +1 -1
  72. package/src/memory/scopedFacts.ts +1 -1
  73. package/src/memory/symbolFolder.js +1 -1
  74. package/src/memory/symbolFolder.ts +1 -1
  75. package/src/modelRouter.js +1 -1
  76. package/src/modelRouter.ts +1 -1
  77. package/src/observer/evidence.js +10 -4
  78. package/src/observer/evidence.ts +10 -4
  79. package/src/osKeychain.js +62 -8
  80. package/src/osKeychain.ts +50 -8
  81. package/src/perception.js +3 -2
  82. package/src/perception.ts +3 -2
  83. package/src/planCache.js +2 -2
  84. package/src/planCache.ts +2 -2
  85. package/src/pluginsFactory/pluginsFactory.js +19 -11
  86. package/src/pluginsFactory/pluginsFactory.ts +18 -11
  87. package/src/promptMentions.js +2 -2
  88. package/src/promptMentions.ts +2 -2
  89. package/src/providers/acp.js +1 -1
  90. package/src/providers/acp.ts +1 -1
  91. package/src/providers/anthropic.js +327 -401
  92. package/src/providers/anthropic.ts +386 -0
  93. package/src/providers/antigravity.js +10 -4
  94. package/src/providers/antigravity.ts +10 -4
  95. package/src/providers/base.js +221 -319
  96. package/src/providers/base.ts +340 -0
  97. package/src/providers/byokHttp.js +58 -15
  98. package/src/providers/byokHttp.ts +59 -16
  99. package/src/providers/byokStream.js +142 -51
  100. package/src/providers/byokStream.ts +146 -42
  101. package/src/providers/dashscope-byok.js +97 -89
  102. package/src/providers/dashscope-byok.ts +114 -0
  103. package/src/providers/deepseek.js +73 -72
  104. package/src/providers/deepseek.ts +99 -0
  105. package/src/providers/factory.js +35 -28
  106. package/src/providers/factory.ts +40 -0
  107. package/src/providers/gemini.js +227 -278
  108. package/src/providers/gemini.ts +261 -0
  109. package/src/providers/loopGuard.js +9 -5
  110. package/src/providers/loopGuard.ts +10 -5
  111. package/src/providers/moonshot.js +70 -72
  112. package/src/providers/moonshot.ts +93 -0
  113. package/src/providers/muse.js +82 -152
  114. package/src/providers/muse.ts +122 -0
  115. package/src/providers/ollama.js +114 -106
  116. package/src/providers/ollama.ts +135 -0
  117. package/src/providers/openai-compatible.js +113 -96
  118. package/src/providers/openai-compatible.ts +139 -0
  119. package/src/providers/openai.js +22 -15
  120. package/src/providers/openai.ts +30 -0
  121. package/src/providers/openrouter.js +136 -74
  122. package/src/providers/openrouter.ts +133 -72
  123. package/src/providers/pi.js +6 -0
  124. package/src/providers/pi.ts +6 -0
  125. package/src/providers/qwen-byok.js +96 -87
  126. package/src/providers/qwen-byok.ts +113 -0
  127. package/src/providers/toolContracts.js +40 -14
  128. package/src/providers/toolContracts.ts +35 -14
  129. package/src/providers/wireNormalizer.js +78 -11
  130. package/src/providers/wireNormalizer.ts +68 -12
  131. package/src/providers/xai.js +73 -72
  132. package/src/providers/xai.ts +97 -0
  133. package/src/reliability/assetEvidence.js +4 -2
  134. package/src/reliability/assetEvidence.ts +4 -2
  135. package/src/sandbox.js +489 -554
  136. package/src/sandbox.ts +552 -0
  137. package/src/sandboxPolicy.js +95 -16
  138. package/src/sandboxPolicy.ts +97 -16
  139. package/src/sessionJournal.js +8 -3
  140. package/src/sessionJournal.ts +9 -3
  141. package/src/skills/skillResourceSafety.js +19 -8
  142. package/src/skills/skillResourceSafety.ts +16 -7
  143. package/src/skillsManager.js +3 -3
  144. package/src/skillsManager.ts +3 -3
  145. package/src/smartToolsUse.js +28 -4
  146. package/src/smartToolsUse.ts +29 -7
  147. package/src/stallGuard.js +45 -22
  148. package/src/stallGuard.ts +46 -22
  149. package/src/subagentJournal.js +6 -4
  150. package/src/subagentJournal.ts +6 -4
  151. package/src/textDiff.js +6 -1
  152. package/src/textDiff.ts +6 -1
  153. package/src/timeMachine.js +7 -1
  154. package/src/timeMachine.ts +7 -1
  155. package/src/tokenTracker.js +43 -28
  156. package/src/tokenTracker.ts +44 -30
  157. package/src/toolPacks.js +3 -1
  158. package/src/toolPacks.ts +3 -1
  159. package/src/tools/archive.js +245 -35
  160. package/src/tools/archive.ts +244 -35
  161. package/src/tools/computerUse.js +7 -3
  162. package/src/tools/computerUse.ts +7 -3
  163. package/src/tools/creativeApps.js +13 -8
  164. package/src/tools/creativeApps.ts +22 -9
  165. package/src/tools/deferredMcpSearch.js +26 -14
  166. package/src/tools/deferredMcpSearch.ts +26 -14
  167. package/src/tools/desktopOpen.js +69 -10
  168. package/src/tools/desktopOpen.ts +70 -11
  169. package/src/tools/documentForge.js +167 -82
  170. package/src/tools/documentForge.ts +169 -84
  171. package/src/tools/fsEdit.js +101 -30
  172. package/src/tools/fsEdit.ts +105 -32
  173. package/src/tools/fsFind.js +8 -5
  174. package/src/tools/fsFind.ts +7 -4
  175. package/src/tools/fsRead.js +119 -13
  176. package/src/tools/fsRead.ts +124 -13
  177. package/src/tools/fsWrite.js +17 -5
  178. package/src/tools/fsWrite.ts +17 -7
  179. package/src/tools/generateMediaViaApi.js +82 -19
  180. package/src/tools/generateMediaViaApi.ts +80 -19
  181. package/src/tools/memoryRecall.js +62 -11
  182. package/src/tools/memoryRecall.ts +70 -13
  183. package/src/tools/memoryWrite.js +27 -14
  184. package/src/tools/memoryWrite.ts +30 -14
  185. package/src/tools/multiEdit.js +100 -30
  186. package/src/tools/multiEdit.ts +104 -32
  187. package/src/tools/nativeEngine.js +33 -18
  188. package/src/tools/nativeEngine.ts +31 -18
  189. package/src/tools/openSourceToolProvisioner.js +49 -14
  190. package/src/tools/openSourceToolProvisioner.ts +54 -15
  191. package/src/tools/osSandbox.js +54 -14
  192. package/src/tools/osSandbox.ts +48 -14
  193. package/src/tools/payloadSanitizer.js +40 -8
  194. package/src/tools/payloadSanitizer.ts +39 -8
  195. package/src/tools/peerAgent.js +96 -34
  196. package/src/tools/peerAgent.ts +114 -37
  197. package/src/tools/pluginsFactory.js +38 -6
  198. package/src/tools/pluginsFactory.ts +42 -6
  199. package/src/tools/readNativeSkill.js +10 -8
  200. package/src/tools/readNativeSkill.ts +10 -8
  201. package/src/tools/requestDecision.js +10 -3
  202. package/src/tools/requestDecision.ts +10 -3
  203. package/src/tools/resolveAutomator.js +91 -17
  204. package/src/tools/resolveAutomator.ts +102 -17
  205. package/src/tools/reverseEngineering.js +168 -41
  206. package/src/tools/reverseEngineering.ts +161 -41
  207. package/src/tools/sysRun.js +69 -29
  208. package/src/tools/sysRun.ts +66 -24
  209. package/src/tools/toolDispatch.js +24 -1
  210. package/src/tools/toolDispatch.ts +21 -1
  211. package/src/tools/toolOutputStore.js +62 -23
  212. package/src/tools/toolOutputStore.ts +56 -23
  213. package/src/tools/toolScanner.js +13 -10
  214. package/src/tools/toolScanner.ts +13 -10
  215. package/src/tools/toolSelfRepair.js +94 -28
  216. package/src/tools/toolSelfRepair.ts +96 -28
  217. package/src/tools/uiForge.js +71 -6
  218. package/src/tools/uiForge.ts +74 -6
  219. package/src/tools/viewImage.js +62 -17
  220. package/src/tools/viewImage.ts +57 -12
  221. package/src/tools/visionInspector.js +15 -3
  222. package/src/tools/visionInspector.ts +15 -3
  223. package/src/tools/walkerSafety.js +2 -0
  224. package/src/tools/walkerSafety.ts +1 -0
  225. package/src/tools/webFetch.js +105 -10
  226. package/src/tools/webFetch.ts +105 -11
  227. package/src/tui/banner.js +3 -2
  228. package/src/tui/banner.ts +3 -2
  229. package/src/tui/consoleGuard.js +12 -4
  230. package/src/tui/consoleGuard.ts +9 -4
  231. package/src/tui/messageInteraction.js +2 -3
  232. package/src/tui/messageInteraction.ts +2 -3
  233. package/src/tui/modelPicker.js +1 -0
  234. package/src/tui/modelPicker.ts +1 -0
  235. package/src/tui/overlay.js +3 -1
  236. package/src/tui/overlay.ts +3 -1
  237. package/src/tui/sessionPicker.js +3 -2
  238. package/src/tui/sessionPicker.ts +3 -2
  239. package/src/tui/sessionPickerView.js +7 -1
  240. package/src/tui/sessionPickerView.ts +6 -1
  241. package/src/tui/toolOutputNormalizer.js +2 -3
  242. package/src/tui/toolOutputNormalizer.ts +4 -3
  243. package/src/tui/viewport.js +4 -4
  244. package/src/tui/viewport.ts +5 -5
  245. package/src/tui/workspaceIdentity.js +2 -1
  246. package/src/tui/workspaceIdentity.ts +2 -1
  247. package/src/uncertainty.js +8 -3
  248. package/src/uncertainty.ts +8 -3
  249. package/src/utils/paths.js +8 -5
  250. package/src/utils/paths.ts +9 -7
  251. package/src/vfeTracker.js +9 -3
  252. package/src/vfeTracker.ts +9 -3
  253. package/src/config.d.ts +0 -2
  254. package/src/providers/base.d.ts +0 -94
  255. package/src/providers/factory.d.ts +0 -1
  256. package/src/sandbox.d.ts +0 -1
@@ -115,7 +115,7 @@ export function getEnhancedEnv(baseEnv?: NodeJS.ProcessEnv): NodeJS.ProcessEnv {
115
115
  path.join(os.homedir(), 'Library', 'Android', 'sdk'), // macOS
116
116
  path.join(os.homedir(), 'Android', 'Sdk'), // Linux
117
117
  '/usr/lib/android-sdk', // Linux package
118
- path.join(process.env.LOCALAPPDATA || '', 'Android', 'Sdk') // Windows
118
+ ...(process.env.LOCALAPPDATA ? [path.join(process.env.LOCALAPPDATA, 'Android', 'Sdk')] : []) // Windows
119
119
  ];
120
120
  for (const dir of candidateDirs) {
121
121
  if (dir && fs.existsSync(dir)) {
@@ -249,9 +249,10 @@ export function isFinalCommandSearch(rawCommand: string): boolean {
249
249
  }
250
250
 
251
251
  const pipeParts = lastStmt.split('|');
252
- 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, '');
253
254
 
254
- 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);
255
256
  }
256
257
 
257
258
  /**
@@ -297,12 +298,38 @@ interface CachedCommandResult {
297
298
  }
298
299
 
299
300
  const COMMAND_CACHE_TTL_MS = 60_000;
301
+ const MAX_CACHE_ENTRIES = 64;
300
302
  const commandCache = new Map<string, CachedCommandResult>();
301
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
+
302
312
  export function clearSysRunCache(): void {
303
313
  commandCache.clear();
304
314
  }
305
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
+
306
333
  export const sysRun = {
307
334
  schema: {
308
335
  name: 'sysRun',
@@ -321,7 +348,7 @@ export const sysRun = {
321
348
 
322
349
  async execute(args: SysRunArgs, context: SysRunContext = {}): Promise<SysRunResult> {
323
350
  const rawCommand = (args?.command || '').trim();
324
- const cwd = args?.cwd ? args.cwd.replace(/^~\//, os.homedir() + '/') : process.cwd();
351
+ const cwd = resolveSysCwd(args?.cwd, context);
325
352
  let timeoutMs = 60000;
326
353
  const rawTimeout = (args as unknown as Record<string, unknown>)?.timeout;
327
354
  if (typeof rawTimeout === 'number' && Number.isFinite(rawTimeout) && rawTimeout > 0) {
@@ -337,8 +364,10 @@ export const sysRun = {
337
364
  else timeoutMs = val <= 600 ? Math.round(val * 1000) : Math.round(val);
338
365
  }
339
366
  }
340
- if (timeoutMs < 1000) {
367
+ if (!Number.isFinite(timeoutMs) || timeoutMs < 1000) {
341
368
  timeoutMs = 1000;
369
+ } else if (timeoutMs > 2_147_483_647) {
370
+ timeoutMs = 2_147_483_647;
342
371
  }
343
372
  const signal = context.signal;
344
373
 
@@ -428,6 +457,15 @@ export const sysRun = {
428
457
  let outputBuffer = '';
429
458
  let isDetached = false;
430
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
+
431
469
  const checkServerDetach = (): void => {
432
470
  if (isDetached) return;
433
471
  if (isPersistentServerCommand(rawCommand)) {
@@ -435,7 +473,7 @@ export const sysRun = {
435
473
  isDetached = true;
436
474
  if (timeoutId) clearTimeout(timeoutId);
437
475
  if (serverGraceTimer) clearTimeout(serverGraceTimer);
438
- child.unref();
476
+ detachChild();
439
477
  resolve({
440
478
  success: true,
441
479
  output: cleanSubprocessOutput(outputBuffer),
@@ -478,7 +516,7 @@ export const sysRun = {
478
516
  if (!isDetached && child.exitCode === null) {
479
517
  isDetached = true;
480
518
  if (timeoutId) clearTimeout(timeoutId);
481
- child.unref();
519
+ detachChild();
482
520
  resolve({
483
521
  success: true,
484
522
  output: cleanSubprocessOutput(outputBuffer) || 'Server process started and running in background.',
@@ -489,13 +527,21 @@ export const sysRun = {
489
527
  }, 2500);
490
528
  }
491
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
+
492
539
  let timeoutId: NodeJS.Timeout | undefined;
493
540
  if (timeoutMs > 0) {
494
541
  timeoutId = setTimeout(() => {
495
- if (isDetached) return;
496
- if (serverGraceTimer) clearTimeout(serverGraceTimer);
542
+ if (isDetached || settled) return;
497
543
  child.kill('SIGKILL');
498
- resolve({
544
+ finish({
499
545
  success: false,
500
546
  output: cleanSubprocessOutput(outputBuffer),
501
547
  error: `Process timed out after ${timeoutMs}ms`,
@@ -505,10 +551,8 @@ export const sysRun = {
505
551
  }
506
552
 
507
553
  child.on('error', (err: Error) => {
508
- if (isDetached) return;
509
- if (timeoutId) clearTimeout(timeoutId);
510
- if (serverGraceTimer) clearTimeout(serverGraceTimer);
511
- resolve({
554
+ if (isDetached || settled) return;
555
+ finish({
512
556
  success: false,
513
557
  output: cleanSubprocessOutput(outputBuffer),
514
558
  error: err.message,
@@ -517,23 +561,21 @@ export const sysRun = {
517
561
  });
518
562
 
519
563
  child.on('close', (code: number | null) => {
520
- if (isDetached) return;
521
- if (timeoutId) clearTimeout(timeoutId);
522
- if (serverGraceTimer) clearTimeout(serverGraceTimer);
564
+ if (isDetached || settled) return;
523
565
  const cleanOutput = cleanSubprocessOutput(outputBuffer);
524
566
  const exitCode = typeof code === 'number' ? code : 1;
525
567
 
526
568
  if (exitCode === 0) {
527
569
  const res: SysRunResult = { success: true, output: cleanOutput, exitCode: 0 };
528
570
  if (isIdempotent) {
529
- commandCache.set(cacheKey, {
571
+ setCachedResult(cacheKey, {
530
572
  output: cleanOutput,
531
573
  exitCode: 0,
532
574
  success: true,
533
575
  timestamp: Date.now()
534
576
  });
535
577
  }
536
- resolve(res);
578
+ finish(res);
537
579
  } else if (exitCode === 1 && isFinalCommandSearch(rawCommand)) {
538
580
  // Semantic Exit Code Normalization: Search tool found 0 matching lines.
539
581
  const res: SysRunResult = {
@@ -543,7 +585,7 @@ export const sysRun = {
543
585
  note: 'Command executed successfully with 0 search matches.'
544
586
  };
545
587
  if (isIdempotent) {
546
- commandCache.set(cacheKey, {
588
+ setCachedResult(cacheKey, {
547
589
  output: res.output,
548
590
  exitCode: 1,
549
591
  success: true,
@@ -551,16 +593,16 @@ export const sysRun = {
551
593
  timestamp: Date.now()
552
594
  });
553
595
  }
554
- resolve(res);
596
+ finish(res);
555
597
  } else {
556
598
  let errorMsg = `Command exited with code ${exitCode}`;
557
599
  if (cleanOutput.includes('more than one device/emulator')) {
558
600
  errorMsg = 'adb failed: multiple devices/emulators connected. Pass `-s <serial>` (e.g. `adb -s emulator-5554 ...`) or set `export ANDROID_SERIAL=<serial>`.';
559
601
  }
560
602
  if (signal && signal.aborted) {
561
- 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 });
562
604
  } else {
563
- resolve({ success: false, output: cleanOutput, error: errorMsg, exitCode });
605
+ finish({ success: false, output: cleanOutput, error: errorMsg, exitCode });
564
606
  }
565
607
  }
566
608
  });
@@ -586,7 +628,7 @@ export const sysRunBg = {
586
628
 
587
629
  async execute(args: SysRunBgArgs, context: SysRunContext = {}): Promise<SysRunBgResult> {
588
630
  try {
589
- const cwd = args.cwd ? args.cwd.replace(/^~\//, os.homedir() + '/') : process.cwd();
631
+ const cwd = resolveSysCwd(args?.cwd, context);
590
632
  const shell = os.platform() === 'win32' ? 'cmd.exe' : '/bin/bash';
591
633
  const shellArgs = os.platform() === 'win32' ? ['/c', args.command] : ['-c', args.command];
592
634
  const resolvedMode = resolveOsSandboxMode(process.env, context.parentLoop?.config?.osSandbox);
@@ -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
 
@@ -124,7 +124,7 @@ function resolveLocalRef(ref, defs, activeRefs) {
124
124
  else if (ref.startsWith('#/definitions/')) {
125
125
  key = ref.slice('#/definitions/'.length);
126
126
  }
127
- if (!key)
127
+ if (!key || !Object.hasOwn(defs, key))
128
128
  return null;
129
129
  const target = defs[key];
130
130
  return isPlainObject(target) ? target : null;
@@ -141,7 +141,7 @@ function pushRewrittenPath(rewritten, path) {
141
141
  * Recursively inspect a schema for raw or residual provider incompatibilities.
142
142
  */
143
143
  function inspectSchemaForProvider(toolName, schema, path, provider, issues) {
144
- if (!isPlainObject(schema))
144
+ if (path.length > 32 || !isPlainObject(schema))
145
145
  return;
146
146
  const pathStr = path.join('.');
147
147
  const isGemini = provider === 'gemini';
@@ -186,7 +186,7 @@ function inspectSchemaForProvider(toolName, schema, path, provider, issues) {
186
186
  if (schema['type'] === 'object' && Array.isArray(schema['required']) && isPlainObject(schema['properties'])) {
187
187
  const props = schema['properties'];
188
188
  for (const req of schema['required']) {
189
- if (typeof req === 'string' && !(req in props)) {
189
+ if (typeof req === 'string' && !Object.hasOwn(props, req)) {
190
190
  issues.push({
191
191
  tool: toolName,
192
192
  path: `${pathStr}.required.${req}`,
@@ -528,7 +528,7 @@ function compileSchemaNode(schema, dialect, path, rewritten, defs, activeRefs) {
528
528
  }
529
529
  if (adapted['type'] === 'object' && Array.isArray(adapted['required']) && isPlainObject(adapted['properties'])) {
530
530
  const props = adapted['properties'];
531
- const filtered = adapted['required'].filter((k) => typeof k === 'string' && k in props);
531
+ const filtered = adapted['required'].filter((k) => typeof k === 'string' && Object.hasOwn(props, k));
532
532
  if (filtered.length > 0) {
533
533
  adapted['required'] = filtered;
534
534
  }
@@ -681,8 +681,11 @@ export function scanAndAdaptToolsForProvider(tools, provider, options = {}) {
681
681
  let adapted;
682
682
  if (isGemini) {
683
683
  const declaration = { name, description };
684
- if (rawSchema && !isEmptyObjectSchema(rawSchema)) {
685
- declaration['parameters'] = adaptSchemaForGemini(rawSchema, [], rewritten);
684
+ if (rawSchema) {
685
+ const compiled = adaptSchemaForGemini(rawSchema, [], rewritten);
686
+ if (!isEmptyObjectSchema(compiled)) {
687
+ declaration['parameters'] = compiled;
688
+ }
686
689
  }
687
690
  adapted = declaration;
688
691
  }
@@ -805,7 +808,7 @@ function applyAtPath(node, path, transform) {
805
808
  return;
806
809
  const target = node;
807
810
  const [head, ...rest] = path;
808
- if (!head)
811
+ if (!head || head === '__proto__' || head === 'constructor' || head === 'prototype')
809
812
  return;
810
813
  if (head === '[]') {
811
814
  if (!Array.isArray(node))
@@ -814,10 +817,10 @@ function applyAtPath(node, path, transform) {
814
817
  applyAtPath(entry, rest, transform);
815
818
  return;
816
819
  }
820
+ if (!Object.hasOwn(target, head))
821
+ return;
817
822
  if (rest.length === 0) {
818
- if (head in target) {
819
- target[head] = transform(target[head]);
820
- }
823
+ target[head] = transform(target[head]);
821
824
  return;
822
825
  }
823
826
  applyAtPath(target[head], rest, transform);